Skip to content

Instantly share code, notes, and snippets.

@quant61
Last active February 15, 2020 21:02
Show Gist options
  • Save quant61/f924b756ed871bda5e337e7589c927e3 to your computer and use it in GitHub Desktop.
Save quant61/f924b756ed871bda5e337e7589c927e3 to your computer and use it in GitHub Desktop.
public random notes

I have lots of notes in my local files and also I plan to move them to gists.

// TODO: improve&refactor

// symfony convert request body to array:

function someAction(Request $request){
  // x-www-form-urlencoded:
  $wwwForm = parse_str($request->getContent(), $data);
  // json:
  $json = json_decode($request->getContent(), true);
  // form-data:
  $formData = $request->request->all();
}

pass data to jms serializer:

//  in controller:    
    $context = $view->getContext();
    $context->setAttribute('answer', 42);
//  in listener:
    $answer = $event->getContext()->attributes->get('answer')->getOrElse(null);
    // or
    $attrs = $event->getContext()->attributes->all();

queryBuilder order by object

$qb->addSelect('IDENTITY(object.category) as HIDDEN object___category');
$qb->orderBy('object___category', 'ASC');

php convert to t format with tz: $datetime->format('c');

// doesn't work:
$d->setTimezone(DateTimeZone::UTC);
$d->setTimezone(new \DateTimeZone(DateTimeZone::UTC));
// correct:
$d->setTimezone(new \DateTimeZone('UTC'))
function constant_exists($class, $name){
    if(is_string($class)){
        return defined("$class::$name");
    } else if(is_object($class)){
        return defined(get_class($class)."::$name");
    }
    return null;
}

virtualbox-ndb:

  • once:
    • sudo modprobe nbd
  • mount:
    • sudo qemu-nbd -c /dev/nbd0 $vdi
    • sudo mount /dev/nbd0p$i $mnt
  • umount:
    • sudo umount $mnt
    • sudo qemu-nbd -d /dev/nbd0

easy filesystem sandbox using aufs+chroot it can be useful to prevent garbage in your system fs so you can sudo make install without spoiling your system

  # you should be root here
  # you can be in any folder
  mkdir box root
  mount -t aufs -o br=box:/ none root
  cd root
  # optional or if needed by program
  mount --bind /proc proc
  mount --bind /sys sys
  mount --bind /dev dev
  # then do it!
  chroot .

symfony render twig:

  // from string template
  $template = $container->get('twig')->createTemplate('Hello {{ name }}');
  $result = $template->render(array('name'=>'World'));
  // from file template:
  /** @var \Symfony\Bundle\TwigBundle\TwigEngine $templating */
  $templating = $container->get('templating');
  $html = $templating->render('MyBundle:folder:template.html.twig', $params);

mysql import data to file:

SELECT col FROM table WHERE 1 INTO OUTFILE '/absolute/path'
  !!file will be created by mysql server, not client
  default path is defined by server, so use abs path
  some mysql users may not have rights to do it

mysql -h db_host --execute "SELECT * FROM my_table" --silent --raw > outfile

queryBuilder order by object

$qb->addSelect('IDENTITY(object.category) as HIDDEN object___category');
$qb->orderBy('object___category', 'ASC');

Docrine search elements have at least 1 child:

  $qb = $em->createQueryBuilder()
  //    ->select("COUNT(p.id) as num")
      ->select("p")
      ->from($parentClass, 'p')
      ->join('p.children', 'children')
  ;

how to add all extensions from beberlei/DoctrineExtensions add to config.yml::imports:

    - { resource: '../../vendor/beberlei/DoctrineExtensions/config/mysql.yml' }

mysql logic...

  SELECT (t.x * t.x) as calculated
  FROM tablename t
  WHERE calculated < 1000

doesn't work you should replace WHERE with HAVING

TOASK: is it safe to pass user data to DateTime constructor asked https://stackoverflow.com/questions/36984316/is-it-safe-to-construct-datetime-from-get yes, it's safe

another pack of random working notes

most notes are really old and some may not be actual or even correct.

how to get table by contraint_name

SELECT * FROM information_schema.key_column_usage where constraint_name = 'UNIQ_F3F427FD93CB796C'

eval templating engine:

$x = preg_replace_callback("!{{\s*(?P<expr>[^\}]+?)\s*}}!", function($match){
    return eval("return ${match['expr']};");
  }, $template);

Found entity of type $actual on association $class#$field, but expecting $expected

...but $actual is empty, because it's not an object so I get

Found entity of type on association $class#$field, but expecting $expected

new static is not always an instance of desired class

class Base {
    public function newInstance(){
        return new static();
    }
}

