问:
PHP / LARAVEL 5 ErrorException in MainController.php
all.
I have problems after making some new steps. I'm rails developer, but now i have to do some support in php/laravel project. After making some UI + backend in project(adding OpenGraph in project + admin) - i made a command - php artisan migrate:fresh.
And now i have this code error.

(1/1) ErrorException
Trying to get property 'title' of non-object

in MainController.php line 78

MetaTag.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Setting
 *
 * @mixin \Eloquent
 */
class MetaTag extends Model
{
    /**
     * @var array
     */
    protected $table = "meta_tags";
    protected $fillable = ['title', 'description', 'keywords','og_type','og_title','og_description'];

}
```

<p>part of MainController.php</p>

<pre class="lang-php prettyprint-override"><code>

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use App\Http\Requests;

class MainController extends Controller
{
    public function index()
    {
        $main_banner = \App\Banner::where('type', '1')
            ->where('page', '1')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->first();

        $premium_blocks = \App\Banner::where('type', '2')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->get();

        $active_animations = \App\Setting::where('alias', 'anumations_active')->first();
        $active_films = \App\Setting::where('alias', 'films_active')->first();
        $active_games = \App\Setting::where('alias', 'games_active')->first();
        $active_heroes = \App\Setting::where('alias', 'heroes_active')->first();
        $active_news = \App\Setting::where('alias', 'news_active')->first();
        $active_soundtracks = \App\Setting::where('alias', 'soundtracks_active')->first();

        $animations = \App\Animation::where('active', '1')
            ->orderBy('order', 'asc')
            ->get();
        $films = \App\Film::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $games = \App\Game::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $heroes = \App\Hero::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $news = \App\News::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $soundtracks = \App\Soundtrack::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();

        $arr_month_rus = \Config::get('settings.arr_month_rus');
        $arr_month_rus_lower = \Config::get('settings.arr_month_rus_lower');
        $arr_games_types = \Config::get('settings.arr_games_types');
        $arr_news_types = \Config::get('settings.arr_news_types');

        $agent = new Agent();

        $browser = $agent->browser();
        $v = explode('.',$agent->version($agent->browser()));
        $version = $v[0];

        if (
            ($browser == "Internet Explorer" && $version > 10) ||
            ($browser == "Edge" && $version > 11) ||
            ($browser == "Firefox" && $version > 46) ||
            ($browser == "Opera" && $version > 38) ||
            ($browser == "Safari" && $version > 8) ||
            ($browser == "Chrome" && $version > 51)
        )
            $outdated = false;
        else $outdated = true;

        $meta_tags = \App\MetaTag::where('alias',  '=', 'main_page')->first();
        $title = $meta_tags->title;
        $description = $meta_tags->description;
        $keywords = $meta_tags->keywords;
        $og_title = $meta_tags->og_title;
        $og_description = $meta_tags->og_description;
        $og_type = $meta_tags->og_type;

        return view((($agent->isMobile()) ? 'mobile.home' : 'home'), compact(
            'main_banner',
            'premium_blocks',
            'animations',
            'films',
            'games',
            'heroes',
            'news',
            'soundtracks',
            'active_animations',
            'active_films',
            'active_games',
            'active_heroes',
            'active_news',
            'active_soundtracks',
            'arr_games_types',
            'arr_month_rus_lower',
            'arr_news_types',
            'arr_month_rus',
            'outdated',
            'title',
            'description',
            'keywords',
            'og_title',
            'og_type',
            'og_description'
        ));
    }
</code>```

I expect just solve this little problem.
Thanks!

答:
Check if this line returns anything:

```<code>$meta_tags = \App\MetaTag::where('alias',  '=', 'main_page')->first();
</code>```

You can add an if statement like this (but set a default value for the variables to prevent errors):

```<code>$meta_tags = \App\MetaTag::where('alias', 'main_page')->first(); // You CAN ignore the equal sign
if($meta_tags){
    $title = $meta_tags->title;
    $description = $meta_tags->description;
    $keywords = $meta_tags->keywords;
    $og_title = $meta_tags->og_title;
    $og_description = $meta_tags->og_description;
    $og_type = $meta_tags->og_type;
} else {
    $title = "";
    $description = "";
    $keywords = "";
    $og_title = "";
    $og_description = "";
    $og_type = "";
}
</code>```

Body:
all.
I have problems after making some new steps. I'm rails developer, but now i have to do some support in php/laravel project. After making some UI + backend in project(adding OpenGraph in project + admin) - i made a command - php artisan migrate:fresh.
And now i have this code error.

(1/1) ErrorException
Trying to get property 'title' of non-object

in MainController.php line 78

MetaTag.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Setting
 *
 * @mixin \Eloquent
 */
class MetaTag extends Model
{
    /**
     * @var array
     */
    protected $table = "meta_tags";
    protected $fillable = ['title', 'description', 'keywords','og_type','og_title','og_description'];

}

part of MainController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use App\Http\Requests;

class MainController extends Controller
{
    public function index()
    {
        $main_banner = \App\Banner::where('type', '1')
            ->where('page', '1')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->first();

        $premium_blocks = \App\Banner::where('type', '2')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->get();

        $active_animations = \App\Setting::where('alias', 'anumations_active')->first();
        $active_films = \App\Setting::where('alias', 'films_active')->first();
        $active_games = \App\Setting::where('alias', 'games_active')->first();
        $active_heroes = \App\Setting::where('alias', 'heroes_active')->first();
        $active_news = \App\Setting::where('alias', 'news_active')->first();
        $active_soundtracks = \App\Setting::where('alias', 'soundtracks_active')->first();

        $animations = \App\Animation::where('active', '1')
            ->orderBy('order', 'asc')
            ->get();
        $films = \App\Film::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $games = \App\Game::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $heroes = \App\Hero::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $news = \App\News::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $soundtracks = \App\Soundtrack::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();

        $arr_month_rus = \Config::get('settings.arr_month_rus');
        $arr_month_rus_lower = \Config::get('settings.arr_month_rus_lower');
        $arr_games_types = \Config::get('settings.arr_games_types');
        $arr_news_types = \Config::get('settings.arr_news_types');

        $agent = new Agent();

        $browser = $agent->browser();
        $v = explode('.',$agent->version($agent->browser()));
        $version = $v[0];

        if (
            ($browser == "Internet Explorer" && $version > 10) ||
            ($browser == "Edge" && $version > 11) ||
            ($browser == "Firefox" && $version > 46) ||
            ($browser == "Opera" && $version > 38) ||
            ($browser == "Safari" && $version > 8) ||
            ($browser == "Chrome" && $version > 51)
        )
            $outdated = false;
        else $outdated = true;

        $meta_tags = \App\MetaTag::where('alias',  '=', 'main_page')->first();
        $title = $meta_tags->title;
        $description = $meta_tags->description;
        $keywords = $meta_tags->keywords;
        $og_title = $meta_tags->og_title;
        $og_description = $meta_tags->og_description;
        $og_type = $meta_tags->og_type;

        return view((($agent->isMobile()) ? 'mobile.home' : 'home'), compact(
            'main_banner',
            'premium_blocks',
            'animations',
            'films',
            'games',
            'heroes',
            'news',
            'soundtracks',
            'active_animations',
            'active_films',
            'active_games',
            'active_heroes',
            'active_news',
            'active_soundtracks',
            'arr_games_types',
            'arr_month_rus_lower',
            'arr_news_types',
            'arr_month_rus',
            'outdated',
            'title',
            'description',
            'keywords',
            'og_title',
            'og_type',
            'og_description'
        ));
    }

I expect just solve this little problem.
Thanks!

Body:
Check if this line returns anything:

$meta_tags = \App\MetaTag::where('alias',  '=', 'main_page')->first();

You can add an if statement like this (but set a default value for the variables to prevent errors):

$meta_tags = \App\MetaTag::where('alias', 'main_page')->first(); // You CAN ignore the equal sign
if($meta_tags){
    $title = $meta_tags->title;
    $description = $meta_tags->description;
    $keywords = $meta_tags->keywords;
    $og_title = $meta_tags->og_title;
    $og_description = $meta_tags->og_description;
    $og_type = $meta_tags->og_type;
} else {
    $title = "";
    $description = "";
    $keywords = "";
    $og_title = "";
    $og_description = "";
    $og_type = "";
}


来源: stackexchange

问:
Can somebody please justify this output?
I just want a proper explanation on to why printing __init__method using an object gives output "none".</p>

```<code>class cars:
    wheels = 4

    def __init__(self):
        self.mil = 10
        self.company = "BMW"

c1 = cars()
print(c1.__init__())
</code>```

答: __init__ doesn't return anything explicitly, therefore it implicitly returns None, which is the result you're seeing.

ContentLicense: CC BY-SA 4.0

Body:
I just want a proper explanation on to why printing __init__method using an object gives output "none".

class cars:
    wheels = 4

