- 1
- 2
- 3
- 4
- 5
- 6
@jfredys 23-Mar-2011 01:07
I was looking for trimming all the elements in an array, I found this as the simplest solution:
<?php
array_walk($ids, create_function('&$val', '$val = trim($val);'));
?>
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+165
@jfredys 23-Mar-2011 01:07
I was looking for trimming all the elements in an array, I found this as the simplest solution:
<?php
array_walk($ids, create_function('&$val', '$val = trim($val);'));
?>
array_map? не, не слышал.
+126
//javax.swing.JTree
public void setBounds(Rectangle r) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBounds(r);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setBounds(r);
}
}
}
public void setSize (Dimension d) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setSize(d);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setSize(d);
}
}
}
public void requestFocus() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).requestFocus();
} else {
Component c = getCurrentComponent();
if (c != null) {
c.requestFocus();
}
}
}
public void addFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).addFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.addFocusListener(l);
}
}
}
public boolean isFocusTraversable() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isFocusTraversable();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isFocusTraversable();
} else {
return false;
}
}
}
+134
<style type="text/css">
p, div, ol, ul {
margin: 0;
padding: 0;
border: 0;
vertical-align: baseline;
background: transparent;
}
.exception {
width: 700px;
border: 1px solid #D6D6D6;
background-color: #FAFAFA;
font-family: arial, tahoma, verdana;
font-size: 75%;
padding: 10px;
line-height: 140%;
}
.exception img {
float: left;
margin-right: 7px;
}
.exceptionTitle {
padding-top: 2px;
color: #AA0000;
font-size: 120%;
font-weight: bold;
}
.exceptionMessage {
background-color: white;
border: 1px solid #E1E1E1;
padding: 5px;
font-size: 110%;
margin: 10px 0;
}
.exception a {
cursor: pointer;
padding: 1px;
border-bottom: 1px dotted #555;
color: #000;
}
.exceptionTraceContainer {
font-size: 95%;
line-height: 150%;
font-family: verdana, tahoma, arial;
margin: 10px 0;
}
.exceptionTraceContainer ol {
padding-left: 25px;
}
.exceptionTraceContainer li {
padding-top: 5px;
}
.exceptionSystemInfo {
font-size: 90%;
border-top: 1px solid #E1E1E1;
padding: 10px 5px;
color: #666;
}
</style>
<!--[if IE]>
<style type="text/css">
img { display: none; }
</style>
<![endif]-->
<script type="text/javascript">
function _showAllTrace() {
var trace = document.getElementById('exceptionTrace');
trace.style.display = (trace.style.display == 'none') ? '' : 'none';
}
</script>
<div class="exception">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAARCAYAAAA7bUf6AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABZ0RVh0Q3JlYXRpb24gVGltZQAxMi8wMi8wOOE6tm4AAAAYdEVYdFNvZnR3YXJlAEFkb2JlIEZpcmV3b3Jrc0+zH04AAAHsSURBVDiNlZDNahNhFIaf+clkkknSNNHUohSRYlyIyxYRXLhVL8B7qCIKigUR3IobewOC0EWgdyCIf4sstLSRlopasQhxmkyTSTIZJ/PjIiZlzJTEB87iO3w8vO8RHMcJiOBX+Qad6iu0E1eYWVyN+jJEjFoalfvYtTKZmUXsepnqu+v/J3Gam5g/SqSOXyCuFZiavchvcwujcm9yiVFZJqZOo6g5CDwkSSGVP09j9wVd/eV4idPcwDI+oGXnIfCGo6hZEuk59tdvj5cYlQfEEwUkSQlJCDy0qTP4PRNj8+7REs+uYtXXSWbnABdwyS+UyC+UABdBDEjlzmLureE0N6IlB5+WkZUUsqweJhjw9x1PTBNT0tQ+LkVLOvprkpmT4Rr/SPq1TuF0vtPZWw1LWl+fEfg94onMsEp/BhzuJDmGqhU42HkSljR3n6Nq+ZFjRiUh8EikjuF292lsPwJAaOvl4Ofba+QK5xCl2Mjlj6LbqWG1DU5f/Ybc2H6MomiIogCBG/qYv/QGgPr7yyOSRDJLt6XT2HqI8HmtEKSzsyhqauIUA2yrSdvUkQUxhu854RtMiO/3EMUYYq64RNvU6XbqBL7TrzRmfNfGatWw2nVyxZsIjuMErS9PMXZW8Fx74hSSrJIr3iI9f4c/ZwP51LVnSksAAAAASUVORK5CYII=" alt="exception" />
<div class="exceptionTitle">Application was halted by an exception.</div>
<p>Debug-mode is off.</p></div>
Это что-то новенькое на говнокоде. Вылезло при попытке открыть один говнокод на отдельной странице (после другого сбоя, неудачи голосования). Кстати, это весь код страницы, никаких <html>, <head> и <body> не было.
+160
public function isValidModule($module)
{
if (!is_string($module)) {
return false;
}
$module = strtolower($module);
$controllerDir = $this->getControllerDirectory();
foreach (array_keys($controllerDir) as $moduleName) {
if ($module == strtolower($moduleName)) {
return true;
}
}
return false;
}
Великий и могучий Zend Framework в очередной раз очаровывает своих адептов изяществом и простотой(((
+146
package gargoyle.xenox.game;
import gargoyle.util.log.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
@SuppressWarnings("rawtypes")
public abstract class Persistent<T extends Persistent> implements Serializable {
private static final long serialVersionUID = 1L;
private File file(final Class<? extends Persistent> clazz) {
return new File(System.getProperty("user.home"), clazz.getName() + ".dat");
}
@SuppressWarnings("unchecked")
final protected T load(final Class<T> clazz) {
ObjectInputStream in;
try {
in = new ObjectInputStream(new FileInputStream(this.file(clazz)));
return (T) in.readObject();
} catch (final IOException e) {
Log.error(e);
} catch (final ClassNotFoundException e) {
Log.error(e);
}
return null;
}
final protected void save(final T o) {
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream(this.file(o.getClass())));
os.writeObject(this);
os.flush();
} catch (final IOException e) {
Log.error(e);
} finally {
try {
if (os != null) {
os.close();
}
} catch (final IOException e) {
Log.error(e);
}
}
}
}
такой вот забавный сериализатор получился
причина - запутался в генериках
+171
if (a == 0 && b == 0 && c == 0 && d == 0) n = 0;
if (a == 0 && b == 0 && c == 0 && d != 0) n = 0;
if (a == 0 && b == 0 && c != 0 && d == 0) n = 0;
if (a == 0 && b != 0 && c == 0 && d == 0) n = 0;
if (a != 0 && b == 0 && c == 0 && d == 0) n = 0;
if (a == 0 && b == 0 && c != 0 && d != 0 && c == d) m += 1;
if (a == 0 && b != 0 && c != 0 && d == 0 && b == c) m += 1;
if (a == 0 && b != 0 && c == 0 && d != 0 && b == d) m += 1;
if (a != 0 && b == 0 && c == 0 && d != 0 && a == d) m += 1;
if (a != 0 && b == 0 && c != 0 && d != 0 && a == c) m += 1;
if (a != 0 && b != 0 && c == 0 && d == 0 && a == b) m += 1;////
if (a == 0 && b != 0 && c != 0 && d != 0 && b == c) m += 1;
if (a == 0 && b != 0 && c != 0 && d != 0 && b == d) m += 1;
if (a == 0 && b != 0 && c != 0 && d != 0 && c == d) m += 1;//
if (a != 0 && b == 0 && c != 0 && d != 0 && a == c) m += 1;
if (a != 0 && b == 0 && c != 0 && d != 0 && a == d) m += 1;
if (a != 0 && b == 0 && c != 0 && d != 0 && d == c) m += 1;//
if (a != 0 && b != 0 && c == 0 && d != 0 && a == b) m += 1;
if (a != 0 && b != 0 && c == 0 && d != 0 && a == d) m += 1;
if (a != 0 && b != 0 && c == 0 && d != 0 && b == d) m += 1;//
if (a != 0 && b != 0 && c != 0 && d == 0 && a == b) m += 1;
if (a != 0 && b != 0 && c != 0 && d == 0 && a == c) m += 1;
if (a != 0 && b != 0 && c != 0 && d == 0 && c == b) m += 1;////
m--;
if (a != 0 && b != 0 && c != 0 && d != 0 && a == b) k += 1;
if (a != 0 && b != 0 && c != 0 && d != 0 && a == c) k += 1;
if (a != 0 && b != 0 && c != 0 && d != 0 && a == d) k += 1;
if (a != 0 && b != 0 && c != 0 && d != 0 && b == c) k += 1;
if (a != 0 && b != 0 && c != 0 && d != 0 && b == d) k += 1;
if (a != 0 && b != 0 && c != 0 && d != 0 && c == d) k += 1;
k -= 3;
if (m <= 0) m = 0;
if (k <= 0) k = 0;
n = k + m;*/
Как на второй день после начала изучения С стал решать задачу "Сколько чисел повторяются"
+173
AX=pow(A[i].r.get_x()*A[i].r.get_x(),0.5);
Берем модуль числа.
+75
float lan = getLan();
float lon = getLan();
if(lan == lan || lon == lon)
{
throw new RuntimeException("Bad value");
}
Из моего реалного проекта. Этот код реально делает полезную вещь
+82
void setEnabled(boolean disable)
+151
function addimagesave()
{
if (!$this->Login->isLogged())
{
$this->loginto();
return;
}
else $this->Login->Update();
$error = '';
$recordExists = false;
$post_name = trim($this->input->post('name'));
if ($post_name != '') $insert['file_name'] = $post_name;
// now need to get from db if id_all in i_pics
$this->db->where('id_all',$this->input->post('id_all'));
$this->db->limit(1);
$query = $this->db->get('i_pics');
if ($query->num_rows() == 1)
{
$row = $query->row();
$recordExists = true;
$file_name = $row->file_name;
$id_pics = $row->id_pics;
}
if (isset($_FILES['upload']) && ($_FILES['upload']['error'] == 0)) // is file loaded?
{
$ext = getExtensionOnly($_FILES['upload']['name']);
if ($post_name != '') $_FILES['upload']['name'] = $post_name.'.'.$ext;
else $post_name = delExtensionWithDot($_FILES['upload']['name']);
$_FILES['upload']['name'] = translitIt(delExtensionWithDot($_FILES['upload']['name'])).'.'.$ext;
$config['upload_path'] = './pics/';
$config['allowed_types'] = 'gif|jpg|png|bmp';
$this->load->library('upload', $config);
if ($this->upload->do_upload('upload'))
{
$this->General->setEmes(array('roster'=>"Картинку загружено."), true);
$data = $this->upload->data();
$insert['file_name'] = $data['file_name'];
// resize now
$config1['image_library'] = 'gd2'; // выбираем библиотеку
$config1['source_image'] = 'pics/'.$data['file_name'];
$config1['create_thumb'] = TRUE; // ставим флаг создания эскиза
$config1['maintain_ratio'] = true; // сохранять пропорции
$config1['width'] = 250; // и задаем размеры
$config1['height'] = 180;
// pre crack image for resizing! )))
$this->load->model('Image');
$this->Image->smartsigninto('pics/'.$data['file_name'], 250, 180);
$this->load->library('image_lib', $config1); // загружаем библиотеку
$this->image_lib->resize(); // и вызываем функцию
// now rename and owerwrite original image
$ext = getExtensionOnly($data['file_name']);
$fol = "pics/";
if (is_file($fol.$data['raw_name'].'_thumb.'.$ext))
rename($fol.$data['raw_name'].'_thumb.'.$ext, $fol.$data['file_name']);
else $this->General->setEmes(array('roster'=>"Файл *_thumb не был создан!"));
// now set new file size
$insert['size'] = round(filesize($fol.$data['file_name'])/1024 , 2);
}
else $this->General->setEmes(array('roster'=>$this->upload->display_errors()));
}
else // we need to try to rename assigned file if name is not empty and file exists
{
if ($recordExists && is_file('pics/'.$file_name) && ($post_name != ''))
{
$ext = getExtensionOnly($file_name);
$fol = "pics/";
$newName = translitIt($post_name).'.'.$ext;
if (is_file('pics/'.$newName))
{
$this->General->setEmes(array('roster'=>"Имя уже существует"), true);
$insert['file_name'] = $file_name;
}
else
{
rename($fol.$file_name, $fol.$newName);
$insert['file_name'] = $newName;
}
}
}
// prepare data to be ins or upd
$insert['lang'] = 'ru';
$insert['title'] = $this->input->post('title');
$insert['alt'] = $this->input->post('alt');
$insert['id_all'] = $this->input->post('id_all');
if ($recordExists)
{
$this->db->where('id_pics',$id_pics);
$this->db->update('i_pics', $insert);
$this->General->setEmes(array('roster'=>"Данные обновлены"), true);
}
else $this->db->insert('i_pics', $insert);
$this->redirect('roster/'.$this->input->post('type'));
}
Функция - контроллер сохранения, resize на лету картинки для новости или прочей байды. Есть все проверки. Любая картинка которая приходит, становится размером 250, 180 , причем без растяжения. Это задача типа вписать прямоугольник в прямоугольник, которую я сейчас ночью выполнил - даже если картинка меньше оно впишет. I must be proud about this functionality! Заметим, что в интернете все и умеют что вырезать квадраты из картинки, а произвольный размер - НЕТ такого. Код выложен чтобы вы посмотрели, нравятся ли вам имена переменных, логическое мышление, форматирование, коментарии (на русском - то не мои коментарии). Код CodeIgniter powered.