问:
Pass array by reference to Laravel Event Listener
I have an array in Laravel applications that I would like to modify in Laravel listener. PHP by default passes an array by value however, the way Laravel events and its listeners work I am unable to modify the original variable. Is there a better way than what I am doing below?

The Model where the event is fired from.

Model: Event.php

```<code>namespace Vendor\Package\Models

use Vendor\Package\Events\PageNodeArrayAfter;
use Event;

class Page
{
   public function toArray()
   {
      $data = [];

      // do something with the data.

      Event::fire(new PageNodeToArrayAfter($data))

      // The data should be modified by a listener when I use it here.
   }
}
</code>```

Event: PageNodeToArrayAfter.php

```<code>namespace Vendor\Package\Events;

class PageNodeToArrayAfter
{
    /**
     * Props to be sent to the view
     * @var array $data
     */
    protected $data = [];

    /**
     * @param array $data
     *
     */
    public function __construct(array &$data)
    {
        $this->data = $data;
    }

    public function getData()
    {
        return $this->data;
    }
}
</code>```

Listener: FlashMessagesListner.php

```<code>namespace Vendor\Package\Listeners;

class FlashMessagesListner
{
    protected $data = [];

    public function handle(PageNodeToArrayAfter $event)
    {
       $this->data = $event->getData();
       // The problem here is the $data is no logner a reference here.
    }
}
</code>```

答:
Based on the documentation for the array this is what it says:

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

So change your constructor to this instead:

```<code>// prepend the argument with the reference operator &
public function __construct(array &$data)
</code>```

Body:
I have an array in Laravel applications that I would like to modify in Laravel listener. PHP by default passes an array by value however, the way Laravel events and its listeners work I am unable to modify the original variable. Is there a better way than what I am doing below?

The Model where the event is fired from.

Model: Event.php

namespace Vendor\Package\Models

use Vendor\Package\Events\PageNodeArrayAfter;
use Event;

class Page
{
   public function toArray()
   {
      $data = [];

      // do something with the data.

      Event::fire(new PageNodeToArrayAfter($data))

      // The data should be modified by a listener when I use it here.
   }
}

Event: PageNodeToArrayAfter.php

namespace Vendor\Package\Events;

class PageNodeToArrayAfter
{
    /**
     * Props to be sent to the view
     * @var array $data
     */
    protected $data = [];

    /**
     * @param array $data
     *
     */
    public function __construct(array &$data)
    {
        $this->data = $data;
    }

    public function getData()
    {
        return $this->data;
    }
}

Listener: FlashMessagesListner.php

namespace Vendor\Package\Listeners;

class FlashMessagesListner
{
    protected $data = [];

    public function handle(PageNodeToArrayAfter $event)
    {
       $this->data = $event->getData();
       // The problem here is the $data is no logner a reference here.
    }
}

Body:
Based on the documentation for the array this is what it says:

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

So change your constructor to this instead:

// prepend the argument with the reference operator &
public function __construct(array &$data)


来源: stackexchange

问:
How to show online offline user status in pubnub using swift 4?
```<code>client.setState(["is_online": true,"user_id":uuid], forUUID: userId as! String, onChannel: "channelName") { (status) in
    if !status.isError {
      print(status)
    }
}
</code>```

答:
User presence functionality can be implemented using the PubNub Presence feature. Go to your PubNub Admin Dashboard and enable the presence feature for your API keys.

Now on the client side you can check which users are online with the whereNowUUID method, which is described thoroughly in the Swift PubNub Presence Documentation

```<code>self.client.whereNowUUID(self.client.uuid(), withCompletion: { (result, status) in

    if status == nil {

        // Handle downloaded presence 'where now' information using: result.data.channels
    }
    else {

        /**
         Handle presence audit error. Check 'category' property
         to find out possible reason because of which request did fail.
         Review 'errorData' property (which has PNErrorData data type) of status
         object to get additional information about issue.

         Request can be resent using: status.retry()
         */
    }
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
User presence functionality can be implemented using the PubNub Presence feature. Go to your PubNub Admin Dashboard and enable the presence feature for your API keys.

Now on the client side you can check which users are online with the whereNowUUID method, which is described thoroughly in the Swift PubNub Presence Documentation

self.client.whereNowUUID(self.client.uuid(), withCompletion: { (result, status) in

    if status == nil {

        // Handle downloaded presence 'where now' information using: result.data.channels
    }
    else {

        /**
         Handle presence audit error. Check 'category' property
         to find out possible reason because of which request did fail.
         Review 'errorData' property (which has PNErrorData data type) of status
         object to get additional information about issue.

         Request can be resent using: status.retry()
         */
    }
})


问:
PHPSpec - fail to run, anyone using it for php development?
Searched stackoverflow for this and found no answer

Coming from Ruby On Rails and Rspec, I need a tool like rspec (easier transition). Installed it through PEAR and tried to run it but it's not working (yet)

Just wanna ask around if anyone's using it have the same problem, since it's not running at all

tried running it with an example from the manual - http://dev.phpspec.org/manual/en/before.writing.code.specify.its.required.behaviour.html

```<code>phpspec NewFileSystemLoggerSpec
</code>```

returns nothing

even running

```<code>phpspec some_dummy_value
</code>```

returns nothing

答: Hello its pretty old Q. in deed, but i think http://behat.org/ should be here. Everyone has this problem should check it out.</p>

OwnerDisplayName: Ed

ContentLicense: CC BY-SA 2.5

Body:
Searched stackoverflow for this and found no answer

Coming from Ruby On Rails and Rspec, I need a tool like rspec (easier transition). Installed it through PEAR and tried to run it but it's not working (yet)

Just wanna ask around if anyone's using it have the same problem, since it's not running at all

tried running it with an example from the manual - http://dev.phpspec.org/manual/en/before.writing.code.specify.its.required.behaviour.html

phpspec NewFileSystemLoggerSpec

returns nothing

even running

phpspec some_dummy_value

returns nothing

ContentLicense: CC BY-SA 3.0


问:
I am not sure why I am getting output for this?
I was learning some string handling in C++ and was doing hit and trail on a code and surprisingly got output for the given code.

```<code>#include<bits/stdc++.h>
using namespace std;
int main(){
    char str[12]={'\67','a','v','i'};
    cout<<str;
    return 0;
}
</code>```

Surprisingly I get 7avi printed .

But if I replace '\67' with '\68'. The following error is shown on Repl.it (https://repl.it/languages/cpp)

```<code>#include<bits/stdc++.h>

using namespace std;

int main(){
    char str[12]={'\68','a','v','i'};
    cout<<str;
    return 0;
}

main.cpp:6:19: warning: multi-character character constant [-Wmultichar]
    char str[12]={'\68','a','v','i'};
                  ^
main.cpp:6:19: error: constant expression evaluates to 1592 which cannot
      be narrowed to type 'char' [-Wc++11-narrowing]
    char str[12]={'\68','a','v','i'};
                  ^~~~~
main.cpp:6:19: note: insert an explicit cast to silence this issue
    char str[12]={'\68','a','v','i'};
                  ^~~~~
                  static_cast<char>( )
main.cpp:6:19: warning: implicit conversion from 'int' to 'char' changes
      value from 1592 to 56 [-Wconstant-conversion]
    char str[12]={'\68','a','v','i'};
                 ~^~~~~
2 warnings and 1 error generated.
compiler exit status 1
</code>```

Please someone explain this behavior.

答:
The \nnn notation, where nnn are digits between 0 and 7, is for octal (base 8) notation.  So in \68, 68 is not a valid octal number.  The number one more than 67 is 70.  The way it's interpreting the code is that you have '\6' as character 6 in octal, but then an additional '8' ASCII character inside your character literal - hence a multi-character constant, which can not be stored in a char variable.  You could store it in a "wide character":

```<code>wchar_t str[12]={'\68','a','v','i'};
</code>```

But, there is no operator<< overload to display an array of wchar_t, so your cout << str line will match the void* overload and just display the memory address of the first element in the array, rather than any of the characters themselves.

You can fix that using:

```<code>wcout << str;
</code>```

Separately, I recommend putting a newline after your output too.  Without it, your output may be overwritten by the console prompt before you can see it, though that doesn't happen in the online REPL you're using.  It should look like:

```<code>wcout << str << '\n';
</code>```

Body:
I was learning some string handling in C++ and was doing hit and trail on a code and surprisingly got output for the given code.

#include<bits/stdc++.h>
using namespace std;
int main(){
    char str[12]={'\67','a','v','i'};
    cout<<str;
    return 0;
}

Surprisingly I get 7avi printed .

But if I replace '\67' with '\68'. The following error is shown on Repl.it (https://repl.it/languages/cpp)

#include<bits/stdc++.h>

using namespace std;

int main(){
    char str[12]={'\68','a','v','i'};
    cout<<str;
    return 0;
}

main.cpp:6:19: warning: multi-character character constant [-Wmultichar]
    char str[12]={'\68','a','v','i'};
                  ^
main.cpp:6:19: error: constant expression evaluates to 1592 which cannot
      be narrowed to type 'char' [-Wc++11-narrowing]
    char str[12]={'\68','a','v','i'};
                  ^~~~~
main.cpp:6:19: note: insert an explicit cast to silence this issue
    char str[12]={'\68','a','v','i'};
                  ^~~~~
                  static_cast<char>( )
main.cpp:6:19: warning: implicit conversion from 'int' to 'char' changes
      value from 1592 to 56 [-Wconstant-conversion]
    char str[12]={'\68','a','v','i'};
                 ~^~~~~
2 warnings and 1 error generated.
compiler exit status 1

Please someone explain this behavior.

Body:
The \nnn notation, where nnn are digits between 0 and 7, is for octal (base 8) notation.  So in \68, 68 is not a valid octal number.  The number one more than 67 is 70.  The way it's interpreting the code is that you have '\6' as character 6 in octal, but then an additional '8' ASCII character inside your character literal - hence a multi-character constant, which can not be stored in a char variable.  You could store it in a "wide character":

wchar_t str[12]={'\68','a','v','i'};

But, there is no operator<< overload to display an array of wchar_t, so your cout << str line will match the void* overload and just display the memory address of the first element in the array, rather than any of the characters themselves.

You can fix that using:

wcout << str;

Separately, I recommend putting a newline after your output too.  Without it, your output may be overwritten by the console prompt before you can see it, though that doesn't happen in the online REPL you're using.  It should look like:

wcout << str << '\n';


问:
Carbon Design Systems UI Shell component is not working in Code Pen
I am trying to use the Carbon Design's UI Shell component in CodePen.

The code for the component is here and the UI looks like this:

```<code><header class="bx--header" role="banner" aria-label="IBM Platform Name" data-header>
 <a class="bx--skip-to-content" href="#main-content" tabindex="0">Skip to main content</a>
  <button class="bx--header__menu-trigger bx--header__action" aria-label="Open menu" title="Open menu"