    def __init__(self):
        self.mil = 10
        self.company = "BMW"

c1 = cars()
print(c1.__init__())


问:
How can I stop emails being sent automatically to followers when a record is created?
Whenever I create a record like in subscription or change the states in the record, a mail is triggered to the followers present in record with the logs. How to stop sending these mails automatically which picks up the logs created in the form view?</p>

答:
Just go to settings->technical settings->subtype->disable the notification for your model.

In your case, for sale.subscription, Just disable the model by clicking the default checkbox.


问:
Protecting the openshift origin web console from public access
So I'm hoping someone can give me some insight in my problem.
Been googling, reading blogs/articles, checking the documentation, but can't really figure it out...

So, if I want to deploy Openshift/OKD to a VPS, doesn't matter if it's the all-in-one deployment or not: how do I secure the web console?

I was expecting that it would be possible to e.g. execute an "oc cluster up" with public-master equal to my local-ip or public ip. Then, use iptables to block access to this port publicly and use ssh port forwarding (in putty) to access the webconsole. However, apparently accessing the web-console executes some form of forwarding, which basically makes ssh port forwarding for accessing it fail. I tried with ssh port forwarding by both setting the public master to my localhost ip and my public ip of the vps: same issue, ssh port forwarding doesn't work.

What I definitely do NOT want to do, is just expose the web-console to everyone with just a username and password combination.

So what options are there to actually secure the web console for openshift for public access over the internet?

There are a lot of articles to be found online on how to deploy it, but basically they all just seem to expose the web console publicly to everyone...

答:
had the same problem, that is, ssh port forwarding didn't work due to web-console forwarding and redirects.

Solved it by forwarding to the same port, which seems to work:

```<code>ssh -L 8443:localhost:8443 -f -N user@host
</code>```

Forwarding to different port didn't work:

```<code>ssh -L 1443:localhost:8443 -f -N user@host
</code>```

Body:
had the same problem, that is, ssh port forwarding didn't work due to web-console forwarding and redirects.

Solved it by forwarding to the same port, which seems to work:

ssh -L 8443:localhost:8443 -f -N user@host

Forwarding to different port didn't work:

ssh -L 1443:localhost:8443 -f -N user@host


问:
If I add one column as list of enum, one row has many category, then it will be efficient or has better way to do this?
Online store has many category. I want to implement this in mysql. If I add one column category as list of enum, then it will be efficient or has better way to do this?</p>

答:
Online store has many category.

This immediately suggests three tables:

stores

categories

storeCategories

The third is called a "junction" or "association" table and it contains one row per store and category.

So, your question is whether you should use an enum for this purpose.  The answer is "no".


问:
Unit test function that is opening and reading a file
I am working on learning go with a simple program that is doing some file reading and am working on adding unit testing to my program. I have ran into an issue/question while doing this. I want to unit test the function below and my question is that the function takes a name of the file which is then opened and processed. During testing I do not want to actually pass it a real file. I am wondering is this something I can somehow mock so that I can just pass it a "fake" file and have it process that instead? Thanks!    </p>

```<code>func openAndReadFile(fileName string) [][]string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Printf("Failed to read file: %s", fileName)
    }
    r := csv.NewReader(file)
    lines, err := r.ReadAll()
    if err != nil {
        log.Fatal(err)
    }
    return lines
}
</code>```

答: I'd strongly suggest using an interface instead of the filename string like the other answers here are recommending, but if you really must do this the only way is likely with a temp file. The decision to use a string file name has locked the code into assuming something to be present on the file system and has pushed in the responsibility of file management. </p>

Body:
I am working on learning go with a simple program that is doing some file reading and am working on adding unit testing to my program. I have ran into an issue/question while doing this. I want to unit test the function below and my question is that the function takes a name of the file which is then opened and processed. During testing I do not want to actually pass it a real file. I am wondering is this something I can somehow mock so that I can just pass it a "fake" file and have it process that instead? Thanks!

func openAndReadFile(fileName string) [][]string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Printf("Failed to read file: %s", fileName)
    }
    r := csv.NewReader(file)
    lines, err := r.ReadAll()
    if err != nil {
        log.Fatal(err)
    }
    return lines
}


问:
How to use Google Colaboratory server as python interpreter in Python IDE?
Google Colaboratory currently by default provides Jupyter notebook like interface for code development. But I feel that code development on this interface without advanced IDE features is constraining.

If I can use Google Colaboratory as a remote python console server for code development in IDE like Spyder or Pycharm it will be great. How do I do this?

答:
Google Collaboratory cannot be used as a remote python console.
Check out this FAQ which states clearly that it is just a Jupyter notebook environment.  </p>


问:
How to join multiple Python scripts together into one script?
Is it possible to easily link each one to the scripts to 'A Complete Formula', as I have to do it multiple times and adding daily?

I have been compiling many of my own python scripts to calculate various math equations. I have over 15 scripts that I want to put together.

I am one of those people who will prefer to have something I can just press and it does the task automatically other than doing in manually - even if it takes twice as long at the start.

I have been just copying and pasting into the 'main' script that I can turn into an .exe but I have found that I have been changing, finding errors or making it better on the original file.

```<code>from math import *
from os import system, name
import math

def clear():

    if name == 'nt':
        _ = system('cls')

while True:
    print("Area of Circle (1)\nArea of a Parallelogram (2)\nArea of a Quadrants and Semicirlces (3)\nArea of a Rectangle (4)\nArea of a Rhombus (5)\nArea of a Trapezium (6)\nArea of a Triangle (7)\nCircumfrence of a Circle (8)\nCircumfrence of a Quadrant or Semicircle (9)\nVolume of a Cylinder (10)\nVolume of a Parallelogram Prism (11)\nVolume of a Rectangular Prism (12)\nVolume of a Rhomus Prism (13)\nVolume of a Sphere (14)\nVolume of a Trapezium Prism (15)\nVolume of a Triangle Prism (16)")
    print()
    choice = input("Choose Formular: ")

    if choice == "1":
        print("Area of a Circle")
        num = float(input("Radius of Circle: "))
        rud = int(input("Place of rounding: "))
        ans = math.pi * num ** int("2")
        print(round(ans, rud))
        input("Press Enter to continue...")
        clear()
</code>```

答:
You can import the scripts.

Let's say you have the files with the individual formulas as formula1.py, formula2.py, etc with one function in it, solve() that does all the work. Asking for input, calculating, then giving the output. You can then do it like this.

```<code>import formula1, formula2, formula3
while True:
    ...
    if choice == '1': formula1.solve()
    elif choice == '2': formula2.solve()
    elif choice == '3': formula3.solve()
    else: print('Wrong Choice')
</code>```

If you want your individual files to work as well then you can write them like this:

```<code>def solve():
    ...

if __name__ == '__main__':
    solve()
</code>```

Do take care that without the if __name__ == '__main__' clause, importing the file will also run it.

Body:
Is it possible to easily link each one to the scripts to 'A Complete Formula', as I have to do it multiple times and adding daily?

I have been compiling many of my own python scripts to calculate various math equations. I have over 15 scripts that I want to put together.

I am one of those people who will prefer to have something I can just press and it does the task automatically other than doing in manually - even if it takes twice as long at the start.

I have been just copying and pasting into the 'main' script that I can turn into an .exe but I have found that I have been changing, finding errors or making it better on the original file.

from math import *
from os import system, name
import math

def clear():

    if name == 'nt':
        _ = system('cls')

while True:
    print("Area of Circle (1)\nArea of a Parallelogram (2)\nArea of a Quadrants and Semicirlces (3)\nArea of a Rectangle (4)\nArea of a Rhombus (5)\nArea of a Trapezium (6)\nArea of a Triangle (7)\nCircumfrence of a Circle (8)\nCircumfrence of a Quadrant or Semicircle (9)\nVolume of a Cylinder (10)\nVolume of a Parallelogram Prism (11)\nVolume of a Rectangular Prism (12)\nVolume of a Rhomus Prism (13)\nVolume of a Sphere (14)\nVolume of a Trapezium Prism (15)\nVolume of a Triangle Prism (16)")
    print()
    choice = input("Choose Formular: ")

    if choice == "1":
        print("Area of a Circle")
        num = float(input("Radius of Circle: "))
        rud = int(input("Place of rounding: "))
        ans = math.pi * num ** int("2")
        print(round(ans, rud))
        input("Press Enter to continue...")
        clear()

Body:
You can import the scripts.

Let's say you have the files with the individual formulas as formula1.py, formula2.py, etc with one function in it, solve() that does all the work. Asking for input, calculating, then giving the output. You can then do it like this.

import formula1, formula2, formula3
while True:
    ...
    if choice == '1': formula1.solve()
    elif choice == '2': formula2.solve()
    elif choice == '3': formula3.solve()
    else: print('Wrong Choice')

If you want your individual files to work as well then you can write them like this:

def solve():
    ...

if __name__ == '__main__':
    solve()

Do take care that without the if __name__ == '__main__' clause, importing the file will also run it.


问:
How to get Android application id?
In Android, how do I get the application's id programatically (or by some other method), and how can I communicate with other applications using that id?</p>

答: If the whole purpose is to communicate data with some other application, use Intent's sendBroadcast methods.</p>

ContentLicense: CC BY-SA 2.5

Title: How to get Android application id?

ContentLicense: CC BY-SA 3.0


问:
Java Error: cannot resolve method split()
I am trying to get user input into a String array and wanted to use the string.split() method but for some reason, my IntelliJ is telling me, that it cannot resolve the method 'split()'.

package com.Practice;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String[] splittedString = input.split();
    }
}
```

<p>I dont think, that there is a problem with my code, mayby with my IDE or Java version, but im no expert at this stuff.
When I try to run the program it throws me this error:</p>

```Error:(10, 40) java: no suitable method found for split(no arguments)
    method java.lang.String.split(java.lang.String,int) is not applicable
      (actual and formal argument lists differ in length)
    method java.lang.String.split(java.lang.String) is not applicable
      (actual and formal argument lists differ in length)
```

答:
As mentioned in some of the other answers, String.split() in Java requires an input, if you intend to apply something to every character or create an array of characters you'll need to iterate for example.

```<code>private String myCoolString = "myCoolString";
private char[] chars = new char[myCoolString.length()];
//array of primitive chars
for( int i = 0; i < myCoolString.length();i++){
    chars[i] = myCoolString.charAt(i);
}

// List of boxed Characters (Java 8+, the above can be used to do this too)
List<Character> charList =
        myCoolString
                .chars()
                .mapToObj(e->(char)e)
                .collect(Collectors.toList());
</code>```

Body:
I am trying to get user input into a String array and wanted to use the string.split() method but for some reason, my IntelliJ is telling me, that it cannot resolve the method 'split()'.

package com.Practice;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String[] splittedString = input.split();
    }
}

I dont think, that there is a problem with my code, mayby with my IDE or Java version, but im no expert at this stuff.
When I try to run the program it throws me this error:

Error:(10, 40) java: no suitable method found for split(no arguments)
    method java.lang.String.split(java.lang.String,int) is not applicable
      (actual and formal argument lists differ in length)
    method java.lang.String.split(java.lang.String) is not applicable
      (actual and formal argument lists differ in length)

Body:
As mentioned in some of the other answers, String.split() in Java requires an input, if you intend to apply something to every character or create an array of characters you'll need to iterate for example.

private String myCoolString = "myCoolString";
private char[] chars = new char[myCoolString.length()];
//array of primitive chars
for( int i = 0; i < myCoolString.length();i++){
    chars[i] = myCoolString.charAt(i);
}

// List of boxed Characters (Java 8+, the above can be used to do this too)
List<Character> charList =
        myCoolString
                .chars()
                .mapToObj(e->(char)e)
                .collect(Collectors.toList());


问:
How to add button tint programmatically
In the new AppCompat library, we can tint the button this way:

```<code><Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/follow"
    android:id="@+id/button_follow"
    android:backgroundTint="@color/blue_100"
    />
