问:
selenium web driver : Able to open Firefox browser but The address isn’t valid
```<code>     WebDriver driver = new FirefoxDriver();

    driver.navigate().to("https://www.google.com");
</code>```

Says "Invalid address"

```<code>public static void main(String[] args) {
        // TODO Auto-generated method stub

        driver.navigate().to("https://www.google.com");
</code>```

答:
Here is the Answer to your Question:

As per your code block:

```<code>WebDriver driver = new FirefoxDriver();
driver.navigate().to("https://www.google.com");
</code>```

This should have worked.

To open a url (considering the url of String type) you can consider to use any of the other two methods as follows:

Use get() method to open the url:

```<code>WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
</code>```

Use Navigation class to create a new object and open url:

```<code>WebDriver driver = new FirefoxDriver();
Navigation sara_navigate = driver.navigate();
sara_navigate.to("https://www.google.com");
</code>```

Let me know if this Answers your Question.

Body:
     WebDriver driver = new FirefoxDriver();

    driver.navigate().to("https://www.google.com");

Says "Invalid address"

public static void main(String[] args) {
        // TODO Auto-generated method stub

        driver.navigate().to("https://www.google.com");

Body:
Here is the Answer to your Question:

As per your code block:

WebDriver driver = new FirefoxDriver();
driver.navigate().to("https://www.google.com");

This should have worked.

To open a url (considering the url of String type) you can consider to use any of the other two methods as follows:

Use get() method to open the url:

WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");

Use Navigation class to create a new object and open url:

WebDriver driver = new FirefoxDriver();
Navigation sara_navigate = driver.navigate();
sara_navigate.to("https://www.google.com");

Let me know if this Answers your Question.


来源: stackexchange

问:
Why this SFINAE snippet is not working in g++, but working in MSVC?
In MSVC2017 this works fine, both static_asserts are NOT triggered as expected:

```<code>template <typename T>
struct do_have_size {
    template <typename = decltype(std::declval<T>().size())>
    static std::true_type check(T);
    static std::false_type check(...);
    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same<TR, std::true_type>::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}
</code>```

However, if I compile in g++7.1 or clang 4.0 I get following compiler error:

```<code>In instantiation of 'struct do_have_size<int>':
20:39:   required from here
9:24: error: request for member 'size' in 'declval<do_have_size<int>::TP>()', which is of non-class type 'int'
</code>```

From my understanding of SFINAE, substition of true_type returning function should fail for int parameter and next function shall be chosen, like it is done in MSVC. Why clang and g++ are not compiling it at all?

I've compiled with -std=c++17 switch only, maybe something more is needed?

答:
SFINAE doesn't work here, as the class is already instantiated with T = int in do_have_size<int>::type. SFINAE works only for a list of template function candidates, in your case you'll get a hard error since in the instantiation

```<code>do_have_size<int>::type
</code>```

the member function

```<code>template <typename = decltype(std::declval<int>().size())>
static std::true_type check(T);
</code>```

is surely ill-formed for int. The

```<code>static std::false_type check(...);
</code>```

won't ever be considered. So gcc is right here in rejecting your code and MSVC2017 should not accept the code.

Related: std::enable_if : parameter vs template parameter and SFINAE working in return type but not as template parameter

One solution is to use the magic of void_t (since C++17, but you can define your own in C++11/14), which maps any type list to void and enables crazy simple-looking SFINAE techniques, like so

```<code>#include <utility>
#include <vector>

template<typename...>
using void_t = void; // that's how void_t is defined in C++17

template <typename T, typename = void>
struct has_size : std::false_type {};

template <typename T>
struct has_size<T, void_t<decltype(std::declval<T>().size())>>
    : std::true_type {};

int main() {
    using TR = typename has_size<std::vector<int>>::type;
    using FL = typename has_size<int>::type;

    static_assert(std::is_same<TR, std::true_type>::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}
</code>```

Live on Wandbox

Here is a Cppcon video by Walter Brown which explains the void_t techniques in great detail, I highly recommend it!

ContentLicense: CC BY-SA 3.0

Body:
In MSVC2017 this works fine, both static_asserts are NOT triggered as expected:

template <typename T>
struct do_have_size {
    template <typename = decltype(std::declval<T>().size())>
    static std::true_type check(T);
    static std::false_type check(...);
    using type = decltype(check(std::declval<T>()));
};

int main() {
    using TR = typename do_have_size<std::vector<int>>::type;
    using FL = typename do_have_size<int>::type;

    static_assert(std::is_same
::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}

However, if I compile in g++7.1 or clang 4.0 I get following compiler error:

In instantiation of 'struct do_have_size<int>':
20:39:   required from here
9:24: error: request for member 'size' in 'declval<do_have_size<int>::TP>()', which is of non-class type 'int'

From my understanding of SFINAE, substition of true_type returning function should fail for int parameter and next function shall be chosen, like it is done in MSVC. Why clang and g++ are not compiling it at all?

I've compiled with -std=c++17 switch only, maybe something more is needed?

Body:
SFINAE doesn't work here, as the class is already instantiated with T = int in do_have_size<int>::type. SFINAE works only for a list of template function candidates, in your case you'll get a hard error since in the instantiation

do_have_size<int>::type

the member function

template <typename = decltype(std::declval<int>().size())>
static std::true_type check(T);

is surely ill-formed for int. The

static std::false_type check(...);

won't ever be considered. So gcc is right here in rejecting your code and MSVC2017 should not accept the code.

Related: std::enable_if : parameter vs template parameter and SFINAE working in return type but not as template parameter

One solution is to use the magic of void_t (since C++17, but you can define your own in C++11/14), which maps any type list to void and enables crazy simple-looking SFINAE techniques, like so

#include <utility>
#include <vector>

template<typename...>
using void_t = void; // that's how void_t is defined in C++17

template <typename T, typename = void>
struct has_size : std::false_type {};

template <typename T>
struct has_size<T, void_t<decltype(std::declval<T>().size())>>
    : std::true_type {};

int main() {
    using TR = typename has_size<std::vector<int>>::type;
    using FL = typename has_size<int>::type;

    static_assert(std::is_same<TR, std::true_type>::value, "TRUE");
    static_assert(std::is_same<FL, std::false_type>::value, "FALSE");
}

Live on Wandbox

Here is a Cppcon video by Walter Brown which explains the void_t techniques in great detail, I highly recommend it!


问:
How to use a shell variable inside sed when doing "d" command?
In my bash, I wish to delete lines from 1 to ${number}, like this:

```<code>number=10
sed '1,${number}d' myfile
</code>```

It failed with syntax error.
I also tried "\${number}", '"$number"', neithers works

I changed to double quote, it works under command line, but not inside bash script file. How to make it work?

答:
I changed to double quote, it works under command line, but not inside
  bash script file

Assuming your bash script is:

```<code>sed "1,${number}d" myfile
</code>```

you should export number variable in bash prompt so that it can be visible in bash script when it is run:

```<code>export number=10
</code>```

Body:
In my bash, I wish to delete lines from 1 to ${number}, like this:

number=10
sed '1,${number}d' myfile

It failed with syntax error.
I also tried "\${number}", '"$number"', neithers works

I changed to double quote, it works under command line, but not inside bash script file. How to make it work?

Body:
I changed to double quote, it works under command line, but not inside
  bash script file

Assuming your bash script is:

sed "1,${number}d" myfile

you should export number variable in bash prompt so that it can be visible in bash script when it is run:

export number=10


问:
Android samasung galaxy tab emulator resolut?
I have updated my  android sdk  with samsung galax tab addon , it installed successfully . problem is that when i open galaxy tab emulator, it displayed portion of emulator ,i.e; bottom of emulator is not visible. i thnk it is problem with desktop resolution , but resolution of desktop is 1280 X 1024 .  Can any one tell me how to get the display of galaxy tab emulator </p>

答: Run the ADV manager, start the glaxay device. A screen will prompt, where you can "scale display to real size". Set a 7" screen (like in real life), and pretend your monitor screen is 50 DPI, you should have a reduced emulator.</p>

ContentLicense: CC BY-SA 2.5


问:
Python 3 Program to print the Initials of a name and with surname
Program: Input a name and Print the Initials and with surname.

Input:- Ted Vivian Mosby

Output:- T V Mosby

Using Python 3 online compiler:-

https://repl.it/languages/python3

```<code>user = input('Please Enter your name \n')
length = len(user)
value=0

for a in range(0,length-1):
    if a==" ":
      value=a

for b in range(0,value):
    if b==0:
      print(user[0])
    elif user[b]==" ":
      print(user[b+1])

for c in range(value+1,length):
    print(user[c])
</code>```

The output I have is:-

Please Enter your name

 Ted Vivian Mosby

e

d

V

i

v

i

a

n

M

o

s

b

y

答:
```<code>user = input('Please Enter your name \n')
length = len(user.split(" "))
value=0
print(length)
for a in user.split(" "):
   if(value==length-1):
      print(a)
   else:
      print(a[0],end=' ')
   value+=1
</code>```

Body:
Program: Input a name and Print the Initials and with surname.

Input:- Ted Vivian Mosby

Output:- T V Mosby

Using Python 3 online compiler:-

https://repl.it/languages/python3

user = input('Please Enter your name \n')
length = len(user)
value=0

for a in range(0,length-1):
    if a==" ":
      value=a

for b in range(0,value):
    if b==0:
      print(user[0])
    elif user[b]==" ":
      print(user[b+1])

for c in range(value+1,length):
    print(user[c])

The output I have is:-

Please Enter your name

 Ted Vivian Mosby

e

d

V

i

v

i

a

n

M

o

s

b

y


问:
MySQL Select last day of current year
Im looking for the easiest way to select/return the last month/day of the current year in the format of 2016-12-31 using MySQL. I've seen examples using Postgres and SQL Server but not MySQL.</p>

答:
```<code>SELECT concat(concat(DATE_FORMAT(sysdate(),'%Y')),'-','10','-','01') end_year;

SELECT DATE_SUB(curdate(),INTERVAL (DAY(curdate()-1)) DAY) frist_day_month;

SELECT DATE_SUB(curdate(),INTERVAL (DAY(curdate()-1)) DAY) frist_day_month;

select    TIMESTAMPADD(month,-1*timestampdiff(month
       , now()
       , '1900-10-01'
       ),'1900-01-01')
</code>```

Title: MySQL Select last day of current year


问:
How to check if socket.io is installed on my system
I am trying to implement chat using the following URL:

https://socket.io/get-started/chat/ ...

the above website says I need to install socket.io using npm

```<code>npm install --save socket.io
</code>```

But I think I have already installed socket.io on my system but I don't know how to check whether it is already or not.

I tried

```<code>socket.io -v
</code>```

but it throws the following error

```<code>-bash : socket.io: command not found
</code>```

答:
Socket.io has been installed on your system if the npm command runned normally.

You can try for example a file with this script in your index.html

```<code>    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io('/');
        socket.emit('api', {command: 'test', args: {
            text: "Hello World"
        }}, function(result) {
            console.log(result)
        });

            socket.on('api', function(data, fn){
            if(data.command=="test"){
                window.alert (data.args.text)
            }
       });

    </script>
</code>```

Body:
I am trying to implement chat using the following URL:

https://socket.io/get-started/chat/ ...

the above website says I need to install socket.io using npm

npm install --save socket.io

But I think I have already installed socket.io on my system but I don't know how to check whether it is already or not.

I tried

socket.io -v

but it throws the following error

-bash : socket.io: command not found

Body:
Socket.io has been installed on your system if the npm command runned normally.

You can try for example a file with this script in your index.html

    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io('/');
        socket.emit('api', {command: 'test', args: {
            text: "Hello World"
        }}, function(result) {
            console.log(result)
        });

            socket.on('api', function(data, fn){
            if(data.command=="test"){
                window.alert (data.args.text)
            }
       });

    </script>


问:
Windows Start command handles EXE and BAT differently, the latter is flawed
Please how can I run batch file with arguments enclosed in double quotes using the Start command?

If you use EXE file, it works (calc is just an example you can test with):

```<code>start "Some Title" "calc.exe" "arg1" "arg 2" "arg  3"
</code>```

The same syntax calling batch file does not: (in the above, only the extension was replaced)

```<code>start "Some Title" "calc.bat" "arg1" "arg 2" "arg  3"
</code>```

Error:

'calc.bat"  "arg1" "arg' is not recognized as an internal or external command,
  operable program or batch file.

(The content of calc.bat file does not matter, it can even have zero length.)

How I can achieve launching calc.bat using start command (asynchronously, in separate window) with arguments arg1, arg 2 and arg  3?

Of course, if you specify arguments without quotes, it works:

```<code>start "Some Title" "calc.bat" arg1 arg2 arg3
</code>```

EDIT:

I actually need start_all.bat which starts 3 parallel processes in 3 new windows:

```<code>set user="abc"
start "Run 1" "calc.bat" "%user%" "arg 1" "arg 2" "arg 3"
start "Run 2" "calc.bat" "%user%" "arg 4" "arg 5" "arg 6"
start "Run 3" "calc.bat" "%user%" "arg 7" "arg 8" "arg 9"
</code>```

but this works only with EXE, not with BAT.

calc.bat can be something simple like

```<code>@echo 1: `%1`
@echo 2: `%2`
@echo 3: `%3`
@pause
</code>```

Additional question: What if the path with the space is present?

set user="abc"
start "Run 1" "c:\batch files\calc.bat" "%user%" "arg 1" "arg 2" "arg 3"
start "Run 2" "c:\batch files\calc.bat" "%user%" "arg 4" "arg 5" "arg 6"
start "Run 3" "c:\batch files\calc.bat" "%user%" "arg 7" "arg 8" "arg 9"
```

答:
You could try invoking the standard interpreter and escape the quotation marks like this:

start "Some Title" "%COMSPEC%" /c"calc.bat ^"arg1^" ^"arg 2^" ^"arg  3^""

Body:
Please how can I run batch file with arguments enclosed in double quotes using the Start command?

If you use EXE file, it works (calc is just an example you can test with):

start "Some Title" "calc.exe" "arg1" "arg 2" "arg  3"

The same syntax calling batch file does not: (in the above, only the extension was replaced)

start "Some Title" "calc.bat" "arg1" "arg 2" "arg  3"

Error:

'calc.bat"  "arg1" "arg' is not recognized as an internal or external command,
  operable program or batch file.

(The content of calc.bat file does not matter, it can even have zero length.)

How I can achieve launching calc.bat using start command (asynchronously, in separate window) with arguments arg1, arg 2 and arg  3?

Of course, if you specify arguments without quotes, it works:

start "Some Title" "calc.bat" arg1 arg2 arg3

EDIT:

I actually need start_all.bat which starts 3 parallel processes in 3 new windows:

set user="abc"
start "Run 1" "calc.bat" "%user%" "arg 1" "arg 2" "arg 3"
start "Run 2" "calc.bat" "%user%" "arg 4" "arg 5" "arg 6"
start "Run 3" "calc.bat" "%user%" "arg 7" "arg 8" "arg 9"

but this works only with EXE, not with BAT.

calc.bat can be something simple like

@echo 1: `%1`
@echo 2: `%2`
@echo 3: `%3`
@pause

Additional question: What if the path with the space is present?

set user="abc"
start "Run 1" "c:\batch files\calc.bat" "%user%" "arg 1" "arg 2" "arg 3"
start "Run 2" "c:\batch files\calc.bat" "%user%" "arg 4" "arg 5" "arg 6"
start "Run 3" "c:\batch files\calc.bat" "%user%" "arg 7" "arg 8" "arg 9"


问:
laravel 5.0 delete and edit in database
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?

This is my library, here I want to delete or update something from my database

```<code>@foreach ($allJobs as $job)
    <tr>
        <td><img src="{{$job->selected_icon}}" width="50" /> </td>
        <td>{{$job->jobtitle_de}}</td>
        <td>{{$job->location}}</td>
        <td><img src="{{$job->selected_image}}" width="100" /></td>
        <td>{{$job->workinghours}}</td>
        <td>{{$job->grey_header_de}}</td>
        <td>{{$job->date}}</td>
        <td>
            <a href=""><button>Edit</button></a> <a href="/delete">
            <button>Delete</button></a></td>
            <!--<td> <button type="delete" name="button"></button>-->
        <td>
        </td>
    </tr>
@endforeach
</code>```

答:
now I found this in the internet:

```<code><div class="library">
<table>
@foreach ($allJobs as $job)
<tr>
  <td><img src="{{$job->selected_icon}}" width="50" /> </td>
  <td>{{$job->jobtitle_de}}</td>
  <td>{{$job->location}}</td>
  <td><img src="{{$job->selected_image}}" width="100" /></td>
  <td>{{$job->workinghours}}</td>
  <td>{{$job->grey_header_de}}</td>
  <td>{{$job->date}}</td>
<td>
    {{ Form::open(['method' => 'DELETE', 'route' => 'job.destroy', $job]-
    >id]) }}
      {{ Form::hidden('id', $job-id) }}
      {{ Form::submit('delete', ['class' => 'library']) }}
    {{Form::close}}
  </td>
 </tr>
@endforeach
</code>```

and this is my Controller

```<code>public function destroy($id)
{
    $jobs = Job::findOrFail($id);
    $jobs->delte();

    return redirect::route('/');
}
</code>```

Title: laravel 5.0 delete and edit in database

Body:
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?

This is my library, here I want to delete or update something from my database

@foreach ($allJobs as $job)

        selected_icon}}" width="50" />
        {{$job->jobtitle_de}}
        {{$job->location}}
        selected_image}}" width="100" />
        {{$job->workinghours}}
        {{$job->grey_header_de}}
        {{$job->date}}

            <button>Edit</button>
            <button>Delete</button>

@endforeach

Body:
now I found this in the internet:

<div class="library">
<table>
@foreach ($allJobs as $job)
<tr>
  <td><img src="{{$job->selected_icon}}" width="50" /> </td>
  <td>{{$job->jobtitle_de}}</td>
  <td>{{$job->location}}</td>
  <td><img src="{{$job->selected_image}}" width="100" /></td>
  <td>{{$job->workinghours}}</td>
  <td>{{$job->grey_header_de}}</td>
  <td>{{$job->date}}</td>
<td>
    {{ Form::open(['method' => 'DELETE', 'route' => 'job.destroy', $job]-
    >id]) }}
      {{ Form::hidden('id', $job-id) }}
      {{ Form::submit('delete', ['class' => 'library']) }}
    {{Form::close}}
  </td>
 </tr>
@endforeach

and this is my Controller

public function destroy($id)
{
    $jobs = Job::findOrFail($id);
    $jobs->delte();

    return redirect::route('/');
}

ContentLicense: CC BY-SA 4.0


问:
How to serve a music stream (e.g. internet radio) via Kodi's music library?
How to serve music streams from internet radios via Kodi's music library and add metadata to it?

What I've tryed so far is to put the stream url in a .strm file:

```<code># cat br-klassik.strm
http://br-brklassik-live.cast.addradio.de/br/brklassik/live/mp3/128/stream.mp3
</code>```

The docs tell to add a album.nfo or a artist.nfo but I don't know how to connect the stream information with those informations.

# cat br-klassik.nfo
<?xml version="1.0" encoding="utf-8"?>
<album>
  <title>BR-Klassik</title>
  <genre clear=true>Internetradio</genre>
  <track>
    <position>Track Number (1)</position>
    <title>br-klassik</title>
  </track>
</album>
```

<p>Is there a <code>song.nfo</code> file similar to <code>musicvideo.nfo</code></p>

<p>I'd expect something like this:</p>

<pre class="lang-xml prettyprint-override"><code># cat br-klassik.nfo
<?xml version="1.0" encoding="utf-8"?>
<song>
  <title>BR-Klassik</title>
  <genre clear=true>Internetradio</genre>
</song>
</code>```

答:
There is no song.nfo, you could just load it via file mode, but then you have no stream infos.

Have you checked if the stream is available via an existing plugin?
Like https://kodi.tv/addon/music-add-ons-plugins/shoutcast-2 or https://kodi.tv/addon/music-add-ons-plugins/radio

Body:
How to serve music streams from internet radios via Kodi's music library and add metadata to it?

What I've tryed so far is to put the stream url in a .strm file:

# cat br-klassik.strm
http://br-brklassik-live.cast.addradio.de/br/brklassik/live/mp3/128/stream.mp3

The docs tell to add a album.nfo or a artist.nfo but I don't know how to connect the stream information with those informations.

# cat br-klassik.nfo
<?xml version="1.0" encoding="utf-8"?>
<album>
  <title>BR-Klassik</title>
  <genre clear=true>Internetradio</genre>
  <track>
    <position>Track Number (1)</position>
    <title>br-klassik</title>
  </track>
</album>

Is there a song.nfo file similar to musicvideo.nfo

I'd expect something like this:

# cat br-klassik.nfo
<?xml version="1.0" encoding="utf-8"?>
<song>
  <title>BR-Klassik</title>
  <genre clear=true>Internetradio</genre>
</song>


问:
Unexpected token function for koa-bodyparser
I am trying to use babel for compilation of my KOA code.But when I run my code, it gives me below error:

```<code>return async function bodyParser(ctx, next) {
           ^^^^^^^^
SyntaxError: Unexpected token function
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Module._extensions..js (module.js:579:10)
at Object.require.extensions.(anonymous function)
</code>```

Node version : 6.10.3

答:
If you're using a Node version that's less than 7.6 with Koa v1, you need to install the right version of koa-bodyparser. Try doing:

```<code>npm install koa-bodyparser@2
</code>```

Version 2 of koa-bodyparser doesn't use async functions. This is described at the bottom in the README of the module.

Body:
I am trying to use babel for compilation of my KOA code.But when I run my code, it gives me below error:

return async function bodyParser(ctx, next) {
           ^^^^^^^^
SyntaxError: Unexpected token function
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Module._extensions..js (module.js:579:10)
at Object.require.extensions.(anonymous function)

Node version : 6.10.3

Body:
If you're using a Node version that's less than 7.6 with Koa v1, you need to install the right version of koa-bodyparser. Try doing:

npm install koa-bodyparser@2

Version 2 of koa-bodyparser doesn't use async functions. This is described at the bottom in the README of the module.


问:
Is there a windows utility similar to HTML Tidy for Javascript?
I want to cleanup some javascript files and reformat them with nice indents, etc,
Are there recommendations for utilities to do this under Windows?</p>

答: If you have Visual Studio you can open the Javascript document and press CTRL+K, CTRL+D to format the whole document.</p>

OwnerDisplayName: Noah

LastEditorDisplayName: Noah

OwnerDisplayName: David Thomas Garcia


问:
how to spread out buttons, they are currently stacked?
I have a bunch of buttons on my page, my html is like:

```<code><div>
  <input ..>
  <input ...>
</dvi>
</code>```

They are currently just stacking up on each other, I want them all on one horizontal line spread out.

I tried doing:

display:inline

on the outer div, but that didn't work.

答:
Try:

```<code>div input {
    float: left;
    margin-right: 10px;
}
</code>```

... or something similar. You could give the inputs classes or IDs (which is generally recommended) so you can apply specific styles to each one.

Body:
I have a bunch of buttons on my page, my html is like:

  <input ..>
  <input ...>
</dvi>

They are currently just stacking up on each other, I want them all on one horizontal line spread out.

I tried doing:

display:inline

on the outer div, but that didn't work.

Body:
Try:

div input {
    float: left;
    margin-right: 10px;
}

... or something similar. You could give the inputs classes or IDs (which is generally recommended) so you can apply specific styles to each one.


问:
Sorting Array in Swift3
In my code, I have a struct like the following:

```<code>struct Object {
    var name: String
    var count: Int
</code>```

I am now creating an array of 10 Objects with random names and random counts.

Is there an easy way to

a) sort them alphabetically

b) sort them numerically in ascending order

Basically, there will be an array like so:
[Object1, Object2, Object3].
Every Object has a name and count attribute, and I want the objects in that list be sorted via these two attributes.

Solution in Swift2 (using this solution: StackOverflow):

```<code>Object.sort{
        if $0.name != $1.name {
            return $0.name < $1.name
        }
        else {
            //suits are the same
            return $0.count < $1.count
        }
    }
</code>```

However, this has been renamed to sorted(by: ) in Swift3, and I don't quit get how to do that.

答:
You can still use shorthand for sorted:

```<code>objNameSorted = objArray.sorted { $0 < $1 }
</code>```

While less readable, it more closely mimics the sort syntax.

Title: Sorting Array in Swift3

Body:
In my code, I have a struct like the following:

struct Object {
    var name: String
    var count: Int

I am now creating an array of 10 Objects with random names and random counts.

Is there an easy way to

a) sort them alphabetically

b) sort them numerically in ascending order

Basically, there will be an array like so:
[Object1, Object2, Object3].
Every Object has a name and count attribute, and I want the objects in that list be sorted via these two attributes.

Solution in Swift2 (using this solution: StackOverflow):

Object.sort{
        if $0.name != $1.name {
            return $0.name < $1.name
        }
        else {
            //suits are the same
            return $0.count < $1.count
        }
    }

However, this has been renamed to sorted(by: ) in Swift3, and I don't quit get how to do that.

Body:
You can still use shorthand for sorted:

objNameSorted = objArray.sorted { $0 < $1 }

While less readable, it more closely mimics the sort syntax.


问:
Queries about ReactiveX programming with swift
A completed project in swift 3.0, I want to update it with ReactiveX frameworks for swift i.e rxSwift, rxCocoa.

My point is as i'm learning reactive it is so different and new for me.
But before doing this I have some question in my mind

Is it worth working, spending time on ReactiveX?

Does it increase the performance of the application?

What do you personally think about the future of ReactiveX?

答:
There are certain topics of contention in the rx-world. I will give u that.
But if ur previous project version did not have rx (in any language), then changes are its bulky.

Imagine this:-
Without Rx:- (we need to pull data)
- u query a data structure/function/service
- a value is returned

With Rx:- (data is already pushed down to us, we do not need to req. separately, but just subscribe)
- values are always available on subscription

Rx changes the way u look at file systems/events, etc.
They are all viewed as data-streams which can be emitted using an Observable.
An observer can then request it on subscription.

So, it is the future and yes the code is reduced severely and much much readable.


问:
Jelastic Traffic Distributor 100-0 balance, Sticky Sessions fail?
So, next Jelastic question!

I'm stuck using Spring Webflow for the time being, so sticky sessions in any load balanced scenario are important.

I'm trying to use the Jelastic Traffic Distributor to achieve Blue/Green deployments.

I have set up two servers and the TD infront of them. I've balanced the TD 100-0 in favour of server 1 and set the Routing Method to Sticky Sessions.

This setup appears to work great, all requests go to server 1 and the sessions are maintained there. Indeed the Sticky Sessions ensure if I move the balance to say 50-50, the sessions already created stick to server 1.

My hope was to achieve Blue-Green deployments by deploying new code into server 2 while the TD was still set to 100-0 balance in favour of server 1. Once the code was deployed I'd move the balance to 0-100 in favour of server 2. Old sessions would continue to run until they're finished with in server 1 (ie stick where they were stuck) while new sessions would be created and stuck to server 2 running the new code. Repeat in reverse for later deployments.

The documentation here implies this tactic should work, particularly the last line;

Also, upon setting 100% ratio for any server, the second one won’t be removed from the settings completely, so it will be able to process the already existing sessions

However what I'm seeing is that as soon as I move the balance to 0-100, the sessions previously stuck to server 1 are lost and all requests are balanced to server 2.

In other words the last line of the docs doesn't appear to be true?

答:
There was incorrect information in our documentation:

```<code>Also, upon setting 100% ratio for any server, the second one won’t be removed from the settings completely, so it will be able to process the already existing sessions.
</code>```

Our tech writers deleted this line from the documentation.

NGINX configuration with weight=0 isn't possible, NGINX will not be started with this parameter value, so it is expected behavior. When you set weight 0 in UI panel - backend server is excluded from NGINX configuration and all requests are directed to backend which remained in nginx upstreams.

There is another solution for you, you are able to set weight ratio 99:1 using UI (or e.g. 10000:1 using nginx-jelastic.conf in Traffic Distributor). In this case there is very small chance that session will be lost.

Body:
There was incorrect information in our documentation:

Also, upon setting 100% ratio for any server, the second one won’t be removed from the settings completely, so it will be able to process the already existing sessions.

Our tech writers deleted this line from the documentation.

NGINX configuration with weight=0 isn't possible, NGINX will not be started with this parameter value, so it is expected behavior. When you set weight 0 in UI panel - backend server is excluded from NGINX configuration and all requests are directed to backend which remained in nginx upstreams.

There is another solution for you, you are able to set weight ratio 99:1 using UI (or e.g. 10000:1 using nginx-jelastic.conf in Traffic Distributor). In this case there is very small chance that session will be lost.


问:
writing multiple returns to a file in python
I need to write the returns of each function in to a text file. I have used the code below. However, when I have multiple functions, this process of using file1.write() consumes a lot of time and lines. Is there any smarter method to write the outputs?

```<code>def function1():
    #some operation
    return "Status 1" + "\n\n"

def function2():
    #some operation
    return "Status 2" + "\n\n"

def function3():
    #some operation
    return "Status 1" + "\n\n"

if __name__ == '__main__':

    file1 = open("test.txt","w")

    output1 = function1()
    file1.write(output1)

    output2 = function2()
    file1.write(output2)

    output3 = function3()
    file1.write(output3)

    file1.close()
</code>```

I have modified the code since many are confused with my question.

答:
The fastest text writer I've come across is Pandas, which I usually use with NumPy.  So it would look something like this:

```<code>import pandas as pd
import numpy as np
a=np.zeros(len(results)) #if you know the result size
#now store all your results in a
a[0]=add(5,6)
a[1]=sub(5,6)
a[2]=multiply(5,6)
#continue
b=pd.DataFrame(a)
b.to_csv('test.csv', header=False, index=False, sep=',')
</code>```

Hope you get the idea - sep can be any delimiter.  If you need a multidimensional array you can do that too.

Body:
I need to write the returns of each function in to a text file. I have used the code below. However, when I have multiple functions, this process of using file1.write() consumes a lot of time and lines. Is there any smarter method to write the outputs?

def function1():
    #some operation
    return "Status 1" + "\n\n"

def function2():
    #some operation
    return "Status 2" + "\n\n"

def function3():
    #some operation
    return "Status 1" + "\n\n"

if __name__ == '__main__':

    file1 = open("test.txt","w")

    output1 = function1()
    file1.write(output1)

    output2 = function2()
    file1.write(output2)

    output3 = function3()
    file1.write(output3)

    file1.close()

I have modified the code since many are confused with my question.

Body:
The fastest text writer I've come across is Pandas, which I usually use with NumPy.  So it would look something like this:

import pandas as pd
import numpy as np
a=np.zeros(len(results)) #if you know the result size
#now store all your results in a
a[0]=add(5,6)
a[1]=sub(5,6)
a[2]=multiply(5,6)
#continue
b=pd.DataFrame(a)
b.to_csv('test.csv', header=False, index=False, sep=',')

Hope you get the idea - sep can be any delimiter.  If you need a multidimensional array you can do that too.


问:
can I use an image that is on my computer with JavaScript?
I was trying to make a house that opens its door onmouseover.

I have already made the two images of the house on photoshop and saved them as .jpg

here's the code I made for HTML:

```<code><img id="house" onmouseover="open()" src="doorclosed.jpg"/>
</code>```

and here's the JavaScript code:

```<code>function open() {
            document.getElementById("house").src='dooropened.jpg';
    }
</code>```

the problem is that when I click on the closed house image on the webpage I get a white page and the html file name is in the title bar.

what did I do wrong? shouldn't I add images from my computer? because I used same code with images from the internet using its url.

答:
You must be change function name. For example change "open" to "changeImg".</p>

```<code><img id="house" onmouseover="changeImg()" src="doorclosed.jpg"/>

function changeImg(){
            document.getElementById("house").src='dooropened.jpg';
    }
</code>```

Body:
I was trying to make a house that opens its door onmouseover.

I have already made the two images of the house on photoshop and saved them as .jpg

here's the code I made for HTML:

and here's the JavaScript code:

function open() {
            document.getElementById("house").src='dooropened.jpg';
    }

the problem is that when I click on the closed house image on the webpage I get a white page and the html file name is in the title bar.

what did I do wrong? shouldn't I add images from my computer? because I used same code with images from the internet using its url.

Body:
You must be change function name. For example change "open" to "changeImg".

<img id="house" onmouseover="changeImg()" src="doorclosed.jpg"/>

function changeImg(){
            document.getElementById("house").src='dooropened.jpg';
    }


问:
Javascript ES6 Get JSON from URL (no jQuery)
I was wondering if there's any ES6 way of getting json or other data from a url.

jQuery GET and Ajax calls are very common but I don't want to use jQuery in this one.

A typical call would look like this:

```<code>var root = 'http://jsonplaceholder.typicode.com';

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(data);
});
</code>```

or without jQuery something like this:

```<code>function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}
</code>```

My question is...Is there any new ways of doing this ... for example ES6 or is it still the same way?

答:
Yes there is, using the new Fetch API. Using that you can compess it as much as doing something like:

```<code>fetch(url).then(r => r.json())
  .then(data => console.log(data))
  .catch(e => console.log("Booo"))
