问:
Replace multiple characters with multiple replacers in Perl
I am updating a piece of code to read a table into R. The delimiters in the table should be semicolons. Some of the elements in the table have semicolons and should be replaced with colons. At the same time, the code is replacing tabs with semicolons and this should be kept.

The current script has the line

```<code>sprintf("%s -e '%s' | perl -pe 's/\t/;/g' > %s", hive.cmd, sql, tmp_file)
</code>```

and should be updated to, in order:

Replace ; with :

Replace \t with ;

Edit: I should add I have no experience in Perl.

答:
A simple another way to replace the strings:

```<code>$str = "\;  \:\;    ";
</code>```

Need to find the two matches \; and \t we can search the both of them in a single regex and replace to the corresponding value matches.

```<code>$str=~s/((\;)|\t)/$2 ? '\:' : '\;'/eg;
           ^   ^
</code>```

$2 matches with semicolon and rest of the one matches with \t delimits.

```<code>print $str;
</code>```

Body:
I am updating a piece of code to read a table into R. The delimiters in the table should be semicolons. Some of the elements in the table have semicolons and should be replaced with colons. At the same time, the code is replacing tabs with semicolons and this should be kept.

The current script has the line

sprintf("%s -e '%s' | perl -pe 's/\t/;/g' > %s", hive.cmd, sql, tmp_file)

and should be updated to, in order:

Replace ; with :

Replace \t with ;

Edit: I should add I have no experience in Perl.

Body:
A simple another way to replace the strings:

$str = "\;  \:\;    ";

Need to find the two matches \; and \t we can search the both of them in a single regex and replace to the corresponding value matches.

$str=~s/((\;)|\t)/$2 ? '\:' : '\;'/eg;
           ^   ^

$2 matches with semicolon and rest of the one matches with \t delimits.

print $str;


来源: stackexchange

问:
Why click event doesn't work in Internet Explorer using Selenium in python?
I've already written a click method and it works fine for chrome and FF Webdrivers I'm trying to run my scripts for IE as well but the problem is that sometimes, click method does not work. It doesn't give back any error. That means it can find the relative elements.
Some of my code is as below:

```<code>time.sleep("a few seconds")  # Here I actually used explicit time wait
browser.switch_to_default_content()
button = browser.find_element_by_id("the_button_id")
button.click()
</code>```

As I mentioned above, I don't get any errors and when I debug my scripts it passes the lines. Frankly, I don't know what's wrong with my code!

The tools version I use is:

windows 7 ultimate 32 bit

Internet Explorer 9

IE_driver_server 32 bit version 2.44

selenium version 2.44.0

python 2.7
  Thank you for your consideration

答:
The problem may be related to native events in IE11:

Visit http://forums.smartclient.com/forum/smart-gwt-technical-q-a/33394-webdriver-ie-click-doesn-t-seem-to-work

capabilities = DesiredCapabilities.INTERNETEXPLORER

capabilities['ignoreProtectedModeSettings'] = True

capabilities['ignoreZoomSetting'] = True

capabilities.setdefault("nativeEvents", False)

driver = webdriver.Ie(capabilities=capabilities)

driver.get(url)

ContentLicense: CC BY-SA 3.0

Body:
I've already written a click method and it works fine for chrome and FF Webdrivers I'm trying to run my scripts for IE as well but the problem is that sometimes, click method does not work. It doesn't give back any error. That means it can find the relative elements.
Some of my code is as below:

time.sleep("a few seconds")  # Here I actually used explicit time wait
browser.switch_to_default_content()
button = browser.find_element_by_id("the_button_id")
button.click()

As I mentioned above, I don't get any errors and when I debug my scripts it passes the lines. Frankly, I don't know what's wrong with my code!

The tools version I use is:

windows 7 ultimate 32 bit

Internet Explorer 9

IE_driver_server 32 bit version 2.44

selenium version 2.44.0

python 2.7
  Thank you for your consideration


问:
How can I group similar results from mySQL database in foreach loop?
```<code>$pdo = $db->prepare('SELECT * FROM animals WHERE id = :id ');
$pdo->execute(array('id' => $id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
     $name = $row["name"];
     echo $name."<br>";
}
</code>```

The result of my loop is right now-

```<code>cat
cat
cat
cat
dog
bird
</code>```

I want to group results if they are similar, so I get as a result like this-

```<code>cat
dog
bird
</code>```

答:
different ways:-

1.DISTINCT:-

```<code>$pdo = $db->prepare('SELECT DISTINCT name FROM animals WHERE id = :id ');
</code>```

2.GROUP BY:-

```<code>$pdo = $db->prepare('SELECT name FROM animals WHERE id = :id  GROUP BY name');
</code>```

Body:
$pdo = $db->prepare('SELECT * FROM animals WHERE id = :id ');
$pdo->execute(array('id' => $id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
     $name = $row["name"];
     echo $name."
";
}

The result of my loop is right now-

cat
cat
cat
cat
dog
bird

I want to group results if they are similar, so I get as a result like this-

cat
dog
bird

Body:
different ways:-

1.DISTINCT:-

$pdo = $db->prepare('SELECT DISTINCT name FROM animals WHERE id = :id ');

2.GROUP BY:-

$pdo = $db->prepare('SELECT name FROM animals WHERE id = :id  GROUP BY name');


问:
Xcode #import not finding .h file
I'm trying to import a .h file from an old xcode project into my current one. The file location is the same as the other files in the project (I moved it there), but after using #import in my program body file, when I try to run the program I get the following fail:

"_OBJC_CLASS_$_Fraction", referenced from:

objc-class-ref-to-Fraction in 9.1main.o

ld: symbol(s) not found
collect2: ld returned 1 exit status

Does anyone know how to fix this? Thanks!

答: Go to Xcode Project Settings -> Build Phases -> In Headers Section look for your .h file and move it to Public list.</p>

Title: Xcode #import not finding .h file


问:
AWS billing - how to view cost for load balancing instance aka ELB?

In brief

How to know the monthly cost of an Elastic Load Balancing instance?

Full detail

My team is using an AWS Elastic Beanstalk instance, and we need to know how much it costs per month.

My google lead me to this AWS page which suggests to view the cost of EC2 and ELB

The principal costs for a web application will typically be for the Amazon EC2 instance(s) and for the Elastic Load Balancing

We can use AWS Calculator to get the monthly cost of an EC2 instance; though we CANNOT find out how to compute the cost for the ELB there ie. using the AWS Calculator.

My google search results as this AWS page which shows a way to compute the cost manually i.e. basing on $0.025 per hour run, and $0.008 per GB of data transfer. But what is the average number of hours and/or transferred data? Why not just have it in the calculator too?

If the load balancer ended up transferring 100 GB of data over a 30 day period, the monthly charge would amount to $18 (or $0.025 per hour x 24 hours per day x 30 days x 1 load balancer) for the load balancer hours and $0.80 (or $0.008 per GB x 100 GB) for the data transferred through the load balancer, for a total monthly charge of $18.80.

答:
To see how much your services are costing you, turn on Detailed Billing Reports. This will create highly detailed billing information, saved in files in Amazon S3.

You can also use the billing option in the management console to see high-level billing by service, but you'll need to turn on Detailed Billing to obtain more detail (and that detail is only available after Detailed Billing is activated).

See also:

Pricing for Classic Load Balancer

Pricing for Application Load Balancer


问:
awk command to delete rows if it has number as the first character of first column in a tsv file
I am trying to delete rows if it has number as the first character in the first column in a tsv file. </p>

```<code>abc london
def paris
4ge berlin
323 rome
xyz prague
#56 Bern
</code>```

<p>I would like to delete (rows: 4ge, 323,#56). What I tried is something like this </p>

```<code>awk 'BEGIN{FS=OFS="\t"}{$1=/^[0-9]/; print $1,$2}' train.tsv > train.tsv
</code>```

答:
Like this:

```<code>awk '!/^[[:digit:]]/' file
</code>```

Since it is the first column you can simply check if the whole line starts (not) with a number. If you would be interested in any other column you can use (for example second column):

```<code>awk '$2 !~ /^[[:digit:]]/' file
</code>```

Btw, you may miss the print command here. That's because it is default command, meaning

```<code>awk '!/^[[:digit:]]/' file
</code>```

is the same as

```<code>awk '!/^[[:digit:]]/{print}' file
</code>```

which is the same as

```<code>awk '!/^[[:digit:]]/{print $0}' file
</code>```

Body:
I am trying to delete rows if it has number as the first character in the first column in a tsv file.

abc london
def paris
4ge berlin
323 rome
xyz prague
#56 Bern

I would like to delete (rows: 4ge, 323,#56). What I tried is something like this

awk 'BEGIN{FS=OFS="\t"}{$1=/^[0-9]/; print $1,$2}' train.tsv > train.tsv

Body:
Like this:

awk '!/^[[:digit:]]/' file

Since it is the first column you can simply check if the whole line starts (not) with a number. If you would be interested in any other column you can use (for example second column):

awk '$2 !~ /^[[:digit:]]/' file

Btw, you may miss the print command here. That's because it is default command, meaning

awk '!/^[[:digit:]]/' file

is the same as

awk '!/^[[:digit:]]/{print}' file

which is the same as

awk '!/^[[:digit:]]/{print $0}' file


问:
Malihu jQuery Custom Scrollbar with Select 2
Scrollbar shows only on first opening and no more.
What I did wrong?</p>

```<code>$('.select').on('select2:open', function () {
    function showScroll() {
        $('.select2-results__options').mCustomScrollbar();
    }
    setTimeout(showScroll, 1);
});
</code>```

答:
This solution works for me:</p>

```<code>$('select').on('select2:open', function (e) {
 $('.select2-results__options').mCustomScrollbar('destroy');
  setTimeout(function () {
    $('.select2-results__options').mCustomScrollbar();
  }, 0);
});
</code>```

Body:
Scrollbar shows only on first opening and no more.
What I did wrong?

$('.select').on('select2:open', function () {
    function showScroll() {
        $('.select2-results__options').mCustomScrollbar();
    }
    setTimeout(showScroll, 1);
});

Body:
This solution works for me:

$('select').on('select2:open', function (e) {
 $('.select2-results__options').mCustomScrollbar('destroy');
  setTimeout(function () {
    $('.select2-results__options').mCustomScrollbar();
  }, 0);
});


问:
How to use a dropdown value as a if function
i have a html code as following

tfa_78 is a dropdown list, but build in formassembly, so not able to put it in the code
the value "Test" is just to show myself, that the code in general is running ;)

```<code><script>

var tfa78 = document.getElementById("tfa_78").selvalue;

if( tfa78 == "karte" )
{
document.getElementById('tfa_2448').innerHTML ='<b>Bei karte anrufen.</b> <br>';
} else {
document.getElementById('tfa_2448').innerHTML ='Test';
}
</code>```

my question: it is not working, i do not get the first result, what might be wrong? is the selvalue the right thing to select the dropdown value? before, i used this code with a textfield, that was working, so i guess it is anyhow related to the wrong "get" value argument?

Thanks a lot in advance for your support.

I updated my code already due to few comments as below:

```<code> <script>
 var tfa78 = document.getElementById("tfa_78").value;
 if( tfa78 == 'tfa_2438' ) {
 document.getElementById('tfa_2448').innerHTML ='<b> anrufen.</b> <br>';
 }else {
 document.getElementById('tfa_2448').innerHTML ='Test'+ tfa78;
 }</script>
</code>```

and this is the dropdown code, but i can not change that.

```<code><select id="tfa_78" name="tfa_78" title="Quelle?" class="required"><option
value="">Bitte auswählen:</option>
<option value="tfa_2438" id="tfa_2438" data-conditionals="#tfa_93"
class="">karte</option>
<option value="tfa_2437" id="tfa_2437" data-conditionals="#tfa_93"
class="">Test</option>
</select>
</code>```

答:
Use .value instead of .selvalue;

```<code>var tfa78 = document.getElementById("tfa_78").value;
</code>```

Complete code is

```<code><script>
    function changeMessage() {
        var tfa78 = document.getElementById("tfa_78").value;
        console.log(tfa78);
        if( tfa78 == "volvo" ){
            document.getElementById('tfa_2448').innerHTML ='<b>Bei karte anrufen.</b> <br>';
        } else {
            document.getElementById('tfa_2448').innerHTML ='Test';
        }
    }

    </script>

    </head>

    <body>
    <select id="tfa_78" onchange="changeMessage()">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>
    <div id = "tfa_2448"> </div>
    </body>
</code>```

Body:
i have a html code as following

tfa_78 is a dropdown list, but build in formassembly, so not able to put it in the code
the value "Test" is just to show myself, that the code in general is running ;)

and this is the dropdown code, but i can not change that.

<select id="tfa_78" name="tfa_78" title="Quelle?" class="required"><option
value="">Bitte auswählen:</option>
<option value="tfa_2438" id="tfa_2438" data-conditionals="#tfa_93"
class="">karte</option>
<option value="tfa_2437" id="tfa_2437" data-conditionals="#tfa_93"
class="">Test</option>
</select>

Body:
Use .value instead of .selvalue;

var tfa78 = document.getElementById("tfa_78").value;

Complete code is

<script>
    function changeMessage() {
        var tfa78 = document.getElementById("tfa_78").value;
        console.log(tfa78);
        if( tfa78 == "volvo" ){
            document.getElementById('tfa_2448').innerHTML ='<b>Bei karte anrufen.</b> <br>';
        } else {
            document.getElementById('tfa_2448').innerHTML ='Test';
        }
    }

    </script>

    </head>

    <body>
    <select id="tfa_78" onchange="changeMessage()">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>
    <div id = "tfa_2448"> </div>
    </body>


问:
Setting up Zend Framework - MVC
I have developed numerous websites using Codeigniter, but now have the need to migrate to Zend Framework.
I am installing it on shared hosting and I have virtually no command line experience. So far I have downloaded the framework, unzipped it and uploaded it to the hosting. I am using a Centos server provided by Godaddy.

I have tried the quick start guide but this uses command line, I also notice there is no index file to route requests through.
Is there a way that I can set up a basic MVC structure without using command line or do you have any pointers for what I need to be doing next.

Thanks in advance.

John

答:
You don't have to use the command line tool. You can create files by yourself too. It's just more work for you ;) So for a basic setting you'd have to create the folders/files listed here. The command line tool only saves you a lot of create/copy & paste work. The code for all files is listed in the quickstart, but a bit spread over the different pages. I'd suggest to read everything first to get the idea of how zf does work and then create all files.