</code>```

How can I set the tint of the button programmatically in my code?
I'm basically trying to implement a conditional coloring of the button based on some user input.

答:
this is easily handled in the new Material Button from material design library, first, add the dependency:

```<code>implementation 'com.google.android.material:material:1.1.0-alpha07'
</code>```

then in your XML, use this for your button:

```<code><com.google.android.material.button.MaterialButton
    android:id="@+id/accept"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/i_accept"
    android:textSize="18sp"
    app:backgroundTint="@color/grayBackground_500" />
</code>```

and when you want to change the color, here's the code in Kotlin, It's not deprecated and it can be used prior to Android 21:

```<code>accept.backgroundTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources,
R.color.colorPrimary, theme))
</code>```

Title: How to add button tint programmatically

Body:
In the new AppCompat library, we can tint the button this way:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/follow"
    android:id="@+id/button_follow"
    android:backgroundTint="@color/blue_100"
    />

How can I set the tint of the button programmatically in my code?
I'm basically trying to implement a conditional coloring of the button based on some user input.

Body:
this is easily handled in the new Material Button from material design library, first, add the dependency:

implementation 'com.google.android.material:material:1.1.0-alpha07'

then in your XML, use this for your button:

<com.google.android.material.button.MaterialButton
    android:id="@+id/accept"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/i_accept"
    android:textSize="18sp"
    app:backgroundTint="@color/grayBackground_500" />

and when you want to change the color, here's the code in Kotlin, It's not deprecated and it can be used prior to Android 21:

accept.backgroundTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources,
R.color.colorPrimary, theme))


问:
server-side restful api analytics
I have a rails-based restful server-side api.

I want to know what services are called the most, their response time, etc.

So this is sort of web analytics, but it's for server-side operation.

Is there any free service out there that can help out( google analytics is a good analogy)?

答:
I've had the same problem. A lot of services are for web analytics, this means they super general, and it's hard to configure it properly.

What I can suggest you is to use some kind of APM. There is one especially for Rails - https://appsignal.com/. But it's not free, price starts from 15 euro / month for 250K of requests.

Title: server-side restful api analytics


问:
Self executing lambda expression in Common Lisp
I thought that this is the only way to write self executing lambda expression in Common LISP:

```<code>(funcall #'(lambda (x) (format t "~S" x)) 10)
</code>```

but it seems that this also work in CLISP on GNU/Linux:

```<code>((lambda (x) (format t "~S" x)) 10)
</code>```

which is more like you do this in Scheme. Is this something that is correct according to Common LISP spec? Does other CL implementation also work this way.

答:
That's standard Common Lisp syntax.

See lambda forms in Conses as Forms.

Body:
I thought that this is the only way to write self executing lambda expression in Common LISP:

(funcall #'(lambda (x) (format t "~S" x)) 10)

but it seems that this also work in CLISP on GNU/Linux:

((lambda (x) (format t "~S" x)) 10)

which is more like you do this in Scheme. Is this something that is correct according to Common LISP spec? Does other CL implementation also work this way.


问:
Getting data from database and displaying it in a dialogue box
I want to get data from database and display it in a text view in a dialog box. In my application, I have a button that when it is clicked, a dialogue box will open. there is a text view in this dialogue box. The text view is going show data from SQLite database. Let me say some more. My database has four fields. one is id, the second title, third is the body and the last one is the translation of the body in another language. In the activity that shows the body, I have a button that when the user clicks on it, a dialogue box will appear that displays the translation. I have used recyclerView to show the titles and bodies.

Thanks in advance.

答: The easiest approach is to use Room and MVVM like this. The second option is to create a cursor and grab the data from that.</p>


问:
Are parentheses required in PSR-2 PHP ternary syntax?

Question: are parentheses required in PSR-2 PHP ternary syntax?

Looking for which (if either) of the following ternary statement's syntax is compliant with PSR-2 - I also need to be pointed to documentation or some authority link:

$error = ($error_status) ? 'Error' : 'No Error';

OR

$error = $error_status ? 'Error' : 'No Error';

Note: php.net it shows the syntax with the parentheses, but I could not find this in any of the 'official PSR-2' docs.

Conclusion

If there is no PSR-2 standard on this, which way is the most common convention?

答:
Some mixed opinions on this, and it's something that's unfortunately arbitrary.

What appears more common to me from what I’ve seen and have learned from would be best explained by noting the differences below, more specifically; how the parentheses don’t move in either case.

Long hand:

```<code>if ($is_full_page) {
  echo "medium-6";
} else {
  echo "medium-7";
}
</code>```

Short hand:

```<code>echo ($is_full_page) ? 'medium-6' : 'medium-7';
</code>```

That; to me; is true consistency in all it's beauty.

Body:
Some mixed opinions on this, and it's something that's unfortunately arbitrary.

What appears more common to me from what I’ve seen and have learned from would be best explained by noting the differences below, more specifically; how the parentheses don’t move in either case.

Long hand:

if ($is_full_page) {
  echo "medium-6";
} else {
  echo "medium-7";
}

Short hand:

echo ($is_full_page) ? 'medium-6' : 'medium-7';

That; to me; is true consistency in all it's beauty.


问:
Cannot find module 'vuetify-loader/lib/plugin'
When I load vuetify via the vue-cli3, I get an error when i do npm run serve, saying there is a missing loader.

Docs etc and searches have come up blank.

This is a fresh project, no code loaded. Just following the instructions from the vuetify site.

Can anyone help?

答:
I've got the same issues while creating new Vuetify app by official guide.

After adding vuetify: vue add vuetify

The missing step was installing new npm dependencies with: npm install

Later I run npm run serve and it started succesfully.

There is an issue in the documentation!


问:
How to bind custom style in b-col (bootstrap-vue) element?
I need to add custom style to my  element like below:

```<code><b-container fluid class="bootstrap-container">
    <b-row id="plan-execution">
        <b-col :style="executionProgress" >Hello!</b-col>
    </b-row>
</b-container>
</code>```

In the executionProgress variable it stores my previously calculated styles eg:

```<code>background: linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat
</code>```

(The style is calculated depending on the data collected from the API)

I tried: :style="", v-bind:style="" but no effect.

In code below binding style works perfect

        Hello!

```

Short question: How I can bind my previously populated style to  element?

答:
I solved my problem a little differently than @Andrei Gheorghiu suggested.

I used "normal"
 instead of  and works.
My solution:

```<code><div class="container sah-table">
    <div id="plan-execution" class="row">
        <div class="col-sm-12" :style="executionProgress">Hello</div>
    </div>
</div>
</code>```

my executionProgress variable I calculate:

```<code>        calculateExecutionProgress: function(progress: number) {
            let alpha = '0.2'

            this.executionProgress = 'background: linear-gradient(to right, rgba(0, 255, 0, ' +  alpha + ') 0% , rgba(0, 255, 0, ' +  alpha + ') ' + (Math.min(progress,1) * 100).toFixed(2) + '%, rgba(0, 255, 0, 0.0) ' + ((Math.min(progress  + 0.02, 1)) * 100).toFixed(2) + '%) no-repeat';
            console.log(this.executionProgress)
        },
</code>```

and it works too.

I don't like not knowing what I'm doing wrong, I have two solutions now :)

Body:
I need to add custom style to my  element like below:

        Hello!

In the executionProgress variable it stores my previously calculated styles eg:

background: linear-gradient(to right, rgba(0, 255, 0, 0.2) 0% , rgba(0, 255, 0, 0.2) 55.00%, rgba(0, 255, 0, 0.0) 57.00%) no-repeat

(The style is calculated depending on the data collected from the API)

I tried: :style="", v-bind:style="" but no effect.

In code below binding style works perfect

        Hello!

Short question: How I can bind my previously populated style to  element?

Body:
I solved my problem a little differently than @Andrei Gheorghiu suggested.

I used "normal" <div class="col" /> instead of <b-col /> and works.
My solution:

<div class="container sah-table">
    <div id="plan-execution" class="row">
        <div class="col-sm-12" :style="executionProgress">Hello</div>
    </div>
</div>

my executionProgress variable I calculate:

        calculateExecutionProgress: function(progress: number) {
            let alpha = '0.2'

            this.executionProgress = 'background: linear-gradient(to right, rgba(0, 255, 0, ' +  alpha + ') 0% , rgba(0, 255, 0, ' +  alpha + ') ' + (Math.min(progress,1) * 100).toFixed(2) + '%, rgba(0, 255, 0, 0.0) ' + ((Math.min(progress  + 0.02, 1)) * 100).toFixed(2) + '%) no-repeat';
            console.log(this.executionProgress)
        },

and it works too.

I don't like not knowing what I'm doing wrong, I have two solutions now :)


问:
pg 1.0.0 `fatal error: 'libpq-fe.h' file not found`
An error occurred while installing pg (1.0.0), and Bundler cannot continue

I have an issue with the bundle install and cannot complete the installation.

What can I do to finish the bundle?

```<code>  find_executable: checking for pg_config... -------------------- no

    --------------------

    find_header: checking for libpq-fe.h... -------------------- no

    "clang -o conftest -I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0/x86_64-darwin17 -I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0/ruby/backward -I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0 -I. -I/Users/leotyndall/.rbenv/versions/2.4.2/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -Wno-error=shorten-64-to-32  -pipe conftest.c  -L. -L/Users/leotyndall/.rbenv/versions/2.4.2/lib -L. -L/Users/leotyndall/.rbenv/versions/2.4.2/lib  -fstack-protector -L/usr/local/lib     -lruby-static -framework CoreFoundation  -lpthread -ldl -lobjc "
    checked program was:
    /* begin */
    1: #include "ruby.h"
    2:
    3: int main(int argc, char **argv)
    4: {
    5:   return 0;
    6: }
    /* end */

        "clang -E -I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0/x86_64-darwin17 -
             I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-
         2.4.0/ruby/backward -
         I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0 -I. -
         I/Users/leotyndall/.rbenv/versions/2.4.2/include  -D_XOPEN_SOURCE -
         D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -Wno-
         error=shorten-64-to-32  -pipe  conftest.c -o conftest.i"
         conftest.c:3:10: fatal error: 'libpq-fe.h' file not found
         #include <libpq-fe.h>
             ^~~~~~~~~~~~
         1 error generated.
         checked program was:
         /* begin */
         1: #include "ruby.h"
         2:
         3: #include <libpq-fe.h>
        /* end */

    --------------------

     extconf failed, exit code 1

        An error occurred while installing pg (1.0.0), and Bundler cannot continue.
        Make sure that `gem install pg -v '1.0.0'` succeeds before bundling.
</code>```