</code>```

However, it's not supported by all browsers yet and not everybody is equally positive about the Fetch API implementation.

Anyhow, you can create your own opinion on that and read up more on it here.

Body:
I was wondering if there's any ES6 way of getting json or other data from a url.

jQuery GET and Ajax calls are very common but I don't want to use jQuery in this one.

A typical call would look like this:

var root = 'http://jsonplaceholder.typicode.com';

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(data);
});

or without jQuery something like this:

function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}

My question is...Is there any new ways of doing this ... for example ES6 or is it still the same way?

Body:
Yes there is, using the new Fetch API. Using that you can compess it as much as doing something like:

fetch(url).then(r => r.json())
  .then(data => console.log(data))
  .catch(e => console.log("Booo"))

However, it's not supported by all browsers yet and not everybody is equally positive about the Fetch API implementation.

Anyhow, you can create your own opinion on that and read up more on it here.


答:
Use split() to separate out the names. Then print the first char of each name, but the entire last name.

```<code>user = input('Please Enter your name \n')
names = user.split()

for i in range(0, len(names)):
    if i < len(names) - 1:
        # print first char only, no newline at the end
        print(names[i][0], end=" ")
    else:
        # print entire last name
        print(names[i]) # print entire name
</code>```

Title: Python 3 Program to print the Initials of a name and with surname

Body:
Program: Input a name and Print the Initials and with surname.

Input:- Ted Vivian Mosby

Output:- T V Mosby

Using Python 3 online compiler:-

https://repl.it/languages/python3

user = input('Please Enter your name \n')
length = len(user)
value=0

for a in range(0,length-1):
    if a==" ":
      value=a

for b in range(0,value):
    if b==0:
      print(user[0])
    elif user[b]==" ":
      print(user[b+1])

for c in range(value+1,length):
    print(user[c])

The output I have is:-

Please Enter your name

 Ted Vivian Mosby

e

d

V

i

v

i

a

n

M

o

s

b

y

Body:
Use split() to separate out the names. Then print the first char of each name, but the entire last name.

user = input('Please Enter your name \n')
names = user.split()

for i in range(0, len(names)):
    if i < len(names) - 1:
        # print first char only, no newline at the end
        print(names[i][0], end=" ")
    else:
        # print entire last name
        print(names[i]) # print entire name


问:
How do I change image on hover of  that the img is in - in jQuery?
You can see the implementation here http://jsfiddle.net/xNSFA/

Right now, when you hover over the cell, it changes some of the characteristics. But the image doesn't change. The image only changes when you hover over the image specifically.

How do I get the image to change with everything else?

By the way, it doesn't HAVE to be done in jQuery. If there is a nice elegant way to do this in CSS, I would love that. But I just assumed it was impossible to do - because of the image manipulation and I didn't want to set the background of the  to be that image. I want the image inside the cell.

Thanks.

答:
You can put the .hover() on the  and find the  inside to change, like this:

```<code>$("table td").hover(function() {
  var img = $(this).find("img")[0];
  img.src = img.src.replace('-grey.png', '-blk.png');
}, function() {
  var img = $(this).find("img")[0];
  img.src = img.src.replace('-blk.png', '-grey.png');
});
</code>```

You can test it out here, or the jQuery-ish way (though slower - some prefer it...I'd go with the above):

```<code>$("table td").hover(function() {
  $(this).find("img").attr("src", function(i, src) {
    return src.replace('-grey.png', '-blk.png');
  });
}, function() {
  $(this).find("img").attr("src", function(i, src) {
    return src.replace('-blk.png', '-grey.png');
  });
});
</code>```

Title: How do I change image on hover of <td> that the img is in - in jQuery?

Body:
You can put the .hover() on the <td> and find the <img> inside to change, like this:

$("table td").hover(function() {
  var img = $(this).find("img")[0];
  img.src = img.src.replace('-grey.png', '-blk.png');
}, function() {
  var img = $(this).find("img")[0];
  img.src = img.src.replace('-blk.png', '-grey.png');
});

You can test it out here, or the jQuery-ish way (though slower - some prefer it...I'd go with the above):

$("table td").hover(function() {
  $(this).find("img").attr("src", function(i, src) {
    return src.replace('-grey.png', '-blk.png');
  });
}, function() {
  $(this).find("img").attr("src", function(i, src) {
    return src.replace('-blk.png', '-grey.png');
  });
});


问:
Paypal sandbox tests for third party payments using PayPal-PHP-SDK
The app needs to implement buyer-to-seller payments without involving marketplace account, meaning direct payments beetween buyer and seller. I've created two sandbox accounts to test how it may work and created Third Party Payment. It worked and said that the payment finished successfuly. But when I go to sandbox account page I can see NO activity, no money were paid and no operations in history. Why it happens and how can I test that this is a proper way for app needs? Thanks</p>

答: While waiting for answers, it's now resolved. Obviously, given sample for Third Party Payment is only about creating the payment without execution. So execution is the answer.</p>


问:
JBoss 6.4 classloading
I have an .ear which contains multiples .war and I would like to deploy it into a jboss 6.4.7 server. The problem is that one of the .war is using a jboss's module (hibernate-jpa-2.0) but the app requires the hibernate-jpa-2.1 version. How to tell my war not using this jboss module. I have added a jboss-deployment-structure into the Ear/application/META-INF with this exclusion :

```<code><jboss-deployment-structure>
<ear-subdeployments-isolated>true</ear-subdeployments-isolated>