The index file responsible for all routing is public/index.php.

ContentLicense: CC BY-SA 2.5

Title: Setting up Zend Framework - MVC


问:
Can't start Jenkins service on Ubuntu
I have an Ubuntu server and have installed Jenkins for Continuous Integration on it. I tried to run some builds this morning and they would not run. I looked at the logs and realised that in /var/log/jenkins there were some large log files filling up my hard drive on the server. I deleted these files and attempted to restart Jenkins.

At this point Jenkins will now no longer start. I have had a look at my /tmp directory and it looks like there is some sort of memory leak which is creating a large 1MB file called winstonexxxxxxxxxxx.jar in my tmp directory which fills the entire 1mb space of my tmp directory.

Can anyone help with how to resolve this?

Thanks in advance

答:
This is a known issue and has been resolved as 2018-02-14.

Suggested solutions when working with an older Jenkins:

Make sure all Jenkins processes are closed and nothing is running at your Jenkins port (by default 8080)

Start Jenkins

Should Jenkins still not start-up, then maybe the 1 MB of /tmp space is the problem. Either enlarge it, or use any of the following solutions to change the temporary directory for Jenkins: How to change the jenkins `/tmp` dir location?

Should the tmp directory still be filling up, you could install the Tmp Cleaner Plugin.

Title: Can't start Jenkins service on Ubuntu

ContentLicense: CC BY-SA 4.0


问:
Javascript collision of two point array polygons
I have searched all over, and I have found answers for rectangle circle and sprite collisions. Nothing that provides collision detection between two arrays of points like for example,

```<code>var poly1=[
    [0,0],
    [20,50],
    [50,70],
    [70,20],
    [50,0]
];
// each point from one to the next represent a line in the shape, then the last point connects to the first to complete it.
var poly2=[
    [50,30],
    [40,90],
    [70,110],
    [90,70],
    [80,20]
];
var collided=arraysCollided(poly1,poly2);
</code>```

Does anyone know of a library that can do just this? My research has come up with nothing that supports just that, and isnt associated with some game engine library.

For example a collision is triggered true when one or more points is inside the polygon of the other.

答:
SAT.js was the anser for me, I just put every point into SAT.Vector then into SAT.Polygon, then test them with SAT.testPolygonPolygon(SAT.Polygon,SAT.Polygon);

```<code>var poly1={
    name:"poly2",
    x:400,
    y:60,
    rotation:0,
    runner:function(){

    },
    points:[
        [20,-50],
        [-30,-50],
        [-30,30],
        [10,60],
        [50,20]
    ]
};
var poly2={
    name:"poly2",
    x:50,
    y:70,
    runner:function(){
        this.x+=1;
    },
    points:[
        [-20,-40],
        [-60,50],
        [10,70],
        [50,30],
        [30,-20]
    ]
};
pGon=(poly)=>{
    var center=SAT.Vector(0,0);
    var pts=[];
    for(var i in poly.points){
        var point=poly.points[i];
        // point = [0:x,1:y]
        pts[pts.length]=new SAT.Vector(point[0]+poly.x,point[1]+poly.y);
    }
    var poly_a=new SAT.Polygon(center,pts);
    return poly_a;
};
pCollide=(p1,p2)=>{
    var p1_poly=pGon(p1);
    var p2_poly=pGon(p2);
    var res=new SAT.Response();
    var collided=SAT.testPolygonPolygon(p1_poly,p2_poly,res);
    console.log(collided);
    console.log(res);
    return collided;
};
var collided=pCollided(poly1,poly2);
</code>```

With that, it maps each point to a polygon on the coordinate system, then tests it from there. So collided = true

Body:
I have searched all over, and I have found answers for rectangle circle and sprite collisions. Nothing that provides collision detection between two arrays of points like for example,

var poly1=[
    [0,0],
    [20,50],
    [50,70],
    [70,20],
    [50,0]
];
// each point from one to the next represent a line in the shape, then the last point connects to the first to complete it.
var poly2=[
    [50,30],
    [40,90],
    [70,110],
    [90,70],
    [80,20]
];
var collided=arraysCollided(poly1,poly2);

Does anyone know of a library that can do just this? My research has come up with nothing that supports just that, and isnt associated with some game engine library.

For example a collision is triggered true when one or more points is inside the polygon of the other.

Body:
SAT.js was the anser for me, I just put every point into SAT.Vector then into SAT.Polygon, then test them with SAT.testPolygonPolygon(SAT.Polygon,SAT.Polygon);

var poly1={
    name:"poly2",
    x:400,
    y:60,
    rotation:0,
    runner:function(){

    },
    points:[
        [20,-50],
        [-30,-50],
        [-30,30],
        [10,60],
        [50,20]
    ]
};
var poly2={
    name:"poly2",
    x:50,
    y:70,
    runner:function(){
        this.x+=1;
    },
    points:[
        [-20,-40],
        [-60,50],
        [10,70],
        [50,30],
        [30,-20]
    ]
};
pGon=(poly)=>{
    var center=SAT.Vector(0,0);
    var pts=[];
    for(var i in poly.points){
        var point=poly.points[i];
        // point = [0:x,1:y]
        pts[pts.length]=new SAT.Vector(point[0]+poly.x,point[1]+poly.y);
    }
    var poly_a=new SAT.Polygon(center,pts);
    return poly_a;
};
pCollide=(p1,p2)=>{
    var p1_poly=pGon(p1);
    var p2_poly=pGon(p2);
    var res=new SAT.Response();
    var collided=SAT.testPolygonPolygon(p1_poly,p2_poly,res);
    console.log(collided);
    console.log(res);
    return collided;
};
var collided=pCollided(poly1,poly2);

With that, it maps each point to a polygon on the coordinate system, then tests it from there. So collided = true


问:
Avoid System.FormatException with Binding.Parse
I have a TextBox which is bound to a property of type decimal. As I want the value in the textfield to be shown with two decimal points (e.g. 3.15), I have implemted the binding as follows:

```<code>Binding bindDecimal = new Binding("Text", viewModel, "myDecimal");
bindDecimal.Format += FormatDecimal;
bindDecimal.Parse += ParseDecimal;
</code>```

The .Format function, so the interesting part is the .Parse function, which is implemented like this:

```<code>private void ParseDecimal(object sender, ConvertEventArgs e)
{
    if (e.DesiredType != typeof(decimal)) return;

    e.Value = Decimal.Parse(e.Value.ToString(), NumberStyles.Number);
}
</code>```