答:
I solved this by installing the library

brew install libpqxx

Next, install pg normally... you can use gem

gem install pg

Body:
An error occurred while installing pg (1.0.0), and Bundler cannot continue

I have an issue with the bundle install and cannot complete the installation.

What can I do to finish the bundle?

  find_executable: checking for pg_config... -------------------- no

    --------------------

    find_header: checking for libpq-fe.h... -------------------- no

    "clang -o conftest -I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0/x86_64-darwin17 -I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0/ruby/backward -I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0 -I. -I/Users/leotyndall/.rbenv/versions/2.4.2/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -Wno-error=shorten-64-to-32  -pipe conftest.c  -L. -L/Users/leotyndall/.rbenv/versions/2.4.2/lib -L. -L/Users/leotyndall/.rbenv/versions/2.4.2/lib  -fstack-protector -L/usr/local/lib     -lruby-static -framework CoreFoundation  -lpthread -ldl -lobjc "
    checked program was:
    /* begin */
    1: #include "ruby.h"
    2:
    3: int main(int argc, char **argv)
    4: {
    5:   return 0;
    6: }
    /* end */

        "clang -E -I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0/x86_64-darwin17 -
             I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-
         2.4.0/ruby/backward -
         I/Users/leotyndall/.rbenv/versions/2.4.2/include/ruby-2.4.0 -I. -
         I/Users/leotyndall/.rbenv/versions/2.4.2/include  -D_XOPEN_SOURCE -
         D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT    -O3 -Wno-
         error=shorten-64-to-32  -pipe  conftest.c -o conftest.i"
         conftest.c:3:10: fatal error: 'libpq-fe.h' file not found
         #include <libpq-fe.h>
             ^~~~~~~~~~~~
         1 error generated.
         checked program was:
         /* begin */
         1: #include "ruby.h"
         2:
         3: #include <libpq-fe.h>
        /* end */

    --------------------

     extconf failed, exit code 1

        An error occurred while installing pg (1.0.0), and Bundler cannot continue.
        Make sure that `gem install pg -v '1.0.0'` succeeds before bundling.


问:
last day/time of month
How do I get the last day of the month to be 11:59:59 pm? Right now it is showing 05/31/2019 12:00 AM. If I just do sysdate it just shows the time I ran it. Thanks. </p>

```<code>LAST_DAY(TRUNC(SYSDATE,'MM'))
</code>```

答:
I would use:

```<code>SELECT TRUNC(SYSDATE, 'MM') + INTERVAL '1' MONTH - INTERVAL '1' SECOND
FROM dual;
</code>```

(This has one less step than Tim's solution.)

Or in the older-fashioned method:

```<code>SELECT ADD_MONTHS(TRUNC(SYSDATE, 'MM'), 1) - 1/(24*60*60)
</code>```

If you convert this to a timestamp, you will see the time value:

```<code>SELECT CAST(TRUNC(sysdate, 'MM') + INTERVAL '1' MONTH - INTERVAL '1' SECOND as TIMESTAMP)
FROM dual;
</code>```

Title: last day/time of month

Body:
How do I get the last day of the month to be 11:59:59 pm? Right now it is showing 05/31/2019 12:00 AM. If I just do sysdate it just shows the time I ran it. Thanks.

LAST_DAY(TRUNC(SYSDATE,'MM'))

Body:
I would use:

SELECT TRUNC(SYSDATE, 'MM') + INTERVAL '1' MONTH - INTERVAL '1' SECOND
FROM dual;

(This has one less step than Tim's solution.)

Or in the older-fashioned method:

SELECT ADD_MONTHS(TRUNC(SYSDATE, 'MM'), 1) - 1/(24*60*60)

If you convert this to a timestamp, you will see the time value:

SELECT CAST(TRUNC(sysdate, 'MM') + INTERVAL '1' MONTH - INTERVAL '1' SECOND as TIMESTAMP)
FROM dual;


问:
Previous layout get clicked from overlaped layout in Activity
I have two reletive layout. First has spinner and recyclerview and second has a imageview. Second layout overlap first layout on button click. But when I click on second layout, first layout spinner and recylerview get clicked and it shows on second layout.</p>

答:
You Should set Visibility as Gone.
So it Will not get any click

Answer :-
(Your layout / any view ).setVisibility("VIEW.GONE");


问:
Disabling a module in a program by not shipping the .dll
If you distribute a .net web application, and you want a certain module of the application to be disabled, AND you don't want to ship the source with it, is it a reasonable solution to just not include the necessary .dll for that module?

I know you can do things programatically, but as long as you don't ship the .dll things should be ok right?

Reason being some .dll's require you to sell the product commercially, and if I want to give it away for free or as a demo I am stuck.

答:
This will definitely break if you are using Web Site instead of Web Application Project, because the DLL reference must be in your web.config... which will throw an error when it's missing.

You could get away with it in a Web Application Project, but that's a pretty ugly method.  Much better to use some sort of plugin architecture, as others suggest.

OwnerDisplayName: Blankman

OwnerDisplayName: Bryan Parker


问:
backbone.js + JQuery: 'this' reference not accessible in JQuery-Event-Handler
I'm trying to use backbone.js in my webapp. I have a View which uses the JQuery draggable plugin to make a div draggable:

```<code>var ExampleView = Backbone.View.extend({
  events: {
    //...
  },

  initialize: function() {
    _.bindAll(this, "render");

    this.model.bind('change', this.render);
  },

  render: function() {
      // icanhaz
      this.el = ich.kinectdevtmpl();

      $(this.el).draggable({
         drag: function() {
                alert(this.model);

         }
      });

    return this;
  }
</code>```

});

But in the drag event handler I can't access 'this.model' because 'this' do not refer to the view anymore. So, how can I access my View in the JQuery event handler?

答:
this has changed and is no longer what you want.
you can assign this to a variable and use that instead.</p>

```<code>var that = this;
$(this.el).draggable({
   drag: function() {
          alert(that.model);

   }
});</code>```

Body:
I'm trying to use backbone.js in my webapp. I have a View which uses the JQuery draggable plugin to make a div draggable:

var ExampleView = Backbone.View.extend({
  events: {
    //...
  },

  initialize: function() {
    _.bindAll(this, "render");

    this.model.bind('change', this.render);
  },

  render: function() {
      // icanhaz
      this.el = ich.kinectdevtmpl();

      $(this.el).draggable({
         drag: function() {
                alert(this.model);

         }
      });

    return this;
  }

});

But in the drag event handler I can't access 'this.model' because 'this' do not refer to the view anymore. So, how can I access my View in the JQuery event handler?

Body:
this has changed and is no longer what you want.
you can assign this to a variable and use that instead.

var that = this;
$(this.el).draggable({
   drag: function() {
          alert(that.model);

   }
});


问:
Threadabortexception when calling showdialog in C#
I have an application that parses a large XML file and builds WPF UI controls based on that content. This task usually takes about 15 - 30 seconds. In order to inform the user about a running task, I display a simple intermediate progress dialog window, like:

Thread progressDialogThread = new Thread(() =>
{
    Window window = new Window
    {
        Content = new ProgressDialog(),
        Height = 100,
        Width = 150,
        WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen
    };
    window.ShowDialog();
});

progressDialogThread.SetApartmentState(ApartmentState.STA);
progressDialogThread.IsBackground = true;
progressDialogThread.Start();

buildUI();

progressDialogThread.Abort();
```

<p>This works, but I sometimes get a ThreadAbortException on <code>progressDialogThread.Start()</code>, when the XML should be parsed once again.</p>

<p>Does anyone know a better approach to "close" the progress dialog? </p>

<p>Since the controls have to be built on the main UI thread, I can not use the backgroundworker...</p>

<p>The progress dialog itself in XAML looks like:</p>

<pre class="lang-xml prettyprint-override"><code><UserControl x:Class="MyDialog.ProgressDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyDialog"
        mc:Ignorable="d"
        Background="{DynamicResource MaterialDesignPaper}"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        Height="100" Width="150">
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <Label HorizontalAlignment="Center">Please wait</Label>
        <ProgressBar
          Style="{StaticResource MaterialDesignCircularProgressBar}"
          Value="0"
          IsIndeterminate="True" Width="40" Height="41" Margin="55,0" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </StackPanel>
</UserControl>
</code>```

答: Things like this are exactly what BackgroundWorker is for, and why it knows the difference between the UI thread and the work thread. Use a background worker, parse your XML file in the DoWork event handler (it will run on the background thread) and regularly report progress using the ReportProgress method while proceeding through DoWork's loop. The ProgressChanged handler code will execute on the UI thread, and it should poke the progress dialog to provide a status update on the process</p>

Body:
I have an application that parses a large XML file and builds WPF UI controls based on that content. This task usually takes about 15 - 30 seconds. In order to inform the user about a running task, I display a simple intermediate progress dialog window, like:

Thread progressDialogThread = new Thread(() =>
{
    Window window = new Window
    {
        Content = new ProgressDialog(),
        Height = 100,
        Width = 150,
        WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen
    };
    window.ShowDialog();
});

progressDialogThread.SetApartmentState(ApartmentState.STA);
progressDialogThread.IsBackground = true;
progressDialogThread.Start();

buildUI();

progressDialogThread.Abort();

This works, but I sometimes get a ThreadAbortException on progressDialogThread.Start(), when the XML should be parsed once again.

Does anyone know a better approach to "close" the progress dialog?

Since the controls have to be built on the main UI thread, I can not use the backgroundworker...

The progress dialog itself in XAML looks like:

<UserControl x:Class="MyDialog.ProgressDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyDialog"
        mc:Ignorable="d"
        Background="{DynamicResource MaterialDesignPaper}"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        Height="100" Width="150">
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        Please wait
        <ProgressBar
          Style="{StaticResource MaterialDesignCircularProgressBar}"
          Value="0"
          IsIndeterminate="True" Width="40" Height="41" Margin="55,0" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </StackPanel>
