问:
Regex to capture html elements with their class name
I am trying to get the element and class name for all elements within an html file using python. I managed to get all class names with the code below. It's written like that because I will go through a lot of html files while storing elements with their class names. Ignoring elements without a class name.

```<code> temp_file = open(root + "/" + file, "r", encoding="utf-8-sig", errors="ignore")
    temp_content = temp_file.read()
    class_names = re.findall("class=\"(.*?)\"", temp_content)
</code>```

However now I am struggling to find a way to get the element that the class belongs to. Keep in mind that elements sometimes overlap with each other, so readlines() won't help too much either and it would proabably be slower than regexing the entire document at once.

```<code><div class="header_container container_12">
        <div class="grid_5">
              <h1><a href="#">Logo Text Here</a></h1>
        </div>
        <div class="grid_7">
            <div class="menu_items">
                <a href="#" class="home active">Home</a><a href="#" class="portfolio">Portfolio</a>
               <a href="#"
                class="about">About Me
                </a><a href="#" class="contact">Contact Me</a>
            </div>
        </div>
</div>
</code>```

The above html snippet is badly indented on purpose, to showcase the kind of data I am working with...
The goal would be to maybe store them in a hashmap.
i.e.

```<code>"header_Container container_12": "div"
 "grid_5": "div"
 "grid_7": "div"
 "menu_items": "div"
 "home active": "a"
 "portfolio": "a"
 "about": "a"
 "contact": "a"
</code>```

答:
Regex is a poor choice for HTML parsing, but luckily this is trivial with BeautifulSoup:

from bs4 import BeautifulSoup

html = """

Logo Text Here

                HomePortfolio
               About Me
                Contact Me

"""

for elem in BeautifulSoup(html, "lxml").find_all(attrs={"class": True}):
    print(elem.attrs["class"], elem.name)
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>['header_container', 'container_12'] div
['grid_5'] div
['grid_7'] div
['menu_items'] div
['home', 'active'] a
['portfolio'] a
['about'] a
['contact'] a
</code>```

You can put this into a dict as you desire, but be careful since more than one element will likely map to each bucket. All it'd tell you is that an element exists and has a certain tag name given a specific class name string or tuple in a specific order.

```<code>elems = {}

for elem in BeautifulSoup(html, "lxml").find_all(attrs={"class": True}):
    elems[tuple(elem.attrs["class"])] = elem.name

for k, v in elems.items():
    print(k, v)
</code>```

Body:
I am trying to get the element and class name for all elements within an html file using python. I managed to get all class names with the code below. It's written like that because I will go through a lot of html files while storing elements with their class names. Ignoring elements without a class name.

 temp_file = open(root + "/" + file, "r", encoding="utf-8-sig", errors="ignore")
    temp_content = temp_file.read()
    class_names = re.findall("class=\"(.*?)\"", temp_content)

However now I am struggling to find a way to get the element that the class belongs to. Keep in mind that elements sometimes overlap with each other, so readlines() won't help too much either and it would proabably be slower than regexing the entire document at once.

Logo Text Here

                HomePortfolio
               About Me
                Contact Me

The above html snippet is badly indented on purpose, to showcase the kind of data I am working with...
The goal would be to maybe store them in a hashmap.
i.e.

"header_Container container_12": "div"
 "grid_5": "div"
 "grid_7": "div"
 "menu_items": "div"
 "home active": "a"
 "portfolio": "a"
 "about": "a"
 "contact": "a"

Body:
Regex is a poor choice for HTML parsing, but luckily this is trivial with BeautifulSoup:

from bs4 import BeautifulSoup

html = """<div class="header_container container_12">
        <div class="grid_5">
              <h1><a href="#">Logo Text Here</a></h1>
        </div>
        <div class="grid_7">
            <div class="menu_items">
                <a href="#" class="home active">Home</a><a href="#" class="portfolio">Portfolio</a>
               <a href="#"
                class="about">About Me
                </a><a href="#" class="contact">Contact Me</a>
            </div>
        </div>
</div>"""

for elem in BeautifulSoup(html, "lxml").find_all(attrs={"class": True}):
    print(elem.attrs["class"], elem.name)

Output:

['header_container', 'container_12'] div
['grid_5'] div
['grid_7'] div
['menu_items'] div
['home', 'active'] a
['portfolio'] a
['about'] a
['contact'] a

You can put this into a dict as you desire, but be careful since more than one element will likely map to each bucket. All it'd tell you is that an element exists and has a certain tag name given a specific class name string or tuple in a specific order.

elems = {}

for elem in BeautifulSoup(html, "lxml").find_all(attrs={"class": True}):
    elems[tuple(elem.attrs["class"])] = elem.name

for k, v in elems.items():
    print(k, v)


来源: stackexchange

问:
Switch behavior -ON -OFF using an Image or label -Binding an image inside a listview in xamarin forms
I would like to change the image source from white.png to blue.png when it gets tapped , I need to access each comannd when the image schange to white.png and when it is blue.png , also .it will be helpful to set it true or false , depending on the image result.

all this will come inside a list . and I need to access each individual tapped.

I tried :

IValueConveter

```<code>public class ConverterAddRemoveImage : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool isAddedToCart = (bool)value;
            if (isAddedToCart)
            {
                return "FilledIcon"; //This will be a string
            }
            else
            {
                return "EmptyIcon";  //This will be a string
            }
        }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
</code>```

Xaml

```<code><Image Source="{Binding IsAddedToCart, Converter={StaticResource AddRemoveImage}}"/>
</code>```

This only shows me the else , never gets to true. Ideally I would like to access each of them and add logic to it and obviously change the image on each tapped.

Second approach- the issue here is - gets tapped only one time and I can not get back to the previous image with the second tapped , and also , I dont know how to access each command. (I want to imitate a switch on and off and on each of them do something)

```<code>public ImageSource ColorImage { get; set; }
</code>```

View Model

```<code>public ICommand SwitchIMGCommand
            {
                get;
                set;
            }

private void AddImg(object obj)
  {
     var selection = obj as ExistingModel;
     selection.ColorImage = "FilledIcon.png";**
     ColorImage= "FilledIcon.png";**I tried this and it doesnt change
     to this img
  }

private ImageSource imagePath = "white.png";
        public ImageSource ColorImage
        {
            get { return imagePath; }
            set
            {
                imagePath = value;
                PropertyChanged(this, new PropertyChangedEventArgs("ColorImage"));
            }
        }
</code>```

Constructor

```<code>SwitchIMGCommand = new Command(AddImg);
</code>```

XAML

```<code><Image
    Source="{Binding ColorImage}">
    <Image.GestureRecognizers>
    <TapGestureRecognizer
    Command="{Binding Source={x:Reference listView}, Path=BindingContext.SwitchIMGCommand}" CommandParameter="{Binding .} "
     NumberOfTapsRequired="1" />
     </Image.GestureRecognizers>
  </Image>
</code>```

答:
You are using the wrong type for your parameter "ColorImage". The source of an image is ImageSource type.

Assuming you set your images correctly on your project, the following code should solve your issue

```<code>private void AddImg(object obj)
{
    ColorImage = ImageSource.FromFile("imgcolorblue.png");
}
</code>```

Change also the type of "ColorImage" by ImageSource.

ContentLicense: CC BY-SA 4.0

Body:
I would like to change the image source from white.png to blue.png when it gets tapped , I need to access each comannd when the image schange to white.png and when it is blue.png , also .it will be helpful to set it true or false , depending on the image result.

all this will come inside a list . and I need to access each individual tapped.

I tried :

IValueConveter

public class ConverterAddRemoveImage : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool isAddedToCart = (bool)value;
            if (isAddedToCart)
            {
                return "FilledIcon"; //This will be a string
            }
            else
            {
                return "EmptyIcon";  //This will be a string
            }
        }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

Xaml

<Image Source="{Binding IsAddedToCart, Converter={StaticResource AddRemoveImage}}"/>

This only shows me the else , never gets to true. Ideally I would like to access each of them and add logic to it and obviously change the image on each tapped.

Second approach- the issue here is - gets tapped only one time and I can not get back to the previous image with the second tapped , and also , I dont know how to access each command. (I want to imitate a switch on and off and on each of them do something)

public ImageSource ColorImage { get; set; }

View Model

public ICommand SwitchIMGCommand
            {
                get;
                set;
            }

private void AddImg(object obj)
  {
     var selection = obj as ExistingModel;
     selection.ColorImage = "FilledIcon.png";**
     ColorImage= "FilledIcon.png";**I tried this and it doesnt change
     to this img
  }

private ImageSource imagePath = "white.png";
        public ImageSource ColorImage
        {
            get { return imagePath; }
            set
            {
                imagePath = value;
                PropertyChanged(this, new PropertyChangedEventArgs("ColorImage"));
            }
        }

Constructor

SwitchIMGCommand = new Command(AddImg);

XAML

<Image
    Source="{Binding ColorImage}">
    <Image.GestureRecognizers>
    <TapGestureRecognizer
    Command="{Binding Source={x:Reference listView}, Path=BindingContext.SwitchIMGCommand}" CommandParameter="{Binding .} "
     NumberOfTapsRequired="1" />
     </Image.GestureRecognizers>
  </Image>

Body:
You are using the wrong type for your parameter "ColorImage". The source of an image is ImageSource type.

Assuming you set your images correctly on your project, the following code should solve your issue

private void AddImg(object obj)
{
    ColorImage = ImageSource.FromFile("imgcolorblue.png");
}

Change also the type of "ColorImage" by ImageSource.


问:
Automatically download S3 images, ZIP them and re-upload back to S3
My question is regarding the AWS platform and I have a fairly complicated issue I am trying to solve.

I have images that are stored in an AWS S3 bucket. These images need to be zipped and re-uploaded to the S3 bucket that they are downloaded from. I have created a docker image that utilizes linux ZIP and UNZIP commands in conjunction with the AWS CLI to perform this task. I can run this docker image manually and it performs the job perfectly.

The problem: I am struggling to figure out the AWS platform so that I may automate this docker image. My ideal scenario is the docker image spins up automatically when required, performs the task and then shuts itself back off. I know something similar to this is possible using AWS ECS. However, I am woefully over my head here. I'd love to open a dialogue with someone who knows how to wrangle AWS to complete this task.

PS. I am mainly looking for guidance on how to do this, I have the docker Image already.

答:
Use Lambda to start an AWS fargate task using your image

This blog goes into detail in implention such a solution
https://serverless.com/blog/serverless-application-for-long-running-process-fargate-lambda/


问:
Using Python to zip and list functions to combine two 2D arrays to produce x,y coordinates?
I have two, 2D-arrays each of dimensions 831 x 918. If:

Matrix A =[[a(1,1), a(1,2),...],[a(2,1),a(2,2)...]]
Matrix B =[[b(1,1), b(1,2),...],[b(2,1),b(2,2)...]]

I would like to combine the two matrices to create a list with ((a(1,1),b(1,1)),(a(1,2),b(1,2)),...).

What is the best way to do this? I have tried to use the zip and list functions as shown below:

```<code>import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt

ly=fits.open(lightyield.fits)
ly=ly[0].data
dx=fits.open(de.fits)
dx=dx[0].data
combo=list(zip(dx,ly))
</code>```

However, this returns a list that is 831 elements long, but each position on the list has a lot of elements. I only want to have a single (x,y) point for each element in the list, not an entire array.

Thanks for any help.
EDIT: As a basic example, for:
 A=[[1,2,3],[4,5,6],[7,8,9]]
 B=[[10,11,12],[13,14,15],[16,17,18]]

I want to get a list to plot of ((1,10),(2,11),(3,12),...).

答:
If you have two arrays of the same shape like:

```<code>a = np.random.random((10, 15))
b = np.random.random((10, 15))
</code>```

You can perform this operation to get a list with the pairs of elements in the same position

```<code>[(a_, b_) for a_, b_ in zip(a.flatten(), b.flatten())]
</code>```

Hope it helps

Body:
I have two, 2D-arrays each of dimensions 831 x 918. If:

Matrix A =[[a(1,1), a(1,2),...],[a(2,1),a(2,2)...]]
Matrix B =[[b(1,1), b(1,2),...],[b(2,1),b(2,2)...]]

I would like to combine the two matrices to create a list with ((a(1,1),b(1,1)),(a(1,2),b(1,2)),...).

What is the best way to do this? I have tried to use the zip and list functions as shown below:

import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt

ly=fits.open(lightyield.fits)
ly=ly[0].data
dx=fits.open(de.fits)
dx=dx[0].data
combo=list(zip(dx,ly))

However, this returns a list that is 831 elements long, but each position on the list has a lot of elements. I only want to have a single (x,y) point for each element in the list, not an entire array.

Thanks for any help.
EDIT: As a basic example, for:
 A=[[1,2,3],[4,5,6],[7,8,9]]
 B=[[10,11,12],[13,14,15],[16,17,18]]

I want to get a list to plot of ((1,10),(2,11),(3,12),...).

Body:
If you have two arrays of the same shape like:

a = np.random.random((10, 15))
b = np.random.random((10, 15))

You can perform this operation to get a list with the pairs of elements in the same position

[(a_, b_) for a_, b_ in zip(a.flatten(), b.flatten())]

Hope it helps


问:
Amazon Lex - Delete Slot Type
I've added a Slot Type into the web front end system of Lex by clicking on the "Save slot type" button.

But now I can't see the Slot Type anywhere. Nor can I edit it. It just seems to have vanished into thin air. However, when I then try and create another Slot Type with the same name, I receive an error saying that it already exists... which it obviously does, but I can't edit it or delete it because I can't see it.

How do I access it?? or how do I access the json for it???

Thanks

答:
This was a cashing issue for me. I closed all browser windows, deleted my cache for the past hour, and logged back into AWS.

Problem solved.

When I did logged back in, the slot was back in my Slot Types, even though I had deleted it (at least it was not showing in my list of Slot Types before). I was able to use it in my bot without any issues.

ContentLicense: CC BY-SA 3.0

Title: Amazon Lex - Delete Slot Type


问:
Laravel: Undefined variable Posts
I am trying to display data using a foreach statement within my system. Now i am passing through the variable 'posts' into my view however i keep receiving the error: Undefined variable: posts (View:.

Search.blade.php

```<code> @foreach($posts as $post)
  <option value="{{$post->distance}}">{{ $post->distance}}</option>

 @endforeach
</code>```

SearchController.php

```<code>     public function index()
    {
       $posts = Post::all();
       return view('pages.Search')->with('posts', $posts);

     }
</code>```

Now in my PostsController.php i have similar code which returns all the posts.

PostsController.php

```<code>  public function index()
   {
    $posts = Post::all();
    return view('posts.index')->with('posts', $posts);

}
</code>```

Is this going to cause the error, i didnt think it would cause its returning to a completely separate page.

答:
Please make sure the variable is passed to the correct view.

Troubleshooting step:

Find the URL

Find the corresponding route

Find the Controller

Find the view

Make sure that you are using the correct controller for the view.

Title: Laravel: Undefined variable Posts

Body:
I am trying to display data using a foreach statement within my system. Now i am passing through the variable 'posts' into my view however i keep receiving the error: Undefined variable: posts (View:.

Search.blade.php

 @foreach($posts as $post)
  <option value="{{$post->distance}}">{{ $post->distance}}</option>

 @endforeach

SearchController.php

     public function index()
    {
       $posts = Post::all();
       return view('pages.Search')->with('posts', $posts);

     }

Now in my PostsController.php i have similar code which returns all the posts.

PostsController.php

  public function index()
   {
    $posts = Post::all();
    return view('posts.index')->with('posts', $posts);

}

Is this going to cause the error, i didnt think it would cause its returning to a completely separate page.


问:
Use custom redirect match redirects together with RewriteRule in Apache .htaccess
I would like to redirect all URLs from domain1 to domain2 maintaining the same links.

I use a RewriteRule for this:

```<code>RewriteRule ^(.*)$ https://www.website2.com/$1 [R=301]
</code>```

But if I want to make a custom redirect that would override this RewriteRule, how could I achieve this?

答:
RewriteRule and RewriteCond e.g. are sensitive to order so you just need to place a new RewriteRule above your catchall with a Last [L] flag

```<code>RewriteRule "^(SOME REGEX)" "/some-url" [R=301,L]
</code>```

Resources

http://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_l

https://cwiki.apache.org/confluence/display/HTTPD/RewriteRule

Body:
I would like to redirect all URLs from domain1 to domain2 maintaining the same links.

I use a RewriteRule for this:

RewriteRule ^(.*)$ https://www.website2.com/$1 [R=301]

But if I want to make a custom redirect that would override this RewriteRule, how could I achieve this?

Body:
RewriteRule and RewriteCond e.g. are sensitive to order so you just need to place a new RewriteRule above your catchall with a Last [L] flag

RewriteRule "^(SOME REGEX)" "/some-url" [R=301,L]

Resources

http://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_l

https://cwiki.apache.org/confluence/display/HTTPD/RewriteRule


问:
Clearing flask session flash messages after pytest tests
I have a Flask site that I'm testing using pytest. I want to test that some views are setting flask.flash messages correctly. I can do this, but the flash messages persist between tests and I'd like them to clear.

I have this test_client fixture:

@pytest.fixture(scope="session")
def app():
    # create_app() returns a configured Flask app:
    app = create_app("testing")
    with app.test_request_context():
        yield app

@pytest.fixture(scope="session")
def test_client(app):
    with app.test_client() as c:
        yield c
```

<p>And I have tests like this:</p>

<pre class="lang-py prettyprint-override"><code>from flask import session

def test_my_redirect_view(test_client):
    "It should redirect and set the correct flash message"
    response = test_client.get("/my/path", follow_redirects=False)

    assert response.status_code == 302
    assert response.location == "http://localhost/a/different/url"

    assert "_flashes" in session
    assert len(session["_flashes"]) == 1
    assert session["_flashes"][0][0] == "warning"
    assert session["_flashes"][0][1] == "My error message"
</code>```

As I say, assuming my view sets this flash message, and redirects correctly, this test passes. But a subsequent, similar test, will fail because then len(session["_flashes"]) will be 2, because it has the messages from both tested views.

I've tried doing this at the end of each test, but with no apparent effect:

    del session["_flashes"][0]
```

答:
This isn't an ideal answer, because it doesn't ensure the tested view only sets a single flash message, but for now I'm replacing the assert lines related to the flash messages with:

    assert ("warning", "My error message") in session["_flashes"]
```

Body:
I have a Flask site that I'm testing using pytest. I want to test that some views are setting flask.flash messages correctly. I can do this, but the flash messages persist between tests and I'd like them to clear.

I have this test_client fixture:

@pytest.fixture(scope="session")
def app():
    # create_app() returns a configured Flask app:
    app = create_app("testing")
    with app.test_request_context():
        yield app

@pytest.fixture(scope="session")
def test_client(app):
    with app.test_client() as c:
        yield c

And I have tests like this:

from flask import session

def test_my_redirect_view(test_client):
    "It should redirect and set the correct flash message"
    response = test_client.get("/my/path", follow_redirects=False)

    assert response.status_code == 302
    assert response.location == "http://localhost/a/different/url"

    assert "_flashes" in session
    assert len(session["_flashes"]) == 1
    assert session["_flashes"][0][0] == "warning"
    assert session["_flashes"][0][1] == "My error message"

As I say, assuming my view sets this flash message, and redirects correctly, this test passes. But a subsequent, similar test, will fail because then len(session["_flashes"]) will be 2, because it has the messages from both tested views.

I've tried doing this at the end of each test, but with no apparent effect:

    del session["_flashes"][0]


问:
iPhone - using YouTube APIs in iPhone app
I was going through the Google API for the iPhone but couldn't quite understand the use of YouTube API in iPhone apps. Neither could I find any good tutorials.

Can someone please point to documentation/samples which explain how to use the YouTube API in an iPhone app.

Thanks.

答:
Try out this link

http://gdata.youtube.com/feeds/api/videos?q=%@&start-index=21&max-results=20&v=2

replace the %@ with the text that you are searching it will return you xml parse it and get the data displayed in your controller

Hope this helps

ContentLicense: CC BY-SA 2.5


问:
Could not find com.google.android.gms:strict-version-matcher-plugin:1.1.0
Could not resolve all files for configuration 'classpath'.

Could not find com.google.android.gms:strict-version-matcher-plugin:1.1.0.

Searched in the following locations: https://jcenter.bintray.com/com/google/android/gms/strict-version-matcher-plugin/1.1.0/strict-version-matcher-plugin-1.1.0.pom https://jcenter.bintray.com/com/google/android/gms/strict-version-matcher-plugin/1.1.0/strict-version-matcher-plugin-1.1.0.jar file:/C:/Users/e1706396/.m2/repository/com/google/android/gms/strict-version-matcher-plugin/1.1.0/strict-version-matcher-plugin-1.1.0.pom file:/C:/Users/e1706396/.m2/repository/com/google/android/gms/strict-version-matcher-plugin/1.1.0/strict-version-matcher-plugin-1.1.0.jar Required by: unspecified:unspecified:unspecified > com.google.gms:google-services:4.2.0

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Get more help at https://help.gradle.org

BUILD FAILED in 7s cmd: Command failed with exit code 1

plugin  are i am using

   <plugin name="cordova-plugin-appavailability" spec="^0.4.2" />
    <plugin name="cordova-plugin-camera" spec="^4.0.3" />
    <plugin name="cordova-plugin-compat" spec="^1.2.0" />
    <plugin name="cordova-plugin-device" spec="^2.0.2" />
    <plugin name="cordova-plugin-googleplus" spec="^5.2.1">
        <variable name="REVERSED_CLIENT_ID" value="xxx" />
    </plugin>
    <plugin name="cordova-plugin-ionic-keyboard" spec="^2.0.5" />
    <plugin name="cordova-plugin-ionic-webview" spec="^1.1.19" />
    <plugin name="cordova-plugin-mfp" spec="^8.0.2018070216" />
    <plugin name="cordova-plugin-mfp-push" spec="^8.0.2018040410" />
    <plugin name="cordova-plugin-network-information" spec="^2.0.1" />
    <plugin name="cordova-plugin-splashscreen" spec="^5.0.2" />
    <plugin name="cordova-plugin-whitelist" spec="^1.3.3" />
    <plugin name="cordova-plugin-x-socialsharing" spec="^5.4.1" />
    <plugin name="cordova-wheel-selector-plugin" spec="^1.1.1" />
    <plugin name="info.protonet.imageresizer" spec="^0.1.1" />```
</div>
</div>
</p>

<p><strong>Build gradle using</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>buildscript {
    repositories {
        maven {
            url "https://maven.google.com"
        }
        mavenCentral()
        jcenter()
    }
    dependencies {

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

allprojects {
    repositories {
        maven {
            url "https://maven.google.com"
        }
        jcenter()
    }
    //This replaces project.properties w.r.t. build settings
    project.ext {
      defaultBuildToolsVersion="27.0.1" //String
      defaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4
      defaultTargetSdkVersion=27 //Integer - We ALWAYS target the latest by default
      defaultCompileSdkVersion=27 //Integer - We ALWAYS compile with the latest by default
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}</code>```

dependency may be i think

old or other system working fine

Node -v 3.10.10,
NPM -v  6.10.10

My current system note working getting error

npm -v 6.4.1,
node -v 8.12.0
node -v

答:
I fixed this by adding maven { url "https://maven.google.com" } to the build.gradle repositories from the cordova-support-google-services plugin. The final file now looks like this:

```<code>buildscript {
    repositories {
        maven { url "https://maven.google.com" }
        jcenter()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.+'
        classpath 'com.google.gms:google-services:4.2.0'
    }
}
</code>```

I'm using Gradle 4.1.

Body:
Could not resolve all files for configuration 'classpath'.

Could not find com.google.android.gms:strict-version-matcher-plugin:1.1.0.

Searched in the following locations: https://jcenter.bintray.com/com/google/android/gms/strict-version-matcher-plugin/1.1.0/strict-version-matcher-plugin-1.1.0.pom https://jcenter.bintray.com/com/google/android/gms/strict-version-matcher-plugin/1.1.0/strict-version-matcher-plugin-1.1.0.jar file:/C:/Users/e1706396/.m2/repository/com/google/android/gms/strict-version-matcher-plugin/1.1.0/strict-version-matcher-plugin-1.1.0.pom file:/C:/Users/e1706396/.m2/repository/com/google/android/gms/strict-version-matcher-plugin/1.1.0/strict-version-matcher-plugin-1.1.0.jar Required by: unspecified:unspecified:unspecified > com.google.gms:google-services:4.2.0

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Get more help at https://help.gradle.org

BUILD FAILED in 7s cmd: Command failed with exit code 1

plugin  are i am using

   <plugin name="cordova-plugin-appavailability" spec="^0.4.2" />
    <plugin name="cordova-plugin-camera" spec="^4.0.3" />
    <plugin name="cordova-plugin-compat" spec="^1.2.0" />
    <plugin name="cordova-plugin-device" spec="^2.0.2" />
    <plugin name="cordova-plugin-googleplus" spec="^5.2.1">
        <variable name="REVERSED_CLIENT_ID" value="xxx" />
    </plugin>
    <plugin name="cordova-plugin-ionic-keyboard" spec="^2.0.5" />
    <plugin name="cordova-plugin-ionic-webview" spec="^1.1.19" />
    <plugin name="cordova-plugin-mfp" spec="^8.0.2018070216" />
    <plugin name="cordova-plugin-mfp-push" spec="^8.0.2018040410" />
    <plugin name="cordova-plugin-network-information" spec="^2.0.1" />
    <plugin name="cordova-plugin-splashscreen" spec="^5.0.2" />
    <plugin name="cordova-plugin-whitelist" spec="^1.3.3" />
    <plugin name="cordova-plugin-x-socialsharing" spec="^5.4.1" />
    <plugin name="cordova-wheel-selector-plugin" spec="^1.1.1" />
    <plugin name="info.protonet.imageresizer" spec="^0.1.1" />

Build gradle using

buildscript {
    repositories {
        maven {
            url "https://maven.google.com"
        }
        mavenCentral()
        jcenter()
    }
    dependencies {

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

allprojects {
    repositories {
        maven {
            url "https://maven.google.com"
        }
        jcenter()
    }
    //This replaces project.properties w.r.t. build settings
    project.ext {
      defaultBuildToolsVersion="27.0.1" //String
      defaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4
      defaultTargetSdkVersion=27 //Integer - We ALWAYS target the latest by default
      defaultCompileSdkVersion=27 //Integer - We ALWAYS compile with the latest by default
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

dependency may be i think

old or other system working fine

Node -v 3.10.10,
NPM -v  6.10.10

My current system note working getting error

npm -v 6.4.1,
node -v 8.12.0
node -v

Body:
I fixed this by adding maven { url "https://maven.google.com" } to the build.gradle repositories from the cordova-support-google-services plugin. The final file now looks like this:

buildscript {
    repositories {
        maven { url "https://maven.google.com" }
        jcenter()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.+'
        classpath 'com.google.gms:google-services:4.2.0'
    }
}

I'm using Gradle 4.1.


问:
Tunnel data-variables through env-variable with "{{" operator
Following the example from https://www.tidyverse.org/blog/2020/02/glue-strings-and-tidy-eval/

How do you pass variables into this function?

library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.2
#> Warning: package 'tidyr' was built under R version 3.6.2

mean_by <- function(data, by, var, prefix = "avg") {
  data %>%
    group_by({{ by }}) %>%
    summarise("{prefix}_{{ var }}" := mean({{ var }}, na.rm = TRUE))
}

mean_by(mtcars, by = cyl, var = mpg, prefix = "avg")
#> # A tibble: 3 x 2
#>     cyl avg_mpg
#>   <dbl>   <dbl>
#> 1     4    26.7
#> 2     6    19.7
#> 3     8    15.1

# Variables to pass into function
params <-  setdiff(colnames(mtcars) ,"mpg")

# How do you pass a variables into this function?
purrr::map(params, mean_by(mtcars, by = .x, var = mpg, prefix = "avg"))
#> Error: Column `.x` is unknown
```

Created on 2020-02-19 by the reprex package (v0.3.0)

答:
Use the .data pronoun with the column name:

purrr::map(params, ~ mean_by(mtcars, by = .data[[.x]], var = mpg, prefix = "avg"))
```

Body:
Following the example from https://www.tidyverse.org/blog/2020/02/glue-strings-and-tidy-eval/

How do you pass variables into this function?

library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.2
#> Warning: package 'tidyr' was built under R version 3.6.2

mean_by <- function(data, by, var, prefix = "avg") {
  data %>%
    group_by({{ by }}) %>%
    summarise("{prefix}_{{ var }}" := mean({{ var }}, na.rm = TRUE))
}

mean_by(mtcars, by = cyl, var = mpg, prefix = "avg")
#> # A tibble: 3 x 2
#>     cyl avg_mpg
#>   <dbl>   <dbl>
#> 1     4    26.7
#> 2     6    19.7
#> 3     8    15.1

# Variables to pass into function
params <-  setdiff(colnames(mtcars) ,"mpg")

# How do you pass a variables into this function?
purrr::map(params, mean_by(mtcars, by = .x, var = mpg, prefix = "avg"))
#> Error: Column `.x` is unknown

Created on 2020-02-19 by the reprex package (v0.3.0)


问:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays in angular 8
i want to render the list of users using the ngFor directive, but when i try to do this console is showing the error that.

Error

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Group-component.ts

```<code>groupUsers: any[] = [];

this.groupService.getGroupUsers(this.groupId)
  .subscribe(groupUsers => {
    this.groupUsers = groupUsers;
  });
</code>```

Group-service.ts

```<code>getGroupUsers(groupId: number): Observable<any[]> {
      return this.http.get<any[]>(this.baseUrl + 'GroupAttendance/GroupUsers/' + groupId);
}
</code>```

Group-component.html

{{ user.user.knownAs }}

```

Here is the response getting the data from the server

I don't know why console show me this error

答:
It seems that groupUsers is not an array. check again your response type.

Did you try to console.log(groupUsers) in your subscribe ?

Body:
i want to render the list of users using the ngFor directive, but when i try to do this console is showing the error that.

Error

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Group-component.ts

groupUsers: any[] = [];

this.groupService.getGroupUsers(this.groupId)
  .subscribe(groupUsers => {
    this.groupUsers = groupUsers;
  });

Group-service.ts

getGroupUsers(groupId: number): Observable<any[]> {
      return this.http.get<any[]>(this.baseUrl + 'GroupAttendance/GroupUsers/' + groupId);
}

Group-component.html

{{ user.user.knownAs }}

Here is the response getting the data from the server

I don't know why console show me this error


问:
read blade variable within the route function
I have a system in Laravel and when I am in the view I build the template with links, I need to insert a route dynamically like this:

```<code><ul class="breadcrumbs pull-left">
    <li><a href="{{route('home')}}">Home</a></li>
    <li><a href="{{route('$route.index')}}">{{$title}}</a></li>
    <li><span>{{$activeList}}</span></li>
</ul>
</code>```

how to read blade variable within the route function?

this dont work:

```<code>{{route('$route.index')}}
</code>```

error: "Route [$active.index] not defined. (View: C:\xampp\htdocs\systemass\resources\views\templates\srtdash\inc\pagearea.blade.php) (View: C:\xampp\htdocs\systemass\resources\views\templates\srtdash\inc\pagearea.blade.php) (View: C:\xampp\htdocs\systemass\resources\views\templates\srtdash\inc\pagearea.blade.php

答:
just use the variable content instead

Home

{{$title}}

{{$activeList}}

```

Body:
I have a system in Laravel and when I am in the view I build the template with links, I need to insert a route dynamically like this:

Home

{{$title}}

{{$activeList}}

how to read blade variable within the route function?

this dont work:

{{route('$route.index')}}

error: "Route [$active.index] not defined. (View: C:\xampp\htdocs\systemass\resources\views\templates\srtdash\inc\pagearea.blade.php) (View: C:\xampp\htdocs\systemass\resources\views\templates\srtdash\inc\pagearea.blade.php) (View: C:\xampp\htdocs\systemass\resources\views\templates\srtdash\inc\pagearea.blade.php

Body:
just use the variable content instead

<ul class="breadcrumbs pull-left">
    <li><a href="{{route('home')}}">Home</a></li>
    <li><a href="{{route($active.'.index')}}">{{$title}}</a></li>
    <li><span>{{$activeList}}</span></li>
</ul>


问:
Is there PHP mysql_real_escape_string for postgresql?
Is there PHP mysql_real_escape_string for postgresql?
if yes then how ? please Give the Examples? & also the work of this string</p>

答: You have both pg_escape_string and pg_escape_bytea available.


问:
Another Repeated column in mapping for entity error
Despite all of the others post, I can't find a solution for this error with GlassFish, on MacOSX, NetBeans 7.2.

```<code>Here the error :
SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer
prepare method
SEVERE: Exception while preparing the app
SEVERE: [PersistenceUnit: supmarket] Unable to build EntityManagerFactory

...

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity:
com.supmarket.entity.Sale column: customerId
(should be mapped with insert="false" update="false")
</code>```

Here the code :

Sale.java

```<code>@Entity
public class Sale {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable=false)
    private Long idFromAgency;

    private float amountSold;

    private String agency;

    @Temporal(javax.persistence.TemporalType.DATE)
    private Date createdate;

    @Column(nullable=false)
    private Long productId;

    @Column(nullable=false)
    private Long customerId;

    @ManyToOne(optional=false)
    @JoinColumn(name="productId",referencedColumnName="id_product")
    private Product product;

    @ManyToOne(optional=false)
    @JoinColumn(name="customerId",referencedColumnName="id_customer")
    private Customer customer;

    public void Sale(){}
    public void Sale(Long idFromAgency, float amountSold, String agency
            , Date createDate, Long productId, Long customerId){
        ...
    }

    // then getters/setters
}
</code>```

Customer.java

```<code>@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id_customer")
    private Long id_customer;

    @Column(nullable=false)
    private Long idFromAgency;

    private String  gender,
                    maritalState,
                    firstname,
                    lastname,
                    incomeLevel;

    @OneToMany(mappedBy="customer",targetEntity=Sale.class, fetch=FetchType.EAGER)
    private Collection sales;

    public void Customer(){}

    public void Customer(Long idFromAgency, String gender, String maritalState,
            String firstname, String lastname, String incomeLevel) {
        ...
    }

}
</code>```

Product.java

```<code>public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id_product")
    private Long id_product;

    @Column(nullable=false)
    private Long idFromAgency;

    private String name;

    @OneToMany(mappedBy="product",targetEntity=Sale.class, fetch=FetchType.EAGER)
    private Collection sales;

    //constructors + getters +setters
}
</code>```

答:
This means you are mapping a column twice in your entity class.
Explaining with an example...

    @Column(name = "column1")
    private String object1;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "column1", referencedColumnName = "column1")
    private TableClass object2;
```

<blockquote>
  <p>The problem in the above code snippet is we are repeating mapping...</p>
</blockquote>

<p><strong>Solution</strong></p>

<p>Since mapping is an important part, you don't want to remove that. Instead, you will remove </p>

<pre class="lang-java prettyprint-override"><code>    @Column(name = "column1")
    private String uniqueId;
</code>```

You can still pass the value of object1 by creating a object of TableClass and assign the String value of Object1 in it.

This works 100%. I have tested this with Postgres and Oracle database.

Body:
Despite all of the others post, I can't find a solution for this error with GlassFish, on MacOSX, NetBeans 7.2.

Here the error :
SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer
prepare method
SEVERE: Exception while preparing the app
SEVERE: [PersistenceUnit: supmarket] Unable to build EntityManagerFactory

...

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity:
com.supmarket.entity.Sale column: customerId
(should be mapped with insert="false" update="false")

Here the code :

Sale.java

@Entity
public class Sale {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable=false)
    private Long idFromAgency;

    private float amountSold;

    private String agency;

    @Temporal(javax.persistence.TemporalType.DATE)
    private Date createdate;

    @Column(nullable=false)
    private Long productId;

    @Column(nullable=false)
    private Long customerId;

    @ManyToOne(optional=false)
    @JoinColumn(name="productId",referencedColumnName="id_product")
    private Product product;

    @ManyToOne(optional=false)
    @JoinColumn(name="customerId",referencedColumnName="id_customer")
    private Customer customer;

    public void Sale(){}
    public void Sale(Long idFromAgency, float amountSold, String agency
            , Date createDate, Long productId, Long customerId){
        ...
    }

    // then getters/setters
}

Customer.java

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id_customer")
    private Long id_customer;

    @Column(nullable=false)
    private Long idFromAgency;

    private String  gender,
                    maritalState,
                    firstname,
                    lastname,
                    incomeLevel;

    @OneToMany(mappedBy="customer",targetEntity=Sale.class, fetch=FetchType.EAGER)
    private Collection sales;

    public void Customer(){}

    public void Customer(Long idFromAgency, String gender, String maritalState,
            String firstname, String lastname, String incomeLevel) {
        ...
    }

}

Product.java

public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id_product")
    private Long id_product;

    @Column(nullable=false)
    private Long idFromAgency;

    private String name;

    @OneToMany(mappedBy="product",targetEntity=Sale.class, fetch=FetchType.EAGER)
    private Collection sales;

    //constructors + getters +setters
}

Body:
This means you are mapping a column twice in your entity class.
Explaining with an example...

    @Column(name = "column1")
    private String object1;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "column1", referencedColumnName = "column1")
    private TableClass object2;

The problem in the above code snippet is we are repeating mapping...

Solution

Since mapping is an important part, you don't want to remove that. Instead, you will remove

    @Column(name = "column1")
    private String uniqueId;

You can still pass the value of object1 by creating a object of TableClass and assign the String value of Object1 in it.

This works 100%. I have tested this with Postgres and Oracle database.


答:
I think regex is the wrong tool for the job here, consider loading your HTML into a DOM document and parsing it using DOM selectors instead.

The following example is javascript, because it will allow me to include it as a runnable snippet - but it should explain the approach enough for you to create the python equivalent.

var classElements = document.querySelectorAll("[class]");

for(i = 0; i < classElements.length; i++)
{
 console.log(classElements[i].className + ": " + classElements[i].tagName);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header_container container_12">
        <div class="grid_5">
              <h1>Logo Text Here</h1>
        </div>
        <div class="grid_7">
            <div class="menu_items">
                HomePortfolio
               About Me
                Contact Me
        </div>
</div></code>```

Title: Regex to capture html elements with their class name

Body:
I am trying to get the element and class name for all elements within an html file using python. I managed to get all class names with the code below. It's written like that because I will go through a lot of html files while storing elements with their class names. Ignoring elements without a class name.

 temp_file = open(root + "/" + file, "r", encoding="utf-8-sig", errors="ignore")
    temp_content = temp_file.read()
    class_names = re.findall("class=\"(.*?)\"", temp_content)

However now I am struggling to find a way to get the element that the class belongs to. Keep in mind that elements sometimes overlap with each other, so readlines() won't help too much either and it would proabably be slower than regexing the entire document at once.

Logo Text Here

                HomePortfolio
               About Me
                Contact Me

The above html snippet is badly indented on purpose, to showcase the kind of data I am working with...
The goal would be to maybe store them in a hashmap.
i.e.

"header_Container container_12": "div"
 "grid_5": "div"
 "grid_7": "div"
 "menu_items": "div"
 "home active": "a"
 "portfolio": "a"
 "about": "a"
 "contact": "a"

Body:
I think regex is the wrong tool for the job here, consider loading your HTML into a DOM document and parsing it using DOM selectors instead.

The following example is javascript, because it will allow me to include it as a runnable snippet - but it should explain the approach enough for you to create the python equivalent.

var classElements = document.querySelectorAll("[class]");

for(i = 0; i < classElements.length; i++)
{
 console.log(classElements[i].className + ": " + classElements[i].tagName);
}

<div class="header_container container_12">
        <div class="grid_5">
              <h1><a href="#">Logo Text Here</a></h1>
        </div>
        <div class="grid_7">
            <div class="menu_items">
                <a href="#" class="home active">Home</a><a href="#" class="portfolio">Portfolio</a>
               <a href="#"
                class="about">About Me
                </a><a href="#" class="contact">Contact Me</a>
        </div>
</div>


问:
Fatal error: Cannot use object of type stdClass as array in
I'm getting the error:

"Fatal error: Cannot use object of type stdClass as array in" on line 183

From this code:

```<code>$getvidids = $ci->db->query(
    "SELECT * FROM videogroupids " .
    "WHERE videogroupid='$videogroup' AND used='0' LIMIT 10");

foreach ($getvidids->result() as $row){
    $vidid = $row['videoid'];              //This is line 183
}
</code>```

Anyone know what's wrong with the above code? Or what this error means?

答:
Controller (Example: User.php)

```<code><?php
defined('BASEPATH') or exit('No direct script access allowed');

class Users extends CI_controller
{

    // Table
    protected  $table = 'users';

    function index()
    {
        $data['users'] = $this->model->ra_object($this->table);
        $this->load->view('users_list', $data);
    }
}
</code>```

View (Example: users_list.php)

```<code><table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Surname</th>
        </tr>
    </thead>

    <tbody>
        <?php foreach($users as $user) : ?>
            <tr>
            <td><?php echo $user->name; ?></td>
            <td><?php echo $user->surname; ?></th>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<!-- // User table -->
</code>```

Body:
I'm getting the error:

"Fatal error: Cannot use object of type stdClass as array in" on line 183

From this code:

$getvidids = $ci->db->query(
    "SELECT * FROM videogroupids " .
    "WHERE videogroupid='$videogroup' AND used='0' LIMIT 10");

foreach ($getvidids->result() as $row){
    $vidid = $row['videoid'];              //This is line 183
}

Anyone know what's wrong with the above code? Or what this error means?

Body:
Controller (Example: User.php)

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Users extends CI_controller
{

    // Table
    protected  $table = 'users';

    function index()
    {
        $data['users'] = $this->model->ra_object($this->table);
        $this->load->view('users_list', $data);
    }
}

View (Example: users_list.php)

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Surname</th>
        </tr>
    </thead>

    <tbody>
        <?php foreach($users as $user) : ?>
            <tr>
            <td><?php echo $user->name; ?></td>
            <td><?php echo $user->surname; ?></th>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<!-- // User table -->


问:
I'm not getting proper output for checking a string to be palindrome or not
I am not getting expected output while running the program

```<code>print('----------palindrome or not---------')
line=input('enter a line:-')
length=len(line)
a=0
if(length%2==0):
    length1=length/2
else:
    length1=(length+1)/2
for i in range (0,length-1):
    if(line[i]==line[length-2]):
        a+=1
if(a==length1):
    print("entered line is palindrome")
else:
    print("entered line is not palindrome")
</code>```

OUTPUT:

答:
What about this simple function?</p>

```<code>def is_palindrome(text):
    return text == text[::-1]
</code>```

Body:
I am not getting expected output while running the program

print('----------palindrome or not---------')
line=input('enter a line:-')
length=len(line)
a=0
if(length%2==0):
    length1=length/2
else:
    length1=(length+1)/2
for i in range (0,length-1):
    if(line[i]==line[length-2]):
        a+=1
if(a==length1):
    print("entered line is palindrome")
else:
    print("entered line is not palindrome")

OUTPUT:

Body:
What about this simple function?

def is_palindrome(text):
    return text == text[::-1]


问:
Dealing with concurrency and complex WCF services interacting with objects of the overall application
I am enjoying creating and hosting WCF services.
Up until now I can create services defining contracts for the service and data (interfaces) and defining hosts and configuration options to reach them (endpoint specifications).

Well, consider this piece of code defining a service and using it (no mention for endpoints that are defined in app.config not shown here):

```<code>[ServiceContract]
public interface IMyService {
   [OperationContract]
   string Operation1(int param1);
   [OperationContract]
   string Operation2(int param2);
}

public class MyService : IMyService {
   public string Operation1(int param1) { ... }
   public string Operation2(int param2) { ... }
}

public class Program {
   public static void Main(stirng[] args) {
      using (ServiceHost host = new ServiceHost(typeof(MyService))) {
         host.Open();
         ...
         host.Close();
      }
   }
}
</code>```

Well, this structure is good when creating something that could be called a Standalone service.
What if I needed my service to use objects of a greater application.
For example I need a service that does something basing on a certain collection defined somewhere in my program (which is hosting the service). The service must look into this collection and search and return a particular element.

The list I am talking about is a list managed by the program and edited and modified by it.

I have the following questions:

1) How can I build a service able to handle this list?
I know that a possible option is using the overloaded ServiceHost constructor accepting an Object instead of a Type service.
So I could pass my list there. Is it good?

```<code>[ServiceContract]
public interface IMyService {
   [OperationContract]
   string Operation1(int param1);
   [OperationContract]
   string Operation2(int param2);
}

public class MyService : IMyService {
   private List<> myinternallist;
   public MyService(List<> mylist) {
      // Constructing the service passing the list
   }
   public string Operation1(int param1) { ... }
   public string Operation2(int param2) { ... }
}

public class Program {
   public static void Main(stirng[] args) {
      List<> thelist;
      ...
      MyService S = new MyService(thelist)
      using (ServiceHost host = new ServiceHost(S)) {
         host.Open();
         ...
         host.Close();
         // Here my application creates a functions and other that manages the queue. For this reason my application will edit the list (it can be a thread or callbacks from the user interface)
      }
   }
}
</code>```

This example should clarify.
Is it the good way of doing? Am I doing right?

2) How to handle conflicts on this shared resource between my service and my application?
When my application runs, hosting the service, my application can insert items in the list and delete them, the same can do the service too. Do I need a mutex? how to handle this?
Please note that the concurrency issue concerns two actors: the main application and the service. It is true that the service is singleton but the application acts on the list!!!
I assume that the service is called by an external entity, when this happens the application still runs right? Is there concurrency in this case???

Thankyou

答:
Regarding point 2, you can use Concurrent Collections to manage most of the thread safety required.

I'm not sure what you mean by point 1.  It sounds like you're describing basic polymorphism, but perhaps you could clarify with an example please?

EDIT:  In response to comments you've made to Sixto's answer, consider using WCF's sessions.  From what you've described it sounds to me like the WCF service should be sat on a seperate host application.  The application you are using currently should have a service reference to the service, and using sessions would be able to call an operation mimicking your requirement for instantiating the service with a list defined by the current client application.

Combine this with my comment on exposing operations that allow interaction with this list, and you'll be able to run multiple client machines, working on session stored Lists?

Hope that's explained well enough.

Body:
I am enjoying creating and hosting WCF services.
Up until now I can create services defining contracts for the service and data (interfaces) and defining hosts and configuration options to reach them (endpoint specifications).

Well, consider this piece of code defining a service and using it (no mention for endpoints that are defined in app.config not shown here):

[ServiceContract]
public interface IMyService {
   [OperationContract]
   string Operation1(int param1);
   [OperationContract]
   string Operation2(int param2);
}

public class MyService : IMyService {
   public string Operation1(int param1) { ... }
   public string Operation2(int param2) { ... }
}

public class Program {
   public static void Main(stirng[] args) {
      using (ServiceHost host = new ServiceHost(typeof(MyService))) {
         host.Open();
         ...
         host.Close();
      }
   }
}

Well, this structure is good when creating something that could be called a Standalone service.
What if I needed my service to use objects of a greater application.
For example I need a service that does something basing on a certain collection defined somewhere in my program (which is hosting the service). The service must look into this collection and search and return a particular element.

The list I am talking about is a list managed by the program and edited and modified by it.

I have the following questions:

1) How can I build a service able to handle this list?
I know that a possible option is using the overloaded ServiceHost constructor accepting an Object instead of a Type service.
So I could pass my list there. Is it good?

[ServiceContract]
public interface IMyService {
   [OperationContract]
   string Operation1(int param1);
   [OperationContract]
   string Operation2(int param2);
}

public class MyService : IMyService {
   private List<> myinternallist;
   public MyService(List<> mylist) {
      // Constructing the service passing the list
   }
   public string Operation1(int param1) { ... }
   public string Operation2(int param2) { ... }
}

public class Program {
   public static void Main(stirng[] args) {
      List<> thelist;
      ...
      MyService S = new MyService(thelist)
      using (ServiceHost host = new ServiceHost(S)) {
         host.Open();
         ...
         host.Close();
         // Here my application creates a functions and other that manages the queue. For this reason my application will edit the list (it can be a thread or callbacks from the user interface)
      }
   }
}

This example should clarify.
Is it the good way of doing? Am I doing right?

2) How to handle conflicts on this shared resource between my service and my application?
When my application runs, hosting the service, my application can insert items in the list and delete them, the same can do the service too. Do I need a mutex? how to handle this?
Please note that the concurrency issue concerns two actors: the main application and the service. It is true that the service is singleton but the application acts on the list!!!
I assume that the service is called by an external entity, when this happens the application still runs right? Is there concurrency in this case???

Thankyou


答:
If both are numpy arrays, you can use pure numpy functions and methods:</p>

```<code>import numpy as np

A = np.arange(1, 10).reshape(3,3)
B = np.arange(10, 19).reshape(3,3)

pairs = np.stack((A,B), axis=2).reshape(-1, 2)
"""
array([[ 1, 10],
   [ 2, 11],
   [ 3, 12],
   [ 4, 13],
   [ 5, 14],
   [ 6, 15],
   [ 7, 16],
   [ 8, 17],
   [ 9, 18]])
"""
</code>```

Title: Using Python to zip and list functions to combine two 2D arrays to produce x,y coordinates?

Body:
I have two, 2D-arrays each of dimensions 831 x 918. If:

Matrix A =[[a(1,1), a(1,2),...],[a(2,1),a(2,2)...]]
Matrix B =[[b(1,1), b(1,2),...],[b(2,1),b(2,2)...]]

I would like to combine the two matrices to create a list with ((a(1,1),b(1,1)),(a(1,2),b(1,2)),...).

What is the best way to do this? I have tried to use the zip and list functions as shown below:

import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt

ly=fits.open(lightyield.fits)
ly=ly[0].data
dx=fits.open(de.fits)
dx=dx[0].data
combo=list(zip(dx,ly))

However, this returns a list that is 831 elements long, but each position on the list has a lot of elements. I only want to have a single (x,y) point for each element in the list, not an entire array.

Thanks for any help.
EDIT: As a basic example, for:
 A=[[1,2,3],[4,5,6],[7,8,9]]
 B=[[10,11,12],[13,14,15],[16,17,18]]

I want to get a list to plot of ((1,10),(2,11),(3,12),...).

Body:
If both are numpy arrays, you can use pure numpy functions and methods:

import numpy as np

A = np.arange(1, 10).reshape(3,3)
B = np.arange(10, 19).reshape(3,3)

pairs = np.stack((A,B), axis=2).reshape(-1, 2)
"""
array([[ 1, 10],
   [ 2, 11],
   [ 3, 12],
   [ 4, 13],
   [ 5, 14],
   [ 6, 15],
   [ 7, 16],
   [ 8, 17],
   [ 9, 18]])
"""


问:
Assign different aggregation functions to different features in pandas groupby
I have a data like below (Instead of 4 columns I have 100 columns)

```<code>raw_data = {
        'age': [52, 52, 24, 24, 24],
        'a': [4, 24, 31, 2, 3],
        'b': [3, 2, 3, 4, 3],
        'c': [2, 5, 8, 2, 1]}
df = pd.DataFrame(raw_data, columns = [ 'age', 'a', 'b', 'c'])
</code>```

which results in

```<code>    age a   b   c
0   52  4   3   2
1   52  24  2   5
2   24  31  3   8
3   24  2   4   2
4   24  3   3   1
</code>```

I want to group data by age and find mean of some features and sum of remaining features. I have tried this:

```<code>feats = ['a', 'b']
df.groupby('age').agg({feats:['mean'], 'c':['sum']})
</code>```

Since I have 100 features in real data, I cannot assign functions (I have multiple functions to assign: RMS, Kurtosis, Energy Index, etc) to individual feature (I can but it is very time consuming and not smart) Is there any way I can achieve this?

答:
Use dictionary comprehension.

```<code>agg_d = {i:'mean' for i in feats}
agg_d['c'] = 'sum'

df.groupby('age').agg(agg_d)
</code>```

Output:

```<code>      a         b   c
age
24   12  3.333333  11
52   14  2.500000   7
</code>```

Update, and you can use multiple aggregation function using a list:

```<code>agg_d = {i:['sum','max','first', lambda x: sum(x**2)] for i in feats}
agg_d['c'] = 'sum'
</code>```

Body:
I have a data like below (Instead of 4 columns I have 100 columns)

raw_data = {
        'age': [52, 52, 24, 24, 24],
        'a': [4, 24, 31, 2, 3],
        'b': [3, 2, 3, 4, 3],
        'c': [2, 5, 8, 2, 1]}
df = pd.DataFrame(raw_data, columns = [ 'age', 'a', 'b', 'c'])

which results in

    age a   b   c
0   52  4   3   2
1   52  24  2   5
2   24  31  3   8
3   24  2   4   2
4   24  3   3   1

I want to group data by age and find mean of some features and sum of remaining features. I have tried this:

feats = ['a', 'b']
df.groupby('age').agg({feats:['mean'], 'c':['sum']})

Since I have 100 features in real data, I cannot assign functions (I have multiple functions to assign: RMS, Kurtosis, Energy Index, etc) to individual feature (I can but it is very time consuming and not smart) Is there any way I can achieve this?

Body:
Use dictionary comprehension.

agg_d = {i:'mean' for i in feats}
agg_d['c'] = 'sum'

df.groupby('age').agg(agg_d)

Output:

      a         b   c
age
24   12  3.333333  11
52   14  2.500000   7

Update, and you can use multiple aggregation function using a list:

agg_d = {i:['sum','max','first', lambda x: sum(x**2)] for i in feats}
agg_d['c'] = 'sum'


问:
Convert date/time format from Etc/GMT to ISO
I need to convert date/time values.

For example I want to convert this "2019-11-21 09:53:10 Etc/GMT" to a value with the same format as this "2020-02-13T15:24:47.977Z".

If you can provide the resulting equivalent value of the given example, I can make that as reference so I can already find the correct code for the conversion.

Or else if you can provide the exact javascript code for the conversion, that is better. I am using 'moment' and 'moment-timezone'.

答:
You just have to pass the your date string in this format 2019 11 21 09:53:10 GMT

let date = new Date('2019 11 21 09:53:10 GMT');
console.log(date.toISOString());```


问:
How do you pass variables to other JS modules with Fetch API?
A JavaScript app uses Web Audio API to create sounds from JSON data. I am fetching weather data, going through the JSON data and setting their properties to variables then using those variables to manipulate my application and create sounds. Each function in it's own JavaScript module script file. The main.js not shown here is the entry point to app.

A sample JSON that will get replaced with real weather data.

dummy-data.json

```<code>{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}
</code>```

The fetch API logic.

fetchWeather.js

```<code>import { manageData} from './manageScript.js';

const DUMMY = '../dummy-data.json';

const fetchWeather = () => {
    fetch(DUMMY)
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            manageData(data); // attaches JSON weather properties to variables
        })
        .catch((error) => {
            console.log(error);
        });
};

export { fetchWeather };
</code>```

Attaches the JSON data to variables.

manageScript.js

```<code>function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    }
    else {
        rainProbability = 0;
    }

    return rainProbability; // not sure how to return the data....?
};

export { manageData };
</code>```

I want the variables from manageData function above to work here

makeSynth.js

```<code>import { manageData } from './manageScript.js';

const createSynth = () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //How do I get the variables to work here. Code below does not work!
    let soundOfRain = manageData().rainProbability;
    console.log(soundOfRain);
};
</code>```

答:
<pre class="lang-js prettyprint-override"><code>// dummy-data.json

{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}

// fetchWeather.js

import { getRainProbability } from './get-rain-probability.js'
import { createSynth } from './create-synth.js'

const DUMMY = '../dummy-data.json'

const fetchWeather = () => {
    return fetch(DUMMY)
        .then((res) => res.json())
        .then((data) => {
            createSynth({ rainProbability: getRainProbability(data) })
        })
        .catch((error) => {
            console.log(error)
        });
};

export { fetchWeather }

// get-rain-probability.js

function getRainProbability(data) {
    let rain = data.weather.rain

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    }
    else {
        rainProbability = 0;
    }

    return rainProbability; // not sure how to return the data....?
};

// create-synth.js

const createSynth = ({ rainProbability }) => {
    const soundOfRain = //WebAPI stuff for audio using `rainProbability`
    console.log(soundOfRain);
};

export { createSynth }
</code>```

Body:
A JavaScript app uses Web Audio API to create sounds from JSON data. I am fetching weather data, going through the JSON data and setting their properties to variables then using those variables to manipulate my application and create sounds. Each function in it's own JavaScript module script file. The main.js not shown here is the entry point to app.

A sample JSON that will get replaced with real weather data.

dummy-data.json

{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}

The fetch API logic.

fetchWeather.js

import { manageData} from './manageScript.js';

const DUMMY = '../dummy-data.json';

const fetchWeather = () => {
    fetch(DUMMY)
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            manageData(data); // attaches JSON weather properties to variables
        })
        .catch((error) => {
            console.log(error);
        });
};

export { fetchWeather };

Attaches the JSON data to variables.

manageScript.js

function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    }
    else {
        rainProbability = 0;
    }

    return rainProbability; // not sure how to return the data....?
};

export { manageData };

I want the variables from manageData function above to work here

makeSynth.js

import { manageData } from './manageScript.js';

const createSynth = () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //How do I get the variables to work here. Code below does not work!
    let soundOfRain = manageData().rainProbability;
    console.log(soundOfRain);
};


问:
Variable declaration and assignment inside a constructor in C++
For the following code:

```<code>    class mgraph
    {
        private:
            int n;
            vector <vector <int>> vec;

        public:
            mgraph(int);
            void connect(int, int, int);
            void disconnect(int, int);
            void isconnected(int, int);
            void AddNode();
            void show();
    };

    mgraph::mgraph(int nodes)
    {
        n = ++nodes;
        vector <vector<int>> vec(n, vector<int>(n, 0));
        this -> vec = vec;
    }
</code>```

Why doesn't the vec assigned to vec (using this pointer) get destroyed as soon as the constructor's task is over. I got the desired values (not the garbage values) after doing this but shouldn't the vector vec created in the constructor get destroyed after the constructor's task is over?

答:
You are right, vec is an automatic variable, so its scope is confined to the constructor. Its lifetime ends thus on exiting the constructor and it's destroyed.

However, the line

```<code>this -> vec = vec;
</code>```

is a copy assignment. The content of vec is copied into this->vec, the implementation of std::vector takes care of that. So it doesn't matter anymore what happens to the local vec, this->vec has its own copy from now on.

You mention pointers... no pointers are involved. Just some copying.

Body:
For the following code:

    class mgraph
    {
        private:
            int n;
            vector <vector <int>> vec;

        public:
            mgraph(int);
            void connect(int, int, int);
            void disconnect(int, int);
            void isconnected(int, int);
            void AddNode();
            void show();
    };

    mgraph::mgraph(int nodes)
    {
        n = ++nodes;
        vector <vector<int>> vec(n, vector<int>(n, 0));
        this -> vec = vec;
    }

Why doesn't the vec assigned to vec (using this pointer) get destroyed as soon as the constructor's task is over. I got the desired values (not the garbage values) after doing this but shouldn't the vector vec created in the constructor get destroyed after the constructor's task is over?