data-navigation-menu-panel-label-expand="Open menu" data-navigation-menu-panel-label-collapse="Close menu"
data-navigation-menu-target="#navigation-menu-fthewlqilpo">
<svg focusable="false" preserveAspectRatio="xMidYMid meet" style="will-change: transform;" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" class="bx--navigation-menu-panel-collapse-icon" width="20" height="20" viewBox="0 0 32 32"><path d="M24 9.4L22.6 8 16 14.6 9.4 8 8 9.4l6.6 6.6L8 22.6 9.4 24l6.6-6.6 6.6 6.6 1.4-1.4-6.6-6.6L24 9.4z"></path></svg>
<svg focusable="false" preserveAspectRatio="xMidYMid meet" style="will-change: transform;" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" class="bx--navigation-menu-panel-expand-icon" width="20" height="20" viewBox="0 0 20 20"><path d="M2 14.8h16V16H2zm0-3.6h16v1.2H2zm0-3.6h16v1.2H2zM2 4h16v1.2H2z"></path></svg>
</button>
...
<!-- the rest of the code can be seen in Code Pen -->
</code>```

But when I copy the code into the CodePen, the output looks like the css is missing:

What is a way to fix it?

答:
You forgot a few things in the setup, namely adding the CDN and setting the CSS and javascript preprocessors.

You can read more about how to add the CDN here
https://www.carbondesignsystem.com/getting-started/developers/vanilla

What's cool though is this company already made a bunch of codepens for you to test out. This may help!

https://codepen.io/collection/XqRbEz/

The first example makes a header just like your codepen, the difference is they use their cloud header

```<code><nav class="bx--cloud-header">
</code>```

I would suggest you fork one of the existing codepens so that you can use their setup to run any other tests that you would like.

In this example, you can see that they do have a hamburger within their header.
https://codepen.io/team/carbon/pen/LedzoM

Personally I work with layouts like this that already have the implemented burger component.
https://vuetifyjs.com/en/examples/layouts/googleContacts

I also work alot with these tried and tested templates. They are all done in HTML and CSS. This man is a genius.
https://html5up.net/

Body:
I am trying to use the Carbon Design's UI Shell component in CodePen.

The code for the component is here and the UI looks like this:

 Skip to main content
  <button class="bx--header__menu-trigger bx--header__action" aria-label="Open menu" title="Open menu"
data-navigation-menu-panel-label-expand="Open menu" data-navigation-menu-panel-label-collapse="Close menu"
data-navigation-menu-target="#navigation-menu-fthewlqilpo">
<svg focusable="false" preserveAspectRatio="xMidYMid meet" style="will-change: transform;" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" class="bx--navigation-menu-panel-collapse-icon" width="20" height="20" viewBox="0 0 32 32"><path d="M24 9.4L22.6 8 16 14.6 9.4 8 8 9.4l6.6 6.6L8 22.6 9.4 24l6.6-6.6 6.6 6.6 1.4-1.4-6.6-6.6L24 9.4z"></path></svg>
<svg focusable="false" preserveAspectRatio="xMidYMid meet" style="will-change: transform;" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" class="bx--navigation-menu-panel-expand-icon" width="20" height="20" viewBox="0 0 20 20"><path d="M2 14.8h16V16H2zm0-3.6h16v1.2H2zm0-3.6h16v1.2H2zM2 4h16v1.2H2z"></path></svg>
</button>
...

But when I copy the code into the CodePen, the output looks like the css is missing:

What is a way to fix it?

Body:
You forgot a few things in the setup, namely adding the CDN and setting the CSS and javascript preprocessors.

You can read more about how to add the CDN here
https://www.carbondesignsystem.com/getting-started/developers/vanilla

What's cool though is this company already made a bunch of codepens for you to test out. This may help!

https://codepen.io/collection/XqRbEz/

The first example makes a header just like your codepen, the difference is they use their cloud header

<nav class="bx--cloud-header">

I would suggest you fork one of the existing codepens so that you can use their setup to run any other tests that you would like.

In this example, you can see that they do have a hamburger within their header.
https://codepen.io/team/carbon/pen/LedzoM

Personally I work with layouts like this that already have the implemented burger component.
https://vuetifyjs.com/en/examples/layouts/googleContacts

I also work alot with these tried and tested templates. They are all done in HTML and CSS. This man is a genius.
https://html5up.net/


问:
Is it possible change the way to show push notifications with firebase
I have an android app with react native. Recently I add firebase messaging to the project for push notifications. It works perfectly. But I want to show the push notification with image, title, and description in the background (app close or second plane). This is easy to make in the foreground but in background I guess that I need to change some .java files. I don't know do that.

Somebody did it before?

答: Yes you can do that, if you are sending push notification from server, firebase also provide options for image, title or descriptions which you can show in a push notification</p>


问:
Flex positionning in CSS
I'm creating a React Native application and I would like to use flex to structure the positionning of my elements on the screen. Considering that we have the following screen: the red zone got a flex-grow value of 1, the yellow zone 2 and the green zone 3. They all have a parent with a display: flex and flex-grow: 1. (This is React Native so default flex-direction is column).

My question is the following: What if there is no green zone? How could I tell flex to take 1/6 of the parent for the red zone, 2/6 for the yellow zone and leave the rest empty ?

答:
I was able to achieve the layout you described by applying flex-grow: 0 and flex-shrink: 0 to the flex items. By setting the flex-basis to the appropriate percentages the layout holds up with or without the presence of the third div.

.wrapper {
  display: flex;
  flex-flow: column nowrap;
  height: 100vh;
}
.one {
  flex: 0 0 16.666%; /* dont grow, dont shrink, starting basis */
  background: red;
}
.two {
  flex: 0 0 33.333%; /* dont grow, dont shrink, starting basis */
  background: yellow;
}
.three {
  flex: 0 0 50%; /* dont grow, dont shrink, starting basis */
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="one">ONE</div>
  <div class="two">TWO</div>
  <div class="three">THREE</div>
</div></code>```

This time I omit the third div and we get the same layout:

.wrapper {
  display: flex;
  flex-flow: column nowrap;
  height: 100vh;
}
.one {
  flex: 0 0 16.666%; /* dont grow, dont shrink, starting basis */
  background: red;
}
.two {
  flex: 0 0 33.333%; /* dont grow, dont shrink, starting basis */
  background: yellow;
}
.three {
  flex: 0 0 50%; /* dont grow, dont shrink, starting basis */
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="one">ONE</div>
  <div class="two">TWO</div>
</div></code>```

Title: Flex positionning in CSS

Body:
I was able to achieve the layout you described by applying flex-grow: 0 and flex-shrink: 0 to the flex items. By setting the flex-basis to the appropriate percentages the layout holds up with or without the presence of the third div.

.wrapper {
  display: flex;
  flex-flow: column nowrap;
  height: 100vh;
}
.one {
  flex: 0 0 16.666%; /* dont grow, dont shrink, starting basis */
  background: red;
}
.two {
  flex: 0 0 33.333%; /* dont grow, dont shrink, starting basis */
  background: yellow;
}
.three {
  flex: 0 0 50%; /* dont grow, dont shrink, starting basis */
  background: green;
}

<div class="wrapper">
  <div class="one">ONE</div>
  <div class="two">TWO</div>
  <div class="three">THREE</div>
</div>

This time I omit the third div and we get the same layout:

.wrapper {
  display: flex;
  flex-flow: column nowrap;
  height: 100vh;
}
.one {
  flex: 0 0 16.666%; /* dont grow, dont shrink, starting basis */
  background: red;
}
.two {
  flex: 0 0 33.333%; /* dont grow, dont shrink, starting basis */
  background: yellow;
}
.three {
  flex: 0 0 50%; /* dont grow, dont shrink, starting basis */
  background: green;
}

<div class="wrapper">
  <div class="one">ONE</div>
  <div class="two">TWO</div>
</div>


问:
How to prevent tkinter from generating duplicating windows
I am using TKInter to create a window that display some information, something like a notice. The window should show up when the 'View Details" button of the main application is clicked.

Here is the code of the window i was talking about. The Categories() method is called when the above mentioned button is clickd.

from tkinter import *
from tkinter import ttk

def Categories():

    roots = Tk()
    roots.minsize(600, 600)
    roots.title("Category Details")

    labelFrameCategory = ttk.LabelFrame(roots,text="Financial")
    labelFrameCategory.configure()
    labelFrameCategory.grid(column=0 ,row=0, pady=10, padx = 30 , sticky = W)

    labelClass = Label(labelFrameCategory, text="Documents related to finance")
    labelClass.grid(column=0, row=1)
    labelClass.config(font=("Courier", 15))

    roots.resizable(False, False)
    roots.mainloop()

```

The problem I have is every time I press the button, it creates a new window but leaves the current window open. So If I click 10 times, it will open 10 similar windows. But I want it to open only 1 window no matter how many times the button is clicked, there should be only 1 such window. How to do that ?

答:
It looks like your function Categories is invoked from a button command of another Tk instance. Generally you want to avoid creating more than 1 instance of Tk.

For your question, there are many ways to do it. One way is to simply disable your button command upon click, and re-activate the command upon the window destroy:

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()

def new_window():
    a.config(command="")
    roots = tk.Toplevel() #Use Toplevel instead if you simply want another window
    roots.minsize(600, 600)
    roots.title("Category Details")

    labelFrameCategory = ttk.LabelFrame(roots,text="Financial")
    labelFrameCategory.configure()
    labelFrameCategory.grid(column=0 ,row=0, pady=10, padx = 30 , sticky = tk.W)

    labelClass = tk.Label(labelFrameCategory, text="Documents related to finance")
    labelClass.grid(column=0, row=1)
    labelClass.config(font=("Courier", 15))

    roots.resizable(False, False)

    def quit_window():
        a.config(command=new_window)
        roots.destroy()

    roots.protocol("WM_DELETE_WINDOW",quit_window)

a = tk.Button(root,text="Click to open new win",command=new_window)
a.pack()

root.mainloop()
</code>```

Alternatively you can also set a flag like window_open=True and check for the flag.

Body:
I am using TKInter to create a window that display some information, something like a notice. The window should show up when the 'View Details" button of the main application is clicked.

Here is the code of the window i was talking about. The Categories() method is called when the above mentioned button is clickd.

from tkinter import *
from tkinter import ttk

def Categories():

    roots = Tk()
    roots.minsize(600, 600)
    roots.title("Category Details")

    labelFrameCategory = ttk.LabelFrame(roots,text="Financial")
    labelFrameCategory.configure()
    labelFrameCategory.grid(column=0 ,row=0, pady=10, padx = 30 , sticky = W)

    labelClass = Label(labelFrameCategory, text="Documents related to finance")
    labelClass.grid(column=0, row=1)
    labelClass.config(font=("Courier", 15))

    roots.resizable(False, False)
    roots.mainloop()

The problem I have is every time I press the button, it creates a new window but leaves the current window open. So If I click 10 times, it will open 10 similar windows. But I want it to open only 1 window no matter how many times the button is clicked, there should be only 1 such window. How to do that ?

Body:
It looks like your function Categories is invoked from a button command of another Tk instance. Generally you want to avoid creating more than 1 instance of Tk.

For your question, there are many ways to do it. One way is to simply disable your button command upon click, and re-activate the command upon the window destroy:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

def new_window():
    a.config(command="")
    roots = tk.Toplevel() #Use Toplevel instead if you simply want another window
    roots.minsize(600, 600)
    roots.title("Category Details")

    labelFrameCategory = ttk.LabelFrame(roots,text="Financial")
    labelFrameCategory.configure()
    labelFrameCategory.grid(column=0 ,row=0, pady=10, padx = 30 , sticky = tk.W)

    labelClass = tk.Label(labelFrameCategory, text="Documents related to finance")
    labelClass.grid(column=0, row=1)
    labelClass.config(font=("Courier", 15))

    roots.resizable(False, False)

    def quit_window():
        a.config(command=new_window)
        roots.destroy()

    roots.protocol("WM_DELETE_WINDOW",quit_window)

a = tk.Button(root,text="Click to open new win",command=new_window)
a.pack()

root.mainloop()

Alternatively you can also set a flag like window_open=True and check for the flag.


问:
What is the quickest way from a concept to a site?
I've got a bunch of website ideas and I was wondering what is the quickest way to get from a pretty thorough concept definition (idea mind-maps, use-cases, architecture diagrams ) to a working website. The only point is to get to something that's functional, not worrying about performance. The idea is to get something out to showcase a functional site, and after worry about fine-tuning or re-writing parts if necessary.

I am familiar with quite a few web frameworks from open-source and proprietary world, but I could not find so far a swiss-army-knife of web development environments that can get you fast from a concept to a working site.  I was kinda wondering if there is such a thing, free or non-free

Looking forward to your suggestions...

UPDATE: The question might get a bit too metaphoric for the kind readers of this site, but I'm at a moment where I feel that implementation details are killing my creativity ... maybe you'll laugh or you'll feel offended, I'm just wondering if anyone can give me a useful hint..

答:
Assuming your site is sufficiently unique enough that it cannot be done with something off the shelf (CMS, blog, open source, etc) then your next best bet to get the site done quickly is to use a programming framework such as asp.net, RoR, Django, Wicket.  You mentioned Coldfusion and that's a possibility too.

Which framework you use depends on you.  In many cases the framework will have ways to cut down development time by giving you functionality in controls/functions or generating code for you.  asp.net has a dynamic data scaffolding-like feature that will build a generic "admin" interface for your database.

Another way to speed up development time is to use an IDE that uses a GUI to build your site.  Some IDEs like this include Dreamweaver and Visual Studio.net (or Visual Web Developer).  Using these IDEs you can build your site almost without touching any code.

OwnerDisplayName: Cip

OwnerDisplayName: webdtc


问:
How do I create a Symfony validator that needs to access other fields values?
I want to implement a Symfony validator that validates passwords for a registration form, which means I want a 'Password confirm' field. How do I make a validator that somehow ties these fields together? I need to check if the password and password confirm values match.

How are stuff like these implemented properly in Symfony?

答: You can use a postValidator . Check the documentation, there is an example with the password confirm validation.</p>


问:
How to open/run .jar file (double-click not working)?
I can't open or run my .jar file.

I just installed java, but I tried to open the .jar with other programs first, so the double-click defaults to something else and I can't change it back.

```<code>java -jar myfile.jar`
</code>```

Above command returns:

'java' is not recognized as an internal or external command, operable program or batch file.

Is there a way I can still open/run this?

e: OS is Windows 8.

Also, I downloaded the .jar file; didn't create it myself (if that's relevant)
Not sure if it contains an executable (but I think it does).

答:
You may have several JDKs installed in your PC. Some older JDK installers also copy some java files such as java.exe, javaw.exe into C:\Windows\System32 folder.

I had a similar issue, and searched the internet for a solution and none of the suggestions didn’t open by double clicking the .jar file.

In my case the reason is I have multiple JDK & JRE versions installed on my computer. Since I am a software developer working with several different versions for different clients I need to use multiple JDKs in my PC (Windows 10 Pro). So I do not want to change the system variables (i.e. JAVA_HOME, JRE_HOME or PATH), instead I use command prompt to run java in user process whenever I wanted to use a different version.

When installing JDK it registers the .jar file association with latest version we installed in the PC. If you right click on the .jar icon and select properties, it will show that file opens with “Java(TM) Platform SE Binary”.  If we look at the registry key: HKEY_CLASSES_ROOT\jarfile\shell\open\command, it will point to latest JDK version.

It is not a good idea (sometimes annoying) to change the registry key every time I want to run an app build from a different version.

So in my situation it is impossible to just double click the .jar file to execute it. But instead I found a work around solution myself.

Scenario:

Multiple JDKs (1.7, 1.8, 9.0, 10.0, 11.0, and 12.0)are installed in the PC, so the latest installed was 12.0.

Problem

Want to double click an executable .jar developed using JDK 1.8 and didn’t work

This is my work around solution:

Create a shortcut for the .jar file that you want to open.

Right click the shortcut icon and select properties -> Shortcut tab

Change the text in the target (for example "D:\Dev\JavaApp1.8.jar")
To

"C:\Program Files\Java\jdk1.8.0\bin\javaw.exe" -jar
"D:\Dev\JavaApp1.8.jar"

Then click ok Double click the shortcut.

It should now open the app.

Body:
I can't open or run my .jar file.

I just installed java, but I tried to open the .jar with other programs first, so the double-click defaults to something else and I can't change it back.

java -jar myfile.jar`

Above command returns:

'java' is not recognized as an internal or external command, operable program or batch file.

Is there a way I can still open/run this?

e: OS is Windows 8.

Also, I downloaded the .jar file; didn't create it myself (if that's relevant)
Not sure if it contains an executable (but I think it does).


问:
How to get latest data inserted in mySQL?
I have this kind of table:

```<code>ID        NUMBER     DATE_INPUT
 A             1     2019-05-26
 A             2     2019-05-27
 A             0     2019-05-28
 B             0     2019-05-27
 B             1     2019-05-28
</code>```

I use GROUP BY to get group the data and the result is:

```<code> ID        NUMBER     DATE_INPUT
 A             1     2019-05-26
 B             0     2019-05-27
</code>```

The desired output is:

```<code> ID        NUMBER     DATE_INPUT
 A             0     2019-05-28
 B             1     2019-05-28
</code>```

答:
use order by desc

```<code>select * from tablename group by ID order by date_input desc
</code>```

With order by all new date will desc so new one will appear first

Body:
I have this kind of table:

ID        NUMBER     DATE_INPUT
 A             1     2019-05-26
 A             2     2019-05-27
 A             0     2019-05-28
 B             0     2019-05-27
 B             1     2019-05-28

I use GROUP BY to get group the data and the result is:

 ID        NUMBER     DATE_INPUT
 A             1     2019-05-26
 B             0     2019-05-27

The desired output is:

 ID        NUMBER     DATE_INPUT
 A             0     2019-05-28
 B             1     2019-05-28

Body:
use order by desc

select * from tablename group by ID order by date_input desc

With order by all new date will desc so new one will appear first


问:
How upload image in angular 7 from backend
i can upload image with postman but in angular it doesn't work for me. solution please

error : cannot read originalname of undefined , in nodejs but with
  postman its work !

//backend

```<code>var express = require("express")
var router = express.Router();
var userModel = require("../models/userModel")
const jwt= require("jsonwebtoken")
const  bcrypt=require("bcrypt")
var app=express()
var io = require('socket.io-client')('http://localhost:3000/alll')

var  socket = require("socket.io");

var fs=require("fs")
var multer=require("multer")
const upload = multer({dest: __dirname + '/upload/images'});

router.post('/uploads', upload.single('image'), function (req, res) {
  var file = __dirname + '/upload' + req.file.originalname;
  fs.readFile(req.file.path, function (err, data) {
    fs.writeFile(file, data, function (err) {
      if (err) {
        console.error(err);
        var response = {
          message: 'Sorry, file couldn\'t be uploaded.',
          filename: req.file.originalname
        };
      } else {
        response = {
          message: 'File uploaded successfully',
          filename: req.file.originalname
        };
        res.json(response);
      }
    })
  })
})
router.post("/add",function (req, res) {

        user = new userModel({firstName: req.body.firstName,
          lastName: req.body.lastName ,
          email:req.body.email ,
          password:req.body.password,
          adresse:req.body.adresse,
          verif:'1',role :'user',
          annonces:req.body.annonces,
          pdf: req.body.pdf
        })
        user.save(function(err) {
          if (err) {
            res.send({"state": "not ok", "msg": "err:" + err})
          } else {
            res.send({"state": " ok", "msg": "ajout"})
          }

        })
})
// model : pdf as String
</code>```

//ts

```<code>import {ChangeDetectorRef, Component, OnInit, TemplateRef} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {UserService} from '../services/user.service';
import {ConnecterComponent} from '../connecter/connecter.component';
import {BsModalRef, BsModalService} from 'ngx-bootstrap/modal';
import { FileUploader } from 'ng2-file-upload';

@Component({
  selector: 'app-singin',
  templateUrl: './singin.component.html',
  styleUrls: ['./singin.component.css']
})
export class SinginComponent implements OnInit {
  registrationForm: FormGroup;
  submit = false;
  fileSelected: File

emailuser: String;
  modalRef: BsModalRef;

  selectedFiles: FileList;
  currentFileUpload: File;
  imgURL: any;
  imgname;
  errorValidImage = '';
    URL ='http://localhost:3000/users/uploads';
  constructor(private router: Router, private userService: UserService, private formbuilder: FormBuilder , private cd : ChangeDetectorRef, private modalService: BsModalService ) { }

  ngOnInit() {

    this.registrationForm = this.formbuilder.group({
      email: [ '', [ Validators.required, Validators.email]],
      password: ['', [ Validators.required, Validators.minLength(8)]],
      firstName:['',[ Validators.required]],
      lastName: ['', Validators.required],
      adresse:['', Validators.required],
      pdf:[''],

    });

  }
  get f() {
    return this.registrationForm.controls;
  }
 OnSubmit(){

    this.submit = true;
    if (this.registrationForm.invalid) {
     return;
   }
    console.log(this.registrationForm.value)
    localStorage.setItem('var', '1');
    this.userService.updateimagee(this.currentFileUpload).subscribe(res=>{
      this.imgname=JSON.parse(JSON.stringify(res['filename']));

    this.userService.register(this.registrationForm.value.firstName,this.registrationForm.value.lastName,this.registrationForm.value.email,this.registrationForm.value.password,this.registrationForm.value.adresse,this.registrationForm.value.pdf=this.imgname).subscribe(  res =>  {
    console.log(res['status'])
  });
    this.userService.login(this.registrationForm.value.email,this.registrationForm.value.password).subscribe(res=>{
      localStorage.setItem('var', '1')
      localStorage.setItem('emailuser',JSON.parse(JSON.stringify(res['data'])).email)
      this.emailuser=localStorage.getItem('emailuser')
      console.log(res['status'])
      console.log(JSON.parse(JSON.stringify(res['data'])).token);
      // console.log(JSON.parse(JSON.stringify(res['data'])).id);
      var iduser = parseInt(JSON.parse(JSON.stringify(res['data'])).id);
      sessionStorage.setItem('id', JSON.parse(JSON.stringify(res['data'])).id);
      this.router.navigate(['']);
    })
    })
  }

  selectFile(event) {
    this.selectedFiles =event.target.files;
    this.currentFileUpload = this.selectedFiles.item(0);
    console.log(this.currentFileUpload);
    const reader = new FileReader();

    reader.onload = (event) => {
      this.imgURL = reader.result;
    };
    console.log(this.imgURL);
    console.log(reader);

  } }
</code>```

//html

```<code>  <div class="container">
    <form method="POST" class="appointment-form" id="appointment-form" [formGroup]="registrationForm" (ngSubmit)="OnSubmit()" enctype="multipart/form-data">
      <h2>education appointment form</h2>
      <div class="form-group-1">
        <div [class]="form-control" >
        <input type="text" class="form-control" formControlName="firstName" placeholder="First Name" [ngClass]="{'is-invalid':submit && f.firstName.errors} " />
          <span class="focus-input100" data-placeholder=""></span>
          <div *ngIf="submit && f.firstName.errors" class="invalid-feedback">
          <div *ngIf="f.firstName.errors.required">firstName is required </div>
        </div>
      </div>
        <div [class]="form-control" >

        <input type="text" formControlName="lastName" placeholder="Last Name" class="form-control" [ngClass]="{'is-invalid':submit && f.lastName.errors}" />
          <div *ngIf="submit && f.lastName.errors" class="invalid-feedback">
            <div *ngIf="f.lastName.errors.required">LastName is required </div>
          </div>
        </div>
          <div [class]="form-control" >
        <input type="email" formControlName="email" placeholder="Email" class="form-control" [ngClass]="{'is-invalid':submit && f.email.errors}" />
        <div *ngIf="submit && f.email.errors" class="invalid-feedback">
          <div *ngIf="f.email.errors.required">Email is required </div>
        </div>
        </div>

        <div [class]="form-control" >
        <input type="password" formControlName="password" placeholder="Password" class="form-control" [ngClass]="{'is-invalid':submit && f.password.errors}"  />
        <div *ngIf="submit && f.password.errors" class="invalid-feedback">
          <div *ngIf="f.password.errors.required">Password is required </div>
          <div *ngIf="f.password.errors.minlength">Au moins 8 caracteres </div>
        </div>
        </div>
        <div [class]="form-control" >
        <input type="text" formControlName="adresse" placeholder="Adresse local" class="form-control" [ngClass]="{'is-invalid':submit && f.adresse.errors}"  />
        <div *ngIf="submit && f.adresse.errors" class="invalid-feedback">
          <div *ngIf="f.adresse.errors.required">Adresse is required </div>
        </div>
        </div>

          <div class="custom-file">
            <input type="file" class="custom-file-input" id="customFile"  (change)="selectFile($event)" formControlName="pdf" [ngClass]="{'is-invalid':submit && f.pdf.errors}" />
            <label class="custom-file-label">Photo de profil</label>
          </div>
        <div class="form-submit">
        <input type="submit" name="submit" id="submit" class="submit" value="Submit" />
      </div>
      </div>
    </form>
  </div>

</div>
</code>```

but console say that there is error in back-end that :

TypeError: Cannot read property 'originalname' of undefined
      at C:\Users\hazem\Desktop\pfe\router\user.js:114:47

答:
It seems like you have not used the library ng2-file-upload Try something like this.

```<code>import { Component, OnInit } from '@angular/core';
import {  FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';

const UploadURL = 'http://localhost:3000/api/upload';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Upload a File';

  public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'image'});

  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
    this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
         console.log('FileUpload:uploaded:', item, status, response);
         alert('File uploaded successfully');
     };
 }
}
</code>```

The line

```<code>public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'image'});
</code>```

is important. make sure you use the same name('image') in you multer middleware,
like this

```<code>upload.single('image')
</code>```

Body:
i can upload image with postman but in angular it doesn't work for me. solution please

error : cannot read originalname of undefined , in nodejs but with
  postman its work !

//backend

var express = require("express")
var router = express.Router();
var userModel = require("../models/userModel")
const jwt= require("jsonwebtoken")
const  bcrypt=require("bcrypt")
var app=express()
var io = require('socket.io-client')('http://localhost:3000/alll')

var  socket = require("socket.io");

var fs=require("fs")
var multer=require("multer")
const upload = multer({dest: __dirname + '/upload/images'});

router.post('/uploads', upload.single('image'), function (req, res) {
  var file = __dirname + '/upload' + req.file.originalname;
  fs.readFile(req.file.path, function (err, data) {
    fs.writeFile(file, data, function (err) {
      if (err) {
        console.error(err);
        var response = {
          message: 'Sorry, file couldn\'t be uploaded.',
          filename: req.file.originalname
        };
      } else {
        response = {
          message: 'File uploaded successfully',
          filename: req.file.originalname
        };
        res.json(response);
      }
    })
  })
})
router.post("/add",function (req, res) {

        user = new userModel({firstName: req.body.firstName,
          lastName: req.body.lastName ,
          email:req.body.email ,
          password:req.body.password,
          adresse:req.body.adresse,
          verif:'1',role :'user',
          annonces:req.body.annonces,
          pdf: req.body.pdf
        })
        user.save(function(err) {
          if (err) {
            res.send({"state": "not ok", "msg": "err:" + err})
          } else {
            res.send({"state": " ok", "msg": "ajout"})
          }

        })
})
// model : pdf as String

//ts

import {ChangeDetectorRef, Component, OnInit, TemplateRef} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {UserService} from '../services/user.service';
import {ConnecterComponent} from '../connecter/connecter.component';
import {BsModalRef, BsModalService} from 'ngx-bootstrap/modal';
import { FileUploader } from 'ng2-file-upload';

@Component({
  selector: 'app-singin',
  templateUrl: './singin.component.html',
  styleUrls: ['./singin.component.css']
})
export class SinginComponent implements OnInit {
  registrationForm: FormGroup;
  submit = false;
  fileSelected: File

emailuser: String;
  modalRef: BsModalRef;

  selectedFiles: FileList;
  currentFileUpload: File;
  imgURL: any;
  imgname;
  errorValidImage = '';
    URL ='http://localhost:3000/users/uploads';
  constructor(private router: Router, private userService: UserService, private formbuilder: FormBuilder , private cd : ChangeDetectorRef, private modalService: BsModalService ) { }

  ngOnInit() {

    this.registrationForm = this.formbuilder.group({
      email: [ '', [ Validators.required, Validators.email]],
      password: ['', [ Validators.required, Validators.minLength(8)]],
      firstName:['',[ Validators.required]],
      lastName: ['', Validators.required],
      adresse:['', Validators.required],
      pdf:[''],

    });

  }
  get f() {
    return this.registrationForm.controls;
  }
 OnSubmit(){

    this.submit = true;
    if (this.registrationForm.invalid) {
     return;
   }
    console.log(this.registrationForm.value)
    localStorage.setItem('var', '1');
    this.userService.updateimagee(this.currentFileUpload).subscribe(res=>{
      this.imgname=JSON.parse(JSON.stringify(res['filename']));

    this.userService.register(this.registrationForm.value.firstName,this.registrationForm.value.lastName,this.registrationForm.value.email,this.registrationForm.value.password,this.registrationForm.value.adresse,this.registrationForm.value.pdf=this.imgname).subscribe(  res =>  {
    console.log(res['status'])
  });
    this.userService.login(this.registrationForm.value.email,this.registrationForm.value.password).subscribe(res=>{
      localStorage.setItem('var', '1')
      localStorage.setItem('emailuser',JSON.parse(JSON.stringify(res['data'])).email)
      this.emailuser=localStorage.getItem('emailuser')
      console.log(res['status'])
      console.log(JSON.parse(JSON.stringify(res['data'])).token);
      // console.log(JSON.parse(JSON.stringify(res['data'])).id);
      var iduser = parseInt(JSON.parse(JSON.stringify(res['data'])).id);
      sessionStorage.setItem('id', JSON.parse(JSON.stringify(res['data'])).id);
      this.router.navigate(['']);
    })
    })
  }

  selectFile(event) {
    this.selectedFiles =event.target.files;
    this.currentFileUpload = this.selectedFiles.item(0);
    console.log(this.currentFileUpload);
    const reader = new FileReader();

    reader.onload = (event) => {
      this.imgURL = reader.result;
    };
    console.log(this.imgURL);
    console.log(reader);

  } }

//html

    <form method="POST" class="appointment-form" id="appointment-form" [formGroup]="registrationForm" (ngSubmit)="OnSubmit()" enctype="multipart/form-data">

education appointment form

        <input type="text" class="form-control" formControlName="firstName" placeholder="First Name" [ngClass]="{'is-invalid':submit && f.firstName.errors} " />

firstName is required

        <input type="text" formControlName="lastName" placeholder="Last Name" class="form-control" [ngClass]="{'is-invalid':submit && f.lastName.errors}" />

LastName is required

        <input type="email" formControlName="email" placeholder="Email" class="form-control" [ngClass]="{'is-invalid':submit && f.email.errors}" />

Email is required

        <input type="password" formControlName="password" placeholder="Password" class="form-control" [ngClass]="{'is-invalid':submit && f.password.errors}"  />

Password is required

Au moins 8 caracteres

        <input type="text" formControlName="adresse" placeholder="Adresse local" class="form-control" [ngClass]="{'is-invalid':submit && f.adresse.errors}"  />

Adresse is required

            <input type="file" class="custom-file-input" id="customFile"  (change)="selectFile($event)" formControlName="pdf" [ngClass]="{'is-invalid':submit && f.pdf.errors}" />
            Photo de profil

        <input type="submit" name="submit" id="submit" class="submit" value="Submit" />

    </form>

but console say that there is error in back-end that :

TypeError: Cannot read property 'originalname' of undefined
      at C:\Users\hazem\Desktop\pfe\router\user.js:114:47

Body:
It seems like you have not used the library ng2-file-upload Try something like this.

import { Component, OnInit } from '@angular/core';
import {  FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';

const UploadURL = 'http://localhost:3000/api/upload';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Upload a File';

  public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'image'});

  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
    this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
         console.log('FileUpload:uploaded:', item, status, response);
         alert('File uploaded successfully');
     };
 }
}

The line

public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'image'});

is important. make sure you use the same name('image') in you multer middleware,
like this

upload.single('image')


答:
Give this code a try.

select l.*
from table l
inner join (
  select
    date_input as latest
  from table
  group by id order by date_input desc
) r
  on l.date_input= r.latest and l.id= r.id
order by date_input desc

Title: How to get latest data inserted in mySQL?


问:
Functional Interface Implementations and use cases
I was just trying to write a functional interface to understand the different use cases.

Looking at the below code which I have written, I understand that I can have different implementations using lambda expressions. Apart from this can anyone show the complex implementations?

Is it possible to use other default method i.e. addLikeOtherWay in lambda expression? if yes how in my example?

Why would I have interface with only one abstract method? What would be the use case of having only single abstract method in my interface?

```<code>public class Calculator {

    public static void main(String[] args) {
        ICalculator i = (int a, int b) -> a + b;
        System.out.println(i.add(5, 2));
        i = (int a, int b) -> a + b + a;
        System.out.println(i.add(5, 2));
    }
}

@FunctionalInterface
interface ICalculator {

    public int add(int a, int b);

    default int addLikeThis(int a, int b) {
        return a + b;
    }

    default int addLikeOtherWay(int a, int b) {
        return a + b + a + b;
    }

}
</code>```

答:
"Is it possible to use the default method in a lambda expression?"  Yes.  In fact, many Functional Interfaces contain default methods.  You need one and only one abstract method in an interface for it to be a functional interface, otherwise there would be other interface methods "unimplemented" by the lambda which is not permitted. But here is how the defaults can be applied.  The BiFunction interface below was lifted from the API sources, sans JavaDoc.

The following code works because BinaryOperator and UnaryOperator extend  BiFunction and Function respectively.

      BinaryOperator<Integer> add = (numb1,numb2)->numb1+numb2;
      UnaryOperator<Integer> mul = resultFromAdd->resultFromAdd*20;
      BinaryOperator<Integer> addThenMul = (numb1,numb2) ->add.andThen(mul).apply(numb1,numb2);
      int result = addThenMul.apply(10,20); // produces (10+20)*20 = 600
```

<p>The following was lifted form the Java API source files.</p>

<pre class="lang-java prettyprint-override"><code>       @FunctionalInterface
       public interface BiFunction<T, U, R> {

          R apply(T t, U u);

          default <V> BiFunction<T, U, V> andThen(
                Function<? super R, ? extends V> after) {
             Objects.requireNonNull(after);
             return (T t, U u) -> after.apply(apply(t, u));
          }
       }

</code>```

In the example code above I could have used BiFunction<Integer,Integer,Integer> and Function<Integer,Integer>.  But the *Operator extensions presume the same type for all args so they are easier to use (i.e. less typing).

Body:
I was just trying to write a functional interface to understand the different use cases.

Looking at the below code which I have written, I understand that I can have different implementations using lambda expressions. Apart from this can anyone show the complex implementations?

Is it possible to use other default method i.e. addLikeOtherWay in lambda expression? if yes how in my example?

Why would I have interface with only one abstract method? What would be the use case of having only single abstract method in my interface?

public class Calculator {

    public static void main(String[] args) {
        ICalculator i = (int a, int b) -> a + b;
        System.out.println(i.add(5, 2));
        i = (int a, int b) -> a + b + a;
        System.out.println(i.add(5, 2));
    }
}

@FunctionalInterface
interface ICalculator {

    public int add(int a, int b);

    default int addLikeThis(int a, int b) {
        return a + b;
    }

    default int addLikeOtherWay(int a, int b) {
        return a + b + a + b;
    }

}

Body:
"Is it possible to use the default method in a lambda expression?"  Yes.  In fact, many Functional Interfaces contain default methods.  You need one and only one abstract method in an interface for it to be a functional interface, otherwise there would be other interface methods "unimplemented" by the lambda which is not permitted. But here is how the defaults can be applied.  The BiFunction interface below was lifted from the API sources, sans JavaDoc.

The following code works because BinaryOperator and UnaryOperator extend  BiFunction and Function respectively.

      BinaryOperator<Integer> add = (numb1,numb2)->numb1+numb2;
      UnaryOperator<Integer> mul = resultFromAdd->resultFromAdd*20;
      BinaryOperator<Integer> addThenMul = (numb1,numb2) ->add.andThen(mul).apply(numb1,numb2);
      int result = addThenMul.apply(10,20); // produces (10+20)*20 = 600

The following was lifted form the Java API source files.

       @FunctionalInterface
       public interface BiFunction<T, U, R> {

          R apply(T t, U u);

          default <V> BiFunction<T, U, V> andThen(
                Function<? super R, ? extends V> after) {
             Objects.requireNonNull(after);
             return (T t, U u) -> after.apply(apply(t, u));
          }
       }

In the example code above I could have used BiFunction<Integer,Integer,Integer> and Function<Integer,Integer>.  But the *Operator extensions presume the same type for all args so they are easier to use (i.e. less typing).


问:
How to align text with image
How to make page like this example using bootstrap 4? Have H1,p and img tags
text continues below, possible without grid? This content generated from admin panel, with standart tinymce.</p>

答:
You don't need Bootstrap, you just need float: right style on  tag.

If you need to do it with Bootstrap for some reason, use float-right class.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Lorem Ipsum

  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit,
  sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
  eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

Title: How to align text with image

Body:
You don't need Bootstrap, you just need float: right style on <img> tag.

If you need to do it with Bootstrap for some reason, use float-right class.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div>
  <img class="float-right" style="width:400px; height: 200px;">
  <h1>Lorem Ipsum</h1>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit,
  sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
  eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>


问:
Best way to create dict out of string in Python
I have the following string:

```<code>mystring = "freq1=440,freq2=425,freq3=410,freq4=0,freq5=0,freq6=0,freq7=0,freq8=0,freq9=0,freq10=0,freq11=0,freq12=0,freq13=0,freq14=0,freq15=0,freq16=0"
</code>```

I would like to create a dictionary out of it such that I can access the values like mydict.freq1.

I can split the string easily enough:

```<code>splitstring = mystring.split(',')
</code>```

So I get:

```<code>freq1=410
freq2=425
freq3=410
freq4=0
</code>```

Which seems far from what I need. Is there an easy way to do this? I am currently on Python 2.7 but working on a migration to 3.0 eventually.

Body:
I have the following string:

mystring = "freq1=440,freq2=425,freq3=410,freq4=0,freq5=0,freq6=0,freq7=0,freq8=0,freq9=0,freq10=0,freq11=0,freq12=0,freq13=0,freq14=0,freq15=0,freq16=0"

I would like to create a dictionary out of it such that I can access the values like mydict.freq1.

I can split the string easily enough:

splitstring = mystring.split(',')

So I get:

freq1=410
freq2=425
freq3=410
freq4=0

Which seems far from what I need. Is there an easy way to do this? I am currently on Python 2.7 but working on a migration to 3.0 eventually.

Body:
Code:

dict(x.split('=') for x in my_string.split(','))

Test Code:

my_string = "freq1=440,freq2=425,freq3=410,freq4=0,freq5=0,freq6=0,freq7=0,freq8=0,freq9=0,freq10=0,freq11=0,freq12=0,freq13=0,freq14=0,freq15=0,freq16=0"
my_dict = dict(x.split('=') for x in my_string.split(','))
print(my_dict)

Results:

{'freq1': '440', 'freq2': '425', 'freq3': '410', 'freq4': '0', 'freq5': '0', 'freq6': '0', 'freq7': '0', 'freq8': '0', 'freq9': '0', 'freq10': '0', 'freq11': '0', 'freq12': '0', 'freq13': '0', 'freq14': '0', 'freq15': '0', 'freq16': '0'}


问:
jQuery convert element ids into comma seperated string
I have a simple html and jquery script like below, I am trying to get a comma seperated list of data-item-id so would look like...

```<code>1,2,3,4,5
</code>```

var items = $('.container').children();
console.log(items);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div></code>```

I have grabbed the items but how can I convert this into the comma seperated string?

答:
Map each item to its item-id, then join by commas:

var items = $('.container')
  .children()
  .map(function() { return $(this).data('item-id') })
  .get()
  .join(',');
console.log(items);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div></code>```

But there's no need for a big library like jQuery to accomplish something this trivial, if you want:

const items = Array.from(
  document.querySelectorAll('.container > .item'),
  div => div.dataset.itemId
)
  .join(',');
console.log(items);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div></code>```

Body:
I have a simple html and jquery script like below, I am trying to get a comma seperated list of data-item-id so would look like...

1,2,3,4,5

var items = $('.container').children();
console.log(items);

Item 1

Item 2

Item 3

Item 4

Item 5

I have grabbed the items but how can I convert this into the comma seperated string?

Body:
Map each item to its item-id, then join by commas:

var items = $('.container')
  .children()
  .map(function() { return $(this).data('item-id') })
  .get()
  .join(',');
console.log(items);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div>

But there's no need for a big library like jQuery to accomplish something this trivial, if you want:

const items = Array.from(
  document.querySelectorAll('.container > .item'),
  div => div.dataset.itemId
)
  .join(',');
console.log(items);

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div>


问:
Use a default image for 404s when using an javascript synchronous image loader for html5 canvas
How would I add a default image (0.png) into this image loader instead of it throwing an error on 404?</p>

```<code>        var artArrayDef = ['player_art/' + p_me_gen + 'body' + me_race + '.png', 'player_art/head' + me_face + '.png'];
        var artArray01  = ['item_art/' + p_me_gen + me_chest + '.png', 'player_art/hair' + me_hair + '.png', 'item_art/' + me_helm + '.png', 'item_art/' + p_me_gen + me_legs + '.png', 'item_art/' + me_feet + '.png', 'item_art/' + me_hands + '.png', 'item_art/' + me_sleeves + '.png', 'item_art/' + me_about + '.png', 'item_art/' + me_hold + '.png', 'item_art/' + me_wield + '.png'];

        // Images for humanoid body and gear
        function loadImage_char(imagePath) {
            return new Promise((resolve, reject) => {
                let image = new Image();
                image.addEventListener("load", () => {
                    resolve(image);
                });
                image.addEventListener("error", (err) => {
                    reject(err);
                });
                image.src = 'https://www.example.com/interface/images/' + imagePath;
            });
        }

        let imageSources = [].concat(artArrayDef, artArray01);
        Promise.all(imageSources.map(i => loadImage_char(i))).then((images) => {
            images.forEach((image) => {
                meCtx.drawImage(image, 0, 0);
            });
        }).catch((err) => {
            console.error(err);
        });
</code>```

答:
```<code>        var artArrayDef = ['player_art/' + p_me_gen + 'body' + me_race + '.png', 'player_art/head' + me_face + '.png'];
        var artArray01  = ['item_art/' + p_me_gen + me_chest + '.png', 'player_art/hair' + me_hair + '.png', 'item_art/' + me_helm + '.png', 'item_art/' + p_me_gen + me_legs + '.png', 'item_art/' + me_feet + '.png', 'item_art/' + me_hands + '.png', 'item_art/' + me_sleeves + '.png', 'item_art/' + me_about + '.png', 'item_art/' + me_hold + '.png', 'item_art/' + me_wield + '.png'];

        // Images for humanoid body and gear
        function loadImage_char(imagePath) {
            return new Promise((resolve, reject) => {
                let image = new Image();
                image.addEventListener("load", () => {
                    resolve(image);
                });
                image.addEventListener("error", (err) => {
                    // Add the default image here <---
                    let defaultImg = new Image();
                    defaultImg.src = 'https://www.example.com/interface/images/item_art/0.png';
                    resolve(defaultImg);
                });
                image.src = 'https://www.example.com/interface/images/' + imagePath;
            });
        }

        let imageSources = [].concat(artArrayDef, artArray01);
        Promise.all(imageSources.map(i => loadImage_char(i))).then((images) => {
            images.forEach((image) => {
                meCtx.drawImage(image, 0, 0);
            });
        }).catch((err) => {
            console.error(err);
        });
</code>```

Body:
How would I add a default image (0.png) into this image loader instead of it throwing an error on 404?

        var artArrayDef = ['player_art/' + p_me_gen + 'body' + me_race + '.png', 'player_art/head' + me_face + '.png'];
        var artArray01  = ['item_art/' + p_me_gen + me_chest + '.png', 'player_art/hair' + me_hair + '.png', 'item_art/' + me_helm + '.png', 'item_art/' + p_me_gen + me_legs + '.png', 'item_art/' + me_feet + '.png', 'item_art/' + me_hands + '.png', 'item_art/' + me_sleeves + '.png', 'item_art/' + me_about + '.png', 'item_art/' + me_hold + '.png', 'item_art/' + me_wield + '.png'];

        // Images for humanoid body and gear
        function loadImage_char(imagePath) {
            return new Promise((resolve, reject) => {
                let image = new Image();
                image.addEventListener("load", () => {
                    resolve(image);
                });
                image.addEventListener("error", (err) => {
                    reject(err);
                });
                image.src = 'https://www.example.com/interface/images/' + imagePath;
            });
        }

        let imageSources = [].concat(artArrayDef, artArray01);
        Promise.all(imageSources.map(i => loadImage_char(i))).then((images) => {
            images.forEach((image) => {
                meCtx.drawImage(image, 0, 0);
            });
        }).catch((err) => {
            console.error(err);
        });


答:
Since you have the DATE_INPUT field, you can use GROUP and ORDER to get what you want:

SELECT ID, NUMBER, DATE_INPUT
FROM MyTable
GROUP BY ID
ORDER BY DATE_INPUT DESC


问:
End date not earlier than Start date and datepicker format
if i remove dateformat, End date will hide earlier date from Start Date..

The problem is, i have to change the date format to dd-mm-yy while make sure End date datepicker are disable to choose earlier date from Start Date

```<code>        $("#StartDate").datepicker({
            dateFormat: 'dd-mm-yy',
            numberOfMonths: 1,
            onSelect: function (selected) {
                var dt = new Date(selected);
                dt.setDate(dt.getDate() + 1);
                $("#EndDate").datepicker("option", "minDate", dt);
            },

        });
        $("#EndDate").datepicker({
            dateFormat: 'dd-mm-yy',
            numberOfMonths: 1,
            onSelect: function (selected) {
                var dt = new Date(selected);
                dt.setDate(dt.getDate() - 1);
                $("#StartDate").datepicker("option", "maxDate", dt);
            }
        });
    });
</code>```

答:
Try this: </p>

```<code>$("#StartDate").datepicker({
            dateFormat: 'dd-mm-yy',
            numberOfMonths: 1,
            onSelect: function (selected) {
                minDate = $("#StartDate").datepicker("getDate");
                var mDate = new Date(minDate.setDate(minDate.getDate()));
                $("#EndDate").datepicker("option", "minDate", mDate);
            }
        });
</code>```

<p>You will also have to additional work:
1. On page load only enable #StartDate textbox and disable #EndDate textbox
2. When #StartDate textbox is removed of value, clear value of #EndDate textbox and disable #EndDate textbox </p>

Body:
if i remove dateformat, End date will hide earlier date from Start Date..

The problem is, i have to change the date format to dd-mm-yy while make sure End date datepicker are disable to choose earlier date from Start Date

        $("#StartDate").datepicker({
            dateFormat: 'dd-mm-yy',
            numberOfMonths: 1,
            onSelect: function (selected) {
                var dt = new Date(selected);
                dt.setDate(dt.getDate() + 1);
                $("#EndDate").datepicker("option", "minDate", dt);
            },

        });
        $("#EndDate").datepicker({
            dateFormat: 'dd-mm-yy',
            numberOfMonths: 1,
            onSelect: function (selected) {
                var dt = new Date(selected);
                dt.setDate(dt.getDate() - 1);
                $("#StartDate").datepicker("option", "maxDate", dt);
            }
        });
    });

Body:
Try this:

$("#StartDate").datepicker({
            dateFormat: 'dd-mm-yy',
            numberOfMonths: 1,
            onSelect: function (selected) {
                minDate = $("#StartDate").datepicker("getDate");
                var mDate = new Date(minDate.setDate(minDate.getDate()));
                $("#EndDate").datepicker("option", "minDate", mDate);
            }
        });

You will also have to additional work:
1. On page load only enable #StartDate textbox and disable #EndDate textbox
2. When #StartDate textbox is removed of value, clear value of #EndDate textbox and disable #EndDate textbox


问:
Lag by taking an instance of an array using es6
I got an empty array while I'm logging for an instance of an array!

```<code>  onSelectMultipleImage = (event): Promise<any> => {
    return new Promise(resolve => {
      const files = <File[]>event.target.files;
      let file: File;
      let counter = -1;
      const response = [];
      while (file = files[++counter]) {
        const reader: FileReader = new FileReader();
        reader.onload = ((f) => {
          return () => {
            response.push({
              file: f,
              base64: reader.result
            })
          }
        })(file);
        reader.readAsDataURL(file);
        console.log(counter);
        if(counter == files.length -1) {
          console.log('inside the while');
          resolve(response);
        }
      }
    });
  };

  onImagesSelect = async (event: Event) => {
    this.newImages = await this.helper.onSelectMultipleImage(event) || [];
    console.log(this.newImages, "Original"); // [file: File, base64: "base 64 long string..."]
    console.log([...this.newImages],"instance"); // [] empty array
    setTimeout(() => {console.log([...this.newImages, 'instance'])}, 2000); // [file: File, base64: "base 64 long string..."]
  }
</code>```

So why I'm getting the presented result? It's something causing by the base64 presented inside the array? if yes what is the solution?

答:
It doesn't wait reader.onload to be completed. So resolve(response) is called before response.push.

You can create a promise to read one file and return them with Promise.all like following code.

```<code>readFile = (file: File): Promise<any> => {
  return new Promise(resolve => {
    const reader: FileReader = new FileReader();
    reader.onload = (f) => {
      resolve({
        file: f,
        base64: reader.result
      });
    };
    reader.readAsDataURL(file);
  })
}

onSelectMultipleImage = (event): Promise<any> => {
  const files = <File[]>event.target.files;
  return Promise.all(files.map(file => readFile(file)));
};
</code>```

Body:
I got an empty array while I'm logging for an instance of an array!

  onSelectMultipleImage = (event): Promise<any> => {
    return new Promise(resolve => {
      const files = <File[]>event.target.files;
      let file: File;
      let counter = -1;
      const response = [];
      while (file = files[++counter]) {
        const reader: FileReader = new FileReader();
        reader.onload = ((f) => {
          return () => {
            response.push({
              file: f,
              base64: reader.result
            })
          }
        })(file);
        reader.readAsDataURL(file);
        console.log(counter);
        if(counter == files.length -1) {
          console.log('inside the while');
          resolve(response);
        }
      }
    });
  };

  onImagesSelect = async (event: Event) => {
    this.newImages = await this.helper.onSelectMultipleImage(event) || [];
    console.log(this.newImages, "Original"); // [file: File, base64: "base 64 long string..."]
    console.log([...this.newImages],"instance"); // [] empty array
    setTimeout(() => {console.log([...this.newImages, 'instance'])}, 2000); // [file: File, base64: "base 64 long string..."]
  }

So why I'm getting the presented result? It's something causing by the base64 presented inside the array? if yes what is the solution?

Body:
It doesn't wait reader.onload to be completed. So resolve(response) is called before response.push.

You can create a promise to read one file and return them with Promise.all like following code.

readFile = (file: File): Promise<any> => {
  return new Promise(resolve => {
    const reader: FileReader = new FileReader();
    reader.onload = (f) => {
      resolve({
        file: f,
        base64: reader.result
      });
    };
    reader.readAsDataURL(file);
  })
}

onSelectMultipleImage = (event): Promise<any> => {
  const files = <File[]>event.target.files;
  return Promise.all(files.map(file => readFile(file)));
};


问:
Extract ratings and corresponding dates from text in R
I want to extract ratings and their dates for each bank from the data frame. Also, make the individual rating records to new rows and separate the ratings and dates into two columns.

Here is my data sample:

```<code>mydf <- data.frame("bank_name"=c("Bank A","Bank B"), "records"=c("Rating: B-\nRating Range: Jun-08-2017 to Present\n\nRating: B\nRating Range: Jan-23-2013 to Jun-08-2017","Rating: BBB-\nRating Range: Oct-02-2018 to Present\n\nRating: B\nRating Range: Apr-06-2018 to Oct-02-2018\n\nRating: A\nRating Range: Jun-08-2007 to Jan-31-2008\n\nRating: CCC\nRating Range: Jan-23-2006 to Aug-08-2007"))
</code>```

Here is what I expect:

```<code>mydf2 <- data.frame("bank_name"=c("Bank A","Bank A","Bank B","Bank B","Bank B","Bank B"), "ratings"=c("B-","B","BBB-","B","A","CCC"),"date"=c("Jun-08-2017","Jan-23-2013","Oct-02-2018","Apr-06-2018","Jun-08-2007","Jan-23-2006"))

> mydf2
  bank_name ratings        date
1    Bank A    B-     Jun-08-2017
2    Bank A    B      Jan-23-2013
3    Bank B    BBB-   Oct-02-2018
4    Bank B    B      Apr-06-2018
5    Bank B    A      Jun-08-2007
6    Bank B    CCC    Jan-23-2006
</code>```

Thank you in advance!

答:
An option would be to extract the characters after the 'Rating', 'Rating Range' in 'records' column with str_extract_all into a list and unnest the list elements

```<code>library(tidyverse)
mydf %>%
  mutate(ratings = str_extract_all(records, "(?<=Rating: )[A-E-]+"),
         date = str_extract_all(records,
              "(?<=Rating Range: )[A-Z][a-z]{2}-\\d{2}-\\d{4}")) %>%
  select(-records) %>%
  unnest
#  bank_name ratings        date
#1    Bank A      B- Jun-08-2017
#2    Bank A       B Jan-23-2013
#3    Bank B    BBB- Oct-02-2018
#4    Bank B       B Apr-06-2018
#5    Bank B       A Jun-08-2007
#6    Bank B     CCC Jan-23-2006
</code>```

Body:
I want to extract ratings and their dates for each bank from the data frame. Also, make the individual rating records to new rows and separate the ratings and dates into two columns.

Here is my data sample:

mydf <- data.frame("bank_name"=c("Bank A","Bank B"), "records"=c("Rating: B-\nRating Range: Jun-08-2017 to Present\n\nRating: B\nRating Range: Jan-23-2013 to Jun-08-2017","Rating: BBB-\nRating Range: Oct-02-2018 to Present\n\nRating: B\nRating Range: Apr-06-2018 to Oct-02-2018\n\nRating: A\nRating Range: Jun-08-2007 to Jan-31-2008\n\nRating: CCC\nRating Range: Jan-23-2006 to Aug-08-2007"))

Here is what I expect:

mydf2 <- data.frame("bank_name"=c("Bank A","Bank A","Bank B","Bank B","Bank B","Bank B"), "ratings"=c("B-","B","BBB-","B","A","CCC"),"date"=c("Jun-08-2017","Jan-23-2013","Oct-02-2018","Apr-06-2018","Jun-08-2007","Jan-23-2006"))

> mydf2
  bank_name ratings        date
1    Bank A    B-     Jun-08-2017
2    Bank A    B      Jan-23-2013
3    Bank B    BBB-   Oct-02-2018
4    Bank B    B      Apr-06-2018
5    Bank B    A      Jun-08-2007
6    Bank B    CCC    Jan-23-2006

Thank you in advance!

Body:
An option would be to extract the characters after the 'Rating', 'Rating Range' in 'records' column with str_extract_all into a list and unnest the list elements

library(tidyverse)
mydf %>%
  mutate(ratings = str_extract_all(records, "(?<=Rating: )[A-E-]+"),
         date = str_extract_all(records,
              "(?<=Rating Range: )[A-Z][a-z]{2}-\\d{2}-\\d{4}")) %>%
  select(-records) %>%
  unnest
#  bank_name ratings        date
#1    Bank A      B- Jun-08-2017
#2    Bank A       B Jan-23-2013
#3    Bank B    BBB- Oct-02-2018
#4    Bank B       B Apr-06-2018
#5    Bank B       A Jun-08-2007
#6    Bank B     CCC Jan-23-2006


问:
Polymorphism can't override when using string
Polymorphism in dec C, isn't working with string

I am using Dev C++ 5.9.2.

I have a parent class A, class B,C,D,E.....extends A and class list is the main class where I use B,C,D.

I don't use parent A , because i want to reuse constructor A.

The problem as follows

```<code>class A
{
    public:
    virtual void show(){
            printf("A");
        }
    private:
    string tokenS;

};

class B :public A
{
    public:
    virtual void show(){
        printf("B:");
       // return 0;
    }
}

class list
{
    public:
        A* getNode(){
           return pta;
        }

        void setNode(B temp){
           this->pta=&temp;
        }
    protected:
    private:
        A *pt1;
};
int main(){
    list ls;
    B b1;
    ls.setNode(b1);
    ls.getNode()->show();
}
</code>```

if i using string tokenS  result :A

if i using char* tokenS   result :B:

I don't understand it, and if I create class and use it , i have the same error

```<code>class Date
{
   // code
};

class A
    {
        public:
        virtual void show(){
                printf("A");
            }
        private:
        Date day;

    };

 class B :public A
    {
        public:
        virtual void show(){
            printf("B:");
           // return 0;
        }
    }
</code>```

答:
The problem is here:

```<code>    void setNode(B temp){
       this->pta=&temp;
    }
</code>```

This sets pta to point to temp, but temp no longer exists when the function ends. Here's on way to fix it and preserve the polymorphism:

```<code>class A
{
    public:
    virtual void show(){
            printf("A");
        }
    virtual std::unique_ptr<A> clone() = 0;
    private:
    string tokenS;

};

class B :public A
{
    public:
    virtual void show(){
        printf("B:");
       // return 0;
    }
    virtual std::unique_ptr<A> clone()
    {
        return std::make_unique<B>(*this);
    }
};

class list
{
    public:
        A& getNode(){
           return *pt1;
        }

        void setNode(A& temp){
           pt1 = temp.clone();
        }
    protected:
    private:
        std::unique_ptr<A> pt1;
};
int main(){
    list ls;
    B b1;
    ls.setNode(b1);
    ls.getNode().show();
}
</code>```

Body:
Polymorphism in dec C, isn't working with string

I am using Dev C++ 5.9.2.

I have a parent class A, class B,C,D,E.....extends A and class list is the main class where I use B,C,D.

I don't use parent A , because i want to reuse constructor A.

The problem as follows

class A
{
    public:
    virtual void show(){
            printf("A");
        }
    private:
    string tokenS;

};

class B :public A
{
    public:
    virtual void show(){
        printf("B:");
       // return 0;
    }
}

class list
{
    public:
        A* getNode(){
           return pta;
        }

        void setNode(B temp){
           this->pta=&temp;
        }
    protected:
    private:
        A *pt1;
};
int main(){
    list ls;
    B b1;
    ls.setNode(b1);
    ls.getNode()->show();
}

if i using string tokenS  result :A

if i using char* tokenS   result :B:

I don't understand it, and if I create class and use it , i have the same error

class Date
{
   // code
};

class A
    {
        public:
        virtual void show(){
                printf("A");
            }
        private:
        Date day;

    };

 class B :public A
    {
        public:
        virtual void show(){
            printf("B:");
           // return 0;
        }
    }

Body:
The problem is here:

    void setNode(B temp){
       this->pta=&temp;
    }

This sets pta to point to temp, but temp no longer exists when the function ends. Here's on way to fix it and preserve the polymorphism:

class A
{
    public:
    virtual void show(){
            printf("A");
        }
    virtual std::unique_ptr<A> clone() = 0;
    private:
    string tokenS;

};

class B :public A
{
    public:
    virtual void show(){
        printf("B:");
       // return 0;
    }
    virtual std::unique_ptr<A> clone()
    {
        return std::make_unique<B>(*this);
    }
};

class list
{
    public:
        A& getNode(){
           return *pt1;
        }

        void setNode(A& temp){
           pt1 = temp.clone();
        }
    protected:
    private:
        std::unique_ptr<A> pt1;
};
int main(){
    list ls;
    B b1;
    ls.setNode(b1);
    ls.getNode().show();
}


问:
JavaScript onclick requires two clicks
My problem is that when onclicktriggers the toggleNew function it's not executing but when I click the div a second time it's executing just as it should...

HTML:

```<code><div id="aside_main">
    <div onclick="toggleNew();">click</div>
    content
</div>
<div id="aside_new">
    content
</div>
</code>```

JS:

```<code>function toggleNew() {
   var e = document.getElementById('aside_main');
   var se = document.getElementById('aside_new');
   if(e.style.display == 'block') {
    e.style.display = 'none';
    se.style.display = 'block';
   } else {
    e.style.display = 'block';
    se.style.display = 'none';
   }
}
</code>```

CSS:

```<code>#aside_main {
  display: block;
}
#aside_new {
  display: none;
}
</code>```

What is happening here and how can I make the function work the first time a user clicks the div?

答:
One way (for me the simplest way) to solve this is by counting clicks.

For this purpose you set the new intiger variable click to 0 outside of your function toggleNew() and everytime you call your function you increase variable click for 1 like this:

```<code><script> var click = 0;
         function toggleNew() {
         click = click +1;
         var e = document.getElementById('aside_main');
         var se = document.getElementById('aside_new');
         if (click > 1) {
                         if(e.style.display == 'block') {
                                                     e.style.display = 'none';
                                                     se.style.display = 'block';
                            } else {
                                     e.style.display = 'block';
                                     se.style.display = 'none';
                                    }
          } else {
                  e.style.display = 'none';
                  se.style.display = 'block';
                  }
        }
</script>
</code>```

Title: JavaScript onclick requires two clicks

Body:
My problem is that when onclicktriggers the toggleNew function it's not executing but when I click the div a second time it's executing just as it should...

HTML:

click

    content

    content

JS:

function toggleNew() {
   var e = document.getElementById('aside_main');
   var se = document.getElementById('aside_new');
   if(e.style.display == 'block') {
    e.style.display = 'none';
    se.style.display = 'block';
   } else {
    e.style.display = 'block';
    se.style.display = 'none';
   }
}

CSS:

#aside_main {
  display: block;
}
#aside_new {
  display: none;
}

What is happening here and how can I make the function work the first time a user clicks the div?

Body:
One way (for me the simplest way) to solve this is by counting clicks.

For this purpose you set the new intiger variable click to 0 outside of your function toggleNew() and everytime you call your function you increase variable click for 1 like this:

<script> var click = 0;
         function toggleNew() {
         click = click +1;
         var e = document.getElementById('aside_main');
         var se = document.getElementById('aside_new');
         if (click > 1) {
                         if(e.style.display == 'block') {
                                                     e.style.display = 'none';
                                                     se.style.display = 'block';
                            } else {
                                     e.style.display = 'block';
                                     se.style.display = 'none';
                                    }
          } else {
                  e.style.display = 'none';
                  se.style.display = 'block';
                  }
        }