<sub-deployment name="myapp.war">
        <exclusions>
            <module name="javax.persistence.api" />
        </exclusions>
    </sub-deployment>
</jboss-deployment-structure>
</code>```

but not working..

The "javax.persistence.api" is written on the module.xml on the jboss server.

Thanks for your help.

答:
Add following

```<code><jboss-deployment-structure>
<ear-subdeployments-isolated>true</ear-subdeployments-isolated>
    <sub-deployment name="myapp.war">
    <exclude-subsystems>
        <subsystem name="jpa" />
    </exclude-subsystems>
    <exclusions>
        <module name="javaee.api" />
    </exclusions>
        </sub-deployment>
    </jboss-deployment-structure>
</code>```

A subsystem is the set of capabilities added by an extension.It
  defines how it will be used and configured. It is also defined in the
  EAP configuration file (standalone.xml or domain.xml) using the
   tag under a profile.
  For every extension added in an EAP instance, the  capabilities and attributes of that extension are
  configured with the <subsystem> element.

Another option can be just replace jar in the JBOSS with newer one

Title: JBoss 6.4 classloading

Body:
I have an .ear which contains multiples .war and I would like to deploy it into a jboss 6.4.7 server. The problem is that one of the .war is using a jboss's module (hibernate-jpa-2.0) but the app requires the hibernate-jpa-2.1 version. How to tell my war not using this jboss module. I have added a jboss-deployment-structure into the Ear/application/META-INF with this exclusion :

<jboss-deployment-structure>
<ear-subdeployments-isolated>true</ear-subdeployments-isolated>

        <exclusions>
            <module name="javax.persistence.api" />
        </exclusions>

</jboss-deployment-structure>

but not working..

The "javax.persistence.api" is written on the module.xml on the jboss server.

Thanks for your help.

Body:
Add following

<jboss-deployment-structure>
<ear-subdeployments-isolated>true</ear-subdeployments-isolated>
    <sub-deployment name="myapp.war">
    <exclude-subsystems>
        <subsystem name="jpa" />
    </exclude-subsystems>
    <exclusions>
        <module name="javaee.api" />
    </exclusions>
        </sub-deployment>
    </jboss-deployment-structure>

A subsystem is the set of capabilities added by an extension.It
  defines how it will be used and configured. It is also defined in the
  EAP configuration file (standalone.xml or domain.xml) using the
   tag under a profile.
  For every extension added in an EAP instance, the  capabilities and attributes of that extension are
  configured with the <subsystem> element.

Another option can be just replace jar in the JBOSS with newer one


问:
How can I fetch values from object array using jquery and javascript
I have this array structure :

```<code>var $obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };
</code>```

I want to fetch data from $obj->section2->row4->key2. How can I make it using jquery and javascript both.

UPDATE: I want it to print the value in a paragraph or div

```<code><p id="array"></p>
</code>```

答:
In javascript use . (dot) notation to access values

var obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };

    console.log(obj.sections2.row4.key2);

    ```

