- 1
- 2
- 3
- 4
- 5
- 6
<script>
var x = [];
var y = [];
x = [<?php foreach ($chart as $word => $f) echo "'$word', " ?>];
y = [<?php foreach ($chart as $f) echo "$f, " ?>];
</script>
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+2
<script>
var x = [];
var y = [];
x = [<?php foreach ($chart as $word => $f) echo "'$word', " ?>];
y = [<?php foreach ($chart as $f) echo "$f, " ?>];
</script>
JS
+4
if ($_REQUEST["date_type"] == 1) {
$filter .= "AND t.id IN (SELECT task_id FROM `task_comments` WHERE (`status_id`=".$DB->F($doneStatus["id"])." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')>=".$DB->F(date("Y-m-d", strtotime($_POST['datefrom'])))." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')<=".$DB->F(date("Y-m-d", strtotime($_POST['dateto']))).") ORDER BY `datetime` DESC) AND t.id NOT IN (SELECT task_id FROM `task_comments` WHERE (`status_id`=".$DB->F($doneStatus["id"])." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')>".$DB->F(date("Y-m-d", strtotime($_POST['dateto']))).") ORDER BY `datetime` DESC)";
} else {
if ($_REQUEST["date_type"] == 2) {
$filter .= "AND t.id IN (SELECT task_id FROM `task_comments` WHERE `status_id` AND (DATE_FORMAT(`datetime`, '%Y-%m-%d')>=".$DB->F(date("Y-m-d", strtotime($_POST['datefrom'])))." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')<=".$DB->F(date("Y-m-d", strtotime($_POST['dateto'])))."))";
} else {
if ($_REQUEST["date_type"] == 3) {
$filter .= "AND t.id IN (SELECT task_id FROM `task_comments` WHERE ((`status_id`=".$DB->F($doneStatus["id"])." OR `status_id`=".$DB->F($failStatus["id"])." OR `status_id`=".$DB->F($failOpStatus["id"]).") AND DATE_FORMAT(`datetime`, '%Y-%m-%d')>=".$DB->F(date("Y-m-d", strtotime($_POST['datefrom'])))." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')<=".$DB->F(date("Y-m-d", strtotime($_POST['dateto']))).") ORDER BY `datetime` DESC) AND t.id NOT IN (SELECT task_id FROM `task_comments` WHERE ((`status_id`=".$DB->F($doneStatus["id"])." OR `status_id`=".$DB->F($failStatus["id"])." OR `status_id`=".$DB->F($failOpStatus["id"]).") AND DATE_FORMAT(`datetime`, '%Y-%m-%d')>".$DB->F(date("Y-m-d", strtotime($_POST['dateto']))).") ORDER BY `datetime` DESC)";
} else {
if ($_REQUEST["date_type"] == 4) {
// am
$filter .= "AND tick.inmoney=1 AND DATE_FORMAT(tick.inmoneydate, '%Y-%m-%d')>=".$DB->F(date("Y-m-d", strtotime($_POST['datefrom']))) . " AND DATE_FORMAT(tick.inmoneydate, '%Y-%m-%d')<=".$DB->F(date("Y-m-d", strtotime($_POST['dateto'])));
} else {
if ($_REQUEST["date_type"] == 5) {
//cl_date
$filter .= "AND t.id IN (SELECT task_id FROM `task_comments` WHERE (`status_id`=".$DB->F($closedStatus["id"])." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')>=".$DB->F(date("Y-m-d", strtotime($_POST['datefrom'])))." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')<=".$DB->F(date("Y-m-d", strtotime($_POST['dateto']))).") ORDER BY `datetime` DESC) AND t.id NOT IN (SELECT task_id FROM `task_comments` WHERE (`status_id`=".$DB->F($closedStatus["id"])." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')>".$DB->F(date("Y-m-d", strtotime($_POST['dateto']))).") ORDER BY `datetime` DESC)";
} else {
if ($_REQUEST["date_type"] == 6) {
//rep_date
$filter .= "AND t.id IN (SELECT task_id FROM `task_comments` WHERE (`status_id`=".$DB->F($reportStatus["id"])." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')>=".$DB->F(date("Y-m-d", strtotime($_POST['datefrom'])))." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')<=".$DB->F(date("Y-m-d", strtotime($_POST['dateto']))).") ORDER BY `datetime` DESC)";
} else {
if ($_REQUEST["date_type"] == 7) {
//rep_date
$filter .= "AND t.id IN (SELECT task_id FROM `task_comments` WHERE (`status_id`=".$DB->F($accStatus["id"])." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')>=".$DB->F(date("Y-m-d", strtotime($_POST['datefrom'])))." AND DATE_FORMAT(`datetime`, '%Y-%m-%d')<=".$DB->F(date("Y-m-d", strtotime($_POST['dateto']))).") ORDER BY `datetime` DESC)";
} else {
$filter .= " AND DATE_FORMAT(t.date_reg, '%Y-%m-%d')>=".$DB->F(date("Y-m-d", strtotime($_POST['datefrom']))) . " AND DATE_FORMAT(t.date_reg, '%Y-%m-%d')<=".$DB->F(date("Y-m-d", strtotime($_POST['dateto'])));
}
}
}
}
}
}
}
Запрос для какого-то отчета by ©senior shaurma developer
−3
<?php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class InterpolationLabsCommand extends ContainerAwareCommand
{
/**
* nodes for interpolation polynomial
*/
protected $_nodes;
protected function configure()
{
$this
->setName('app:interpolation:labs')
->setDescription('interpolation')
->addOption('nodes-count', null, InputOption::VALUE_REQUIRED,
'Sets the number of nodes for interpolation.', null);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$intervalStart = -3;
$intervalEnd = 3;
$nodesCount = $input->getOption('nodes-count');
$this->generateSeries($nodesCount, $intervalStart, $intervalEnd, function($x) {
return sin($x);
});
foreach (range($intervalStart, $intervalEnd, 0.1) as $value) {
$result = $this->getLagrangeValue($value);
$output->writeln("$value $result");
}
}
/**
* Find value for lagrange interpolation polynomial at n nodes
* @throw \Exception
*
* @return
*/
protected function getLagrangeValue($x)
{
$w = function($nodeKey) use ($x) {
if (!array_key_exists($nodeKey, $this->_nodes)) {
throw new \Exception("The key is not exists to the array nodes");
}
$return = 1;
foreach ($this->_nodes as $key => $node) {
if ($key == $nodeKey) {
continue;
}
$return *= ($x - $node->x)/($this->getNode($nodeKey)->x - $node->x);
}
return $return;
};
$result = 0;
foreach ($this->_nodes as $nodeKey => $node) {
$a = $w($nodeKey);
$result += $w($nodeKey) * $node->fx;
}
return $result;
}
protected function getNode($i)
{
return $this->_nodes[$i];
}
private function generateSeries($num, $intervalStart, $intervalEnd, $fun)
{
for ($i=0; $i < $num; $i++) {
$x = $intervalStart + ($intervalEnd - $intervalStart)/($num-1) * $i;
$this->_nodes[] = (object) array('x' => $x,
'fx' => $fun($x));
}
}
}
Лаба по методам численного анализа
0
require_once ('./main/config.php');
class user
{
/*
private login;
private password;
private username;
private about;
*/
function registerUser($login, $password, $username, $about)
{
$db = MysqliDb::getInstance();
$data = Array ("login" => $login,
"password" => $password,
"username" => $username,
"about" => $about,
);
$id = $db->insert ('users', $data);
if($id)
echo 'user was created. Id=' . $id;
}
function authorizeUser($login, $password)
{
$db->where ("id", 1);
$user = $db->getOne ("users");
echo $user['id'];
/*
$logins = $db->getValue ("users", "login", null);
// select login from users
// select login from users limit 5
foreach ($logins as $login)
echo $login;
*/
}
}
Ну как вам? Класс юзера для регистрации и авторизации (недоделан)
+6
public function generate_hash($options = null) {
$string_length = (isset($options["length"])) ? $options["length"] : 10;
$use_lowercase = (isset($options["lowercase"])) ? $options["lowercase"] : true;
$use_uppercase = (isset($options["uppercase"])) ? $options["uppercase"] : true;
$lowercase = array(
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z"
);
$uppercase = array(
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z"
);
$digits = array(
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
);
$arrays = array_merge($lowercase, $uppercase);
$final_string = array();
$final_string[] = $arrays[array_rand($arrays)];
// чтобы первым символом не была цифра
$arrays = array_merge($arrays, $digits);
for ($i = 0; $i < ($string_length - 1); $i++) {
$final_string[] = $arrays[array_rand($arrays)];
}
$final_string = implode("", $final_string);
return $final_string;
}
+1
<?php
/*
> 60 seconds - "s"
> 60 minutes - "m"
> 24 hours - "h"
> 30 days - "d"
< 30 days - "5 sep 2010"
*/
class Date {
public static function DateAgo($DateTime) {
$s = s; $m = m; $h = h; $d = d;
$Now = date('Y-m-d H:i:s');
$Now = time();
$Year = substr($DateTime, 0, 4);
$Month = substr($DateTime, 5, 2);
$Day = substr($DateTime, 8, 2);
$Hour = substr($DateTime, 11, 2);
$Minute = substr($DateTime, 14, 2);
$Second = substr($DateTime, 17, 2);
$Time = mktime($Hour, $Minute, $Second, $Month, $Day, $Year);
$Difference = $Now - $Time;
if($Difference < 60) {
$Ago = $Difference.$s;
} elseif($Difference < (60 * 60)) {
$Ago = floor($Difference / 60).$m;
} elseif($Difference < (60 * 60 * 24)) {
$Ago = floor($Difference / (60 * 60)).$h;
} elseif($Difference < (60 * 60 * 24 * 30)) {
$Ago = floor($Difference / (60 * 60 * 24)).$d;
} else {
$Ago = $Day.'.'.$Month.'.'.$Year;
}
return $Ago;
}
} // End class
?>
Забирайте целиком! Нашёл в CMS от http://fn85.ru/ охрененный класс для работы с датами!
0
Нам нужно больше запросов в БД!!!!111 строим дерево меню:
private function Stack($PageCategory) {
$Menu = NULL;
$Q = 'SELECT * FROM '.$this->table.' WHERE pageCategory = '.$PageCategory.' ORDER BY pagePosition;';
$Result = $this->Result($Q);
while($Row = mysql_fetch_assoc($Result)) {
$Row['pageChilds'] = $this->Stack($Row['pageID']);
$Menu[$Row['pageID']] = $Row;
}
return $Menu;
}
AUTOINCREMENT PHP-way:
private function CurrentID() {
$Q = 'SELECT MAX(pageID) as maxID FROM '.$this->table.';';
$Row = $this->Row($Q);
return ++$Row['maxID'];
}
Так форматируем даты:
private function FormatDate() {
$Year = substr($this->publication['publicationDate'], 0, 4);
$Month = substr($this->publication['publicationDate'], 5, 2);
$Day = substr($this->publication['publicationDate'], 8, 2);
return $Day.'.'.$Month.'.'.$Year;
}
Просто контроллер:) А чо?
<?php
class Slider extends DataBase {
private $slides;
public function GetSlides() {
$Q = 'SELECT * FROM slide ORDER BY slidePosition;';
$this->slides = $this->Rows($Q);
}
public function ViewSlides() {
$Slides = '';
if($this->slides) {
foreach($this->slides as $SlideStack) {
$Slides .= $this->ViewSlide($SlideStack);
}
}
return $Slides;
}
private function ViewSlide($SlideStack) {
$A = '<a href="'.$SlideStack['slideLink'].'">';
$A .= ' <div class="BannerSlide">';
$A .= ' <img src="'.I.'/slides/'.$SlideStack['slideImage'].'.jpg">';
$A .= ' <div class="BannerSlideText">';
$A .= ' <div class="BannerSlideTextInner">'.$SlideStack['slideName'].'<br>';
$A .= ' <span>'.$SlideStack['slideText'].'</span>';
$A .= ' </div>';
$A .= ' </div>';
$A .= ' </div>';
$A .= '</a>';
return $A;
}
} // End class
?>
Окунулся в велосипедную CMS, на которой ваяет контора http://fn85.ru/
+3
function pluralize($num) {
switch ($num) {
case 1:
case 21:
$word = "товар";
break;
case 2:
case 3:
case 4:
case 22:
case 23:
case 24:
case 32:
case 33:
case 34:
$word = "товара";
break;
default:
$word = "товаров";
break;
}
return $word;
}
На продакшене.
+2
<?
$lasturl = ($_GET[url]) ? $_GET[url] : $CONFIG[site_url]; // последний урл
$expire = ($_GET[expire] == 1) ? time() + 365*24*60*60 : 0;
$domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
if (preg_match('/^[\d\.]*$/', $domain)) $cookie_domain = $domain; // ip-домен
else {$temp = explode('.', $domain); $temp = array('', $temp[count($temp)-2], $temp[count($temp)-1]); $cookie_domain = implode('.', $temp);}
setcookie($CONFIG[cookie_name], serialize(array($_GET[user_id],$_GET[password])), $expire, $CONFIG[cookie_path], $cookie_domain,
$CONFIG[cookie_secure], true);
if($_GET['iframe'])
{
setcookie('iframe', '1', $expire, $CONFIG[cookie_path], $cookie_domain,
$CONFIG[cookie_secure], true);
}
$i = array_search('www.'.$domain, $CONFIG[domains]);
if ($i && $CONFIG[domains][$i] && $i == count($CONFIG[domains]) - 1) $url = $lasturl;
else
$url = 'http://'.$CONFIG[domains][$i+1].'/domain_login/?user_id='.$_GET[user_id]
.'&password='.$_GET[password].'&expire='.$_GET[expire].'&url='.rawurlencode($lasturl).'&iframe='.($_GET['iframe']?'1':'0');
header("Location: $url");
ScriptEnd();
?>
... когда хочется бросить все и уехать в деревню. Наслаждаться утренней свежестью, слушать пение птиц. День за днем восстанавливая психику так беспощадно порушенную жестокими людьми-самозванцами, порочащими нашу профессию богов!
© "PHP. Немного боли и страдания"
0
public function format_phone($phone) {
$phone = preg_replace("/\D/", "", $phone);
$first_digit = substr($phone, 0, 1);
if ($first_digit == "7" || $first_digit == "8") {
$phone = substr($phone, 1);
}
if ($first_digit == "+") {
$phone = substr($phone, 2);
}
$p = str_split($phone);
$phone = "(" . $p[0] . $p[1] . $p[2] . ") " . $p[3] . $p[4] . $p[5] . "-" . $p[6] . $p[7] . "-" . $p[8] . $p[9];
return $phone;
}