text:
Q: How to replace default comments with custom HTML? I'm going to replace default list of comments and comment form with Facebook's comment box. As far as I know there is function wp_list_comments(). How can I replace this function with my custom one?
Update: I want completely ignore built-in WordPress comments.
When I try to add my code to the end of content, it works:
add_filter ('the_content', 'fbcommentbox', 100);

But the following code does not:
add_filter ('comments_template', 'fbcommentbox', 100);

A: Note that with the following:
add_filter ('comments_template', 'fbcommentbox', 100);

we expect fbcommentbox() to return the path to the new comments template file. The default is the path of comments.php.
If you create the fbcommentbox.php file in your theme, then you could try:
add_filter( 'comments_template', 'fbcommentbox', 100);

function fbcommentbox( $theme_template )
{
    // Path to our new comment template file
    $new_theme_template = get_template_directory() . '/fbcommentbox.php';

    // Override if it exsits
    if( file_exists( $new_theme_template ) )
        $theme_template = $new_theme_template;

    return $theme_template;
}

If the file fbcommentbox.php doesn't exists then the default one is loaded instead. For a child theme we would use get_stylesheet_directory().
Here's a shorter version:
function fbcommentbox( $theme_template )
{
    return locate_template( 'fbcommentbox.php' );
}

where the locate_template() does all the hard work.
Update
But you mentioned you wanted to override wp_list_comments() instead.
Here's a way to do that by changing the echo argument to false:
add_filter( 'wp_list_comments_args', function( $args )
{
    // Display fbcommentbox.php
    get_template_part( 'fbcommentbox' );

    // Disable output of wp_list_comments()
    $args['echo'] = 0;

    return $args;
} );

and output instead the fbcommentbox.php template.


text:
Q: changed index file, then I want search data to change in Solr Please understand, I can't speak English very well.
I have 3 servers. server1 make index file in NAS(Network Attached Storage), others two server used only search. and I use simple locktype in the solrconfig.xml.
<lockType>${solr.lock.type:simple}</lockType>

If the index file is changed by the server1, I want the search contents of other servers will be changed.
I set the index path of 3 servers all the same to the NAS.
first way.
I changed the index file on the server1, and used the reload URL to confirmed that the search contents of other server changed.

reload URL:
  http://127.0.0.1:9577/solr/admin/cores?action=RELOAD&core=core_name

but, Sometimes errors occur!
org.apache.lucene.store.AlreadyClosedException: this IndexWriter is closed
java.nio.file.NoSuchFileException: core's path/data/index/write.lock

I get an error even when I call reload URL again.

and, I looked for another way.
I changed the index file on the server1, and used the commit or softCommit URL.
However, it didn't work. The search contents of other servers has not changed.
Is there any good way to do this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Optionally passing values via kwargs to inner functions with default parameters I have a outer function foo that calls two inner functions, bar1 and bar2. Each inner function (bar) has default parameters. I'd like to be able to call foo and specify whichever parameters I want, and then use the inner function defaults for whichever parameters I don't specify. How do I do this?
Example:
def foo(**kwargs):
    print(bar1(kwargs['b1p1'], kwargs['b1p2'])
          + bar2(kwargs['b2p1'], kwargs['b2p2']))

def bar1(b1p1 = '', b1p2 = ''):
    return str(b1p1+b1p2)

def bar2(b2p1 = 0, b2p2 = 0):
    return str(b2p1 * b2p2)

foo(b1p1 = 'a', b1p2='b', b2p1 = 1, b2p2 = 3) #returns ab3
foo(b1p1 = 'a') #should return  a0
foo() #should return 0


text:
Q: How to make menu dropdown from DDL in AutoHotKey In VBA a ComboBox can be made to show/dropdown its list by below code.
ComboBox1.DropDown

How to make a DDL dropdown its menu like this in AutoHotKey?

A: In AHK, you have to send the control message manually using SendMessage with a message ID of 0x014F (which is the value of CB_SHOWDROPDOWN) using the following line:
SendMessage, 0x014F, 1, , , ahk_id %controlHwnd% ; CB_SHOWDROPDOWN = 0x014F

To hide the dropdown, just change the 1 to a 0 like so:
SendMessage, 0x014F, 0, , , ahk_id %controlHwnd% ; CB_SHOWDROPDOWN = 0x014F

This control message works on both DropDownList and ComboBox controls.
Note: When using SendMessage in AHK, it is best practice to add a comment identifying the message sent to prevent head-scratching later.
Explanation
Most programming languages (such as VBA) contain syntactic sugar that is out of the scope of AutoHotKey's primary focus. The line ComboBox1.DropDown in VBA sends a CB_SHOWDROPDOWN control message to the control referenced by ComboBox1. The value in this control message is a boolean that controls whether to show (TRUE) or hide (FALSE) the drop down menu.
CB_SHOWDROPDOWN is an unsigned integer and its value (along with the other command messages) can be extracted from the Windows SDK. For this particular control message, it was extracted from the winuser.h file as indicated on the control message reference page here.
Minimum Working Example
#NoEnv  ; Recommended for new scripts
SendMode Input  ; Recommended for new scripts
#SingleInstance Force ; ensures only one instance running

; AUTO-EXECUTE SECTION
; "hwndhColorChoice" stores the AHK control ID in the variable "hColorChoice"
Gui, Add, ComboBox, vColorChoice hwndhColorChoice, Red|Green|Blue|Black|White
Gui, Show
Return ; end auto-execute section

; Press F1 to show combo box options
F1::SendMessage, 0x014F, 1, , , ahk_id %hColorChoice% ; CB_SHOWDROPDOWN = 0x014F

; Exit program when GUI is closed
GuiClose:
GuiEscape:
ExitApp

Command References:

*

*GUI Controls § DropDownList

*SendMessage

*CB_SHOWDROPDOWN


text:
Q: Getting ant to run java file I am having trouble just creating something simple, and it does not seem that any website is clear on how to do this, and honestly I think it should be simple.
I have a bunch of java files for a project. I want to compile all of them, and then run each file with specific arguments.
Basically I want the order of operations to be something like this
javac prob1.java
javac prob2.java

java prob1 parameter
java prob2 parameter

But I want that in ant (build.xml).
I can do the compile part just fine with
<project default="compile">
    <target name="compile">
    <javac srcdir="." />
    </target>
</project>

I just can not get it to run say prob1 with an argument. I imagine this is extremely easy, but every solution I have found, does not seem to work. Also note prob1.class and prob2.class are in the same directory.

A: This should work:
<target name="run">
    <java classname="prob1">
       <classpath>
           <pathelement location="."/>
        </classpath>
        <arg value="parameter" />
    </java>
    <java classname="prob2">
        <classpath>
           <pathelement location="."/>
        </classpath>
        <arg value="parameter" />
    </java>
</target>


text:
Q: Event fired several times when i scroll down the page I try to display some data when the user scroll down the page but the ajax called is done at least 2 times and sometimes 4 times. Is there anyway to execute the ajax call only one time ? Thanks.
   $(window).scroll(function () {
        if ($(document).height() <= $(window).scrollTop() + $(window).height()) {
                $.ajax({
                type : "POST",
                url : $('#AjaxMoreStatus').attr("data-url"),
                dataType : "HTML",
                beforeSend: function() {
                    $('.spinner').show();
                },
                complete: function() {
                    $('.spinner').hide();
                },
                success : function (data) {
                    $('#AjaxMoreStatus').append(data);
                }
            });
        }
    });

A: When you use .scroll() event and when the window is scrolled, it gets fired multiple times. This is an expected behaviour. The best way is to use a timer, for like 500ms and wait for the browser to stop scrolling:
var tmr = 0;
$(window).scroll(function () {
  clearTimeout(tmr);
  $('.spinner').show();
  tmr = setTimeout(function () {
    if ($(document).height() <= $(window).scrollTop() + $(window).height()) {
      $.ajax({
        type : "POST",
        url : $('#AjaxMoreStatus').attr("data-url"),
        dataType : "HTML",
        beforeSend: function() {
          $('.spinner').show();
        },
        complete: function() {
          $('.spinner').hide();
        },
        success : function (data) {
          $('#AjaxMoreStatus').append(data);
        }
      });
    }
  }, 500);
});

This would also save your AJAX polling to server too many times. You may also take the contents of beforeSend() to the top of the AJAX call and timer.

A: Well this is a known issue and it is solved by a technique called debouncing logic.

What is Debouncing logic: Which Returns a function, that, as long as it continues to be invoked, will not be triggered.
   The function will be called after it stops being called for N
  milliseconds. If immediate is passed, trigger the function on the leading edge, instead of the trailing.

Debouncing logic:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
     var context = this, args = arguments;
     var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
     };
     var callNow = immediate && !timeout;
     clearTimeout(timeout);
     timeout = setTimeout(later, wait);
     if (callNow) func.apply(context, args);
  };
};

//target code/callback to be called on scroll/resize event
function callback() {
    clearTimeout(tmr);
   $('.spinner').show();
   tmr = setTimeout(function () {
     if ($(document).height() <= $(window).scrollTop() + $(window).height())  {
      $.ajax({
        type : "POST",
        url : $('#AjaxMoreStatus').attr("data-url"),
        dataType : "HTML",
        beforeSend: function() {
          $('.spinner').show();
        },
        complete: function() {
          $('.spinner').hide();
        },
        success : function (data) {
          $('#AjaxMoreStatus').append(data);
        }
    });
  }
}

//registering callback function to debouncing logic
$(window).scroll(function () {
     debounce(callback, 250);
}

Now using debouncing logic, not only you can solve your current problem but also you can stop worrying about when the user would stop scrolling the page so that you can call your target function, as it may go on for 500 milli seconds or even till 1 sec.
The above code is generic , so you dont have to make any assumptions about user interaction on your script.
Ref:https://davidwalsh.name/javascript-debounce-function


text:
Q: Easier way to solve a LES (only pen/paper, no calculator) I want to solve the following Linear Equation System with only pen and paper;
$$
470 = x_A - \frac{3}{10}x_B \tag{1}
$$
$$
940 = x_B - \frac{2}{10}x_A \tag{2}
$$
I attempt to solve for $x_A$ by inserting equation (2) into (1) and rewriting it, etc. I got something like;
$$
x_A=470 +\frac{3}{10}(940+\frac{2}{10}x_A) \Rightarrow \dots \Rightarrow x_A\frac{94}{100}=470+\frac{3}{10}940=470+\frac{2820}{10}
$$
Next I try to isolate $x_A$ and simplify the expression;
$$
\dots \Rightarrow x_A =\frac{100}{94}(470+\frac{2820}{10})=\frac{100}{94}(470+282)=\frac{100}{94}752
$$
This is where I get stuck. Have I dug myself into a difficult hole when there is a better/more efficient approach to solving this LES? Or am I just missing a good method to solve $x_A=\frac{100}{94}\cdot752$ to get it to 800?
Any insight into "how to think" here and how you solve it with just pen and paper is much appreciated.
(Solution: $x_A=800$, $x_B=1100$)

A: May be, it could be simpler to do $$470 = x_A - \frac{3}{10}x_B \implies4700=10x_A-3x_B\tag{1}$$
$$940 = x_B - \frac{2}{10}x_A \implies9400=10x_B-2x_A\tag{2}$$
Multiply $(1)$ by $10$ and $(2)$ by $3$ and add them together; this gives immediately $$75200=94 x_A\implies x_A=\frac{75200}{94}=800$$ Plug this in $(2)$ to get $x_B$

A: First notice $94=47\cdot 2$. You can simplify before adding/multiplying:
$$x_A\frac{94}{100}=470+\frac{3}{10}940\color{red}{=470+\frac{2820}{10}} \Rightarrow \\
x_A\frac{47\cdot 2}{100}=47\cdot 10+\frac3{10}\cdot 47\cdot 20 \Rightarrow \\
x_A\frac2{100}=10+\frac{60}{10} \Rightarrow \\
2x_A=1000+600 \Rightarrow \\
x_A=800.$$

A: What are your problems ?
$ x_A=\frac{100}{94}\cdot752$ is correct, since $752:94=8.$


text:
Q: ConTeXt: Wrong mathmatrix spacing between rows in startalign-environment When using a mathmatrix (e.g. for vectors) in between \startalign and \stopalign, the spacing between rows becomes too large. I'm running Mark IV and the problem exists on live.contextgarden.net as well.
Is there anything I can do about this?
MWE:
\setupmathmatrix[left={\left[\,}, right={\,\right]}]

\starttext

\startformula
  \startmathmatrix \NC 1 \NR \NC 2 \NR \NC 3 \NR \stopmathmatrix
\stopformula

\startformula \startalign
  \NC \startmathmatrix \NC 1 \NR \NC 2 \NR \NC 3 \NR \stopmathmatrix \NR
\stopalign \stopformula

\stoptext

which gives

Edit: Adding \noalign{\blank[-6pt]} between each row in the matrix solves my problem and I can do that programmatically, so I'll be fine. A nicer solution would be nice though.

A: This bug has been fixed once it was reported to the context mailing list. On the current beta (2013.09.01), I get the following correct output.


text:
Q: Compare columns in 2 Oracle 11g tables I have 2 tables in Oracle 11g one containing the actual source data and the other masked data.
The table has 1260000 rows approximately.
The column I am comparing is Varchar.
I am trying to check if all the data has been masked to value different from the original data.
I am performing a select query with 2 conditions on the join 1. with a unique row identifier 2. the value I am trying to compare.
The query never returns upon execution.
Is there a way to get an output where I can see the rows where the value is the same in both the table ?

A: This is how I understood the question.
For example, I created a "duplicate" of Scott's EMP table and "masked" names:
SQL> create table emp2 as select * From emp;

Table created.

SQL> update emp2 set ename = translate(ename, 'AEIOU', '98765');

14 rows updated.

SQL> select empno, ename from emp2 order by empno;

     EMPNO ENAME
---------- ----------
      7369 SM7TH
      7499 9LL8N
      7521 W9RD
      7566 J6N8S
      7654 M9RT7N
      7698 BL9K8
      7782 CL9RK
      7788 SC6TT
      7839 K7NG
      7844 T5RN8R
      7876 9D9MS
      7900 J9M8S
      7902 F6RD
      7934 M7LL8R

14 rows selected.

To check which names are different:
SQL> select a.empno, a.ename, b.ename
  2  from emp a join emp2 b on a.empno = b.empno
  3  where a.ename <> b.ename
  4  order by a.empno;

     EMPNO ENAME      ENAME
---------- ---------- ----------
      7369 SMITH      SM7TH
      7499 ALLEN      9LL8N
      7521 WARD       W9RD
      7566 JONES      J6N8S
      7654 MARTIN     M9RT7N
      7698 BLAKE      BL9K8
      7782 CLARK      CL9RK
      7788 SCOTT      SC6TT
      7839 KING       K7NG
      7844 TURNER     T5RN8R
      7876 ADAMS      9D9MS
      7900 JAMES      J9M8S
      7902 FORD       F6RD
      7934 MILLER     M7LL8R

14 rows selected.

SQL>

Or, in your case, as you'd want to see values that aren't changed, you'd modify line #3 to
where a.ename = b.ename


text:
Q: Cumulative Distribution Function problems Let $a$ and $b$ be two positive integers. Let also $X$ be a discrete random variable
varying in
$X(\Omega)=\{1, 2, \ldots, ab\}$ such that for every $x∈X(\Omega),P[X = x]=1/a - 1/b$.
a) What conditions should $a$ and $b$ satisfy?
b) Determine the cumulative distribution function $F$ of $X$. Compute $u$ such that
$F(u)=1/2$.
c) Determine $E(X)$. Find the values of $a$ and $b$ such that $E(X) = 7/2$.

A: Some hints: Remember that the sum over x of P[X=x] = 1.  Note that P[X=x] is not a function of x.  c) is trivial once you've solved a), so do a) first.


text:
Q: How to get the Polkadot address from the polkadot public key? Polkadot.js I tried @polkadot/util-crypto lib and @polkadot/keyring to convert, public key to polkadot address but no help.
Is there any method provided by the polkadot.js?
Steps on how to get the address will also work great.
Thank you

A: @polkadot/util-crypto exposes the function encodeAddress which can input your public key bytes/hex and output an SS58 encoded address. If you want to get the address for a specific network, like Polkadot, you need to provide a secondary parameter which is the SS58 Prefix for that network. In the case of Polkadot it is 0.
https://github.com/paritytech/substrate/wiki/External-Address-Format-(SS58)#address-type
For example:

let address = util_crypto.encodeAddress("0x263158a10b39debac59bd1239bc64fb4bd678f507814d24f59efd46279111c71", 0)

document.getElementById("output").innerText = address;
<script src="//unpkg.com/polkadot-js-bundle/polkadot.js"></script>

<div id="output"></output>


text:
Q: Why is there no insert() method for strings in Python? Lists already have an insert() method that works with indexes:
>>> someList = [1, 2, 4, 5]
>>> someList
[1, 2, 4, 5]
>>> someList.insert(2, 3)
>>> someList
[1, 2, 3, 4, 5]

If strings also have indexes, why not an insert() method for them too? Example below:
>>> someString = 'foobar'
>>> someString.insert(3, 'SPAM')
>>> someString
'fooSPAMbar'

A: Short answer: Because strings are immutable.
Every type in Python is either mutable (like a list, a dictionary, or a normal object) , or immutable (like tuples, strings, ints, ...).
That's why you can append, pop, and insert in and from lists, but not tuples.
When you do something like this:
a = "this"
a = a + "that"

a seems to have "changed" to "thisthat", but actually, the name a just points to a new string. You can observe that effect if you hand something to a function and try to modify it in the function: Mutable types will also change outside (although you should usually avoid these side-effects), while immutables won't:
a = 3
b = [3]
def change_a(something):
    something = 4
def change_b(something):
    something[0] = 4
change_a(a)
change_b(b)
print(a,b) # prints "3 4"

If you need to mutate strings, you might want to look into StringIO for Python 2, or io.StringIO for Python 3, respectively:
import io
def insert(s,where,what):
    whatlen=len(what)
    s.seek(0)
    cur=len(s.read())
    if cur < where:
        raise IndexError("Can't insert at position {}: Index out of bounds"
                .format(where))
    s.seek(where)
    r=s.read()
    s.seek(where+whatlen)
    s.write(r)
    s.seek(where)
    s.write(what)

s = io.StringIO("This is a test")

insert(s,5,"hello")
s.seek(0)
print(s.read()) #prints "This hellois a test"

A: Because strings are immutable.  You can't change the contents of a string.  You'd have to make a new string.

A: Because strings are decidedly immutable. As are tuples.

A: Traditional strings are immutable. You can actually use the deprecated MutableString to do this:
string = UserString.MutableString('foobar') # then insert, call string.insert(3, 'SPAM')

A: Hence List are a mutable we can make changes in a list. But Strings ar ean immutable one, we can append charaters in a string. But we cannot change the index position values in a string.


text:
Q: React listen to global Object callback I'm working on an SDK. It currently supports JavaScript however it needs to support React (& possibly Vue/Angular down the road).
It first loads the SDK via a script. Then modifies an element with the sdk-id. The user interacts with the element and the SDK fires a callback, AppNameSDK.callback(data). This all works fine on vanilla javascript however for React I'm having trouble figuring out how to call a callback within the React Component.
In short. How can I either
A) Call a React Components function/method from an externally loaded Object
or
B) Change an externally loaded objects function via a React Component
Example of Vanilla Code (no problems)

// Loads obj called AppNameSDK

Example of React Code (cannot access callback)
import React,{useEffect} from 'react';

const useScript = (url,loadFunc,errorFunc) => {
  useEffect(() => {
    const script = document.createElement('script');
    script.src = url;
    script.async = true;
    document.body.appendChild(script);
    script.addEventListener('load', function () {
      if(loadFunc !== undefined && typeof loadFunc === "function"){
        loadFunc();
      }
    });
    script.addEventListener('error', function (e) {
      console.log();
      if(errorFunc !== undefined && typeof errorFunc === "function"){
        errorFunc();
      }
    });

    return () => {
      if(document.body.contains(script)){
        document.body.removeChild(script);
      }
    }
  }, [url,loadFunc,errorFunc]);
};

const Test = () => {

  let scriptSrc = "https://example.com/sdk/v1/client-id";
  useScript(scriptSrc);

  // Need to figure out how to call this function
  const callback = (data) => {
    console.log("data",data);
  }

  return (

Test Component

  );
};

export default Test;


text:
Q: How to make a variable addressable by name as string in JavaScript? Is there a way to convert variable names to strings in javascript? To be more specific:
var a = 1, b = 2, c = 'hello';
var array = [a, b, c];

Now at some point as I go through the array, I need to get variable names (instead of their values) as strings - that would be 'a' or 'b' or 'c'. And I really need it to be a string so it is writeable. How can I do that?

A: Use a Javascript object literal:
var obj = {
    a: 1,
    b: 2,
    c: 'hello'
};

You can then traverse it like this:
for (var key in obj){
    console.log(key, obj[key]);
}

And access properties on the object like this:
console.log(obj.a, obj.c);

A: What you could do is something like:
var hash = {};
hash.a = 1;
hash.b = 2;
hash.c = 'hello';
for(key in hash) {
    // key would be 'a' and hash[key] would be 1, and so on.
}

A: Goint off of Triptych's stuff (Which Thanks)...

(function(){
  (createSingleton = function(name){  // global
    this[name] = (function(params){
      for(var i in params){
        this[i] = params[i];
        console.log('params[i]: ' + i + ' = ' + params[i]);
      }
      return this;
    })({key: 'val', name: 'param'});
  })('singleton');
  console.log(singleton.key);
})();

Just thought this was a nice little autonomous pattern...hope it helps!  Thanks Triptych!


text:
Q: Java generate circle without intersection of existing circles I have Circle structure :
public class Circle
{
    private int x;
    private int y;
    private int radius;

    private static final int color = Color.WHITE;

    public Circle(int x, int y, int radius)
    {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    public int getRadius()
    {
        return radius;
    }

    public int getY()
    {
        return y;
    }

    public int getX()
    {
        return x;
    }

    public int getColor()
    {
        return color;
    }
}

and store them in Stack<Circle>
I want to generate a new circle that have no intersection of other Circles in Stack
Following this answer I do next :
public Circle generateNew(Stack<Circle> circles)
{
    Circle circle = null;
    while (circle == null)
    {
        int x0 = new Random().nextInt(mMaxWidth);
        int y0 = new Random().nextInt(mMaxHeight);
        int R0 = new Random().nextInt(5) * 25;
        boolean isIntersect = !circles.isEmpty();
        for (Circle c : circles)
        {
            int x1 = c.getX();
            int y1 = c.getY();
            int R1 = c.getRadius();
            int d = (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);
            if (((R0 - R1) * (R0 - R1) <= d && d <= (R0 + R1) * (R0 + R1)))
            {
                isIntersect = true;
            }
        }
        if (!isIntersect)
        {
            circle = new Circle(x0, y0, R0);
        }
    }
    return circle;
}

But it no working. What i'm doing wrong?
Log after try to generate second Circle :
x0 = 496
y0 = 487
R0 = 100

x1 = 1121
y1 = 188
R1 = 100

A: Keep it simple
    boolean isIntersect = false;
    for (Circle c : circles)
    {
        int x1 = c.getX();
        int y1 = c.getY();
        int R1 = c.getRadius();
        int distanceSq = (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);
        if (distanceSq <= (R0 + R1) * (R0 + R1))
        {
            isIntersect = true;
            break;
        }

A: More refactoring using @Joop Eggen code:
public Circle generateNew(Stack<Circle> circles)
{
    while (true)
    {
        int x0 = new Random().nextInt(mMaxWidth);
        int y0 = new Random().nextInt(mMaxHeight);
        int R0 = new Random().nextInt(5) * 25;
        boolean isIntersect = false;
        for (Circle c : circles)
        {
            int x1 = c.getX();
            int y1 = c.getY();
            int R1 = c.getRadius();
            int distanceSq = (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);
            if (distanceSq <= (R0 + R1) * (R0 + R1))
            {
                isIntersect = true;
                break;
            }
        }
        if (!isIntersect)
        {
            return new Circle(x0, y0, R0);
        }
    }
}


text:
Q: Не работает getline при использовании контейнера vector Написал небольшую программку, а-ля "телефонная книга" на Си. Сейчас разбираюсь с STL-контейнерами и вот столкнулся с тем, что при использовании не работает ф-ия getline.
Вот сам код:
#include <iostream>
#include <vector>

using namespace std;

const int n = 10;

struct Entry
{
    string name;
    int ID;
};

int cin_entry(vector<Entry> &v);
int print_entry(vector<Entry> &v);

int main()
{
    vector<Entry> phone_book(n);
    cin_entry(phone_book);
    cout << endl;
    print_entry(phone_book);
}

int cin_entry(vector<Entry> &v)
{
    for (int i = 0; i < n; ++i)
    {
        //getline(cin, v[i].name);
        cin >> v[i].name;
        cin >> v[i].ID;
    }
}

int print_entry(vector<Entry> &v)
{
    for (int i = 0; i < n; ++i)
    {
        cout << i + 1 << ". " << v[i].name << " " << v[i].ID << endl;
    }
}

В чем проблема? Почему не работает getline, а cin работает? И как мне тогда (если getline не пашет), что бы я мог в одну строку ввести несколько слов через пробел?
A: @Hamsternik, если это ещё актуально, то ответ на ваш вопрос приблизительно такой:

действительно, operator>> оставляет в входном потоке символ новой строки '\n', поэтому следующий вызов getline(cin, v[i].name); опускается.

Если вы хотите, чтобы всё работало как надо, то вам необходимо очищать входной поток от этого символа:
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

А вообще, везде советуют не применять в связке operator>> и getline() из-за подобных вещей, пробуйте подобрать другие варианты ввода.
A: @Hamsternik, опять же если еще актуально.
Если не лениться, то лучше всего читать входной файл по строкам, а потом уже разбирать прочитанную строку.
Например, Ваша программа ввода телефонной книги может выглядеть так
#include <iostream>
#include <vector>
#include <string>

#include <stdlib.h>
#include <string.h>
#include <errno.h>

using namespace std;
#define SPACES " \t"

struct Entry {
  unsigned long long num;  // ведь на самом деле телефонные номера м.б. длинными
  string text;
};

int main(int ac, char *av[])
{
  Entry in;
  vector<Entry> v(1);
  string str;

  while (cout << "Enter Number Text: ", getline(cin, str)) {
    // анализ введенных данных
    if (str.find_first_not_of(SPACES) == string::npos)
      continue;  // просто ничего не ввели

    // дальше часть на Си, т.к. нормальное чтение числа из строки появилось только в С++11
    char *t;
    in.num = strtoull(str.c_str(), &t, 10);
    if (t == str.c_str() || !isspace(*t) || errno == ERANGE ||
        !t[strspn(t, SPACES)]) { // !t[strspn(...)] это проверка, что после номера есть текст
      errno = 0;
      cout << "Bad data\n";
      continue;
    }

    // уберем лидирующие пробелы из запоминаемого текста одной строкой
    in.text = t + strspn(t, SPACES);  // и здесь использовать Си короче
    v.push_back(in);
  }

  for (int i = 0; i < v.size(); i++)
    cout << v[i].num << ": " << v[i].text << '\n';

}


text:
Q: Deploy a backend application on a Windows Server I'm making an application in C# with VS 2012 that checks a database every 15 seconds and perform some actions when it finds data. Right now I've created a Console Application so I can debug it easely but during relese this application needs to run in a IIS server.
How can I do that? I've read this question but it looks like some sort of workaround because to run it I need to perform these steps. Right now I'm reading the docs about Windows Service Application, Is this the right way?
EDIT Sorry but I've never used Windows server before, so as people pointed out IIS is only a web server, the thing I need to do is run my application in a Windows Server environment

A: If your application is performing some data query and manipulation on the server then I would recommend the approach to host it in a windows service.
Some advantages to this are:

*

*The service will start and run independently of a user logging into the server.

*You can configure the service to recover should it experience an exception (ideally not!).

*The service will start automatically (if configured) when the server restarts.

*You can configure which user group (or user) the service should run under so you have a more granual approach to security.

*As it's running as a seperate process, you can monitor its memory and processor utilisation.

Debugging is slightly more cumbersome but not difficult, one approach I've used is to install the service locally, start it and then attach to it via the debugger. This question describes another approach I've also used.

A: IIS is a web-server and accordingly it should be used for hosting web applications.
Develop a windows service which does the job of checking the database in intervals and invoke a web service (which you can host in IIS)


text:
Q: How deobfuscate a javascript variable obfuscated to hexadecimal representation? I have the following code that probably was obfuscated using this site.
I want to know if there is a way to revert this code to original version before obfuscation.
 var _0x25e019 = _0x3409['uaQTyc'][_0x2ed933];
    if (_0x25e019 === undefined) {
        _0x3e0f4c = _0x3409['SqQRqd'](_0x3e0f4c);
        _0x3409['uaQTyc'][_0x2ed933] = _0x3e0f4c;
    } else {
        _0x3e0f4c = _0x25e019;
    }
    return _0x3e0f4c;
};

A: No, you can't.
According to obfuscator.io,

Can I recover the original source code from the obfuscated one?
No, it's impossible to revert the obfuscated code back to your original code, so keep the original safe.

A: The browser does it for you. See it here:


text:
Q: updating HTML in react/gatsby I'm trying to re render my HTML after I have clicked on a badge:
onClick={() => filterCategories(c.category)}

The code:
const BlogPage = props => {
  console.log(props);
//After I click on the button comes back with the correct posts.
  let posts =
    props.data.allContentfulPost !== undefined
      ? props.data.allContentfulPost.edges
      : props.data;
  const categoriesStyle = {
    marginBottom: '8px',
  };
  const filterCategories = category => {
    posts = posts.filter(p => p.node.category === category);
    BlogPage({ data: posts });
  };
  return(
     filterCategories(c.category)}
     role="button"
     onKeyDown={filterCategories}>
     <Badge value={c.category} category={c.category} color="#fff">
            {c.category}
      </Badge>

  )
}

So if I'm not mistaking I have to make use of setState, but when I try to use it I can't do it because is not a class and I will need a class to add the constructor as well right? The problem with this code is that it was writing by someone else using Gatsby and I'm new to React and Gatsby

A: I'd recommend you maintain the category in state and then filter posts based on that stateful category.
const BlogPage = props => {
  const [category, setCategory] = useState(null);
  const posts =
    props.data.allContentfulPost !== undefined
      ? props.data.allContentfulPost.edges
      : props.data;
  const categoriesStyle = {
    marginBottom: '8px',
  };
  const filterCategories = category => {
    setCategory(category)
  };

  // These are your filtered posts
  const filteredPosts = category ?
    posts.filter(p => p.node.category === category) :
    posts;

  return(
     filterCategories(c.category)}
     role="button"
     onKeyDown={filterCategories}>
     <Badge value={c.category} category={c.category} color="#fff">
            {c.category}
      </Badge>

  )
}


text: Q: Can Bremsstrahlung radiation produced as a result of electron-electron interaction? Can Bremsstrahlung radiation produced by the electron-electron interaction as e-e interaction can result acceleration due to coulomb repulsive force? If yes, how the energy of bremsstrahlung radiation produced by e-nucleus and e-e interaction can be compared?


text:
Q: Qtip-like bubbles in a Java Swing application I'm looking for something like Qtip (http://craigsworks.com/projects/qtip/) for my Java Swing application.

A: http://docs.oracle.com/javase/tutorial/uiswing/misc/trans_shaped_windows.html
http://jexp.ru/index.php/Java_Tutorial/Swing/JToolTip
Just combine both
Or try this
http://javabyexample.wisdomplug.com/component/content/article/55.html


text:
Q: ember-data model.save is not a function i have a page with button "CONFIRM NOW" where upon clicking i am getting it to save across network with an JSON REST adapter.
/accounts/chinboon@gmail.com/verification
/accounts/{email}/verification

But i am getting a "model.save is not a function" error.
Uncaught TypeError: model.save is not a function
    at Class.verifyEmail (index.js:19)
    at Router.triggerEvent (ember.debug.js:28654)
    at trigger (ember.debug.js:55917)
    at Router.trigger (ember.debug.js:57517)
    at Class.send (ember.debug.js:27844)
    at Class.send (ember.debug.js:31852)
    at ember.debug.js:11639
    at Object.flaggedInstrument (ember.debug.js:18475)
    at ember.debug.js:11638
    at Backburner.run (ember.debug.js:717)

templates/accounts/show/verification/index.hbs:

        <form {{action "verifyEmail" on="submit"}}>

Confirm your email now to complete the registration

            <button type="submit" class="btn btn-success">CONFIRM NOW</button>

        </form>

        You are receiving this email because ...

router.js:
import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType,
  rootURL: config.routerRootURL
});

// page route
Router.map(function() {
  this.route('accounts', function() {
    // /accounts/new
    this.route('new', function () {
      //this.route('success');
    });

    this.route('show', { path: '/:account_id' }, function() {
      // /accounts/1/confirmation
      this.route('confirmation');
      // /accounts/1/verification
      this.route('verification', function() {
        // /accounts/1/verification/success
        this.route('success');
      });
    });
  });
});

export default Router;

routes/accounts/show/verification/index.js:
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.createRecord('account-verification');
  },

  actions: {
    /* account email verification */
    verifyEmail() {
      var model = this.get('model');

      var self = this;

      <<<<<PROBLEM HERE, "MODEL.SAVE IS NOT A FUCTION">>>>>
      model.save().then(function(data) {
        // handle success
        // route user to success page
      }).catch((adapterError) => {
        console.log(adapterError);
      });
    }
  }
});

models/account-verification.js:
import DS from 'ember-data';

export default DS.Model.extend({
  email: DS.attr('string'),
  secretToken: DS.attr('string')
});

A: this.get('model') inside Route will return model function not the record you created through model method. so either you need to move this action to corresponding controller or use controllerFor and get the model from controller.
Move actions to controllers/accounts/show/verification/index.js file.
import Ember from 'ember';
export default Ember.Controller.extend({
    actions: {
        /* account email verification */
        verifyEmail() {
            var model = this.get('model');
            var self = this;
            model.save().then(function(data) {
                // handle success
                // route user to success page
            }).catch((adapterError) => {
                console.log(adapterError);
            });
        }
    }
});


text:
Q: How to pass volume to docker container? I am running the below docker command :
docker run -d -v /Users/gowthamkrishnaaddluri/Documents/dfki_sse/demo:/quantum-demo/ -it demo python3 /quantum-demo/circuit.py --res './'
I am trying to run the above command in python and I have the code as follows:
container = client.create_container(
image='demo',
stdin_open=True,
tty=False,
command="python3 /quantum-demo/circuit.py --res='./'",
volumes=['/Users/gowthamkrishnaaddluri/Documents/dfki_sse/demo', '/quantum-demo/'],
detach=True,
)
client.start(container=container.get('Id'))
I am not able to see the files which get generated when the python file(circuit.py) is run. The files get generated when I just run the docker command , when I use the container api the file is not seen in the directory. Am I doing something wrong on using the volumes in the client create container?
Thanks!
How can I rectify the above problem so that I can map the volume properly? Or please let me know how can I use docker volumes so that the file generated in the docker folder can be copied to the local directory( such as saved neural network model after training)
Thanks!

A: Hi  Hope you are doing well!
So instead of the list, you should use dict and also you should use another method. An example is below:
import docker

client = docker.from_env()
client.containers.run(
    image="python",
    auto_remove=True,
    detach=True,
    tty=False,
    stdin_open=True,
    volumes={
        # path on your machine/host
        "/Users/volodymyr/Development/sandbox/stackoverflow/file.py": {
            "bind": "/mnt/file.py",  # path inside the container
            "mode": "rw",
        }
    },
    command=["python", "/mnt/file.py", "-w", "world!"],
)

# file.py
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-w", "--word")
    args = parser.parse_args()

    print(f"Hello {args.word!s}.")

I tested this code on my machine and it works. (docker sdk version is 6.0.1)
Docs: https://docker-py.readthedocs.io/en/stable/containers.html


text:
Q: Simple dojo Tree with ObjectStore Can someone fix this simple dojo tree? Without ObjectStore it would work, but I need this store for further implementations.
myStore = new Observable(myStore);
var dataStore = new dojo.data.ObjectStore({ objectStore: myStore }); // I need this dataStore for further implementations.
var myModel = new dijit.tree.TreeStoreModel({
                    store: dataStore,
                    query: { id: 'world' }
                });

Here you find the Fiddle for it.

A: Since you're using an object store, I believe you need ObjectStoreModel instead of TreeStoreModel:
/*var myModel = new TreeStoreModel({
    store: myStore,//dataStore,
    query: { id: 'world' }
});*/

var myModel = new ObjectStoreModel({
    store: myStore,
    query: { id: 'world' }
});

The TreeStoreModel and ForestStoreModel classes are legacy models for dojo.data, while the ObjectStoreModel is for when you use dojo.store.
See if this fiddle works for you: http://jsfiddle.net/zawSX/52/


text:
Q: Java - Tomcat: Reload context.xml without restarting server I'm using spring mvc and tomcat as a server. I want to be able to change a jndi field that is Autowired(as String):
<jee:jndi-lookup id="someMessage" jndi-name="someMessage"/>

in one of the my services, that is referenced to conf/context.xml of Tomcat, that looks something like this:
<Environment name="someMessage" value="Change this." type="java.lang.String" />.

However, when I change the value on context.xml, this change is not reflected on my service managed by spring, unless I restart server. Is there anyway to reflect this change without restarting or redeploying war? I know there is a solution to include such a dynamic field in one of properties file and then use commons configuration library to reload the changes, but I'm looking for a solution to keep this field on my conf/context.xml...

A: I think that is not possible. Why don't use a property file or a static class?

A: As far as I know, it's impossible if you put it into the conf/context.xml of your tomcat home as the following doc shows:

*

*StandardContext.html#reload(): If the context.xml has changed, you should stop this Context and create (and start) a new Context instance instead. -- i.e. can't achieve by original context

*Reload Existing App: Reload an existing web application, to reflect changes in the contents of /WEB-INF/classes or /WEB-INF/lib. -- i.e. not reflect the change of context.xml

But you can define your app's /META-INF/context.xml, which will be packed into war and you can replace war without restart server.


text:
Q: Script out Agent job using asp c# or TSQL I have an asp application to start/stop/enable/disable/create/schedule SQL agent jobs. Now i want to add DELETE job functionality to it. before deleting i would like to take a backup of the job and store it in a table. Can somebody help me to how script out Agent jobs using C#?
I heard about using SMOs but im not aware of it. Please guide me.

A: You can do this using TSQL.
With SQL Server Management Studio, you can get a "master" script, for deleting and creating the job.
Open SQL Server Management Studio, right-click on your job, select "Script Job as" and then "DROP And CREATE to", or "DROP To".
A script is displayed in the query Result. You only have to customize the script.
Note : if you need more informatin about the job (for instance the GUIDs), follow this link : http://www.mssqltips.com/sqlservertip/2561/querying-sql-server-agent-job-information/.


text:
Q: How can we use minio storage as same as s3 url How can we use minio storage as same as S3. Is there any need to change the code of java spring boot?. Previous codes are aws related. I don't want to change the code, But i want to access the storage from another source. Is that possible with minio.

A: I assume, that you are using the aws-java-sdk s3client. Therefore you just need to set the endpoint-configuration (for example http://localhost:9000, if minio runs on port 9000 on your local machine)
For more infos about the endpoint-configuration, you can look here


text:
Q: How Stackoverflow Realtime Updates works? Here is the screenshot taken from questions tagged with PHP.

So, If I open this page and leave it without refresh for some minutes it appers
x questions with new activity
And when I click it, It display all latest updates. I want to write similar script for news updates. Is it using JavaScript setTimeout to poll the server and embed the updates to <div>?

A: websockets
StackExchange.realtime.init('ws://sockets.ny.stackexchange.com:80');

http://socket.io/


text:
Q: Ubuntu 12.04 slow performance Just installed Ubuntu 12.04 64-bit on my ACER 5742 laptop. The performance is really slow.
While browsing pictures in Google, occasionally my system just freezes for about 5 seconds. Also, installing applications takes a lot of time. For example, installing "Skype" took me about 30 min or so.
In October, I installed earlier version of Ubuntu, and that version did not display any of these symptoms, so my laptop isn't to blame. And, my laptop's specs aren't that bad:
Model: Acer 5742g
Processor: Intel Pentium P6200 2.13GHz (duo-core)
Graphics Card: AMD Radeon HD6370M, 512 MB
RAM/Memory: 6GB 1066Mhz
Hard drive:: 500GB (5200 RPM)
I tried both a USB HDD and my 5200 RPM 500GB HDD.
I installed all the drivers that were displayed in Additional Drivers. But still, there is no improvement in performance.
Is it better to just install earlier version of Ubuntu or what?

A: unity 3d (default ubuntu interface) probally is too heavy for you, try a diffrent Desktop Enviorment and Window Manager, like LXDE, or XFCE
you can get a lxde enviorment with your current install by installing the lubuntu-desktop package
sudo apt-get install lubuntu-desktop

or for xfce- xubuntu-desktop
sudo apt-get install xubuntu-desktop

you could also try gnome-panel package for a more traditional pre 11.04 like interface (like gnome2)

A: Another alternative: Try to change unity 3d to 2d by clicking on the "unitysymbol" at the loginscreen (next to your login name).
Malte

A: You installed the drivers: That's the problem. AMD has had bad driver support for Linux and Ubuntu since the beginning of the ATi Radeon chipset back in 2000. Common complaints after installing AMD/ATi graphical drivers are: slow performance, slow and/or delayed compiz (visual effects) actions, and just bad system performance in general. Uninstall the drivers immediately with the Additional Drivers tool and reboot. You can install CompizConfig Settings Manager in the Ubuntu Software Center to handle any advanced graphical changes or alterations you want to make to your system.


text:
Q: How to create documentation for a package with roxygen2 in a language different from English? I am trying to create documentation in Russian but get "Warning: unable to re-encode" and a kind of mess instead of documentation like "<8e>..."
Is it possible to generate documentation with roxygen2 in a language different from English?


text:
Q: Has the behavior for DataAnnotations in asp.net mvc 3 changed? I have a Model with a property
[ReadOnly(true)]
public decimal BodyMassIndex { get; private set; }

In my View when I call
@Html.EditorForModel()

I still get a standard editable textbox for that property
Why is this? if the textbox is still editable whats the point of this DataAnnotation Attibute?
Brad Wilson's post

A: That is not a DataAnnotation attribute. Notice it's in the System.ComponentModel namespace. Data Annotations are in the System.ComponentModel.DataAnnotations namespace.
However, this is a case where we could consider supporting it. But what exactly did you expect to happen and why do you want this?

A: AFAIK the ReadOnlyAttribute is for property of class. From MSDN
 Members that are marked with the ReadOnlyAttribute set to true or that do not have a Set method
 cannot be changed. Members that do not have this attribute or that are marked with the
 ReadOnlyAttribute set to false are read/write, and they can be changed. The default is No.

So you use this inside your classes to prevent modification to the properties. (at least the meaning I give to that attribute)
If you want a textbox readonly use something like that
 @Html.TextBox("MyText", "my text", new { @readonly="readonly" })

the @ first of readonly tell the compiler to bybass the reserved word

A: you can use
@Html.TextBoxFor(x=> x.ModelProperty, new { @readonly="readonly"})

A: From what I understand of your question and the comments on other answers, you simply want to display the BodyMassIndex, not have it as editable.
If this is the case, use @Html.DisplayFor rather than @Html.EditorFor.

A: This works in Vs2013 C# with Bootstrap 3.

                @Html.LabelFor(model => model.PasswordHash, htmlAttributes: new { @class = "control-label col-md-3" })

                    @Html.EditorFor(model => model.PasswordHash, new { htmlAttributes = new { @class = "form-control", @readonly="readonly" } })
                    @Html.ValidationMessageFor(model => model.PasswordHash, "", new { @class = "text-danger" })


text:
Q: Mockito runnable: wanted but not invoked? I want to make sure I'm not doing something terribly wrong before I submit a bug report.  This is really weird.  The setup:
robolectric 3.0; mockito 1.10.19
Unit under test:
public BbScrollView( Context context ){
  this( context, null );
}

public BbScrollView( Context context, AttributeSet attrs ) {
  super( context, attrs );

  mScrollTask = new Runnable() {

    public void run() {
      checkForStopped();
    }
  };
}

public void checkForStopped(){
  int newPosition = getScrollY();
  // the rest is irrelevant , but I hit a breakpoint here.
}

public void startScrollTask() {
  mInitialPosition = getScrollY();
  postDelayed( mScrollTask, mTimeUntilNextCheckForStopped );
}

The test:
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class BbScrollViewTests {

  @Test
  public void test_startScrollTask(){
    BbScrollView uut = spy( new BbScrollView( RuntimeEnvironment.application ) );

    // This calls the method above that enqueues the runnable
    uut.startScrollTask();

    // Robolectric runs the runnable
    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    // I can hit a breakpoint inside this method but verify() fails
    verify( uut ).checkForStopped();
  }
}

The test fails with:
Wanted but not invoked:
bbScrollView.checkForStopped();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:62)

However, there were other interactions with this mock:
bbScrollView.startScrollTask();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

bbScrollView.getScrollY();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

bbScrollView.$$robo$getData();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

bbScrollView.postDelayed(
    com.myapp.android.BbKit.view.BbScrollView$1@7f830761,
    100
);
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

bbScrollView.$$robo$getData();
-> at com.myapp.android.BbKit.test.view.BbScrollViewTests.test_startScrollTask(BbScrollViewTests.java:58)

I repeat:  I hit breakpoints inside the method that verify() checks but the test fails.  I've also tried creating a dummy method inside of checkForStopped() and verifying on that to no avail.  I've also tried 1000ms thread.sleep on either side of the robolectric UI thread call.  My guess is something is going on with an interaction between robolectric's and mockito's reflection stuff?

A: You've caught a really fun bit of expected-but-unintuitive behavior, based on this Mockito principle: To create a spy, Mockito makes a shallow copy of the original object.
When you create the anonymous inner Runnable in the constructor, the Runnable contains an implicit reference to BbScrollView.this, your original BbScrollView object. Then, you make a copy as you create the spy, and the reference to your original BbScrollView persists. This means that your call to checkForStopped happens to the original object that Mockito can't observe, not the spy.
One way to fix this is to move your anonymous inner Runnable creation to your startScrollTask method, invoked on the spy, so this refers to the spy. When the Runnable is run, it will call methods on the spy instead of the real object, allowing Mockito to intercept and verify the call.


text:
Q: How to change product status from sql using SKU I need to disable and enable a huge quantity of products filtering by sku and the easiest solution seem to be through Sql query but i have some issues to find the right code
For example i need to disable 10000 products Sku: 001, 002, 003, 004, etc... i've found the right code for magento 1.9 but for magento 2 it's not working

A: To disable product by using SKU. First of all find the attribute_id value for status.
For find the correct attribute_id run this command in sql
select `eav_attribute`.`attribute_id` AS `attribute_id`, `catalog_product_entity_int`.`entity_id` AS `entity_id`, `catalog_product_entity_int`.`value` AS `value`, `catalog_product_entity`.`sku` AS `sku` from ((`eav_attribute` join `catalog_product_entity_int` on ((`eav_attribute`.`attribute_id` = `catalog_product_entity_int`.`attribute_id`))) join `catalog_product_entity` on ((`catalog_product_entity_int`.`entity_id` = `catalog_product_entity`.`entity_id`))) where ((`eav_attribute`.`attribute_code` = 'status') and (`catalog_product_entity_int`.`value` = 1))

The first value (for me was 97 ) is the correct attribute_id to replace at XXX
Copy the Attribute id and paste it in the SQL query run it in phpMyAdmin.
UPDATE catalog_product_entity_int a, catalog_product_entity b
SET a.value = "2"
WHERE b.entity_id = a.entity_id
AND b.sku LIKE '%SKU%'
AND a.attribute_id = **XXX**

After running the query Login to your admin and go to
System > Cache Management - >  Clear Cache
System > Index management > Rebuild Catalog Index
Also
You can also change status massively via products grid: check the boxes for items -> Actions - Change status -> Enable/Disable


text:
Q: JS Change CSS Nested tr I am looking to do this:
.LoanAppLine:nth-of-type(5) tr {
...
}

but in JavaScript. I tried this but am not sure how to get it to work.
document.getElementsByClassName('LoanAppLine')[5] tr.style.display = 'none';

I just want to change the CSS in the nested tr's.

A: You can use querySelector() instead of getElementsByClassName(). The newer querySelector() returns the first element that matches the specified CSS selector. You could use:
document
  .querySelector('.LoanAppLine:nth-of-type(5) tr')
  .style
  .display = 'none'

If you have more than one element, you can use querySelectorAll() instead which returns a NodeList (a list of elements that matches your selector). NodeLists have a forEach() method you can use to iterate over the elements:
document
  .querySelectorAll('.LoanAppLine:nth-of-type(5) tr')
  .forEach(el => el.style.display = 'none')

A: You can use document.querySelectorAll to get all elements matching a selector and use forEach to loop over it.
document.querySelectorAll(".LoanAppLine:nth-of-type(5) tr").forEach(x => x.style.display = "none");


text:
Q: Trend line and slope (R) I'm trying to study this protein interaction net. I need to do a plot of the degree distribution of the edges (last lines of the code), but I'm not able to make a trend line and the slope (last line of the code). Can someone help me please?
    install.packages("igraph")
    library("igraph")
    tfile<-tempfile()
    download.file("http://pdg.cnb.uam.es/pazos/tmp/Yeast_int.txt", tfile)
    datosraw <- subset(read.delim(tfile, sep="\t", header=F, stringsAsFactors = F), !is.na(V3) & V3!="" & V3!="METHOD")
    names(datosraw)<-c("orf1","orf2","method")
    datos<-split(datosraw,datosraw$method)
    df.y2h <- graph.data.frame(d = datos$Y2H[1:5125,c(1,2)], directed = FALSE)
    deg.dist.df.y2h <- degree.distribution(df.y2h)
    plot(deg.dist.df.y2h, xlab="k", ylab="P(k)", main="Y2H")
    plot(deg.dist.df.y2h, xlab="log k", ylab="log P(k)", main="Y2H", log = "xy", asp)
    abline(lm(deg.dist.df.y2h))

A: You are placing abline on the plot done on log10-log10 scale. Here's one way of doing it
Your code
library("igraph")
tfile<-tempfile()
download.file("http://pdg.cnb.uam.es/pazos/tmp/Yeast_int.txt", tfile)
datosraw <- subset(read.delim(tfile, sep="\t", header=F, stringsAsFactors = F), !is.na(V3) & V3!="" & V3!="METHOD")
names(datosraw)<-c("orf1","orf2","method")
datos<-split(datosraw,datosraw$method)
df.y2h <- graph.data.frame(d = datos$Y2H[1:5125,c(1,2)], directed = FALSE)

The rest can be wrapped in to a helper function
plot_degree_distribution = function(graph) {
  # calculate degree
  d = degree(graph, mode = "all")
  dd = degree.distribution(graph, mode = "all", cumulative = FALSE)
  degree = 1:max(d)
  probability = dd[-1]
  # delete blank values
  nonzero.position = which(probability != 0)
  probability = probability[nonzero.position]
  degree = degree[nonzero.position]
  # plot
  plot(probability ~ degree, log = "xy", xlab = "Degree (log)", ylab = "Probability (log)",
       col = 1, main = "Degree Distribution")
  abline(lm(log10(probability) ~ log10(degree)))
}

plot_degree_distribution(df.y2h)


text:
Q: Correct way of specifying a given date in T-SQL I am writing some T-SQL which needs to enforce a minimum date value onto some null fields:
DECLARE @epoch DATETIME;
set @epoch='1900-01-01';
select min = ISNULL(ValidFromDate,@epoch)

Is the string '1900-01-01' always going to return a datetime of Jan 1 1900 in any environment or will SQL server try to parse the string according to local culture rules?
If that's not good enough, what is the recommended way of specifying a particular date/time in T-SQL?

A: The best format for string-based dates is the ISO-8601 standard format.
For DATETIME variables and columns, this is either YYYYMMDD (for dates without time; without any dashes!) or YYYY-MM-DDTHH:MM:SS (date + time).
Contrary to popular belief, YYYY-MM-DD for DATETIME variables is NOT language-/dateformat-independent! If you try this, the second CAST will result in an error:
SET LANGUAGE us_english
SELECT CAST('2011-07-20' AS DATETIME)

SET LANGUAGE british
SELECT CAST('2011-07-20' AS DATETIME)

but this will work:
SET LANGUAGE british
SELECT CAST('20110720' AS DATETIME)

This is the best format since it's indepdendent of your language and dateformat settings in SQL Server.
For SQL Server 2008 and columns of type DATE (just date - no time), the format can also be YYYY-MM-DD (with the dashes) and that works for all settings, too.
Why there is such a difference between DATE and DATETIME is beyond me - that's just the way it is for now!
See Tibor Karaszi's excellent The Ultimate Guide to the DateTime data types for even more details and examples.


text:
Q: Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it When I do...
Select TO_CHAR (date_field, 'Month DD, YYYY')
from...

I get the following:
July      01, 2011
April     01, 2011
January   01, 2011

Why are there extra spaces between my month and day?  Why doesn't it just put them next to each other?

A:
Why are there extra spaces between my month and day? Why does't it just put them next to each other?

So your output will be aligned.
If you don't want padding use the format modifier FM:
SELECT TO_CHAR (date_field, 'fmMonth DD, YYYY')
  FROM ...;

Reference: Format Model Modifiers

A: You should use fm element to delete blank spaces.
SELECT TO_CHAR(sysdate, 'fmDAY DD "de" MONTH "de" YYYY') CURRENT_DATE
FROM   dual;

A: if you use 'Month' in to_char it right pads to 9 characters; you have to use the abbreviated 'MON', or to_char then trim and concatenate it to avoid this. See, http://www.techonthenet.com/oracle/functions/to_char.php
select trim(to_char(date_field, 'month')) || ' ' || to_char(date_field,'dd, yyyy')
  from ...

or
select to_char(date_field,'mon dd, yyyy')
  from ...

A: SQL> -- original . . .
SQL> select
  2  to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ) dt
  3  from dual;

DT
----------------------------------------
Friday    the 13th of May      , 2016

SQL>
SQL> -- collapse repeated spaces . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  * *', ' ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May , 2016

SQL>
SQL> -- and space before commma . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  *(,*) *', '\1 ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May, 2016

SQL>
SQL> -- space before punctuation . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  *([.,/:;]*) *', '\1 ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May, 2016

A: try this:-
select to_char(to_date('01/10/2017','dd/mm/yyyy'),'fmMonth fmDD,YYYY') from dual;

select to_char(sysdate,'fmMonth fmDD,YYYY') from dual;

A: select to_char(sysdate, 'DD-fmMONTH-YYYY') "Date" from Dual;
The above query result will be as given below.
Date
01-APRIL-2019


text:
Q: Vue / Laravel - SPA performance I noticed that while using a REST client like insomnia, I'm getting a high ms while performing a post for login.

Also my app.js is currently sitting at 2.43 MB with just these lines.
window.Vue = require('vue')

import Vue from 'vue'
import Vuetify from 'vuetify'
import VueRouter from 'vue-router'
import NProgress from 'vue-nprogress'
import 'vuetify/dist/vuetify.min.css'

import App from './App.vue'
import { router } from './routes.js'

Vue.use(Vuetify)
Vue.use(VueRouter)
Vue.use(NProgress)

Vue.component('base-table', require('./components/BaseTable.vue').default)

const vuetify = new Vuetify();
const nprogress = new NProgress();

new Vue({
  el: '#app',
  render: h=>h(App),
  vuetify,
  router,
  nprogress
});

I'm fairly new with Vue + Laravel SPA and I don't know if this is considered as very bad for loading an application. Will minimizer greatly reduce the file size and boost loading speed when it's ready for production?


text:
Q: Podio Item task_count not passed in Filter items in the ruby as php library I see the task_count being referenced as an attribute however when doing the API call (only tested in ruby) I always get task_count = null.
Can this be fixed? Or another way to quickly get the task count for a larger amount of items?

A: There is a call to get tasks.
https://developers.podio.com/doc/tasks/get-task-count-38316458
Its returning perfect count for me. I have done the same with Java SDK.It take ref type and id as a parameter.
In your case reftype = Item and id = item id.
Let me know if it helps or you need more details.


text:
Q: Why does my figure title move when we increase the number of subplots? I've plotted a graph containing many subplots, by using matplotlib in Python 3. I inserted the figure title by using fig.text() rather than fig.suptitle() because I need to place the title in the middle, on the right, and on the left. You can see this result in the next url (number of rows = 6):
RESULT OF PLOT: N-rows = 6
Now, I have some problems when the number of subplots increase or decrease. The space between the title and the top of the upper subplots decrease or increase. The x label has the same behavior as well.
For instance, when number of rows = 2 that space decrease, as you can see in the next picture:
RESULT OF PLOT: N-rows = 2
In the other hand, when number of rows = 15 that space increase, as you can see in the next picture:
RESULT OF PLOT: N-rows = 15
I want that the space of the title and the x axis label don't change when I increase or decrease the number of rows. Any suggestion? Thank you.
This is my MWE:
import matplotlib.pyplot as plt

n_rows = 15
n_cols = 2
fig, axs = plt.subplots(n_rows, n_cols, figsize=(7*n_cols,1*n_rows), sharex="col", sharey="row",
                        gridspec_kw={'hspace': 0, 'wspace': 0})
# labels
fig.text(0.513, 0.06, 'Time UTC', ha='center', va='center', fontsize=14)
fig.text(0.09, 0.5, 'S4', ha='center', va='center', rotation='vertical', fontsize=14, color='b')
fig.text(0.94, 0.5, 'Elevation Angle', ha='center', va='center', rotation=-90, fontsize=14, color='g')
# title
fig.text(0.513, 0.91, 'S4', ha='center', va='center', fontsize=17)
fig.text(0.32, 0.91, 'Jicamarca', ha='center', va='center', fontsize=17, color='r')
fig.text(0.12, 0.91, '2020/07/16', ha='left', va='center', fontsize=17)
fig.text(0.9, 0.91, 'Scintillation index', ha='right', va='center', fontsize=17)


text:
Q: Is C++ compiler allowed to store function ptr in register before its arguments are evaluated? My collegues and I were fighting a rather weird bug in an app we're developing. Eventually we got it fixed, but we are still unsure if what the compiler was doing is legit or not.
Assuming we have code like this:
class B {
public:
    virtual int foo(int d) { return d - 10; }
};

class C : public B {
public:
    virtual int foo(int d) { return d - 11; }
};

class A {
public:
    A() : count(0) { member = new B;}
    int bar() {
        return member->foo(renew());
    }

    int renew() {
        count++;
        delete member;
        member = new C;
        return count;
    }
private:
    B *member;
    int count;
};

int square() {
    A a;
    cout << a.bar() << endl;
    return 0;
}

The Visual Studio x86 compiler, for function A::bar, generates something like this when compiled with /O1 (You can check the full code on godbolt):
        push    esi
        push    edi
        mov     edi, ecx
        mov     eax, DWORD PTR [edi]  ; eax = member
        mov     esi, DWORD PTR [eax]  ; esi = B::vtbl
        call    int A::renew(void)    ; Changes the member, vtable and esi are no longer valid
        mov     ecx, DWORD PTR [edi]
        push    eax
        call    DWORD PTR [esi]       ; Calls wrong stuff (B::vtbl[0])
        pop     edi
        pop     esi
        ret     0

Is this optimization allowed by the standard or is it an undefined behaviour?
I was unable to get similar assembly with GCC or clang.

A: Just for perfect clarity, here's the Order of evaluation document Jarod42 already linked, and the relevant quote:

14) In a function-call expression, the expression that names the function is sequenced before every argument expression and every default argument.

So we should read the statement
return member->foo(renew());

as
return function-call-expression;

where function-call-expression is
{function-naming-expression member->foo} ( {argument-expression renew()} )

so, the function-naming-expression member->foo is sequenced-before the argument expression. The doc already linked says

If A is sequenced before B, then evaluation of A will be complete before evaluation of B begins.

so we have to completely evaluate member->foo first. I think it should expand like
// 1. evaluate function-naming-expression
auto tmp_this_member = this->member;
int (B::*tmp_foo)(int) = tmp_this_member->foo;

// 2. evaluate argument expression
int tmp_argument = this->renew();

// 3. make the function call
(tmp_this_member->*tmp_foo) ( tmp_argument );

... which is exactly what you see. This is the sequencing required by C++17, and prior to that the sequencing and behaviour were both undefined.

tl;dr the compiler is right, and that code would be nasty even if it worked.

A: Whereas order of evaluation is implementation specific prior to C++17, C++17 imposes some ordering, see evaluation order.
so in
this->member->foo(renew());

renew() might be called before evaluating this->member (prior C++17).
To guaranty order prior, C++17, you have to split into several different statement:
auto m = this->member;
auto param = renew(); // m is now pointing on deleted memory
m->foo(param);        // UB.

or, for the other order:
auto param = renew();
this->member->foo(param);


text:
Q: javascript function is not invoked at the first time onclick I have a following code:
$this->content->text  .=
         '

            Click Here

';

return $this->content;

When I login and click "Click Here" the onclick event doesn't trigger. It works at the second click. However, after that (before logging out), single click works just fine.
What should be the potential problem?

A: try
Click Here
and then , return false; in the pop() function , or wrap it in an other function that returns false. that might do the trick.


text:
Q: Complex htaccess rewrite for variable url I have a shopping cart which has SEO links, i'm creating a option to refine the search option within the results displayed.
This is an example of what i am trying to achieve
Customer display a list of products
www.example.com/products/Drives-Bluray/view/list/category_id/30/sub_category/167
Then if customer want to search by manufacturer as well
www.example.com/products/Drives-Bluray/view/list/category_id/30/sub_category/167?manufacturer=LG
or if customer wants to order by manufacturer and price
www.example.com/products/Drives-Bluray/view/list/category_id/30/sub_category/167?manufacturer=LG&orderby=price
In my htaccess I currently have;
RewriteRule view/([a-z]+)/category_id/([0-9]+)/sub_category/([0-9]+)$ com_products.php?view=$1&category_id=$2&sub_category=$3 [L]

I've searched and can't seem to figure out how to have multiple variables, which may or may not be there using RewriteCond.
Can someone please give an example on the way forward with this?
Thanks
Jay

A: To be able to append a query to the end of your rewritten URL, you'll want to use the QSA flag. This allows you to have that query string at the end of the pretty URL starting with ? rather than &.


text:
Q: how can I select the array with the oldest time I have these arras
[0] => Array
        (
            [TEAM] => Array
                (
                    [id] => 5
                    [name] => localhost

                )

            [Registraion] => Array
                (

                     [Registered] => 2011-09-20 09:20:51
                )

        )

[1] => Array
        (
            [TEAM] => Array
                (
                    [id] => 6
                    [name] => localhost

                )

            [Registraion] => Array
                (

                     [Registered] => 2011-09-20 09:30:51
                )

        )

[2] => Array
        (
            [TEAM] => Array
                (
                    [id] => 7
                    [name] => localhost

                )

            [Registraion] => Array
                (

                     [Registered] => 2011-09-20 09:40:51
                )

        )

I want to get this
[0] => Array
            (
                [TEAM] => Array
                    (
                        [id] => 5
                        [name] => localhost

                    )

                [Registraion] => Array
                    (

                         [Registered] => 2011-09-20 09:20:51
                    )

            )

as that person is the oldest to register.
How can I get the oldest registration value?
thanks

A: $oldestkey = null;

foreach (array_keys($array) as $key) {
    if (isnull($oldestkey) || ($array[$key]['Registraion']['Registered'] < $array[$oldestkey]['Registraion']['Registered']) {
         $oldestkey = $key;
    }
}

Note that your key Registraion is mis-spelled, I'm guessing it should be Registration? Also note that this code will not handle the case where there's multiple keys with the same registration time. It'll pick out the FIRST oldest time and return the key for that record. Any duplicate times will be ignored.

A: Loop each item
 $oldest = $arr[0];
 foreach($array as $arr){
      if($arr["Registration"]["Registered"] < $oldest["Registration"]["Registered"])
            $oldest = $arr;
 }

Please use the time comparision while comparing

A: function getOldestRecord($ar)
{
   $last_id;
   $last_time = 0;
   foreach($ar as $key => $val)
   {
      $time_stamp = strtotime($val['Registration']['Registered']);
      if($time_stamp > $last_time)
      {
         $last_time = $time_stamp;
         $last_id = $key;
      }
   }
   return $ar[$last_id];
}

function above accepts your array, then loops through it and compare dates, and it will return last registered user.


text:
Q: Is the inverse of a one-to-one, total function itself one-to-one and total? The problem, from Boolos and Jeffrey's Computability and Logic, states the following definitions:

*

*"If a function $f(a)$ (from $A$ to $B$) is defined for every element $a$ of $A$, then it is called total"

*"A correspondence between sets $A$ and $B$ is a one-to-one, total function from $A$ onto $B$."

*"Two sets are said to be equinumerous if and only if there is a correspondence between $A$ and $B$."
Then, it asks the reader to show that if $A$ is equinumerous with $B$, then $B$ is equinumerous with $A$. So far, the work I've done is to show that, for a function $f : A \rightarrow B$, there exists a function $f^{-1} : B \rightarrow A$ that is onto (which follows from $f$ being total), and one-to-one (which follows from $f$ existing). However, it remains to be shown that $f^{-1}$ is total. This seems to require that $f$ is onto, which doesn't seem to be stated by the problem. I would appreciate any hints on how to show that $f^{-1}$ must be total, given the constraints.

A: It is common to write that the function is "onto $B$" to mean that it is surjective (onto). Otherwise, we would say that a function $f$ is a [total] function "from $A$ to $B$".
So when it says that it is a total one-to-one, function from $A$ onto $B$ it is telling you (i) the domain is all of $A$; (ii) the function is one-to-one; and (iii) the image is all of $B$.


text:
Q: SQL Server identity specification not sequential I have noticed that SQL Sever (2008 Express) is randomly jumping forwards when it is inserting  auto-incrementing identity specifications.
For example one of my columns "HitStat_ID" will insert sequentially 15, 16, 17, 18, then all of a sudden, it will decide to jump to, say 1012, 1013, 1014.... then 9120, 9121 etc.
It doesn't matter really, so long as they are unique (which they are) but why would it do this? Its doing it in more than one table too.
The odd thing is that is only done this over the last week or so, but the application has been in development for months!
I'm working in ASP.NET VB.
This is the insert (in this case):
sql = "INSERT INTO [HitStats] ([PageName], [Date_and_Time], [User_ID]) values ('Home',
'" + TheDateTime + "', '" + Session("User_ID") + "')"
Dim dbcmd As SqlCommand = New SqlCommand(sql, dbconn)
dbcmd.ExecuteNonQuery()
dbcmd.Dispose()

Please don't go on about SQL injection - its not going to happen!

A: If you're using an application and transactions, when you rollback a transaction you will loose that Auto-incrementing number generated.
Also if you make some inserts and rollback them.
See more here
Also, if you delete data, you won't get again that numbers generated, unless you do a reseed.
See here

A: Such gaps would not be uncommon if the database is being replicated and Automatic Identity Range Management is being used.
What happens is the blocks of identity values are handed to each server involved in replication, so that they can hand out identity values without having to communicate with the other servers. Once a block has been used up on a server, it will "jump" to the next block that has been allocated to it, which will likely be for a much higher range of values.

A: +1 on @ElVieejo regarding "failed inserts". Another possibility, someone or something might be adding specific values (SET IDENTITY_INSERT ON) -- this might explain the large gaps.

A: Identity is not guaranteed to be incremented by 1. See "consecutive values" on Microsoft's page. Also see: Identity increment is jumping in SQL Server database.


text:
Q: How to parse json data based on dynamic id with jquery in codeigniter I need to fetch the country code of the selected country ID from dropdown
I have  ajax call which returns a json data:
function fetchCountryCode(sel) {

    var country_id = sel;
    var data = "country_id=" + country_id
   // var baseurl =
    alert(country_id);
    $("#code").html("");
    if (country_id.length > 0) {

        $.ajax({
            type: "POST",
            url: "<?php echo base_url();?>index.php/register/code",
            data: "country_id=" + country_id,
            dataType: 'json',
            success: function(html) {
                $("#code").html(html);

            }

        });
    }

}

Controller function parsing the data:
public function code($countryId)
{
    // Get countries list
    $cId = $_POST['country_id'];
    //echo "<pre>"; print_r($cId); exit;
    $code = file_get_contents($this->config->config['api_url'] . 'countries');
    $rawdata = json_decode($code);
   // echo "<pre>"; var_dump($rawdata);

    foreach($rawdata as $item){
        print_r($item->code);
    }
 exit;
    $data['countries'] = $this->load->view('login/code', $code);
}

Its is giving me all the countries data but i need to fetch the selected id's data only. I am new to it pls guide

A: You can create an array with the only matching id and then echo the result as json.
$result = array() ;

foreach($rowdata as item){
    if($item->id == $cId)
           array_push($result, $item) ;
}

echo json_encode($result);


text:
Q: JavaFX - Wrapping FXML to Java Class Controller I have a FXML file that has a TreeView control:
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="500.0" xmlns:fx="http://javafx.com/fxml" fx:controller="test.MyControllerClass">

<TreeView fx:id="locationTreeView" layoutX="12.0" layoutY="158.0" prefHeight="193.0" prefWidth="471.0" />

Then my Java Class Controller needs to wrap with this TreeView and add TreeItem's dynamically. That's the problem, it isn't loading those TreeItem's. That's the test code below, from my Controller:
public class MyControllerClass extends Application {

    @FXML
    private TreeView<String> locationTreeView;

    @Override
    public void start(Stage stage) throws Exception {

        stage.initStyle(StageStyle.TRANSPARENT);
        stage.getIcons().add(new Image(getClass().getResourceAsStream("myIcon.png")));

        Parent root = FXMLLoader.load(getClass().getResource("myInterface.fxml"));

        Scene scene = new Scene(root);
        stage.setScene(scene);

        loadTreeItems();

        stage.show();
    }

    // Just a simple example that still doesn't works
    private void loadTreeItems() {

        try {
            TreeItem<String> root = new TreeItem<String>("Root Node");
            root.setExpanded(true);
            root.getChildren().addAll(
                new TreeItem<String>("Item 1"),
                new TreeItem<String>("Item 2"),
                new TreeItem<String>("Item 3")
            );

            locationTreeView = new TreeView<String>(root);

        } catch (Exception exc) {
            System.out.println("Error: " + exc.getMessage());
        }
    }

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

Any ideas why its not working?

A: There are a couple of reasons why your application doesn't work:

*

*You need to make the Controller and the Application separate classes.

*You should allow the FXML system to inject the TreeView instance rather than creating a new instance (as Aaron points out in his answer).

The way you have your application currently structured what will happen is:

*

*The Java system will create an instance of MyControllerClass on startup (and invoke it's start method).

*The FXMLLoader will create another instance of MyControllerClass each time the myInterface.fxml file is loaded.

*The FXMLLoader will create a new TreeView instance and perform the FXML injection on the locationTreeView member of the new MyControllerClass instance it creates.

*The FXMLLoader will try to invoke the initialize method on the new MyControllerClass (of which you have none).

*The FXMLLoader will not invoke the start method on the new MyControllerClass.

*Your original start method invocation on your original MyControllerClass will continue processing and create another new TreeView instance which it will set the locationTreeView member of the old MyControllerClass instance to.

I updated your code to make the modifications I suggested above and the code now works.  The updated code is available.
A sample screenshot from the running code is:

MyApplicationClass.java
import javafx.animation.*;
import javafx.application.Application;
import javafx.event.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.stage.*;
import javafx.util.Duration;

/** Sample application to demonstrate programming an FXML interface. */
public class MyApplicationClass extends Application {
  @Override public void start(final Stage stage) throws Exception {
    // load the scene fxml UI.
    // grabs the UI scenegraph view from the loader.
    // grabs the UI controller for the view from the loader.
    final FXMLLoader loader = new FXMLLoader(getClass().getResource("myInterface.fxml"));
    final Parent root = (Parent) loader.load();
    final MyControllerClass controller = loader.<MyControllerClass>getController();

    // continuously refresh the TreeItems.
    // demonstrates using controller methods to manipulate the controlled UI.
    final Timeline timeline = new Timeline(
      new KeyFrame(
        Duration.seconds(3),
        new TreeLoadingEventHandler(controller)
      )
    );
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.play();

    // close the app if the user clicks on anywhere on the window.
    // just provides a simple way to kill the demo app.
    root.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
      @Override public void handle(MouseEvent t) {
        stage.hide();
      }
    });

    // initialize the stage.
    stage.setScene(new Scene(root));
    stage.initStyle(StageStyle.TRANSPARENT);
    stage.getIcons().add(new Image(getClass().getResourceAsStream("myIcon.png")));
    stage.show();
  }

  /** small helper class for handling tree loading events. */
  private class TreeLoadingEventHandler implements EventHandler<ActionEvent> {
    private MyControllerClass controller;
    private int idx = 0;

    TreeLoadingEventHandler(MyControllerClass controller) {
      this.controller = controller;
    }

    @Override public void handle(ActionEvent t) {
      controller.loadTreeItems("Loaded " + idx, "Loaded " + (idx + 1), "Loaded " + (idx + 2));
      idx += 3;
    }
  }

  // main method is only for legacy support - java 8 won't call it for a javafx application.
  public static void main(String[] args) { launch(args); }
}

MyControllerClass.java
import javafx.fxml.FXML;
import javafx.scene.control.*;

/** Sample controller class. */
public class MyControllerClass {
  // the FXML annotation tells the loader to inject this variable before invoking initialize.
  @FXML private TreeView<String> locationTreeView;

  // the initialize method is automatically invoked by the FXMLLoader - it's magic
  public void initialize() {
    loadTreeItems("initial 1", "initial 2", "initial 3");
  }

  // loads some strings into the tree in the application UI.
  public void loadTreeItems(String... rootItems) {
    TreeItem<String> root = new TreeItem<String>("Root Node");
    root.setExpanded(true);
    for (String itemString: rootItems) {
      root.getChildren().add(new TreeItem<String>(itemString));
    }

    locationTreeView.setRoot(root);
  }
}

myInterface.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns:fx="http://javafx.com/fxml" fx:controller="test.MyControllerClass">
  <TreeView fx:id="locationTreeView" layoutX="0" layoutY="0" prefHeight="193.0" prefWidth="471.0" />
</AnchorPane>

A: In your loadTreeItems() function you are creating a new TreeView instance.  This is replacing the one that is defined in your FXML file and attached to your scene with a new instance that is not part of the scene graph.
To add items to a TreeView that was created via the FXMLLoader you can use the setRoot() function.
private void loadTreeItems() {

    try {
        TreeItem<String> root = new TreeItem<String>("Root Node");
        root.setExpanded(true);
        root.getChildren().addAll(
            new TreeItem<String>("Item 1"),
            new TreeItem<String>("Item 2"),
            new TreeItem<String>("Item 3")
        );

        locationTreeView.setRoot(root);

    } catch (Exception exc) {
        System.out.println("Error: " + exc.getMessage());
    }
}


text:
Q: Compile php-ssh2 module from source on Ubuntu 16.04 Because I install PHP5.6.31 from source so I can't use this command:
apt-get install php-ssh2

to install SSH2 module for PHP.
Now I try to install this module from source. I read this install step

1. download the libssh2 package from http://libssh2.org, command as following:
   tar vxzf libssh2-1.4.2.tar.gz
   cd libssh2-1.4.2
   ./configure
   make
   make install

2. download the php-ssh2 package from http://pecl.php.net/package/ssh2:
tar vxzf ssh2-0.11.3
cd ssh2-0.11.3
phpize
./configure --with-ssh2
make
make install

and the ssh2.so file will copy into /usr/lib64/php/modules
check it.

*modify the php.ini

  vi /etc/php.ini add the "extension=ssh2.so" to the extension part of
  php.ini

*check the environment of php, use phpinfo();

But I fail in step 2:

Please help me.
Thank in advance.