Body:
I have this array structure :

var $obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };

I want to fetch data from $obj->section2->row4->key2. How can I make it using jquery and javascript both.

UPDATE: I want it to print the value in a paragraph or div


问:
VueJS how to rerender a component
I have a VueJS component which populates a table via ajax, than I have a modal form inside component which creates new entries in table.

On modal hide I want to update the table to show new entries.

```<code>export default {
        created() {
            axios.get('/api/v1/customers')
                .then(response => {
                    this.customers = response.data;
                });
        },

        methods: {

            store() {
                this.form.errors = [];

                axios.post('/api/v1/customers', this.form)
                    .then(response => {
                        this.form.name = '';
                        this.form.scopes = [];
                        this.form.errors = [];

                        $('#modal-edit-client').modal('hide');
                        this.$forceUpdate();
                    })
                    .catch(error => {

                        console.log(error)
                        /*if (typeof error.response.data === 'object') {
                            this.form.errors = _.flatten(_.toArray(error.response.data));
                        } else {
                            this.form.errors = ['Something went wrong. Please try again.'];
                        }*/
                    });
            },

            newUser: function () {
                $('#modal-edit-client').modal('show');
            },

            edit: function () {
                alert('edit modal')
            }
        },

        data() {
            return {
                customers: {},
                alert: {
                    show: false,
                    type: null,
                    title: null,
                    message: null,
                },
                form: {
                    scopes: [],
                    errors: []
                }
            };
        }
    }
</code>```