</script>


Title: Best way to create dict out of string in Python

Body:
Code:

mystring = "freq1=440,freq2=425,freq3=410,freq4=0,freq5=0,freq6=0,freq7=0,freq8=0
splitdic={}
for value in mystring.split(','):
    splitdic[value.split("=")[0]]=value.split("=")[1]
print(splitdic)

Result:

{'freq9': '0', 'freq8': '0', 'freq2': '425', 'freq5': '0', 'freq4': '0', 'freq6': '0', 'freq15': '0', 'freq1': '440', 'freq3': '410', 'freq11': '0', 'freq12': '0', 'freq16': '0', 'freq10': '0', 'freq13': '0', 'freq14': '0', 'freq7': '0'}


问:
Overloading a function with void
Trying to overloading a function in C programming language with _Generic. Have found examples:

https://www.quora.com/Does-C-support-function-overloading

How to achieve function overloading in C?

This the example:

```<code>#include <stdio.h>
#include <math.h>

void display_float(float dispid) ;
void display_int(int dispid) ;
void display_void(void) ;

#define display(x) _Generic((x), \
          float: display_float, \
          int: display_int,  \
          default: display_float  \
)(x)

void display_void(void){
    printf("display id: 0\n") ;
}

void display_float(float dispid){
   printf("display id: %f\n", dispid) ;
}

void display_int(int dispid){
    printf("display id: %d\n", dispid) ;
}

void main(void){

    display(5) ;
    display(6.5) ;
}
</code>```

Now I also want to overload the function with display(). Meaning the function would intake a void, call the function display_void(), and display 0. Can't seem to do this. Any help would be appreciated.

EDIT 1:

Also, see the examples here. One of the examples (I think) is passing a pointer to a void. Can this be implemented?

答:
Trying to overloading a function in C programming language

C11 does not have any function overloading and _Generic is for genericity, not for overloading, check that by reading n1570. Consider switching to C++ (or even better, Rust) which provides function overloading. Notice that it is illegal to have a void (not void*, just void) argument to a C function, so there is no any "top" super-type in C, which would be a super type of other types (and this because of calling conventions and ABI considerations making C a low-level programming language, sometimes even called a "portable assembler"). Read more about abstract interpretation and type systems please.

If _Generic was for overloading, the members of the C11 standard committee - all programming language experts and good enough English writers -  would have named it like _Overload, but they wisely did not.

Food for thought (assuming both stderr and stdin works like you want them to work) :
 what about some hypothetical display(stderr) or display(*stdin) or display("abc") ?

(a wrong suggestion below, followed by a better advice)

bad approach

(this does not work!)

Your  display_void should take some argument, e.g.

```<code>void display_void(void*p) { printf("p@%p\n", p);
</code>```

Then you might have:

```<code>#define display_anything(P) display_void((void*)(&(P)))
</code>```

with

```<code>#define display(x) _Generic((x), \
      float: display_float, \
      int: display_int,  \
      default: display_anything  \
)(x)
</code>```

better advice

Since that does not work (and it does not), design your code in some other way. For example, consider having some tagged union, like here. Look into GVariant (from Glib) implementation for inspiration.

Title: Overloading a function with void

Body:
Trying to overloading a function in C programming language with _Generic. Have found examples:

https://www.quora.com/Does-C-support-function-overloading

How to achieve function overloading in C?

This the example:

#include <stdio.h>
#include <math.h>

void display_float(float dispid) ;
void display_int(int dispid) ;
void display_void(void) ;

#define display(x) _Generic((x), \
          float: display_float, \
          int: display_int,  \
          default: display_float  \
)(x)

void display_void(void){
    printf("display id: 0\n") ;
}

void display_float(float dispid){
   printf("display id: %f\n", dispid) ;
}

void display_int(int dispid){
    printf("display id: %d\n", dispid) ;
}

void main(void){

    display(5) ;
    display(6.5) ;
}

Now I also want to overload the function with display(). Meaning the function would intake a void, call the function display_void(), and display 0. Can't seem to do this. Any help would be appreciated.

EDIT 1:

Also, see the examples here. One of the examples (I think) is passing a pointer to a void. Can this be implemented?

Body:
Trying to overloading a function in C programming language

C11 does not have any function overloading and _Generic is for genericity, not for overloading, check that by reading n1570. Consider switching to C++ (or even better, Rust) which provides function overloading. Notice that it is illegal to have a void (not void*, just void) argument to a C function, so there is no any "top" super-type in C, which would be a super type of other types (and this because of calling conventions and ABI considerations making C a low-level programming language, sometimes even called a "portable assembler"). Read more about abstract interpretation and type systems please.

If _Generic was for overloading, the members of the C11 standard committee - all programming language experts and good enough English writers -  would have named it like _Overload, but they wisely did not.

Food for thought (assuming both stderr and stdin works like you want them to work) :
 what about some hypothetical display(stderr) or display(*stdin) or display("abc") ?

(a wrong suggestion below, followed by a better advice)

bad approach

(this does not work!)

Your  display_void should take some argument, e.g.

void display_void(void*p) { printf("p@%p\n", p);

Then you might have:

#define display_anything(P) display_void((void*)(&(P)))

with

#define display(x) _Generic((x), \
      float: display_float, \
      int: display_int,  \
      default: display_anything  \
)(x)

better advice

Since that does not work (and it does not), design your code in some other way. For example, consider having some tagged union, like here. Look into GVariant (from Glib) implementation for inspiration.


问:
Can I connect my IBM Cloudant Database as the callback URL for my Twilio IBM STT add-on service?
I have a Watson voice assistant instance connected using SIP trunk to a Twilio API. I want to enable to the IBM Speech-To-Text add-on from the Twilio Marketplace which will allow me to obtain full transcriptions of phone calls made to the Watson Assistant bot. I want to store these transcriptions in a Cloudant Database I have created in IBM Cloud. Can I use the endpoint of my Cloudant Database as the callback URL for my Twilio add-on so that when the add-on is activated, the transcription will be added as a document in my Cloudant Database?

It seems that I should be able to somehow call a trancsription service through IBM Cloud's STT service in IBM Cloud, but since my assistant is connected through Twilio, this add-on seems like an easier option. I am new to IBM Cloud and chat-bot development so any information is greatly appreciated.

答:
Twilio developer evangelist here.

First up, I don't believe that you can enable add-ons for voice services that are served through Twilio SIP trunking.

Unless I am mistaken and you are making a call through a SIP trunk to a Twilio number that is responding with TwiML. In this case, then you can add the STT add-on. I'm not sure it would be the best idea to set the webhook URL to your Cloudant DB URL as the webhook is not going to deliver the data in the format that Cloudant expects.

Instead I would build out an application that can provide an endpoint to receive the webhook, transform the data into something Cloudant will understand and then send it on to the DB.

Does that help at all?


问:
Custom Cocoapod always returns "No such module XXX"
I followed the guide found here

This is my .podspec file

```<code>Pod::Spec.new do |s|
  s.name         = "iOSUtils"
  s.version      = "0.0.1"
  s.summary      = "A really short description of MyFramework."
  s.description  = <<-DESC
  A much much much longer description of MyFramework.
                   DESC
  s.homepage     = "https://github.com/xxxxxxx/ios-utils"
  s.license      = "MIT"
  s.author       = { "xxxxxxx" => "xxxxxxx@xxxxxxx.io" }
  s.source       = { :path => '.' }
  # s.source       = { :git => "https://github/samwize/MyFramework", :tag => "#{s.version}" }
  s.source_files  = "Source/**/*.swift"
end
</code>```

My solution is laid out as

And for testing purposes I created a simple service

```<code>public class TestService {
    static public let shared = TestService()
    private init() { }

    public func foo() {
        print("bar")
    }
}
</code>```

The Podfile of my project that will use this new framework looks like pod 'iOSUtils', :path => '../iOSUtils' and running install returns success messages.

When I then try and import my module however, I get the no such module error and cannot build.

Looking at my project also, I cannot see the source included under development pods

答:
Try adding your package name into the s.source_files of your iOSUtils.podspec file.

```<code>  s.source_files  = "iOSUtils/Source/**/*.swift"
</code>```

Body:
I followed the guide found here

This is my .podspec file

Pod::Spec.new do |s|
  s.name         = "iOSUtils"
  s.version      = "0.0.1"
  s.summary      = "A really short description of MyFramework."
  s.description  = <<-DESC
  A much much much longer description of MyFramework.
                   DESC
  s.homepage     = "https://github.com/xxxxxxx/ios-utils"
  s.license      = "MIT"
  s.author       = { "xxxxxxx" => "xxxxxxx@xxxxxxx.io" }
  s.source       = { :path => '.' }
  # s.source       = { :git => "https://github/samwize/MyFramework", :tag => "#{s.version}" }
  s.source_files  = "Source/**/*.swift"
end

My solution is laid out as

And for testing purposes I created a simple service

public class TestService {
    static public let shared = TestService()
    private init() { }

    public func foo() {
        print("bar")
    }
}

The Podfile of my project that will use this new framework looks like pod 'iOSUtils', :path => '../iOSUtils' and running install returns success messages.

When I then try and import my module however, I get the no such module error and cannot build.

Looking at my project also, I cannot see the source included under development pods

Body:
Try adding your package name into the s.source_files of your iOSUtils.podspec file.

  s.source_files  = "iOSUtils/Source/**/*.swift"


Body:
I have the following string:

mystring = "freq1=440,freq2=425,freq3=410,freq4=0,freq5=0,freq6=0,freq7=0,freq8=0,freq9=0,freq10=0,freq11=0,freq12=0,freq13=0,freq14=0,freq15=0,freq16=0"

I would like to create a dictionary out of it such that I can access the values like mydict.freq1.

I can split the string easily enough:

splitstring = mystring.split(',')

So I get:

freq1=410
freq2=425
freq3=410
freq4=0

Which seems far from what I need. Is there an easy way to do this? I am currently on Python 2.7 but working on a migration to 3.0 eventually.

Body:
mystring = "freq1=440,freq2=425,freq3=410,freq4=0,freq5=0,freq6=0,freq7=0,freq8=0,freq9=0,freq10=0,freq11=0,freq12=0,freq13=0,freq14=0,freq15=0,freq16=0"
res= {i.split('=')[0]:i.split('=')[1] for i in mystring.split(',') }

print(res)

output

{'freq1': '440', 'freq2': '425', 'freq3': '410', 'freq4': '0',
 'freq5': '0', 'freq6': '0', 'freq7': '0', 'freq8': '0', 'freq9': '0',
 'freq10': '0', 'freq11': '0', 'freq12': '0',
 'freq13': '0', 'freq14': '0', 'freq15': '0', 'freq16': '0'}