text:
Q: Backbone events with wildcards Is there a way to listen to all events of a namespace. So when I listen to an event like this:
app.vent.on('notification(:id)', function(type){console.lof(type)})

It will listen to all events likes this:
app.vent.trigger('notification:info')
app.vent.trigger('notification:error')
app.vent.trigger('notification:success')

A: No. Backbone typically fires a general eventName event, as well as eventName:specifier event. An example of this is Model.change, which allows you to listen to all changes, as well as changes to individual fields:
model.on('change', this.onAnyPropertyChanged);
model.on('change:name', this.onNamePropertyChanged);

Following this pattern in your code, you could trigger your events as follows:
app.vent.trigger('notification', 'info');
app.vent.trigger('notification:info');

And listen to the general event:
app.vent.on('notification', function(type){
  console.log(type);  //-> "info"
});

A: As mentioned by in this answer it is not possible to listen events with wildcards. But as you can listen to all this will work:
vent.on('all', function(evenName, options) {
  var type = evenName.split(/notification:/)[1];
  if (type) {
    console.log(type, options);
  }
});

A: I have written this helper:
export default class EventsHelper {
  static triggerNamespacedEvent(eventBus, event, args) {
    event.split(':').reduce((previous, current) => {
      eventBus.trigger(previous, current);
      return `${previous}:${current}`;
    });
    eventBus.trigger(event, args);
  }
}

To use this in your view you would do:
actionOne(argsOne){
    EventsHelper.triggerNamespacedEvent(this, 'click:chart:one', argsOne);
}

actionTwo(argsTwo){
    EventsHelper.triggerNamespacedEvent(this, 'click:chart:two', argsTwo);
}

To listen for these events you would do:
//Listen for all clicks
this.listenTo(view, 'click', (args) => {
    console.log(`clicked something: ${args}`); //output: clicked something: chart
});

//Listen for all chart clicks
this.listenTo(view, 'click:chart', (args) => {
    console.log(`clicked chart: ${args}`); //output: clicked chart: one
});

//Listen for fully qualified event
this.listenTo(view, 'click:chart:two', (args) => {
    console.log(`clicked chart two: ${args}`); //output: clicked chart two: evtArgs
});

A: Warning: Listening to event namespaces on custom events may not work any more. For example, this does not work:
  @listenTo @app, 'session', -> console.log ".listenTo `session` triggered"
  @listenTo @app, 'session:login_success', -> console.log ".listenTo `session:login_success` triggered"

  @app.on 'session', -> console.log ".on `session` triggered"
  @app.on 'session:login_success', -> console.log ".on `session:login_success` triggered"

If I trigger 'session:login_success' on the @app, only the two specific events fire, not the namespace one.
Related github issue: https://github.com/documentcloud/backbone/issues/2558


text:
Q: Can I use declare-const to eliminate the forall universal quantifier? I have some confusion of using universal quantifier and declare-const without using forall
(set-option :mbqi true)
(declare-fun f (Int Int) Int)
(declare-const a Int)
(declare-const b Int)

(assert (forall ((x Int)) (>= (f x x) (+ x a))))

I can write like this:
(declare-const x Int)
(assert  (>= (f x x) (+ x a))))

with Z3 will explore all the possible values of type Int in this two cases. So what's the difference?
Can I really use the declare-const to eliminate the forall quantifier?

A: No, the statements are different.  Constants in Z3 are nullary (0 arity) functions, so (declare-const a Int) is just syntactic sugar for (declare-fun a () Int), so these two statements are identical.  Your second statement (assert  (>= (f x x) (+ x a)))) implicitly asserts existence of x, instead of for all x as in your first statement (assert (forall ((x Int)) (>= (f x x) (+ x a)))).  To be clear, note that in your second statement, only a single assignment for x needs to satisfy the assertion, not all possible assignments (also note the difference in the function f, and see this Z3@rise script: http://rise4fun.com/Z3/4cif ).
Here's the text of that script:
(set-option :mbqi true)
(declare-fun f (Int Int) Int)
(declare-const a Int)
(declare-fun af () Int)
(declare-const b Int)
(declare-fun bf () Int)

(push)
(declare-const x Int)
(assert  (>= (f x x) (+ x a)))
(check-sat) ; note the explicit model value for x: this only checks a single value of x, not all of them
(get-model)
(pop)

(push)
(assert (forall ((x Int)) (>= (f x x) (+ x a))))
(check-sat)
(get-model) ; no model for x since any model must satisfy assertion
(pop)

Also, here's an example from the Z3 SMT guide ( http://rise4fun.com/z3/tutorial/guide from under the section "Uninterpreted functions and constants"):
(declare-fun f (Int) Int)
(declare-fun a () Int) ; a is a constant
(declare-const b Int) ; syntax sugar for (declare-fun b () Int)
(assert (> a 20))
(assert (> b a))
(assert (= (f 10) 1))
(check-sat)
(get-model)

A: You can eliminate a top-level exists with a declare-const. Maybe this is the source of your confusion? The following two are equivalent:
    (assert (exists ((x Int)) (> x 0)))
    (check-sat)

and
   (declare-fun x () Int)
   (assert (> x 0))
   (check-sat)

Note that this only applies to top-level existential quantifiers. If you have nested quantification of both universals (forall) and existentials (exists), then you can do skolemization to float the existentials to the top level. This process is more involved but rather straightforward from a logical point of view.
There is no general way of floating universal quantifiers to the top-level in this way, at least not in classical logic as embodied by SMT-Lib.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Diff of two pdf files? I'm looking for a good program to show me the differences between two similar pdf files.  In particular, I'm looking for something that doesn't just run diff on an ascii version (with "pdftotext") of the files.  This is what pdfdiff.py does.

A: You can use DiffPDF for this. From the description:

DiffPDF is used to compare two PDF
  files.  By default the comparison is
  of the text on each pair of pages, but
  comparing the appearance of pages is
  also supported (for example, if  a
  diagram is changed or a paragraph
  reformatted). It is also possible  to
  c> ompare particular pages or page
  ranges. For example, if there are  two
  versions of a PDF file, one with pages
  1-12 and the other with  pages 1-13
  because of an extra page having been
  added as page 4, they  can be compared
  by specifying two page ranges, 1-12
  for the first and 1-3,  5-13 for the
  second. This will make DiffPDF compare
  pages in the pairs  (1, 1), (2, 2),
  (3, 3), (4, 5), (5, 6), and so on, to
  (12, 13).

A: If you have 2-3 huge pdf (or epub or other formats, read below) files to compare , then it is possible to combine the power of:

*

*calibre (to convert your source to text)

*meld (to visually search for the differences between the text files)

*parallel (to use all your system cores to speed up)
Below script accept as input any of the following file formats:
MOBI, LIT, PRC, EPUB, ODT, HTML, CBR, CBZ, RTF, TXT, PDF and LRS.
If not installed, then install meld, calibre and parallel:
#install packages
sudo apt-get -y install meld calibre parallel

To be able to execute the code from anywhere in your computer, save following code in a file named "diffepub" (with no extensions) inside directory "/usr/local/bin".
usage="
*** usage:

diffepub - compare text in two files. Valid format for input files are:
MOBI, LIT, PRC, EPUB, ODT, HTML, CBR, CBZ, RTF, TXT, PDF and LRS.

diffepub -h | FILE1 FILE2

-h print this message

Example:
diffepub my_file1.pdf my_file2.pdf
diffepub my_file1.epub my_file2.epub

v0.2 (added parallel and 3 files processing)
"

#parse command line options
while getopts "h" OPTIONS ; do
  case ${OPTIONS} in
    h|-help) echo "${usage}"; exit;;
  esac
done
shift $(($OPTIND - 1))

#check if first 2 command line arguments are files
if [ -z "$1" ] || [ -z "$2" ] || [ ! -f "$1" ] || [ ! -f "$2" ]
then
  echo "ERROR: input files do not exist."
  echo
  echo "$usage"
  exit
fi

#create temporary files (first & last 10 characters of
# input files w/o extension)
file1=`basename "$1" | sed -r -e '
s/\..*$//                     #strip file extension
s/(^.{1,10}).*(.{10})/\1__\2/ #take first-last 10 chars
s/$/_XXX.txt/                 #add tmp file extension
'`
TMPFILE1=$(mktemp --tmpdir "$file1")

file2=`basename "$2" | sed -r -e '
s/\..*$//                     #strip file extension
s/(^.{1,10}).*(.{10})/\1__\2/ #take first-last 10 chars
s/$/_XXX.txt/                 #add tmp file extension
'`
TMPFILE2=$(mktemp --tmpdir "$file2")

if [ "$#" -gt 2 ]
then
  file3=`basename "$3" | sed -r -e '
  s/\..*$//                     #strip file extension
  s/(^.{1,10}).*(.{10})/\1__\2/ #take first-last 10 chars
  s/$/_XXX.txt/                 #add tmp file extension
  '`
  TMPFILE3=$(mktemp --tmpdir "$file3")
fi

#convert to txt and compare using meld
doit(){ #to solve __space__ between filenames and parallel
  ebook-convert $1
}
export -f doit
if [ "$#" -gt 2 ]
then
  (parallel doit ::: "$1 $TMPFILE1" \
                     "$2 $TMPFILE2" \
                     "$3 $TMPFILE3" ) &&
  (meld "$TMPFILE1" "$TMPFILE2" "$TMPFILE3")
else
  (parallel doit ::: "$1 $TMPFILE1" \
                     "$2 $TMPFILE2" ) &&
  (meld "$TMPFILE1" "$TMPFILE2")
fi

Make sure the owner is your user and it has execution permissions:
sudo chown $USER:$USER /usr/local/bin/diffepub
sudo chmod 700 /usr/local/bin/diffepub

To test it, just type:
diffepub FILE1 FILE2

I test it to compare 2 revisions of a +1600 pages pdf and it works perfect. Because calibre is written using python for portability, it took 10 minutes to convert both files to text. Slow, but reliable.

A: I just figured out a hack to make DiffPDF (the program suggested by @qbi) usable for more than minor changes.  What I do is concatenate all pages pdfs into a long scroll using pdfjam and then compare the scrolls.  It works even when large sections are removed or inserted!
Here is a bash script that does the job:
#!/bin/bash
#
# Compare two PDF files.
# Dependencies:
#  - pdfinfo (xpdf)
#  - pdfjam  (texlive-extra-utils)
#  - diffpdf
#

MAX_HEIGHT=15840  #The maximum height of a page (in points), limited by pdfjam.

TMPFILE1=$(mktemp /tmp/XXXXXX.pdf)
TMPFILE2=$(mktemp /tmp/XXXXXX.pdf)

usage="usage: scrolldiff -h FILE1.pdf FILE2.pdf
  -h print this message

v0.0"

while getopts "h" OPTIONS ; do
    case ${OPTIONS} in
        h|-help) echo "${usage}"; exit;;
    esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ] || [ -z "$2" ] || [ ! -f "$1" ] || [ ! -f "$2" ]
then
  echo "ERROR: input files do not exist."
  echo
  echo "$usage"
  exit
fi

    #Get the number of pages:
pages1=$( pdfinfo "$1" | grep 'Pages' - | awk '{print $2}' )
pages2=$( pdfinfo "$2" | grep 'Pages' - | awk '{print $2}' )
numpages=$pages2
if [[ $pages1 > $pages2 ]]
then
  numpages=$pages1
fi

     #Get the paper size:
width1=$( pdfinfo "$1" | grep 'Page size' | awk '{print $3}' )
height1=$( pdfinfo "$1" | grep 'Page size' | awk '{print $5}' )
width2=$( pdfinfo "$2" | grep 'Page size' | awk '{print $3}' )
height2=$( pdfinfo "$2" | grep 'Page size' | awk '{print $5}' )

if [ $(bc <<< "$width1 < $width2") -eq 1 ]
then
  width1=$width2
fi
if [ $(bc <<< "$height1 < $height2") -eq 1 ]
then
  height1=$height2
fi

height=$( echo "scale=2; $height1 * $numpages" | bc )
if [ $(bc <<< "$MAX_HEIGHT < $height") -eq 1 ]
then
  height=$MAX_HEIGHT
fi
papersize="${width1}pt,${height}pt"

    #Make the scrolls:
pdfj="pdfjam --nup 1x$numpages --papersize {${papersize}} --outfile"
$pdfj "$TMPFILE1" "$1"
$pdfj "$TMPFILE2" "$2"

diffpdf "$TMPFILE1" "$TMPFILE2"

rm -f $TMPFILE1 $TMPFILE2

A: As complement to the above answer about diff and diffuse we can use Meld as graphical comparison tool - install it with
sudo apt-get install meld

and then compare documents with command like
meld <(pdftotext -layout old.pdf /dev/stdout) <(pdftotext -layout new.pdf /dev/stdout)

Personally I like Meld more than DiffUse of Kdiff3.

A: We've been working on a tool and wanted to chime in.
If you're happy with trying an online tool, we built something at Draftable.com which does what you seem to want - compare two PDF/Word files and show deletions and additions.
Right now, our Desktop version is Windows only; but, we also have an API that we published a few years ago and it has been working very well for people with high volumes or security concerns.
I've prepared an image (link below) so that you can see the kind of output you'd get without needing to visit the site. Feedback greatly appreciated!

A: Even though this doesn't solve the issue directly, here is a nice way to do it all from the commandline with few dependencies:
diff <(pdftotext -layout old.pdf /dev/stdout) <(pdftotext -layout new.pdf /dev/stdout)

https://linux.die.net/man/1/pdftotext
It works really well for basic pdf comparisons.  If you have a newer version of pdftotext you can try -bbox instead of -layout.
As far as diffing programs go, I like using diffuse, so the command changes ever so slightly:
diffuse <(pdftotext -layout old.pdf /dev/stdout) <(pdftotext -layout new.pdf /dev/stdout)

http://diffuse.sourceforge.net/
Hope that helps.


text:
Q: How to input external sensor's data for Head tracking in cardboard I would like to make cardboard app without android internal sensors and input the external sensor's data for Head Tracking. How do I make that?
Could you give me link or sample code for that?

A: i think you can see this repo
This is decompilated source from cardboard.
Simple way - inherit from cardboard classes and rewrite  sensor listners code.


text:
Q: SQL statement WHERE combined with AND and OR I want to update table headers' columns_header where field is equal to 'c02_Emissions' and field_base either 'VEHICLE' or 'VEHICLE_FP'. My current script updates all 'VEHICLE' and 'VEHICLE_FP' records and doesn't care about field = 'c02_Emissions'. This is not what I want. Can I get a bit of help on how to do it properly?
UPDATE headers
SET columns_header = 'CO2 Emissions'
WHERE field = 'c02_Emissions'
AND field_base = 'VEHICLE'
OR field_base = 'VEHICLE_FP';

A: When combing AND's and OR's, you should always use parentheses:
UPDATE headers
SET columns_header = 'CO2 Emissions'
WHERE field = 'c02_Emissions'
AND (field_base = 'VEHICLE'
OR field_base = 'VEHICLE_FP');

A: You can also try this
UPDATE headers
SET columns_header = 'CO2 Emissions'
WHERE field = 'c02_Emissions'
AND field_base IN ( 'VEHICLE','VEHICLE_FP');


text:
Q: Codeigniter DB where clause syntax error Consider this function to retrieve data from DB in Codeigniter:
function popular_list($limit=2)
{
    $this->db->select('news.*');
    $this->db->where('id',$this->uri->segment(3));
    $this->db->where('publish',1);
    $this->db->where('viewed',(>=5));
    $this->db->order_by('id','DESC');
    $this->db->limit($limit);
    $query = $this->db->get('news');
    return $query->result();
}

I'm getting this parse error:
Parse error: parse error in C:\xampp\htdocs\misnews\application\models\home_model.php on line 113 Line 113 is : $this->db->where('viewed',(>=5));

What am I doing wrong?

A: change your condition as below:
$this->db->where('viewed >= ',5);


text:
Q: WP - cURL call to an externa API stopped working- cURL Error 60: SSL certificate problem: certificate has expired I have created some 'basic' API calls using cURL on a WP website that have been working until last Friday.
Since then I receive this error message.
Error n: 60,
Error: SSL certificate problem: certificate has expired.
Now I just checked on https://www.ssllabs.com/ssltest/analyze.html?d=ombri-immo.lu
(ombri-immo.lu is the domain of the website) and the certificate is still valid.
(To be thorough I have two website that call the same API and give back the same error)
 $ch = curl_init();

  curl_setopt_array($ch, array(
    CURLOPT_URL => 'https://middleware-production.easy2pilot-v8.com/api/***/token',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER, false,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_POSTFIELDS =>'{
    "login": "**",
    "password": "**"
  }',
    CURLOPT_HTTPHEADER => array(
      'Content-Type: application/json;charset=UTF-8'
    ),
  ));

  $response = curl_exec($ch);

  echo 'GETINFO: ' . curl_getinfo($ch) . '
';
  echo curl_errno($ch) . '
';
  echo 'CURL ERROR: ' . curl_error($ch) . '
';

  curl_close($ch);
  echo $response;

This is the code of the call. The credentials work properly since I tested them on Postman and everything is fine.
I have read many posts and most of them suggest touching thing on the server side, which I have no access to and no knowledge about functioning, I take for granted that it is the domain provider (OVH) that id taking care of that.
Also I am not completely in charge of the project and know for a fact that WordPress is not up to date (Hopefully this will happen tomorrow and will fix everything :) ) and also I have noticed that the curl version installed on the server is old ( again I have contacted the reseller and asked him to update that.
Does anybody have any suggestions on things to try or if for example the domain and server provider should be able to take care of this?
Thanks for taking the time of reading the post.

A: The problem I can see is with your CA bundle that is not correct in ombri-immo.lu domain so it must be updated.
Certificate Chain: The certificate chain does NOT validate.
This certificate was issued by the R3 CA bundle.
-----BEGIN CERTIFICATE-----
MIIEZTCCA02gAwIBAgIQQAF1BIMUpMghjISpDBbN3zANBgkqhkiG9w0BAQsFADA/
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
DkRTVCBSb290IENBIFgzMB4XDTIwMTAwNzE5MjE0MFoXDTIxMDkyOTE5MjE0MFow
MjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxCzAJBgNVBAMT
AlIzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuwIVKMz2oJTTDxLs
jVWSw/iC8ZmmekKIp10mqrUrucVMsa+Oa/l1yKPXD0eUFFU1V4yeqKI5GfWCPEKp
Tm71O8Mu243AsFzzWTjn7c9p8FoLG77AlCQlh/o3cbMT5xys4Zvv2+Q7RVJFlqnB
U840yFLuta7tj95gcOKlVKu2bQ6XpUA0ayvTvGbrZjR8+muLj1cpmfgwF126cm/7
gcWt0oZYPRfH5wm78Sv3htzB2nFd1EbjzK0lwYi8YGd1ZrPxGPeiXOZT/zqItkel
/xMY6pgJdz+dU/nPAeX1pnAXFK9jpP+Zs5Od3FOnBv5IhR2haa4ldbsTzFID9e1R
oYvbFQIDAQABo4IBaDCCAWQwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8E
BAMCAYYwSwYIKwYBBQUHAQEEPzA9MDsGCCsGAQUFBzAChi9odHRwOi8vYXBwcy5p
ZGVudHJ1c3QuY29tL3Jvb3RzL2RzdHJvb3RjYXgzLnA3YzAfBgNVHSMEGDAWgBTE
p7Gkeyxx+tvhS5B1/8QVYIWJEDBUBgNVHSAETTBLMAgGBmeBDAECATA/BgsrBgEE
AYLfEwEBATAwMC4GCCsGAQUFBwIBFiJodHRwOi8vY3BzLnJvb3QteDEubGV0c2Vu
Y3J5cHQub3JnMDwGA1UdHwQ1MDMwMaAvoC2GK2h0dHA6Ly9jcmwuaWRlbnRydXN0
LmNvbS9EU1RST09UQ0FYM0NSTC5jcmwwHQYDVR0OBBYEFBQusxe3WFbLrlAJQOYf
r52LFMLGMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjANBgkqhkiG9w0B
AQsFAAOCAQEA2UzgyfWEiDcx27sT4rP8i2tiEmxYt0l+PAK3qB8oYevO4C5z70kH
ejWEHx2taPDY/laBL21/WKZuNTYQHHPD5b1tXgHXbnL7KqC401dk5VvCadTQsvd8
S8MXjohyc9z9/G2948kLjmE6Flh9dDYrVYA9x2O+hEPGOaEOa1eePynBgPayvUfL
qjBstzLhWVQLGAkXXmNs+5ZnPBxzDJOLxhF2JIbeQAcH5H0tZrUlo5ZYyOqA7s9p
O5b85o3AM/OJ+CktFBQtfvBhcJVd9wvlwPsk+uyOy2HI7mNxKKgsBTt375teA2Tw
UdHkhVNcsAKX1H7GNNLOEADksd86wuoXvg==
-----END CERTIFICATE-----

You can confirm in ssllabs -> Certification Paths -> Select any Mozilla|Apple|Android|Java|Windows -> Path #2: Not trusted (invalid certificate [Fingerprint SHA256: 0687260331a72403d909f105e69bcf0d32e1bd2493ffc6d9206d11bcd6770739]) -> 4 In trust store
DST Root CA X3   Self-signed
Fingerprint SHA256: 0687260331a72403d909f105e69bcf0d32e1bd2493ffc6d9206d11bcd6770739
Pin SHA256: Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=
RSA 2048 bits (e 65537) / SHA1withRSA
Valid until: Thu, 30 Sep 2021 14:01:15 UTC
EXPIRED
Weak or insecure signature, but no impact on root certificate


text:
Q: Giving unique IDs to all nodes? I am making a class in Python that relates a lot of nodes and edges together. I also have other operations that can take two separate objects and merge them into a single object of the same type, and so on.
However, I need a way to give every node a unique ID for easy lookup. Is there a "proper way" to do this, or do I just have to keep an external ID variable that I increment and pass into my class methods every time I add more nodes to any object?
I also considered generating a random string for each node upon creation, but there is still a risk of collision error (even if this probability is near-zero, it still exists and seems like a design flaw, if not a longwinded overengineered way of going about it anyway).

A: If you just need a unique identifier, the built-in Python id() function would do it:

Return the "identity" of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

A: You could keep a class variable and use it for ordinal ids:
class Node(object):
    _id = 0

    def __init__(self):
        self._id = Node._id
        Node._id += 1

It also has the benefit that your class will be able to know how many objects were altogether created.
This is also way cheaper than random ids.

A: Pretty much both of your solutions are what is done in practice.
Your first solution is to just increment a number will give you uniqueness, as long as you don't overflow (with python bigintegers this isnt really a problem). The disadvantage of this approach is if you start doing concurrency you have to make sure you use locking to prevent data races when increment and reading your external value.
The other approach where you generate a random number works well in the concurrency situation. The larger number of bits you use, the less likely it is you will run into a collision. In fact you can pretty much guarantee that you won't have collisions if you use say 128-bits for your id.
An approach you can use to further guarantee you don't have collisions, is to make your unique ids something like TIMESTAMP_HASHEDMACHINENAME_PROCESSID/THREADID_UNIQUEID. Then pretty much can't have collisions unless you generate two of the same UNIQUEID on the same process/thread within 1 second. MongoDB does something like this where they just increment the UNIQUEID. I am not sure what they do in the case of an overflow (which I assume doesn't happen too often in practice). One solution might be just to wait till the next second before generating more ids.
This is probably overkill for what you are trying to do, but it is a somewhat interesting problem indeed.

A: UUID is good for this sort of thing.
>>> from uuid import uuid4
>>> uuid4().hex
'461dd72c63db4ae9a969978daadc59f0'

Universally Unique ID's have very low collision rate -- unless you are creating billions of nodes, it should do the trick.


text:
Q: Как убрать рамку из приложения Java?Используется JFrame!
Рамка между красными линиями.
Я пишу программу калькулятор и чтобы калькулятор выглядел красивее мне нужно убрать эту рамку).

Вот как выглядит таймер без рамки, мне надо добиться примерно такого же результата

A:
public class Test extends JFrame {

        Test() {
            super("No taskbar");
            setSize(200, 200);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setUndecorated(true);
            setVisible(true);
        }

    public static void main(String[] args) {
        new Test();
    }
}

Добрый день! Вы можете использовать  setUndecorated(true) при создании JFrame. Тестовый код чтобы посмотреть прикладываю. В этом случае кнопку выхода Вам придется реализовать самостоятельно.


text:
Q: XAML MSBuild task XamlMarkupCompilePass1 fails in parallel MSBuild and throws error Access denied We have several projects containing XAML UI and XAML workflow files. Since we enabled execution of MSBuild in parallel, with the flag /m the builds, from time to time we get an exception in the MSBuild task XamlMarkupCompilePass1
##[error]C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Xaml.targets(193,5): Error XC1000: XC1020: Build error occurred in the XAML MSBuild task: 'Could not load file or assembly 'file:///C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Facades\System.Threading.ThreadPool.dll' or one of its dependencies. Access is denied.

This is just an example, it is also happening sometimes on NuGet packages and not only .NET framework assemblies.
What is our setup: We have build servers and on each we have at least 2 build agents.
What did we try out already:

*

*Turning off build agents to have only one per server, still running MSBuild with /m --> failed with Access denied

*Run msbuild without /m --> was successful, but not a solution because of too long running build

*Try to use a hidden flag for MSBuild, to retry on access denied MSBUILDALWAYSRETRY --> this is only used for Copy MSBuild task and not the XAML msbuild task

Question: Is there a way to affect the MSBuild task XamlMarkupCompilePass1 somehow? or is there another solution than turning off parallel execution of MSBuild? I guess there is also a possibility that XamlMarkupCompilePass2 could fail as well but didn't see that.


text:
Q: Escaping spaces in tab-completion in a Cygwin shell subprocess on GNU Emacs on Windows I use GNU Emacs on Windows and Cygwin as my shell.  If I create a Cygwin shell subprocess with M-x shell, I get a proper bash prompt.  If I type this:
cd ~/My<tab>

it tab-completes to
cd ~/My Documents/

which is correct in Emacs/Tramp, but useless in the Cygwin bash shell subprocess, since the space has to be escaped with a backslash.
How do I get this tab-completion to automatically insert a backslash?


text:
Q: How can I recreate my Show Desktop icon on WinXP? Quick Launch became corrupted and I need to recreate everything.  I know I've done it before but I can't remember the object name: how do I recreate the Show Desktop icon?

A: Go to C:\Documents and settings\YourUserName\Application Data\Microsoft\Internet Explorer\Quick Launch and create a new text file; put the following inside:
[Shell]
Command=2
IconFile=explorer.exe,3
[Taskbar]
Command=ToggleDesktop

Save the file as "Show Desktop.scf" and you're done.

A: google is your friend.
http://www.google.com/search?hl=en&source=hp&q=how+to+recreate+the+show+desktop+icon&aq=f&oq=&aqi=g1
http://support.microsoft.com/kb/190355

A: From: http://support.microsoft.com/kb/190355
follow these instructions:
To re-create the Show desktop icon yourself, follow these steps:

*

*Click Start, click Run, type notepad
in the Open box, and then click OK.

*Carefully copy and then paste the
following text into the Notepad
window:
[Shell]
Command=2
IconFile=explorer.exe,3
[Taskbar]
Command=ToggleDesktop

*On the File menu, click Save As, and then save  the file to your desktop as "Show    desktop.scf". The Show desktop icon is created on your desktop.

*Click and then drag the Show desktop icon  to your Quick Launch toolbar.


text:
Q: OSX Toolbar for Ubuntu What do i need to install, and what settings do i need to change to have the magnify toolbar thing that OSX has in Ubuntu 9.04?
My system is running Compiz and is able to do all of the frilly UI "wow" things like cube, wobble window, etc, without any lag, so machine horsepower shouldn't be an issue.

A: Recent versions of Gnome-Do have this as well. It is called Docky, I use it on my machine and I love it. Gnome-Do's Docky feature is pretty simple, something like awn provides some more features and fancy looks more in line with OS X Leopard's dock.

A: I believe you're looking for a dock. Cairo is one of the most popular for Ubuntu, this should get you up and running!

A: What you're looking for is the Avant Window Navigator (awn) - the link has instructions for gutsy, but they should apply equally to new distributions as well!


text:
Q: Bash script to stop ssh and smbd depending on SSID My bash scripting skills are very rusty (it's been ~10 years since I scripted regularly). So, I'm probably overlooking something obvious. I am trying to get the following script to work:
#!/bin/bash

SSID=$(iwgetid -r)

if [[ $SSID = NETWORK ]]; then

if (( $(ps aux | grep [s]shd | wc -l) > 0 )); then
sudo service ssh stop

if (( $(ps aux | grep [s]mdb | wc -l) > 0 )); then
sudo service smbd stop

if (( $(ps aux | grep [n]mdb | wc -l) > 0 )); then
sudo service nmbd stop

else
echo You are not connected to NETWORK
fi
fi
fi
fi
exit 0

What it should do: If I am connected to particular network (SSID removed from script), check to see if ssh, smbd, and nmbd are running, and if so, stop them. If they aren't, do nothing. If not connected to the network, say so and exit. Bash seems to be ignoring the last 2 if...then statements, and I'm not sure why (Wrong order maybe? Conditional formatting incorrect?)
Any help would be appreciated. Also, if you have style tips, I'll take those too (like I said, I'm very rusty). I spent a few hours looking around here and Google, but couldn't find anything relevant and helpful.

A: You almost certainly meant to do this:
SSID=$(iwgetid -r)

if [[ $SSID = NETWORK ]]; then

  if (( $(ps aux | grep [s]shd | wc -l) > 0 )); then
    sudo service ssh stop
  fi

  if (( $(ps aux | grep [s]mdb | wc -l) > 0 )); then
    sudo service smbd stop
  fi

  if (( $(ps aux | grep [n]mdb | wc -l) > 0 )); then
    sudo service nmbd stop
  fi
else
  echo You are not connected to NETWORK
fi

But there is no real cost to running service stop on something which is not running, so you can simplify:
SSID=$(iwgetid -r)
if [[ $SSID = NETWORK ]]; then
  sudo service ssh stop
  sudo service smbd stop
  sudo service nmbd stop
else
  echo You are not connected to NETWORK
fi

Finally, I would recommend not using sudo inside the script. Instead, run the script itself with sudo check_ssid (or whatever it is called), so that the script ends up being:
SSID=$(iwgetid -r)
if [[ $SSID = NETWORK ]]; then
  service ssh stop
  service smbd stop
  service nmbd stop
else
  echo You are not connected to NETWORK
fi

By the way, if you really want to use ps and grep to check if a process is running, consider my answer here: How to test if a process is running with grep in bash?


text:
Q: Laravel 4 : Error in fetching photos from Flickr I am using Anahkiasen/flickering to get data from flickr in Laravel.
I am new to Laravel. See What I had did to fetching data from Flickr.
In the HomeController I made one method
public function flicker()
    {
            $apiKey = "MY API KEY";
            $apiSecret = "MY API SECRET";
            $method = Flickering::handshake($apiKey,$apiSecret);
            $result = Flickering::getResultsOf('photosets.getList', array('user_id' => '116552873@N04', 'per_page' => 20));
                echo "<pre>";print_r($result);echo "</pre>";die;
    }

This code throws this error :

A: Looking at the documentation:

To start working with Flickering, create a new instance of it like the
  example underneath. If you set your API credentials in the config
  file, you don't need to pass any arguments to the constructor as it
  will automatically fetch your key and secret key from the config
  files.

You need to create a new instance:
$flickering = new Flickering\Flickering($apiKey, $apiSecret);

So:
$method = $flickering->handshake($apiKey,$apiSecret);
$result = $flickering->getResultsOf('photosets.getList', array(
    'user_id' => '116552873@N04',
    'per_page' => 20
));

If you really want to use the Facade then:
Flickering\Facades\Flickering::handshake($apiKey, $apiSecret);

I don't recommend this way as there is no benefit in taking this route, the other option allows you to create more testable code.
You should really read the documentation: https://github.com/Anahkiasen/flickering
Edit: Add these lines to the specified configuration section in config/app.php.
providers
'Flickering\FlickeringServiceProvider'

aliases
Flickering' => 'Flickering\Facades\Flickering'

It seems that the package is creating an error when creating a new instance of the class.

Argument 1 passed to Flickering\Flickering::__construct() must be an
  instance of Illuminate\Container\Container, string given

This could be an issue with Laravel 4.1 on my part.
The Facade is working as expected though:
Flickering\Facades\Flickering::handshake("bar", "foo");


text:
Q: Drop index query is slow This is the query I'm trying to execute:
DROP INDEX id_index on table;
I've been able to drop indexes quickly in the past, but this query ran for almost an hour before I gave up on it. What could be causing this slow pace?

A: SHOW CREATE TABLE -- If it says ENGINE=MyISAM, the DROP is performed this way:

*

*Copy the entire table data over into a temp (slow due to lots of I/O)

*Rebuild all the remaining indexes (very slow, in some cases)

*Rename to replace the existing table (always fast)

This can be very slow, depending on the size of the table.  This is because of all the disk I/O.
If it says ENGINE=InnoDB, things could be better.  But it still matters whether you are DROPping the PRIMARY KEY or not.  And possibly whether the KEY is involved in a FOREIGN KEY constraint.  I assume old_alter_table is set to OFF.
http://dev.mysql.com/doc/refman/5.6/en/alter-table.html
has a lot of details.  What you needed to say was ALGORITHM=INPLACE.  You probably got ALGORITHM=DEFAULT, and I don't see in the doc what the default is.
ALGORITHM=COPY acts like I mentioned above for MyISAM.
ALGORITHM=INPLACE should take very little time, regardless of the table/index size.
(Be sure to check the details of ALTER for whichever version you are running.  There have been several significant changes in recent major versions.)


text: Q: No Sound on Ubuntu 21.04 Fresh Installation I just installed ubuntu 21.04 and there is no sound, checked sound settings, Only dummy output is there. I am using a headphone connected with rare jacks on pc.


text:
Q: Load all my.settings to textboxes in Visual Basic I am trying to load all saved my.settings to my textboxes but I am unable to retrieve the saved values. Here is my code
Dim ctrl As Control
    For Each ctrl In Me.Controls
        If (ctrl.GetType() Is GetType(TextBox)) Then
            Dim txt As TextBox = CType(ctrl, TextBox)
            For i As Integer = 1 To 20
                txt.Text = My.Settings("fp" & i)
            Next
        End If
    Next

What is the proper way to do it?Thanks

A: Generally when you reference a value stored in settings it would be along the lines of ;
My.Settings.<name of the setting>

My.Settings has an Item property which takes the Settings PropertyName (as a string ) as a parameter allowing you to either set or get the relevant value.
So to start with try the following;
Dim ctrl As Control
    For Each ctrl In Me.Controls
        If (ctrl.GetType() Is GetType(TextBox)) Then
            Dim txt As TextBox = CType(ctrl, TextBox)
            For i As Integer = 1 To 20
                txt.Text = My.Settings.Item("fp" & i.ToString)
            Next
        End If
    Next


text:
Q: Integração webservice ADVPL x SOAP Estou desenvolvendo uma integração com uma determinada prefeitura e estou tendo o seguinte retorno quando executo pelo SoapUI. Alguém poderia me ajudar?
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <s:Fault>
         <faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</faultcode>
         <faultstring xml:lang="pt-BR">Referência de cadeia de caracteres não foi definida como uma instância de cadeia de caracteres.
Nome do parâmetro: s</faultstring>
         <detail>
            <ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
               <HelpLink i:nil="true"/>
               <InnerException i:nil="true"/>
               <Message>Referência de cadeia de caracteres não foi definida como uma instância de cadeia de caracteres.
Nome do parâmetro: s</Message>
               <StackTrace><![CDATA[em System.Text.Encoding.GetBytes(String s)
   em CTIC.NFSE.Model.Implementadas.XML.WCFWebServices.ValidatorManager.ValidateByXsd(String xmlContent, List`1 listaMensagemRetorno)
   em CTIC.NFSE.Model.Implementadas.XML.WCFWebServices.ValidatorManager.ValidateLotSimplifyForm(String cpfCnpjTransmitter, String xmlDoLote)
   em CTIC.Framework.Model.Business.BOWebService.RecepcionarLoteRps(String xmlEnvio)
   em CTIC.NFSE.WebServices.NFSEServices.RecepcionarLoteRps(String xmlEnvio)
   em SyncInvokeRecepcionarLoteRps(Object , Object[] , Object[] )
   em System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   em System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
   em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
   em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)
   em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
   em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
   em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
   em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
   em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
   em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
   em System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)]]></StackTrace>
               <Type>System.ArgumentNullException</Type>
            </ExceptionDetail>
         </detail>
      </s:Fault>
   </s:Body>
</s:Envelope>

A: Resolvido.
Acrescido no parâmetro da integração: "xmlns:s=http://schemas.xmlsoap.org/soap/http"


text:
Q: NSMutableDictionary Is Still Nil After Being Instantiated And Initialized Below is the method being called every time a speaker info is received.
- (void)handleGroupingFromReceivedSpeakerInfo:(SpeakerInfo *)speakerInfo
{
    GroupInfo *groupInfo = [_IP_GroupInfo_Map objectForKey:speakerInfo.mGroupIP];

    if(groupInfo == nil)
    {
        groupInfo = [[GroupInfo alloc] init];
        groupInfo.mIP = speakerInfo.mGroupIP;
        groupInfo.isTemp = YES;

        NSLog(@"HandleGrouping: New temp group %@", groupInfo.mIP);
    }

    if(groupInfo.isTemp)
    {
        if(![groupInfo.mSpeakerIDList containsObject:[@(speakerInfo.mID) stringValue]])
        {
            [groupInfo.mSpeakerIDList addObject:[@(speakerInfo.mID) stringValue]];

            NSLog(@"HandleGrouping: added new member with id %@ temp group with ip %@", [@(speakerInfo.mID) stringValue], groupInfo.mIP);

            [_IP_GroupInfo_Map setObject:groupInfo forKey:groupInfo.mIP];
        }
    }
}

Now I'll explain a bit about what the code does.

*

*Everytime a speaker info is received, it will get the stored GroupInfo obtained with the key, speakerInfo.mGroupIP

*If groupInfo is nil then simple instantiate a new one and then add the speaker info's ID into groupInfo

*If it is not then go on and add the speakerInfo into the existing GroupInfo
Ok, here's the problem, take a look at the Log(Please don't mind other Log messages, only the one that starts with "HandleGrouping: "):
Discovered speaker with id 6494094734139439904
2015-08-28 17:41:53.756 soulbeats[13558:3307] Added speakerID: 6494094734139439904 to AllSpeakersIDList
2015-08-28 17:41:53.758 soulbeats[13558:1803] Discovered speaker with id 72243140485806144
2015-08-28 17:41:53.763 soulbeats[13558:3307] Old speaker info is null
2015-08-28 17:41:53.765 soulbeats[13558:1803] Added speakerID: 72243140485806144 to AllSpeakersIDList
2015-08-28 17:41:53.770 soulbeats[13558:3307] HandleGrouping: New temp group 239.11.11.12
2015-08-28 17:41:53.772 soulbeats[13558:1803] Old speaker info is null
2015-08-28 17:41:53.777 soulbeats[13558:3307] HandleGrouping: added new member with id 6494094734139439904 temp group with ip 239.11.11.12
2015-08-28 17:41:53.779 soulbeats[13558:1803] HandleGrouping: New temp group 239.11.11.12
2015-08-28 17:41:53.785 soulbeats[13558:3307] Discovered speaker with id 7782687177520836128
2015-08-28 17:41:53.788 soulbeats[13558:1803] HandleGrouping: added new member with id 72243140485806144 temp group with ip 239.11.11.12
2015-08-28 17:41:53.794 soulbeats[13558:3307] Added speakerID: 7782687177520836128 to AllSpeakersIDList
2015-08-28 17:41:53.802 soulbeats[13558:3307] Old speaker info is null
2015-08-28 17:41:53.807 soulbeats[13558:3307] HandleGrouping: added new member with id 7782687177520836128 temp group with ip 239.11.11.12
2015-08-28 17:41:55.711 soulbeats[13558:60b] SendBrowseCmd: browse again!!!
2015-08-28 17:41:55.719 soulbeats[13558:60b] SendBrowseCmd: refresh!!!
2015-08-28 17:41:55.721 soulbeats[13558:60b] Refresh: found one temp group with ip 239.11.11.12 with speakerIDListCount 2

As can be seen from above, the groupInfo was instantiated TWICE. You can see the log message "New temp group 239.11.11.12" appeared TWICE.
2015-08-28 17:41:53.770 soulbeats[13558:3307] HandleGrouping: New temp group 239.11.11.12
2015-08-28 17:41:53.772 soulbeats[13558:1803] Old speaker info is null
2015-08-28 17:41:53.777 soulbeats[13558:3307] HandleGrouping: added new member with id 6494094734139439904 temp group with ip 239.11.11.12
2015-08-28 17:41:53.779 soulbeats[13558:1803] HandleGrouping: New temp group 239.11.11.12

I don't understand why this is happening. I get the groupInfo object with the same key, which is the ip of the speakerInfo received, 239.11.11.12. So I am expecting that on the first call on this method, the groupInfo should be nil. But after that, since I already added a speakerInfo.mID in it and set it again to the _IP_GroupInfo_Map dictionary, groupInfo shouldn't be nil on next call of this method.
Additional information:
I declare NSMutableDictionary this way:
@property (nonatomic, strong) NSMutableDictionary *IP_GroupInfo_Map;

What can I do to solve this? Please help. Many many thanks.
--------- UPDATE: Added NSLog(@"%@", self) --------------
2015-08-28 18:41:28.497 soulbeats[13652:5d03] Discovered speaker with id 7782687177520836128
2015-08-28 18:41:28.505 soulbeats[13652:1803] <MultiroomPlay: 0x1760ba90>
2015-08-28 18:41:28.507 soulbeats[13652:3903] <MultiroomPlay: 0x1760ba90>
2015-08-28 18:41:28.508 soulbeats[13652:5d03] Added speakerID: 7782687177520836128 to AllSpeakersIDList
2015-08-28 18:41:28.516 soulbeats[13652:1803] HandleGrouping: New temp group 239.11.11.12
2015-08-28 18:41:28.518 soulbeats[13652:3903] HandleGrouping: New temp group 239.11.11.12
2015-08-28 18:41:28.519 soulbeats[13652:5d03] Old speaker info is null
2015-08-28 18:41:28.527 soulbeats[13652:1803] HandleGrouping: added new member with id 6494094734139439904 temp group with ip 239.11.11.12
2015-08-28 18:41:28.530 soulbeats[13652:3903] HandleGrouping: added new member with id 72243140485806144 temp group with ip 239.11.11.12
2015-08-28 18:41:28.531 soulbeats[13652:5d03] <MultiroomPlay: 0x1760ba90>
2015-08-28 18:41:28.543 soulbeats[13652:5d03] HandleGrouping: added new member with id 7782687177520836128 temp group with ip 239.11.11.12

As can be seen, the id is exactly the SAME.
------- ANOTHER UPDATE: Added Code On How Class Is Initialized -------
+ (MultiroomPlay *)getMultiroomPlay
{
    static MultiroomPlay *sharedMultiroomPlay;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken,
    ^{
        sharedMultiroomPlay = [[MultiroomPlay alloc] init];
    });

    return sharedMultiroomPlay;
}

- (id)init
{
    self = [super init];

    if (self)
    {
        [self openSocket];

        _allSpeakersIDList = [[NSMutableArray alloc] init];
        _allPermGroupsIDList = [[NSMutableArray alloc] init];
        _allGroupsIPList = [[NSMutableArray alloc] init];
        _allUngroupedSpeakersList = [[NSMutableArray alloc] init];
        _allUngroupedPermGroupsList = [[NSMutableArray alloc] init];
        _allTempGroupsList = [[NSMutableArray alloc] init];
        _tempGroupMemberRemoveSeqList = [[NSMutableArray alloc] init];

        _ID_TCPConnection_Map = [[NSMutableDictionary alloc] init];
        _ID_SpeakerInfo_Map = [[NSMutableDictionary alloc] init];
        _ID_PermGroupInfo_Map = [[NSMutableDictionary alloc] init];
        _IP_GroupInfo_Map = [NSMutableDictionary dictionary]; // <--Look here
        _IP_PlayerInfo_Map = [[NSMutableDictionary alloc] init];
        _IP_PlayBackTimer_Map = [[NSMutableDictionary alloc] init];
        _IP_FinishSeqNum_Map = [[NSMutableDictionary alloc] init];
    }

    return self;
}

--------- Added Log For Value Of GroupInfo ------------
2015-08-28 19:07:29.043 soulbeats[13709:3307] Discovered speaker with id 6494094734139439904
2015-08-28 19:07:29.046 soulbeats[13709:1803] Discovered speaker with id 72243140485806144
2015-08-28 19:07:29.050 soulbeats[13709:3307] Added speakerID: 6494094734139439904 to AllSpeakersIDList
2015-08-28 19:07:29.052 soulbeats[13709:1803] Added speakerID: 72243140485806144 to AllSpeakersIDList
2015-08-28 19:07:29.058 soulbeats[13709:3307] Old speaker info is null
2015-08-28 19:07:29.060 soulbeats[13709:1803] Old speaker info is null
2015-08-28 19:07:29.066 soulbeats[13709:3307] <MultiroomPlay: 0x1460e920>
2015-08-28 19:07:29.069 soulbeats[13709:1803] <MultiroomPlay: 0x1460e920>
2015-08-28 19:07:29.074 soulbeats[13709:3307] Value of Groupinfo: (null)
2015-08-28 19:07:29.076 soulbeats[13709:1803] Value of Groupinfo: (null)
2015-08-28 19:07:29.081 soulbeats[13709:3307] HandleGrouping: New temp group 239.11.11.12
2015-08-28 19:07:29.083 soulbeats[13709:1803] HandleGrouping: New temp group 239.11.11.12
2015-08-28 19:07:29.089 soulbeats[13709:3307] HandleGrouping: added new member with id 6494094734139439904 temp group with ip 239.11.11.12
2015-08-28 19:07:29.091 soulbeats[13709:1803] HandleGrouping: added new member with id 72243140485806144 temp group with ip 239.11.11.12
2015-08-28 19:07:29.098 soulbeats[13709:3307] Discovered speaker with id 7782687177520836128
2015-08-28 19:07:29.250 soulbeats[13709:3307] Added speakerID: 7782687177520836128 to AllSpeakersIDList
2015-08-28 19:07:29.332 soulbeats[13709:3307] Old speaker info is null
2015-08-28 19:07:29.380 soulbeats[13709:3307] <MultiroomPlay: 0x1460e920>
2015-08-28 19:07:29.394 soulbeats[13709:3307] Value of Groupinfo: <GroupInfo: 0x1589aad0>
2015-08-28 19:07:29.400 soulbeats[13709:3307] HandleGrouping: added new member with id 7782687177520836128 temp group with ip 239.11.11.12

A: It turns out your program is multithreaded. Surrounding your code with @synchronized and getting the expected output showed this.
The @synchronized causes the block to be executed atomically. Whereas before two threads could enter your code, both find that your dictionary was nil and both instantiate it, now the two (or more) threads each wait at the top of the synchronised block until the other(s) exit.
However, instead of just accepting "it works now", you should try and find out why is multithreaded when you didn't think it was!

(Parts of this issue were discussed in chat).

A: Add following line in an appropriate initialisation method
_IP_GroupInfo_Map = [NSMutableDictionary dictionary];


text:
Q: construct a PDA for the following language I'm studying automata and I have this problem related to PDAs
construct a PDA for the language L = {
w = x1y1x2y2….xnyn | where w belongs to {0,1}*, and the string y1y2….yn is the same as x1x2….xn except
the 1's in y come after the 0's}
For example the string 100111 belongs to L since x=101 and y=011. So
do the strings 0011, 00, 1111, 100001, etc. However, the strings 0110, 11111001, 1100, 01, 10 do not
belong to L. For simplicity, in the construction of the PDA assume the input consists of pairs of symbols
in which the first belongs to x and the second to y. Thus the input alphabet is Σ = {00, 01, 10, 11}.
I realize I have to push/pop from the stack in a way that guarantees that the same input in x appears in y where 0's come before 1's a but the problem is how to check that the 0's in y come before the 1's . a hint for the solution is really appreciated

A: Hint 1: Since the string is the in the form xyxyxy..., you will always encounter a 1 in the x part before a 1 in the y part, even if the x and y parts are the same.
Hint 2: You're matching 1s in the x part to the 1s in the y part. Push for 1s in x, pop for 1s in y.
Hint 3: Once you pop, you can't stop. (I.e., hint #2 is not enough on its own, consider a string like 100100.)


text:
Q: White spaces in the html for email design using table tags

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <meta content="width=device-width" name="viewport" />
  <title></title>

I've been trying to design an email template which has images. I use table structure to create the email with HTML and CSS. However, I see white lines between the images in different platforms. I don't have a problem in Gmail desktop, but I see white lines when opened in Gmail mobile app. How can this be fixed? I've also tried adding display: block; and font-size: 0px; but the issue still exists.

A: Try this code brother

<!doctype html>

    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Simple Transactional Email</title>

    This is preheader text. Some clients will show this text as a preview.

Hi there,

Sometimes you just want to send a simple HTML email with a simple design and clear call to action. This is it.

                                       Call To Action

This is a really simple email template. Its sole purpose is to get the recipient to click the button with no distractions.

Good luck! Hope it works.

                    Company Inc, 3 Abbey Road, San Francisco CA 94102

 Don't like these emails? Unsubscribe.

                    Powered by HTMLemail.


text:
Q: How to get max date, given in unix timestamp from hive query/pyspark I have a date column in unix timestamp as follows:
%sql select timestamp from table where date_column = 'date=2018053000' limit 5
1527688604
1527688608
1527688610
1527688612
1527688616

Now, with this query, I am able to convert to date
%sql select from_unixtime(timestamp) as timestamp2 from table where date_column = 'date=2018053000' limit 5
timestamp2

    2018-05-30 13:56:44
    2018-05-30 13:56:48
    2018-05-30 13:56:50
    2018-05-30 13:56:52
    2018-05-30 13:56:56

I want to get the max date value. I tried some stack overflow answers but none of them give me expected results.
I am trying to find both max and min dates out of my results. This is just 5 results using limit 5 but in actual I want to do on the entire result set.


text:
Q: WebGL 3D -- Spectrogram functionality I am interested in learning WebGL 3D graphics and I stumbled upon this Github repo:
https://github.com/googlecreativelab/chrome-music-lab/tree/master/spectrogram
Demo: https://musiclab.chromeexperiments.com/Spectrogram/
I am a bit overwhelmed (and very impressed) on how this was setup.
Anyway, the question I have particularly is the mic functionality: based on the audio input that the browser it receives, I am trying to figure out how I can filter certain frequency range.
At the moment, it captures all types of frequency when using the mic. But what if I want to just show the highest/lowest frequency based on how it is receiving.
I spent hours trying to reverse engineer but had no luck.
If anyone can help me pinpoint where I should look at, that would be great.
Thank you


text:
Q: Where is the mistake - they shows incorrect message I created function for my blog, but it not works correctly.
Controller:
$id_get = Model::factory('index')->get_id($slug);
$this->template->content = View::factory('index/article')
                    ->set('slug', $mysql_respnse)
        ->set('commentars', Model::factory('index')->find_commentars($id_get));

View:
    <?php
    if($commentars){
      echo 'There is a commentar!';
    }
else{
echo 'There is no any commentar!';
}
    ?>

Model:
public function get_id($slug){
    $query = DB::query(Database::SELECT, 'SELECT id FROM ieraksti WHERE slug = :slug')
            ->parameters(array(':slug' => $slug))->execute()->as_array();
}

Where is the mistake? The script shows 'There is no any commentars!', but I need 'There is a commentar'.

A: You do not return anything in the get_id() method of your model. Therefor $get_id has a value of NULL and so does $commentars.


text:
Q: How to easily port a cocos2d-html5 app to cocos2d-iphone I wrote a cocos2d-html5 app. Due to performance issues I need to port it to native cocos2d-iphone. How can I do it easily. I heard about javascript-bindings and stuff like that. I'm not sure if this is possible. What is the best way to proceed ?

A: You can use cocos2d-x with the JavaScript bindings, the API is 1-1 with cocos2d-html5: http://www.cocos2d-x.org/.
Also checkout the sample game using the JavaScript bindings on github: https://github.com/jhurt/cocos2d-x/tree/gles20/samples/MoonWarriors


text:
Q: How to convert 1e8 value to normal integer in PHP? I have integer value 4567 that I have convert it with 1e8 become 0.00004567, so my question how can I be able convert it back to 4567 in PHP ?

A: You can convert it back using number_format() e.g
using number_format($scientific, 0, '.', '');
<?php

function makeScientificNumber($number){
        $power = ($number % 10) - 1;
        return ($number / pow(10, $power)) . "e" . $power;
}

function makeNormalNumber($scientific){

    return number_format($scientific, 0, '.', '');
}

$number = 4567;
$scientific_number = makeScientificNumber($number);
echo "Scientific number is = $scientific_number";

echo PHP_EOL;

$normal_number = makeNormalNumber($scientific_number);
echo "Normal number is $normal_number";
?>

Output:
Scientific number is = 0.004567e6

Normal number is 4567

DEMO: https://3v4l.org/jpUnV


text:
Q: No Module Named Pygame Sublime Text, Python3 I keep getting an error while trying to import Pygame and Tkinter in Sublime Text.
When I look it up on Terminal it says bother are installed.
Thanks.

A: MACOS SOLUTION:

*

*on the terminal type:

*

*curl https://bootstrap.pypa.io/get-pip.py > get-pip.py (hit enter)

*after installation type:

*

*sudo pip install pygame (hit enter, enter your password and then hit enter again)

This should suffice it.
See, the way IDEs work on computers is they have their own environment integrated and the directory which the IDE is using might not be the same as the one your terminal is pointing to. By doing it this way the older versions/folders are overwritten and if there is none this installation process makes sure it's placed in an environment that is visible to most IDEs. I learned it after installing the Thonny IDE. But later on, I switched to Sublime. The only problem is the Pygame module given the fact the Tkinter is a totally integrated pre-installed library of the Python language.


text:
Q: How to populate DynamoDB for testing I'm currently looking into AWS for a project, and trying to work out how to do automated testing.
My current setup is to deploy the infrastructure at the start of the tests - I'm using Terraform so an ephemeral environment is easy. Then I'm going to run API level and UI level E2E tests against this and finally tear it all down.
For the most part this is fairly straightforward - it's not really any different to a normal monolith, just needing to deploy infrastructure first and get the addresses of it.
What I'm struggling with is setting up the data to test with. Both in terms of inserting data and removing it.
Inserting into DynamoDB (and Cognito, etc) with the AWS SDK is relatively easy, but it does mean that the test framework needs to know the names of every data store needed for the entire application. That's not a huge issue though.
Deleting from these data stores seems much harder. All the answers im seeing seems to suggest that to truncate one, you're best off actually deleting the table and recreating it. This seems to completely defeat the point of using Terraform for creating the infrastructure.
The alternative seems to be to scan for all the records and delete them one at a time, which isn't especially efficient.
Is there a better way to achieve all this? What do people normally do for this? Am I just missing something?
Cheers


text:
Q: Angle Chasing in Geometry Suppose there is an isosceles triangle ABC with $\angle$B$=20$ degrees, $AB=BC$
M,N are points on AB,BC such that $\angle$MCA=60 degrees, $\angle$ NAC=50 degrees.
Find $\angle$NMC
How do you even start? Many angles can be found by using angle sum property of the triangle but I can't get anywhere beyond that. I tried constructing a parallel through both M and N but it doesn't help.
Also, one could repeatedly use sin rule to find it out, but this is extremely inefficient.
Please give me a hint...

A: HINT
The lines $MC$ and $NA$ cross at a point I'll call $X$ in the middle of the triangle. The "vertical angle" theorem at $X$ tells you, for instance, that $MXN$ and $AXC$ are equal angles.
Can you determine the angles $BAC$ and $BCA$? Hint: isoceles.
If you draw the line $MN$, then at the point $M$, there are three angles ($BMN, NMX, XMA$) that sum to $180$ degrees, and similarly at $N$.
From those facts along, you should be able to determine the answer.


text:
Q: Refresh token for Google Storage Client I must be stupid I think. Using OAuth.
Have the following piece of code
// Authenticate with Google
        using (MemoryStream stream =
            new MemoryStream(GetSecrets()))
        {
            string credPath = "token.json";
            this.userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

Works fine and sets this.userCredential as expected
Now I want to create a StorageClient
But StorageClient cannot be created directly from UserCredential.
The only way I can see is to create from the AccessToken
GoogleCredential googleCredential = GoogleCredential.FromAccessToken(this.userCredential.Token.AccessToken);
        return StorageClient.Create(googleCredential);

Problem is this token expires after an hour.
However, in C# I cannot for the life of me find a way to pass in the refresh token (which I have in the UserCredential) and have it refresh itself as needed
It seems possible in Java though, using the .Builder
Does anyone know if this is possible ?

A: The simplest way of achieving this is to create the StorageService yourself, and then pass that to the StorageClientImpl constructor:
var service = new StorageService(new BaseClientService.Initializer
{
    HttpClientInitializer = userCredential,
    ApplicationName = StorageClientImpl.ApplicationName,
});

StorageClient client = new StorageClientImpl(service);

We might consider adding an overload of Create that takes an IConfigurableHttpClientInitializer instead of a GoogleCredential, in the future.


text:
Q: Algorithm to generate an undirected graph with path to all nodes with a maximum degree? I'm trying to generate an undirected graph in which each node has a maximum degree associated with it. That is, if a node has a maximum degree of 2, it can connect to at most two nodes (connected node would be allowed, but not 0). My problem is that I'm trying to generate a graph in which its possible to get from one node to the other. Currently, I can have nodes "randomly" connect to one other, but the problem is that its possible to create divided graphs, ie if you have 10 nodes, then sometimes inadvertently two graphs of 5 nodes each forms. If anyone knows of an efficient solution, I'd love to hear it!
EDIT: Suppose that I have a graph with ten nodes, and I specify a maximum degree of 2. In this case, here is something that would be desirable:

Whereas this is what I'm trying to avoid:

Both graphs have a maximum degree of 2 per node, but in the second image, it's not possible to select an arbitrary node and be able to get to any other arbitrary node.

A: This problem is a pretty well-known problem in graph theory, soluble in polynomial time, the name of which I forget (which is probably "find a graph given its degree sequence"). Anyhow, Király's solution is a nice way to do it, explained much better here than by me. This algorithm solves for the exact graphs that satisfy the given degree sequence, but it should be easy to modify for your more loose constraints.

A: The obvious solution would be to build it as an N-way tree -- if the maximum degree is two, you end up with a binary tree.
To make it undirected, you'll have pointers not only to the "child" nodes, but also a backward pointer to the "parent" node. At least presumably, that one doesn't count toward the degree of the node (if it does, your degree of two basically ends up as a doubly-linked linear list instead of a tree).
Edit: post-clarification, it appears that the latter really is the case. Although they're drawn different (with links going in various different directions) your first picture showing the desired result is topologically just a linear linked list. As noted above, since you want an undirected graph, it ends up as a doubly linked list.

A: It sounds like you already know what the graph should look like, so I believe if you can use a depth-first search approach. Although breath-first search can be used to avoid recursion.
For example, if you have the nodes 1-5, and k=2, then you can build a graph by starting at node 1, and then simply randomly choosing an unvisited node. Like so:
1 [Start at 1]
1-2 [expand 2, add edge(1,2) to graph]
1-2-3 [expand 3, add edge(2,3) to graph]
1-2-3-4 [expand 4, add edge(3,4) to graph]
1-2-3-4-5 [expand 5, add edge(4,5) to graph]
1-2-3-4-5-1 [expand 1, add edge(5,1) to graph] (this step may or may not be done)

If an edge is never used twice, then p paths will lead to degree p*2 overall, with the degree of the start and end nodes dependent on if the paths are really a tour. To avoid duplicate work, it is probably easier to just label of the vertices as the integers 1 through N, then create edges such that each vertex, v, connects to the vertex numbered (v+j) mod (N+1) where j and (N+1) are co-prime < N-1. The last bit making things a bit problematic, as the number of co-primes from 1 to N can be limited if N is not prime. This means solutions don't exist for certain values, at least in the form of a new Hamiltonian path/tour. However, if you ignore the co-prime aspect and simply make j be integers from 1 thru p, then go through each vertex and create the edges (instead of using the path approach), you can make all the vertices have degree k, where k is an even number >= 2. This is achievable in O(N*k), although it may be pushed back as far as O(N^2) if co-prime method is used.
Thus the path for k=4 would look like this, if started at 1, with j=2:
1 [Start at 1]
1-3 [expand 3, add edge(1,3) to graph]
1-3-5 [expand 5, add edge(3,5) to graph]
1-3-5-2 [expand 2, add edge(5,2) to graph]
1-3-5-2-4 [expand 4, add edge(2,4) to graph]
1-3-5-2-4-1 [expand 1, add edge(4,1) to graph] (this step may or may not be done)

Since |V| = 5 and k = 4, the resulting edges form a complete graph, which is expected. It's also works out since 2 and 5 are co-prime.
Obtaining an odd degree is a bit more difficult. First obtain the degree k-1, then edges are added in such a way an odd degree is obtained overall. It seems fairly easy to get very close (with one or two exceptions) to all edges being an odd degree, but it seems impossible or at least very difficult with odd number of vertices, and requires a careful selection of edges with even number of vertices. The section of which, isn't easy to put into an algorithm. However, it can be approximated by simply picking two unused vertices and creating an edge between them such that the vertices are not used twice, and the edges are not used twice.


text:
Q: Can't Use Next/Link with NextJs 13 app directory when i enable nextjs 13 appDir feature and add a Link i get and error of
" Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'call') "
in the console i also see another error
" Uncaught Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering. "
here is my code

import Link from 'next/link';

function Header() {
  return (
    <div>
      <Link href="/">Home</Link>
    </div>
  );
}

export default Header;

inside the appDir i have
layout.tsx
page.tsx
head.tsx
Header.tsx

i havnt yet changed anything in any of them expect that i added the Header component in the layout.tsx

import Header from './Header';
import '../styles/globals.css';
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <head />
      <body>
        <Header />
       {children}
      </body>
    </html>
  );
}

ONLY WHEN I AM ADDING 'LINK'
if im not using the appdir and using good old ./pages it's fine..
what's wrong here ? because i saw many tutorials and im just copying and pasting i also get the same error when adding Link


text:
Q: AG Grid React > ReactUI > Loading Bug? I'm getting an odd behavior when trying to switch my React AG Grid to use the ReactUI param as described here: https://www.ag-grid.com/react-data-grid/reactui/#js-components-inside-react-ui
When I add the following to my AgGridReact component:
reactUi

The loaders I have setup using the following don't clear after the content is loaded:
components={{
  loadingRenderer: (params) => {
    if (params.value !== undefined) {
      return params.value
    } else {
      return '<img src="https://www.ag-grid.com/example-assets/loading.gif">'
    }
  }
}}

It works as expected if I remove the reactUi param.  Here is a plunker I have setup that illustrates the problem.
https://plnkr.co/edit/D2bKgj6USnIhO1Tj
Is there an alternative approach to setting up the loader or is this a bug in AG Grid?
UPDATE: Also posted this issue here: https://github.com/ag-grid/ag-grid/issues/4771


text:
Q: LOGGER IN r, msg function in R I am a beginner in R,
While I have to edit some pre written codes in R.
there is a specific one which I cannot understand.
it would be really helpful if anyone can help me understand this.
# Logger
log.msg = function(msg){
  ## capture messages and errors to a file.
  fileConn<-file("output.txt", open = "a+")
  writeLines(c(msg), fileConn)
  close(fileConn)
}

 log.msg("Start Data extraction and merging..")

A: log.msg = function(msg){
  ## capture messages and errors to a file.

  ## create file connection in append mode (a+)
  fileConn<-file("output.txt", open = "a+")

  ## write the msg to this file
  writeLines(c(msg), fileConn)

  ## close connection
  close(fileConn)
}


text:
Q: java code style: returning specific Map implementation when generic contract is not sufficient You have method, which returns Map. Returned instance is LinkedHashMap, because of necessity of predictable iteration order. I know that code-style requests that most generic type is used as return value type, which would suggest, that java.util.Map is used. However this contract is not sufficient in the context, as the code requires the predictability of order as requisite, not just some unimportant sideeffect of implementation. So therefore I'd think, it's OK and even correct not to return java.util.Map but actual implementation java.util.LinkedHashMap as this is least specific class bearing required contract, although no LinkedHashMap specific methods are used. What do you think? What is correct and what should be used in such situation?
comment: yes, most of such usacases are just abuse of Map, and it should have been implemented as list of pairs or some similar structure. But abusing map is actually easier and "LOC-friendly". For the sake of question please assume, that it's not this kind of abuse, and Map has  true meaning here and has to be used. On the otherhand, if you know about readily available structure offering list of pairs(tuples) behavior with better than linear methods to get all i-th elements, please suggest.

A: Why not just use LinkedHashMap as the return type if this is the Map implementation that behaves as required? Everything doesn't have to be generic or always return an interface.
You said yourself:

the code requires the predictability of order as requisite, not just
  some unimportant sideeffect of implementation

In my opinion, just return LinkedHashMap

A: I'd say that your method should return a Map, since LinkedHashMap is a specific implementation, so you don't want to force your method to always return a LinkedHashMap.
Your method should state in its Javadoc that the returned Map has an iteration order which is the same as the insertion order. This way it is allowed to return any Map implementation that fulfills this contract, and not just LinkedHashMap. Even if LinkedHashMap is the only implementation currently fulfilling this contract, that doesn't have to be the case in the future, and you don't want to prevent yourself from being able to change the implementation in the future.
Of course if would have been cleaner if there was a sub-interface of Map having the "iteration order the same as insertion order" contract, in which case you would have returned that sub-interface type instead of Map.


text:
Q: Hive get mimimum of two values for where clause I am trying to write a hive query such that i need to use a date based where clause to filter on records.
WHERE date_key
BETWEEN date_sub(current_date, 4)
  AND MINIMUM(date_sub(current_date, 1), to_date("2018-10-14"))

Can we do something like MINIMUM of two values?

A: if you are using oracle then there is a keyword called "least" which will output the lesser of values.
Eg:
WHERE date_key
BETWEEN date_sub(current_date, 4)
  AND LEAST(date_sub(current_date, 1), to_date("2018-10-14"))

Otherwise you can handcraft the query to compare the two values as follows
WHERE date_key
BETWEEN date_sub(current_date, 4)
  AND (CASE WHEN date_sub(current_date, 1)< to_date("2018-10-14") THEN
                 date_sub(current_date, 1)
            ELSE to_date("2018-10-14")
        END)

A: Don't bother.  Just write:
WHERE date_key >= date_sub(current_date, 4) AND
      date_key <= date_sub(current_date, 1) AND
      date_key <= to_date('2018-10-14')

If something is less than the minimum of two values, then it is less than each of the values.


text:
Q: Exporting Resharper Inspection Results for Incoming Calls? In Resharper, Inspection Results - Incoming Calls
Is it possible to export the results to Text,Html or XML?
There is an export button with drop down for Text,Html and XML. But clicking it does not bring up the Reharper save to file to dialog.
Highlighting and pressing ctrl + C also does not copy the values.
Is this a bug in Resharper, or this feature doesn't work in in Reshaper Evaluation mode?
PS: Just notice export seems not to work for File Structure either, either I am missing a setting or this is a bug or it is not enabled for Evaluation Mode.
I have tested this on 2 separate machines, one with fresh installation on windows and VS2013, with same results.
Also pressing '+' to expand all for all the incoming calls does not cause the all the nodes to expand, still have to manually click every node, is this a common behavior for everyone or just in the evaluation mode?

A: It looks like the export issue is a bug. I've reported it here - RSRP-440597. You can log on, vote and track it.
The expand all behaviour is a little unintuitive. It's actually expanding all items that have previously been expanded, rather than expanding anything that hasn't yet been searched for. I can understand why - this could be massively slow as it recursively works out usages for all items, but it's not obvious that it works like this. There's an issue that already tracks this - RSRP-414445.


text:
Q: How to show all text on the axis for each minute slots rather than just 6am, 7am etc I've got:
axisFormat: 'h(:mm)tt',
slotMinutes: 45,
and on the left hand side, my time shows:
12am
[blank]
[blank]
[blank]
[blank]
3am
or if the default was left on for slotMinutes, it would show:
12am
[blank] - but this would really be 12:30
1am
and so on.
Is there any way I can show the blanked times? so:
12am
12:45
or
12am
12:30
1am
1:30 etc?
EDIT
apologies, shouldave posted this before. Basically, its FullCalendar from:
the fullcalendar doc site
The code I have so far is:
<script type='text/javascript'>

    $(document).ready(function() {

        $('#calendar').fullCalendar({
            defaultView: 'agendaWeek',
            selectable: true,
            selectHelper: true,
            firstDay:1,
            allDaySlot:false,// this decides if the all day slot should be showed at the top
            axisFormat: 'h(:mm)tt',
            slotMinutes: 45,
            defaultEventMinutes:45,
            select: function(start, end, allDay) {
                var title = prompt('Event Title:');
                if (title) {
                    calendar.fullCalendar('renderEvent',
                        {
                            title: title,
                            start: start,
                            end: end,
                            allDay: allDay
                        },
                        true // make the event "stick"
                    );
                }
                calendar.fullCalendar('unselect');
            },
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            editable: true,
            theme: true,
            events: "json-events.php",

            eventClick: function(event,delta) {
            alert(event.id + event.title + ' was moved ' + delta + ' days\n' +
                '(should probably update your database)');
            if (event.url) {
                $.fancybox({
                        'transitionIn': 'none',
                    'transitionOut': 'none',
                    'type': 'ajax',
                    'href': event.url
                }); }},

            eventDrop: function(event, delta) {
                alert(event.id + event.title + ' was moved ' + delta + ' days\n' +
                '(should probably update your database)');
            },
            removeEvent: function(event, delta) {
                $('#calendar').fullCalendar('removeEvents', id);
            },

            updateEvent: function(event, delta) {
                var event = $('#calendar').fullCalendar('clientEvents', id);
                event.title = title;
                $('#calendar').fullCalendar('updateEvent', event);
            },

            loading: function(bool) {
                if (bool) $('#loading').show();
                else $('#loading').hide();
            }

        });

    });

Basically, it looks like: http://arshaw.com/js/fullcalendar-1.5.1/demos/selectable.html
If you then click on the Week (top right). See how its listed as 6am, blank, 7am, blank. Im trying to make no blanks, so 6am, 6:30am, 7am etc.
EDIT 2.. Done some debugging, and the field that controls the time on the left is slotMinutes, some values work, some fail:
slotMinutes: 5 WORKS
slotMinutes: 10 WORKS
slotMinutes: 15 FAILS
slotMinutes: 20 WORKS
slotMinutes: 25 WORKS
slotMinutes: 30 FAILS
slotMinutes: 35 WORKS
slotMinutes: 40 WORKS
slotMinutes: 45 FAILS
slotMinutes: 50 WORKS
slotMinutes: 55 WORKS
slotMinutes: 60 WORKS

Any ideas??
Thanks
Thanks


text:
Q: How to get the list of records in Hibernate using Criteria Query I have three classes

*

*Category{}

*Topic{
@ManytoOne Catgoery category
@ManyToMany Questions
}

*Question{
 @ManytoMany Topic
}

So if i have to find all the questions that belong to a Category. I need to first find
1. All the Topics of the Category
2. Then find all the Questions that belong to this Category list of step 1
Can any one tell me how to write this query
I have tried many things, however could not get it right.
List<Topic> topicList = getSession()
                .createCriteria(Topic.class)
                .add(Restrictions.eq("category", new Category(id)))
                .list();

        System.out.println(">>>>>>>>>>>>>>>>>size="+topicList.size());
        return getSession().createCriteria(Question.class)
                .createAlias("topics", "topic")
                .add(Restrictions.in("topic", topicList))
                .list();

I get the following output
>>>>>>>>>>>>>>>>>size=8
org.hibernate.QueryException: could not resolve property: topic of: com.ekiras.domain.Question
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
    at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
    at org.hibernate.persister.entity.AbstractEntityPersister.getSubclassPropertyTableNumber(AbstractEntityPersister.java:1985)
    at org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:61)
    at org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1960)
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:523)
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.findColumns(CriteriaQueryTranslator.java:538)
    at org.hibernate.criterion.InExpression.toSqlString(InExpression.java:51)
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:419)
    at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:123)
    at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:92)
    at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:95)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1643)
    at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
    at com.ekiras.dao.QuestionDAO.findByCategoryId(QuestionDAO.java:35)
    at com.ekiras.service.QuestionService.findByCategory(QuestionService.java:22)
    at com.ekiras.controller.QuestionController.listCategoryQuestions(QuestionController.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)

A: I could be wrong but I think Hibernate message is pretty clear it saying your Question class does not have "topic" as filed member . Can you cross check for the name and spelling in your Question class? I say this because I dint find anything else wrong here unless we get to see entity classes and I have faced such issue and it was case with me.


text:
Q: Colision Resolution between Circles - Slow Sliding I am having trouble with circle to circle collision resolution.
First, i detect the collision, then if the balls collide, i separate them by the sum of their radii and set the velocities. That's easy.
My problem is when gravity is acting and a ball collides with another ball from above. It's suposed to bouce off but instead it slides very slowly until it drops in the ground.
Whats hapning is that afer the colision resolution, gravity pushes the ball down and causes another colision. I've tried separating the ball by the sum of their radii + x but it just slides a little faster.
You can watch the video at http://www.youtube.com/watch?v=tk7qQ9KDFp0&feature=youtu.be.
And here's the code that hadles colision:
for p in world.particle_list:

        if not p == self:

            if self.pos.sub(p.pos).get_length() <= self.radius * ppm + p.radius * ppm:

                p_mass_ratio = float(self.mass) / (self.mass + p.mass)
                self_mass_ratio = float(p.mass) / (self.mass + p.mass)

                rel_pos = p.pos.sub(self.pos)
                shift = rel_pos.set_length(- rel_pos.get_length() + self.radius * ppm + p.radius * ppm)
                p.pos = p.pos.add(shift.scale(0.50))
                self.pos = self.pos.add(shift.scale(-0.50))

                p_speed = p.speed
                self_speed = self.speed

                self.speed = p_speed.add(self.speed.norm_reflect(rel_pos.set_angle(rel_pos.get_angle() + 90).scale(-self.friction))).scale(0.50 * self_mass_ratio)
                p.speed = self_speed.add(p.speed.norm_reflect(rel_pos.set_angle(rel_pos.get_angle() + 90).scale(self.friction))).scale(0.50 * p_mass_ratio)

I made a vector class to handle this:
def dcos(x):

    return cos(radians(x))

def dsin(x):

    return sin(radians(x))

def dtan(x):

    return tan(radians(x))

class Vec(object):

    def __init__(self, x, y):

        self.x = float(x)
        self.y = float(y)

        self.length = self.get_length()
        self.angle = self.get_angle()

    def get_length(self):

        return sqrt(self.x ** 2 + self.y ** 2)

    def get_angle(self):

        return atan2(self.y, self.x) * 180 / pi

    def add(self, vec1):

        new_x = self.x + vec1.x
        new_y = self.y + vec1.y

        return Vec(new_x, new_y)

    def sub(self, vec1):

        new_x = self.x - vec1.x
        new_y = self.y - vec1.y

        return Vec(new_x, new_y)

    def scale(self, k):

        return Vec(self.x * k, self.y * k)

    def set_angle(self, a):

        new_x = self.length * dcos(a)
        new_y = self.length * dsin(a)

        if a == -90 or a == 90:

            new_x = 0

        if a == 180 or a == 0 or a == -180:

            new_y = 0

        return Vec(new_x, new_y)

    def set_length(self, l):

        new_x = l * dcos(self.angle)
        new_y = l * dsin(self.angle)

        return Vec(new_x, new_y)

    def inverse(self):

        return Vec(- self.x, - self.y)

    def norm_reflect(self, vec1):

        if self.get_angle == vec1.get_angle():

            return Vec(self.x, self.y)

        if vec1.get_angle() >= 0:

            return self.set_angle(vec1.get_angle() - self.get_angle() + 90)

    else:

        return self.set_angle(vec1.get_angle() - self.get_angle() - 90)

A: (I don't know python, but I know physics and you aren't getting other answers so I'll take a crack at it.)
Look at
if self.pos.sub(p.pos).get_length() <= self.radius * ppm + p.radius * ppm:
  ...
  rel_pos = p.pos.sub(self.pos)
  shift = rel_pos.set_length(- rel_pos.get_length() + self.radius * ppm + p.radius * ppm)
  p.pos = p.pos.add(shift.scale(0.50))
  self.pos = self.pos.add(shift.scale(-0.50))

You're setting the length to a negative number, so you're moving the objects toward each other.
The norm_reflect() function doesn't make much sense, and I suspect it does something other than what you intend (in which case you're not testing your code).
These two lines:
self.speed = p_speed.add(self.speed.norm_reflect(rel_pos.set_angle(rel_pos.get_angle() + 90).scale(-self.friction))).scale(0.50 * self_mass_ratio)
p.speed = self_speed.add(p.speed.norm_reflect(rel_pos.set_angle(rel_pos.get_angle() + 90).scale(self.friction))).scale(0.50 * p_mass_ratio)

seem to be invoking norm_reflect() with only one argument, and you're bringing friction and mass ratios into the picture before the simple case is working, and you're reusing rel_pos after multiple transformations, and the physics is non-Newtonian (i.e. wrong enough to require starting over from a blank slate).


text:
Q: Using PHP xdebug with the PHP CLI binary from MAMP I am using the PHP CLI binary of MAMP (ie. /Applications/MAMP/bin/php/php7.2.10/bin/php) to execute scripts from the Terminal. How can I use Xdebug to step thru a script that I execute this way?
So far I have read:
https://joshbuchea.com/mac-enable-xdebug-in-mamp/
Getting Xdebug Working with MAMP and Mac
which mentions how to enable xdebug but only through calling the script from a web server.
And this:
Installing Xdebug for PHP CLI
Which is on Xdebug with XAMPP which I unfortunately find difficult to extrapolate to MAMP.
Is there not a simple way like:
$ phpdebugger phpfile.php

(
Instead of
$ php phpfile.php

)
Which will just start the debugging session with the file?
If xdebug is not suitable for this, is there another program to do this?

A: *

*You can either set -dxdebug.start_with_request=yes:
php -dxdebug.start_with_request=yes you-script.php

*Or, set xdebug.start_with_request=yes in php.ini (use php --ini to find out which file that is).

*Or, you can use the trigger environment variable:
XDEBUG_TRIGGER=yes php your-script.php

A: I do not use MAMP but what I use to debug PHP CLI is
export PHP_IDE_CONFIG="serverName=your.servername.com"
php -dxdebug.client_host=xx.xx.xx.xx -dxdebug.mode=debug -dxdebug.start_with_request=yes php_command_here

and obviously, add breakpoints to your code.


text:
Q: Making Excel VBA code work for all rows I have created the statement below which which works just as I need it to with one flaw, it only works on the second row of my sheet (the first contains a header row).
How can I make it work for all rows within the sheet? The sheet has a varying number of rows in it from day to day.
Dim result As String
Adnet = Range("AB2").Value
TSNumber = Range("BQ2").Value

If (Adnet = "goog" Or Adnet = "bing" Or TSNumber = "8006522096" Or TSNumber = "8006522097" Or TSNumber = "8006522098") Then
    result = "PPC"
Else
    result = "None/Other"
End If

Range("AC2").Value = result
End Sub

A: How about:
Sub qwerty()
    Dim result As String, N As Long, i As Long
    N = Cells(Rows.Count, "AB").End(xlUp).Row
    For i = 2 To N
        Adnet = Range("AB" & i).Value
        TSNumber = Range("BQ" & i).Value
        If (Adnet = "goog" Or Adnet = "bing" Or TSNumber = "8006522096" Or TSNumber = "8006522097" Or TSNumber = "8006522098") Then
            result = "PPC"
        Else
            result = "None/Other"
        End If
        Range("AC" & i).Value = result
    Next i
End Sub


text:
Q: How to use two different database one from sql server and another from mysql server in same laravel application I am developing a laravel application. I connect my laravel application with a mysql database. But I need a table data that is in another server and that database is sql database is in IIS server.
'default' => env('DB_CONNECTION', 'mysql'),

   'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => false,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=line
DB_USERNAME=root
DB_PASSWORD=

I need help to use two databases from different server (one from mysql and another from sql) on my same laravel application.

A: In your config/database.php
 'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => false,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

// Add this (Connect sql server)
//TCP port 1433 is typically the port used by a default instance of SQL Server
'sqlsrv' => [
            'driver' => 'sqlsrv',
            'url' => env(''),
            'host' => env('DB_HOST', 'X.X.X.X'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'database_name'),
            'username' => env('DB_USERNAME', 'user'),
            'password' => env('DB_PASSWORD', 'password'),
            'charset' => 'utf8mb4',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

Get your mysql table
$mysql = DB::connection('mysql')->table('xxx')->select('*')->get();

Get your sql server table
$sqlsrv= DB::connection('sqlsrv')->table('xxx')->select('*')->get();


text:
Q: How to find file system of external hard drive? I have plugged external hard drive. It does not show in Normal Mode. I can see its Type Name and Identifier thru terminal.

*

*I want to find the file system of the external hard drive.

*I want to format the disk.

A: The easiest way to format any disk is to use Disk Utility (in /Applications/Utilities). Just start the application, select the drive to be formatted in the left column, make double sure you've selected the right one and select the file system type, partition sizes etc. on the right hand side.

A: First, it is important to be aware that technically Drives are not formatted, Volumes are. One drive can have multiple volumes, even if in practice most users just fill the whole drive with a single volume.
Normally the drive's volume(s) should appear on the desktop when you plug it in. If that were the case, you could simply hit Command+I with a volume highlighted and see its Format listed in the General section of the Info window that pops up.
Since the drive is not appearing in that case, you will need to run Disk Utility. If the drive is available there, you will see an icon and name for the drive on the left, and then below that an icon and name for each volume on the drive. Click on the volume (the indented one), not the drive, and at the bottom of the window you will see a Format field reporting the format of that volume.
Make sure that you click on the Volume, not the Drive, because as I explained at the beginning there is no format on the Drive itself.
From there you can easily reformat the drive by clicking the Drive (not the Volume) and selecting the Partition tab to the right. That brings up a tab where you can delete existing partitions, create new ones, and format them. You can treat Partition as a synonym for Volume (they're not exactly the same thing, but for your purposes they are).
All that being said, if your drive/volume is not appearing when you plug it in, it is likely that either the drive is crashed or the volume is corrupted.
In the latter case, you may see the Drive icon but not the Volume icon in Disk Utility, and you can try erasing the drive from the Erase tab and reformatting.
If you don't see either icon in Disk Utility, the drive is crashed/broken and should be replaced.
Good luck!


text:
Q: How to convert new Date() to extended JSON in mongodb aggeragate? I have following query part in a mongodb aggregate inside a project which is working perfectly in the shell and now I need to convert this in to extended JSON.
is_older_than_90days: {
$cond: {
    if : {
        $lt: ['$iso_timestamp', (new Date((new Date()).getTime() - (90 * 24 * 60 * 60 * 1000)))]
    },
then: false,
else : true
}

how to do that?


text:
Q: Smoothening Analog Input Values I made a Potentiometer testing device that reads the analog values from an MCP3008 ADC.
In order to hide the sporadic analog input fluctuations I am calculating the average of several measurements in a while loop with a function similar to the following:
def analog_average():
    analog1 = (mcp_analog)
    time.sleep(0.001)
    analog2 = (mcp_analog)
    time.sleep(0.001)
    analog3 = (mcp_analog)
    time.sleep(0.001)
    analog4 = (mcp_analog)
    time.sleep(0.001)
    analog5 = (mcp_analog)
    analog_average = ((analog1 + analog2 + analog3 + analog4 + analog5) / 5)
    print(analog_average)

mcp_analog is the value of the ADC's first analog input.
I am getting the results that I want. Is there, however, a cleaner-more efficient way?

A: Using a loop and statistics.mean:
from statistics import mean

def analog_average(N):
    measures = []
    for _ in range(N):
        measures.append(mcp_analog.value)
        time.sleep(0.001)

    return mean(measures)

print(analog_average(5))

This way you can easily change the amount of samples without having to add more and more lines of sleep and analog variables.


text:
Q: Razor autocomplete doesen't work when submitted I'm having some problem with the autocomplete on my Razor project. Everytime it returns me error/failure. Maybe it could be even a stupid thing but I'm new to ASP so it would be difficult for me to notice.
Javascript Code
 $(function () {
    $('#searchCliente').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '/Index?handler=Search',
                data: { "term": request.term },
                type: "POST",
                success: function (data) {
                    response($.map(data, function (item) {
                        return item;
                    }))
                },
                error: function (response) {
                    alert(response.responseText);
                },
                failure: function (response) {
                    alert(response.responseText);
                }
            });
        },
        select: function (e, i) {
            $("#idCliente").val(i.item.val);
            $("#idFatt").val(i.item.val);
        },
        minLength: 3
    });
});

Page Model Code
public IActionResult OnPostSearch(string term)
        {

            var clientefatt = (from cliente in this.context.Arc_Anagrafiche
                               where cliente.RagioneSociale.StartsWith(term)
                               select new
                               {
                                   label = cliente.RagioneSociale,
                                   val = cliente.IdAnag
                               }).ToList();

            return new JsonResult(clientefatt);
        }

HTML Code
<input asp-for="intervento.Cliente" class="form-control" id="searchCliente" />
<input asp-for="intervento.IdClienteFatturazione" class="form-control" id="idCliente" type="hidden" />

A: Maybe you shall assign the ajax datatype property, and also change the "type" property from post to get, as below:
            $.ajax({
            url: '/Index?handler=Search',
            data: { "term": request.term },
            datatype: 'json'
            type: "GET",
            success: function (data) {
                response($.map(data, function (item) {
                    return item;
                }))
            },
            error: function (response) {
                alert(response.responseText);
            },
            failure: function (response) {
                alert(response.responseText);
            }
        });

Also in the Model code you can try one of the following,

*

*as when returning json the JSONRequestBehavior property shall be specified as AllowGet:
return Json(new {clientefatt = clientefatt}, JsonRequestBehavior.AllowGet);

*Change the Model code method's return type to JsonResult, as below
public JsonResult OnPostSearch(string term){
 return new JsonResult(clientefatt);
}

Most probably the first options, since you're using .net core, will give you an error "ASP.NET Core - The name 'JsonRequestBehavior' does not exist in the current context"

A: Perhaps the issue is related to the AntiForgeryToken, try to add the XSRF-TOKEN property in the request header before sending the Ajax request.
Please refer to the following samples and modify your code:

*

*Add AddAntiforgery() service in the ConfigureServices method:
 services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

*In the Ajax beforeSend event, get the RequestVerificationToken from the hidden field, and set the request header:
 @page
 @model RazorPageSample.Pages.AutocompleteTestModel

 <form method="post">
     @Html.AntiForgeryToken()
     <input type="text" id="txtCustomer" name="label" />
     <input type="hidden" id="hfCustomer" name="val" />

     <input type="submit" value="Submit" asp-page-handler="Submit" />

 </form>
 @section Scripts{

     <link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />

 }

Code in the .cshtml.cs file:
    public IActionResult OnPostAutoComplete(string prefix)
    {
        var customers = new List<Customer>()
        {
            new Customer(){ ID=101, Name="Dillion"},
            new Customer(){ID=102, Name = "Tom"},
            new Customer(){ ID=103, Name="David"}
        };
        return new JsonResult(customers.Where(c=>c.Name.ToLower().StartsWith(prefix.ToLower())).Select(c=> new { label = c.Name, val = c.ID }).ToList());

    }

    public class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

Then, the screenshot as below:

Reference: jQuery AutoComplete in ASP.Net Core Razor Pages