</UserControl>


问:
Bootstrap progress bar issue in react component
Except Bootstrap Progress Bar All Bootstrap components working in React Component</p>

```<code>    class Demo extends Component {
      render() {
        return (
              <div>
                <div className="profile_record">
                  <h5 className="progress-label"><strong>PROFILE COMPLETENESS</strong></h5>
                  <div className="progress">
                    <div className="progress-bar" role="progressbar" style={{width: "25%"}} aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">25%</div>
                  </div>
                </div>
              </div>
            )
           }
         }
</code>```

答:
Starting from Sep, 2018, you can use the Bootstrap ProgressBar, credits goes here BootStrap ProgressBar

```<code>import { ProgressBar } from "react-bootstrap";

<div>
  <ProgressBar variant="success" now={40} />
  <ProgressBar variant="info" now={20} />
  <ProgressBar variant="warning" now={60} />
  <ProgressBar variant="danger" now={80} />
</div>
</code>```

Body:
Except Bootstrap Progress Bar All Bootstrap components working in React Component

    class Demo extends Component {
      render() {
        return (

PROFILE COMPLETENESS

25%

            )
           }
         }

Body:
Starting from Sep, 2018, you can use the Bootstrap ProgressBar, credits goes here BootStrap ProgressBar

import { ProgressBar } from "react-bootstrap";

<div>
  <ProgressBar variant="success" now={40} />
  <ProgressBar variant="info" now={20} />
  <ProgressBar variant="warning" now={60} />
  <ProgressBar variant="danger" now={80} />
</div>


问:
How can update attributes for existing registered user in Hyperledger Fabric?
I registered one user with some attributes using ABAC features with Node.js SDK but after some operation, I want to update its attributes, is it possible to update?

I found how can we modify existing identity attributes using command but how can I do with Node.js SDK?

Here is the link:
http://hyperledger-fabric-ca.readthedocs.io/en/latest/users-guide.html#modifying-an-identity

Please help how can I do this with Node.js SDK.

答: It is possible through using IdentityService. You can easily change attributes by update method. The code is provided here. https://jira.hyperledger.org/browse/FABN-572?focusedCommentId=46030&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-46030</p>


问:
Solving T(n) = 9T(n / 10) + log^3 n?
I have the recurrence

T(n) = 9T(n/10) + log3 n

and I'm trying to find its complexity .

After i-substitutions I can see that

T(i) = 9T(n / 10i+1) + log3(n / 10i).

I don't know how to continue, however. How do I solve this recurrence?

答:
use master method to solve the problem

It solves the recurrences of form T(n) = aT(n/b) + f(n).

Master Method is a direct way to get the solution. The master method works only for following type of recurrences or for recurrences that can be transformed to following type.

T(n) = aT(n/b) + f(n) where a >= 1 and b > 1
There are following three cases:
1. If f(n) = Θ(nc) where c < Logba then T(n) = Θ(nLogba)

If f(n) = Θ(nc) where c = Logba then T(n) = Θ(ncLog n)

3.If f(n) = Θ(nc) where c > Logba then T(n) = Θ(f(n))

.it is used to solve recurrences in functions like T(n) = aT(n/b) + f(n) where a >= 1 and b > 1
same as yours

Title: Solving T(n) = 9T(n / 10) + log^3 n?


问:
What command is needed to clear the terminal in cern's root?
I have just started using cern's ROOT and couldn't find a command to clear the terminal. The beginner's manual and the user guide don't seem to mention anything about a command similar to clear in bash.

To be clear, what needs to be typed after root[number] prompt so that the console screen clears out and root keeps running?

答:
Thanks to @MaryChang

.!clear

P.S.: .!cls for windows; just clear or cls on root prompt doesn't work (as of ROOT ver 6.16/00)


问:
Conversion of datetime to varchar not working when passing through variables
I came across this weird problem where I need to convert datetime to varchar.

I ran these 2 queries:

```<code>declare @d datetime
set @d ='31/12/2019 16:12:25.317'

select @d

select convert(varchar(50), '31/12/2019 16:12:25.317', 101)
</code>```

The first query throws an error:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

The second query works fine.

答:
If I guess correct, you are looking for 103 date time format (British/French) which is DD/MM/YYYY. That case you can try this below-</p>

```<code>DECLARE @d DATETIME
SET @d =CONVERT(DATETIME, '31/12/2019 16:12:25.317',103)

SELECT @d

SELECT CONVERT(DATETIME, '31/12/2019 16:12:25.317', 103)
</code>```

Body:
I came across this weird problem where I need to convert datetime to varchar.

I ran these 2 queries:

declare @d datetime
set @d ='31/12/2019 16:12:25.317'

select @d

select convert(varchar(50), '31/12/2019 16:12:25.317', 101)

The first query throws an error:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

The second query works fine.

Body:
If I guess correct, you are looking for 103 date time format (British/French) which is DD/MM/YYYY. That case you can try this below-

DECLARE @d DATETIME
SET @d =CONVERT(DATETIME, '31/12/2019 16:12:25.317',103)

SELECT @d

SELECT CONVERT(DATETIME, '31/12/2019 16:12:25.317', 103)


问:
Matplotlib: How to plot heatmap based on values
I need to plot a heatmap based on values in a file. The structure of the file is as follows:

```<code>,  c1 ,  c2  , ... , cN
-- --    --          --
c1, 1 , 0.24 , ... , 0.37
c2,0.29,  1  , ... , 0.31
...
...
...
cN,0.42, 0.27, ... ,  1
</code>```

I need the output in the form of a heatmap where the labels along both the x-axis and the y-axis are c1,c2,...,cN.

These values are not correlation values, but rather the intersection values in the range of 0 to 1. Hence, I am unable to use the corr() method. The examples I have seen online usually deal with heat maps of the correlation matrix, or the file is structured in a different way.

答:
Here is my attempt with some fake data and assuming that value in each cell can be used as is and does not require more processing.

import seaborn as sns
```

<p>Create fake data</p>

<pre class="lang-py prettyprint-override"><code>data = """
,  c1 ,  c2  , cN
-- --    --    --
c1, 1 , 0.24 , 0.37
c2,0.29,  1  , 0.31
cN,0.42, 0.27, 1
"""
with open("temp.txt", "wt") as f:
    f.write(data)
</code>```

Use pandas to read data in and excluding the line with '--' in it.

data = pd.read_csv("temp.txt",index_col=0, skiprows=[2])
```

<p>Use <code>seaborn.heatmap</code> to create a heat map with proper labels.</p>

```sns.heatmap(data)
```

I get the following output.

Hope this is what you have in mind.

Body:
I need to plot a heatmap based on values in a file. The structure of the file is as follows:

,  c1 ,  c2  , ... , cN
-- --    --          --
c1, 1 , 0.24 , ... , 0.37
c2,0.29,  1  , ... , 0.31
...
...
...
cN,0.42, 0.27, ... ,  1

I need the output in the form of a heatmap where the labels along both the x-axis and the y-axis are c1,c2,...,cN.

These values are not correlation values, but rather the intersection values in the range of 0 to 1. Hence, I am unable to use the corr() method. The examples I have seen online usually deal with heat maps of the correlation matrix, or the file is structured in a different way.

Body:
Here is my attempt with some fake data and assuming that value in each cell can be used as is and does not require more processing.

import seaborn as sns

Create fake data

data = """
,  c1 ,  c2  , cN
-- --    --    --
c1, 1 , 0.24 , 0.37
c2,0.29,  1  , 0.31
cN,0.42, 0.27, 1
"""
with open("temp.txt", "wt") as f:
    f.write(data)

Use pandas to read data in and excluding the line with '--' in it.

data = pd.read_csv("temp.txt",index_col=0, skiprows=[2])

Use seaborn.heatmap to create a heat map with proper labels.

sns.heatmap(data)

I get the following output.

Hope this is what you have in mind.


问:
Using ternary for if else
I’m having this if-else condition..

```<code>if UIDevice.current.iPad {
    if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
        theImage.contentMode = .scaleAspectFill
    } else {
        theImage.contentMode = .scaleToFill
    }
} else {
    theImage.contentMode = .scaleAspectFill
}
</code>```

How can I use a ternary operator instead of this if-else condition..

I referred this link..but it didn’t help

答:
For the inside if:

```<code>if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
   theImage.contentMode = .scaleAspectFill
} else {
   theImage.contentMode = .scaleToFill
}
</code>```

Gives:

```<code>theImage.contentMode = (APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) ? . scaleAspectFill : . scaleToFill
</code>```

Now, if we do the top level if:

```<code>theImage.contentMode = UIDevice.current.iPad ? insideIf : . scaleAspectFill
</code>```

In full code:

```<code>theImage.contentMode = UIDevice.current.iPad ? (APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) ? . scaleAspectFill
                                                                                : . scaleToFill
                                             : . scaleAspectFill