Body:
You are right, vec is an automatic variable, so its scope is confined to the constructor. Its lifetime ends thus on exiting the constructor and it's destroyed.

However, the line

this -> vec = vec;

is a copy assignment. The content of vec is copied into this->vec, the implementation of std::vector takes care of that. So it doesn't matter anymore what happens to the local vec, this->vec has its own copy from now on.

You mention pointers... no pointers are involved. Just some copying.


问:
How to show polylines on map
I tried to show the polylines and it shows the correct line when I put it in onLocationResult.

However, I only want it to show polylines when the user clicks on the start button.
So I tried to put the code into onClickListener, the screen only displays the marker but not the lines.

```<code>Location mLastLocation;
    LocationRequest mLocationRequest;
    private SupportMapFragment mapFragment;
    private FusedLocationProviderClient mFusedLocationClient;
    private FirebaseAuth myAuth;
    private FirebaseDatabase mDatabase;
    private DatabaseReference myRef;
    private Marker currentUserLocationMarker;
    private ArrayList<LatLng> points; //added
    Polyline line;
    private Button btnStartRun;
    LatLng latLng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_googls_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        points = new ArrayList<LatLng>();

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        btnStartRun=findViewById(R.id.btnStartRun);

        btnStartRun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                points.add(latLng);//add points to the array
                redrawLine();

                myAuth=FirebaseAuth.getInstance();
                DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("OnlineUsers");//.child("OnlineUser");
                DatabaseReference currentUserDB=mDatabase.child(myAuth.getCurrentUser().getUid());
                currentUserDB.child("CurrentLatitude").setValue(mLastLocation.getLatitude());
                currentUserDB.child("CurrentLongitude").setValue(mLastLocation.getLongitude());
            }
        });
    }
</code>```

Here is my onLocationResult

```<code> LocationCallback mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            for (Location location : locationResult.getLocations()) {
                mLastLocation = location;

                latLng = new LatLng(location.getLatitude(), location.getLongitude());

                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

            }
        }
    };
</code>```

Here is my redrawline()

```<code>    private void redrawLine(){

        mMap.clear();  //clears all Markers and Polylines

        PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);//set the colour and width of the polyline
        for (int i = 0; i < points.size(); i++) {
            LatLng point = points.get(i);
            options.add(point);
        }
        addMarker(); //add Marker in current position
        line = mMap.addPolyline(options); //add Polyline
    }
</code>```

Thank you.

答:
You are only adding to points on the button click, but that is incorrect.  You should be adding to points every time you get an onLocationChanged (or perhaps your location callback), otherwise, you don't have any line to draw.

Your onLocationChanged (or callback) should call the redrawLine method every time.

Your redrawLine method should have a flag, such as hasStarted.  If hasStarted = false, then clear the map, but don't draw the line.  If hasStarted = true, then clear the map and DO draw the line.

In the onClick listener, simply set hasStarted = true (or, if you want it to be a toggle, say hasStarted = !hasStarted).

Title: How to show polylines on map

Body:
I tried to show the polylines and it shows the correct line when I put it in onLocationResult.

However, I only want it to show polylines when the user clicks on the start button.
So I tried to put the code into onClickListener, the screen only displays the marker but not the lines.

Location mLastLocation;
    LocationRequest mLocationRequest;
    private SupportMapFragment mapFragment;
    private FusedLocationProviderClient mFusedLocationClient;
    private FirebaseAuth myAuth;
    private FirebaseDatabase mDatabase;
    private DatabaseReference myRef;
    private Marker currentUserLocationMarker;
    private ArrayList<LatLng> points; //added
    Polyline line;
    private Button btnStartRun;
    LatLng latLng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_googls_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        points = new ArrayList<LatLng>();

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        btnStartRun=findViewById(R.id.btnStartRun);

        btnStartRun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                points.add(latLng);//add points to the array
                redrawLine();

                myAuth=FirebaseAuth.getInstance();
                DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("OnlineUsers");//.child("OnlineUser");
                DatabaseReference currentUserDB=mDatabase.child(myAuth.getCurrentUser().getUid());
                currentUserDB.child("CurrentLatitude").setValue(mLastLocation.getLatitude());
                currentUserDB.child("CurrentLongitude").setValue(mLastLocation.getLongitude());
            }
        });
    }

Here is my onLocationResult

 LocationCallback mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            for (Location location : locationResult.getLocations()) {
                mLastLocation = location;

                latLng = new LatLng(location.getLatitude(), location.getLongitude());

                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

            }
        }
    };

Here is my redrawline()

    private void redrawLine(){

        mMap.clear();  //clears all Markers and Polylines

        PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);//set the colour and width of the polyline
        for (int i = 0; i < points.size(); i++) {
            LatLng point = points.get(i);
            options.add(point);
        }
        addMarker(); //add Marker in current position
        line = mMap.addPolyline(options); //add Polyline
    }

Thank you.


问:
How to wrap a long text having no spaces in php

Possible Duplicate:

  How to wrap long lines without spaces in HTML?

I have a long text "jkjkllllllllljcsccncnmchdkcjhvcjdkvk".how to wrap this text in php

答:
Use this:</p>

```<code><?php
$iamlong = "woooooooooooord.";
$iamwrapped = wordwrap($iamlong , 8, "<br>", true);

echo $iamwrapped;
?>
</code>```

Body:
Use this:

<?php
$iamlong = "woooooooooooord.";
$iamwrapped = wordwrap($iamlong , 8, "<br>", true);

echo $iamwrapped;
?>


问:
Panel Data Time Series (Add TimeStamps with interpolated values)
I have a panel dataset with missing time stamps including values for some identities in a dataframe.

```<code>Index      Identiy Value
2015-01-01   A      13
2017-01-01   A      14
2018-01-01   A      24
2019-01-01   A      30
2015-01-01   B      10
2016-01-01   B      12
2017-01-01   B      18
2018-01-01   B      25
2019-01-01   B      30
</code>```

How is it possible to automatically check if certain time stamps (gaps) are missing and then creat a row with the interpolated value. Easier, how can i  add a row in the dataframe with the follwing info.

```<code>Index         Identity        Value
2016-0101         A         13,5 (Interpolated between the gap (13,5)
</code>```

This should only be done to gaps with less then 6 missing points.

I understand the interpolate function but unforunately can not bed it into the creation of row.
Can anyone help?

答:
Use GroupBy with resample to yearly, so we add the missing years to our data per Identity, then interpolate and finally set your index to beginning of year with pd.offsets.YearBegin:

```<code>dfn = df.groupby('Identiy').apply(lambda x: x.resample('Y').first().interpolate(limit=5).ffill())

dfn.index = dfn.index.droplevel(0) - pd.offsets.YearBegin()

           Identiy  Value
2015-01-01       A   13.0
2016-01-01       A   13.5
2017-01-01       A   14.0
2018-01-01       A   24.0
2019-01-01       A   30.0
2015-01-01       B   10.0
2016-01-01       B   12.0
2017-01-01       B   18.0
2018-01-01       B   25.0
2019-01-01       B   30.0
</code>```

Body:
I have a panel dataset with missing time stamps including values for some identities in a dataframe.

Index      Identiy Value
2015-01-01   A      13
2017-01-01   A      14
2018-01-01   A      24
2019-01-01   A      30
2015-01-01   B      10
2016-01-01   B      12
2017-01-01   B      18
2018-01-01   B      25
2019-01-01   B      30

How is it possible to automatically check if certain time stamps (gaps) are missing and then creat a row with the interpolated value. Easier, how can i  add a row in the dataframe with the follwing info.