A: You're missing the package which essential in order to run the script properly, simply install.
sudo apt-get install autoconf


text:
Q: Synchronize data in MongoDB in BigQuery with python error json I am trying to synchronize between 2 databases:
MongoDB and BigQuery
I got this error:
Traceback (most recent call last):
   File "mongodb1.py", line 53, in <module>
     job = client_bq.load_table_from_json(data, table_ref, job_config=job_config)
   File "/usr/local/lib/python2.7/dist-packages/google/cloud/bigquery/client.py", line 2366, in load_table_from_json
     data_str = u"\n".join(json.dumps(item) for item in json_rows)
   File "/usr/local/lib/python2.7/dist-packages/google/cloud/bigquery/client.py", line 2366, in <genexpr>
     data_str = u"\n".join(json.dumps(item) for item in json_rows)
   File "/usr/lib/python2.7/json/__init__.py", line 244, in dumps
     return _default_encoder.encode(obj)
   File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
     chunks = self.iterencode(o, _one_shot=True)
   File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
     return _iterencode(o, 0)
   File "/usr/lib/python2.7/json/encoder.py", line 184, in default
     raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2014, 12, 30, 0, 0) is not JSON serializable

I made this script:
from pymongo import MongoClient
import json
from google.cloud import bigquery
from google.api_core.retry import Retry
import os
from bson import ObjectId

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'gissoft-378107-19dbaa3080fa.json'

dataset_id = "gissoft-378107.mongodb"
table_id = "sessions"

if __name__ == '__main__':
    client = MongoClient("mongodb+srv://codercoder42:xxxxxxxx@cluster0.to2e8pb.mongodb.net/?retryWrites=true&w=majority", 27017, maxPoolSize=50)
    print("Connection Successful")
    db = client['sample_restaurants']

    client_bq = bigquery.Client()

    for collection_name in db.list_collection_names():

        collection = db[collection_name]
        sample_document = collection.find_one()
        if sample_document is None:
            continue

        table_ref = client_bq.dataset('mongodb').table(collection_name)
        schema = []
        for field_name, value in sample_document.items():
            field_type = 'STRING'
            if isinstance(value, int):
                field_type = 'INTEGER'
            elif isinstance(value, float):
                field_type = 'FLOAT'
            elif isinstance(value, bool):
                field_type = 'BOOLEAN'
            schema.append(bigquery.SchemaField(field_name, field_type))

        table = bigquery.Table(table_ref, schema=schema)
        table = client_bq.create_table(table)

        data = []
        for document in collection.find():
            #print(document)
            data.append(document)

        print(data)
        job_config = bigquery.LoadJobConfig(schema=schema, write_disposition="WRITE_TRUNCATE")
        job = client_bq.load_table_from_json(data, table_ref, job_config=job_config)
        job.result()

    client.close()
    client_bq.close()

When I send the data to BigQuery, it creates the table with the correct schema, but the data is not entered into the table.
The mongodb table looks like this:

I think it's a json problem, can someone help me?

A: To solve your issue and load correctly data to BigQuery, you have to convert the datetime retrieved from Mongo to String ISO date, example of supported date format BQ : 2008-12-25T05:30:00
You can apply the conversion with a code that looks like :
from pymongo import MongoClient
import json
from google.cloud import bigquery
from google.api_core.retry import Retry
import os
from bson import ObjectId

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'gissoft-378107-19dbaa3080fa.json'

dataset_id = "gissoft-378107.mongodb"
table_id = "sessions"

if __name__ == '__main__':
    client = MongoClient("mongodb+srv://codercoder42:xxxxxxxx@cluster0.to2e8pb.mongodb.net/?retryWrites=true&w=majority", 27017, maxPoolSize=50)
    print("Connection Successful")
    db = client['sample_restaurants']

    client_bq = bigquery.Client()

    for collection_name in db.list_collection_names():

        collection = db[collection_name]
        sample_document = collection.find_one()
        if sample_document is None:
            continue

        table_ref = client_bq.dataset('mongodb').table(collection_name)
        schema = []
        for field_name, value in sample_document.items():
            field_type = 'STRING'
            if isinstance(value, int):
                field_type = 'INTEGER'
            elif isinstance(value, float):
                field_type = 'FLOAT'
            elif isinstance(value, bool):
                field_type = 'BOOLEAN'
            schema.append(bigquery.SchemaField(field_name, field_type))

        table = bigquery.Table(table_ref, schema=schema)
        table = client_bq.create_table(table)

        data = []
        for document in collection.find():

            # Date conversion here.
            my_date = document['my_field_date']
            my_date_as_str = current_date.isoformat()

            document.update(my_field_date='my_date_as_str')

            #print(document)
            data.append(document)

        print(data)
        job_config = bigquery.LoadJobConfig(schema=schema, write_disposition="WRITE_TRUNCATE")
        job = client_bq.load_table_from_json(data, table_ref, job_config=job_config)
        job.result()

    client.close()
    client_bq.close()

I applied a conversion from datetime to iso string in the document object.
So data should be saved correctly to the BigQuery table.


text:
Q: Connection refused errors not reported in apache logs I have a system where a bunch of raspberry pis access a central server through http. Recently a lot of them have been getting Connection Refused errors (111), but not all of them, and it seems to be a bit random whether their connections will be refused or not. I'm really struggling to debug this, as apache is not reporting these errors in either error.log or access.log. Any clue how I can get these errors in the log so I can start to debug this?

A: If you get the "connection refused" errors on the clients (RasPis) then apache can't log these errors, since it never sees the connections in the first place (the error comes most likely from the TCP/IP stack, not the HTTP layer).
If apache refuses a connection you always get a corresponding HTTP error code (like 403, 404 etc)


text:
Q: Roadmap to better data access for asp.net MVC app I've have quite small asp.net MVC 2 application to maintain/extend. Currently it uses hand written stored procedures + application code for doing data access. Basically what it does is that it loads data and wraps it to POCOs.
Current implementation is tedious to maintain. Especially when I have to add new property - not to mention adding new class/table for doing CRUD. Application has separate caching  that is also hard to maintain - and it has led to a few defects. I would love to get rid off that also.
I 've started to thinking about switching to some ORM tool like NHibernate or Entity Framework.
I have very limited experience when it comes to ORM or data access in general. What are the best practices in this situation? What should I take in consideration before jumping to NHibernate/Entity? And what about the downsides?

A: "Best practice" is one of my least favourite words - it's often used to assign more importance to an opinion than it really merits...
Having said that...
First, choose your database access strategy; ORM is the current de-facto industry standard, and you've identified the front runners; see this thread for a comparison.
Different database access methodologies trade off different things. The one your app currently uses provides a lot of detailed control over the queries and the way they are mapped to your domain - but at the expense of a lot of hand coding. It's likely to provide the best performance, and the most flexibility; some would argue it's the easiest to maintain because there's no "magic" for developers to get their heads round.
ORM solutions trade performance and control for shorter development and (some argue) easier maintenance. There's a learning curve, and the intermediate layer of "magic" can make some problems harder to identify - the classic anti-pattern with ORM is "loading the entire database into memory", but performance issues can also be tricky to debug. On the other hand, you reduce the overall amount of code, and make simple CRUD operations far easier to build. Developers with experience in ORM will find it easier to maintain; developers who are new to ORM will have to learn the framework.
In general, I think the industry is moving to ORM for applications that don't have extreme performance requirements; it's becoming mainstream, and most developers we interview these days have experience with ORM. However, the learning curve can be quite steep, and there's a definite chicken and egg - which ORM do you choose without having experience of them all? FWIW, I think Steven Lacy's answer is on the money there...
What you're proposing is basically a refactoring. I'd recommend a process along the following lines:

*

*pick a feature to refactor

*make sure you have a automated tests to ensure it works with the current implementation

*replace the current implementation with your chosen ORM

*run your automated tests to ensure it still works

*rinse and repeat.

I would put at least as much effort into creating the tests as in the refactoring itself - and I would resist the urge to add new features until you've replaced the current implementation.
Make sure your tests include performance and scalability testing.

A: I've used both NHibernate and Entity Framework.
In work we went with Entity Framework because it was easier to convince others to use it rather than an open source application.
The vast majority of the developers I encounter use NHibernate but then both have their disadvantages, they make the amount of work you have to do less when accessing data but they also restrict you.
Currently in EF I face a problem where I can't use Full Text Searches on SQL server because EF doesn't support that. I could do a direct query through the context but I'd much rather use Table Valued Functions which should be very easy to implement with Linq2 whatever but for some reason the EF team haven't gotten around to.
Make sure that you follow a unit of work pattern, your session gets created when it's needed and destroyed at the end of the web request. Both of them are designed to work well under these conditions, do something like hold the context/session in the application scope and you will encounter problems.
Build your application as if you are planning on switching ORM in the future, because as your first commenter said you probably will have to.
Your Domain Objects should be POCOs, they should have no persistence knowledge
Buy EntityFramework Prof or NHibernate Prof (it will help you optimise queries)
Expect that this will take a fair amount of time to get used to whatever framework you choose. Buy a book and start reading it on your chosen technology, ask questions on stackoverflow early before they become blockers.
Use Code first EF or Fluent Nhibernate, mappings break at runtime, fluent breaks at compile time.
Use Linq2Entities or Linq2Nhibenate, strongly typed queries make life easier about 80% of the time.
Don't have one giant xml file like an EDMX which is horribly difficult to version control.
Beware of code generation, it helps... but it's also dangerous in many situations.
I strongly suggest that you try starting from scratch on a sample project before you alter your existing code. Changing your mind is easier with smaller projects.


text:
Q: cuda malloc fails with structures I have a hard time getting my struct malloc to work for cuda.
my struct looks like this:
typedef struct Map{
    int length;
    double *A;
    int *x;
    int *dx;
    int *y;
    int *dy;
    int *delta;
    int *phi;
}Map;

The malloc function I try to call is as follows:
void cudaMallocMap(Map **m, int p){
    cudaMalloc((void**)m, sizeof(Map));
    cudaMemset(&((**m).length), p, 1);
    if(p>0){
        cudaMalloc((void**)&((**m).A), p*sizeof(double));
        cudaMalloc((void**)&((**m).x), p*sizeof(int));
        cudaMalloc((void**)&((**m).dx), p*sizeof(int));
        cudaMalloc((void**)&((**m).y), p*sizeof(int));
        cudaMalloc((void**)&((**m).dy), p*sizeof(int));
        cudaMalloc((void**)&((**m).delta), p*sizeof(int));
        cudaMalloc((void**)&((**m).phi), p*sizeof(int));
    }
}

It is called in the following way:
Map *dev_x;
int xSize = 31;
...
cudaMallocMap(&dev_x, xSize);

It gives an "Access violation writing location 0x________" at or after the first cudaMalloc in the if-statement.
What is wrong with this code and how can I fix it?


text:
Q: Azure Container Service Kubernetes: How to Change VM Size? I would like to change the VM size of agents. I can't seem to do that from the CLI or by adjusting the Container Service. How can I change the size of the agents?

A:
How can I change the size of the agents?

We can change k8s agent via Azure portal, the agent in Azure is a VM, we should resize the VM :