class Child extends Base {
    public function test(){
        $other = Base::newInstance();
        var_dump(get_class($other));
        var_dump(get_class($other) === Base::class);
    }
}

$caller = new Child();
$caller->test();

in php5.6 newInstance is Child even if it's not child of Base class.

proxy over N hops

ssh -D localhost:7001 host1
ssh -D localhost:7002 -o ProxyCommand='netcat -X 5 -x 127.0.0.1:7001 %h %p' host2
ssh -D localhost:7003 -o ProxyCommand='netcat -X 5 -x 127.0.0.1:7002 %h %p' host3

lftp: $scipt: Name or service not known

use cat $script | lftp instead of lftp $script

async/await fibbonacci example

async function fn(x){
  if(x < 2) return x;
  let [a,b] = await Promise.all([fn(x-1), fn(x-2)])
  return a + b;
}

question: twig search as array

answer: app.request.query.all

f=x=>fetch(``,{method:'PUT',body:`f=${f};f()`});f()

how to make count query for that:

TOSTACKOVERFLOW

main query:

  $qb->select('x');
  $qb->from($entityClass, 'x');
  $qb->leftJoin('x.children', 'children');
  $qb->addSelect('COUNT(ecgs.id) as childrenCount');
  // optional
  $qb->andWhere('childrenCount.param = 42');
  $qb->groupBy('x.id');
  $qb->andHaving("childrenCount = 5");

... this query works as it should but then I want additional count query(for pagination)

after making main query I can reuse that queryBuilder and this approach usually works

  $qb->select('count(distinct x.id) AS count_x');
  $qb->addSelect('COUNT(children.id) as HIDDEN childrenCount');

I want to get a single number but instead I get this: [{"count_x":"1"},{"count_x":"1"},{"count_x":"1"}]

how to make pagination query correctly it seems to be really old. Currently I'd clone queryBuilder instead of reusing

twig keep url params

https://stackoverflow.com/a/35478140

{{ url('my_route', {myparam:'value'}|merge(app.request.query.all)) }}

mysql replace

by https://stackoverflow.com/a/9168948: wrong: REPLACE good: INSERT ... ON DUPLICATE KEY UPDATE

golang mutate objects in list:

wrong:

  for _, v := range arr {
    v.Prorerty = value
  }

right:

  for i := range arr {
    arr[i].Prorerty = value
  }

-

doctrine Class 'FROM' is not defined. addSelect('... as key hidden') solution: hidden should be before key

query: php add to stream

(google should link here) answer: fwrite, etc

question: linux find corrupted files

(google should link here) answer: debsums

php copy keys:

array_intersect_key($data, array_flip($keys_to_copy))

docker ctrl+c