Which works, as long as the value is a legit one. If I start using letters or (more realistically) just leave the field empty, it returns a System.FormatException, since it cannot convert the value to a decimal. A twist on the problem is, that it also occurs if you close the form window, while the TextBox is empty.

What is the best way to avoid this exception?

Also, if it makes any difference, here is the .Format function:

```<code>private void FormatDecimal(object sender, ConvertEventArgs e)
{
    // The method converts only to string type. Test this using the DesiredType.
    if (e.DesiredType != typeof(string)) return;

    // Formats the value with two decimals
    e.Value = string.Format("{0:n2}", e.Value);
}
</code>```

答:
```<code>private void ParseDecimal(object sender, ConvertEventArgs e)
{
    if (e.DesiredType != typeof(decimal)) return;

    Decimal bob;

    if (Decimal.TryParse(e.Value.ToString(), NumberStyles.Number, new CultureInfo.CurrentCulture, out bob);
    {
        e.Value = bob;
    }
}
</code>```

Body:
I have a TextBox which is bound to a property of type decimal. As I want the value in the textfield to be shown with two decimal points (e.g. 3.15), I have implemted the binding as follows:

Binding bindDecimal = new Binding("Text", viewModel, "myDecimal");
bindDecimal.Format += FormatDecimal;
bindDecimal.Parse += ParseDecimal;

The .Format function, so the interesting part is the .Parse function, which is implemented like this:

private void ParseDecimal(object sender, ConvertEventArgs e)
{
    if (e.DesiredType != typeof(decimal)) return;

    e.Value = Decimal.Parse(e.Value.ToString(), NumberStyles.Number);
}

Which works, as long as the value is a legit one. If I start using letters or (more realistically) just leave the field empty, it returns a System.FormatException, since it cannot convert the value to a decimal. A twist on the problem is, that it also occurs if you close the form window, while the TextBox is empty.

What is the best way to avoid this exception?

Also, if it makes any difference, here is the .Format function:

private void FormatDecimal(object sender, ConvertEventArgs e)
{
    // The method converts only to string type. Test this using the DesiredType.
    if (e.DesiredType != typeof(string)) return;

    // Formats the value with two decimals
    e.Value = string.Format("{0:n2}", e.Value);
}


问:
ConstrainLayout not able to align two views
I want to align Sachin Textview with Tendulkar Textview.

Screenshot:

Design time I'm getting proper alignment. But it fails in app.

XML:

```<code><TextView
        android:id="@+id/tvFirstName"
        style="@style/MediumBlack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        android:text="First Name: "
        app:layout_constraintHorizontal_bias="0.09"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvLastName"
        style="@style/MediumBlack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Last Name: "
        app:layout_constraintLeft_toLeftOf="@+id/tvFirstName"
        app:layout_constraintTop_toBottomOf="@+id/tvFirstName"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="-10dp" />

    <TextView
        android:id="@+id/textView4"
        style="@style/SmallGray"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0dp"
        android:text="Sachin"
        app:layout_constraintLeft_toRightOf="@+id/tvFirstName"
        app:layout_constraintBaseline_toBaselineOf="@+id/tvFirstName" />

    <TextView
        android:id="@+id/textView2"
        style="@style/SmallGray"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tendulkar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBaseline_toBaselineOf="@+id/tvLastName"
        app:layout_constraintHorizontal_bias="0.47" />
</code>```

is there any android studio-constraintlayout specific feature?

答:
Your constraints on "Tendulkar" are causing the TextView to be centered. You want to align the left side of that TextView with the left side of "Sachin" as follows:

```<code><TextView
    android:id="@+id/textView2"
    style="@style/SmallGray"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Tendulkar"
    app:layout_constraintLeft_toLeftOf="@id/textView4"
    app:layout_constraintBaseline_toBaselineOf="@+id/tvLastName"/>
</code>```

I also removed the bias.

Body:
I want to align Sachin Textview with Tendulkar Textview.

Screenshot:

Design time I'm getting proper alignment. But it fails in app.

XML:

<TextView
        android:id="@+id/tvFirstName"
        style="@style/MediumBlack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        android:text="First Name: "
        app:layout_constraintHorizontal_bias="0.09"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvLastName"
        style="@style/MediumBlack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Last Name: "
        app:layout_constraintLeft_toLeftOf="@+id/tvFirstName"
        app:layout_constraintTop_toBottomOf="@+id/tvFirstName"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="-10dp" />

    <TextView
        android:id="@+id/textView4"
        style="@style/SmallGray"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0dp"
        android:text="Sachin"
        app:layout_constraintLeft_toRightOf="@+id/tvFirstName"
        app:layout_constraintBaseline_toBaselineOf="@+id/tvFirstName" />

    <TextView
        android:id="@+id/textView2"
        style="@style/SmallGray"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tendulkar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBaseline_toBaselineOf="@+id/tvLastName"
        app:layout_constraintHorizontal_bias="0.47" />

is there any android studio-constraintlayout specific feature?

Body:
Your constraints on "Tendulkar" are causing the TextView to be centered. You want to align the left side of that TextView with the left side of "Sachin" as follows:

<TextView
    android:id="@+id/textView2"
    style="@style/SmallGray"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Tendulkar"
    app:layout_constraintLeft_toLeftOf="@id/textView4"
    app:layout_constraintBaseline_toBaselineOf="@+id/tvLastName"/>

I also removed the bias.


问:
Extracting a laser line in an image (using OpenCV)
i have a picture from a laser line and i would like to extract that line out of the image.

As the laser line is red, i take the red channel of the image and then searching for the highest intensity in every row:

The problem now is, that there are also some points which doesnt belong to the laser line (if you zoom into the second picture, you can see these points).

Does anyone have an idea for the next steps (to remove the single points and also to extract the lines)?

That was another approach to detect the line:
First i blurred out that "black-white" line with a kernel, then i thinned(skeleton) that blurred line to a thin line, then i applied an OpenCV function to detect the line.. the result is in the below image:

NEW:

Now i have another harder situation.
I have to extract a green laser light.

  The problem here is that the colour range of the laser line is wider and changing.

On some parts of the laser line the pixel just have high green component, while on other parts the pixel have high blue component as well.

答:
Getting the highest value in every row will always output a value, instead of ignoring when the value isn't high enough. Consider using a threshold too, so that you can discard ones that aren't high enough.

However, that's not a very efficient way to do this at all. A much better and easier solution would be to use the OpenCV function inRange(); define a lower and upper bound for the red color in all three channels, and this will return a binary image with white pixels where the image intensity is within that BGR range.

This is in python but it does the job, should be easy to see how to use the function:

```<code>import cv2
import numpy as np

img = cv2.imread('image.png')
lowerb = np.array([0, 0, 120])
upperb = np.array([100, 100, 255])
red_line = cv2.inRange(img, lowerb, upperb)

cv2.imshow('red', red_line)
cv2.waitKey(0)
</code>```

This produces the output:

This could be further processed by finding contours or other methods to turn the points into a nice curve.

Body:
Getting the highest value in every row will always output a value, instead of ignoring when the value isn't high enough. Consider using a threshold too, so that you can discard ones that aren't high enough.

However, that's not a very efficient way to do this at all. A much better and easier solution would be to use the OpenCV function inRange(); define a lower and upper bound for the red color in all three channels, and this will return a binary image with white pixels where the image intensity is within that BGR range.

This is in python but it does the job, should be easy to see how to use the function:

import cv2
import numpy as np

img = cv2.imread('image.png')
lowerb = np.array([0, 0, 120])
upperb = np.array([100, 100, 255])
red_line = cv2.inRange(img, lowerb, upperb)

cv2.imshow('red', red_line)
cv2.waitKey(0)

This produces the output:

This could be further processed by finding contours or other methods to turn the points into a nice curve.


问:
Inconsitent TypeScript behavior with union and object type
Let's have a following snippet:

```<code>interface A {
  isEmpty(x: any[] | string | object): boolean;
  isEmptyObject(x: object): boolean;
}

const a: A = <A>{};

a.isEmptyObject({});
a.isEmptyObject({a: 1});

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty({a: 1});
</code>```

When I try to compile it, it crashes with this:

```<code>a.ts(14,12): error TS2345: Argument of type '{ a: number; }' is not assignable to parameter of type 'string | object | any[]'.
  Object literal may only specify known properties, and 'a' does not exist in type 'string | object | any[]'.
</code>```

How is this possible, when the union type (string | object | any[]) contains type object for which it works (the isEmptyObject call with {a: 1} is fine)?

