text:
Q: How to fix tensorflow TypeError: only size-1 arrays can be converted to Python Scalars I was using this to test my tflite
Traceback (most recent call last):
  File "label_image.py", line 124, in <module>
    print('{:08.6f}: {}'.format(float(results[i]), labels[i]))
TypeError: only size-1 arrays can be converted to Python scalars

I'm quite a newbie in using Tensorflow so any help is much appreciated
Edit 1 : I forgot to include the label and image sample
Edit 2 : I tried debugging by print(results[i]) and this is the result
[[27.572786   2.910608  39.202885   4.485999 ]
[19.35345    2.12116   22.764465   5.368863 ]
[ 2.664798   2.9718513 11.22389   11.967384 ]
[11.17787    1.9934689 13.393661   8.419806 ]]

And I still have no idea what is happening

A: This errors means that something in your code is trying to interpret or convert a tensor as/to a single float but the tensor is not of size 1. A "tensor of size-1" means that it only contains one single float.
Here is an example of size-1 tensor:
import tensorflow as tf

data = tf.constant([1.0])

print(data.shape)

This prints (1,) which tells that data has only one dimension and only one element along that dimension.
Here is an example of a tensor not of size-1:
import tensorflow as tf

data = tf.constant([[1, 2], [3, 4]])
print(data.shape)

this prints (2, 2) which means that data is a two dimensional tensor (a matrix) of size 2 by 2.

The issue in your code is probably in the expression float(results[i]). This will fail if result[i] is not a size-1 tensor. You should debug this expression, for instance by printing its contents of shape.


text:
Q: How to multiLine an #import I have this long #import in my C++ header file:
#import "XXX.tlb" no_namespace rename("A", "B") rename("C", "D") and so on

How can I beautify it so it would look something like this:
#import "XXX.tlb"
        no_namespace
        rename("A", "B")
        rename("C", "D")
        rename("E", "F")
        ...

A: Use a backslash to escape newlines, as you would for any preprocessor directive.
There's an example at the bottom of the Microsoft documentation for #import:
#import "test.lib" no_namespace \
   rename("OldName", "NewName")

Applied to your example, that's:
#import "XXX.tlb" \
    no_namespace \
    rename("A", "B") \
    rename("C", "D") \
    rename("E", "F") \
    ...

Be sure not to leave a space after the backslash, otherwise all you'll be doing is escaping the space!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unix/Linux API for file/runtime permissions I want to write memory in /proc/$pid/mem but I assume this will need superuser root privileges.   Is there an API to test if the program has the permission to edit these files?

A: You can stat() the pathname and the st_mode field of the outcoming struct stat contains the permission bits. See manpage stat(2) for details.

A: int access(const char *path, int amode);

where path is your filename and amode is a bitwise inclusive OR of access permissions to check against.
R_OK, W_OK, and X_OK hold mode values for checking read, write, and search/execute permissions respectively.
int readable, readwritable;

//checking for read access
readable = access("/usr/bin/file", R_OK);

//checking for read and write access
readwritable = access("/usr/bin/file", R_OK|W_OK);

For full description of access() check man pages.


text:
Q: Making a list from a loop output data = ['network 10.185.16.64 255.255.255.224','network 55.242.33.0 255.255.255.0','network 55.242.154.0 255.255.255.252']

pref_network_find = re.findall('(\S+\s+255.255.255.\w+)',str(data))

mydict = {"255.255.255.0":24,"255.255.255.128":25,"255.255.255.192":26,"255.255.255.224":27,"255.255.255.240":28,"255.255.255.248":29,"255.255.255.252":30}

for i in pref_network_find:
 splitlines = i.split()
 for word in splitlines:
    if word in mydict:
        i = i.replace(word,str(mydict[word]))
        pref = print (i)
listi = []
for line in pref_network_find:
   listi.append(i)
print (listi)

10.185.16.64 27
55.242.33.0 24
55.242.154.0 30
['55.242.154.0 30', '55.242.154.0 30', '55.242.154.0 30']

Process finished with exit code 0

Im trying to get ['55.242.154.0 30', '55.242.33.0 24', '10.185.16.64 27'] as list1 at the end, but cant understand my mistake here. Could you help me with that?

A: You do not need to garner the initial spliced and joined IPs with regex; instead, just use str.split():
import re
data = ['network 10.185.16.64 255.255.255.224','network 55.242.33.0 255.255.255.0','network 55.242.154.0 255.255.255.252']
mydict = {"255.255.255.0":24,"255.255.255.128":25,"255.255.255.192":26,"255.255.255.224":27,"255.255.255.240":28,"255.255.255.248":29,"255.255.255.252":30}

final_list = sorted(['{} {}'.format(b, mydict[c]) for a, b, c in [i.split() for i in data]], key=lambda x:map(int, re.split('\.|\s', x)), reverse=True)

Output:
['55.242.154.0 30', '55.242.33.0 24', '10.185.16.64 27']

A: Your code is wrong because you are appending with wrong index i at here :
for line in pref_network_find:
    listi.append(i)

We have last value in i = 55.242.154.0 from previous loop. You should use line instead of i or append in for loop directly
data = ['network 10.185.16.64 255.255.255.224','network 55.242.33.0 255.255.255.0','network 55.242.154.0 255.255.255.252']

pref_network_find = re.findall('(\S+\s+255.255.255.\w+)',str(data))

mydict = {"255.255.255.0":24,"255.255.255.128":25,"255.255.255.192":26,"255.255.255.224":27,"255.255.255.240":28,"255.255.255.248":29,"255.255.255.252":30}

listi = []

for i in pref_network_find:
    splitlines = i.split()
    for word in splitlines:
        if word in mydict:
            listi.append(i.replace(word, str(mydict[word])))

print(listi)

A: Obviously, it will print 30 at the end because your this code
for i in pref_network_find:
 splitlines = i.split()
 for word in splitlines:
    if word in mydict:
        i = i.replace(word,str(mydict[word]))
        pref = print (i)

i is 30 after execution. And you are using old variable 'i' like this
for line in pref_network_find:
   listi.append(i)

So yes the code is doing its job well, i is 30 and it is appending 30 to your result.
Correct code goes like this.
import re

data = ['network 10.185.16.64 255.255.255.224','network 55.242.33.0 255.255.255.0','network 55.242.154.0 255.255.255.252']
pref_network_find = re.findall('(\S+\s+255.255.255.\w+)',str(data))
mydict = {"255.255.255.0":24,"255.255.255.128":25,"255.255.255.192":26,"255.255.255.224":27,"255.255.255.240":28,"255.255.255.248":29,"255.255.255.252":30}
listi = []
for i in pref_network_find:
 splitlines = i.split()
 for word in splitlines:
    if word in mydict:
        i = i.replace(word,str(mydict[word]))
        pref = print (i)
        listi.append(i)

print (listi)

Correct me if I am wrong here, maybe you want something else, however, this is what I understood by your question.


text:
Q: How can I make a collection from a backbone models attribute? In our backbone app, we have a profile model. It has an attribute "completeness" that is an array containing the fields the user has not added to their profile (like profile picture, full name, etc).
In order to easily do listenTo on this array, I'm trying to create a collection to replace the array. My idea is to keep the array in the profile model, and to create a progfileProgress model that gets data from the array in the profile. Then to add this to a collection "Completeness".
How can I juggle the data from the first model into the second collection?

A: I would do something like this (assuming you have underscore/lodash because you are using Backbone):
// Here I build a data structure from the completeness array.
// It will be the model of the new Collection.
var missingFields = _.map(profileModel.get('completeness'), function(el) {
    return {missing: el};
});

// The new collection that you can set on your model and do listenTo
profileModel.set('profileProgress', new Backbone.Collection(missingFields));


text:
Q: Check ALL empty comlumn in PHP & MySQL Ex : I have 1 table below
ID   USER1    USER2     USER3
1      X                  X
2      X                  X
3      X                  X
4      X                  X
5      X                  X

How i can check ALL value USER2 comlumn is empty in PHP & MySQL? I code below but it's not working
$res = mysqli_query($conn, "SELECT USER2 FROM TABLE")
if(count($res)== "0") echo "OK";

A: select sum(user2 <> '') as count
from your_table

A: This would help,
$res = mysqli_query($conn, "SELECT COUNT(*) AS count FROM TABLE where USER2 IS NULL OR USER2=''");
if($res['count']==0)
{
  echo "It is Empty";
}
else
{
   echo $res['count']." rows have User2 empty";
}

count(*) returns the no of rows coming as the output of the query, which will be in integer form. $res == "0" means that you are comparing with a string "0", not an integer.

A: $res = mysqli_query($conn, "SELECT * FROM TABLE where USER2=''")
$n_rows_void_user2 = mysql_num_rows($res);
if($n_rows_void_user2) echo "OK";
else
echo "There are $n_rows_void_user2";

A: you can do something like this:
    $res = mysqli_query($conn, "SELECT * FROM TABLE where USER2 IS NULL OR USER2 = ''");

    $num = $res->num_rows;
   if($num != 0){
        echo "number of empty row for USER2".$num;
       }else{
     echo "on empty column for USER2";
    }

A: First of all you have to write the correct query:
"SELECT * FROM mytable WHERE --user2 condition--"

Where user2 condition may be different depend on your data:
WHERE ISNULL(user2) OR user2=''

It depends on your data.
Then to execute this query in php:
$res = mysqli_query($conn, $query);
$n_rows = mysql_num_rows($res);
if ($n_rows > 0) {
  // echo your rows here
}

Also you should connect to database before, i hope you did that.

A: An extension to the answer by @juergen :
   select sum(user2 IS NOT NULL OR some_col <> '') as count
    from your_tabl;


text:
Q: Kivy callbacks for instanced buttons/widgets? I am trying to make some instanced buttons that will trigger the 'on_toggle_button_state' function like the KV snippet below.  I'm sure it's something simple I've overlooked, but this has stumped me for longer than I'd like to admit.
AttributeError: 'ToggleButtons' object has no attribute 'state'
class ToggleButtons(StackLayout):

    def __init__(self, *args,  **kwargs):
        super().__init__(**kwargs)

        conn = sqlite3.connect('players_db.db')
        c = conn.cursor()
        c.execute("DELETE FROM players WHERE (name IS NULL OR name  = '')") ##Remove empty entries
        c.execute("SELECT * FROM players")
        records = c.fetchall()
        records = list(filter(None, records))

        for i in range(0, len(records)):
            name = str(records[i])[2:-3]
            b = ToggleButton(size_hint = (0.2, 0.2), text = name, on_state = self.on_toggle_button_state())
            self.add_widget(b)

    def on_toggle_button_state(self, widget):
        print("toggle state: " + widget.state)
        if widget.state == "normal":
            widget.text = "OFF"
            self.count_enabled = False
        else:
            widget.text = "ON"
            self.count_enabled = True