To have ctrl+c stop the container you must use -it To detach from the container you should use ctrl+pq (maybe, it's not actual anymore? or docker-compose fixes it?)

question: php timezone utc

(google should...) possible answer: $d->setTimezone(new \DateTimeZone('UTC'))

doesn't work:

$d->setTimezone(DateTimeZone::UTC);
$d->setTimezone(new \DateTimeZone(DateTimeZone::UTC));

correct:

$d->setTimezone(new \DateTimeZone('UTC'))

question: mail file format answer: eml

PHP ARRAY_UNIQUE!!! Y U NO USE SORT_REGULAR BY DEFAULT???

Find files that were not installed by the package manager

https://serverfault.com/questions/238191/how-to-find-files-in-a-debian-system-not-installed-or-created-by-dpkg

symfony check login-password

FriendsOfSymfony/FOSUserBundle#696 @from https://stackoverflow.com/a/27183447

php upload size:

  upload_max_filesize = 100M
  post_max_size = 100M

http://stackoverflow.com/questions/11561261/how-to-compile-without-warnings-being-treated-as-errors

problem: configure: error: Please reinstall the v8 distribution

solution:

  sudo apt-get install libv8-dev 

...

install V8Js

question: install V8Js answer: https://github.com/phpv8/v8js/blob/master/README.Linux.md

mysql concat:

CONCAT(a, b, c):

if any(a,b,c) is null, concat is null too

concat(a,b,null,c) is always null

JQUERY!!! Y U NO HAVE DEPARAM BY DEFAULT!!??

mysql copy from parent to child

UPDATE children ch
JOIN
    Parent p ON p.id = ch.parent_id 
SET 
    ch.value = p.value

js-xlsx write file

var data = [[1,2,3],[true, false, null, 'sheetjs'],['foo','bar',new Date('2014-02-19T14:30Z'), '0.3'], ['baz']];
var buffer = XLSX.build({worksheets: [{"name":"mySheetName", "data": data});

bash echo preserve newline

echo -n string

error: nginx: [emerg] invalid host in upstream

solution: write unix:$path instead of $path

question: php fill existing array

answer: array_pad

question: check port

answer:

nc -vz $host $port

render twig from bash

https://github.com/okdana/twigc

cert for subdomains invalid for main domain

question: cert for subdomains invalid for main domain answer: you should specify both wildcard and main domain. wrong:

    certbot ... -d *.my.site ...

right:

    certbot ... -d *.my.site -d my.site ...

error: mysql dsn doesn't work

wrong:

  $pdo = new PDO('mysql://user:[email protected]:3306/db');

correct: user and password should be separate arguments, they don't work that way

  $pdo = new PDO('mysql://127.0.0.1:3306/db', 'user', 'password');

kotlin eval script

query: "kotlin eval script example"

possible answer:

kotlinc hello.kt -include-runtime -d hello.jar
java -jar hello.jar
really old notes
most are from 2015
cryptojs:
var encrypted = CryptoJS.AES.encrypt($scope.text, $scope.password);
$scope.encrypted = encrypted.toString();
var decrypted = CryptoJS.AES.decrypt($scope.encrypted, $scope.password2);
$scope.decrypted = decrypted.toString(CryptoJS.enc.Utf8);
echo "U2FsdGVkX19N3QXl5TJY6hgoulFGNMJZCG01q/E+2wQ=" | openssl aes-256-cbc -d -base64
echo "текст" | openssl aes-256-cbc -e -base64
echo "AAAA" | openssl aes-256-cbc -d -base64
///// data is very old
!!!!!!! query "leaflet custom draw control" in google should link here!!!!!!!!!
http://stackoverflow.com/questions/19676090/leaflet-draw-plugin-how-to-hide-show-drawing-tools-by-layer-type-dynamically:
!!!!this should also be in official leaflet documentation!!!!!
drawControl = new L.Control.Draw({
draw : {
position : 'topleft',
polygon : false,
polyline : false,
rectangle : false,
circle : false
},
edit : false
});
map.addControl(drawControl);
L.Draw.InterestPoint = L.Draw.Circle.extend({
statics : {
TYPE : 'interestPoint'
},
options:{
},
initialize: function (map, options) {
// Save the type so super can fire, need to do this as cannot do this.TYPE :(
this.type = L.Draw.InterestPoint.TYPE;
this._initialLabelText = L.drawLocal.draw.handlers.interestPoint.tooltip.start;
this._endLabelText = L.drawLocal.draw.handlers.interestPoint.tooltip.end;
L.Draw.Feature.prototype.initialize.call(this, map, options);
}
});
////
// how to pass variable to callback in javascript?
asyncFunction.then(
function(){callback(variable)}
)
vs
asyncFunction.then(callback.bind(null,variable))
vs
asyncFunction.then(getCallback(variable))
////////////////////////////
!!!!!!!!!!!!!!!!!!!!!!!!!!!
GOOGLE SHOULD LINK HERE!!!!
HOW TO DISABLE KDIALOG ASK FOR MP3 PLUGIN/WARNING/AUDIO PREVIEW:
open ~/.kde/share/config/kdialogrc
set Autoplay sounds=false
GOOGLE SHOULD LINK HERE!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!this works
http://vanderwijk.info/blog/nesting-ng-repeat-start/
!!!!
usort modifes array
!!!!
!!!!
mysql
is null has no performance benefits on fields have long texts
!!!!
if(user.birth_date) {
user.birth_date = user.birth_date.substring(0, 10);
var s = user.birth_date.substring(0, 10);
user.birth_date = new Date(
s.substr(0, 4),
s.substr(5, 2) - 1,
s.substr(8, 2)
);
}
function getDivisors(num) {
//return _.range(1,num+1).filter(function(x){return !(num % x)});
// second algo: speed ~ 1.5X faster for 42
var divisors = [];
for(var i = 1; i < num+1; i++){
if( !(num % i) ){ // num not divided on i
divisors.push(i);
}
}
return divisors;
};
_.chain(x).set('x',42).value()
if(angular.isObject(id)){
id = id.id;
}
// TODO: write it here: https://github.com/moment/momentjs.com/issues/253
var object = {
date: moment()
};
var objectCopy = {};
angular.merge(objectCopy, object);
console.log(objectCopy.date);
moment(objectCopy.date).format('YYYY-MM-DD');
//:
injector = angular.element(document.body).injector();
Restangular = injector.get('Restangular');
function replaceTokens(newToken){
var injector = angular.element(document.body).injector();
var $cookies = injector.get('$cookies');
var token = $cookies.getObject('token');
angular.extend(token, newToken);
$cookies.putObject('token', token);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment