text:
Q: Julie's guests arrived slightly earlier/ more early The task is 'Complete the sentences by changing the words in brackets into comparative adverbs'.
The sentence is 'Julie's guests arrived slightly ... (early) than she expected'.
Finally, the answer is 'earlier'. However,

*

*The BC Learn English Web site saysTwo or more syllables: Alan finished the test quickly. >   more quickly    >   most quickly. The table is attached at the end.

*'Early' consists of 2 syllables according to multiple sources including this one
Regarding these two pieces of information, the right answer should be 'more early'.
I read this thread before writing this question but it doesn't provide an answer to my question because the approved answer accepts 'speak slower' as correct -which may perfectly be, I don't have enough knowledge to judge- however; 'speak slower' is incorrect English according to the rules and guidelines listed on BC Learn English Web site -which I cited on the top- as 'slower' consists of 2 syllables.
My question is why does 'more early' is not the answer?

A: The actual rule is:

If there is only one syllable, add "er" (there are exceptions to this — more fun).

If there are two syllables, it depends on the word: early →  earlier, silly → sillier, simple → simpler, but stupid → more stupid, orange →  more orange, likely → more likely. For some adjectives, both forms are acceptable.

If there are three or more syllables, use more. I don't know of any exceptions to this.

A: A complete  description of the formation  of comparatives for  adverbs is given  in CoGEl  (A comprehensive grammar of the English laguage). (It is complete as far as it treats  the main points) The rule for adverbs is  derived from  that for adjectives.
Adjectives

(CoGEL § 7.81) Choice between inflectional and periphrastic comparison
The choice between inflectional and periphrastic comparison is largely
determined by the length of the adjective.
(a) Monosyllabic adjectives normally form their comparison by inflection:
low - lower - lowest
Real, right, wrong, and the preposition like  take only periphrastic forms:

*

*She is  more like her grandmother.
She is   liker her grandmother.
However, most other monosyllabic adjectives can take either inflectional or periphrastic comparison.
(b) Many disyllabic adjectives can also take inflections, though they have the alternative of the periphrastic forms:

*

*Her childre are politer/more polite.

*Her childre are (the) politest/(the) most polite.
Disyllabic adjectives that can most readily take inflected forms are those ending in an unstressed vowel, [syllabic l, as in "able"] or [schwa (r coloured schwa  in AmE)], eg:
-- y: early, easy, funny, happy, noisy, wealthy, pretty
-- ow: mellow, narrow, shallow
-- le: able, feeble, gentle, noble, simple
-- er, ure: clever, mature, obscure  [user LPH's addition: not"eager","proper",etc.]

Aderbs

(CoGEL § 7.83) Comparison of adverbs
(e) Adverbs that are identical in form with adjectives take
inflections: fast, hard, late, long, quick. They follow the same spelling and phonological rules as for adjectives, eg:
early - earlier - earliest

*

*You have to work harder/faster/longer.
Then-er - -est inflections cannot be added to open-class adverbs ending in -ly :

*quickly -- more quickly quicklier
               -- more quickly quickliest
When earlier is synonymous with before (that) or  previously, and when later is synonymous with after (that), they are not comparatives of the adverbs early and late.

Note  that "most
readily" in "7.81 b)" implies no unique choice and nothing  as  to  the preference between the two use, which each user of English  has to determine through experience; the following ngrams show that.

"More early" is not exactly a form that you could call wrong, but it is hardly used in comparison  to "earlier".

Although  the pages of examples  for  "more early" contain numerous occurrences, a patient examination will show that a great  many  of  those are false positives (for  instance, "more" does not modify the adjective but instead the noun it qualifies). Nevertheless, the periphrastic  form is found often enough (even  fairly recently) and it is sometimes used  to some advantage, so  that it  seems possible to say that it is not really incorrect.
(ref., 1972)... And if this was the case then , we may safely conclude , that the Unitarians were much more numerous in a more early period , as it is well known that they kept losing , and not gaining ground , for several centuries
(ref., 2003) This evening Mr Hume not quite so well , and goes to bed at a more early hour than he used to do . Ferry bridge , Sunday , 28th
(ref., 1974) .. the latter more early useful ... than they should otherwise be
(ref., 1973)  I would therefore recommend to every parent to begin the establishment of authority much more early than is commonly supposed to be possible
(ref., 2000) Open bite could even be correlated with yet inadequate growth of the jaws to accommodate the disproportionately large size of the more early - maturing tongue that must posture forward for accommodation within the oral cavity
(ref., 1807) Sometimes it happens , by badness of weather , & c . that a considerable quantity is fown the first week in december , but the more early fowings generally produce the strongest crops
(ref., 1858) The improvement is most strongly marked in the acute cases , and the more early the operation the more successful is the result obtained
(ref., 1858) but there  are causes which  operate  in promoting its more early maturity
(ref.,1958) Pyrus serotina pear require more amount of nitrogen through the growing year , more moisturous and fertile soil , to start more early and rapid growth than apple eventhough the Korean weather condition in spring season is always
In  this preceding case  the  use of the periphrastic form is quite understandable as "more" applies also to "rapid".
(ref., 1814) The sweetness of climate ad fertility of soil in Asia Minor, were favourable to a early icrease of population, and consequently to the more early organization of civil society.
This new occurrence  seems  justified by the need to make it clear that what  is meant is not  "preceding organization".


text:
Q: Send longer parameters in HTTP GET request I am trying to call an GET API where I need to pass lat,lon values
https://domainname.com/path?lat=39.0&lon=99.0&lat=23.50209&lon=78.85565&.... 1000 times
It works fine upto 300 repetation but after that it gives error saying "400 Bad Request"
I can change the API to POST method but it violates the REST API resource concept as we are getting information of lat and lon. So it should be GET.
Any suggestion on how to solve this? Shall I change it to POST or any other way of doing it?

A: First, it's a good practice to keep URLs shorter than 2,000 characters.
So, my first question would be: Is it really necessary to handle more than 300 repetitions of those parameters? Is there a way you can split the service/params?
If that's not possible (or doesn't make sense), probably using a POST works for you. Don't be afraid of violating rules, but do not violate them without a good reason.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get Name value using ID From another table (sql server) I have two tables
Table1 ID: 10001 Name: JM
Table2 ID:       Name:

I make an relationship to relationship the ID to table1 and table2
table1 as primary and table2 as Foreign key
I'm using QR code scanner to insert data to table2 . when I scan the QR code with value of 10001 it will automatically saved the ID : 10001 to the table2 , then if i scan the ID not in the list it will give an error because of the relationship .
Here is my sql code:
  command.CommandText = " INSERT INTO Table2 (ID,Name) VALUES (@id,@name);";
            command.Parameters.AddWithValue("@id", decoded_text);
  command.Parameters.AddWithValue("@name", decoded_text);

Now, if i scan the 10001 ID . i want to automatically saved the Name "JM" also to the table2 .
Hope someone understand my point

A: you should create a new field in database table that you want to add JM in it.
then you can use insert Query for insert data.
if possible please send your database tables structure in this post.
thanks.


text:
Q: Annotating quantikz circuit I'm trying to annotate certain parts of my quantikz circuit and drawing boxes around some gates:
\documentclass{article}
\usepackage{graphicx}
\usepackage{amssymb,amsfonts,dsfont}
\usepackage{tikz}
\usetikzlibrary{quantikz}

\begin{document}

\begin{quantikz}[row sep={20pt,between origins},column sep=.2cm,font=\small]
\lstick{\ket{0}} & \qw & \qw & \qw & \qw & \qw &[1cm] \qw & \qw \\
\lstick{\ket{0}} & \qw & \qw\qwbundle{} & \qw & \qw & \qw &[1cm] \qw & \gate[3]{U_2} \\
\lstick{\ket{0}} & \qw & \qw\qwbundle{} & \qw & \qw & \qw &[1cm] \qw & \qw \\
\lstick{\ket{0}} & \qw & \qwbundle{} & \gate{H}\gategroup[wires=2,steps=3,style={dashed,rounded corners,fill=white,inner xsep=2pt},background]{mylabel}  & \ctrl{1} & \gate{U_1} &[1cm] \qw & \qw \\
\lstick{\ket{b}} & \qw & \qw\qwbundle{} & \qw & \gate{Z} & \qw &[1cm] \qw & \qw \\
\end{quantikz}

\end{document}

and I want it to look like:

I read the quantikz docs and adapted the gategroup examples on p. 13, but I get an error that I don't understand: l.76 I think the culprit is a tikzcd arrow in cell 5-8. \errmessage ...currentrow -\tikzcd@currentcolumn }

A:
I think it is better to try to do the drawing directly, without specialized libraries.  I suggest the solution below which is based on the fit command to group nodes in a rectangle.
The code
\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{fit, math}

\begin{document}

\newcommand{\ket}[1]{$|#1\rangle$}
\tikzset{%
  box/.style={draw, fill=white,
    minimum width=2em, minimum height=4ex,
    inner sep=1ex, outer sep=.2ex%
  },
    hbox/.style={draw, fill=white,
    minimum width=2em, minimum height=#1 ex,
    inner sep=1ex, outer sep=.2ex%
  },
  dot/.style={circle, fill=black, minimum size=1ex,
    inner sep=0pt, outer sep=2pt}
}
\begin{tikzpicture}[evaluate={real \a, \posl; \a=6; \posl=.75;}]
  \draw (0, 1) node {\ket{0}} ++(.5, 0) -- ++(.5, 0) -- ++(\a, 0);
  \draw (0, 0) node {\ket{0}} ++(.5, 0) -- ++(.5, 0) node {$/$} -- ++(\a, 0);
  \draw (0, -1) node {\ket{0}} ++(.5, 0) -- ++(.5, 0) node {$/$} -- ++(\a, 0)
  coordinate (U1);
  \draw (0, -2) node {\ket{0}} ++(.5, 0) -- ++(.5, 0) node {$/$} -- ++(\a, 0)
  node[pos=.15, box] (H) {$H$} node[pos=.3, dot] {} node[pos=.45, box] (U) {$U_1$}
  node[pos=\posl, red, above] (a) {\ket{a}};
  \draw (0, -3) node {\ket{b}} ++(.5, 0) -- ++(.5, 0) node {$/$} -- ++(\a, 0)
  node[pos=.3, box] (Z) {$Z$}
  node[pos=\posl, blue, above] (b) {$\beta$\/\ket{b}}
  node[pos=\posl, blue, below=1ex] (ab) {$\beta\,${\color{red}\ket{a}}\ket{b}};

  \path node[draw, dashed, fit={(H) (U) (Z)}, inner sep=1.5ex,
  label={270: my label}] {}
  node[fill=gray, opacity=.15, fit={(a) (b)}, inner sep=.5ex] {};
  \path (U1) node[hbox=15] {$U_1$};
\end{tikzpicture}
\end{document}

A: The problem is that you put \\ at the end of the last line of the circuit.
Furthermore some small changes to the gategroup regarding positioning of the label and size of the box.
\documentclass{article}
\usepackage{graphicx}
\usepackage{amssymb,amsfonts,dsfont}
\usepackage{tikz}
\usetikzlibrary{quantikz}

\begin{document}

\begin{quantikz}[row sep={20pt,between origins},column sep=.2cm,font=\small]
\lstick{\ket{0}} & \qw & \qw & \qw & \qw & \qw &[1cm] \qw & \qw \\
\lstick{\ket{0}} & \qw & \qw\qwbundle{} & \qw & \qw & \qw &[1cm] \qw & \gate[3]{U_2} \\
\lstick{\ket{0}} & \qw & \qw\qwbundle{} & \qw & \qw & \qw &[1cm] \qw & \qw \\
\lstick{\ket{0}} & \qw & \qwbundle{} & \gate{H}\gategroup[wires=2,steps=3,style={dashed,rounded corners,fill=white,inner xsep=0pt},background,label style={label position=below,anchor=
north,yshift=-0.2cm}]{mylabel}  & \ctrl{1} & \gate{U_1} &[1cm] \qw & \qw \\
\lstick{\ket{b}} & \qw & \qw\qwbundle{} & \qw & \gate{Z} & \qw &[1cm] \qw & \qw
\end{quantikz}

\end{document}


text:
Q: How to connect to a server in Windows Command Line (or Powershell) without netcat What is the command in Cmd or Powershell in Windows to create a connect to server and port? In Linux it's nc [host] [port] but in Windows there's no netcat to do this task.

A: You'd typically want to use:
Enter-PSSession -Computername HOSTNAME

Beware that there are some requirements to do this.
Running winrm qc on the host usually solves the most problems.
See full info on Enter-PSSession.


text:
Q: No metrics in Graphite I have been at this for eight hours now, and nothing seems to work. I am not receiving any metrics in my Graphite installation. I am using Grafana to display the data, and it works like a charm, only that the data from Graphite is empty.
Response:
[]

I have tried everything I can think of, and as far as I understand, Collectd can send the data properly to Carbon as I get the following when I restart Collectd:
/var/log/carbon/listener.log
11/02/2016 22:47:45 :: MetricLineReceiver connection with 127.0.0.1:51926 closed cleanly
11/02/2016 22:47:47 :: MetricLineReceiver connection with 127.0.0.1:51927 established

I am running a VPS on Ubuntu 14.04.2 LTS.
Where can I start troubleshooting? Grafana works and Collectd works, as far as I can tell, but Graphite refuses to show any metrics.
Thank you.


text:
Q: My internet speed is 100 Mbps but my download speed is only 250 kbps Why? I live in Denmark in the city of Fredensborg, my internet is living its own life, sometimes it has a download speed of 250 Kbps and sometimes it's 750 Kbps, it doesn't matter if I turn all my pcs and iphones off, it doesn't change my internet speed at all.
Speedtest.net says that i have a download speed of 2.5 bits per sec. im using ADSL

A: 100 Mbps is the maximum speed your LAN can support.
Your internet speed is 250 Kbps ( or max 750 kbps).
Regarding internet speed, you can test on websites like speedtest.net
Do remember that LAN and internet speed are two different things.
Following links may be helpful :

*

*Link 1

*Link 2

*Link 3

A: The Internet speed also depends on server speed. If you downloading from the server that is shared among multiple users on the web. and the speed will be decreased for no of users increased..
For example. Torrent download speed depends on no of peers it has. here peers act as servers

A: Well i predict that you are talking about the speed that is shown in the notification area when you are connected with network. Its actually the maximum speed your LAN can support. Further you need to specify what kind of connection you are using. What Internet Tariff plan is it.
You may check your download speed on www.speedcheck.net and other contributors have already cleared many doubts.


text:
Q: WordPress global $post variable is empty I'm working on a wordpress plugin(managing background image), when I try to use
global $post;
print_r($post);

the object is empty.
Probably there is some required data (I dont know what.)
Please help me if you know.

A: The WordPress global variable $post contains the data of the current Post within the The Loop.
This means that WordPress will assign a value to this variable in each loop iteration. Consecuently, if you're trying to access $post from anywhere in your code outside the WP loop, it will be of course empty...


text:
Q: iOS MapKit userlocation without initializing the map Is it possible to get the users current location, using MapKit or something else, without using the map?
Say I just wanted to show the user their current lat/lng, but without the map. When they move the lat/lng updates.

A: This is exactly the purpose of CoreLocation.framework.
At this address http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html you can find some nice information on how to get the user's location or you can google "CoreLocation" and find a lot of tutorial.

A: You may find my handler helpful.
https://github.com/dsdavids/TTLocationHandler


text:
Q: What are hypothetical indexes? Does anybody know what hypothetical indexes are used for in sql server 2000?  I have a table with 15+ such indexes, but have no idea what they were created for.  Can they slow down deletes/inserts?

A: hypothetical indexes are usually created when you run index tuning wizard, and are suggestions, under normal circumstances they will be removed if the wizard runs OK.
If some are left around they can cause some issues, see this link for ways to remove them.

A: Not sure about 2000, but in 2005 hypothetical indexes and database objects in general are objects created by DTA (Database Tuning Advisor)
You can check if an index is hypothetical by running this query:
SELECT  *
FROM    sys.indexes
WHERE   is_hypothetical = 1

If you have given the tuning advisor good information on which to base it's indexing strategy, then I would say to generally trust its results, but if you should of course examine how it has allocated these before you trust it blindly. Every situation will be different.

A: A google search for "sql server hypothetical indexes" returned the following article as the first result. Quote:

Hypothetical indexes and database objects in general are simply objects created by DTA (Database Tuning Advisor)

A: Hypothetical indexes are those generated by the Database Tuning Advisor.  Generally speaking, having too many indexes is not a great idea and you should examine your query plans to prune those which are not being used.

A: From sys.indexes:
is_hypothetical     bit

1 = Index is hypothetical and cannot be used directly as a data access path.
    Hypothetical indexes hold column-level statistics.

0 = Index is not hypothetical.

They could be also created manually with undocumented WITH STATISTICS_ONLY:
CREATE TABLE tab(id INT PRIMARY KEY, i INT);

CREATE INDEX MyHypIndex ON tab(i) WITH STATISTICS_ONLY = 0;
/* 0 - withoud statistics -1 - generate statistics */

SELECT name, is_hypothetical
FROM sys.indexes
WHERE object_id = OBJECT_ID('tab');

db<>fiddle demo


text:
Q: remove entry from array with value = NULL
Possible Duplicate:
remove element from array based on its value?

I have this array
$arr = array(
 'key1'=>'value1',
 'key2'=>NULL,
 'key3'=>'value2'
);

if I do implode(',',$arr); I get: value1,,value2 (notice the empty space)
Is there a way to skip that NULL values? To get something like this:
value1,value2
I could traverse all the array and unset manually the key where the value is NULL, but it's a bit an overkill doens't it?
Edit:
To save time Maybe I could do just one loop to iterate over the array, and in the same loop I check for null values and if isn't null I append it the ','
like this:
foreach($arr as $k=>$v) {
  if ($v !== NULL) {
   echo $v.',';
  }
}

The problem here is that I have a final ',' at the end.
Edit
As gordon asked, it ran this test (1000000 iterations)
First using array_filter:
$pairsCache = array('key1'=>'value1','key2'=>NULL,'key3'=>'value3',
                    'key4'=>'value4','key5'=>'value5');

for($i=0;$i<1000000;$i++) {

    $query = "INSERT INTO tbl (";
    $keys='';
    $values='';

    $pairs = array_filter($pairsCache,function($v){return $v !== NULL;});

    $keys = array_keys($pairs);

    //> keys
    $query .= implode(',',$keys ) . ") VALUES ( '";

    //> values
    $query .= implode("','",$pairs) . "')";
}

Time: 7.5949399471283
Query: "INSERT INTO tbl (key1,key3,key4,key5) VALUES ( 'value1','value3','value4','value5')"
Second using only one loop:
for($i=0;$i<1000000;$i++) {

    $query = "INSERT INTO tbl (";
    $keys='';
    $values='';

    foreach($pairsCache as $k=>$v) {
        if ($v!==NULL) {

            $keys .= $k.',';
            $values .= "'{$v}',";
        }
     }

    $keys=rtrim($keys,',');
    $values=rtrim($values,',');

    $query = $query . $keys . ') VALUES ( ' . $values . ')';

 }

Time: 4.1640941333771
Query: INSERT INTO tbl (key1,key3,key4,key5,) VALUES ( 'value1','value3','value4','value5')

A: $arr = array_filter($arr);

array_filter() removes every value, that evaluates to false from $arr.
If you need finer control, you can pass a callback as second argument
arr = array_filter($arr, function ($item) { return !is_null($item);});

At last of course you can iterate over the array yourself
foreach (array_keys($arr) $key) {
  if (is_null($arr[$key])) unset($arr[$key]);
}

Note, that there is no downside, if you filter and output in two separate steps

A: You can use array_filter():
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
implode(',', array_filter($arr));

A: You can simply use bellow code.
Edited.
function nullFilter($val)
{
    return $val !== NULL;
}
$arr = array( 'key1'=>'value1', 'key2'=>NULL, 'key3'=>'value2' );

$filteredArray = array_filter($arr,"nullFilter");

echo implode(',', $filteredArray);

Cheers!
Prasad.

A: There is no possibility to do this using only implode().
You can traverse all the array (as you said) maybe in a wrapper my_implode() function, or you can use something less elegant such as:
trim(preg_replace('/[,]+/', ',', implode(',', $arr)), ',');


text:
Q: Using type -t command in linux c.? I use popen to execute type -t type , this give me an error message -t not found. When I perform type -t type in the shell this gives me builtin. Why doesn't this work with popen?

A: POSIX specifies that the shell used with popen is /bin/sh. Your interactive shell is probably bash. The behaviour of the type command is different for sh and bash. sh does not support -t.
Your system probably has /bin/sh symbolically linked to /bin/dash, but that's just an implementation detail.
If you need bash behaviour, run bash explicitly:
   popen("/bin/bash -c 'type -t type'", "r")

Live demo.


text:
Q: Uploading Django Development to Dreamhost/Passenger first time "Could no import" I've been developing on my laptop.
Now, I've uploaded my development project from Django 1.2/Python 2.7 up to Dreamhost created using the Passenger setup.  I am using South for migration.
I modified settings.py to access MySQL.  Got Admin working.
Questions:
1) Where is the std out shown when you hit the site? (all my print statements)
2) I had to add
from decimal import Decimal

to get the settings.py to run.
Now, hitting the server gives me a 500.  When I go to the commandline and try any manage.py command I'm getting:
Error: Could not import settings 'pholdershare.settings' (Is it on sys.path? Does it have syntax errors?): No module named settings
I modified the permissions for my folder to 755 but that didn't change anything.
3) Regarding development to testing to live, I'm totally unclear on how to do this.  I want to have a nice solid system for development where I can do releases but I've never done that.  I have been using GIT locally.  Can anybody point me to the tutorial on setting up the release system?
Suggestions?
Thanks much!

A: "Could not import settings 'pholdershare.settings'"
...usually means either settings.py has an import error or syntax error, or pholdershare has not been added to sys.path in your wsgi.py


text:
Q: Can someone help me replace the **for loop** to **while loop** I'm struggling to figure it out? Can someone help me replace the for loop to while loop I'm struggling to figure it out?
The question specifically asks us not to use for loop. That's why I need to replace it with the while loop
I have listed below:

*

*my code

*Sample testing of the input and the output

*the conditions we have to follow:

 def matrix_equal(matrix1, matrix2):
    """
    -------------------------------------------------------
    Compares two matrices to see if they are equal - i.e. have the
    same contents in the same locations.
    Use: equal = matrix_equal(matrix1, matrix2)
    -------------------------------------------------------
    Parameters:
        matrix1 - the first matrix (2D list of ?)
        matrix2 - the second matrix (2D list of ?)
    Returns:
        equal - True if matrix1 and matrix2 are equal,
            False otherwise (boolean)
    ------------------------------------------------------
    """
    equal = True
    if((len(matrix1) != len(matrix2)) or (len(matrix1[0]) != len(matrix2[0]))):
        equal = False
    for x in range(len(matrix1)):
        if(equal == False):
            break
        for y in range(len(matrix1[0])):
            num1 = matrix1[x][y]
            num2 = matrix2[x][y]
            if(num1 != num2):
                equal = False
                break
    return equal

Sample testing:
First matrix:
      0    1    2
 0    c    a    t
 1    d    o    g
 2    b    i    g

Second matrix:
      0    1    2
 0    c    a    t
 1    d    o    g
 2    b    i    g

Equal matrices: True

The conditions we have to follow:
1. should not call input in the function
2. should not call print in the function
3. should not have multiple returns

A: This should solve your problem, this is a solution using while loop :
def matrix_equal(mat1,mat2):
  equal = True
  if(len(mat1[0]) == len(mat2[0]) and len(mat1) == len(mat2)):
    i = 0
    n = len(mat1[0])
    m = len(mat1)
    while(i < m):
      j = 0
      while(j < n):
        if(mat1[i][j] != mat2[i][j]):
          equal = False
          break
        j+=1
      if(equal==False):
        break
      i+=1
  else:
        equal = False
  return equal

A: Change
for x in range(len(matrix1)):

to
x = 0
while x < len(matrix1):
    x += 1

Cheers!

A: You can transform :
for i in range(mat.shape[0]):
  {do stuff...}

into
i = 0
while i < mat.shape[0]:
  {do stuff...}
  # increment i with 1
  i += 1

so here you would get :
def mat_eq_while(matrix1, matrix2):
  i = 0
  j = 0
  equal = True
  if(not (mat1.shape == mat2.shape) ):
      equal = False
  while i < mat1.shape[0]:
      if(equal == False):
          break
      while j < mat1.shape[1]:
          num1 = matrix1[i, j]
          num2 = matrix2[i, j]
          if(num1 != num2):
              equal = False
              break
          j += 1
      i += 1
  return equal

test it with
import numpy as np
mat1 = np.matrix(range(9)).reshape(3,3)
mat2 = np.matrix(range(1, 10)).reshape(3,3)

print( mat_eq_while(mat1, mat1) )
print( mat_eq_while(mat1, mat2) )


text:
Q: Mysql ERROR 1215 (HY000): Cannot add foreign key constraint state_id I am currently attempting to learn mysql and I am on the section of referencing foreign keys but cannot seem to get it to accept it.
What am I missing? Hope you can help :)
mysql> create table states (
    -> id tinyint(3) not null primary key auto_increment,
    -> name varchar(255));
Query OK, 0 rows affected (0.02 sec)

mysql> create table customers (
    -> id integer(10) not null auto_increment primary key,
    -> name varchar(255) not null,
    -> email varchar(255) not null,
    -> states_id tinyint unsigned not null,
    -> foreign key(states_id) references states(id) on update cascade);
ERROR 1215 (HY000): Cannot add foreign key constraint

A: Columns related through foreign keys need to have the same data type.  The id is TINYTINT(3) but states_id is TINYTINT UNSIGNED.
Redefine your definition of states and try it again.


text:
Q: How to make double click event into single click event in angular 4? I have click event in span.While clicking the span icon, it downloads the appropriate file.If I click double time, it's downloads two times.Any solution for this.
Html:
     <ng-template #tmplt>

        {{isEnglish ? kbase.Name :kbase.Name_AR}}

</ng-template>

Method:
  download(id: number) {
        if (id != 0) {
            this._documentService.downloadDcoumentDetails(id, 'KnowledgeHub').subscribe(
                (response: any) => {
                    if (response.content != null) {
                        this.performDownloadFile(response.fileName, response.content);
                    }
                }, err => { }, () => {

                });
        }

    }
    performDownloadFile(fileName: string, content: any) {
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style.display = "none";
        let blob = new Blob([content], { type: "application/octet-stream" });
        let objectUrl = window.URL.createObjectURL(blob);
        a.href = objectUrl;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(objectUrl);
    }

Thanks

.

A: Welcome to the Observable's world. Just use Observable to get the desired result. Get the reference of your input in the component and use this code. debounceTime will let the event to trigger at least after 1 second from the previous trigger. It will let you not to fire on every click when user double clicks.
Observable.fromEvent(yourButton, 'click').debounceTime(1000).subscribe(value => /* */)

Select your target button with @viewchild() or something like that

In the subscribe method you can write your logic.

A: Add a boolean to the function download(id) like so:
var clicked = false;

function download(id) {
    if(!clicked){
        clicked = true;
        service.get(url).subscribe(function(data){
            clicked = false;
        });
    }
}

This will prevent a double click while the current download is still being performed.

A: You should create a variable to control whether there's a download already running or not.
Something like this:
public downloadInProgress = false;

public download(id: string) {
  if (this.downloadInProgress) {
    return;
  }

  this.downloadInProgress = true;
}

```
Then, once you receive the file from your API/Server you can assign false to this flag.


text:
Q: How do i unset row result when str_split characters is not upto required In my mysql database table called promo, I have msg, price and qty in column code row in the column are as example
code | msg          |  price  | qty
180  | weallwinthem |  150    | 7
180  | yeswellhappy |  520    | 15
180  | wearerunning |  100    | 10

How do I unset a row result of qty if the required msg str_split is not upto qty required?
E:g2
if msg split is we, al, lw, in, th, em and qty is 7 unset qty to 6
example3
we, al, lw, in, th, em qty 6 i have tried:
$sql = mysqli_query($conn, "SELECT * FROM promo WHERE code='180' LIMIT 1");
while($row = mysqli_fetch_array($sql)) {
    $msg = $row["msg"];
    $qty = $row["qty"];
    $disp = str_split($msg, 2);
    for($b = 0; $b < 2; $b++) {
        if(strlen($disp[$b]) != $qty) {
            unset($qty[$b]);
            $amt += ($row["price"] * $qty);
            $so = "uncompleted";

        } else {

            $so = "$disp[$b]";
            echo "','$so $amt";
        }
    }

thanks for reading and impact in my solutions

A:
if msg split is we, al, lw, in, th, em and qty is 7 unset qty to 6

As far as I understood from your second example:
We can write a function that "calculate" the right Qty according the the msg.

*

*Split the message

*Count the amount of spliced words

*This should be the new Qty. (return it)

function getDesiredQtyBySplit($msg){
   $split = str_split($msg, 2);
   $count = count($split);
   return $count;
}

For each row will run this function, if the row's Qty is the desiredQty - no need to take any action, otherwise, we should update the row's Qty column.
$sql = mysqli_query($conn, "SELECT * FROM promo WHERE code='180' LIMIT 1");
while($row = mysqli_fetch_array($sql)) {
    $msg = $row["msg"];
    $qty = $row["qty"];
    $desiredQty = getDesiredQtyBySplit($msg);
    if($desiredQty != $qty){
       //Using mysqli, UPDATE qty so it would be $desiredQty
       //Make sure that your condition (WHERE) related to this specific row.
      //Usually there's a "Primary Key" (for instance: id) which is has a unique value.
    }
}


text:
Q: Stripe ephemeral key I am following this tutorial to add stripe to my android firebase app. The tutorial is asking me to "create a new user or account on your server, create a corresponding Customer object at the same time, even if you don't collect payment information from your users when they sign up. This ensures that your application has a matching Customer for each user." How do I create this Customer Object?

A: You can create customer in Stripe for your app users (after registration or before payment) using server-side codes as mentioned here create customer


text:
Q: Scale design for iPad Pro I'm developing an app for the iPad. When installed on the iPad pro, the layout elements are all too tiny. Since the iPad pro is the same proportion as the older iPads, is there a way to simply scale everything up and include @3x assets?
I'm also a bit confused that the size classes are the same as well. I have a button that is 200 x 200 pixels on the iPad Retina (perfect) too small on the iPad pro.
Thank you for your time.

A: I found a solution by following a few steps:

*

*made my subview 1:1 aspect ratio to itself

*added a background view that had left/top/right/bottom constraints set to 0

*added an aspect ratio constraint to the background and the button

The above sizes the button properly for both devices but the position was off

*

*for x/y placement, I added 2 constraints to the superview (center vertically and center horizontally)

*Using multipliers in InterfaceBuilder I was able to position the button properly

Hope this helps someone who runs into the same issue


text:
Q: Pointer in C++ - Need explanation how it works http://www.codeproject.com/KB/IP/SocketFileTransfer.aspx?artkw=socket%20send%20a%20file
I don't clearly understand this line :
// get the file's size first
cbLeftToReceive = sizeof( dataLength );

do
{
    BYTE* bp = (BYTE*)(&dataLength) + sizeof(dataLength) - cbLeftToReceive;
    cbBytesRet = sockClient.Receive( bp, cbLeftToReceive );

    // test for errors and get out if they occurred

    if ( cbBytesRet == SOCKET_ERROR || cbBytesRet == 0 )
    {
        int iErr = ::GetLastError();
        TRACE( "GetFileFromRemoteSite returned
          a socket error while getting file length\n"
          "\tNumber of Bytes received (zero means connection was closed) = %d\n"
          "\tGetLastError = %d\n", cbBytesRet, iErr );

        /* you should handle the error here */

        bRet = FALSE;
        goto PreReturnCleanup;
    }

    // good data was retrieved, so accumulate

    // it with already-received data

    cbLeftToReceive -= cbBytesRet;

}
while ( cbLeftToReceive > 0 );

I want to know how get it get size of the file to dataLength :)
This line : BYTE* bp = (BYTE*)(&dataLength) + sizeof(dataLength) - cbLeftToReceive; does it right that bp is a byte pointer of dataLength addr but what + sizeof(dataLength) - cbLeftToReceive mean ?
I don't think the file is that small : 4 bytes, just onc Receive how can they receive dataLength and data ? Does it send dataLength first and data after ?

A: Oh.  The funny array arithmetic.  The idea is to count from the end, so that when you reach the end you know you're done.  In pieces:
 1. Find the address of dataLength (BYTE*)(&dataLength)
 2. Skip to the end of dataLength + sizeof(dataLength)
 3. Back up by the number of bytes we expect to receive - cbLeftToReceive
This is where we are writing the bytes we get from the network.
As we get bytes from the network, we reduce cbLeftToReceive (cbLeftToReceive -= cbBytesRet;) and continue trying to receive bytes until we are done.  So every time through the loop, bp points to where we need to write the next bytes we Receive().
EDIT:
So now that we know how many bytes we're going to get, how to we receive them without potentially filling all of RAM with hunks of the data?  We get a buffer, repeatedly fill it, and flush that buffer to disk whenever it's not empty.  When there's still a lot of data (more than a buffer) left to receive, we try to Receive() a fill buffer.  When there's less than a full buffer to go, we only request to the end of the file.

  iiGet = (cbLeftToReceive<RECV_BUFFER_SIZE) ?
                      cbLeftToReceive : RECV_BUFFER_SIZE ;
  iiRecd = sockClient.Receive( recdData, iiGet );

The we catch and handle errors.  If there was no error, write however many bytes we got and reduce the number of bytes we expect to receive by the number we got.

  destFile.Write( recdData, iiRecd); // Write it
  cbLeftToReceive -= iiRecd;

If we're still not done receiving bytes, go back to the top and keep going.

  while ( cbLeftToReceive > 0 );

General advice:
It's good to practice reading code where you don't pay too much attention to the error handling and exception handling code.  Typically what's left is much easier to understand.

A: He/She means that he sets aside the size of int in the start of the buffer, where the size of the file will be placed (it will be later read from the socket)


text:
Q: Jquery - Ajax - display submit button after loading image?    $.ajax({
            type:"GET",
            url:"<?php echo Yii::app()->request->baseUrl; ?>/admin/"+urlPage+"?t=ajax&img="+$("#image_name").val()+"&w="+
                thumb_width+"&h="+thumb_height+"&x1="+x_axis+"&y1="+y_axis,
            cache:false,

            success:function(rsponse)
            {
                $("#cropimage1").hide();
                $("#thumbs1").html("");
                if(th_size == '1'){
                $("#thumbs").html("<img src='<?php echo Yii::app()->request->baseUrl; ?>/upload/temporary/thumb/"+rsponse+"?version="+Math.ceil(Math.random()*100)*10+"' /><input type='button' class='save-btn' onclick='refresh();' name='save' value='<?php echo Yii::t(Yii::app()->session["translator"], "Save and continue");?>'>");
               $('html, body').animate({ scrollTop: $('#thumbs').offset().top }, 'slow');
                document.getElementById("small_image").value =rsponse;
               //alert(document.getElementById("small_image").value)
                }

    }

Here am loading a div id "thumbs" dynamically on response from ajax call.Inside this thumbs div there is  an image and submit button .. The issue is that the submit button loads quickly but if the image is heavy its taking time to load. How can i make submit button  to load after image .. Any Help appreciated ?

A: You can use .onload of image object.
The code would be like below:
var img = new Image();
img.onload = function(){
    $("#thumbs").append(img).append("<input type='button' class='save-btn' onclick='refresh();' name='save' value='<?php echo Yii::t(Yii::app()->session["translator"], "Save and continue");?>'>");
};
img.src = '<?php echo Yii::app()->request->baseUrl; ?>/upload/temporary/thumb/"+rsponse+"?version="+Math.ceil(Math.random()*100)*10+"';

I don't run this code, if any error please point it out because of the value which contains php code.
But setting src and onload is exactly used like this.
Here is a simple jsfiddle. http://jsfiddle.net/U7nYb/2/

A: Here is my suggestion, I use jQuery throughout instead of mixing things
$.ajax({
  type:"GET",
  url:"<?php echo Yii::app()->request->baseUrl; ?>/admin/"+urlPage+"?t=ajax&img="+$("#image_name").val()+"&w="+thumb_width+"&h="+thumb_height+"&x1="+x_axis+"&y1="+y_axis,
  cache:false,
  success:function(rsponse) {
    $("#cropimage1").hide();
    $("#thumbs1").empty();
    if(th_size == '1'){
      $("#thumbs").html('<img id="thumbImage" src="<?php echo Yii::app()->request->baseUrl; ?>/upload/temporary/thumb/'+rsponse+'?version='+Math.ceil(Math.random()*100)*10+' />');
      $("#thumbImage").on("load",function() {
        $("#thumbs").append('<input id="saveBtn" type="button" class="save-btn" onclick="refresh();" name="save" value="<?php echo Yii::t(Yii::app()->session["translator"], 'Save and continue');?>">');
      });
      $('html, body').animate({ scrollTop: $('#thumbs').offset().top }, 'slow');
      $("#small_image").val(rsponse);
    }
  }
.
.
.


text:
Q: If "verbalize" puts thoughts into spoken word, what about putting thoughts into written word? If "verbalize" puts thoughts into spoken word, what about putting thoughts into written word?
I considered document, record, but neither capture the visualization of "writing" the way verbalize captures "speaking".
Here is an example sentence where I would like to replace verbalize:

I have always thought this, but I have never been able to verbalize the sentiment.

I am also aware, verbalize may be used, but I'd like to use something more explicitly indicating writing.

A: The phrasal verbs (which I consider a single word) might work for you. Depending on the context, you could use either

write out
  1. To express or compose in writing

or, for more prosaic writings,

write down
  1. To set down in writing.

[American Heritage® Dictionary of the English Language, Fifth Edition. S.v. "write." Retrieved March 14 2016 from http://www.thefreedictionary.com/write ]
So, I would use the first for your example:

I have always thought this, but I have never been able to write out the sentiment.

For less informal terms, 'pen' and 'indite' suggest themselves. 'Pen' has, in my experience, the elegance of brevity and succinctness:

pen
tr.v. penned, pen·ning, pens
  To write or compose.

'Indite', on the other hand, is more ponderous and official in tone, and seems somewhat tainted by archaism:

in·dite  (ĭn-dīt′)
tr.v. in·dit·ed, in·dit·ing, in·dites
  ....
  2. To set down in writing.

(op. cit.)

A: I would suggest articulate or express

I have always thought this, but I have never been able to articulate the sentiment.

Although verbalize itself may be fitting in a written sense too.

A: Consider transcribe

put (thoughts, speech, or data) into written or printed form. (MW)

"The senator's speech was transcribed."

A: Consider textualize

To render (an oral narrative, for example) in written form, especially in a permanent, rigid, or authoritative form. (AHDEL/TFD)

:  to put into text :  set down as concrete and unchanging (the novel textualizes complex emotions) (MW)

Though the usage of this may be for more formal writing, similar to putting something in black and white.

A: A few other options:
If finally pulling together the threads to express a story or recount an event, then perhaps, "Compose" or "Chronicle".
If looking to formulate and express an idea, then you can use:
Promulgate (Dictionary.com):

*

*to make known by open declaration; publish; proclaim formally or put into operation (a law, decree of a court, etc.).

*to set forth or teach publicly (a creed, doctrine, etc.).


text:
Q: Demasiada demora em consulta apenas em MySql Aqui na empresa possuímos bancos de dados PG e MySql, esses dois bancos ficam em rede e são idênticos tanto em estrutura como em dados, onde um "robô" realiza esse espelhamento entre eles de 10 em 10 min.
Até aí tudo bem... Acontece que agora que as bases estão ficando gigantes (atualmente 1170000 linhas em uma tabela), e chegou a um ponto em que o MySql não consegue executar mais consultas ou demora vários minutos. Os dois bancos são absolutamente os mesmos (tabelas, dados, estrutura, relacionamentos, etc). Quando realizamos uma consulta no Pg o retorno é rápido, não passa de 4 segundos, porém a mesma consulta que deveria retornar a mesma quantidade de dados o MySql não consegue atender.
Estou me referindo a uma consulta simples, sem Join, por exemplo. Como a seguinte:
SELECT idCdr, agente
FROM `cdr`
WHERE agente <> ''
GROUP BY agente
HAVING COUNT( agente ) > 1;

Essa mesma instrução, o PG me retorna em 3 segundos e o MySql leva alguns minutos. Já fiz testes na dashboard dos próprios bancos (phpMyAdmin e PgAdmin) e aconteceu mesma coisa.
Alguém tem ideia do que pode estar havendo?


text: Q: Android: Display Google Map in grids of specific area I have requirement of displaying google map as grids of X km2 in Android. Also while zoom in/out the grid size will be updated to enclose the particular area. I am not sure whether it is possible or not? If possible , please help how can we implement this. thanks in advance


text:
Q: PHP and CKEditor included image does not show in the email I have the following page to send newsletters.
page
When I include an image from the toolbar icon. It displays correctly realtime. But however when I click Send, email gets the message without the image. Just only the message (formatted text by the editor shows correctly)
My image is located in this URL: http://raveen.comlu.com/sport.jpg
Also I print content made by the editor after sending message as well;
Even there also, image does not show on the page(see screenshot)

I have the following code;
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title> A simple page with CKEditor </title>
    <script src="ckeditor/ckeditor.js"> </script>
</head>

<body>
    <form method="post" action="">
        <!-- Create a <textarea> element first -->
        <textarea name="editor1" id="editor1" rows="10" cols="80">
            This is my textarea to be replaced with CKEditor.
        </textarea>

        <script>
            //replace the <textarea id="editor1"> with a CKEditor instance
            CKEDITOR.replace( 'editor1' );

            //Retrieve data from CKEditor instance with ID of editor1
            var data = CKEDITOR.instances.editor1.getData()

        </script>

        <input type="submit" name="btnSubmit" value="Send">
    </form>

    <?php
        if( isset($_POST['btnSubmit']) ){

            $editor_data = $_POST['editor1'];
            echo $editor_data;

            $to = "receiver1@yahoo.com, receiver2@gmail.com";
            $subject = "Here is the subject";

            $message = $editor_data;

            $header = "From: Sender Name <senderemail@gmail.com> \r\n";

            $header .= "MIME-Version: 1.0 \r\n";
            $header .= "Content-type:text/html;charset=UTF-8 \r\n";

            $retval = mail( $to, $subject, $message, $header );

            if( $retval == true ){
                echo "Message sent successfully";
            }
            else{
                echo "Message could not be sent!";
            }
        }
    ?>

</body>

A: All of your quotes from your editor data are being escaped so you can try adding this line before echo $editor_data;
$editor_data = stripslashes($editor_data);


text:
Q: MySQL query results in PHP differ to those in phpMyAdmin I have some UTF-8 characters that were stored incorrectly in my MySQL database, e.g. £ is stored as £. Since there are too many to manually correct I want to run a query via PHP to get the affected rows and use regular expressions to replace them.
The basic query I am using to test this is:
SELECT *
  FROM `notes`
 WHERE `notes` LIKE '%£%';

If I run this in phpMyAdmin it returns 754 rows, but in my PHP script it only returns 5 rows:
$query = "SELECT * FROM `notes` WHERE `notes` LIKE '%£%'";
$result = mysqli_query($this->connection, $query);
echo "rows... " . mysqli_num_rows($result));

I also tried setting the character set:
mysqli_set_charset($connection, 'utf-8');

Why does the same query to the same database produce different results?


text:
Q: Amazon RDS Oracle 12.1 Automatic Report Capturing I look after two RDS client sites, both of which are on Oracle 12.1.0.2.v12.
One of the instances has a high CPU load which appears to be caused by the 12.1 "feature" known as Automatic Report Capturing.

It's a known issue:
https://smarttechways.com/2017/10/11/with-monitor_data-as-select-inst_id-query-found-caused-performance-issue/
https://liups.com/wp-content/uploads/2018/01/Document-2102131.1.pdf
and can ordinarily be disabled by running  alter system set "_report_capture_cycle_time"=0;
However, as this is an RDS instance this parameter can't be set.
What's puzzling me is that the other site doesn't appear to have this issue - the specific SQL statement doesn't appear in session history:
WITH MONITOR_DATA AS (SELECT INST_ID, KEY, NVL2(PX_QCSID, NULL, STATUS) STATUS, FIRST_REFRESH_TIME, LAST_REFRESH_TIME, REFRESH_COUNT, PROCESS_NAME, SID, SQL_ID, SQL_EXEC_START, SQL_EXEC_ID, DBOP_NAME, DBOP_EXEC_ID, SQL_PLAN_HASH_VALUE, SQL_FULL_PLAN_HASH_VALUE, SESSION_SERIAL#, SQL_TEXT, IS_FULL_SQLTEXT, PX_SERVER#, PX_SERVER_GROUP, PX_SERVER_SET, PX_QCINST_ID, PX_QCSID, CASE WHEN ELAPSED_TIME < (CPU_TIME+ APPLICATION_WAIT_TIME+ CONCURRENCY_WAIT_TIME+ CLUSTER_WAIT_TIME+ USER_IO_WAIT_TIME+ QUEUIN... (truncated)

It's as though the "feature" has been disabled on the other site somehow - or conversely, it's somehow been inadvertently enabled at the problematic site.
Any ideas on how this can be disabled?

A: Normally if you have huge amount of CPU consumption, you will probably get error messages in the alert log of this type
Thu Sep 08 04:00:41 2016
Errors in file /app/oracle/diag/rdbms/dbname/dbinstance/trace/dbinstance_m002_14490.trc:
ORA-12850: Could not allocate slaves on all specified instances: 3 needed, 2 allocated

If that is the case, indeed disable the feature can only be done by
alter system set "_report_capture_cycle_time"=0; /* Default is 60 seconds */

Reason:

If the CPU consumption is significantly high then it is not an
expected behaviour and could be due to optimizer choosing suboptimal
plan for the SQL statements. This can happen due to Adaptive
Optimization, a new feature in 12c.

Therefore, if you can't change the hidden parameter, you might try to disable Adaptive Optimization all together
alter system set optimizer_adaptive_features = false scope=both ;

As the documentation states

In 12.1, adaptive optimization as a whole is controlled by the dynamic
parameter optimizer_adaptive_features, which defaults to TRUE. All of
the features it controls are enabled when optimizer_features_enable >=
12.1.

Either you upgrade to 19c, or you disable all optimizer adaptive features
Amazon RDS now supports 19c

A: "optimizer_adaptive_features" is not related to "_report_capture_cycle_time" anyhow.


text:
Q: Parallel invoking with conditionally I have a scenario where I would like to invoke functions but want them to be invoke conditionally. So in the below code only function 2 and 3 will be invoked. However, the Action part doesnt return a value but in my case I want to store the return value.
List<int> list = new List<int> {2,3};
Dictionary<int, Action> actions = new Dictionary<int, Action>()
{
   {1, Function1},
   {2, Function2},
   {3, Function3}
};

Parallel.Invoke((from action in list select actions[action]).ToArray());

Initially what I had was below code but this would invoke all the functions. Any thoughts?
Parallel.Invoke(
 () => return1=function1,
 () => return2=function2,
 () => return3=function3
);

A: If you need results from the execution, Parallel and Action won't be able to get you the function results, but if we use Task and Func<T> we can get the results back after running them in parallel.
I added to your example below to use Task instead of Parallel to have the functions run concurrently AND allow you to store the results. I assumed int for the return type of functions 1, 2, and 3 - you can change it to fit your needs.
List<int> list = new List<int> { 2, 3 };
Dictionary<int, Func<int>> actions = new Dictionary<int, Func<int>>()
{
    {1, Function1},
    {2, Function2},
    {3, Function3}
};

List<Task<int>> taskList = (from a in list select Task.Run(actions[a])).ToList();

// Allow all processing to finish before accessing results
Task.WaitAll(taskList.ToArray());
int result = taskList[0].Result;

Final note, you may be able to swap taskList.ForEach(...) with Parallel.ForEach(...), but I think that will introduce some unnecessary overhead.

A: If I learned it correctly, you just want to execute some actions that are present in list. Why not just write it at C#?
var hs = new HashSet<int> { 2, 3 };
var actions = new Dictionary<int, Action>()
{
   {1, Function1},
   {2, Function2},
   {3, Function3}
};

actions.Where(x => hs.Contains(x.Key)).AsParallel().ForAll(x => x.Value());

How they read it: take all pairs with key presented in set of required keys (2 and 3 in this example), and then execute theirs actions in parallel manner. Pretty clear, I guess.
If you want return some values, use Func and Select instead of Action and ForAll respectively.

A: I am dealing with some parallel tasks right now, and I was using Parallel.Invoke, I ended up switching the way I was calling the actions to be in a list, and called the Parallel.ForEach on it. Which ended up shaving off 1.2 ms/per row for me. Which was awesome. So I figured I would take a stab at what I think you were asking.
        int Function1(int input)
        {
            return 10 * input;
        }
        int Function2(int input)
        {
            return 20 * input;
        }
        int Function3(int input)
        {
            return 30 * input;
        }
        List<int> list = new List<int> { 2, 3 };
        Dictionary<int, Func<int, int>> actions = new Dictionary<int, Func<int, int>>()
        {
           {1, (arg) => Function1(arg)},
           {2, (arg) => Function2(arg)},
           {3, (arg) => Function3(arg)}
        };
        var bag = new ConcurrentBag<int>();

        Parallel.ForEach(actions,  action => {
            if(action.Key == 2 || action.Key == 3)
            {
                bag.Add(action.Value.Invoke(3));
            }
        });

        foreach(var number in bag)
        {
            Console.WriteLine(number);
        }

I think what you were trying to do is conditionally call the methods, and then store off the return from those Funcs. I was a little confused because you were using Action (which return nothing). So I switched them to Func which is Function takes an int, and returns and int. I also added some inline functions just so the code would be able to run from a copy and paste.
Also here is a .net fiddle with the solution if you want to play around with it a bit.


text:
Q: Android TextView and Buttons not working in my app I am learning Android and trying one simple Android app development, I got one demo code from my lecture and the teacher simply do the following:
There are 2 buttons, 1 textview. When touching button A, it will show "text A" in the textview, while touching button B, it will present "text B" in textview.
I followed the code and rewrote it, but i can't get the correct result when I ran with emulator.
When I touch either button, there's no content in the TextView. But my teacher's reference code works:
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;

public class ActTwo extends Activity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_act_two);
        tv = (TextView) this.findViewById(R.id.textView2);
    }

    public void report(View v) {
        if(v.getId() == R.id.button1)
            tv.setText(R.string.anrep);
        else
            tv.setText(R.string.iprep);
    }

}

How is report(View v) called? I can't understand how this class is called. Could someone please help me out?

A: You need to let your button know that, when pressed, report() should be called. This may be done through the android:onClick attribute of your button on your layout's XML:
<Button
 android:id="@+id/button1"
 android:layout_height="wrap_content"
 android:layout_width="wrap_content"
 android:text="@string/button_text"
 android:onClick="report" />

Or by code, attaching an OnClickListener to the button:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_act_two);
    button1 = (Button) this.findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            report(v);
        }
    });
}

Hope it helps.

A: You should implements the View.OnClickListener, and override that OnClick method. You also need to setOnClickListener on your buttons. So your code should be like:
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;

public class ActTwo extends Activity implements View.OnClickListener{

    private TextView tv;
    private Button button1, button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_act_two);
        tv = (TextView) this.findViewById(R.id.textView2);

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(this);

        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.button1)
            tv.setText(R.string.anrep);
        else
            tv.setText(R.string.iprep);
    }
}

A: import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;

public class ActTwo extends Activity {

    private TextView tv;

    private Button button1, button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_act_two);
        tv = (TextView) this.findViewById(R.id.textView2);
        button1 =(Button)this.findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
               report(v);
            }
        });
        button2 =(Button)this.findViewById(R.id.button2):
        button2.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
               report(v);
            }
        });
    }

    public void report(View v) {
        if(v.getId() == R.id.button1)
            tv.setText(R.string.anrep);
        else
            tv.setText(R.string.iprep);
    }

}


text:
Q: Simple algebra involving trigonometry, but confusing How do I get from
$$\frac{\sqrt3}{2} + \frac12 \tan x = 2 \tan x \cdot \frac{\sqrt3}{2}$$
to
$$\frac{\sqrt3}{2 \sqrt3 - 1} = \tan x$$
and then to
$$11 \tan x = 6 + \sqrt3$$

A: Simple: isolate $\tan x$ in one side. You get:
$$\frac{2\sqrt3-1}{2}\,\tan x=\frac{\sqrt3}2 \enspace\text{whence}\enspace \tan x=\frac{\sqrt3}{2\sqrt3-1}$$
Then rationalise the denominator:
$$\tan x=\frac{\sqrt3(2\sqrt3+1)}{12-1}=\frac{6+\sqrt3}{11}.$$

A: I will try to make it a bit more elaborate since you are going to need to be able to manipulate equations like this all the time.
Multiply both sides by 2:
$\implies \sqrt{3}+\tan(x)=2\tan(x)\sqrt{3}$
Subtract $\tan(x)$ from both sides in order isolate $\tan(x)$
$\implies \sqrt{3}=2\tan(x)\sqrt{3}-\tan(x)$
You have two terms with $\tan(x)$ on the RHS so you can factor out $\tan(x)$
$\implies \sqrt{3}=\tan(x)(2\sqrt{3}-1)$
Divide both sides by $(2\sqrt{3}-1)$
$\implies \tan(x)=\frac{\sqrt{3}}{2\sqrt{3}-1}$
Now you can multiply the fraction on the RHS by $\frac{2\sqrt{3}+1}{2\sqrt{3}+1}$ in order to get rid of the sqare root in the denominator. Remember you are just multiplying by 1 so it doesn't change the equation
$\implies \tan(x)=\frac{\sqrt{3}}{2\sqrt{3}-1}\cdot \frac{2\sqrt{3}+1}{2\sqrt{3}+1}$
Just do a bit of multiplication and you will get
$\tan(x)=\frac{6+\sqrt{3}}{11} \iff 11\tan(x)=6+\sqrt{3} $

A: $$\frac{\sqrt{3}}{2\sqrt{3}-1}=\tan(x)$$
$$\frac{\sqrt{3}}{2\sqrt{3}-1}*\frac{2\sqrt{3}+1}{2\sqrt{3}+1}=\tan(x)$$
$$\frac{6+\sqrt{3}}{11}=\tan(x)$$


text:
Q: Search by field in related/joined table using Laravel query builder I have two tables: brands and models. The brands table has an ID for each brand and the name. The models table has a model id and a foreign key with each brand id and model name.

Here is the model table where "cod_marca" is the foreign key and "modelo" is the model name.

And here I have the branding table, where "cod_marca" is the ID and "marca" is the name.
I want the user to search according to the name of each brand and everything to be listed according to "cod_marca", that is, if the user searches for "Chevrolet", I want the models with id "1" to appear.
Here is my search code:
public function buscar(Request $request) {
    $model = $request->get('marca');
    $models = DB::table('marcas')->where('marca', 'like', '%' . $marca . '%')->paginate(5);

    return view('buscar', ['models' => $models]);
}

The form code is generic, I just used a <select> with the brand name.

A: Personally, Id prefer to create models for each table with relationships linking those models and use Eloquent to pull the results.
That said, you could do what you want using the query builder's join method like so:
public function buscar(Request $request) {
    $model = $request->get('marca');
    $models = DB::table('models ')
        ->join('marcas', 'models.cod_marca', '=', 'marcas.cod_marca')
        ->select('models.cod_modelo', 'models.cod_marca', 'models.modelo', 'marcas.marca')
        ->where('marcas.marca', 'like', '%' . $marca . '%')
        ->paginate(5);
    return view('buscar', ['models' => $models]);
}


text:
Q: ¿Cómo obtener el valor de una propiedad css de un elemento html? Estoy intentando obtener el valor de una propiedad pero no se guarda dentro de la variable que creo con javascript. Me gustaría saber cómo obtener el valor de propiedades css de los elementos. ¿Acaso hay alguna función específica para eso en javaScript?
Por ejemplo:

Este div está visible

Por tanto este DIV también lo está

A:

Este div está visible

Por tanto este DIV también lo está

Lo estabas realizando correctamente, pero al tener el


text:
Q: Async.js each continue without callback Why async.js each still works without calling callback
var async = require('async');

var arr = ['a', 'b', 'c', 1, 2, 3];

async.each(arr, function(item, callback) {
  console.log(item);
}, function(error) {
  if (error) console.log(error);
});

as a result I can see in terminal each array item, but as I understand that shouldn't be, until calling callback, right?

A: async.each just calls the "loop body" callback for each item in the array. If they are asynchronous, they'll run concurrently.
You are never getting into your final callback, as your "asynchronous tasks" stay forever pending without ever calling callback. That's the actual problem with your code.
If you don't want to see the next item until the previous one has called its callback, you should be using async.eachSeries instead.


text:
Q: How to set duration of task based on index on machine ortools? I have the following code to create a schedule. I would like to set: duration = max_duration if task is the first on machine or the previous task on the same machine has different id or there is an idle time on the same machine before current task. In all other cases, I would like to set duration = min_duration.
I have no clue how to check these conditions in ortools.
def flexible_jobshop():

    """Solve a small flexible jobshop problem."""
    # Data part.

    # For us:
        # job is set of 2 robots, it consists of two tasks: robot for filling the queue and robot for processing it
        # each of them has multiple alternatives for each of the machines it can be run on

    jobs = [  # task = (id, time per single item, priorita, machine id options, start time min, start time max)
        [  # Job 0
            ["gga5", 3, 1, ["a", "c"], 10],  #task0
            ["gga6", 2, 2, ["b", "c"]],    #task1
            ["gga6", 2, 2, ["b", "c"]],
            ["gga6", 2, 2, ["b", "c"]],
            ["gga6", 2, 2, ["b", "c"]],
            ["gga6", 2, 2, ["b", "c"]],
            ["gga6", 2, 2, ["b", "c"]],
            ["gga6", 2, 2, ["b", "c"]],
            ["gga6", 2, 2, ["b", "c"]]

        ],
        [  # Job 1
            ["h4jk", 4, 1, ["a", "b", "c"], 8, 12],
            ["h4jl", 1, 1, ["a"]],
            ["h4jl", 1, 1, ["a"]],
            ["h4jl", 1, 1, ["a"]],
            ["h4jl", 1, 1, ["a"]],
            ["h4jl", 1, 1, ["a"]],
            ["h4jl", 1, 1, ["a"]],
            ["h4jl", 1, 1, ["a"]],
            ["h4jl", 1, 1, ["a"]]

        ],
        [  # Job 2
            ["p0o1", 2, 1, ["a", "b"], 0, 10],
            ["p0o2", 3, -1, ["a", "b", "c"]],
            ["p0o2", 3, -1, ["a", "b", "c"]],
            ["p0o2", 3, -1, ["a", "b", "c"]],
            ["p0o2", 3, -1, ["a", "b", "c"]],
            ["p0o2", 3, -1, ["a", "b", "c"]],
            ["p0o2", 3, -1, ["a", "b", "c"]],
            ["p0o2", 3, -1, ["a", "b", "c"]],
            ["p0o2", 3, -1, ["a", "b", "c"]],
            ["p0o2", 3, -1, ["a", "b", "c"]]
        ]
    ]

    ID_ROBOT = 0
    PROCESSING_TIME = 1
    PRIORITA = 2
    MACHINE_ID = 3
    START_TIME_MIN = 4
    START_TIME_MAX = 5

    TIME_PENALTY = 1

    num_jobs = len(jobs)
    all_jobs = range(num_jobs)

    list_machines = set([alt for job in jobs for task in job for alt in task[MACHINE_ID]])
    num_machines = len(list_machines) # 1 position of machine id
    all_machines = range(num_machines)

    # Model the flexible jobshop problem.
    model = cp_model.CpModel()

    horizon = 0
    for job in jobs:
        for task in job:
            max_task_duration = task[PROCESSING_TIME] + TIME_PENALTY
            horizon += max_task_duration

    print('Horizon = %i' % horizon)

    # Global storage of variables.
    intervals_per_resources = collections.defaultdict(list)
    durations_per_resources = collections.defaultdict(list)
    starts = {}  # indexed by (job_id, task_id).
    presences = {}  # indexed by (job_id, task_id, alt_id).
    job_ends = []

    # Scan the jobs and create the relevant variables and intervals.
    for job_id in all_jobs:
        job = jobs[job_id]
        num_tasks = len(job)
        previous_end = None
        for task_id in range(num_tasks):
            task = job[task_id]

            min_duration = task[PROCESSING_TIME]
            max_duration = min_duration + TIME_PENALTY

            num_alternatives = len(task[MACHINE_ID])
            all_alternatives = range(num_alternatives)

            # Create main interval for the task.
            suffix_name = '_j%i_t%i' % (job_id, task_id)
            start = model.NewIntVar(0, horizon, 'start' + suffix_name)
                 #start of this given task could be somewhere between 0 and end = horizon = total duration?
                # if we want to run the schedule between 8 and 15, should we specify it here?
            duration = model.NewIntVar(min_duration, max_duration,
                                       'duration' + suffix_name)
            end = model.NewIntVar(0, horizon, 'end' + suffix_name)
            interval = model.NewIntervalVar(start, duration, end,
                                            'interval' + suffix_name)

          #  model.Add(duration == duration + 1)
            # Store the start for the solution.
            starts[(job_id, task_id)] = start

            # Add penalty for switching between processes

            # Add precedence with previous task in the same job.
                # filler runs before processor!
                # so if each job is in our case two robots: one filler of the queue and the 2nd the processor
                # then their precedence is secured
            if previous_end is not None:
                model.Add(start >= previous_end)
            previous_end = end

            # If there is time restrictions for each day, then implement
            try:
                start_limit = task[START_TIME_MIN]
                model.Add(starts[(job_id, task_id)] >= start_limit)
            except:
                  print(f"For {task[ID_ROBOT]} there is no limit for start time")

            try:
                end_limit = task[START_TIME_MAX]
                model.Add(starts[(job_id, task_id)] <= start_limit)
            except:
                  print(f"For {task[ID_ROBOT]} there is no limit for end time")

            # Create alternative intervals: choose only one of alternatives - single job runs on single machine
            if num_alternatives > 1:
                l_presences = []
                for alt_id in all_alternatives:
                    alt_suffix = '_j%i_t%i_a%i' % (job_id, task_id, alt_id)
                    l_presence = model.NewBoolVar('presence' + alt_suffix)
                    l_start = model.NewIntVar(0, horizon, 'start' + alt_suffix)
                    l_duration = model.NewIntVar(min_duration, max_duration,
                                       'duration' + suffix_name)
                    l_end = model.NewIntVar(0, horizon, 'end' + alt_suffix)
                    l_interval = model.NewOptionalIntervalVar(
                        l_start, l_duration, l_end, l_presence,
                        'interval' + alt_suffix)
                    l_presences.append(l_presence)

                    # Link the primary/global variables with the local ones.
                    model.Add(start == l_start).OnlyEnforceIf(l_presence)
                    model.Add(duration == l_duration).OnlyEnforceIf(l_presence)
                    model.Add(end == l_end).OnlyEnforceIf(l_presence)

                    # Add the local interval to the right machine.
                    intervals_per_resources[task[MACHINE_ID][alt_id]].append(l_interval)

                    # Store the presences for the solution.
                    presences[(job_id, task_id, alt_id)] = l_presence

                # Select exactly one presence variable.
                model.AddExactlyOne(l_presences)
            else:
                intervals_per_resources[task[MACHINE_ID][0]].append(interval)
                presences[(job_id, task_id, 0)] = model.NewConstant(1)

        job_ends.append(previous_end)

    # Create machines constraints: No everlap of jobs per singe interval
    for machine_id in list_machines:
        intervals = intervals_per_resources[machine_id]
        if len(intervals) > 1:
            #print(f"For machine {machine_id} there is more than 1 interval.")
            model.AddNoOverlap(intervals)

    # Makespan objective
    makespan = model.NewIntVar(0, horizon, 'makespan')
    model.AddMaxEquality(makespan, job_ends)
    model.Minimize(makespan)

    # Solve model.
    solver = cp_model.CpSolver()
    solution_printer = SolutionPrinter()
    status = solver.Solve(model, solution_printer)

    print(solver.StatusName(status))
    # Print final solution.
    for job_id in all_jobs:
        print('Job %i:' % job_id)
        for task_id in range(len(jobs[job_id])):
            print(starts[(job_id, task_id)])
            start_value = solver.Value(starts[(job_id, task_id)])
            machine = -1
            duration = -1
            selected = -1
            for alt_id in range(len(jobs[job_id][task_id][MACHINE_ID])):
                if solver.Value(presences[(job_id, task_id, alt_id)]):
                    robot = jobs[job_id][task_id][ID_ROBOT]
                    duration = jobs[job_id][task_id][PROCESSING_TIME]
                    machine = jobs[job_id][task_id][MACHINE_ID][alt_id]
                    selected = alt_id
            print(
                '  task_%i_%i (id: %s) starts at %i (alt %i, machine %s, min duration %i)' %
                (job_id, task_id, robot, start_value, selected, machine, duration))

    print('Solve status: %s' % solver.StatusName(status))
    print('Optimal objective value: %i' % solver.ObjectiveValue())
    print('Statistics')
    print('  - conflicts : %i' % solver.NumConflicts())
    print('  - branches  : %i' % solver.NumBranches())
    print('  - wall time : %f s' % solver.WallTime())

flexible_jobshop()

I tried to do the following but it is wrong because it makes the decision based on how the tasks are organised in the input data not in the machine. On the top of that the condition
previous_end == start

does not even work. I dont understand why.
            equal = model.NewBoolVar("equal")
            print(previous_end == start)
            if previous_end == start:
                model.Add(equal == 1)
            else:
                model.Add(equal == 0)

            try:
                if previous_robot == task[ID_ROBOT]: # jsou po sobě v datech ne na machine! Špatně!
                    model.Add(duration == min_duration).OnlyEnforceIf(equal)
                else:
                    model.Add(duration == max_duration)
            except:
                model.Add(duration == max_duration)

            previous_robot = task[ID_ROBOT]

I also checked circuit constraint but I dont understand it from the sample codes I saw online.
Can somebody please help? Sample code how to solve the issue would be very much appreciated!
Thank you!!


text:
Q: Query to find first,last and prior to last values I have a requirement to get the first,last and prior to last id from a table(max,min,max-1) to analyze the ID details of each and every project which are scanned first,last and prior to last.If there is only one scan,then i need to capture that alone.But if we use Max/min or Rownum then it will capture the same value for both max and min values if we have only one id alone.
Source table
CREATE TABLE TABLE1
(
SOA_SECTOR VARCHAR2(128),
SOA_REGION VARCHAR2(128),
USERNAME VARCHAR2(128),
PROJECT VARCHAR2(256) NOT NULL,
SOLUTION VARCHAR2(256),
PATH VARCHAR2(2048) NOT NULL,
TIME DATE NOT NULL,
LOC NUMBER(10) NOT NULL,
SCAN_ID NUMBER(10),
SESSION_ID VARCHAR2(256),
FILE_ID VARCHAR2(256),
FILE_INFO_ID VARCHAR2(256),
SCAN_YEAR_MON VARCHAR2(7),
SCAN_YEAR VARCHAR2(7),
SCAN_MONTH VARCHAR2(7),
LOAD_DATE_TIME DATE NOT NULL,
CONSTRAINT rpt_scan_summary_pk PRIMARY KEY (SCAN_ID, FILE_ID)
);
target table
CREATE TABLE table2 (
PROJECT VARCHAR2(256 CHAR) NOT NULL,
SOLUTION VARCHAR2(256 CHAR),
FIRST_SCAN_ID NUMBER(10) NOT NULL,
LAST_SCAN_ID NUMBER(10) NOT NULL,
PRIOR_SCAN_ID NUMBER(10) NOT NULL,
CONSTRAINT pk_tmp_first_last_scan_ids_id PRIMARY KEY (PROJECT)
);

Sample records
Insert into EXPORT_TABLE (PROJECT,SOLUTION,FIRST_SCAN,LAST_SCAN,PRIOR_SCAN) values ('park.Cash.Trading.csproj','TWSTicketing.sln',2491149,2514275,2514274);
Insert into EXPORT_TABLE (PROJECT,SOLUTION,FIRST_SCAN,LAST_SCAN,PRIOR_SCAN) values ('RBCheck.Services.ArchiveAndPurgeService.csproj','RB.Citi.GlobalCheck.sln',1989546,5385142,5384987);
Insert into EXPORT_TABLE (PROJECT,SOLUTION,FIRST_SCAN,LAST_SCAN,PRIOR_SCAN) values ('Cmb.UI.Framework.Core.csproj','BE2UI.sln',51839,61995,61994);

What i tried
CREATE OR REPLACE PROCEDURE PROC1 AS
BEGIN
INSERT INTO table2
SELECT
first_scan.PROJECT,
first_scan.SOLUTION,
first_scan.First_Scan_ID,
last_scan.Last_Scan_ID,
prior_scan.Prior_Scan_ID
FROM (
Select PROJECT,
SOLUTION,First_Scan_ID,seq from (SELECT
PROJECT,
SOLUTION,
SCAN_ID First_Scan_ID,
ROW_NUMBER()
OVER (
PARTITION BY PROJECT
ORDER BY SCAN_ID ASC ) seq
FROM portal_CSA.table1)
where Seq=1

) first_scan
JOIN (
Select PROJECT,
SOLUTION,Last_Scan_ID,seq from (SELECT
PROJECT,
SOLUTION,
SCAN_ID Last_Scan_ID,
ROW_NUMBER()
OVER (
PARTITION BY PROJECT
ORDER BY SCAN_ID Desc ) seq
FROM portal_CSA.table1)
where Seq=1
) last_scan ON first_scan.PROJECT = last_scan.PROJECT -- AND first_scan.SOLUTION = last_scan.SOLUTION
left outer JOIN (
Select PROJECT,
SOLUTION,Prior_Scan_ID,seq from (SELECT
PROJECT,
SOLUTION,
SCAN_ID Prior_Scan_ID,
ROW_NUMBER()
OVER (
PARTITION BY PROJECT
ORDER BY SCAN_ID Desc ) seq
FROM portal_CSA.table1)
where Seq=2
) prior_scan ON first_scan.PROJECT=prior_scan.PROJECT;
END;

A: Is this what you want?
select t.*
from  (Select t.*
              row_number() over (partition by project order by scan_id) as seqnum,
              count(*) over (partition by project) as cnt
       from portal_CSA.table1 t
      ) t
where seqnum in (1, cnt - 1, cnt);

If you want this in one row, you can use conditional aggregation:
select project,
       max(case when seqnum = 1 then scan_id end) as first_scan_id,
       max(case when seqnum = cnt - 1 and cnt > 2 then scan_id end) as prior_scan_id,
       max(case when seqnum = cnt and cnt > 1 then scan_id end) as last_scan_id,
from  (Select t.*
              row_number() over (partition by project order by scan_id) as seqnum,
              count(*) over (partition by project) as cnt
       from portal_CSA.table1 t
      ) t
where seqnum in (1, cnt - 1, cnt)
group by project;


text:
Q: JavaFX: Issue while loading another FXML on button click I wanted a window (FXML) to show up when the user clicks the button. Apparently, the problem is very weird. Whenever I click the button, there is a strange exception which I'm unable to resolve. If my called FXML use the existing controller as controller class, then the exception is thrown, else the windows loads properly.Here is what em doing on button click.Button Click Action:
@FXML
private void handleSmartSingle(ActionEvent ae) throws IOException {
    try {
        Parent root = FXMLLoader.load(getClass().getResource("Spinner.fxml"));
        final Stage stage = new Stage();
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.setScene(new Scene(root));
        stage.show();
    } catch (Exception e) {
        Logger.getLogger(PeersController.class.getName()).log(Level.SEVERE, null, e);
    }
}

And here is the exception em keeping on getting:
javafx.fxml.LoadException:

at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at peers.PeersController.handleSmartSingle(PeersController.java:426)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.control.MenuItem.fire(MenuItem.java:462)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1405)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:352)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:388)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)

Caused by: java.lang.NullPointerException
at peers.PeersController.initialize(PeersController.java:1117)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 61 more

Anyone having any clue, ur help is very much appreciated. Thank You.
Edit:  Exception @ 1117 line
@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO

    //Miscellaneous
    inboxPath.setText(sharedDirectory.toString()); //1117
    final Circle clip = new Circle(75, 75, 65); //1118
    userImgView.setClip(clip); //1119 and so on.

    //Getting windows Username
    userField.setText(System.getProperty("user.name"));

    //Search-Field text property listner (Dynamic Search)
    searchField.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            if (!searchField.getText().isEmpty() && ipList.size() != 0) {
                request = "Search";
                System.out.println(request);
                for (String iplist : ipList) {
                    new Thread(new miniClient(iplist)).start();
                }
            } else if (searchField.getText().isEmpty() && ipList.size() != 0) {
                if (!sfiData.isEmpty()) {
                    sfiData.clear();
                }
            }
        }
    });
}


text:
Q: Java -- static & dynamic type -- "what does this print?" So I'm having a bit of trouble understanding this example that was shown in class -- it's supposed to illustrate subtleties between static & dynamic types in Java.
public class Piece {

    public static void main (String[] args) {
        Piece p2 = new Knight();
        Knight p1 = new Knight();
        p1.capture(p2); // call 1; "Knight is bored" is supposed to be printed
        p2.capture(p1); // call 2; "knight is bored" is supposed to be printed
    }

    public void capture () {
        System.out.println("Capturing");
    }

    public void capture (Piece p) {
        System.out.println("I'm bored")
    }

public class Knight extends Piece {

    public void capture (Piece p) {
        System.out.println("Knight is bored");
    }

    public void capture (Knight k) {
        System.out.println("TOO SLOW BUDDY");
    }
}

Here's my understanding of what happens when the two calls get made:
Call 1: p1.capture(p2)
The capture method is called from p1.  Via dynamic type lookup, it sees that p1's dynamic type is Knight. So it looks in the Knight subclass. p2 is passed in as an argument. To see which capture method to invoke within the Knight subclass, it checks the static type of p2, which is piece. Therefore, "Knight is Bored" is printed. This is the right output, but is my reasoning correct?
Call 2: p2.capture(p1)
Using the same reasoning, the capture method is called from p2. Via dynamic type lookup, it sees that p2's dynamic type is Knight. So it looks in the Knight subclass. p1 is passed in as an argument. To see which capture method to invoke, it looks at p1's static type, which is Knight. Therefore, "TOO SLOW BUDDY" is printed. Obviously, my reasoning is wrong, as that's not what's really printed. Any direction?
Thanks!

A: In the second call, you can only call methods of the Piece class or the same methods in its subclasses. That's why it will call capture(Piece p) instead of capture(Knight k). The latter is specific to the Knight class.
For example, when we have "List a = new Arraylist();", you can only call methods that were declared in List, not additional but similar looking methods in ArrayList.

A: When you add @Override annotation to Knights methods it becomes clear.
public void capture (Knight k) {
    System.out.println("TOO SLOW BUDDY");
}

this method isn't overriden - it's new, added in Knight class.
So it could be used only on object with type Knight - for example: Knight k = new Knight();
You dont have such example, that this method is invoked on Knight with Knight as argument. You invoked capture on Knight with Piece, and on Piece with knight
    p1.capture(p2); // call 1; "Knight is bored" is supposed to be printed
    p2.capture(p1); // call 2; "knight is bored" is supposed to be printed
    p1.capture(p1); // call 3:  TOO SLOW BUDDY <- look here :)

A:  p2.capture(p1); // call 2; "knight is bored" is supposed to be printed

Here you are calling capture method on Piece class object and since you have passes p1(Knight) class reference it will call overridden capture method of class Knight. that is
 public void capture (Piece p) {
        System.out.println("Knight is bored");
    }

A: If you run the following code -
public class Piece {

public static void main (String[] args) {
    Piece p2 = new Knight();
    Knight p1 = new Knight();
    p1.capture(p2);
    p2.capture(p1);
}

public void capture () {
    System.out.println("Capturing");
}

public void capture (Piece p) {
    System.out.println("I'm bored");
}

}
  class Knight extends Piece {

  //    public void capture (Piece p) {
  //        System.out.println("Knight is bored");
  //    }

public void capture (Knight k) {
    System.out.println("TOO SLOW BUDDY"+k);
}

}
The result is  -
I'm bored
I'm bored
So the dynamic lookup checks if the subclass has overridden the function or not.

A: As I remember, I've learned "extending" means "laying the new one over the old one but not delete it" and if you are "override" the method, it would be like you described.
In your case if you call "p1.capture(p1)" it should result in "TOO SLOW BUDDY" (but I did not tried).

A: I don't think this sample is telling you the deferences between static & dynamic type . You even need not to think about the superclass and subclass . It is just telling you the method definition . ---> Only when caller , method name , parameters' names and parameters' types are all the same , the right method will be called .


text:
Q: std::vector::emplace in C++11 According to cppreference.com:

Notes
The specialization std::vector<bool> did not have emplace() member
  until C++14.

What does it mean? Can template specialization omit member? Does mean that member function is not present at all? Or is it just not specialized?
Following code seems to work on gcc 7.1.0:
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    std::vector<bool> v;
    v.emplace_back(true);
    v.emplace_back(false);
    for (const auto &b : v) {
        std::cout << b << std::endl;
    }
}

http://coliru.stacked-crooked.com/a/07c8c0fc6050968f

A: A template specialization can be completely different from the generic template. So in theory, you cannot know whether the classes A<int> and A<bool> have any common members:
template <typename T>
class A
{
public:
    void foo()
    {}
};

template <>
class A<bool>
{
public:
    void bar()
    {}
};

int main()
{
    A<int> a;
    a.foo();

    A<bool> b;
    b.bar();

    b.foo();  // error: 'class A<bool>' has no member named 'foo'
}

The class std::vector<bool> is a specialized template. Your quote from the standard says that the emplace() method was missing in that specialization until C++14.
In practice, concrete standard libraries such as libstdc++ may have provided the emplace() method for std::vector<bool> even before C++14, but it was not required in the standard.


text:
Q: Flat file data mapping to sibling nodes I have a flat file coming in where each record is a customer and it has a shipto and billto address in that record.  The output schema has a customer record with an address child node.  I don't know how to map the 2 addresses from the incoming record to sibiling child nodes of the customer record.
I have an input file that is defined like:
<customer>
    <customernum/>
    <shipaddrcity/>
    <shipaddrstate/>
    <shipaddrzip/>
    <billaddrcity/>
    <billaddrstate/>
    <billaddrzip/>
</customer>

The output needs to end up looking like:
<customer>
    <customernum/>
    <addr>
        <type/>
        <city/>
        <state/>
        <zip/>
    </addr>
    <addr>
        <type/>
        <city/>
        <state/>
        <zip/>
    </addr>
</customer>

I'm quite new to biztalk and have been unable to find any decent examples of how to complete this using the Biztalk Mapper.  I'm also willing to listen to how to do this with xslt.

A: You probably want something specific to BizTalk, and I don't know anything about BizTalk, but this might be helpful to you any way.
Given an input document of ...
<customers>
<customer>
    <customernum>1</customernum>
    <shipaddrcity>Cairns</shipaddrcity>
    <shipaddrstate>QLD</shipaddrstate>
    <shipaddrzip>b</shipaddrzip>
    <billaddrcity>Sydney</billaddrcity>
    <billaddrstate>NSW</billaddrstate>
    <billaddrzip>c</billaddrzip>
</customer>
<customer>
    <customernum>2</customernum>
    <shipaddrcity>d</shipaddrcity>
    <shipaddrstate>WA</shipaddrstate>
    <shipaddrzip>e</shipaddrzip>
    <billaddrcity>Melbourne</billaddrcity>
    <billaddrstate>Vic</billaddrstate>
    <billaddrzip>f</billaddrzip>
</customer>
</customers>

... this XSLT 1.0 stylesheet ...
<xsl:transform
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

<xsl:output omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*" />

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="customer">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()[not(
      self::shipaddrstate|
      self::shipaddrzip  |
      self::billaddrstate|
      self::billaddrzip   )]"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="shipaddrcity">
  <addr>
    <type>ship</type>
    <city><xsl:value-of select="." /></city>
    <xsl:apply-templates select="../(shipaddrstate|shipaddrzip)" />
  </addr>
</xsl:template>

<xsl:template match="billaddrcity">
  <addr>
    <type>bill</type>
    <city><xsl:value-of select="." /></city>
    <xsl:apply-templates select="../(billaddrstate|billaddrzip)" />
  </addr>
</xsl:template>

<xsl:template match="shipaddrstate|billaddrstate">
  <state><xsl:value-of select="." /></state>
</xsl:template>

<xsl:template match="shipaddrzip|billaddrzip">
  <zip><xsl:value-of select="." /></zip>
</xsl:template>

</xsl:transform>

... when applied to the input document, will yield ...
<customers>
   <customer>
      <customernum>1</customernum>
      <addr>
         <type>ship</type>
         <city>Cairns</city>
         <state>QLD</state>
         <zip>b</zip>
      </addr>
      <addr>
         <type>bill</type>
         <city>Sydney</city>
         <state>NSW</state>
         <zip>c</zip>
      </addr>
   </customer>
   <customer>
      <customernum>2</customernum>
      <addr>
         <type>ship</type>
         <city>d</city>
         <state>WA</state>
         <zip>e</zip>
      </addr>
      <addr>
         <type>bill</type>
         <city>Melbourne</city>
         <state>Vic</state>
         <zip>f</zip>
      </addr>
   </customer>
</customers>


text:
Q: Win32: SendInput Alt+Click not working in some programs I want to send Alt + Mouse Click to some programs.
It works in most programs, it needs a small delay for some, but doesn't work at all in one of them.
The mouse click is working, but the Alt key isn't. If I hold Alt manually and trigger a Mouse Click with SendInput(), it works. So I assume that the Alt key press is not being sent/handled correctly?
This is the code I'm using:
void SendAltClick()
{
    INPUT inputs[4] = {};
    ZeroMemory(&inputs, sizeof(INPUT));

    // Alt down
    inputs[0].type = INPUT_KEYBOARD;
    inputs[0].ki.wVk = VK_MENU;

    // Left down
    inputs[1].type = INPUT_MOUSE;
    inputs[1].mi.dwFlags = MOUSEEVENTF_LEFTDOWN;

    // Left up
    inputs[2].type = INPUT_MOUSE;
    inputs[2].mi.dwFlags = MOUSEEVENTF_LEFTUP;

    // Alt up
    inputs[3].type = INPUT_KEYBOARD;
    inputs[3].ki.wVk = VK_MENU;
    inputs[3].ki.dwFlags = KEYEVENTF_KEYUP;

    SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT));
}

All calls to SendInput() return 1.
I've also tried Ctrl/Shift + Click, and they work as expected.
Why doesn't it behave the same way with all programs? Why does it need a small delay for some of them? Why doesn't it work at all with one of them?
I can only reproduce with some specific programs. I don't know if I should post the specific details here, since they contain names to commercial products.
EDIT:
I went back to the documentation and found the following note at the end of the remarks section, could it be related? How?

An accessibility application can use SendInput to inject keystrokes
corresponding to application launch shortcut keys that are handled by
the shell. This functionality is not guaranteed to work for other
types of applications.

A:
It works in most programs, it needs a small delay for some, but doesn't work at all in one of them.

"Most programs" check the Alt key state from inside the mouse message handler with correct synchronization.  There are two correct ways:

*

*Look at the modifier flags in the message parameters (only applicable to Control and Shift, NOT Alt)

*GetKeyState()

"Needs a small delay for some" -- these programs check the Alt key state unsynchronized with the message delivery, probably with

*

*GetAsyncKeyState()
but it could also mean the mouse message handler sets a flag and then some later code calls GetKeyState()

"doesn't work at all in one of them"
This program doesn't use the OS input queue (and its abstraction of keyboard state) at all for the behavior you are after, it reads the Alt key from the true keyboard, for example using Raw Input, DirectInput or the HID API.  Usually you only see these techniques in games.
To make this "reads the true keyboard" program behave as if the Alt key is pressed, you'll need a USB keyboard simulator/driver sending real HID profile USB events, where the Raw Input portion of the OS will see them.  And the program will still be able to detect a difference between "Alt key on keyboard #1" vs "Alt key on keyboard #2"


text:
Q: MFSideMenu full size pan gesture I use MFSideMenu in my application, and i can show the menu using a pan gesture on the navigation bar only. I would like it to work on the whole screen, like on the facebook app.!

I've tried changing this line (l.39 in MFSideMenuManager.m)
[controller.navigationBar addGestureRecognizer:recognizer];

to this :
[controller.view addGestureRecognizer:recognizer];

but it just won't work.
Do you have any idea of what i should edit for it to work?
Thank you for your help

A: I finally succeeded making it work. The gesture is actually already implemented but working only if the menu is hidden. We have to remove 2 conditions to make sure it works both ways
There are two lines to edit in the MFSideMenuManager.m
In the gestureRecognizerShouldBegin: method
    if([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        if([gestureRecognizer.view isEqual:self.navigationController.view] &&
           self.navigationController.menuState != MFSideMenuStateHidden) return YES;

becomes
    if([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        if([gestureRecognizer.view isEqual:self.navigationController.view]) return YES;

In the navigationControllerPanned: method, just remove the if line
- (void) navigationControllerPanned:(id)sender {
    if(self.navigationController.menuState == MFSideMenuStateHidden) return;

    [self handleNavigationBarPan:sender];
}

becomes
- (void) navigationControllerPanned:(id)sender {
    [self handleNavigationBarPan:sender];
}

And it works!
It is not a really good practice to edit a library, but it is easy if you want to go further to add a boolean option to MFSideMenu to make it configurable.

A: I don't know the MFSideMenuManager but if the bar is draggable I expect it to have a UIPanGestureRecognizer with a line
[self.navigationController.navigationBar addGestureRecognizer:gestureRecognizer];

So what you do is replace the navigation bar with the view for the whole navigation controller
[self.navigationController.view addGestureRecognizer:gestureRecognizer];