</code>```

That's not really redable.

But

```<code>if UIDevice.current.iPad {
    if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
        theImage.contentMode = .scaleAspectFill
    } else {
        theImage.contentMode = .scaleToFill
    }
} else {
    theImage.contentMode = .scaleAspectFill
}
</code>```

Might be transformed into:

```<code>if UIDevice.current.iPad && !(APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) {
    theImage.contentMode = .scaleToFill
} else {
    theImage.contentMode = .scaleAspectFill
}
</code>```

That's shorter, but might be harder to read.

With ternary if:

```<code>theImage.contentMode = UIDevice.current.iPad && !(APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) ? . scaleToFill : . scaleAspectFill
</code>```

In my opinion? Keep your version (or maybe the version where I use only one if/else). Compiler will optimise nevertheless, and it's easier to fix/modify it two months later if you can grasp why and what it does quickly.

Title: Using ternary for if else

Body:
I’m having this if-else condition..

if UIDevice.current.iPad {
    if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
        theImage.contentMode = .scaleAspectFill
    } else {
        theImage.contentMode = .scaleToFill
    }
} else {
    theImage.contentMode = .scaleAspectFill
}

How can I use a ternary operator instead of this if-else condition..

I referred this link..but it didn’t help

Body:
For the inside if:

if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
   theImage.contentMode = .scaleAspectFill
} else {
   theImage.contentMode = .scaleToFill
}

Gives:

theImage.contentMode = (APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) ? . scaleAspectFill : . scaleToFill

Now, if we do the top level if:

theImage.contentMode = UIDevice.current.iPad ? insideIf : . scaleAspectFill

In full code:

theImage.contentMode = UIDevice.current.iPad ? (APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) ? . scaleAspectFill
                                                                                : . scaleToFill
                                             : . scaleAspectFill

That's not really redable.

But

if UIDevice.current.iPad {
    if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
        theImage.contentMode = .scaleAspectFill
    } else {
        theImage.contentMode = .scaleToFill
    }
} else {
    theImage.contentMode = .scaleAspectFill
}

Might be transformed into:

if UIDevice.current.iPad && !(APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) {
    theImage.contentMode = .scaleToFill
} else {
    theImage.contentMode = .scaleAspectFill
}

That's shorter, but might be harder to read.

With ternary if:

theImage.contentMode = UIDevice.current.iPad && !(APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc) ? . scaleToFill : . scaleAspectFill

In my opinion? Keep your version (or maybe the version where I use only one if/else). Compiler will optimise nevertheless, and it's easier to fix/modify it two months later if you can grasp why and what it does quickly.


问:
Vue js 2 list rendering issue
I have faced an issue when doing a simple shopping cart app in vue js 2
Here is the code I have:

blank cart item array for when I press add to cart button then that particular product will be pushed in this array.

```<code>data () {
    return {
      cartItems: []
    }
}
</code>```

add to cart method:

```<code>methods: {
    addToCart (product) {
      product.quantity += 1
      this.cartItems.push(product)
    }
}
</code>```

Template view:

```<code><ul>
   <li v-for="item in items">
        ```
            {{item.name}} -- {{item.quantity}}
        ```
    </li>
</ul>
</code>```

in the browser, I got this:

note: right side 1 and 2 value is the quantity of that product
but I want something like this.

note: right side 1 and 2 value is the quantity of that product

If I use vue js 1 instead of vue js 2 then same code gives me browser view like 2nd screenshot I attached.

Please, anybody, help me to solve this.

答: that is because you increment number of product and again after that you  push same product to list . you should check if that item is in the list or not</p>

Title: Vue js 2 list rendering issue

Body:
I have faced an issue when doing a simple shopping cart app in vue js 2
Here is the code I have:

blank cart item array for when I press add to cart button then that particular product will be pushed in this array.

data () {
    return {
      cartItems: []
    }
}

add to cart method:

methods: {
    addToCart (product) {
      product.quantity += 1
      this.cartItems.push(product)
    }
}

Template view:

            {{item.name}} -- {{item.quantity}}

in the browser, I got this:

note: right side 1 and 2 value is the quantity of that product
but I want something like this.

note: right side 1 and 2 value is the quantity of that product

If I use vue js 1 instead of vue js 2 then same code gives me browser view like 2nd screenshot I attached.

Please, anybody, help me to solve this.


问:
How to revert word object references in vba to earlier project library?
There is a section of code I have written where a label merge is executed via Excel VBA. My client (2010) has an earlier version of Excel than me (2013) and is unable to execute that section due to having Word object references v 14 and me 15.

I believe the issue lies in early vs late binding? I have been trying to make the code work without the 15 reference checked in VBA, but no matter what variation of code I know possible, it still debugs when I try to save something that was previously declared an object. Im pretty sure that has something to do with it also. In the code, 3 seperate label templates are used to produce 3 label documents. There's no issue calling and closing the template, it's declared directly as its workbook path. The issue comes when the output of the merge, "wd" which I've set as an object, is attempted to be saved.

```<code>Sub RunMerge()
    ' Word constants

    Dim wd As Object
    Dim wdocSource As Object
    Dim wks As Worksheet
    Dim Worksheets
    Dim strWorkbookName As String

    On Error Resume Next
    Set wd = GetObject(, "Word.Application")
    If wd Is Nothing Then
        Set wd = CreateObject("Word.Application")
    End If
    On Error GoTo 0

    Set Worksheets = ActiveWorkbook.Sheets
    Set wks = ActiveSheet
    With ActiveWorkbook
        For Each wks In Worksheets

            Set wdocSource = wd.Documents.Open(ThisWorkbook.Path & "\Label Templates\PRODUCT Label Template_" & wks.Name & ".docx")

            strWorkbookName = ThisWorkbook.Path & "\Order Output\Order_Output_ " & Format(Date, "dd.mm.yyyy") & ".xlsx"

            wdocSource.MailMerge.MainDocumentType = wdFormLabels

            wdocSource.MailMerge.OpenDataSource _
                Name:=strWorkbookName, _
                AddToRecentFiles:=False, _
                Revert:=False, _
                Format:=wdOpenFormatAuto, _
                Connection:="Data Source=" & strWorkbookName, _
                SQLStatement:="SELECT * FROM [" & wks.Name & "$]"

            With wdocSource.MailMerge
                .Destination = wdSendToNewDocument
                .SuppressBlankLines = True
                 With .DataSource
                     .FirstRecord = wdDefaultFirstRecord
                     .LastRecord = wdDefaultLastRecord
                 End With
                 .Execute Pause:=False
            End With

            wd.SaveAs2 (ThisWorkbook.Path & "\Label Output\Label Output_" & wks.Name & "_" & Format(Date, "dd.mm.yyyy") & ".docx")
            wdocSource.Close SaveChanges:=False

        Next wks
    End With

    wd.Visible = True
    Set wdocSource = Nothing
    Set wd = Nothing
    Set wks = Nothing
    Set Worksheets = Nothing
End Sub
</code>```

As soon as it hits wd.SaveAs2 there is an object reference error thrown, and if I change it there to ActiveDocument, or document or word.something or Dim it, Set it, put it in an end/with as an object, nothing works!!

答: Your code is basically set up for use with late binding, but you've violated the late-binding principles by referring to built-in Word constants - and that necessitates the Word object library reference. Delete the Word object library reference and amend you code to be fully-workable with late binding (e.g. replace the built-in Word constants with their numeric values).</p>

Body:
There is a section of code I have written where a label merge is executed via Excel VBA. My client (2010) has an earlier version of Excel than me (2013) and is unable to execute that section due to having Word object references v 14 and me 15.

I believe the issue lies in early vs late binding? I have been trying to make the code work without the 15 reference checked in VBA, but no matter what variation of code I know possible, it still debugs when I try to save something that was previously declared an object. Im pretty sure that has something to do with it also. In the code, 3 seperate label templates are used to produce 3 label documents. There's no issue calling and closing the template, it's declared directly as its workbook path. The issue comes when the output of the merge, "wd" which I've set as an object, is attempted to be saved.

Sub RunMerge()
    ' Word constants

    Dim wd As Object
    Dim wdocSource As Object
    Dim wks As Worksheet
    Dim Worksheets
    Dim strWorkbookName As String

    On Error Resume Next
    Set wd = GetObject(, "Word.Application")
    If wd Is Nothing Then
        Set wd = CreateObject("Word.Application")
    End If
    On Error GoTo 0

    Set Worksheets = ActiveWorkbook.Sheets
    Set wks = ActiveSheet
    With ActiveWorkbook
        For Each wks In Worksheets

            Set wdocSource = wd.Documents.Open(ThisWorkbook.Path & "\Label Templates\PRODUCT Label Template_" & wks.Name & ".docx")

            strWorkbookName = ThisWorkbook.Path & "\Order Output\Order_Output_ " & Format(Date, "dd.mm.yyyy") & ".xlsx"

            wdocSource.MailMerge.MainDocumentType = wdFormLabels

            wdocSource.MailMerge.OpenDataSource _
                Name:=strWorkbookName, _
                AddToRecentFiles:=False, _
                Revert:=False, _
                Format:=wdOpenFormatAuto, _
                Connection:="Data Source=" & strWorkbookName, _
                SQLStatement:="SELECT * FROM [" & wks.Name & "$]"

            With wdocSource.MailMerge
                .Destination = wdSendToNewDocument
                .SuppressBlankLines = True
                 With .DataSource
                     .FirstRecord = wdDefaultFirstRecord
                     .LastRecord = wdDefaultLastRecord
                 End With
                 .Execute Pause:=False
            End With

            wd.SaveAs2 (ThisWorkbook.Path & "\Label Output\Label Output_" & wks.Name & "_" & Format(Date, "dd.mm.yyyy") & ".docx")
            wdocSource.Close SaveChanges:=False

        Next wks
    End With

    wd.Visible = True
    Set wdocSource = Nothing
    Set wd = Nothing
    Set wks = Nothing
    Set Worksheets = Nothing
End Sub

As soon as it hits wd.SaveAs2 there is an object reference error thrown, and if I change it there to ActiveDocument, or document or word.something or Dim it, Set it, put it in an end/with as an object, nothing works!!


问:
Moving a control by dragging it with the mouse in C#
I'm trying to move the control named pictureBox1 by dragging it around. The problem is, when it moves, it keeps moving from a location to another location around the mouse, but it does follow it...
This is my code. and I would really appreciate it if you could help me</p>

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    bool selected = false;
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        selected = true;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (selected == true)
        {
            pictureBox1.Location = e.Location;
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        selected = false;
    }

}
</code>```

答:
You can also use the extension:

```<code>public static class CmponentsExtensions
{
  //Management of mouse drag and drop
    #region Menu and Mouse
    private static bool mouseDown;
    private static Point lastLocation;

    /// <summary>
    /// To enable control to be moved around with mouse
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="control"></param>
    public static void moveItselfWithMouse<T>(this T control) where T: Control
    {
        control.MouseDown += (o, e)=> { mouseDown = true; lastLocation = e.Location; };
        control.MouseMove += (o, e) =>
        {
            if (mouseDown)
            {
                control.Location = new Point((control.Location.X - lastLocation.X) + e.X, (control.Location.Y - lastLocation.Y) + e.Y);
                control.Update();
            }
        };
        control.MouseUp += (o, e) => { mouseDown = false; } ;
    }

    public static void moveOtherWithMouse<T>(this T control, Control movedObject) where T : Control
    {
        control.MouseDown += (o, e) => { mouseDown = true; lastLocation = e.Location; };
        control.MouseMove += (o, e) =>
        {
            if (mouseDown)
            {
                movedObject.Location = new Point((movedObject.Location.X - lastLocation.X) + e.X, (movedObject.Location.Y - lastLocation.Y) + e.Y);
                movedObject.Update();
            }
        };
        control.MouseUp += (o, e) => { mouseDown = false; };
    }

    #endregion
}
</code>```