I tried to use $forceUpdate() but does not seems to work

output template

```<code><template>
    <div class="row" v-cloak>
        <div class="col-md-12 ">
            <div class="panel panel-default custom-panel">

                <div class="panel-heading">
                    <strong>Customers</strong>
                    <div id="custom-search-input">
                        <div class="input-group col-md-12">
                            <input v-on:keyup.enter="filter" type="text" class="form-control input-sm" placeholder="Search Customer" />
                            <span class="input-group-btn">
                        <button class="btn btn-info btn-lg" type="button">
                            <i class="glyphicon glyphicon-search"></i>
                        </button>
                    </span>
                        </div>
                    </div>

                    <a class="btn icon-btn btn-success" id="new__item" href="#" @click="newUser">
                        <span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span> Add Customer
                    </a>
                </div>

                <div class="panel-body">
                    <table class="table table-condensed">
                        <tbody>
                        <tr>
                            <th style="width: 10px">#</th>
                            <th>Firma</th>
                            <th>Strasse</th>
                            <th>PLZ</th>
                            <th>Ort</th>
                            <th>Tel</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>

                        <tr v-for="customer in customers">
                            <td>{{ customer.id }}</td>
                            <td>{{ customer.customer_name }}</td>
                            <td>{{ customer.customer_street }}</td>
                            <td>{{ customer.customer_plz }}</td>
                            <td>{{ customer.customer_city }}</td>
                            <td>{{ customer.customer_telephone }}</td>
                            <td><span class="badge bg-green"><i class="fa fa-check"></i></span></td>
                            <td class="actions">
                                <a href=""><i class="fa fa-pencil"></i></a>
                                <a href=""><i class="fa fa-trash"></i></a>
                            </td>
                        </tr>
                        </tbody>
                    </table>

                </div>
            </div>
        </div>

        <!-- Edit Client Modal -->
        <div class="modal fade" id="modal-edit-client" tabindex="-1" role="dialog">
            <div class="spinner"></div>
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button " class="close" data-dismiss="modal" aria-hidden="true">×</button>

                        <h4 class="modal-title">
                            Add Customer
                        </h4>
                    </div>

                    <div class="modal-body">
                        <!-- Form Errors -->
                        <!--<div class="alert alert-danger" v-if="alert" >
                            <p><strong>Whoops!</strong> Something went wrong!</p>
                            <br>
                        </div>-->

                        <!-- Edit Client Form -->

                        <form class="form-horizontal" id="modal-create-customer"  role="form" method="POST" action="">

                            <div class="row">
                                <div class="col-xs-12">
                                    <label for="customer_name" class="control-label">Firmenbezeichnung</label>
                                    <input id="customer_name" type="text" class="form-control" v-model="form.customer_name" name="customer_name" value="" required autofocus>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-6">
                                    <label for="sex" class="control-label">Anrede</label>
                                    <select v-model="form.customer_contact_sex" name="title" id="sex" class="form-control">
                                        <option value="Herr">Herr</option>
                                        <option value="Frau">Frau</option>
                                    </select>
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-6">
                                    <label for="title" class="control-label">Title</label>
                                    <select v-model="form.customer_contact_title" name="title" id="title" class="form-control">
                                        <option value="">No title</option>
                                        <option value="Dr.">Dr.</option>
                                        <option value="Prof.">Prof.</option>
                                    </select>
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-xs-6">
                                    <label for="name" class="control-label">First Name</label>

                                    <input id="name" type="text" class="form-control" v-model="form.customer_first_name" name="customer_name" value="" required autofocus>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-6">
                                    <label for="email" class="control-label">Last Name</label>

                                    <input id="email" type="text" class="form-control" v-model="form.customer_last_name" name="customer_last_name" value="" required>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-6">
                                    <label for="street" class="control-label">Street</label>

                                    <input id="street" type="text" class="form-control" v-model="form.customer_street" name="customer_street" value="" required>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-2">
                                    <label for="plz" class="control-label">PLZ</label>

                                    <input id="plz" type="text" class="form-control" v-model="form.customer_plz" name="customer_plz" value="" required>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-4">
                                    <label for="city" class="control-label">City</label>

                                    <input id="city" type="text" class="form-control" v-model="form.customer_city" name="customer_city" value="" required>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-6">
                                    <label for="customer_telephone" class="control-label">Tel.</label>

                                    <input id="customer_telephone" type="text" class="form-control" v-model="form.customer_telephone" name="customer_telephone" value="" required>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-6">
                                    <label for="customer_fax" class="control-label">Fax.</label>

                                    <input id="customer_fax" type="text" class="form-control" name="customer_fax" value="" required>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-6">
                                    <label for="customer_mobile" class="control-label">Mobil</label>

                                    <input id="customer_mobile" type="text" class="form-control" name="customer_mobile" value="" required>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-6">
                                    <label for="customer_email" class="control-label">E-Mail.</label>

                                    <input id="customer_email" type="text" class="form-control" name="customer_email" value="" required>

                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>

                                <div class="col-xs-12">
                                    <label for="customer_note" class="control-label">Notiz</label>

                                    <textarea name="csutomer_note" id="customer_note" class="form-control"></textarea>
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Modal Actions -->
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                        <button type="button" class="btn btn-primary" @click="store">
                            Register
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
</code>```

答:
As said in the comments, your code looks fine except that you're not actually updating the customers property with anything.
When you're performing the XHR request with Axios, you need to use the response to populate the component, which will automatically update the relevant DOM.
Here is the relevant part of your code that you should modify:

```<code>axios.post('/api/v1/customers', this.form)
.then(response => {
  this.form.name = '';
  this.form.scopes = [];
  this.form.errors = [];

  // Set the component's customers property to what you get
  // in the response
  this.customers = response.data.customers;

  $('#modal-edit-client').modal('hide');

  // You don't need to forceUpdate as Vue will take care of
  // rerendering the relevant parts of the DOM
  // this.$forceUpdate();
})
</code>```