KV that works for not-instanced buttons:
StackLayout:
    ToggleButton:
        text: "Charlie"
        on_state: root.on_toggle_button_state(self)
        size_hint: 0.2, 0.2

A: In you kv file use <ToggleButton>: to assign the on_state method with self.parent.on_toggle_button_state(self).
self is the dynamically instantiated button and parent is the ToggleButtons StackLayout where you have defined the on_toggle_button_state method.
I've modified your code a bit so I could run it without the SQL stuff. So ignore these changes.
The difference between ToggleButton and <ToggleButton> is that the first places an instance into the StackLayout - not what you want here.
And the bracket notation, defines methods & styles for each of your instances.
Please find the snippet below with the mentioned change:
from kivy.app import App
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button
from kivy.lang import Builder

kv = '''
StackLayout:

<ToggleButton>:
    text: "Charlie"
    on_state:
        self.parent.on_toggle_button_state(self)
    size_hint: 0.2, 0.2
'''

Builder.load_string(kv)

class ToggleButton(Button):
    pass

class ToggleButtons(StackLayout):

    def __init__(self, *args,  **kwargs):
        super().__init__(**kwargs)

        # conn = sqlite3.connect('players_db.db')
        # c = conn.cursor()
        # c.execute("DELETE FROM players WHERE (name IS NULL OR name  = '')") ##Remove empty entries
        # c.execute("SELECT * FROM players")
        # records = c.fetchall()
        # records = list(filter(None, records))
        records = ["test1", "test2"]
        for i in range(0, len(records)):
            # name = str(records[i])[2:-3]
            name = records[i] # just for testing
            print(name)
            b = ToggleButton(size_hint = (0.2, 0.2), text = name, on_state = self.on_toggle_button_state)
            self.add_widget(b)

    def on_toggle_button_state(self, widget):
        print("toggle state: " + widget.state)
        if widget.state == "normal":
            widget.text = "OFF"
            widget.count_enabled = False
        else:
            widget.text = "ON"
            widget.count_enabled = True

class MyApp(App):
    def build(self):
        return ToggleButtons()

if __name__ == '__main__':
    MyApp().run()


text:
Q: Passing language=british to biblatex-chicago with polyglossia This question is similar to this one, except the crux here is biblatex-chicago.
I understand it's been a little rough building polyglossia support for biblatex. Thus far, biblatex-chicago has been tested for babel instead.
To achieve British localization in biblatex-chicago, the manual says to load babel with the option british. When I instead use polyglossia and \setmainlanguage[variant=british]{english}, however, it loads cms-american.lbx, in effect the same situation noted in this question. In this answer to that question, one of the solutions is to manually pass (in that case) language=ngerman to biblatex. Accordingly, the option language=british works for my purposes with biblatex. If this option is passed to biblatex-chicago, however, something seems to go amiss in the loading of the localization file, as all bibliography strings remain undefined:
\documentclass{book}
\usepackage{fontspec}
\usepackage{filecontents}
\usepackage[style=british]{csquotes}
\usepackage{polyglossia}
\usepackage[notes,language=british]{biblatex-chicago}

\setdefaultlanguage[variant=british]{english}
\setmainfont[Ligatures=TeX]{Cardo}
\begin{filecontents}{book.bib}
@online{key1,
   title = {Stack Exchange},
   url = {http://www.stackexchange.com},
   urldate = {2014-09-16}
}
\end{filecontents}
\addbibresource{book.bib}

\begin{document}

See date formatting in footnote below.\autocite{key1}

\end{document}

Warnings returned:
Package biblatex Warning: Bibliography string 'urlseen' undefined
(biblatex)                at entry 'key1' on input line 21.

Package biblatex Warning: Bibliography string 'september' undefined
(biblatex)                at entry 'key1' on input line 21.

Output:

(source: langeslag.org)
If I load ngerman instead it actually works, though obviously with the wrong localization. This suggests that british fails to be tied to a localization file.
I can think of a couple of workarounds:

*

*Opt for biblatex over biblatex-chicago and copy the relevant contents of biblatex-chicago.sty into my own preamble (as well as importing the contents of biblatex-chicago's cms-british.lbx somehow -- what's the elegant way of doing this?);

*Swap out polyglossia in favour of babel. Note that my document contains over a dozen European languages.

But what's the correct way of actually telling biblatex-chicago to load the localization from its own cms-british.lbx?

A: You can make biblatex-chicago into thinking that the language is indeed british:
\begin{filecontents}{\jobname.bib}
@online{key1,
   title = {Stack Exchange},
   url = {http://www.stackexchange.com},
   urldate = {2014-09-16}
}
\end{filecontents}
\documentclass{book}
\usepackage{fontspec}
\usepackage{filecontents}
\usepackage[style=british]{csquotes}
\usepackage{polyglossia}
\setdefaultlanguage[variant=british]{english}

\let\keptlanguagename\languagename
\def\languagename{british}
\usepackage[notes,language=british]{biblatex-chicago}
\let\languagename\keptlanguagename

\setmainfont[Ligatures=TeX]{Cardo}
\addbibresource{\jobname.bib}

\begin{document}

See date formatting in footnote below.\autocite{key1}

\end{document}

Proper support of polyglossia would require changing biblatex-chicago.sty.

A: Afaik, the polyglossia definition of the UK variant is
\setdefaultlanguage[variant=uk]{english}

so try changing the line
\setdefaultlanguage[variant=british]{english}

Hope it helps! Jigdrel


text:
Q: Two links to the same image lightbox I need to add 2 different link to the same lightbox gallery (http://lokeshdhakar.com/projects/lightbox2/). The problem is that if i set as href the same image url, when I click on one of the links I get the same image repeated two times.
Here is the code I write:
<a href="<?php echo base_url().'gallery/'.md5($annuncio['id']).'/'.$first_image; ?>" rel="lightbox[gallery]">first link
<a href="<?php echo base_url().'gallery/'.md5($annuncio['id']).'/'.$first_image; ?>" rel="lightbox[gallery]">second link with same image url
<a href="<?php echo base_url().'gallery/'.md5($annuncio['id']).'/'.$second_image; ?>" rel="lightbox[gallery]">third link to a different image
<a href="<?php echo base_url().'gallery/'.md5($annuncio['id']).'/'.$third_image; ?>" rel="lightbox[gallery]">fourth link to a different image


text:
Q: Mastering Android Layouts How to maintain consistent app layouts cross-device?
Per consistency i mean to proportions, readability, usability and user comfort.
For some time I'm doing apps for android. All these applications were made for corporate clients. Each application was designed for a specific phone so i never need mastering the layouts deeply.
Recently, I received a request to build a complex application for all android 2.2 devices and up to 5.0. The requirement includes: ActionBar, Sliding Menu, Master/Detail Flows, Many Fragments, Many buttons, Maps, the list go on. So i begun research.
Research
First, to support all Views mentioned above, I decided to use appcompat_v7. Simply because Google made it. Discard ActionBarSherlock because it's a third party library.
Alternative Layouts:
Under certain conditions, you need to use an alternative layout. This is done easily with an alias.
values-large/aliases.xml
<resources>
    <item name="main_layout" type="layout">@layout/main_latyout_large</item>
</resources>

This will make this code:
setContentView(R.layout.main_layout);

Operate effectively as this one
setContentView(R.layout.main_layout_large);

So far so good, but as will be seen later something is escaping me. (see Finally)
Note: An alternative way is to place master_layout_large.xml as layout-large/master_layout.xml.
Scaffolding, proportions
A trivial example:
layout/master_layout.xml
<LinearLayout
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:weightSum="@dimen/layout_weightSum">
  <View
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="@dimen/view1_weight"/>
  <View
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="@dimen/view2_weight"/>
</LinearLatyout>

values/dimens.xml
<resources>
    <dimen name="layout_weightSum">1</dimen>
    <dimen name="view1_weight">0.2</dimen>
    <dimen name="view2_weight">0.8</dimen>
</resources>

This configuration allows me to easily change the proportions as follows:
For Android 2.2 to Android 3.1
values-small/dimens.xml
<resources>
    <dimen name="view1_weight">0.3</dimen>
    <dimen name="view2_weight">0.7</dimen>
</resources>

For Android 3.2 and up:
values-sh240dp/dimens.xml
<resources>
    <dimen name="view1_weight">0.3</dimen>
    <dimen name="view2_weight">0.7</dimen>
</resources>

In How to Support Multiple Screens say:

The configuration qualifiers you can use to provide size-specific resources are small, normal, large, and xlarge. For example, layouts for an extra-large screen should go in layout-xlarge/.
  Beginning with Android 3.2 (API level 13), the above size groups are deprecated and you should instead use the swdp configuration qualifier to define the smallest available width required by your layout resources.

Then in How Android Finds the Best-matching Resource explains (by an example) the process of resource selection. What is not said (or could find) is how it discard deprecated qualifiers. (even if do)
Q1: Should I use both methods in an application that requires work in all versions?
Q2: Can deprecated resource qualifiers (small,normal,etc) match over non deprecated resource qualifiers?
Note: This technique of scaffolding was taken from here.
Readability:
TextViews are frustrating. Nothing native that supports auto resizing. WTF?.
But suppose I use the component of this response. So i can use the same method, dimensions.
layout/other_layout.xml (relevant code)
<myns.AutoResizeTextView
    android:id="@+id/title"
    android:textSize="@dimen/title_textSize"/>

values/dimens.xml
<resources>
    <dimen name="title_textSize">24dp</dimen>
</resources>

values-xlarge/dimens.xml
<resources>
    <dimen name="title_textSize">64dp</dimen>
</resources>

values-sw600dp/dimens.xml
<resources>
    <dimen name="title_textSize">64dp</dimen>
</resources>

Same problemas as before, event here the another problem is to show the text in an optimal size for each screen, but is more tedious, because according to my tests, I need to define many variants of the dimension to make it look consistent across devices.
Q3: How to maintain Readability in easy way?
Finally
I realize that the way I'm facing this project the need arises to create multiple value- * and becomes exponentially considering the amount of options out there. (view Providing Alternative Resources)
Q4: What I can do to minimize the amount of value- * that seems to need my application.
Any other sugestion?


text:
Q: In Java, remove the first char of the string if it is , (comma) In Java, I have a String variable.
Sometimes the first character of the string is a comma ,
I want to remove the first char only if it is a comma.
What is the best approach to do this?

A: Something like:
text = text.startsWith(",") ? text.substring(1) : text;

is pretty simple...

A: I would use the ^ anchor together with replaceFirst():
niceString = yourString.replaceFirst("^,", "");

A: If you have commons-lang in your classpath, may have a look at StringUtils.removeStart(String str, String remove)

A: Try this
public String methodNoCharacter(String input, String character){

if(input!= null && input.trim().length() > 0)//exist
            if(input.startsWith(character))//if start with '_'
                return methodNoCharacter(input.substring(1));//recursive for sure!

        return input;

}


text:
Q: Nee help @ array in a Perl script I need some help @ a script in perl
I have the following file "etichete":
0.000000 8.700000 speech_L1
8.710000 27.300000 speech_L2
27.310000 27.600000 speech_L3
31.210000 37.210000 speech_L4
37.220000 61.210000 speech_L5

I need to create "etichete.rttm" file using "etichete" like this:
SPKR-INFO etichete 1 <NA> <NA> <NA> unknown speech_L1 <NA>
SPKR-INFO etichete 1 <NA> <NA> <NA> unknown speech_L2 <NA>
SPKR-INFO etichete 1 <NA> <NA> <NA> unknown speech_L3 <NA>
SPEAKER etichete 1 0.000 8.556 <NA> <NA> speech_L1 <NA>
SPEAKER etichete 1 8.556 21.063 <NA> <NA> speech_L2 <NA>
SPEAKER etichete 1 32.304 9.515 <NA> <NA> speech_L3 <NA>
SPEAKER etichete 1 42.049 0.767 <NA> <NA> speech_L1 <NA>

This is my code (I think my mistakes are near creating the matrix @rttm):
#!/usr/bin/perl -w

use List::MoreUtils qw(uniq);
use File::Path qw(make_path);
use File::Copy "cp";
use warnings;
use autodie;

open my $fh, "etichete" or die $!;

$nume="etichete";
my @file_array;
while (my $line = <$fh>) {
    chomp $line;
    my @line_array = split(/\s+/, $line);
    push (@file_array, \@line_array);
}

my @arr=@file_array;
my $arrSize = @arr;

@speakers=$arr[0][2];
$j=0;
while ($j < $arrSize)
{
    push(@speakers, $arr[$j][2]);
    $j++;
}

my @uniq;
foreach my $x (@speakers){
        push @uniq, $x if !grep{/^$x$/}@uniq;
}

my $s1= @uniq;
my @rttm=();

$contorlinie1=0;
while ($contorlinie1 < $s1){
     $rttm[$contorlinie1][0]="SPKR-INFO";
     $rttm[$contorlinie1][1]="$nume";
     $rttm[$contorlinie1][2]="1";
     $rttm[$contorlinie1][3]="<NA>";
     $rttm[$contorlinie1][4]="<NA>";
     $rttm[$contorlinie1][5]="<NA>";
     $rttm[$contorlinie1][6]="unknown";
     $rttm[$contorlinie1][7]="$uniq[$contorlinie1]";
     $rttm[$contorlinie1][8]="<NA>";
    $contorlinie1++;
    }
$contorlinie2=$s1;
while ($contorlinie2 < $arrSize)
     {
        $rttm[$contorlinie2][0]="SPEAKER";
     $rttm[$contorlinie2][1]="$nume";
     $rttm[$contorlinie2][2]="1";
     $rttm[$contorlinie2][3]="$arr[$contorlinie2][0]";
     $rttm[$contorlinie2][4]="$arr[$contorlinie2][1]";
     $rttm[$contorlinie2][5]="<NA>";
     $rttm[$contorlinie2][6]="<NA>";
     $rttm[$contorlinie2][7]="$arr[$contorlinie2][2]";
     $rttm[$contorlinie2][8]="<NA>";
    $contorlinie2++;
}

open my $fh1,">etichete.rttm" or die $!;
foreach(@rttm)
    {
    print $fh1 "$-\n";
    }
close $fh1;

When I run the script it creates an file filled with zeros on every line and when i put to print matrix is something like this:
ARRAY(0x10b13d8)
ARRAY(0x10b14e0)
ARRAY(0x10b15e8)
ARRAY(0x1038f78)
ARRAY(0x1039080)

A: Your example code doesn't produce the output you showed. You probably changed $_ to $-.
The reason is @rttm is an array of arrays. You can't print an array reference directly to get the inner array, you have to dereference it first:
print $fh1 "@$_\n";

BTW, when you use autodie, there's no need to add or die after open.

A: This alternative program may help you.
As far as I ca tell, what you need is an output record for each unique speaker labelled SPKR-INFO, followed by a reformatted version of the original lines labelled SPEAKER.
The input data you show doesn't seem to correspond with your required output. My program below uses this input
 0.000  8.556 speech_L1
 8.556 21.063 speech_L2
32.304  9.515 speech_L3
42.049  0.767 speech_L1

The biggest change is that I have abandoned the @rttm array, as on the face of it you can just print each line to the output file as you come to it.
I have also removed the awkward while loops that iterate over the array indices. Because there is no need for the value of the index except to access the array element it is simpler and clearer just to interate over the array values directly.
Note also that, if you have autodie in place, there is no need to test the success of open calls with an or die....
Since you have included the List::MoreUtils module, I have used the uniq function instead of coding it using a @uniq array
use strict;
use warnings;
use autodie;

use List::MoreUtils qw(uniq);

open my $fh, '<', 'etichete';

my $nume = 'etichete';

my @file;
while (<$fh>) {
  push @file, [ split ];
}

my @unique_speakers = sort { $a cmp $b } uniq map $_->[2], @file;

open my $out, '>', 'etichete.rttm';

for my $speaker (@unique_speakers) {
  print $out join(' ', 'SPKR-INFO', $nume, '1', '<NA>', '<NA>', '<NA>', 'unknown', $speaker, '<NA>'), "\n";
}

for my $line (@file) {
  print $out join(' ', 'SPEAKER', $nume, '1', $line->[0], $line->[1], '<NA>', '<NA>', $line->[2], '<NA>'), "\n";
}

close $out;

output
SPKR-INFO etichete 1 <NA> <NA> <NA> unknown speech_L1 <NA>
SPKR-INFO etichete 1 <NA> <NA> <NA> unknown speech_L2 <NA>
SPKR-INFO etichete 1 <NA> <NA> <NA> unknown speech_L3 <NA>
SPEAKER etichete 1 0.000 8.556 <NA> <NA> speech_L1 <NA>
SPEAKER etichete 1 8.556 21.063 <NA> <NA> speech_L2 <NA>
SPEAKER etichete 1 32.304 9.515 <NA> <NA> speech_L3 <NA>
SPEAKER etichete 1 42.049 0.767 <NA> <NA> speech_L1 <NA>


text:
Q: Hover over image won't appear when site is live So when working with this site locally on my computer the hover over image works perfect.  However, when I put the site up on a server then the image doesn't appear.
I'm referring to the links with the grey background image.  I've provided the css specifically for the Contact us link.
http://bankruptcyimmigrationlaw.com/NEWSTARTLAW/Home.html
...

#Contact_us li:first-child a {
padding:9px 5px 15px 30px;
margin-top:25px;
background-image:url(../images/DefaultNavBg.png);
background-position:-30px -15px;
background-repeat:no-repeat;
height:76px;
width:350px;
border-bottom:none;
text-decoration:none;
}

#Contact_us li:first-child a:hover {
padding:9px 5px 0px 15px;
margin-top:25px;
background-image:url(../images/CurrentNavBg.png);
background-position:-30px -15px;
background-repeat:no-repeat;
height:76px;
width:350px;
border-bottom:none;
cursor:pointer;
text-decoration:none;
}

A: It appears that your images isn't where you think it is, I'm getting 404.  It could be that you didn't upload it, or if your testing on Windows and deploying to *Nix it could be an issue with the case of the file (or directory) name.

A: You didn't send the image to the server:
http://bankruptcyimmigrationlaw.com/NEWSTARTLAW/images/CurrentNavBg.png
returns 404
Tip: Using webrowser with some king of inspector - for an example Chrome with build-in inspector or Firefox + Firebug is best friend of every webmaster, webdevloper, webdesigner, etc.
Edit
Try to avoid CaseMixing in all your file names and paths. This is very reason of mistakes and bugs, so using same variation of lower case is definitely better.
My favourite notation is_lower_case_underscored.jpg,
using hypens is other recommended way, however it can be reason of mistakes when creating filenames with JavaScript as the hypen can be recognized as minus operator by accident.


text:
Q: Removing index from returned data I have a data-frame (df)
which looks like:
  first_name surname location identifier
0       Fred   Smith   London  FredSmith
1       Jane   Jones  Bristol  JaneJones

I am trying to query a particular field and return it to a variable value using:
value = df.loc[df['identifier'] == query_identifier ,'location']

so where query_identifier is equal to FredSmith I get returned to value:
0 London

How can I remove the 0 so I just have:
London

A: Try this statement:
value = df.loc[df['identifier'] == "FredSmith" ,'location'].values[0]

This will help you.
If there is multiple values for the same identifier, then:
value = df.loc[df['identifier'] == "FredSmith" ,'location'].values
for df_values in value:
    print(df_values)

This is just enhancement.


text:
Q: How to format a variable in Ansible value Given that Ansible processes all variables through Jinja2, and doing something like this is possible:
- name: Debug sequence item value
  debug: msg={{ 'Item\:\ %s'|format(item) }}
  with_sequence: count=5 format="%02d"

Which correctly interpolates the string as:
ok: [server.name] => (item=01) => {"item": "01", "msg": "Item: 01"}
ok: [server.name] => (item=02) => {"item": "02", "msg": "Item: 02"}
ok: [server.name] => (item=03) => {"item": "03", "msg": "Item: 03"}
ok: [server.name] => (item=04) => {"item": "04", "msg": "Item: 04"}
ok: [server.name] => (item=05) => {"item": "05", "msg": "Item: 05"}

Why then doesn't this work:
- name: Debug sequence item value
  debug: msg={{ 'Item\:\ %02d'|format(int(item)) }}
  with_sequence: count=5

This apparently causes some sort of parsing issue which results in our desired string being rendered verbose:
ok: [server.name] => (item=01) => {"item": "01", "msg": "{{Item\\:\\ %02d|format(int(item))}}"}

Noting that in the above example item is a string because the default format of with_sequence is %d, and format() doesn't cast the value of item to the format required by the string interpolation %02d, hence the need to cast with int().
Is this a bug or am I missing something?

A: It took me a couple of tries to get this right, but try this, instead:
debug: msg={{ 'Item\:\ %02d'|format(item|int) }}

Jinja2 is a bit funny.


text:
Q: Calculate average percentage difference in a php array Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 3
    [6] => 1
)

I was wondering how one would go about working out the average percentage difference between the current value in an array and the next value. If the next value were a larger one, it would perform like so. (ie keys [0]-[1] 1/2 * 100 = 50). If it were a smaller value it would perform like so. (ie keys [4]-[5] = 3/5 * 100 = -60).
The following will represent what I am aiming to do with these percentage calculations.
1/2 * 100
2/3 * 100
3/4 * 100
4/5 * 100
3/5 * 100 (negative)
1/3 * 100 (negative)

Total : total/count
This will iterate through the list and then work out the average from the count. I have looked into splitting arrays but don't see how else I could do this.
$count = count($num);
foreach ($num as $value) {
    array_chunk($num, 1);
    if($value<$value){
    $total1 = $total1 + ($value/$value)*100;
    }
    if($value>$value){
    $total2 = $total2 + ($value/$value)*100;
    }
}
$average = (($total1-$total2)/$count);
print($average);

I understand the above code is incorrect, but I hope it reveals where I am getting at with this.
Any help would be greatly appreciated.

A: You don't want to use foreach as you'll always be needing two array elements.  Note that this snippet does not protect you from 0 values.  These will make your script fail.
$num   = array(1, 2, 3, 4, 5, 3, 1);
$total = 0;
// The number of percent changes is one less than
// the size of your array.
$count = count($num) - 1;
// Array indexes start at 0
for ($i = 0; $i < $count; $i++) {
    // The current number is $num[$i], and the
    // next is $num[$i + 1]; knowing that it's
    // pretty easy to compare them.
    if ($num[$i] < $num[$i + 1]) {
        $total += (100 * $num[$i] / $num[$i + 1]);
    }
    else {
        $total += (-100 * $num[$i + 1] / $num[$i]);
    };
};
echo ($total / $count);


text:
Q: Query to search data I have two tables,one containing specific text keyword in one column and another table with large text in a column, each having distinct number of records.
I want to write a query to check whether text field in second table contains any of keyword from 1st table.
I want to check all my keywords with all the records of 2nd table's text field.
Thanks in advance.

A: You should put the LIKE clause in the JOIN.  See sqlFiddle
SELECT *
FROM TableTwo t2
JOIN TableOne t1 ON t2.ColumnOne LIKE '%' + t1.ColumnOne + '%'


text:
Q: slice each day ROR Im creating a time line with some columns from a table.
At the moment is the time line just display each column ordered by the "created_at" field.
But i want slice it for each day like this:
       TODAY
content -|
         |
         |- content
         |
content -|
         |
      YESTERDAY
         |
         |- content
         |
content -|

At the moment am i using this code

<% @timeline.each do |timeline| %>

        <%= timeline.title %>

<% end %>

I want to do something like the "each_slice(5)" function.
Hope anybody can tell me how to do this.
Thanks in advance.

A: You can group your array with ruby group_by:
@timeline.group_by { |el| el.created_at.to_date.to_s(:db) }

Note: I assume that @timeline already sorted.
Probably, this method will be reusable, so better place it in models like:
def self.to_grouped_by_day
  group_by { |el| el.created_at.to_date.to_s(:db) }
end

And than call it in the controller.


text:
Q: Azure DevOps API- How to create a repository? I'm developing a internal app that creates the skeleton of a solution according to internal guidelines.
As a improvement, I would like to enable the user to automatically have the solution "formalized" on our DevOps, where he would clone and start coding right away, instead of the current download as ZIP.
In order to do that, i started looking at the azure devops docs, but could not figure out a way to create a repository via API...
How can I do that?

A: Here is a sample of code we use in a PowerShell script to create repos
$repoBody = @{
    name = "YourRepoName"
} | ConvertTo-Json

Invoke-WebRequest -method Post -Headers @{Authorization = "Basic $encodedPat"} -body $repoBody -Uri $projUrl -ContentType "application/json" -UseBasicParsing

A: You have the Repositories - Create Rest API:
POST https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.0

Body:
{
  "name": "NewRepository",
  "project": {
    "id": "6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c"
  }
}

A: This is the API call you are looking for:
POST https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.0

Source: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories/create?view=azure-devops-rest-5.0

A: In addition, if you have the AZ modules loaded in powershell, you can simply execute
    az repos create --name "MyNewRepoName" --org "https://dev.azure.com/OrganizationName/" --project "ProjectNameToCreateRepoIn"

To install AZ modules in powershell use command
    Install-Module -Name Az -AllowClobber -Scope CurrentUser

With AZ modules installed execute this before creating repo
    Set-AzContext -SubscriptionId "YourSubscriptionID


text:
Q: "Users resort to seeking..." -- Is it correct to use a gerund like this? I am not sure if the use of a gerund is correct in the following sentence:

Users resort to seekING answers in social media

or

Users resort to seek answers in social media

I know that the rule is that if we can substitute the gerund with a noun then it's correct, otherwise I should use a verb. However, I'm not sure if using a noun would be correct. For instance:

Users resort to the search of answers in social media

But in the above sentence I also added the word of, so should I add of after the gerund in the original sentence, i.e. "seeking of answers" or it is correct even without it?


text:
Q: How do I access the RGB contents of a png image using the CImg library? So I've been searching for roughly a week on how to access the RGB contents of a specified pixel in c++, and haven't had the best of luck...
I did happen to find a library called CImg that fits what I want to do, but the code I've written keeps giving me errors and I don't know what I've done wrong.
#include "CImg.h"
#include <vector>
using namespace cimg_library;

std::vector<int> GetPixel(char file[50], int x, int y)
{
     CImg<int> image(file);

     int r = (int)image(x, y, 0, 0);
     int g = (int)image(x, y, 0, 1);
     int b = (int)image(x, y, 0, 2);

     std::vector<int> Pixel(2);

     Pixel[0] = r;
     Pixel[1] = g;
     Pixel[2] = b;

     return Pixel;
}

I'm using Microsoft visual studio 2017, and have included the directories for the CImg library... I doubt it's the libraries problem as when I comment out my code, it builds fine.
The errors in the compiler are such:
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(140): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(140): error C2146: syntax error: missing ';' before identifier 'PROPSHEETPAGE_RESOURCE'
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(198): error C3646: 'pResource': unknown override specifier
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(198): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(204): error C3646: 'pResource': unknown override specifier
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(204): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(213): error C3646: 'pResource': unknown override specifier
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(213): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(225): error C3646: 'pResource': unknown override specifier
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(225): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(244): error C3646: 'pResource': unknown override specifier
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(244): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(250): error C3646: 'pResource': unknown override specifier
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(250): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(259): error C3646: 'pResource': unknown override specifier
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(259): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(271): error C3646: 'pResource': unknown override specifier
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\prsht.h(271): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\commctrl.h(7770): error C2061: syntax error: identifier 'LPSCROLLINFO'
1>c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\commctrl.h(7785): error C2061: syntax error: identifier 'LPSCROLLINFO'
1>c:\users\micah notanalien\desktop\programming projects\chili directx framework\chili framework 2016\engine\drawgame.cpp(29): warning C4018: '<': signed/unsigned mismatch
1>c:\users\micah notanalien\desktop\programming projects\chili directx framework\chili framework 2016\engine\drawgame.cpp(31): warning C4018: '<': signed/unsigned mismatch
1>c:\users\micah notanalien\desktop\programming projects\chili directx framework\chili framework 2016\engine\drawgame.cpp(70): warning C4018: '<': signed/unsigned mismatch
1>c:\users\micah notanalien\desktop\programming projects\chili directx framework\chili framework 2016\engine\drawgame.cpp(72): warning C4018: '<': signed/unsigned mismatch
1>c:\users\micah notanalien\desktop\programming projects\chili directx framework\chili framework 2016\engine\drawgame.cpp(86): warning C4244: 'initializing': conversion from 'double' to 'int', possible loss of data
1>c:\users\micah notanalien\desktop\programming projects\chili directx framework\chili framework 2016\engine\drawgame.cpp(87): warning C4244: 'initializing': conversion from 'double' to 'int', possible loss of data
1>c:\users\micah notanalien\desktop\programming projects\chili directx framework\chili framework 2016\engine\drawgame.cpp(101): warning C4018: '<': signed/unsigned mismatch
1>c:\users\micah notanalien\desktop\programming projects\chili directx framework\chili framework 2016\engine\drawgame.cpp(103): warning C4018: '<': signed/unsigned mismatch

Any and all help is appreciated, and if someone has another library that works that would be just fine.
Thanks, Finn.
---EDIT---
This is the function using GetPixel() along with these two other GetWidth() and GetHeight() functions...
int GetWidth(char file[50]) {
    CImg<int> image(file);
    return image.width();
}

int GetHeight(char file[50]) {
    CImg<int> image(file);
    return image.height();
}

(and now the function using these functions)
void DrawGame::DrawSprite(char file[50], int x, int y)
{
    int width = GetWidth(file);
    int height = GetHeight(file);

    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++)
        {
            std::vector<int> Pixel;
            Pixel.resize(2);
            Pixel = GetPixel(file, i, j);

            SetVSPixel(x + i, y + j, Pixel[0], Pixel[1], Pixel[2]);
        }
    }
}

(and finally the main function)
#include "MainWindow.h"
#include "Game.h"
#include "DrawGame.h"
#include "ChiliException.h"

int WINAPI wWinMain( HINSTANCE hInst,HINSTANCE,LPWSTR pArgs,INT )
{
    try
    {
        MainWindow wnd( hInst,pArgs );
        try
        {
            DrawGame DrawTheGame(wnd);
            DrawTheGame.CreateMatrix();
            DrawTheGame.SetVSPixel(3, 5, 255, 255, 255);

            Game Player(wnd, DrawTheGame);

            while( wnd.ProcessMessage() )
            {
                DrawTheGame.Go();
                DrawTheGame.DrawSprite("person.png", 8, 8);
                Player.Go();
            }
        }
        catch( const ChiliException& e )
        {
            const std::wstring eMsg = e.GetFullMessage() +
                L"\n\nException caught at Windows message loop.";
            wnd.ShowMessageBox( e.GetExceptionType(),eMsg );
        }
        catch( const std::exception& e )
        {
            // need to convert std::exception what() string from narrow to wide string
            const std::string whatStr( e.what() );
            const std::wstring eMsg = std::wstring( whatStr.begin(),whatStr.end() ) +
                L"\n\nException caught at Windows message loop.";
            wnd.ShowMessageBox( L"Unhandled STL Exception",eMsg );
        }
        catch( ... )
        {
            wnd.ShowMessageBox( L"Unhandled Non-STL Exception",
                L"\n\nException caught at Windows message loop." );
        }
    }
    catch( const ChiliException& e )
    {
        const std::wstring eMsg = e.GetFullMessage() +
            L"\n\nException caught at main window creation.";
        MessageBox( nullptr,eMsg.c_str(),e.GetExceptionType().c_str(),MB_OK );
    }
    catch( const std::exception& e )
    {
        // need to convert std::exception what() string from narrow to wide string
        const std::string whatStr( e.what() );
        const std::wstring eMsg = std::wstring( whatStr.begin(),whatStr.end() ) +
            L"\n\nException caught at main window creation.";
        MessageBox( nullptr,eMsg.c_str(),L"Unhandled STL Exception",MB_OK );
    }
    catch( ... )
    {
        MessageBox( nullptr,L"\n\nException caught at main window creation.",
            L"Unhandled Non-STL Exception",MB_OK );
    }

    return 0;
}

The main function was used from a starter project by a YouTube channel I was watching to get used to c++.


text:
Q: Play Framework compiling causes "method render in class views cannot be applied to given types" error I am new to the Play Framework and am passing values from a controller to a view.  When I compile in activator (in the Command line), I receive this error:
[error] C:\WebDev\git\PlayAuthenticate\app\controllers\Application.java:633: met
hod render in class views.html.profile.profile cannot be applied to given types;
[error]   required: play.data.Form<controllers.Application.ProfileRegister>,java
.util.List<models.Service>
[error]   found: play.data.Form<controllers.Application.ProfileRegister>
[error]   reason: actual and formal argument lists differ in length
[error] profile.render

Here is my function in the controller:
public Result addProfile() {
    List<Service> services = Service.find.all();
    return ok(profile.render(form(ProfileRegister.class), services));
}

Here is the first line in the view.html.profile.profile:
@(profileForm: Form[Application.ProfileRegister], servicesList: java.util.List[Service])

I am not sure what I am missing.  When I remove the second parameter -- the List object -- it compiles.
I found a few posts, but it did not fix my problem:
Play Framework 2.2.1 - Compilation error: "method render in class index cannot be applied to given types;"
Compilation error: method render in class list cannot be applied to given types;
Thanks for the help!

A: It looks like Eclipse did not like the space between the parameters.  I removed the space and the project compiled.


text:
Q: How to Add/Remove class jQuery in filter? I have filter on my website. There are categories and it display services from category when you click on that category link.
I want to add animation for those posts, so when I click on category to animate those posts. I made animation and all I need is to add fade-in-services class to every post when I click on his category, and before that to remove if that post have fade-in-services class.
I have two lists, one for categories, other for posts and that looks like this

  All

  Cat1

  Cat2

Post 1

Post 2

Post 3

So when you click on All it displays all three posts, when click on Cat1 displays only Post 1 and Post 2, and when you click on Cat2 displays Post 3.
jQuery('.subcats li').click(function() {
    jQuery('.hp-single-service').addClass('fade-in-services');
    jQuery(this).removeClass('fade-in-services');
    });

and this work but not always, because jQuery(this) catch .subcats li and doesn't remove class fade-in-services. So when I go throw categories, if same post is in two categories that post doesn't animate because it have fade-in-service class.
How can I fix this?
Thank you!

A: I'm not sure your code does what you think it does. It does the following:

*

*Sets an on click event on the 3 li in the ul.subcats