Then you need to use it with some control:

In this case pictureBox1 moved the whole Form

```<code>pictureBox1.moveOtherWithMouse(this);
</code>```

In this case you move only pictureBox:

```<code>pictureBox1.moveItselfWithMouse();
</code>```

Body:
I'm trying to move the control named pictureBox1 by dragging it around. The problem is, when it moves, it keeps moving from a location to another location around the mouse, but it does follow it...
This is my code. and I would really appreciate it if you could help me

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    bool selected = false;
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        selected = true;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (selected == true)
        {
            pictureBox1.Location = e.Location;
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        selected = false;
    }

}

Body:
You can also use the extension:

public static class CmponentsExtensions
{
  //Management of mouse drag and drop
    #region Menu and Mouse
    private static bool mouseDown;
    private static Point lastLocation;

    /// <summary>
    /// To enable control to be moved around with mouse
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="control"></param>
    public static void moveItselfWithMouse<T>(this T control) where T: Control
    {
        control.MouseDown += (o, e)=> { mouseDown = true; lastLocation = e.Location; };
        control.MouseMove += (o, e) =>
        {
            if (mouseDown)
            {
                control.Location = new Point((control.Location.X - lastLocation.X) + e.X, (control.Location.Y - lastLocation.Y) + e.Y);
                control.Update();
            }
        };
        control.MouseUp += (o, e) => { mouseDown = false; } ;
    }

    public static void moveOtherWithMouse<T>(this T control, Control movedObject) where T : Control
    {
        control.MouseDown += (o, e) => { mouseDown = true; lastLocation = e.Location; };
        control.MouseMove += (o, e) =>
        {
            if (mouseDown)
            {
                movedObject.Location = new Point((movedObject.Location.X - lastLocation.X) + e.X, (movedObject.Location.Y - lastLocation.Y) + e.Y);
                movedObject.Update();
            }
        };
        control.MouseUp += (o, e) => { mouseDown = false; };
    }

    #endregion
}

Then you need to use it with some control:

In this case pictureBox1 moved the whole Form

pictureBox1.moveOtherWithMouse(this);

In this case you move only pictureBox:

pictureBox1.moveItselfWithMouse();


问:
expected assignment or function call: no-unused-expressions ReactJS
```<code>class Game extends Component
{
  constructor()
  {
    super()
    this.state = {
      speed: 0
    }
    //firebaseInit()
  }
  render()
  {
    return
    (
      <div>
        <h1>The Score is {this.state.speed};</h1>
      </div>
    )
  }
}

export default Game;
</code>```

I am new to React and for this code its giving this error

```<code>Expected an assignment or function call and instead saw an expression  no-unused-expressions
</code>```

Dont understand where getting wrong, please help

答:
```<code>import React from 'react';

class Counter extends React.Component{
    state = {
        count: 0,
    };

    formatCount() {
        const {count} = this.state;
        // use a return statement here, it is a importent,
        return count === 0 ? 'Zero' : count;
    }
    render() {
        return(
          <React.Fragment>
              <span>{this.formatCount()}</span>
              <button type="button" className="btn btn-primary">Increment</button>
          </React.Fragment>
        );
    }
}

export default Counter;
</code>```

Body:
class Game extends Component
{
  constructor()
  {
    super()
    this.state = {
      speed: 0
    }
    //firebaseInit()
  }
  render()
  {
    return
    (

The Score is {this.state.speed};

    )
  }
}

export default Game;

I am new to React and for this code its giving this error

Expected an assignment or function call and instead saw an expression  no-unused-expressions

Dont understand where getting wrong, please help


问:
how to scrape multilevel drop down list using selenium python [dependent selection]
i want to extract some data from a multilevel selection dependent drop down menu can any one tell me how can i select and click items using selenium so sub drop downs may be updated automatically!

you can visit the source for reference or run the code to see the output once clicked it never selects item.

i have written several codes here is one of them!

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import csv
import time

//#from selenium.webdriver.support import Select

print ("opening chorome....")
driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(10)

csvData = ['Year', 'Make', 'Model', 'Body', 'Submodel', 'Size']

Yindex = Mkindex = Mdindex = Bindex = Smindex = Sindex = 0
print ("waiting for program to set variables....")
time.sleep(10)

print ("initializing and setting variables....")

Year = Select(driver.find_element_by_id("icm-years-select"))
for year in driver.find_elements(By.XPATH, '//*[@id="icm-years-select"]'):
    Year.select_by_index(++Yindex)
    year.click()
    time.sleep(1)
    Make = Select(driver.find_element_by_id("icm-makes-select"))
    for make in driver.find_elements(By.XPATH, '//*[@id="icm-makes-select"]'):
        Make.select_by_index(++Mkindex)
        make.click()
        time.sleep(1)
        Model = Select(driver.find_element_by_id("icm-models-select"))
        for model in driver.find_elements(By.XPATH, '//*[@id="icm-models-select"]'):
            Model.select_by_index(++Mdindex)
            model.click()
            time.sleep(1)
            Body = Select(driver.find_element_by_id("icm-drivebodies-select"))
            for body in driver.find_elements(By.XPATH, '//*[@id="icm-drivebodies-select"]'):
                Body.select_by_index(++Bindex)
                body.click()
                time.sleep(1)
                Submodel = Select(driver.find_element_by_id("icm-submodels-select"))
                for subm in driver.find_elements(By.XPATH, '//*[@id="icm-submodels-select"]'):
                    Submodel.select_by_index(++Smindex)
                    subm.click()
                    time.sleep(1)
                    Size = Select(driver.find_element_by_id("icm-sizes-select"))
                    for size in driver.find_elements(By.XPATH, '//*[@id="icm-sizes-select"]'):
                        Size.select_by_index(++Sindex)
                        csvData.append([year.text, make.text, model.text, body.text, subm.text, size.text])
</code>```

答:
Try this:

Select multilevel dependent drop-down menu option

```<code>selectYear = Select(driver.find_element_by_id("icm-years-select"))

for yearOption in selectYear.options:
    yearText = yearOption.text
    selectYear.select_by_visible_text(yearText)
    time.sleep(1)

    selectMakes = Select(driver.find_element_by_id("icm-makes-select"))

    for makesOption in selectMakes.options:
        makesText = makesOption.text
        selectMakes.select_by_visible_text(makesText)
        time.sleep(1)
        selectModel = Select(driver.find_element_by_id("icm-models-select"))

        for modelOption in selectModel.options:
            modelText = modelOption.text
            selectModel.select_by_visible_text(modelText)
</code>```

See more

Body:
i want to extract some data from a multilevel selection dependent drop down menu can any one tell me how can i select and click items using selenium so sub drop downs may be updated automatically!

you can visit the source for reference or run the code to see the output once clicked it never selects item.

i have written several codes here is one of them!

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import csv
import time

//#from selenium.webdriver.support import Select

print ("opening chorome....")
driver = webdriver.Chrome()
driver.get('https://www.wheelmax.com/')
time.sleep(10)

csvData = ['Year', 'Make', 'Model', 'Body', 'Submodel', 'Size']

Yindex = Mkindex = Mdindex = Bindex = Smindex = Sindex = 0
print ("waiting for program to set variables....")
time.sleep(10)

print ("initializing and setting variables....")

Year = Select(driver.find_element_by_id("icm-years-select"))
for year in driver.find_elements(By.XPATH, '//*[@id="icm-years-select"]'):
    Year.select_by_index(++Yindex)
    year.click()
    time.sleep(1)
    Make = Select(driver.find_element_by_id("icm-makes-select"))
    for make in driver.find_elements(By.XPATH, '//*[@id="icm-makes-select"]'):
        Make.select_by_index(++Mkindex)
        make.click()
        time.sleep(1)
        Model = Select(driver.find_element_by_id("icm-models-select"))
        for model in driver.find_elements(By.XPATH, '//*[@id="icm-models-select"]'):
            Model.select_by_index(++Mdindex)
            model.click()
            time.sleep(1)
            Body = Select(driver.find_element_by_id("icm-drivebodies-select"))
            for body in driver.find_elements(By.XPATH, '//*[@id="icm-drivebodies-select"]'):
                Body.select_by_index(++Bindex)
                body.click()
                time.sleep(1)
                Submodel = Select(driver.find_element_by_id("icm-submodels-select"))
                for subm in driver.find_elements(By.XPATH, '//*[@id="icm-submodels-select"]'):
                    Submodel.select_by_index(++Smindex)
                    subm.click()
                    time.sleep(1)
                    Size = Select(driver.find_element_by_id("icm-sizes-select"))
                    for size in driver.find_elements(By.XPATH, '//*[@id="icm-sizes-select"]'):
                        Size.select_by_index(++Sindex)
                        csvData.append([year.text, make.text, model.text, body.text, subm.text, size.text])

Body:
Try this:

Select multilevel dependent drop-down menu option

selectYear = Select(driver.find_element_by_id("icm-years-select"))

for yearOption in selectYear.options:
    yearText = yearOption.text
    selectYear.select_by_visible_text(yearText)
    time.sleep(1)

    selectMakes = Select(driver.find_element_by_id("icm-makes-select"))

    for makesOption in selectMakes.options:
        makesText = makesOption.text
        selectMakes.select_by_visible_text(makesText)
        time.sleep(1)
        selectModel = Select(driver.find_element_by_id("icm-models-select"))

        for modelOption in selectModel.options:
            modelText = modelOption.text
            selectModel.select_by_visible_text(modelText)

See more


问:
How to change the input language in C# code?
I am writting a wpf application using C# (VS2010) and when my application runs , the input language is taken from the system input language which is English.

I want my application to change the input language automatically without having to press (Shift + Alt)

Can you tell me how to do that please?

Another question, can I change the timezone in my system using my application too?

答:
First add

```<code>using System.Globalization;
</code>```

Then write after InitializeComponent(); this code

```<code>        InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(Application.CurrentCulture);
        InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("ar-EG"));