Also, considering you're expecting an array of customers to render the table, you should set the customers default value accordingly:

```<code>data() {
  return {
    customers: []
    // ...
  };
}
</code>```

Title: VueJS how to rerender a component

Body:
I have a VueJS component which populates a table via ajax, than I have a modal form inside component which creates new entries in table.

On modal hide I want to update the table to show new entries.

export default {
        created() {
            axios.get('/api/v1/customers')
                .then(response => {
                    this.customers = response.data;
                });
        },

        methods: {

            store() {
                this.form.errors = [];

                axios.post('/api/v1/customers', this.form)
                    .then(response => {
                        this.form.name = '';
                        this.form.scopes = [];
                        this.form.errors = [];

                        $('#modal-edit-client').modal('hide');
                        this.$forceUpdate();
                    })
                    .catch(error => {

                        console.log(error)
                        /*if (typeof error.response.data === 'object') {
                            this.form.errors = _.flatten(_.toArray(error.response.data));
                        } else {
                            this.form.errors = ['Something went wrong. Please try again.'];
                        }*/
                    });
            },

            newUser: function () {
                $('#modal-edit-client').modal('show');
            },

            edit: function () {
                alert('edit modal')
            }
        },

        data() {
            return {
                customers: {},
                alert: {
                    show: false,
                    type: null,
                    title: null,
                    message: null,
                },
                form: {
                    scopes: [],
                    errors: []
                }
            };
        }
    }

I tried to use $forceUpdate() but does not seems to work

output template

<template>

                    Customers

                            <input v-on:keyup.enter="filter" type="text" class="form-control input-sm" placeholder="Search Customer" />

                        <button class="btn btn-info btn-lg" type="button">

                        </button>

                         Add Customer

                            #
                            Firma
                            Strasse
                            PLZ
                            Ort
                            Tel
                            Status
                            Actions

                            {{ customer.id }}
                            {{ customer.customer_name }}
                            {{ customer.customer_street }}
                            {{ customer.customer_plz }}
                            {{ customer.customer_city }}
                            {{ customer.customer_telephone }}

                        <button type="button " class="close" data-dismiss="modal" aria-hidden="true">×</button>

                            Add Customer

                        <form class="form-horizontal" id="modal-create-customer"  role="form" method="POST" action="">

                                    Firmenbezeichnung
                                    <input id="customer_name" type="text" class="form-control" v-model="form.customer_name" name="customer_name" value="" required autofocus>

                                    Anrede
                                    <select v-model="form.customer_contact_sex" name="title" id="sex" class="form-control">
                                        <option value="Herr">Herr</option>
                                        <option value="Frau">Frau</option>
                                    </select>

                                    Title
                                    <select v-model="form.customer_contact_title" name="title" id="title" class="form-control">
                                        <option value="">No title</option>
                                        <option value="Dr.">Dr.</option>
                                        <option value="Prof.">Prof.</option>
                                    </select>

                                    First Name

                                    <input id="name" type="text" class="form-control" v-model="form.customer_first_name" name="customer_name" value="" required autofocus>

                                    Last Name

                                    <input id="email" type="text" class="form-control" v-model="form.customer_last_name" name="customer_last_name" value="" required>

                                    Street

                                    <input id="street" type="text" class="form-control" v-model="form.customer_street" name="customer_street" value="" required>

                                    PLZ

                                    <input id="plz" type="text" class="form-control" v-model="form.customer_plz" name="customer_plz" value="" required>

                                    City

                                    <input id="city" type="text" class="form-control" v-model="form.customer_city" name="customer_city" value="" required>

                                    Tel.

                                    <input id="customer_telephone" type="text" class="form-control" v-model="form.customer_telephone" name="customer_telephone" value="" required>

                                    Fax.

                                    <input id="customer_fax" type="text" class="form-control" name="customer_fax" value="" required>

                                    Mobil

                                    <input id="customer_mobile" type="text" class="form-control" name="customer_mobile" value="" required>

                                    E-Mail.

                                    <input id="customer_email" type="text" class="form-control" name="customer_email" value="" required>

                                    Notiz

                                    <textarea name="csutomer_note" id="customer_note" class="form-control"></textarea>

                        </form>

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                        <button type="button" class="btn btn-primary" @click="store">
                            Register
                        </button>

</template>

Body:
As said in the comments, your code looks fine except that you're not actually updating the customers property with anything.
When you're performing the XHR request with Axios, you need to use the response to populate the component, which will automatically update the relevant DOM.
Here is the relevant part of your code that you should modify:

axios.post('/api/v1/customers', this.form)
.then(response => {
  this.form.name = '';
  this.form.scopes = [];
  this.form.errors = [];

  // Set the component's customers property to what you get
  // in the response
  this.customers = response.data.customers;

  $('#modal-edit-client').modal('hide');

  // You don't need to forceUpdate as Vue will take care of
  // rerendering the relevant parts of the DOM
  // this.$forceUpdate();
})

Also, considering you're expecting an array of customers to render the table, you should set the customers default value accordingly:

data() {
  return {
    customers: []
    // ...
  };
}


问:
Rails: What's a good way to validate links (URLs)?
I was wondering how I would best validate URLs in Rails. I was thinking of using a regular expression, but am not sure if this is the best practice.

And, if I were to use a regex, could someone suggest one to me? I am still new to Regex.

Body:
You could use regex for this, for me works good this one:

(^|[\s.:;?\-\]<\(])(ftp|https?:\/\/[-\w;\/?:@&=+$\|\_.!~*\|'()\[\]%#,]+[\w\/#](\(\))?)(?=$|[\s',\|\(\).:;?\-\[\]>\)])


问:
Convert array in json javascript - same key
I have a PHP file where I have the name of the files of one folder and my objective now is to output this array as JSON.

My array looks like this:

Array (
    [0] => teste3.pdf
    [1] => teste2.pdf
    [2] => teste.pdf
    [3] => ..
    [4] => .
)
```

<p>And I'd like my JSON structured like this:</p>

<pre class="lang-js prettyprint-override"><code>{
    "Documents": [
        {
            "NameDoc": "teste3.pdf"
        },
        {
            "NameDoc": "teste2.pdf"
        },
        {
            "NameDoc": "teste.pdf"
        },
     ]
}
</code>```

I tried using json_encode but this alone doesn't give me what I want.

答:
Assuming your array of files is called MyArr.

```<code>const obj = {
  Documents: MyArr.map(file => ({ NameDoc: file }))
}
</code>```

Now do whatever you want to do with obj.

Body:
I have a PHP file where I have the name of the files of one folder and my objective now is to output this array as JSON.

My array looks like this:

Array (
    [0] => teste3.pdf
    [1] => teste2.pdf
    [2] => teste.pdf
    [3] => ..
    [4] => .
)

And I'd like my JSON structured like this:

{
    "Documents": [
        {
            "NameDoc": "teste3.pdf"
        },
        {
            "NameDoc": "teste2.pdf"
        },
        {
            "NameDoc": "teste.pdf"
        },
     ]
}

I tried using json_encode but this alone doesn't give me what I want.

Body:
Assuming your array of files is called MyArr.

const obj = {
  Documents: MyArr.map(file => ({ NameDoc: file }))
}

Now do whatever you want to do with obj.


问:
JSON Schema make property conditionally required
My current JSON schema definition is like this

```<code>{
  "properties": {
    "account_type": {
      "description": "account type",
      "enum": [
        "CURRENT",
        "SAVINGS",
        "DEMAT"
      ],
      "type": "string"
    },
    "demat_account_number": {
      "description": "demat_account_number",
      "type": "string"
    }
  },
  "required": [
    "account_type"
  ],
  "type": "object"
}
</code>```

My requirement is if "account_type" = "DEMAT" then "demat_account_number" should become a required attribute.

Is there any way we can achieve this validation?

答:
You can use "oneOf". This forces conforming documents to implement only one of a number of possible patterns:</p>

```<code>{
    "oneOf":[
        {
            "properties":{
                "account_type":{
                    "description":"account type",
                    "enum":[
                        "CURRENT",
                        "SAVINGS"
                    ],
                    "type":"string"
                }
            },
            "required":[
                "account_type"
            ],
            "type":"object"
        },
        {
            "properties":{
                "account_type":{
                    "description":"account type",
                    "enum":[
                        "DEMAT"
                    ],
                    "type":"string"
                },
                "demat_account_number":{
                    "description":"demat_account_number",
                    "type":"string"
                }
            },
            "required":[
                "account_type",
                "demat_account_number"
            ],
            "type":"object"
        }
    ]
}
</code>```

Body:
My current JSON schema definition is like this

{
  "properties": {
    "account_type": {
      "description": "account type",
      "enum": [
        "CURRENT",
        "SAVINGS",
        "DEMAT"
      ],
      "type": "string"
    },
    "demat_account_number": {
      "description": "demat_account_number",
      "type": "string"
    }
  },
  "required": [
    "account_type"
  ],
  "type": "object"
}

My requirement is if "account_type" = "DEMAT" then "demat_account_number" should become a required attribute.

Is there any way we can achieve this validation?

Body:
You can use "oneOf". This forces conforming documents to implement only one of a number of possible patterns:

{
    "oneOf":[
        {
            "properties":{
                "account_type":{
                    "description":"account type",
                    "enum":[
                        "CURRENT",
                        "SAVINGS"
                    ],
                    "type":"string"
                }
            },
            "required":[
                "account_type"
            ],
            "type":"object"
        },
        {
            "properties":{
                "account_type":{
                    "description":"account type",
                    "enum":[
                        "DEMAT"
                    ],
                    "type":"string"
                },
                "demat_account_number":{
                    "description":"demat_account_number",
                    "type":"string"
                }
            },
            "required":[
                "account_type",
                "demat_account_number"
            ],
            "type":"object"
        }
    ]
}