*When one of the li is clicked it:
2a. Adds .fade-in-services to all elements with .hp-single-service
2b. Removes .fade-in-services from the clicked li
2bi. (which doesn't have the class at any point)


text:
Q: Select last N rows from MySQL - codeigniter I'm using codeigniter;
I would like to get last N rows from my table.
In my query I want to get last 200 rows:
         $this->m_general->select('count(*)');
         $this->m_general->from('pm');
         $result_count_query = $this->m_general->get();
         $count_query = $result_count_query->num_rows();

$data['all']     = $this->m_general->get('pm', array( 'admin_delete'=>0 ) , $count_query-200,$count_query, array('admin_seen'=>'asc' , 'id'=>'desc') );

but it returns nothing.
where is my wrong ?
updated
below query not worked fine and it returns all records :
$data['all']     = $this->m_general->get('pm', array( 'admin_delete'=>0 ) ,200, array('admin_seen'=>'asc' , 'id'=>'desc') );

A: Check out the API

https://ellislab.com/codeigniter/user-guide/database/active_record.html

Looks like you can't do this with the get method.
Build your query according to the API.
$this->m_general->limit(200);
$this->m_general->order_by("admin_seen", "asc");
$this->m_general->order_by("id", "desc");

$data['all']     =
$this->m_general->get('pm', array( 'admin_delete'=>0 ));

A: This Solve the Problem
$query = $this->db->query("SELECT * FROM pm WHERE admin_delete= 0 AND admin_seen=0 ORDER BY id DESC LIMIT  200");
$result = $query->result_array();
$count = count($result);

if(empty($count))
{
    echo 'array is empty';
}
else{
    return $result;
}


text:
Q: Javascript native method throws unexpectedly exception I am updating a vaadin project from vaadin 6 version to vaadin 7. It contains some native Javascript methods which work well in the old version. However some of them throw an exception when they should be called. I am not acquainted enough to Javascript programming and therefore I am not able to identify the source of the error. In particular the method is:
 protected static native void addSthToImg()
    /*-{
        $wnd.$(document).ready(function() {
            var = $wnd.$;
            var('.settingswrapper > img').addClass("imgStartup");
            if (var('.settingswrapper > img').hasClass("imgStartup")) {
                console.log("imgStartup exist");
                var('.settingswrapper > img')
      .animate(null, 300, function() {
                    var('.settingswrapper > img').removeClass("imgStartup");
                    var('.settingswrapper > img').addClass("imagePopIn");

                });
            }
        });
    }-*/;

On the Console in Chrome I see the error stack trace:
Caused by: com.google.gwt.core.client.JavaScriptException: (TypeError) : Object [object global] has no method '$'

What could be a possible cause of the error and why is it working in the old version? Is a jar/library missing?

A: Seems like jQuery alias $ is not defined in the global scope (denoted by $wnd). Are you sure your page includes jQuery?
You should have something like <script src="/js/jquery.js" type="text/javascript"></script> (but pointing to the actual location of jquery.js in your project) in your HTML source. I don't know if Vaadin manages JavaScript libraries automatically, since I'm not familiar with the framework.


text:
Q: why my union index not working in MySQL 5.7 I create a union index in my table like this:
CREATE INDEX app_list_idx ON report_envelope_app_list (created_time,round_id,app_id);

this is the created result:

then I using this to see, but not using the index:
explain select *
from report_envelope_app_list
where created_time > 1598716800000
and created_time < 1599716800000

this is the explain result:

why the index not working? what should I do to fix it? created a single created_time index? the a,b,c index will work with the left match rule a.This is my table DML:
CREATE TABLE `report_envelope_app_list` (
  `id` bigint(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `send_time` bigint(11) NOT NULL COMMENT '发包时间',
  `sender` bigint(11) NOT NULL COMMENT '发包人',
  `sender_name` varchar(256) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '发包人姓名',
  `code` varchar(128) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '房间编号',
  `room_type` int(11) NOT NULL COMMENT '房间公私类型',
  `house_type` bigint(11) NOT NULL COMMENT '房间创建类型',
  `room_type_name` varchar(256) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '房间公私类型名称',
  `house_type_name` varchar(256) COLLATE utf8mb4_bin DEFAULT '' COMMENT '房间类型',
  `room_amount` int(11) NOT NULL DEFAULT '0' COMMENT '普通房间数',
  `room_id` bigint(11) NOT NULL COMMENT '房间类型ID(与house_type一致)',
  `room_play_id` bigint(20) DEFAULT NULL,
  `room_play_name` varchar(256) COLLATE utf8mb4_bin DEFAULT NULL,
  `deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除',
  `wallet_id` bigint(20) NOT NULL COMMENT '红包ID',
  `created_time` bigint(20) NOT NULL COMMENT '创建时间',
  `updated_time` bigint(20) NOT NULL COMMENT '更新时间',
  `room_amount_range` varchar(256) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '房间金额范围',
  `round_id` bigint(20) DEFAULT NULL COMMENT '局ID',
  `app_id` bigint(20) NOT NULL COMMENT '应用ID',
  `app_mark` varchar(128) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '应用标记',
  `room_amount_fmt` varchar(256) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '房间金额格式化',
  `tenant_id` bigint(20) NOT NULL COMMENT '租户ID',
  PRIMARY KEY (`id`),
  KEY `app_list_idx` (`created_time`,`round_id`,`app_id`)
) ENGINE=InnoDB AUTO_INCREMENT=705829 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='游戏记录';

A: If more than about 20% of the table is being extracted, the index is a waste of time.  To see this, try a smaller range.
The explain 585K of 705K rows will be extracted.  The bouncing back and forth between the index's BTree and the data's BTree is not worth the effort.  It is much faster to simply scan the data, ignoring rows that don't match.
(Your Question is a common one.  My Answer is always about the same.)


text:
Q: Test Suite for Double Metaphone? I've translated Double-Metaphone into ActionScript3 and I want to test it (obviously) before I release the source to ... um ... the open.
I'm looking for a long list of names with the primary and secondary codes. Google does not find anything except one list with pairs of names (presumably they should match).
Thanks

A: You could find someone else's double metaphone implementation, run it on the same long list of words, and compare the results to your own.
For long lists of words, I like infochimps.  They have lots of word lists, like this one of 350,000 english words or this one of place names, and many more.
Here are implementations you can compare your results against.  Here is an online example, except that it tests only one word at a time - I guess you'll have to download and run one of the scripts to test a large list of words.
For each word, two codes will be returned; you'll probably want to test that both codes returned match the ones returned of another implementation.  You probably know that the reference implementation is here with full source code here, but including the links anyway for others' benefit.


text:
Q: Add clickable function in functions.php - parse error I'm trying to add onclick event to a div. But Wordpress keep saying that my function is undefined.

Uncaught ReferenceError: thfull is not defined

function thfull()  {
echo "document.getElementById('thf').style.maxHeight = '1000px';";
}
add_action('wp_enqueue_scripts', 'thfull');

html:

< div class="thumbnail" id="thf" onclick="thfull()">

The whole point is to toggle css class on div.
I'm a total noob when it comes to JS and stuff like that... Please help.

A: For clarity's sake regarding my comments, this is something more akin to what I'm talking about...
// plugins/wpse392844/wpse392844.php

function wpse392844_enqueue_assets() {
  wp_enqueue_script(
    'wpse392844-frontend',
    plugins_url( 'assets/js/frontend.js', __FILE__ )
  );
}

add_action( 'wp_enqueue_scripts', 'wpse392844_enqueue_assets' );

// plugins/wpse392844/assets/js/frontend.js

function thfull() {
  document.getElementById('thf').style.maxHeight = '1000px';
}

(we're defining the thfull() function in JavaScript rather than PHP such that the browser will be aware of and able to use it. The PHP just makes sure that the browser loads the JS)


text:
Q: Php is not loop when having another foreach inside I'm so tired of finding out why the code is not loop with foreach in place. 1st loop is fetching the person name from db I use while loop as usual and it works. 2nd loop I test the total action each one of them doing in a month so I use a foreach loop for each month. But the problem is here. I can't make it loop again because of no clue.
Here's my codes:
error_reporting(E_ALL);
$thisYear=intval(date("Y"));

for($i=1;$i<13;$i++){
    $i=sprintf("%02d",$i);
    $monArr[]=$i;
}

//select all team members
$sql_sTeam=mysqli_query($con,"select * from TEAMNAMES order by fname asc");
$result=array();
while($rec_sTeam=mysqli_fetch_array($sql_sTeam)){
    $rows['name']=$rec_sTeam['sale_fname'];//sale name

    foreach($monArr as $key=>$val){
        //$rows['data'][]=(int)$key;
        $mon=intval($val);
        //n action each member\
        $sql_mLog=mysqli_query($con,"select * from mail_log where mlog_sid='$rec_sTeam[imap_sid]' and year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
        $num_mLog=mysqli_num_rows($sql_mLog);
        $rows['data'][] =(int)$num_mLog;//(int) will remove double qoutes around numbers
    }//foreach

    array_push($result,$rows);
}//while
echo json_encode($result);

There're 4 people in TEAMNAMES but this is the only result from json_encode:
[{"name":"Ar-eshah","data":[0,0,0,0,0,0,6,0,0,0,0,0]}]

Please point me out of here coz I'm stuck for several hours.
Regards,

A: Here the solution that you are looking for:
error_reporting(E_ALL);
$thisYear = intval(date("Y"));

for($i = 1; $i < 13; $i++){
    $i = sprintf("%02d",$i);
    $monArr[] = $i;
}

//select all team members
$sql_sTeam = mysqli_query($con,"select * from TEAMNAMES order by fname asc");
$result=array();
while($rec_sTeam=mysqli_fetch_array($sql_sTeam)){
    $row = array();
    $row['name']=$rec_sTeam['sale_fname'];//sale name
    $row['data'] = array();

    foreach($monArr as $key=>$val){

        $mon=intval($val);
        //n action each member\
        $sql_mLog=mysqli_query($con,"select * from mail_log where mlog_sid='$rec_sTeam[imap_sid]' and year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
        $num_mLog=mysqli_num_rows($sql_mLog);
        $row['data'][] =(int)$num_mLog;//(int) will remove double qoutes around numbers
    }//foreach

    $result[] = $row;
}//while
echo json_encode($result)

A: Any MySQL errors? In this line:
    $sql_mLog=mysqli_query($con,"select * from mail_log
where mlog_sid='$rec_sTeam[imap_sid]' and
year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");

You need to brake the string in order to add an array value or use curly braces... like this:
    $sql_mLog=mysqli_query($con,"select * from mail_log
where mlog_sid='".$rec_sTeam[imap_sid]."' and
year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");

OR
    $sql_mLog=mysqli_query($con,"select * from mail_log
where mlog_sid='{$rec_sTeam[imap_sid]}' and
year(mlog_dtime)='{$thisYear}' and month(mlog_dtime)='{$mon}' ");

An example:
    $a = array("name"=>"predte4a");
echo "My name is: $a['name']";
// will echo My name is array()['name']
echo "My name is: {$a['name']}";
//will echo My name is predte4a

And do not forget the quotes in your associative array keys


text:
Q: Best way to implement view count logic in Django I've been building my personal blog using Django and I must say that I'm learning a great deal. One of those things being the fact that the implementing the view count logic is not as simple as doing view_count += 1. So far, I've done some research and narrowed my options to

*

*Using Django's F-expression

*Using django-hitcount module

*Learn more about how sessions work and see if I can make it work with Django's sessions.

The reason I ask this is that I want to implement a more Youtube like logic for my posts. Users must view the article for a certain length (time or word wise).
What do you think is the best way to go about this?
Any references to helpful articles are greatly appreciated.
Thanks!


text:
Q: Do I need JRE_HOME? Tomcat java environment version difference Recently I had come across an error while running a basic webapp in tomcat.
The error was "class has been compiled by a more recent version of the Java Environment". I am using jdk-11.0.2 and jre1.8.0_201. Then I came across this page about setting tomcat server which says :
If both JRE_HOME and JAVA_HOME are specified, JRE_HOME is used
So I tried deleting the JRE_HOME variable and that solved the error.
Is this the right method to solve the issue? Is it possible to make JRE_HOME invisible for tomcat alone? Am I going to need JRE_HOME anywhere else?

A:
So I tried deleting the JRE_HOME variable and that solved the error.
  Is this the right method to solve the issue?

Yes. Based on your information , your web app requires Java version >8 to run. And what you do here is to ensure that Tomcat is using Java 11 to run which is the right direction to solve the problem.
Also , it is very normal that you only set JAVA_HOME but not set JRE_HOME because behind the scenes if you do not set JRE_HOME , Tomcat startup script (setclasspath.bat) will automatically set JRE_HOME for you based on the JAVA_HOME value.
You can also customize / override JRE_HOME or JAVA_HOME by creating a setenv.sh inside bin folder. All settings inside setenv.sh is only applied for the Tomcat  :
export JAVA_HOME=/path/to/jdk-11.0.2


text:
Q: Unable to load database in SSDT for Visual Studio 2013 SSDT for Visual Studio 2013 is not populating my databases when am creating a package in SSIS. I can however access these databases in SSMS.
Any help?


text:
Q: Handle multiple file selection I have the following code:
void OpenJpgFile(HWND hWnd)
{
OPENFILENAME ofn;
wchar_t szFileName[17*MAX_PATH] = L"";

ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrTitle = L"Selecione as fotos que deseja adicionar...";
ofn.lpstrFilter = L"Arquivos JPEG (*.jpg)\0*.jpg\0Todos os Arquivos (*.*)\0*.*\0";
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT;
ofn.lpstrDefExt = L"jpg";
if(GetOpenFileName(&ofn))
{
            //Test
    MessageBox(hWnd,ofn.lpstrFileTitle,L"TESTE",NULL);

            if(gpBitmap)
    {
        delete gpBitmap;
    }
    gpBitmap = new Bitmap(szFileName);

        InvalidateRect(hWnd, NULL, TRUE);
        UpdateWindow(hWnd);
    }
}

What I wanted to know is how can I get the name of all files the user has selected...
All I can get is the path to the folder... is there an array that keeps the file names?

A: Per the documentation of OFN_ALLOWMULTISELECT when OFN_EXPLORER is also specified, lpstrFile will contain the directory followed by the names of the files, separated by null characters, and terminated with two adjacent null characters. When you call new Bitmap(szFileName) you are treating szFileName incorrectly - that is you pass it to a constructor that expects a standard single-null terminated string. Instead you have to process it more carefully to read past the initial null, and probably recreate your full file paths.
This string format happens to be the same format as used for REG_MULTI_SZ so, aside from not having to worry about missing final terminators, advice related to handling values of type REG_MULTI_SZ can help you here.
Note that to be fully general, you may also have to handle cases that require a larger buffer. See GetOpenFileName() with OFN_ALLOWMULTISELECT flag set for another angle on that


text:
Q: Does this algorithm have time and space complexity O(n) or O(1)?
Update:
  - Wikipedia says o(n) not O(n) so this algorithm isn't an in-place solution.
  - Debating whether this solution runs in O(n) or O(1).

This is my solution for LeetCode question Flatten Binary Tree to Linked List. In terms of time and space complexity analysis, I'm not quite sure it's O(1) according to some explanations. I think it's O(n) because of the use of the stack. Is my analysis correct?
According to Wikipedia, O(n) is still accepted as in-place.

More broadly, in-place means that the algorithm does not use extra space for manipulating the input but may require a small though nonconstant extra space for its operation. Usually, this space is O(log n), though sometimes anything in o(n) is allowed.

/**
 * Function flattens a binary tree.
 * Time = O(n) because we iterate through all nodes.
 * Space = O(n) because we use a stack.
 * @param {root} root Input tree.
 */
var flatten = function(root) {
    // If reach end of leaf node, return.
    if (root === null) return;

    let stack = [];
    let currentNode = root;

    while (true) {
        // Push right branch to stack first,
        if (currentNode.right) stack.push(currentNode.right);
        // then left branch.
        if (currentNode.left) stack.push(currentNode.left);
        // If there are branches in stack:
        if (stack.length > 0) {
            // Change the current currentNode right branch to the last element of the stack:
            currentNode.right = stack.pop();
            // Change left branch to null
            currentNode.left = null;
            // Advance by changing current currentNode to the right currentNode.
            currentNode = currentNode.right;
        }
        else break;
    }
}

A: Yes, the algorithm uses Theta(N) worst-case time and worst-case additional space where N is the number of nodes in the tree. The time complexity is is clear, because you push and pop each node once.
The space complexity is a bit more tricky, but consider for example a tree that is a list where the next elements of the list are the left children, but assume it has additionally for each of these list nodes one right child which itself does not have any children.
With that example your algorithm will walk through the left-hand nodes, adding the right-hand ones to the stack, but only popping those once the end of the original list is reached, i.e. there will be about N/2 elements in the stack.
Best-case, the time complexity is still Theta(N), because you always iterate over all nodes, but the best-case space complexity is Theta(1), because e.g. a tree that is already a list will never increase the stack size to more than 1.
This would usually not be considered an in-place algorithm, because it uses additional Theta(N) space, at least worst-case. As explained in the Wikipedia article, an in-place algorithm should require o(N) additional space or, I would say, usually only O(1) or slightly more than that, e.g. O((ln N)^k) for some k maximum. Whether one should count worst-case or average-case is another question.
o(N) is the little-o notation, not the big-O notation. It means the the time/space is asymptotically smaller than c*N for every c > 0. Theta(N) is therefore never o(N).
Also, Theta(N) means that not only is it O(N), meaning asymptotically smaller then c*N for some c > 0, but also that it is asymptotically larger than c*N for some c.
If you want an in-place algorithm by the stricter definition, you should not require any additional container of dynamic size.


text:
Q: How to migrate spring boot admin server and client into one spring boot application I'm using spring boot admin to monitor my springboot application, it's pretty good. But I need to start spring boot admin server firstly and then start my application which contains spring boot client.
Is there a way to contain the spring boot server into my spring boot application, make them looks like one application, so that I can just start my application, then the server started and the client registerd to the server. The ultimate purpose is my application is running on port 8080, and the spring boot admin is running on port 8081.
I have checked this thread: How to run spring boot admin client and server in same application but it doesn't contain any details, I can't implement with the possible solution.
PS: I know I can package the spring boot admin server, and then write the start.sh, startup the server firstly and then start my application, but it's not a pretty solution.
Anyone can help?
SpringBoot version: 2.3.4.RELEASE
Spring Boot Admin version: 2.3.0

A: Technically this should be possible to integrate both in one single application, but I'm afraid you'll run into problems soon.
But let us give it a try...
Reference: Proof of concept GitHub
Problems with this approach:

*

*launch 2 servers on startup: the client on port 8080, and the admin-server on port 8081

*the client and the server should have separate configurations

Let's start with the configuration
We could separate the multiple configurations by using a profile so we can take advantage of Profile Specific Files
application-client.properties
server.address=localhost
spring.boot.admin.client.url = http://localhost:8081/
management.endpoints.web.exposure.include = *
management.endpoint.health.show-details= always

spring.application.name=client-app
spring.boot.admin.client.instance.name=client-app

application-admin.properties
server.address=localhost
server.port=8081

Launch the server, and the client with the correct profile.
DemoApplication
public class DemoApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication admin = new SpringApplication(DemoAdminServer.class);
        admin.setAdditionalProfiles("admin");
        admin.run(args);

        SpringApplication client = new SpringApplication(DemoClient.class);
        client.setAdditionalProfiles("client");
        client.run(args);
    }
}

@EnableAdminServer
@Configuration
@EnableAutoConfiguration
@Profile("admin")
class DemoAdminServer {

}

@SpringBootApplication
@RestController
@Profile("client")
class DemoClient {

    @GetMapping
    public String hello(){
        return "Hello world!";
    }

}

Launch the Application, and we should be good...

*

*client

*admin-server

If you have two separate applications, then in your client you could launch the admin-server via a process.
@SpringBootApplication
public class ClientApplication {

    public static void main(String[] args) throws Exception{
        startAdminServer();
        SpringApplication.run(DemoApplication.class, args);
    }

    static void startAdminServer() throws Exception {
        new ProcessBuilder()
                .redirectErrorStream(true)
                .command("cmd.exe",
                         "/c",
                         "java -jar path_to_your_admin_server.jar")
                .start();
    }
}

A: Explore spring multi-module feature for solving your use-case.
Have your spring boot server as a parent project and add all your spring boot client projects as individual modules. All these individual modules are nothing but a spring boot application. You can package and deploy those individual modules on any different ports.

A: An easier solution would be to have the applications run inside containers and will be better to have them isolated instead of turning them into a monolith.
You can build your applications using docker (https://spring.io/guides/gs/spring-boot-docker/)
Basically you will have a docker file for each app, something like this:
FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

And start them using docker-compose
version: '3.7'
services:
  spring-boot-admin:
    image: spring-boot-admin-image
    container_name: spring-boot-admin
    ports:
      - 8081:8081
    healthcheck:
      test: "curl --fail --silent localhost:8081/actuator/health | grep UP || exit 1"
      interval: 20s
      timeout: 5s
      retries: 5
      start_period: 40s

  spring-boot-client:
    image: spring-boot-client-image
    container_name: spring-boot-client
    ports:
      - 8080:8080
    depends_on:
      - spring-boot-admin

The depends_on will make sure your spring-boot-client starts after spring-boot-admin is healthy


text:
Q: Spring, CGLIB: why can't a generic class be proxied? I'd like to ask about the root cause of the exception:
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to
java.lang.reflect.ParameterizedType

which happens in Spring when we make Spring generate proxies for classes (i.e. setting proxy-target-class="true" on a transaction manager):
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true"/>

and when the class to proxy is a parameterized class, i.e.
public class SomeDAOImpl<SomeEntity> implements SomeDAO ...

The full story can be, for example, read in this question: Abstract DAO pattern and Spring's "Proxy cannot be cast to ..." problem!
Question: why can't Spring proxy this class? Is it because it uses old code generation libraries? Because of type erasure? If the SomeDAOImpl was not a generic class, it would succeed (I checked that).
Please don't answer like: "you should proxy interfaces, not classes". I know that.

A: This looks like a Spring/CGLIB problem but the issue is actually in your constructor!  I'm guessing you are trying to get the parameter type so that you can supply it to the entity manager (or whatever persistence framework you're trying to use).  I'm also guessing that to do that you are calling getGenericSuperclass() and casting it to a ParameterizedType?
The way that method behaves depends on the class.  It turns out that not all Class objects implement the ParameterizedType interface (which I agree, is bizarre).  The generated CGLIB proxies do not keep the generics information.  It looks something like:
public class SomeDAOImplProxy extends SomeDAOImpl

I don't actually know why CGLIB proxies don't keep the generics as the details of CGLIB proxies are very complex.  It could be that it is simply impossible to do so.  It could also be that doing so is not a priority to them.
Here is a simple experiment which takes Spring and CGLIB out of the picture but still gets that error.
public static void main(String [] args) {
    List<Object> fooList = new ArrayList<Object>();
    String fooString = "";
    System.out.println((ParameterizedType)fooList.getClass().getGenericSuperclass());
    System.out.println((ParameterizedType)fooString.getClass().getGenericSuperclass());
}

A: Since CGLIB subclasses your class to generate the proxy, you have to get the generic superclass of the superclass to get the ParameterizedType:
public class MyCglibProxiedBean<T> {

    private final Class<T> paramClass;

    public MyCglibProxiedBean() {
        Type genericSuperClass = getClass().getGenericSuperclass();

        // Get the generic super class of the super class if it's a cglib proxy
        if (getClass().getName().contains("$$EnhancerByCGLIB$$")) {
            genericSuperClass = getClass().getSuperclass().getGenericSuperclass();
        }

        this.paramClass = (Class<T>) ((ParameterizedType) genericSuperClass).getActualTypeArguments()[0];
    }
}

A: We use a solution similar to James's answer but IMHO a little bit more general:
Type genericSuperClass = repositoryClass.getGenericSuperclass();
ParameterizedType parametrizedType;
if (genericSuperClass instanceof ParameterizedType) { // class
    parametrizedType = (ParameterizedType) genericSuperClass;
} else if (genericSuperClass instanceof Class) { // in case of CGLIB proxy
    parametrizedType = (ParameterizedType) ((Class<?>) genericSuperClass).getGenericSuperclass();
} else {
    throw new IllegalStateException("class " + repositoryClass + " is not subtype of ParametrizedType.");
}

@SuppressWarnings("unchecked")
Class<T> entityClass = (Class<T>) parametrizedType.getActualTypeArguments()[0];
return entityClass;

A: I managed to solve the problem with this code:
Type t = getClass();
do {
  t = ((Class<T>) t).getGenericSuperclass();
} while (!(t instanceof ParameterizedType));
ParameterizedType pt = (ParameterizedType) t;
actualGenericType = (Class<T>) pt.getActualTypeArguments()[0];

I think it's a bit cleaner solution because it doesn't use internal structure of CGLIB.


text:
Q: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 I am making a shop and using an input to get results, now I have the AJAX that calls the PHP script and it calls it fine, but I get an error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064

NOTE: The error line is the $query->execute(array(':input'=>$input)) line
here's the AJAX script ( + HTML calling the function )
                     <input type="text" name="search_item" onkeyup="showItems(this.value)" id="search_item">
                     <script>
                        function showItems(str) {
                            if (str.length == 0) {

                            } else {
                                var xmlhttp = new XMLHttpRequest();
                                xmlhttp.onreadystatechange = function() {
                                    if (this.readyState == 4 && this.status == 200) {
                                        document.getElementById("items").innerHTML = this.responseText;
                                    }
                                };
                                xmlhttp.open("GET", "searchScript.php?iName=" + str, true);
                                xmlhttp.send();
                            }
                        }
                    </script>

and here's the called PHP:
    $input = $_REQUEST["iName"];
    $input = "%".$input."%";
$dsn = 'mysql:host=xxx.com;dbname=dbNameHidden;charset=utf8mb4';
$username = 'hidden';
$password = 'hidden';

try{
    // connect to mysql
    $con = new PDO($dsn,$username,$password);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
    echo 'Not Connected '.$ex->getMessage();
}
$query = $con->prepare("SELECT * FROM store AS s INNER JOIN product_pictures AS pp ON s.product_id = pp.id INNER JOIN product_name AS pn ON s.product_id = pn.id WHERE product_name LIKE %:input% LIMIT 9 ");
$query->execute(array(':input' => $input));
$items = $query->fetchAll();

A: Add the wildcards to the parameter:
$query = $con->prepare("SELECT ... WHERE product_name LIKE :input LIMIT 9 ");
$query->execute(array(':input' => '%' . $input. '%'));

That way the wildcards are contained in the value, essentially making the query like this:
SELECT .... WHERE product_name LIKE '%name%'

A: Your query results in LIKE %'something'% which is not correct. Add % to the variable not the query. You want something like:
$input = "%$input%";

$query = $con->prepare("SELECT * FROM store AS s
                        INNER JOIN product_pictures AS pp ON s.product_id = pp.id
                        INNER JOIN product_name AS pn ON s.product_id = pn.id
                        WHERE product_name LIKE :input LIMIT 9 ");
$query->execute(array(':input' => $input));


text:
Q: ant build : unable to locate tools.jar. Expected find it in C:\Program Files\Java\jre7\lib\tools.jar I know that this question is popular, but no one of solutions can help me.
I used this, this, this and this solutions, but no one help me.
I want to implement uiautomator Tests and need to build my build.xml with ant, but get this strange error.
I use Windows 8.1
My JAVA_HOME system variable set to c:\programs files\java\jdk1.7.0_51 and to c:\programs files(x86)\java\jdk1.7.0_51
My PATH system  variable set also to %JAVA_HOME%/bin, my %ANT_HOME% is set to c:\apache-ant.
But when I execute ant build in the android app derictory I get the
unable to locate tools.jar. Expected find it in C:\Program Files\Java\jre7\lib\tools.jar
BUILD FAILED
Perhaps JAVA_HOME does not point to the JDK

But my JAVA_HOME points to right JDK ! I confused with this. I also rebuild my build several times, I've got the same.
Will be glad if somebody help me.

A: I too had this problem and solved it by setting variables like this :
[1] ANT_HOME - C:\apache-ant-1.9.3

[2] JAVA_HOME - C:\Program Files\Java\jdk1.7.0_21

[3] PATH - D:\Android_Development\android_sdk\platform-tools\;%ANT_HOME%\bin;%JAVA_HOME%\bin;D:\Android_Development\android_sdk\tools

Note : Set all these in System variables not in user variables.
This solved my problem.
Hope it helps.

A: In regards to the tools.jar, I experienced the following: when downloading ant, it came with open java 7. However, the system I had downloaded, uses Java 8 u 40 (the Oracle version). Therefore, when I pointed the lib/jre via a softlink in linux, to the place of the tools.jar, I got the error, that now the version/subversion was not matching. This because ant was using version 7, and the tools.jar from Oracle was now version 8.
The solution was, to use the above help (with the setting of the JAVA_PATH to become my Oracle version 8u40 of Java), such that both the compiler and the tools.jar file is of same version.
The scenario I am in, therefore has the jdk downloaded as it came from Oracle in my /home/david/Desktop/Android5.0/jdk1.8.0u40 directory - the Android packages as they came in /home/david/Desktop/Android5.0 directory, my Eclipse workspace in /home/david/workspace - and now I hope to be better to go.
The ant-file build.xml is placed in my /home/david/workspace directory - and it is looking like this:
<project>
    <target name="clean">
        <delete dir="build"/>
    </target>

    <target name="compile">
        <mkdir dir="build/classes"/>
        <javac srcdir="src" destdir="build/classes"/>
    </target>

    <target name="jar" depends="compile">
        <mkdir dir="build/jar"/>
        <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="oata.HelloWorld"/>
            </manifest>
        </jar>
    </target>

    <target name="run" depends="jar">
        <java jar="build/jar/HelloWorld.jar" fork="true"/>
    </target>

</project>

The java file in this question - HelloWorld.java, is being put into the directory /home/david/workspace/build/src/oata - and it now compiles to its destination you can see above, and from there the jar file is being built too.
True - there are methods where one can make one version of Java pretend to be another - but I didn't want to go there, because I am setting up a build environment where I can do extracts from the repository, build, and storing of the built code into a download site.
The above build.xml sample is slightly modified from the following Ant tutorial for build: https://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html
Guys - hope it works for you too, because ant is really one of the best ways of building, as you can invoke it from the command line, you can make it pick files from the repository first (GitHub or BitBucket etc.), and then you can FTP the compiled result to your preferred download site for developers, you can zip together the code such that you have the version ready and zipped in worst case...

A: Copy the tools.jar from C:\Program Files\Java\jdk1.8.0_91\lib and pate to C:\Program Files\Java\jdk1.8.0_91\bin. It worked fine for me in my case

A: *

*Set in the system-variables:

*

*JAVA_HOME: C:\Program Files\Java\jdkVERSION

*ANT_HOME: C:\Program Files\apache-ant-VERSION

*PATH: %JAVA_HOME%\bin;%ANT_HOME%\bin;... (at the beginning of the PATH-variable)

*Remove everything related to Java/Ant from the user-variables

*Restart the commandline (!) to receive the new Variables in the context of the running instance.

A: To Recover this problems you can just copy the tools.jar from "C:\ProgramFiles\Java\jdk1.7.0\lib" directly into "C:\Program Files\Java\jre7\lib\".You will successfully recover the problems.
It works!..

A: I solved issue with setting %JAVA_HOME% to start of the PATH. It worked for me when I set it exactly to the start.

A: Check the value of JAVA_HOME and PATH variable, sometime you might be putting
JAVA_HOME="C:\Program Files\Java\jdk1.8.0\bin" .

instead of
JAVA_HOME="C:\Program Files\Java\jdk1.8.0" .

and PATH=%JAVA_HOME%\bin;%PATH% .
just echo out the PATH variable in CLI.
echo %PATH%.

A: kindly set the system variable for JDK not JRE. this will solve the problem

A: Follow the below steps to resolve the issue:
Goto Control Panel -> Set below environment variables:

*

*ANT_HOME - C:\apache-ant-1.9.14

*JAVA_HOME - C:\Program Files\Java\jdk1.8.0_181

*PATH - %ANT_HOME%\bin;%JAVA_HOME%\bin;

A: This is because editing the environmental variables instead of creating new one. Though java home and path variables were set, it is not pointed properly.
Just delete java home and path variable and add it again.
This one fixed my issue.


text:
Q: How to check Internet bandwidth in Ubuntu? Instead of going to sites like http://speedtest.net , or others, I want to check my current Internet speed from the terminal on Ubuntu. How can I do it?

A: Theres a cli tool for speedtest.net:
https://github.com/sivel/speedtest-cli
An other option would be to measure the download time for a big file (>100 MB) from a known to be fast server and calculate the current bandwidth from that. I wrote a munin plugin quite a time ago, which was doing this perfectly fine.
A good starting point is the following command:
time(wget –output-document=/dev/null http:///files/downloadtest 2>/dev/null 1>&2)

A: Let my start by saying that "your internet speed" typically isn't fixed.
It depends on the path between your end of the connection and the other end-point. And along that path there can be traffic shaping, high bandwidth connections, slower links, congestion, low latency connections or high latency links (satellite uplink anyone?) etc. and the cumulative effect of all segments determines that effective "speed", with the lowest bandwidth segment typically being the limiter on bandwidth and latency being cumulative.
But having said that:
ethtool will give the negotiated/configured link speed between your Linux server's ethernet device and whatever (typically the switch port) it is connected to:
ethtool  eth0
Settings for eth0:
    ...
    Speed: 1000Mb/s
    Duplex: Full
    ...

So the speed between my server and the switch is 1 GBit/s.
That of course doesn't even imply that I get such bandwidth when downloading research data from McMurdo station on Antarctica!
Another tool is iperf which can be used to measure maximum TCP/IP performance from the commandline.  You can use that to for instance measure the bandwidth you get between your server and your gateway and between your server the next hop from your gateway to your ISP.


text:
Q: Why assertThat().isEqualTo yields different results than equals with Hibernate? I use festAssertions in my tests and I noticed that using assertThat(object).isEqualTo(otherObject) yields different results than assertThat(object.equals(otherObject)).isTrue(); in tests where hibernate objects are tested.
I had to do workaround and now test looks really ugly but I cannot use
assertThat(collection).contains(object1, object2) because that just does not work!
Here is partial code(look at last line):
seasonRate, seasonRate1 are created and persisted. Then retrieved from db and checked against originals. Nothing fancy, but does not work with festAssertions.
Do you have any idea how to fix that and if it is some error on my side or not?
    (...)
    session.save(seasonRate);
    session.save(seasonRate2);

    session.getTransaction().commit();
    session.close();

    session = sessionFactory.getCurrentSession();
    session.beginTransaction();
    RateRepositoryHibernate rateRepositoryHibernate= new RateRepositoryHibernate(new StubHibernateSessionFactory(sessionFactory));
    // when
    final Collection<Rate> allRatesForRoom = rateRepositoryHibernate.getAllRatesForRoom(room);

    // then
    assertThat(allRatesForRoom.size()).isEqualTo(EXPECTED_RATES);
    for(Rate rate : allRatesForRoom)
    {
        if(rate.getRateName().equals("season name 2"))
        {
            assertThat(rate.equals(seasonRate2)).isTrue();
        }
        if(rate.getRateName().equals("season name"))
        {
            assertThat(rate.equals(seasonRate)).isTrue();
        }
    }
    //assertThat(allRatesForRoom).contains(seasonRate, seasonRate2); // this does not work somehow

A: It turns out that this is not festAssertions issue because after changes to code I cannot reproduce that bug and .contains method works nicely.
My changes were related to current session concept and I probably had some bad code.
If you happen to face similar issue then you should look for problems in your hibernate related code and configuration but not inside festAssertions.


text:
Q: First appearance of a condition in a dataframe I have a pandas dataframe like this:
    col
0   3
1   5
2   9
3   5
4   6
5   6
6   11
7   6
8   2
9   10

that could be created in Python with the code:
import pandas as pd

df = pd.DataFrame(
    {
        'col': [3, 5, 9, 5, 6, 6, 11, 6, 2, 10]
    }
)

I want to find the rows that have a value greater than 8, and also there is at least one row before them that has a value less than 4.
So the output should be:
    col
2   9
9   10

You can see that index 0 has a value equal to 3 (less than 4) and then index 2 has a value greater than 8. So we add index 2 to the output and continue to check for the next rows. But we don't anymore consider indexes 0, 1, 2, and reset the work.
Index 6 has a value equal to 11, but none of the indexes 3, 4, 5 has a value less than 4, so we don't add index 6 to the output.
Index 8 has a value equal to 2 (less than 4) and index 9 has a value equal to 10 (greater than 8), so index 9 is added to the output.
It's my priority not to use any for-loops for the code.
Have you any idea about this?

A: Boolean indexing to the rescue:
# value > 8
m1 = df['col'].gt(8)

# get previous value <4
# check if any occurred previously
m2 = df['col'].shift().lt(4).groupby(m1[::-1].cumsum()).cummax()

df[m1&m2]

Output:
   col
2    9
9   10

A: Check Below code using SHIFT:
df['val'] = np.where(df['col']>8, True, False).cumsum()

df['val'] = np.where(df['col']>8, df['val']-1, df['val'])

df.assign(min_value = df.groupby('val')['col'].transform('min')).\
query('col>8 and min_value<4')[['col']]

OUTPUT:


text:
Q: What method to use to fire an event after datetime is selected using datetime selector UI? I came across a datatimepicker plugin
I am trying to use it in a small app that I am working on. I need to be able to enable a button after a user selects data from the picker.
What method would use to trigger some logic after the datetime was selected

A: You could bind an event to your form input element to fire when it changes.
('#date').datetimepicker({
  ...

  onChangeDateTime: function(dp,$input){
     alert($input.val())
  }

  ...
});

Within the handler function you will probably want to implement some kind check to ensure that the value is what you want it to be before enabling the button.


text:
Q: Cognos Report Studio / Concur Reporting - multiple rows into one first off, i am new not only to cognos report studio, but to working with databases/tables and queries in general. I am tasked with building reports using sap concur's implementation of IBM Cognos report studio (v10.2.1). That means the data model is defined by the concur people.
I am using 5 queries joined together in 4 Joins and now have all the columns and values the way i want them in the report (through more trial and error than i am comfortable with, to be honest), except for one thing:
Adding the column "Comments" generates duplicate rows, one for each comment. There can be no comments, 1 comment or multiple comments per item.
So what i want to achieve is concatenating all comments (if there are any) into the same row.
I tried using a repeater doing the following steps:

*

*adding the repeater from the toolbox giving it the same query as the
list

*"unlocking" the report to be able to make changes to the layout

*placing the data item from the comment column into the repeater

*placing the repeater containing the data item back into the column

Unfortunately this doesn't change anything. Any help would be much appreciated.
PS: Of course i used the available training resources (manuals & recorded training sessions) provided by concur concerning their reporting solution. However, these are rather low level and very light on the issue of joining multiple queries.

A: This is serendipity. I was the principal modeler and report developer for Concur's Cognos solution for five years. It's definitely a small, small world.
As to your issue, I'm not sure you can successfully do what you are trying to do which is take a multiple rows from a table and merge them into a single column. In theory, you could do multiple self-joins, one for each comment and then concatenate the results but this would be both unwieldy and you'd have to set a limit as to how many comments would be supported this way as you'd have to have a manually defined join for each.
I did some exploring to see what can be done to solve your problem. I think your best bet is to use a Master Detail pattern. This embeds a list inside another list and establishes a relationship between the two using equivalent data items that exist in both queries. The disadvantage is that it will take up a lot of space as each comment will get its own row in the detail portion of the master/detail.
The basic steps are outlined-below. The steps assume you already have an existing list with the columns, other than comment, that you want:

*

*Drag over a new list object and add it to the end of the existing list and select the appropriate query from the dialog that comes up.

*You should see the last column of the outside list now contains it's own empty list.

*Drag over the comment column and place it in the inside list

*Select the inside list object. Either click on the three red dots at the top left corner of the list or select it from the properties dialog.

*Click on the Master Detail Relationships property.

*Click on the New Link button at the top and select the equivalent columns on both the left and right and click OK

When you run the report, you should see now all the associated comments in their own list within each row.

A: The steps assume you have already got Associate in Nursing existing list with the columns, aside from comment, that you simply want:

*

*Move as well as create a new list object to the end of the initial
list and choose from the conversation that came up the correct query.

*You can see the outer list's last column containing its own
unoccupied list.

*Push and locate the comment section in the inside list

*Choose the object from the list inside. it either click on the three
red dots in the list's top left corner or select them from the
various properties dialog.

*Click the property of Master Detail Relationships.

*Click the New Link button at the top and try to select the right and
left columns and click ok again