Main question: Is this a TypeScript bug, or how one should write that input may be an array of any value or string or object (but not any primitive, I don't want any or Object)?

Tested with TypeScript 2.3.4.

答:
This is not a bug but a feature to support API-s which utilizes argument objects. Take for example jQuery-s ajax function. It takes an object as an argument.

```<code>interface JQueryAjaxParam {
    url: string;
    data?: any;
}

...

$.ajax({
    url: "",
    datta: "" // notice the typo here
});
</code>```

You do want a compilation error in this case, even though {url:"",datta:""} implements the param interface. To overcome this they added excess property checks for object literals as direct parameters. This is a good thing, provides more confidence in the typechecker, and only causes false errors when people try to conduct quick tests like yours. You have to keep this rule in mind, this is the cost of additional safety.

UPDATE: TypeScript 2.4 additionally introduces Weak types

So then there are functions with this signature:

```<code>function isEmptyObject(x : object) : void;
</code>```

Here, the intention is clear, this function aims to accept any object with any keys. A function accepting only empty object has little use. So they added an exception: when the parameter is of the type object exactly, then the previous check is omitted.

So what to do? Nothing. In real uses your function will typecheck just fine. You can try it:

```<code>interface A {
  isEmpty(x: any[] | string | object): boolean;
  isEmptyObject(x: object): boolean;
}

const a: A = <A>{};
const param = {a: 1};

a.isEmptyObject({});
a.isEmptyObject(param);

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty(param);
</code>```

UPDATE

Your example is an actual usecase, you want it to work even with literals. After Nitzan, I too suggest to use function overloading for this.

```<code>interface A {
    isEmpty(x: any[]): boolean;
    isEmpty(x: string): boolean;
    isEmpty(x: object): boolean;
    isEmptyObject(x: object): boolean;
}

const a: A = <A>{};
a.isEmptyObject({b: 6});
a.isEmptyObject({a: 1});

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty({a: 1});
</code>```

Body:
Let's have a following snippet:

interface A {
  isEmpty(x: any[] | string | object): boolean;
  isEmptyObject(x: object): boolean;
}

const a: A = {};

a.isEmptyObject({});
a.isEmptyObject({a: 1});

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty({a: 1});

When I try to compile it, it crashes with this:

a.ts(14,12): error TS2345: Argument of type '{ a: number; }' is not assignable to parameter of type 'string | object | any[]'.
  Object literal may only specify known properties, and 'a' does not exist in type 'string | object | any[]'.

How is this possible, when the union type (string | object | any[]) contains type object for which it works (the isEmptyObject call with {a: 1} is fine)?

Main question: Is this a TypeScript bug, or how one should write that input may be an array of any value or string or object (but not any primitive, I don't want any or Object)?

Tested with TypeScript 2.3.4.

Body:
This is not a bug but a feature to support API-s which utilizes argument objects. Take for example jQuery-s ajax function. It takes an object as an argument.

interface JQueryAjaxParam {
    url: string;
    data?: any;
}

...

$.ajax({
    url: "",
    datta: "" // notice the typo here
});

You do want a compilation error in this case, even though {url:"",datta:""} implements the param interface. To overcome this they added excess property checks for object literals as direct parameters. This is a good thing, provides more confidence in the typechecker, and only causes false errors when people try to conduct quick tests like yours. You have to keep this rule in mind, this is the cost of additional safety.

UPDATE: TypeScript 2.4 additionally introduces Weak types

So then there are functions with this signature:

function isEmptyObject(x : object) : void;

Here, the intention is clear, this function aims to accept any object with any keys. A function accepting only empty object has little use. So they added an exception: when the parameter is of the type object exactly, then the previous check is omitted.

So what to do? Nothing. In real uses your function will typecheck just fine. You can try it:

interface A {
  isEmpty(x: any[] | string | object): boolean;
  isEmptyObject(x: object): boolean;
}

const a: A = <A>{};
const param = {a: 1};

a.isEmptyObject({});
a.isEmptyObject(param);

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty(param);

UPDATE

Your example is an actual usecase, you want it to work even with literals. After Nitzan, I too suggest to use function overloading for this.

interface A {
    isEmpty(x: any[]): boolean;
    isEmpty(x: string): boolean;
    isEmpty(x: object): boolean;
    isEmptyObject(x: object): boolean;
}

const a: A = <A>{};
a.isEmptyObject({b: 6});
a.isEmptyObject({a: 1});

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty({a: 1});


问:
Lubridate parse date warning
I'm receiving warnings when I try to read vector a which contains many dates.

Here's the text file for vector a which I made using write(a,"a.txt"). As it's pretty big, I've attached it on Google drive for anyone to download. Basically, it contains the dates from 2012-01-01 to 2012-12-31, repeated many times.

https://drive.google.com/file/d/0B12dCpdCVHeSZjA4YmVXNmV6VUU/edit?usp=sharing

I tried to do this and received a warning message.

```<code>> head(ymd(a))
[1] "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC"
[6] "2012-01-01 UTC"
Warning message:
 7202 failed to parse.
</code>```

Looking at the warning message, it would be easy to assume that the date format is wrong. However, YYYY-MM-DD is a format that is supported by lubridate. When I do the same to a part of the vector, nothing happens.

```<code>> head(ymd(a[1:50000]))
[1] "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC"
[6] "2012-01-01 UTC"
</code>```

Using strptime and as.Date also doesn't produce any error

```<code>> head(strptime(a,format="%Y-%m-%d"))
[1] "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01"
> head(as.Date(a))
[1] "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01"
</code>```

My question is, do I need to worry about the warning message or can I safely ignore it?

答:
Different solution using the anydate package, which seems to work. </p>

```<code>library(anydate)
text <- anydate(a[, 1])
sum(is.na(text))

# 0
</code>```

Title: Lubridate parse date warning

Body:
I'm receiving warnings when I try to read vector a which contains many dates.

Here's the text file for vector a which I made using write(a,"a.txt"). As it's pretty big, I've attached it on Google drive for anyone to download. Basically, it contains the dates from 2012-01-01 to 2012-12-31, repeated many times.

https://drive.google.com/file/d/0B12dCpdCVHeSZjA4YmVXNmV6VUU/edit?usp=sharing

I tried to do this and received a warning message.

> head(ymd(a))
[1] "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC"
[6] "2012-01-01 UTC"
Warning message:
 7202 failed to parse.

Looking at the warning message, it would be easy to assume that the date format is wrong. However, YYYY-MM-DD is a format that is supported by lubridate. When I do the same to a part of the vector, nothing happens.

> head(ymd(a[1:50000]))
[1] "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC" "2012-01-01 UTC"
[6] "2012-01-01 UTC"

Using strptime and as.Date also doesn't produce any error

> head(strptime(a,format="%Y-%m-%d"))
[1] "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01"
> head(as.Date(a))
[1] "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01"

My question is, do I need to worry about the warning message or can I safely ignore it?

Body:
Different solution using the anydate package, which seems to work.

library(anydate)
text <- anydate(a[, 1])
sum(is.na(text))

# 0


问:
Using Entity manager and JPA, returns object only
When i run the following code it was return only object list. i want the list in vehicle. what is the error in my code?

My Dao Class Is:

```<code>public class VehicleDao {

HibernateTemplate template;
private EntityManager emManager;

@PersistenceContext
public void setEm(EntityManager emManager) {
    this.emManager = emManager;
}
public List<Vehicle> getVehicleDataUsing_Sp()
{
Properties prop= new Properties();
    try {
        InputStream input = new FileInputStream("E:\\spring4AndHibernate5\\src\\Query.properties");
        prop.load(input);
        Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"));
        List<Vehicle> list = query.getResultList();
        return list;
        }
}
</code>```

答:
You can't return List<Vehicle> when you have specified the return type as void.

Try this instead:

```<code>public List<Vehicle> getVehicleDataUsing_Sp()
</code>```

And you also need to add a catch block after the try block, like this:

```<code>catch(Exception e)
{
}
</code>```

Body:
When i run the following code it was return only object list. i want the list in vehicle. what is the error in my code?

My Dao Class Is:

public class VehicleDao {

HibernateTemplate template;
private EntityManager emManager;

@PersistenceContext
public void setEm(EntityManager emManager) {
    this.emManager = emManager;
}
public List<Vehicle> getVehicleDataUsing_Sp()
{
Properties prop= new Properties();
    try {
        InputStream input = new FileInputStream("E:\\spring4AndHibernate5\\src\\Query.properties");
        prop.load(input);
        Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"));
        List<Vehicle> list = query.getResultList();
        return list;
        }
}

Body:
You can't return List<Vehicle> when you have specified the return type as void.

Try this instead:

public List<Vehicle> getVehicleDataUsing_Sp()

And you also need to add a catch block after the try block, like this:

catch(Exception e)
{
}


问:
Use div as radio-button
How can I use a div as radio button ?

I mean that :

you can select a div and then it is bordered blue

you can only select one of them

答:
If you want a CSS Only solution, this is an excellent one :

.labl {
    display : block;
    width: 400px;
}
.labl > input{ /* HIDE RADIO */
    visibility: hidden; /* Makes input not-clickable */
    position: absolute; /* Remove input from document flow */
}
.labl > input + div{ /* DIV STYLES */
    cursor:pointer;
    border:2px solid transparent;
}
.labl > input:checked + div{ /* (RADIO CHECKED) DIV STYLES */
    background-color: #ffd6bb;
    border: 1px solid #ff6600;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="labl">
    <input type="radio" name="radioname" value="one_value" checked="checked"/>
    <div>Small</div>
</label>
<label class="labl">
    <input type="radio" name="radioname" value="another" />
    <div>Small</div>
</label></code>```

Inspired by this answer

Title: Use div as radio-button

Body:
If you want a CSS Only solution, this is an excellent one :

.labl {
    display : block;
    width: 400px;
}
.labl > input{ /* HIDE RADIO */
    visibility: hidden; /* Makes input not-clickable */
    position: absolute; /* Remove input from document flow */
}
.labl > input + div{ /* DIV STYLES */
    cursor:pointer;
    border:2px solid transparent;
}
.labl > input:checked + div{ /* (RADIO CHECKED) DIV STYLES */
    background-color: #ffd6bb;
    border: 1px solid #ff6600;
}

<label class="labl">
    <input type="radio" name="radioname" value="one_value" checked="checked"/>
    <div>Small</div>
</label>
<label class="labl">
    <input type="radio" name="radioname" value="another" />
    <div>Small</div>
</label>

Inspired by this answer


问:
Long path name in SetCurrentDirectoryW
Using this msdn reference I created a small use case.

```<code>#include <iostream>
#include <windows.h>

int main()
{

    const std::wstring dir_path = L"\\\\?\\c:\\temp\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory";

    if (!CreateDirectoryW(dir_path.c_str(), NULL))
    {
        std::cout << " Error occurred while creation of directory!!!  " << GetLastError() << std::endl;
    }
    else
    {
        std::cout << "Lenth is " << dir_path.length() << std::endl;

        if (dir_path.length() > 255)
        {
            if (!SetCurrentDirectoryW(buf.c_str()))
            {
                std::cout << " Error occurred!!!  " << GetLastError() << std::endl;
            }
            else
            {
                std::cout << " Successful!!!" << std::endl;
            }
        }
    }
    return 0;
}
</code>```

However, I get the output as

```<code>Error occurred while creation of directory!!!  3
</code>```

Error code 3 points me to

```<code>ERROR_PATH_NOT_FOUND
3 (0x3)
The system cannot find the path specified.
</code>```

Are there any other way to use long path names in CreateDirectoryW or SetCurrentDirectoryW APIs that I am unaware of ?

PS:I am using VS 2015 Update 3 compiler on Windows 7.

答:
You have to create each directory on the path one by one. So the parent directory to the directory you pass must exist before you call CreateDirectory.

This information can be found by reading the documentation. It specifically calls out that error code and says:

One or more intermediate directories do not exist; this function will only create the final directory in the path.

Title: Long path name in SetCurrentDirectoryW

Body:
Using this msdn reference I created a small use case.

#include <iostream>
#include <windows.h>

int main()
{

    const std::wstring dir_path = L"\\\\?\\c:\\temp\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory\\ThisIsPrettyLongNameForDirectory";

    if (!CreateDirectoryW(dir_path.c_str(), NULL))
    {
        std::cout << " Error occurred while creation of directory!!!  " << GetLastError() << std::endl;
    }
    else
    {
        std::cout << "Lenth is " << dir_path.length() << std::endl;

        if (dir_path.length() > 255)
        {
            if (!SetCurrentDirectoryW(buf.c_str()))
            {
                std::cout << " Error occurred!!!  " << GetLastError() << std::endl;
            }
            else
            {
                std::cout << " Successful!!!" << std::endl;
            }
        }
    }
    return 0;
}

However, I get the output as

Error occurred while creation of directory!!!  3

Error code 3 points me to

ERROR_PATH_NOT_FOUND
3 (0x3)
The system cannot find the path specified.

Are there any other way to use long path names in CreateDirectoryW or SetCurrentDirectoryW APIs that I am unaware of ?

PS:I am using VS 2015 Update 3 compiler on Windows 7.


问:
Why does Spark Streaming start jobs only after it gets terminated?
I have a very simple spark streaming job running locally in standalone mode. There is a customer receiver which reads from database and pass it to the main job which prints the total. Not an actual use case but I am playing around to learn. Problem is that job gets stuck forever, logic is very simple so I think it is neither doing any processing nor memory issue. What is strange is if I STOP the job, suddenly in logs I see the output of job execution and other backed jobs follow! Can some one help me understand what is going on here?

```<code> val spark = SparkSession
  .builder()
  .master("local[1]")
  .appName("SocketStream")
  .getOrCreate()

val ssc = new StreamingContext(spark.sparkContext,Seconds(5))
val lines = ssc.receiverStream(new HanaCustomReceiver())

lines.foreachRDD{x => println("==============" + x.count())}

ssc.start()
ssc.awaitTermination()
</code>```

After terminating program following logs roll which shows execution of the batch -

```<code>17/06/05 15:56:16 INFO JobGenerator: Stopping JobGenerator immediately
17/06/05 15:56:16 INFO RecurringTimer: Stopped timer for JobGenerator after time 1496696175000
17/06/05 15:56:16 INFO JobGenerator: Stopped JobGenerator
==============100
</code>```

答:
TL;DR Use local[2] at the very least.

The issue is the following line:

```<code>.master("local[1]")
</code>```

You should have at least 2 threads to use for receivers in Spark Streaming or your streaming jobs don't get even a chance to start as they get stuck waiting for resources, i.e. a free thread to allocate.

Quoting Spark Streaming's A Quick Example:

// The master requires 2 cores to prevent from a starvation scenario.

My recommendation is to use local[2] (the minimum) or local[*] to take as many cores as possible. The best solution is to use a cluster manager like Apache Mesos, Hadoop YARN or Spark Standalone.

Body:
I have a very simple spark streaming job running locally in standalone mode. There is a customer receiver which reads from database and pass it to the main job which prints the total. Not an actual use case but I am playing around to learn. Problem is that job gets stuck forever, logic is very simple so I think it is neither doing any processing nor memory issue. What is strange is if I STOP the job, suddenly in logs I see the output of job execution and other backed jobs follow! Can some one help me understand what is going on here?

 val spark = SparkSession
  .builder()
  .master("local[1]")
  .appName("SocketStream")
  .getOrCreate()

val ssc = new StreamingContext(spark.sparkContext,Seconds(5))
val lines = ssc.receiverStream(new HanaCustomReceiver())

lines.foreachRDD{x => println("==============" + x.count())}

ssc.start()
ssc.awaitTermination()

After terminating program following logs roll which shows execution of the batch -

17/06/05 15:56:16 INFO JobGenerator: Stopping JobGenerator immediately
17/06/05 15:56:16 INFO RecurringTimer: Stopped timer for JobGenerator after time 1496696175000
17/06/05 15:56:16 INFO JobGenerator: Stopped JobGenerator
==============100

Body:
TL;DR Use local[2] at the very least.

The issue is the following line:

.master("local[1]")

You should have at least 2 threads to use for receivers in Spark Streaming or your streaming jobs don't get even a chance to start as they get stuck waiting for resources, i.e. a free thread to allocate.

Quoting Spark Streaming's A Quick Example:

// The master requires 2 cores to prevent from a starvation scenario.

My recommendation is to use local[2] (the minimum) or local[*] to take as many cores as possible. The best solution is to use a cluster manager like Apache Mesos, Hadoop YARN or Spark Standalone.


问:
Laravel Route : route::resource
I'm very new in laravel,
I'm following some tutorial

this code work fine

```<code>Route::group(['middleware' => 'web'], function() {
    Route::resource('tes', 'TesController');
});
<form action="{{ route('tes.destroy',3) }}" method="post">
</code>```

until i modified it like this one

```<code>Route::resource('tes/keren', 'TesController');

<form action="{{ route('tes/keren.destroy',3) }}" method="post">
</code>```

It said tes/keren.destroy undefined....
just simple question, which should I modify so, I can route with /

Thank you

答:
Route::resource('url/resource-route','ResouceControllerName') takes the last segment as a resource name & then automatically build the routes for it.

when you use Route::resource('tes', 'TesController'); it build the routes for tes resource (like tes.store, tes.create, tes.destroy, etc)

But when your change your route to this  Route::resource('tes/keren', 'TesController');

It binds all the routes to keren resource.

So use this in your blade file.

```<code><form action="{{ route('keren.destroy', 3) }}" method="post">
</code>```

Title: Laravel Route : route::resource

Body:
I'm very new in laravel,
I'm following some tutorial

this code work fine

Route::group(['middleware' => 'web'], function() {
    Route::resource('tes', 'TesController');
});
<form action="{{ route('tes.destroy',3) }}" method="post">

until i modified it like this one

Route::resource('tes/keren', 'TesController');

<form action="{{ route('tes/keren.destroy',3) }}" method="post">

It said tes/keren.destroy undefined....
just simple question, which should I modify so, I can route with /

Thank you

Body:
Route::resource('url/resource-route','ResouceControllerName') takes the last segment as a resource name & then automatically build the routes for it.

when you use Route::resource('tes', 'TesController'); it build the routes for tes resource (like tes.store, tes.create, tes.destroy, etc)

But when your change your route to this  Route::resource('tes/keren', 'TesController');

It binds all the routes to keren resource.

So use this in your blade file.

<form action="{{ route('keren.destroy', 3) }}" method="post">


问:
displaying images that are retrieved from json url
I have a json url like such...

[{"Image":"http://xyz.com/abc.png",
 "Title":"Sample"},{"Image":"http://xyz.com/def.png",
 "Title":"Sample2"}

]

What i want to achieve is to get the image from json url and display it into a list. Beside it there must be title. There will be number of such objects so they must be in a list form. I couldnt understand how to get started. Any suggestions with sample code will be of great help... Thanks...

答:
you need to parse the json response you have obtained.
fetch the image url from them
these urls are just the link

establish an http connection to this url and fetch the image
the response of this connection will send  image in bytes
convert it to bitmap or encoded image
and display

remember to process server requests in form of queue if there exists many urls fro many images


问:
Build html parts from value of a js function
I really don't know how to put that in words correctly, sorry if the title misleads.

I have a function in a js file, which checks if an element is in a data array. If so the html page should show all the values of the element (so far so good). But if the element is not in the array, my html page should only display: Element not found.

js function:

```<code>function containsID(arr, number) {
    var i = arr.length;
    while (i--) {
       if (arr[i].id === number) {
           return true;
       }
    }
    return false;
}
</code>```

html:

```<code>{% if containsID(data, id) %} //I want something like that
    <p>{{data[id].text}}</p>
{% else %}
    <p> Not found </p>
{% endif %}
</code>```

答:
you need to return the index of the item with given ID

```<code>function containsID(arr, obj) {
  var i = arr.length;
  while (i--) {
    if (arr[i].id === obj) {
       return i;
    }
  }
  return -1;
}
</code>```

I am not sure what {% %} annotation stands for (looks like some template engine), but your html should by something like this:

```<code>{% if containsID(data, id) >= 0 %} //I want something like that
  <p>{{data[containsID(data, id)].text}}</p>
{% else %}
  <p> Not found </p>
{% endif %}
</code>```

better is to store the result of containsID in some template variable and then use it twice (once in condition, once in output) to avoid looping the array two times

Body:
I really don't know how to put that in words correctly, sorry if the title misleads.

I have a function in a js file, which checks if an element is in a data array. If so the html page should show all the values of the element (so far so good). But if the element is not in the array, my html page should only display: Element not found.

js function:

function containsID(arr, number) {
    var i = arr.length;
    while (i--) {
       if (arr[i].id === number) {
           return true;
       }
    }
    return false;
}

html:

{% if containsID(data, id) %} //I want something like that

{{data[id].text}}

{% else %}

 Not found

{% endif %}

Body:
you need to return the index of the item with given ID

function containsID(arr, obj) {
  var i = arr.length;
  while (i--) {
    if (arr[i].id === obj) {
       return i;
    }
  }
  return -1;
}

I am not sure what {% %} annotation stands for (looks like some template engine), but your html should by something like this:

{% if containsID(data, id) >= 0 %} //I want something like that
  <p>{{data[containsID(data, id)].text}}</p>
{% else %}
  <p> Not found </p>
{% endif %}

better is to store the result of containsID in some template variable and then use it twice (once in condition, once in output) to avoid looping the array two times


问:
How to ignore / omit / exclude files during test coverage?
In order to get 100% test coverage, I need to ignore some file(s) in python.

I searched the web and I found nosetests which I don't want to use.

I also found that I can edit my .coveragerc file and omit files and functions, when running my tests using intellij (with unittest framework), it didn't manage to use .coveragerc file.

Any idea how to ignore / omit / exclude files during test coverage ?

How can I run the test using this file as a parameter ?

答:
You can use this command in your .coveragerc file.

```<code># .coveragerc
[report]
show_missing = True
omit =
    junk/*
</code>```

You include the path of files you want to omit under the omit command, for example, I want to omit every file in the junk folder hence my use of junk/*.

Body:
You can use this command in your .coveragerc file.

# .coveragerc
[report]
show_missing = True
omit =
    junk/*

You include the path of files you want to omit under the omit command, for example, I want to omit every file in the junk folder hence my use of junk/*.


问:
clickable listview on bottomsheet
I've made an bottom sheet with listview which working really fin but, I also want, that listview items be clickable.

main_activity:

```<code>public class MainActivity extends AppCompatActivity {

String[] serialNumber = new String[]{"XX-453-CS","KF-009-KD","GD-098-ML","SG-865-43","IJ-736-OK"};
String[] fee = new String[]{"50თ","74თ","30თ","88თ","65თ"};
String[] avtime = new String[] {"02:36","03:32","10:55","00:36","03:46"};

Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn);
    final ArrayList<Offers> listViewData = getOffers();
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BottomSheetDialog dialog = new BottomSheetDialog(MainActivity.this);
            View parentView = getLayoutInflater().inflate(R.layout.bottom_sheet_layout,null);
            dialog.setContentView(parentView);
            BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from((View) parentView.getParent());
            bottomSheetBehavior.setPeekHeight(
                    (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,100,getResources().getDisplayMetrics()));
            BottomSheetListView listView = (BottomSheetListView) dialog.findViewById(R.id.listViewBtmSheet);
            OffersAdapter adapter = new OffersAdapter(MainActivity.this,listViewData);
            listView.setAdapter(adapter);
            dialog.show();
        }
    });
}

private ArrayList<Offers> getOffers() {
    ArrayList<Offers> list =new ArrayList<>();
    for(int j=0;j<5;j++) {
        for (int i = 0; i < fee.length; i++) {
            Offers offer = new Offers(serialNumber[i], fee[i], avtime[i]);
            list.add(offer);
        }
    }
    return list;
}
}
</code>```

Bottomsheetlistview is from here : ListView in BottomSheet

and finally bottom sheet layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Offers"
            android:textSize="20sp"
            android:layout_gravity="center"/>

        <ge.yep.bb.BottomSheetListView
            android:id="@+id/listViewBtmSheet"
            android:divider="@color/colorPrimary"
            android:dividerHeight="10dp"
            android:layout_width="match_parent"
            android:layout_height="250dp" />

</LinearLayout>
</code>```

答:
Add this to your code:

```<code>listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //TODO:: Whatever you want to do
        }
    });
</code>```

This sets an individual click listener for each item. Inside the onItemClick you can implement anything you want.

Good day!

Title: clickable listview on bottomsheet

Body:
I've made an bottom sheet with listview which working really fin but, I also want, that listview items be clickable.

main_activity:

public class MainActivity extends AppCompatActivity {

String[] serialNumber = new String[]{"XX-453-CS","KF-009-KD","GD-098-ML","SG-865-43","IJ-736-OK"};
String[] fee = new String[]{"50თ","74თ","30თ","88თ","65თ"};
String[] avtime = new String[] {"02:36","03:32","10:55","00:36","03:46"};

Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn);
    final ArrayList<Offers> listViewData = getOffers();
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BottomSheetDialog dialog = new BottomSheetDialog(MainActivity.this);
            View parentView = getLayoutInflater().inflate(R.layout.bottom_sheet_layout,null);
            dialog.setContentView(parentView);
            BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from((View) parentView.getParent());
            bottomSheetBehavior.setPeekHeight(
                    (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,100,getResources().getDisplayMetrics()));
            BottomSheetListView listView = (BottomSheetListView) dialog.findViewById(R.id.listViewBtmSheet);
            OffersAdapter adapter = new OffersAdapter(MainActivity.this,listViewData);
            listView.setAdapter(adapter);
            dialog.show();
        }
    });
}

private ArrayList<Offers> getOffers() {
    ArrayList<Offers> list =new ArrayList<>();
    for(int j=0;j<5;j++) {
        for (int i = 0; i < fee.length; i++) {
            Offers offer = new Offers(serialNumber[i], fee[i], avtime[i]);
            list.add(offer);
        }
    }
    return list;
}
}

Bottomsheetlistview is from here : ListView in BottomSheet

and finally bottom sheet layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Offers"
            android:textSize="20sp"
            android:layout_gravity="center"/>

        <ge.yep.bb.BottomSheetListView
            android:id="@+id/listViewBtmSheet"
            android:divider="@color/colorPrimary"
            android:dividerHeight="10dp"
            android:layout_width="match_parent"
            android:layout_height="250dp" />

</LinearLayout>

Body:
Add this to your code:

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //TODO:: Whatever you want to do
        }
    });

This sets an individual click listener for each item. Inside the onItemClick you can implement anything you want.

Good day!


问:
urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error
I am getting the following error:

```<code>Exception in thread Thread-3:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in        __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in  run
self.__target(*self.__args, **self.__kwargs)
File "/Users/Matthew/Desktop/Skypebot 2.0/bot.py", line 271, in process
info = urllib2.urlopen(req).read()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1240, in https_open
context=self._context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>
</code>```

This is the code that is causing this error:

```<code>if input.startswith("!web"):
    input = input.replace("!web ", "")
    url = "https://domainsearch.p.mashape.com/index.php?name=" + input
    req = urllib2.Request(url, headers={ 'X-Mashape-Key': 'XXXXXXXXXXXXXXXXXXXX' })
    info = urllib2.urlopen(req).read()
    Message.Chat.SendMessage ("" + info)
</code>```

The API I'm using requires me to use HTTPS. How can I make it bypass the verification?

答:
Try

pip install --trusted-host pypi.python.org packagename

It worked for me.

Body:
I am getting the following error:

Exception in thread Thread-3:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in        __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in  run
self.__target(*self.__args, **self.__kwargs)
File "/Users/Matthew/Desktop/Skypebot 2.0/bot.py", line 271, in process
info = urllib2.urlopen(req).read()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1240, in https_open
context=self._context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>

This is the code that is causing this error:

if input.startswith("!web"):
    input = input.replace("!web ", "")
    url = "https://domainsearch.p.mashape.com/index.php?name=" + input
    req = urllib2.Request(url, headers={ 'X-Mashape-Key': 'XXXXXXXXXXXXXXXXXXXX' })
    info = urllib2.urlopen(req).read()
    Message.Chat.SendMessage ("" + info)

The API I'm using requires me to use HTTPS. How can I make it bypass the verification?


问:
OpenCover not covering actual source code
I am trying to use open cover to generate code coverage reports for my project, but it only covers test classes, not the source ones that I want.
I am using the following command to run my tests:

```<code>"C:\Program Files (x86)\OpenCover\OpenCover.Console.exe" -register:user -target:"$nunit_path\nunit-console.exe" -targetargs:"$project_path\Project.Test\Project.Test.dll -noshadow"  -mergebyhash -output:C:\Reports\NUnit\projectCoverageReport.xml
</code>```

$nunit_path and $project_path are just the paths to my files, I skipped them to make the command clearer.

When I run this command, I get the full coverage of the test classes (inside the Project.Test.dll assembly) but nothing else. How do I make OpenCover consider the source code as well?

答:
One possible reason for this issue is the way pdb files are configured for that particular project. OpenCover expects the pdb files to be in their 'full' form rather than in 'portable' form. By default, visual studio marks pdb files as 'portable'. You can check this by doing following..

Right click on project -> proerties -> build -> Output -> Advanced -> debugging information.

Here the value should be 'full'.

Body:
I am trying to use open cover to generate code coverage reports for my project, but it only covers test classes, not the source ones that I want.
I am using the following command to run my tests:

"C:\Program Files (x86)\OpenCover\OpenCover.Console.exe" -register:user -target:"$nunit_path\nunit-console.exe" -targetargs:"$project_path\Project.Test\Project.Test.dll -noshadow"  -mergebyhash -output:C:\Reports\NUnit\projectCoverageReport.xml

$nunit_path and $project_path are just the paths to my files, I skipped them to make the command clearer.

When I run this command, I get the full coverage of the test classes (inside the Project.Test.dll assembly) but nothing else. How do I make OpenCover consider the source code as well?


问:
How can one close HTML tags in Vim quickly?
It's been a while since I've had to do any HTML-like code in Vim, but recently I came across this again. Say I'm writing some simple HTML:

```<code><html><head><title>This is a title</title></head></html>
</code>```

How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.

Of course I can use CtrlP to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.

答:
If you're doing anything elaborate, sparkup is very good.

An example from their site:

ul > li.item-$*3 expands to:

```<code><ul>
    <li class="item-1"></li>
    <li class="item-2"></li>
    <li class="item-3"></li>
</ul>
</code>```

with a <C-e>.

To do the example given in the question,

```<code>html > head > title{This is a title}
</code>```

yields

```<code><html>
  <head>
    <title>This is a title</title>
  </head>
</html>
</code>```

OwnerDisplayName: wds

Body:
It's been a while since I've had to do any HTML-like code in Vim, but recently I came across this again. Say I'm writing some simple HTML:

<title>This is a title</title>

How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.

Of course I can use CtrlP to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.

Body:
If you're doing anything elaborate, sparkup is very good.

An example from their site:

ul > li.item-$*3 expands to:

<ul>
    <li class="item-1"></li>
    <li class="item-2"></li>
    <li class="item-3"></li>
</ul>

with a <C-e>.

To do the example given in the question,

html > head > title{This is a title}

yields

<html>
  <head>
    <title>This is a title</title>
  </head>
</html>


问:
Python How do I count the number of month of 30 days after a date
I have a dataframe containing date, and I would like to process the data as follow for feature engineering

df

```<code>date
2016/1/1
2015/2/10
2016/4/5
</code>```

after process I would like to make the df looks like

```<code>date      Jan    Feb   Mar   Apr
2016/1/1  30     0    0      0    //date from 1/1 to 1/30 : the number of dates in jan
2015/2/10  0     19   11     0    //date from 2/10 to 3/11 : the number of dates in feb and no of dates in mar
2016/3/25  0     0    7     21    //date from 3/25 to 4/21 : the number of dates in mar and no of dates in apr
</code>```

get 30 days after the df["date"]

df["date"] + timedelta(month=1)

count the frequency of months which belong to the specific 30 days

Is there any method to do this quickly?

Thanks.

答:
You can use custom function with date_range and groupby with size:

```<code>date = df[['date']]
names = ['Jan', 'Feb','Mar','Apr','May']

def f(x):
    print (x['date'])
    a = pd.date_range(x['date'], periods=30)
    a = pd.Series(a).groupby(a.month).size()
    return (a)

df = df.apply(f, axis=1).fillna(0).astype(int)
df = df.rename(columns = {k:v for k,v in enumerate(names)})
df = date.join(df)
print (df)
        date  Feb  Mar  Apr  May
0 2016-01-01   30    0    0    0
1 2015-02-10    0   19   11    0
2 2016-03-25    0    0    7   23
</code>```

Similar solution with value_counts:

```<code>date = df[['date']]
names = ['Jan', 'Feb','Mar','Apr','May']

df = df.apply(lambda x: pd.date_range(x['date'], periods=30).month.value_counts(), axis=1)
       .fillna(0)
       .astype(int)
df = df.rename(columns = {k:v for k,v in enumerate(names)})
df = date.join(df)
print (df)
</code>```

Another solution:

```<code>names = ['Jan', 'Feb','Mar','Apr','May']
date = df[['date']]

df["date1"] = df["date"] + pd.Timedelta(days=29)
df = df.reset_index().melt(id_vars='index', value_name='date').set_index('date')
df = df.groupby('index').resample('D').asfreq()
df = df.groupby([df.index.get_level_values(0), df.index.get_level_values(1).month])
      .size()
      .unstack(fill_value=0)
df = df.rename(columns = {k+1:v for k,v in enumerate(names)})
df = date.join(df)
print (df)
        date  Jan  Feb  Mar  Apr
0 2016-01-01   30    0    0    0
1 2015-02-10    0   19   11    0
2 2016-03-25    0    0    7   23
</code>```

Body:
I have a dataframe containing date, and I would like to process the data as follow for feature engineering

df

date
2016/1/1
2015/2/10
2016/4/5

after process I would like to make the df looks like

date      Jan    Feb   Mar   Apr
2016/1/1  30     0    0      0    //date from 1/1 to 1/30 : the number of dates in jan
2015/2/10  0     19   11     0    //date from 2/10 to 3/11 : the number of dates in feb and no of dates in mar
2016/3/25  0     0    7     21    //date from 3/25 to 4/21 : the number of dates in mar and no of dates in apr

get 30 days after the df["date"]

df["date"] + timedelta(month=1)

count the frequency of months which belong to the specific 30 days

Is there any method to do this quickly?

Thanks.

Body:
You can use custom function with date_range and groupby with size:

date = df[['date']]
names = ['Jan', 'Feb','Mar','Apr','May']

def f(x):
    print (x['date'])
    a = pd.date_range(x['date'], periods=30)
    a = pd.Series(a).groupby(a.month).size()
    return (a)

df = df.apply(f, axis=1).fillna(0).astype(int)
df = df.rename(columns = {k:v for k,v in enumerate(names)})
df = date.join(df)
print (df)
        date  Feb  Mar  Apr  May
0 2016-01-01   30    0    0    0
1 2015-02-10    0   19   11    0
2 2016-03-25    0    0    7   23

Similar solution with value_counts:

date = df[['date']]
names = ['Jan', 'Feb','Mar','Apr','May']

df = df.apply(lambda x: pd.date_range(x['date'], periods=30).month.value_counts(), axis=1)
       .fillna(0)
       .astype(int)
df = df.rename(columns = {k:v for k,v in enumerate(names)})
df = date.join(df)
print (df)

Another solution:

names = ['Jan', 'Feb','Mar','Apr','May']
date = df[['date']]

df["date1"] = df["date"] + pd.Timedelta(days=29)
df = df.reset_index().melt(id_vars='index', value_name='date').set_index('date')
df = df.groupby('index').resample('D').asfreq()
df = df.groupby([df.index.get_level_values(0), df.index.get_level_values(1).month])
      .size()
      .unstack(fill_value=0)
df = df.rename(columns = {k+1:v for k,v in enumerate(names)})
df = date.join(df)
print (df)
        date  Jan  Feb  Mar  Apr
0 2016-01-01   30    0    0    0
1 2015-02-10    0   19   11    0
2 2016-03-25    0    0    7   23


问:
How can I group similar results from mySQL database in foreach loop?
```<code>$pdo = $db->prepare('SELECT * FROM animals WHERE id = :id ');
$pdo->execute(array('id' => $id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
     $name = $row["name"];
     echo $name."<br>";
}
</code>```

The result of my loop is right now-

```<code>cat
cat
cat
cat
dog
bird
</code>```

I want to group results if they are similar, so I get as a result like this-

```<code>cat
dog
bird
</code>```

答:
use DISTINCT of mysql to get the unique records from your table as

```<code>$pdo = $db->prepare('SELECT DISTINCT name FROM animals WHERE id = :id ');
</code>```

Body:
$pdo = $db->prepare('SELECT * FROM animals WHERE id = :id ');
$pdo->execute(array('id' => $id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
     $name = $row["name"];
     echo $name."
";
}

The result of my loop is right now-

cat
cat
cat
cat
dog
bird

I want to group results if they are similar, so I get as a result like this-

cat
dog
bird

Body:
use DISTINCT of mysql to get the unique records from your table as

$pdo = $db->prepare('SELECT DISTINCT name FROM animals WHERE id = :id ');


答:
Sql DISTINCT Clause is your Friend.
Alternatively, doing by php will go this way,</p>

```<code>$pdo = $db->prepare('SELECT * FROM animals WHERE category = :category ');
        $pdo->execute(array('category' => $category));
        while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
            $name[$row["name"]] = $row["name"];
            echo $name."<br>";
        }
</code>```

Title: How can I group similar results from mySQL database in foreach loop?

Body:
Sql DISTINCT Clause is your Friend.
Alternatively, doing by php will go this way,

$pdo = $db->prepare('SELECT * FROM animals WHERE category = :category ');
        $pdo->execute(array('category' => $category));
        while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
            $name[$row["name"]] = $row["name"];
            echo $name."<br>";
        }


问:
How to enable/disable a button while validating a button?
here I try this code.......enter image description here I try this code...I want to disable a button while validating a username and password.
if my username and password is correct then my button will enable...But I didn't get correct answer.</p>

答: It looks to me like sbutton is an IBAction, not an outlet. If so your code probably won't compile. You need to control-drag from your button into your code to create an IBOutlet for your button and use the outlet to enable/disable the button.


问:
Better null-management try-catch with Java 8
Given the following code:

```<code>StaticPOIDataType response = null;
try {
  final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
  final Unmarshaller unmarshaller = jc.createUnmarshaller();
  unmarshaller.setSchema(getSchema());

  response =((JAXBElement<StaticPOIDataType>) unmarshaller.unmarshal(cpoGatewayURL)).getValue();

} catch (JAXBException e) {
  e.printStackTrace();
} finally {
  return response;
}
</code>```

I heard of a new Java 8-feature to express this in a much more elegant way by avoiding null-initializiation. But I don't know what to search for.

答:
I think you are looking for Optional in  Java 8,

Please find a this documentation with nice samples.

https://dzone.com/articles/java-8-optional-avoid-null-and

Body:
Given the following code:

StaticPOIDataType response = null;
try {
  final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
  final Unmarshaller unmarshaller = jc.createUnmarshaller();
  unmarshaller.setSchema(getSchema());

  response =((JAXBElement<StaticPOIDataType>) unmarshaller.unmarshal(cpoGatewayURL)).getValue();

} catch (JAXBException e) {
  e.printStackTrace();
} finally {
  return response;
}

I heard of a new Java 8-feature to express this in a much more elegant way by avoiding null-initializiation. But I don't know what to search for.


问:
How to remove an inherited ValidationAttribute?
I have a controller which take a model as parameter. This model is a specialized version of a generic model. I want my specialized model to hide a required base field to make it not required.

Here is what I did :

Controller

```<code>public class TestController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new SpecializedModel());
    }

    [HttpPost]
    public ActionResult Index(SpecializedModel model)
    {
        if(ModelState.IsValid)
        {
            //Do some stuff, eventually redirect elsewhere
        }

        return View(model);
    }
}
</code>```

GenericModel

```<code>public class GenericModel
{
    [Required(ErrorMessage = "The field is required.")]
    public string SomeValue { get; set; }
}
</code>```

SpecializedModel

```<code>public class SpecializedModel : GenericModel
{
    new public string SomeValue { get; set; }
}
</code>```

View

```<code>    <form method="post">
        @Html.TextBoxFor(model => model.SomeValue)<br />
        @Html.ValidationMessageFor(model => model.SomeValue)<br />
        <input type="submit" />
    </form>
</code>```

When I validate the form, the error message

The field is required.

is shown. I gather the RequiredAttribute is kept... is there a way to get rid of it ?

Edit : I also tried to make the SomeValue a virtual field to override it, but the problem is the same.

答:
Remove this line from your view

@Html.ValidationMessageFor(model => model.SomeValue)

Body:
I have a controller which take a model as parameter. This model is a specialized version of a generic model. I want my specialized model to hide a required base field to make it not required.

Here is what I did :

Controller

public class TestController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new SpecializedModel());
    }

    [HttpPost]
    public ActionResult Index(SpecializedModel model)
    {
        if(ModelState.IsValid)
        {
            //Do some stuff, eventually redirect elsewhere
        }

        return View(model);
    }
}

GenericModel

public class GenericModel
{
    [Required(ErrorMessage = "The field is required.")]
    public string SomeValue { get; set; }
}

SpecializedModel

public class SpecializedModel : GenericModel
{
    new public string SomeValue { get; set; }
}

View

    <form method="post">
        @Html.TextBoxFor(model => model.SomeValue)

        @Html.ValidationMessageFor(model => model.SomeValue)

        <input type="submit" />
    </form>

When I validate the form, the error message

The field is required.

is shown. I gather the RequiredAttribute is kept... is there a way to get rid of it ?

Edit : I also tried to make the SomeValue a virtual field to override it, but the problem is the same.


问:
How to move cursor from one text field to another automatically in swift ios programmatically?
```<code>    func textFieldDidBeginEditing(textField: UITextField) {
    scrlView.setContentOffset(CGPointMake(0, textField.frame.origin.y-70), animated: true)

    if(textField == firstDigit){

        textField.becomeFirstResponder()
        secondDigit.resignFirstResponder()
    }

    else if(textField == secondDigit){

        textField.becomeFirstResponder()
        thirdDigit.resignFirstResponder()
    }

    else if(textField == thirdDigit){
        //textField.becomeFirstResponder()
        fourthDigit.becomeFirstResponder()
    }
</code>```

I am using four textfields for OTP entry in which only one number can be entered at a time. After entering the number I need to move the cursor automatically to next textfield.

答:
for swift 3

```<code>    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // On inputing value to textfield
    if ((textField.text?.characters.count)! < 1  && string.characters.count > 0){
        let nextTag = textField.tag + 1;

        // get next responder
        let nextResponder = textField.superview?.viewWithTag(nextTag);
        textField.text = string;

        if (nextResponder == nil){
            textField.resignFirstResponder()
        }
        nextResponder?.becomeFirstResponder();
        return false;
    }
    else if ((textField.text?.characters.count)! >= 1  && string.characters.count == 0){
        // on deleting value from Textfield
        let previousTag = textField.tag - 1;

        // get next responder
        var previousResponder = textField.superview?.viewWithTag(previousTag);

        if (previousResponder == nil){
            previousResponder = textField.superview?.viewWithTag(1);
        }
        textField.text = "";
        previousResponder?.becomeFirstResponder();
        return false;
    }
    return true;
}
</code>```

Body:
    func textFieldDidBeginEditing(textField: UITextField) {
    scrlView.setContentOffset(CGPointMake(0, textField.frame.origin.y-70), animated: true)

    if(textField == firstDigit){

        textField.becomeFirstResponder()
        secondDigit.resignFirstResponder()
    }

    else if(textField == secondDigit){

        textField.becomeFirstResponder()
        thirdDigit.resignFirstResponder()
    }

    else if(textField == thirdDigit){
        //textField.becomeFirstResponder()
        fourthDigit.becomeFirstResponder()
    }

I am using four textfields for OTP entry in which only one number can be entered at a time. After entering the number I need to move the cursor automatically to next textfield.

Body:
for swift 3

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // On inputing value to textfield
    if ((textField.text?.characters.count)! < 1  && string.characters.count > 0){
        let nextTag = textField.tag + 1;

        // get next responder
        let nextResponder = textField.superview?.viewWithTag(nextTag);
        textField.text = string;

        if (nextResponder == nil){
            textField.resignFirstResponder()
        }
        nextResponder?.becomeFirstResponder();
        return false;
    }
    else if ((textField.text?.characters.count)! >= 1  && string.characters.count == 0){
        // on deleting value from Textfield
        let previousTag = textField.tag - 1;

        // get next responder
        var previousResponder = textField.superview?.viewWithTag(previousTag);

        if (previousResponder == nil){
            previousResponder = textField.superview?.viewWithTag(1);
        }
        textField.text = "";
        previousResponder?.becomeFirstResponder();
        return false;
    }
    return true;
}


问:
How can i add custom build steps in Qt-Creator?
After build my app, i want copy it to specific directory (on Windows 7).

Custom build step

```<code>cmd.exe \c \k copy MyPlugin.dll ..\..\..\HostApp\Debug\plugins
</code>```

But I have error:

```<code>Can't run process "cmd.exe \c \k copy MyPlugin.dll ..\..\..\HostApp\Debug\plugins"
</code>```

That's wrong?

答:
One way to do it would be to change the build output directory in the .pro file.
Something like

```<code>CONFIG(debug, debug|release) {
    DESTDIR = C:/myApp/debug
} else {
    DESTDIR = C:/myApp/release
}
</code>```

Or in your particular case

```<code>CONFIG(debug, debug|release) {
    DESTDIR = ..\..\..\HostApp\Debug\plugins
} else {
    DESTDIR = ..\..\..\HostApp\Release\plugins
}
</code>```

Edit:
This question has some good alternatives to my answer.

Body:
After build my app, i want copy it to specific directory (on Windows 7).

Custom build step

cmd.exe \c \k copy MyPlugin.dll ..\..\..\HostApp\Debug\plugins

But I have error:

Can't run process "cmd.exe \c \k copy MyPlugin.dll ..\..\..\HostApp\Debug\plugins"

That's wrong?

Body:
One way to do it would be to change the build output directory in the .pro file.
Something like

CONFIG(debug, debug|release) {
    DESTDIR = C:/myApp/debug
} else {
    DESTDIR = C:/myApp/release
}

Or in your particular case

CONFIG(debug, debug|release) {
    DESTDIR = ..\..\..\HostApp\Debug\plugins
} else {
    DESTDIR = ..\..\..\HostApp\Release\plugins
}

Edit:
This question has some good alternatives to my answer.


问:
XPATH - Find element where child items h3 text has a specific value

I need to find the selected DIV using a 'Employment' text for h3 tag.

I can find it using the following XPATH:

```<code>.//div[table[tbody[tr[td[h3[text() = 'Employment']]]]]]/following-sibling::div[@class = 'pbBody']
</code>```

But this is too big and ugly, what is the good way? something like:

parent::div[h3]following-sibling::div, so without this [table[tbody[tr[td[

HTML text:

Employment

```

答:
If you want shorter version you can try</p>

```<code>//h3[.="Employment"]/following::div[@class="pbBody"]
</code>```

Body:
I need to find the selected DIV using a 'Employment' text for h3 tag.

I can find it using the following XPATH:

.//div[table[tbody[tr[td[h3[text() = 'Employment']]]]]]/following-sibling::div[@class = 'pbBody']

But this is too big and ugly, what is the good way? something like:

parent::div[h3]following-sibling::div, so without this [table[tbody[tr[td[

HTML text:

Employment

Body:
If you want shorter version you can try

//h3[.="Employment"]/following::div[@class="pbBody"]


问:
System.ComponentModel.Win32Exception: The system cannot find the file specified
I been working on a website and when i finished everything was working properly then when i published it on somee.com i had an error when i tried to log in

PS.. log in credentials are not from a database, so i don't get why I'm receiving a database related error, and when i go back to visula studio and run the site it works without any errors

```<code>        if (TextBoxUserName.Text == "administrator" && TextBoxPassword.Text == "aphamia")
        {
            Session["user_ID"] = TextBoxUserName.Text;
            Response.Redirect("EmpLogin.aspx");
        }
        else
            LabelLogin.Text = "Icorrect Username or Password";

        if (Session["user_ID"] != null)
            PanelLogIn.Visible = false;
</code>```

答: Please Change the information of connection-string accordingly to hosted environment i.e database credentials,database schema,data-source etc. Make sure these information are correct</p>

Body:
I been working on a website and when i finished everything was working properly then when i published it on somee.com i had an error when i tried to log in

PS.. log in credentials are not from a database, so i don't get why I'm receiving a database related error, and when i go back to visula studio and run the site it works without any errors

        if (TextBoxUserName.Text == "administrator" && TextBoxPassword.Text == "aphamia")
        {
            Session["user_ID"] = TextBoxUserName.Text;
            Response.Redirect("EmpLogin.aspx");
        }
        else
            LabelLogin.Text = "Icorrect Username or Password";

        if (Session["user_ID"] != null)
            PanelLogIn.Visible = false;


问:
Conventions for metadata attributes in netCDF for compound data types
NetCDF allows (at least in its version 4 format based on HDF5) to create compound data types (very similar to a C struct). Each component has a label and a type and a position in the compound type. For example, for a data set of statistics, we could use the compound type defined by [('min', 'float'), ('max', 'float'), ('avg', 'float'), ('std', 'float')] has as its second component a float labeled max.

Now, netCDF also allows for adding metadata. These typically follow cenventions, such as the NetCDF Climate and Forecast (CF) Metadata Conventions. This is useful so that other users of the generated netCDF file can easily understand the metadata.

But I have not found conventions specifically dealing with compound data types, e.g., to give metadata specifically for one component of the compound data.

Are there such conventions?

If not or also, what is being used in practice?

If this is not used, what do you advise and why? (I was thinking of using multi-line attributes, so separated by \n, with a component-specific label to start each line, such as [avg] or #avg.)

答:
To stay within the CF conventions you could create a separate variable for each member of the compound type and use the ancillary_variables attribute to indicate that they are related:

```<code>netcdf test {
dimensions:
    time = 3 ;
    lat = 36 ;
    lon = 36 ;
variables:
    double time(time) ;
        time:long_name = "Time" ;
        time:standard_name = "time" ;
        time:units = "Days since 1970-01-01 00:00" ;
        time:calendar = "standard" ;
    float ctp(time, lat, lon) ;
        ctp:_FillValue = -999.f ;
        ctp:long_name = "Cloud Top Pressure" ;
        ctp:standard_name = "air_pressure_at_cloud_top" ;
        ctp:units = "Pa" ;
        ctp:cell_methods = "time: mean" ;
        ctp:ancillary_variables = "ctp_std ctp_min ctp_max" ;
    float ctp_std(time, lat, lon) ;
        ctp_std:_FillValue = -999.f ;
        ctp_std:long_name = "Cloud Top Pressure Standard Deviation" ;
        ctp_std:units = "Pa" ;
        ctp_std:cell_methods = "time: standard_deviation" ;
    float ctp_min(time, lat, lon) ;
        ctp_min:_FillValue = -999.f ;
        ctp_min:long_name = "Cloud Top Pressure Minimum" ;
        ctp_min:units = "Pa" ;
        ctp_min:cell_methods = "time: minimum" ;
    float ctp_max(time, lat, lon) ;
        ctp_max:_FillValue = -999.f ;
        ctp_max:long_name = "Cloud Top Pressure Maximum" ;
        ctp_max:units = "Pa" ;
        ctp_max:cell_methods = "time: maximum" ;
}
</code>```

You could then add metadata as usual via the variables' attributes. For example, the cell_methods attribute could be used to describe the applied statistics.

If you want to stick to the compound datatype, there is a ticket about vector quantities which might be related (although it is quite old): https://cf-trac.llnl.gov/trac/ticket/79

Body:
To stay within the CF conventions you could create a separate variable for each member of the compound type and use the ancillary_variables attribute to indicate that they are related:

netcdf test {
dimensions:
    time = 3 ;
    lat = 36 ;
    lon = 36 ;
variables:
    double time(time) ;
        time:long_name = "Time" ;
        time:standard_name = "time" ;
        time:units = "Days since 1970-01-01 00:00" ;
        time:calendar = "standard" ;
    float ctp(time, lat, lon) ;
        ctp:_FillValue = -999.f ;
        ctp:long_name = "Cloud Top Pressure" ;
        ctp:standard_name = "air_pressure_at_cloud_top" ;
        ctp:units = "Pa" ;
        ctp:cell_methods = "time: mean" ;
        ctp:ancillary_variables = "ctp_std ctp_min ctp_max" ;
    float ctp_std(time, lat, lon) ;
        ctp_std:_FillValue = -999.f ;
        ctp_std:long_name = "Cloud Top Pressure Standard Deviation" ;
        ctp_std:units = "Pa" ;
        ctp_std:cell_methods = "time: standard_deviation" ;
    float ctp_min(time, lat, lon) ;
        ctp_min:_FillValue = -999.f ;
        ctp_min:long_name = "Cloud Top Pressure Minimum" ;
        ctp_min:units = "Pa" ;
        ctp_min:cell_methods = "time: minimum" ;
    float ctp_max(time, lat, lon) ;
        ctp_max:_FillValue = -999.f ;
        ctp_max:long_name = "Cloud Top Pressure Maximum" ;
        ctp_max:units = "Pa" ;
        ctp_max:cell_methods = "time: maximum" ;
}

You could then add metadata as usual via the variables' attributes. For example, the cell_methods attribute could be used to describe the applied statistics.

If you want to stick to the compound datatype, there is a ticket about vector quantities which might be related (although it is quite old): https://cf-trac.llnl.gov/trac/ticket/79