问:
An easy way to support tags in a jekyll blog
I am using the standard jekyll installation to maintain a blog, everything is going fine. Except I would really like to tag my posts.

I can tag a post using the YAML front matter, but how do I generate pages for each tag that can will list all posts for a tag?

答:
This gist will generate a page per category for you: https://gist.github.com/524748

It uses a Jekyll Generator plugin, plus a Page subclass.


问:
Filter Condition in Business Object BO
I have a problem with a filter condition in BO.
Imagine that I have this database

ID | DESC

0  |  None

1   | Company

2  |  All

In BO I have a filter that ask where do you want to find the objects and 2 options:

"Company" or "All".

If I choose "All" then I should have all the datas with the "ID" 0,1,2 and if I choose "Company" only the data with the "ID" 1.

So I did something like this:

TABLE_NAME.ID <= (CASE WHEN @Prompt('where do you want to find the objects','A',{'Company', 'All'},mono,constrained,not_persistent,{'Company'}) = 'Company' THEN 1  ELSE 2 END)

This filter is OK when I choose "All" because I have all the "ID" smaller than 2, i.e, 0,1,2.

But It does not work when my option is company, because it also shows the data with the "ID" 0.

I should have some with "=" combined with "<="

答:
If it's really only that simple, the following will work:</p>

```<code>TABLE_NAME.ID =
    (CASE @Prompt('where do you want to find the objects',
            'A',
            {'Company', 'All'},
            mono,
            constrained,
            not_persistent,{'Company'}
            )
          WHEN 'Company'
          THEN 1
          WHEN 'All'
          THEN TABLE_NAME.ID
          END)
</code>```

Title: Filter Condition in Business Object BO

Body:
If it's really only that simple, the following will work:

TABLE_NAME.ID =
    (CASE @Prompt('where do you want to find the objects',
            'A',
            {'Company', 'All'},
            mono,
            constrained,
            not_persistent,{'Company'}
            )
          WHEN 'Company'
          THEN 1
          WHEN 'All'
          THEN TABLE_NAME.ID
          END)


问:
PHP 1st while loop's output result as 2nd while loop's variable for query
Question 1: Is it possible to feed 1st while loop's output result as 2nd while loop's variable for query?

I have mySQL table "reorder_in_process" below:

```<code>(`id`, `item`, `to_order`, `cat_no`, `supplier`) VALUES
(48, 'Petri Dish', 62, 1006, 'Progressive'),
(47, 'Beaker', 46, 1005, 'Progressive'),
(46, 'Tissue', 17, 1008, 'Needpoint'),
(45, 'Pipet', 77, 1004, 'Kumpulan');
</code>```

And my php below:

```<code><?PHP
include ('db.php');
$sql4 = "SELECT DISTINCT supplier FROM reorder_in_process";
$result4 = mysqli_query($con,$sql4);
$supplier4 = $row4['supplier'];
$i=0;

while($row4 = mysqli_fetch_array($result4)){
echo "<h4>".$row4['supplier']."</h4>";

echo  "<div><table><tr>
                        <th>No</th>
                        <th>Item</th>
                        <th>Cat. No</th>
                        <th>Buy QTY</th>
                        <th>Supplier</th>
                    </tr>";
$sql5 = "SELECT * FROM reorder_in_process WHERE supplier=$supplier4";
$result5 = mysqli_query($con,$sql5);
while($row5 = mysqli_fetch_array($result5)) {
$i++;
    echo "<tr>
            <td>".$i. "</td>
           <td>".$row5['item']."</td>
           <td>".$row5['cat_no']."</td>
           <td>".$row5['to_order']."</td>
           <td>".$row5['supplier']."</td>
     </tr>";
}
echo "</table></div>";
}
mysqli_close($con);
?>
</code>```

I doesn't work...I want the output result like below:

```<code>Progressive
No  Item    Cat. No Buy QTY Supplier
1   Petri Dish  1006    62  Progressive
2   Beaker      1005    46  Progressive

Needpoint
No  Item    Cat. No Buy QTY Supplier
1   Tissue  1008    17  Needpoint

Kumpulan
No  Item    Cat. No Buy QTY Supplier
1   Pipet   1004    77  Kumpulan
</code>```

Pls help to find my mistake and solution to it. Thanks.

答:
You don't need to run two queries like that.