Index         Identity        Value
2016-0101         A         13,5 (Interpolated between the gap (13,5)

This should only be done to gaps with less then 6 missing points.

I understand the interpolate function but unforunately can not bed it into the creation of row.
Can anyone help?

Body:
Use GroupBy with resample to yearly, so we add the missing years to our data per Identity, then interpolate and finally set your index to beginning of year with pd.offsets.YearBegin:

dfn = df.groupby('Identiy').apply(lambda x: x.resample('Y').first().interpolate(limit=5).ffill())

dfn.index = dfn.index.droplevel(0) - pd.offsets.YearBegin()

           Identiy  Value
2015-01-01       A   13.0
2016-01-01       A   13.5
2017-01-01       A   14.0
2018-01-01       A   24.0
2019-01-01       A   30.0
2015-01-01       B   10.0
2016-01-01       B   12.0
2017-01-01       B   18.0
2018-01-01       B   25.0
2019-01-01       B   30.0


问:
Electron-Angular9 App showing blank white screen in Windows 7 , but working fine on Windows 8
My Electron App built for Windows with electron-builder is working fine on windows 8 , but showing white blank screen when the setup file installed on Windows 7</p>

答: I could fix the issue After installing .NET 4.8 developer pack</p>


问:
multiplying 2 2d matrices and get a 3d matrix out
```<code>import numpy as np

a = np.array([[1,2],[3,4]])

print(a.shape)

c = np.array([[1,2,3]])

print(c.shape)

#wanted result multiplication of a*c would return 2,2,3 shape matrix

final = np.array([[[1,2,3],[2,4,6]],[[3,6,9],[4,8,12]]])

print(final.shape)
print(final)
</code>```

I would like to multiply two matrices with different shapes and basically get a result which would be a 3d matrix. I hope you get the pattern from the code. Is there any simple numpyic way for this? I would appreciate it.

答:
You can use NumPy broadcasting for this:

```<code>a[...,None] * c

array([[[ 1,  2,  3],
        [ 2,  4,  6]],

       [[ 3,  6,  9],
        [ 4,  8, 12]]])
</code>```

The following basically alings the dimensions so the multiplication is broadcast to the desired output shape:

```<code>a[...,None].shape
(2, 2, 1)
</code>```

Body:
import numpy as np

a = np.array([[1,2],[3,4]])

print(a.shape)

c = np.array([[1,2,3]])

print(c.shape)

#wanted result multiplication of a*c would return 2,2,3 shape matrix

final = np.array([[[1,2,3],[2,4,6]],[[3,6,9],[4,8,12]]])

print(final.shape)
print(final)

I would like to multiply two matrices with different shapes and basically get a result which would be a 3d matrix. I hope you get the pattern from the code. Is there any simple numpyic way for this? I would appreciate it.

Body:
You can use NumPy broadcasting for this:

a[...,None] * c

array([[[ 1,  2,  3],
        [ 2,  4,  6]],

       [[ 3,  6,  9],
        [ 4,  8, 12]]])

The following basically alings the dimensions so the multiplication is broadcast to the desired output shape:

a[...,None].shape
(2, 2, 1)


问:
Is there a way to initialize a vector by index in c++11?
It is easy to fill the elements of a vector by index after it has been initialized:

```<code>std::vector<int> myVector {0, 0, 0};
int indexOfInterest = 1;
myVector[indexOfInterest] = 999;
// myVector now contains {0, 999, 0}
</code>```

However, is there a way to initialize a vector directly with the index? indexOfInterest may change in my code in the future, and I would like to avoid hard-coding the vector with

```<code>std::vector<int> myVector {0, 999, 0};
</code>```

Is there some syntax like

```<code>int indexOfInterest = 1;
std::vector<int> myVector[3] {indexOfInterest : 999}; // this is made-up syntax!
// desired: myVector contains {0, 999, 0} and is 3 elements large
</code>```

that can be used in C++11 to achieve this effect?

答:
Another way of doing this would be to use std::unordered_map. Not quite the same thing, but could work for you depending on what you're doing:

```<code>std::unordered_map<int, int> mp{ { indexOfInterest, 999} };
mp[someOtherIndex] = 42;
</code>```

All the indexes you haven't assigned anything to will have the default value (0 in this case) when you try to access them.

Body:
It is easy to fill the elements of a vector by index after it has been initialized:

std::vector<int> myVector {0, 0, 0};
int indexOfInterest = 1;
myVector[indexOfInterest] = 999;
// myVector now contains {0, 999, 0}

However, is there a way to initialize a vector directly with the index? indexOfInterest may change in my code in the future, and I would like to avoid hard-coding the vector with

std::vector<int> myVector {0, 999, 0};

Is there some syntax like

int indexOfInterest = 1;
std::vector<int> myVector[3] {indexOfInterest : 999}; // this is made-up syntax!
// desired: myVector contains {0, 999, 0} and is 3 elements large

that can be used in C++11 to achieve this effect?

Body:
Another way of doing this would be to use std::unordered_map. Not quite the same thing, but could work for you depending on what you're doing:

std::unordered_map<int, int> mp{ { indexOfInterest, 999} };
mp[someOtherIndex] = 42;

All the indexes you haven't assigned anything to will have the default value (0 in this case) when you try to access them.


问:
How does Linux emulator in Javascript by Fabrice Bellard work?
Today I had a jaw dropping moment, when I saw Linux emulator in Javascript:
http://bellard.org/jslinux/

It compiles C programs, it has vi and emacs, it supports all shell commands, etc etc.

How does it work?

答:
At first, I also thought this is just a terminal emulator connecting you to a VM but it isn't. If you watch the network connections, you can see that, after bootup, no data is transmitted anymore.

So it's real.

A CPU is not something magic; in fact all it does is read bytes from memory and modify the RAM in accordance to what the commands mean.

In this case, the CPU emulator is based on the qemu code. What he does is he creates an array of functions where the index is the next byte at the PC (program counter).

Now all you need is a simple linux distribution that doesn't need any exotic CPU commands like floating point arithmetic or MMX code and voila.

What's interesting is the speed of the beast. The whole thing is a bit sluggish but then, it's JavaScript in a browser.

Conclusion: Impressive. Can't wait to see a C64 emulator :-)


问:
C++ typeid template value into union no acceptable conversion
Im trying to build a dictionary of properties that are read in from an XML blender scene and am running into an issue with templates and getting their type_info. The containing map is setup as the name of the property and its value which is stored into a struct of typeinfo and union. Is it possible to do it this way or does it have to recognize it on the specific type? I have made attempts to initialize the struct before passing it to the map, and even to copy the binary data to the union, but it errors everytime on getting typeid(T). And I have also attempted using tuples in the map instead of the struct.
here's the line causing the error

```<code>line 80 = mProperties[name] = std::make_tuple(typeid(T), d);
</code>```

The error

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,std::basic_string<char,std::char_traits<char>,std::allocator<char>>>' (or there is no acceptable conversion)   OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,int>' (or there is no acceptable conversion)   OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,float>' (or there is no acceptable conversion) OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,double>' (or there is no acceptable conversion)    OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,bool>' (or there is no acceptable conversion)  OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676
</code>```

Code:

```<code>private:
    union data
    {
        std::string sVal;
        bool bVal;
        int iVal;
        float fVal;
        double dVal;
    };
    struct propertyData {
        type_info dataType;
        data val;
    };

protected:
    GameObject* Parent;
    std::map<std::string, std::tuple<type_info, data>> mProperties;

public:
    /// Append the property of type T to the property map container
    template<typename T>
    void add_xml_property(std::string name, T d)
    {
        if (mProperties.find(name) == mProperties.end())
        {

            //struct propertyData pData = {typeid(T), d};
            //memcpy_s((void*)&pData.val, sizeof(d), (void*)&d, sizeof(d));
            mProperties[name] = std::make_tuple(typeid(T), d);
        }
    };
</code>```

答:
The copy constructor of std::type_info is deleted so you can't copy those objects into your map. However, typeid() ...

... refers to an object with static storage duration, of the polymorphic type const std::type_info or of some type derived from it.

... so you can store const std::type_info pointers in your map:

```<code>#include <iostream>
#include <map>
#include <string>
#include <typeinfo>
#include <utility>
#include <variant>

using data = std::variant<std::string, bool, int, float, double>;

std::ostream& operator<<(std::ostream& os, const data& v) {
    switch(v.index()) {
    case 0: os << std::get<0>(v); break;
    case 1: os << std::get<1>(v); break;
    case 2: os << std::get<2>(v); break;
    case 3: os << std::get<3>(v); break;
    case 4: os << std::get<4>(v); break;
    }
    return os;
}

std::map<std::string, std::pair<const std::type_info*, data>> mProps;

template<typename T>
void add_xml_property(const std::string& name, T d) {
    if(mProps.find(name) == mProps.end()) mProps[name] = {&typeid(T), d};
}

int main() {
    add_xml_property("foo", std::string("hello"));
    add_xml_property("bar", 123);
    add_xml_property("baz", 3.14159);

    for(auto& [k, v] : mProps)
        std::cout << k << ": " << v.first->name() << '\n' << v.second << "\n\n";
}
</code>```

Possible output:

```<code>bar: i
123

baz: d
3.14159

foo: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
hello
</code>```

Body:
Im trying to build a dictionary of properties that are read in from an XML blender scene and am running into an issue with templates and getting their type_info. The containing map is setup as the name of the property and its value which is stored into a struct of typeinfo and union. Is it possible to do it this way or does it have to recognize it on the specific type? I have made attempts to initialize the struct before passing it to the map, and even to copy the binary data to the union, but it errors everytime on getting typeid(T). And I have also attempted using tuples in the map instead of the struct.
here's the line causing the error

line 80 = mProperties[name] = std::make_tuple(typeid(T), d);

The error

Severity    Code    Description Project File    Line    Suppression State
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,std::basic_string<char,std::char_traits<char>,std::allocator<char>>>' (or there is no acceptable conversion)   OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,int>' (or there is no acceptable conversion)   OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,float>' (or there is no acceptable conversion) OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,double>' (or there is no acceptable conversion)    OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::tuple<type_info,bool>' (or there is no acceptable conversion)  OgreEngine  D:\SchoolAndProjects\Programs\ETGG 3802_01 Realtime Interactive Prog 2\Lab 1\OgreEngine\OgreEngine\include\component.h  80
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676
Error   C2280   'void *std::pair<const std::string,std::tuple<type_info,OgreEngine::Component::data>>::__delDtor(unsigned int)': attempting to reference a deleted function OgreEngine  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\xmemory 676

Code:

private:
    union data
    {
        std::string sVal;
        bool bVal;
        int iVal;
        float fVal;
        double dVal;
    };
    struct propertyData {
        type_info dataType;
        data val;
    };

protected:
    GameObject* Parent;
    std::map<std::string, std::tuple<type_info, data>> mProperties;

public:
    /// Append the property of type T to the property map container
    template<typename T>
    void add_xml_property(std::string name, T d)
    {
        if (mProperties.find(name) == mProperties.end())
        {

            //struct propertyData pData = {typeid(T), d};
            //memcpy_s((void*)&pData.val, sizeof(d), (void*)&d, sizeof(d));
            mProperties[name] = std::make_tuple(typeid(T), d);
        }
    };

Body:
The copy constructor of std::type_info is deleted so you can't copy those objects into your map. However, typeid() ...

... refers to an object with static storage duration, of the polymorphic type const std::type_info or of some type derived from it.

... so you can store const std::type_info pointers in your map:

#include <iostream>
#include <map>
#include <string>
#include <typeinfo>
#include <utility>
#include <variant>

using data = std::variant<std::string, bool, int, float, double>;

std::ostream& operator<<(std::ostream& os, const data& v) {
    switch(v.index()) {
    case 0: os << std::get<0>(v); break;
    case 1: os << std::get<1>(v); break;
    case 2: os << std::get<2>(v); break;
    case 3: os << std::get<3>(v); break;
    case 4: os << std::get<4>(v); break;
    }
    return os;
}

std::map<std::string, std::pair<const std::type_info*, data>> mProps;

template<typename T>
void add_xml_property(const std::string& name, T d) {
    if(mProps.find(name) == mProps.end()) mProps[name] = {&typeid(T), d};
}

int main() {
    add_xml_property("foo", std::string("hello"));
    add_xml_property("bar", 123);
    add_xml_property("baz", 3.14159);

    for(auto& [k, v] : mProps)
        std::cout << k << ": " << v.first->name() << '\n' << v.second << "\n\n";
}

Possible output:

bar: i
123

baz: d
3.14159

foo: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
hello