</code>```

Body:
First add

using System.Globalization;

Then write after InitializeComponent(); this code

        InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(Application.CurrentCulture);
        InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("ar-EG"));


问:
TNonblockingServerTransport not implemented with Thrift C# library
When using Apache Thrift [https://github.com/apache/thrift] to create a non blocking server in C#, the following Classes/Types cannot be recognized:

```<code>TNonblockingServerTransport
TNonblockingServer
</code>```

I want to send command from my win10 laptop to control a time-consuming calculation performed on a high performance server (ubuntu). That's why I came to Apache Thrift. I have found the official C# version tutorial [https://github.com/apache/thrift/tree/master/tutorial/csharp] and it works well. This tutorial uses the so-called Blocking Mode (TSimpleServer). But in my situation, the time-consuming calculation procedure should be interrupt-able. Consequently, I must use a non-blocking server.

The logic is simple. For the server, I used a private flag forceStop. If the Client call Stop(), forceStop will set to true and the calculation loop will break.

```<code>        // #Server#
        // Server Set-Up
        private void SetUp()
        {
         try
            {
                CalculatorHandler handler = new CalculatorHandler();
                Calculator.Processor processor = new
                Calculator.Processor(handler);
                var serverTransport = new TServerSocket(9090);
                TServer server = new TSimpleServer(processor, serverTransport);

                // Use this for a multithreaded server
                // server = new TThreadPoolServer(processor, serverTransport);

                Console.WriteLine("Starting the server...");
                server.Serve();
            }
            catch (Exception x)
            {
                Console.WriteLine(x.StackTrace);
            }
        }

        private bool forceStop;
        public int TimeConsumingOperation(int n1, int n2)
        {
            Console.WriteLine("add({0},{1})", n1, n2);
            for (int i = 0; i < 10; i++)
            {
                //calculating
                Thread.Sleep(500);

                if (forceStop)
                {
                    Quit();
                }
            }
            return n1 + n2;
        }

        public void Stop()
        {
            forceStop = true;
        }
</code>```

```<code>// Client

// Button#1 Click callback
private void Button_Start_Click()
{
    client.TimeConsumingOperation(0,0);
}

// Button#2 Click callback
private void Button_Stop_Click()
{
    client.Stop();
}
//
</code>```

I've found some useful examples in java [https://chamibuddhika.wordpress.com/2011/10/02/apache-thrift-quickstart-tutorial/]. I've try my best to convert the java code of non-block server to the corresponding C# code but I found that there seems to be no TNonblockingServerTransport in C#. Anyone could help me with this probelm?

// Java Code
public class NonblockingServer {

    private void start() {
        try {
            TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(7911);
            ArithmeticService.Processor processor = new ArithmeticService.Processor(new ArithmeticServiceImpl());

            TServer server = new TNonblockingServer(new TNonblockingServer.Args(serverTransport).
                    processor(processor));
            System.out.println("Starting server on port 7911 ...");
            server.serve();
        } catch (TTransportException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        NonblockingServer srv = new NonblockingServer();
        srv.start();
    }
}
```

答:
There's actually two answers to that question.

Possible implementation

Your setup is flawed, to begin with.

```<code>    // #Server#
    // Server Set-Up

    private bool forceStop;

    public void Stop()
    {
        forceStop = true;
    }
</code>```

Let's assume, we have two clients, both starting a new calculation. Now one client wants to abort. What happens?

The solution would be to structure it in a way where the calculation is a separate business logic object that is instantiated at TimeConsumingOperation() and made available to the client by some means, typically by returning some sort of ID.

When the client now wants to abort, it calls Stop(calcualtionID). The server side logic now routes that call to the implementation and triggers whatever the abort mechanism might be, with C# is is probably a CancellationToken.

A third call would be needed to query the final results from the server end once the calculation has finished. Note that we still work with a TSimpleServer and the reason it works is because we avoid blocking calls by means of the API design.

Nonblocking server

Yes, there is no implementation yet for C#. Since Thrift is Open Source, that probably simply means that there were nobody running into that use case so far and wanted to spend time on an implementation. That is not to say that such a use case may not exist.

What exists are

Threaded and Threadpool servers

Task.Run(() => { your code })

which may help to solve your use case. Also, when used with ASP.NET there is no need for a nonblocking server since the runtime offers enough support already for multiple connections.

Bottom line

There are certain ways to work around that limitation you experierenced. One additional alternative could be to become a contributor by porting one of the existing (e.g. Java) nonblocking implementation to NetStd (preferred, since C# and NetCore will mature into "deprecated" state with the next release and both be replaced by NetStd eventually)

Body:
When using Apache Thrift [https://github.com/apache/thrift] to create a non blocking server in C#, the following Classes/Types cannot be recognized:

TNonblockingServerTransport
TNonblockingServer

I want to send command from my win10 laptop to control a time-consuming calculation performed on a high performance server (ubuntu). That's why I came to Apache Thrift. I have found the official C# version tutorial [https://github.com/apache/thrift/tree/master/tutorial/csharp] and it works well. This tutorial uses the so-called Blocking Mode (TSimpleServer). But in my situation, the time-consuming calculation procedure should be interrupt-able. Consequently, I must use a non-blocking server.

The logic is simple. For the server, I used a private flag forceStop. If the Client call Stop(), forceStop will set to true and the calculation loop will break.

        // #Server#
        // Server Set-Up
        private void SetUp()
        {
         try
            {
                CalculatorHandler handler = new CalculatorHandler();
                Calculator.Processor processor = new
                Calculator.Processor(handler);
                var serverTransport = new TServerSocket(9090);
                TServer server = new TSimpleServer(processor, serverTransport);

                // Use this for a multithreaded server
                // server = new TThreadPoolServer(processor, serverTransport);

                Console.WriteLine("Starting the server...");
                server.Serve();
            }
            catch (Exception x)
            {
                Console.WriteLine(x.StackTrace);
            }
        }

        private bool forceStop;
        public int TimeConsumingOperation(int n1, int n2)
        {
            Console.WriteLine("add({0},{1})", n1, n2);
            for (int i = 0; i < 10; i++)
            {
                //calculating
                Thread.Sleep(500);

                if (forceStop)
                {
                    Quit();
                }
            }
            return n1 + n2;
        }

        public void Stop()
        {
            forceStop = true;
        }

// Client

// Button#1 Click callback
private void Button_Start_Click()
{
    client.TimeConsumingOperation(0,0);
}

// Button#2 Click callback
private void Button_Stop_Click()
{
    client.Stop();
}
//

I've found some useful examples in java [https://chamibuddhika.wordpress.com/2011/10/02/apache-thrift-quickstart-tutorial/]. I've try my best to convert the java code of non-block server to the corresponding C# code but I found that there seems to be no TNonblockingServerTransport in C#. Anyone could help me with this probelm?

// Java Code
public class NonblockingServer {

    private void start() {
        try {
            TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(7911);
            ArithmeticService.Processor processor = new ArithmeticService.Processor(new ArithmeticServiceImpl());

            TServer server = new TNonblockingServer(new TNonblockingServer.Args(serverTransport).
                    processor(processor));
            System.out.println("Starting server on port 7911 ...");
            server.serve();
        } catch (TTransportException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        NonblockingServer srv = new NonblockingServer();
        srv.start();
    }
}

Body:
There's actually two answers to that question.

Possible implementation

Your setup is flawed, to begin with.

    // #Server#
    // Server Set-Up

    private bool forceStop;

    public void Stop()
    {
        forceStop = true;
    }

Let's assume, we have two clients, both starting a new calculation. Now one client wants to abort. What happens?

The solution would be to structure it in a way where the calculation is a separate business logic object that is instantiated at TimeConsumingOperation() and made available to the client by some means, typically by returning some sort of ID.

When the client now wants to abort, it calls Stop(calcualtionID). The server side logic now routes that call to the implementation and triggers whatever the abort mechanism might be, with C# is is probably a CancellationToken.

A third call would be needed to query the final results from the server end once the calculation has finished. Note that we still work with a TSimpleServer and the reason it works is because we avoid blocking calls by means of the API design.

Nonblocking server

Yes, there is no implementation yet for C#. Since Thrift is Open Source, that probably simply means that there were nobody running into that use case so far and wanted to spend time on an implementation. That is not to say that such a use case may not exist.

What exists are

Threaded and Threadpool servers

Task.Run(() => { your code })

which may help to solve your use case. Also, when used with ASP.NET there is no need for a nonblocking server since the runtime offers enough support already for multiple connections.

Bottom line

There are certain ways to work around that limitation you experierenced. One additional alternative could be to become a contributor by porting one of the existing (e.g. Java) nonblocking implementation to NetStd (preferred, since C# and NetCore will mature into "deprecated" state with the next release and both be replaced by NetStd eventually)


问:
How to get the xml sub-parameters
How to get the xml sub-parameters?
how to get all the results of category and return a result $category .. category = Test1, Test2

my xml

```<code><xml>
<title>Test 123</title>
<categories>
<category>Test1</category>
<category>Test2</category>
</categories>
</xml>
</code>```

my get code

```<code>$category = htmlspecialchars($item->categories->category, ENT_XML1 | ENT_QUOTES, 'UTF-8');

echo $category; //I want to return Test1, Test2
</code>```

答:
You could loop $item->categories->category using a foreach:

```<code>$source = <<<DATA
<xml>
<title>Test 123</title>
<categories>
<category>Test1</category>
<category>Test2</category>
</categories>
</xml>
DATA;

$item = simplexml_load_string($source);

foreach ($item->categories->category as $elm) {
    echo $elm . PHP_EOL;
}
</code>```

That will give you:

```<code>Test1
Test2
</code>```

See a php demo

Title: How to get the xml sub-parameters

Body:
How to get the xml sub-parameters?
how to get all the results of category and return a result $category .. category = Test1, Test2

my xml

<xml>
<title>Test 123</title>
<categories>
<category>Test1</category>
<category>Test2</category>
</categories>
</xml>

my get code

$category = htmlspecialchars($item->categories->category, ENT_XML1 | ENT_QUOTES, 'UTF-8');

echo $category; //I want to return Test1, Test2

Body:
You could loop $item->categories->category using a foreach:

$source = <<<DATA
<xml>
<title>Test 123</title>
<categories>
<category>Test1</category>
<category>Test2</category>
</categories>
</xml>
DATA;

$item = simplexml_load_string($source);

foreach ($item->categories->category as $elm) {
    echo $elm . PHP_EOL;
}

That will give you:

Test1
Test2

See a php demo