Instead of performing one query, just to query the same table again inside the loop, modify your structure such that you just query the table once. Just ORDER BY supplier and check if the current rows supplier differs from the last rows supplier. (Disclosure: I haven't fully tested this logic, it might need some tweaking).

```<code>$result = mysqli_query($con, "SELECT * FROM reorder_in_process ORDER BY supplier");
$first_iteration = true;
$current_supplier = null;

while($row = mysqli_fetch_assoc($result)){
    // If a new supplier is encountered, close the first table (if its no the first iteration) and add new header + start new table
    if ($row['supplier'] != $current_supplier) {
        if ($first_iteration == false)
            echo "</table></div>";

        $i = 1;
        $first_iteration = false;
        $current_supplier = $row['supplier'];
        echo "<h4>".$row['supplier']."</h4>";
        echo  "<div><table><tr>
                    <th>No</th>
                    <th>Item</th>
                    <th>Cat. No</th>
                    <th>Buy QTY</th>
                    <th>Supplier</th>
                </tr>";
    }

    echo "<tr>
                <td>".$i. "</td>
               <td>".$row['item']."</td>
               <td>".$row['cat_no']."</td>
               <td>".$row['to_order']."</td>
               <td>".$row['supplier']."</td>
         </tr>";
    $i++;
}
echo "</table></div>";
</code>```

Body:
Question 1: Is it possible to feed 1st while loop's output result as 2nd while loop's variable for query?

I have mySQL table "reorder_in_process" below:

(`id`, `item`, `to_order`, `cat_no`, `supplier`) VALUES
(48, 'Petri Dish', 62, 1006, 'Progressive'),
(47, 'Beaker', 46, 1005, 'Progressive'),
(46, 'Tissue', 17, 1008, 'Needpoint'),
(45, 'Pipet', 77, 1004, 'Kumpulan');

And my php below:

<?PHP
include ('db.php');
$sql4 = "SELECT DISTINCT supplier FROM reorder_in_process";
$result4 = mysqli_query($con,$sql4);
$supplier4 = $row4['supplier'];
$i=0;

while($row4 = mysqli_fetch_array($result4)){
echo "
".$row4['supplier']."
";

echo  "

                        No
                        Item
                        Cat. No
                        Buy QTY
                        Supplier

";
$sql5 = "SELECT * FROM reorder_in_process WHERE supplier=$supplier4";
$result5 = mysqli_query($con,$sql5);
while($row5 = mysqli_fetch_array($result5)) {
$i++;
    echo "

            ".$i. "
           ".$row5['item']."
           ".$row5['cat_no']."
           ".$row5['to_order']."
           ".$row5['supplier']."

";
}
echo "

";
}
mysqli_close($con);
?>

I doesn't work...I want the output result like below:

Progressive
No  Item    Cat. No Buy QTY Supplier
1   Petri Dish  1006    62  Progressive
2   Beaker      1005    46  Progressive

Needpoint
No  Item    Cat. No Buy QTY Supplier
1   Tissue  1008    17  Needpoint

Kumpulan
No  Item    Cat. No Buy QTY Supplier
1   Pipet   1004    77  Kumpulan

Pls help to find my mistake and solution to it. Thanks.

Body:
You don't need to run two queries like that.

Instead of performing one query, just to query the same table again inside the loop, modify your structure such that you just query the table once. Just ORDER BY supplier and check if the current rows supplier differs from the last rows supplier. (Disclosure: I haven't fully tested this logic, it might need some tweaking).

$result = mysqli_query($con, "SELECT * FROM reorder_in_process ORDER BY supplier");
$first_iteration = true;
$current_supplier = null;

while($row = mysqli_fetch_assoc($result)){
    // If a new supplier is encountered, close the first table (if its no the first iteration) and add new header + start new table
    if ($row['supplier'] != $current_supplier) {
        if ($first_iteration == false)
            echo "</table></div>";

        $i = 1;
        $first_iteration = false;
        $current_supplier = $row['supplier'];
        echo "<h4>".$row['supplier']."</h4>";
        echo  "<div><table><tr>
                    <th>No</th>
                    <th>Item</th>
                    <th>Cat. No</th>
                    <th>Buy QTY</th>
                    <th>Supplier</th>
                </tr>";
    }

    echo "<tr>
                <td>".$i. "</td>
               <td>".$row['item']."</td>
               <td>".$row['cat_no']."</td>
               <td>".$row['to_order']."</td>
               <td>".$row['supplier']."</td>
         </tr>";
    $i++;
}
echo "</table></div>";


问:
where to place python file when it execute with php?
i am finding problem in passing string from php to python code.i think my code is fine but may be in problem of path of python file.so suggest me where i have to place python file when it execute with php file.thank u so much in advance

here is my code:-

test.php

```<code><?php
$s= "what is your name";
$output= shell_exec('xampp/htdocs/fbchat/public/test.py ' .$s);
echo $output;
?>
</code>```

test.py

```<code>import sys
x= sys.argv[1]
print x
</code>```

答:
Try this:</p>

```<code>shell_exec('python xampp\\htdocs\\fbchat\\public\\test.py ' . $s);
</code>```

Body:
i am finding problem in passing string from php to python code.i think my code is fine but may be in problem of path of python file.so suggest me where i have to place python file when it execute with php file.thank u so much in advance

here is my code:-

test.php

<?php
$s= "what is your name";
$output= shell_exec('xampp/htdocs/fbchat/public/test.py ' .$s);
echo $output;
?>

test.py

import sys
x= sys.argv[1]
print x

Body:
Try this:

shell_exec('python xampp\\htdocs\\fbchat\\public\\test.py ' . $s);


问:
Can i extract a specific character from a string stored in a list?
str=['qIQNlQSLi', 'eOEKiVEYj', 'aZADnMCZq', 'bZUTkLYNg', 'uCNDeHSBj', 'kOIXdKBFh']

I want to extract the 5th index of each string in list i.e o/p is linked.

答:
List comprehensions should work for this. However you have to check whether your string has 5th index or not. Adding a sample code below.

```<code>str_list = ['qIQNlQSLi', 'eOEKiVEYj', 'aZADnMCZq', 'bZUTkLYNg', 'uCNDeHSBj', 'kOIXdKBFh']
return [item[5] for item in str_list if len(item) > 5]
</code>```

There is a lot you could do with List Comprehensions.

Body:
List comprehensions should work for this. However you have to check whether your string has 5th index or not. Adding a sample code below.

str_list = ['qIQNlQSLi', 'eOEKiVEYj', 'aZADnMCZq', 'bZUTkLYNg', 'uCNDeHSBj', 'kOIXdKBFh']
return [item[5] for item in str_list if len(item) > 5]

There is a lot you could do with List Comprehensions.


问:
Achieve smooth video scrubbing with AVPlayer
I am trying to achieve smooth video scrubbing with AVPlayer through UISlider I have searched and it seems Apple has a Technical Q&A and explained how to achieve this, but my problem is how should I use this method and change player current time with a UISlider:
stopPlayingAndSeekSmoothlyToTime(newChaseTime:CMTime)

Here is my code :

```<code>//Play Intro Movie
let videoURL = Bundle.main.url(forResource: "intro", withExtension: "mp4")
player = AVPlayer(url:videoURL!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.frame
view.layer.addSublayer(playerLayer)
//videoPlayer.play()

view.addSubview(slider)
slider.maximumValue = 0
slider.maximumValue = Float(CMTimeGetSeconds((player.currentItem?.asset.duration)!))
</code>```

Here is Apple sample code :

```<code>func stopPlayingAndSeekSmoothlyToTime(newChaseTime:CMTime)
    {
        player.pause()

        if CMTimeCompare(newChaseTime, chaseTime) != 0
        {
            chaseTime = newChaseTime;

            if !isSeekInProgress
            {
                trySeekToChaseTime()
            }
        }
    }

    func trySeekToChaseTime()
    {
        if playerCurrentItemStatus == .unknown
        {
            // wait until item becomes ready (KVO player.currentItem.status)
        }
        else if playerCurrentItemStatus == .readyToPlay
        {
            actuallySeekToTime()
        }
    }

    func actuallySeekToTime()
    {
        isSeekInProgress = true
        let seekTimeInProgress = chaseTime
        player.seek(to: seekTimeInProgress, toleranceBefore: kCMTimeZero,
                          toleranceAfter: kCMTimeZero, completionHandler:
            { (isFinished:Bool) -> Void in

                if CMTimeCompare(seekTimeInProgress, self.chaseTime) == 0
                {
                    self.isSeekInProgress = false
                }
                else
                {
                    self.trySeekToChaseTime()
                }
        })
    }
</code>```

答:
On slider value change event, just call the

stopPlayingAndSeekSmoothlyToTime(CMTime.init(seconds: (player.currentItem?.asset.duration.seconds)!* slider.value, preferredTimescale: 1000))

The Apples sample code will change the player current time. You can also adjust toleranceBefore and toleranceAfter if you scrub the slider really fast.

Body:
I am trying to achieve smooth video scrubbing with AVPlayer through UISlider I have searched and it seems Apple has a Technical Q&A and explained how to achieve this, but my problem is how should I use this method and change player current time with a UISlider:
stopPlayingAndSeekSmoothlyToTime(newChaseTime:CMTime)

Here is my code :

//Play Intro Movie
let videoURL = Bundle.main.url(forResource: "intro", withExtension: "mp4")
player = AVPlayer(url:videoURL!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.frame
view.layer.addSublayer(playerLayer)
//videoPlayer.play()

view.addSubview(slider)
slider.maximumValue = 0
slider.maximumValue = Float(CMTimeGetSeconds((player.currentItem?.asset.duration)!))

Here is Apple sample code :

func stopPlayingAndSeekSmoothlyToTime(newChaseTime:CMTime)
    {
        player.pause()

        if CMTimeCompare(newChaseTime, chaseTime) != 0
        {
            chaseTime = newChaseTime;

            if !isSeekInProgress
            {
                trySeekToChaseTime()
            }
        }
    }

    func trySeekToChaseTime()
    {
        if playerCurrentItemStatus == .unknown
        {
            // wait until item becomes ready (KVO player.currentItem.status)
        }
        else if playerCurrentItemStatus == .readyToPlay
        {
            actuallySeekToTime()
        }
    }

    func actuallySeekToTime()
    {
        isSeekInProgress = true
        let seekTimeInProgress = chaseTime
        player.seek(to: seekTimeInProgress, toleranceBefore: kCMTimeZero,
                          toleranceAfter: kCMTimeZero, completionHandler:
            { (isFinished:Bool) -> Void in

                if CMTimeCompare(seekTimeInProgress, self.chaseTime) == 0
                {
                    self.isSeekInProgress = false
                }
                else
                {
                    self.trySeekToChaseTime()
                }
        })
    }


问:
How to parse separate json arrays inside existing json in php?
Let me describe in detail, I have a json as below :

```<code>{
    "client_id": 1234,
    "rawdata": [{
        "task_id1": {
            "apikey1": "1234",
            "flow": "ssp",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        },
        "task_id2": {
            "apikey2": "1235",
            "flow": "mobileweb",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        }
    }]

}
</code>```

What I want is separate rawdata in json only . There can be n numbers of rawdata data . I need to iterate & segregate based on task id .

I am stuck  cannot proceed till now what I wrote :

```<code><?php

require_once 'execute_query.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rawdata = file_get_contents("php://input");
    $array=json_decode($rawdata, true);
}
var_dump ($array);
$clientId= $array[client_id];
echo $clientId;
//print_r(array_keys($array));
?>
</code>```

So to brief :

Input is :

```<code>{
    "client_id": 1234,
    "rawdata": [{
        "task_id1": {
            "apikey1": "1234",
            "flow": "ssp",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        },
        "task_id2": {
            "apikey2": "1235",
            "flow": "mobileweb",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        }
    }]

}
</code>```

Output :  There are two taskids & there respective json are

```<code>{
"task_id1": {
    "apikey1": "1234",
    "flow": "ssp",
    "total_chocolate_request": 43235,
    "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
    "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
}
</code>```

and

```<code>{

"task_id2": {
                "apikey2": "1235",
                "flow": "mobileweb",
                "total_chocolate_request": 43235,
                "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
                "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
            }
</code>```

答:
This is real easy. JSON decode into an array. Grab what you need. You can json_encode() back if you need to.

```<code>$array = json_decode($json, true);

$rawDatas = $array['rawdata'][0];

foreach($rawDatas as $key =>$data) {
    echo $key."\n......\n";
    var_dump($data);
    echo "............\n";
}
</code>```

See it in action here: https://3v4l.org/bF9mt

Body:
Let me describe in detail, I have a json as below :

{
    "client_id": 1234,
    "rawdata": [{
        "task_id1": {
            "apikey1": "1234",
            "flow": "ssp",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        },
        "task_id2": {
            "apikey2": "1235",
            "flow": "mobileweb",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        }
    }]

}

What I want is separate rawdata in json only . There can be n numbers of rawdata data . I need to iterate & segregate based on task id .

I am stuck  cannot proceed till now what I wrote :

<?php

require_once 'execute_query.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rawdata = file_get_contents("php://input");
    $array=json_decode($rawdata, true);
}
var_dump ($array);
$clientId= $array[client_id];
echo $clientId;
//print_r(array_keys($array));
?>

So to brief :

Input is :

{
    "client_id": 1234,
    "rawdata": [{
        "task_id1": {
            "apikey1": "1234",
            "flow": "ssp",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        },
        "task_id2": {
            "apikey2": "1235",
            "flow": "mobileweb",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        }
    }]

}

Output :  There are two taskids & there respective json are

{
"task_id1": {
    "apikey1": "1234",
    "flow": "ssp",
    "total_chocolate_request": 43235,
    "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
    "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
}

and

{

"task_id2": {
                "apikey2": "1235",
                "flow": "mobileweb",
                "total_chocolate_request": 43235,
                "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
                "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
            }

Body:
This is real easy. JSON decode into an array. Grab what you need. You can json_encode() back if you need to.

$array = json_decode($json, true);

$rawDatas = $array['rawdata'][0];

foreach($rawDatas as $key =>$data) {
    echo $key."\n......\n";
    var_dump($data);
    echo "............\n";
}

See it in action here: https://3v4l.org/bF9mt


问:
Windows: Determine domain name from cmd
If I don't know if computer is in domain or not, and I don't know the workstations name, Is it possible to determine if the user(for example jack which is not the user I'm logged in) is domain username or local username from command line? I've searched to find the answer but all I got is to check the USERDOMAIN variable?

答:
```<code>wmic useraccount get localaccount,name
</code>```

or to be specific to a certain user:

```<code>wmic useraccount where "name='Gast'" get localaccount
</code>```

To get it into a variable:

```<code>for /f %%a in ('wmic useraccount where "name='Gast'" get localaccount /value^|find "="') do set %%a
echo %localaccount%
</code>```

(Note: this is syntax for batchfile. If you want to execute on command line, replace every %%a with %a)

Title: Windows: Determine domain name from cmd

Body:
wmic useraccount get localaccount,name

or to be specific to a certain user:

wmic useraccount where "name='Gast'" get localaccount

To get it into a variable:

for /f %%a in ('wmic useraccount where "name='Gast'" get localaccount /value^|find "="') do set %%a
echo %localaccount%

(Note: this is syntax for batchfile. If you want to execute on command line, replace every %%a with %a)