问:
cannot find or open PDB file, debugging native code
I have a code running that successfully register Excel AddIn using C# Automation and talks to C++ though C# layer

```<code>// Tools -> Create GUID -> Register Format
namespace MyExcelAddins
{
    [ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
    [Guid("6F89542F-3DAC-471F-86DD-145F5E456968")]

    public class MyExcelFunctions : AddInRegistrator
    {
        [DllImport(@"C:\Users\Ilya\Documents\Visual Studio 2012\Projects\UnmanegedTester\x64\Debug\")]
        public static extern double AddNumbers(double a, double b);

        public double SampleAdd(double a, double b)
        {
            double res = AddNumbers(a, b);
            return res;
        }
    }
}
</code>```

Here is the view of my solution where C++ project I added from another directory.

I was able to debug C# code and now I want to try to debug the C++ part. I set the debug property of C# project to

and when click run, the error I got is

If I uncheck "Enable Native Code Debugging", I do not have the error but of course cannot debug C++. My guess I'm missing something in the settings. Please let me know if anyone has an idea how to fix that.

If I continue debugging I can hit breakpoint in C# but not in C++

答: That error message is telling you that you don't have debug symbols for excel.exe, which is not surprising since it is a Microsoft program.  You can continue debugging, and your code (which should have debugging information) will still be debuggable.  For example, you can set a breakpoint in some of your code that will be called by Excel and the debugger will stop on it when it is reached.

Body:
I have a code running that successfully register Excel AddIn using C# Automation and talks to C++ though C# layer

// Tools -> Create GUID -> Register Format
namespace MyExcelAddins
{
    [ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
    [Guid("6F89542F-3DAC-471F-86DD-145F5E456968")]

    public class MyExcelFunctions : AddInRegistrator
    {
        [DllImport(@"C:\Users\Ilya\Documents\Visual Studio 2012\Projects\UnmanegedTester\x64\Debug\")]
        public static extern double AddNumbers(double a, double b);

        public double SampleAdd(double a, double b)
        {
            double res = AddNumbers(a, b);
            return res;
        }
    }
}

Here is the view of my solution where C++ project I added from another directory.

I was able to debug C# code and now I want to try to debug the C++ part. I set the debug property of C# project to

and when click run, the error I got is

If I uncheck "Enable Native Code Debugging", I do not have the error but of course cannot debug C++. My guess I'm missing something in the settings. Please let me know if anyone has an idea how to fix that.

If I continue debugging I can hit breakpoint in C# but not in C++


来源: stackexchange

问:
How to increase speed of execute query in EF
The Method FindByQueryAsNoTracking() impelemented below:

```<code>public IEnumerable<T> FindByAsNoTracking(Expression<Func<T, bool» predicate)
{
    IQueryable<T> query = Dbset.Where(predicate).AsNoTracking().AsQueryable();
        return query;
}
</code>```

if we use FindByAsQuery that impelemented below:

```<code>public IQueryable<T> FindByQuery(Expression<Func<T, bool» predicate)
{
    IQueryable<T> query = Dbset.Where(predicate).AsQueryable();
    return query;
}
</code>```

The Speed will get better??

答:
```<code>AsNoTracking(IQueryable)
</code>```

Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object. If the underlying query object does not have an AsNoTracking method, then calling this method will have no effect.

No Tracking Queries

5.1 Disabling change tracking to reduce state management overhead If
  you are in a read-only scenario and want to avoid the overhead of
  loading the objects into the ObjectStateManager, you can issue "No
  Tracking" queries.  Change tracking can be disabled at the query
  level.

Note though that by disabling change tracking you are effectively
  turning off the object cache. When you query for an entity, we can't
  skip materialization by pulling the previously-materialized query
  results from the ObjectStateManager. If you are repeatedly querying
  for the same entities on the same context, you might actually see a
  performance benefit from enabling change tracking.

When querying using ObjectContext, ObjectQuery and ObjectSet instances
  will remember a MergeOption once it is set, and queries that are
  composed on them will inherit the effective MergeOption of the parent
  query. When using DbContext, tracking can be disabled by calling the
  AsNoTracking() modifier on the DbSet.

In short words, yes by using AsNoTracking you gain better performance especially when you are going to load lots of data rows but don't forget that it doesn't effect on the SQL generated query, it only increases performance in the .NET.

ps:
Charts are taken from StaticVoid blog.

ContentLicense: CC BY-SA 4.0

Body:
The Method FindByQueryAsNoTracking() impelemented below:

public IEnumerable<T> FindByAsNoTracking(Expression<Func<T, bool» predicate)
{
    IQueryable<T> query = Dbset.Where(predicate).AsNoTracking().AsQueryable();
        return query;
}

if we use FindByAsQuery that impelemented below:

public IQueryable<T> FindByQuery(Expression<Func<T, bool» predicate)
{
    IQueryable<T> query = Dbset.Where(predicate).AsQueryable();
    return query;
}

The Speed will get better??

Body:
AsNoTracking(IQueryable)

Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object. If the underlying query object does not have an AsNoTracking method, then calling this method will have no effect.

No Tracking Queries

5.1 Disabling change tracking to reduce state management overhead If
  you are in a read-only scenario and want to avoid the overhead of
  loading the objects into the ObjectStateManager, you can issue "No
  Tracking" queries.  Change tracking can be disabled at the query
  level.

Note though that by disabling change tracking you are effectively
  turning off the object cache. When you query for an entity, we can't
  skip materialization by pulling the previously-materialized query
  results from the ObjectStateManager. If you are repeatedly querying
  for the same entities on the same context, you might actually see a
  performance benefit from enabling change tracking.

When querying using ObjectContext, ObjectQuery and ObjectSet instances
  will remember a MergeOption once it is set, and queries that are
  composed on them will inherit the effective MergeOption of the parent
  query. When using DbContext, tracking can be disabled by calling the
  AsNoTracking() modifier on the DbSet.

In short words, yes by using AsNoTracking you gain better performance especially when you are going to load lots of data rows but don't forget that it doesn't effect on the SQL generated query, it only increases performance in the .NET.

ps:
Charts are taken from StaticVoid blog.


问:
Images Processing/JavaScript
I am trying to write a javascript program that modifies  an image by putting three vertical stripes on it. A red stripe on the left one third, a green stripe in the middle and a blue stripe on the right one third.

Here is the algorithm that i am trying to implement:
1. Start with the image you want to change.

Figure out the width of the image.

For each pixel in the image:
Get the x-coordinate for that pixel
If the pixel’s x-coordinate is less than one-third of the image’s width, set the pixel’s red value to 255.
If the pixel’s x-coordinate is between one-third and two-thirds of the image’s width, set the pixel’s green value to 255.
If the pixel’s x-coordinate is more than two-thirds of the image’s width, set the pixel’s blue value to 255.

Print the image.

```<code>var MyImage = new SimpleImage("hilton.jpg");
var ImgWidth = MyImage.getWidth();

for (var pix of MyImage.values()){
    var Xcoordinate = pix.getX();
    var Ycoordinate = pix.getY();
    if (Xcoordinate < ImgWidth/3){
        pix.setRed(255);
    }

    else if (ImgWidth/3< Xcoordinate < ImgWidth/2){
        pix.setGreen(255);
    }

    else{
        Xcoordinate > ImgWidth/3;
        pix.setBlue(255);
    }
}
print(MyImage);
</code>```

The red strip is coming out as expected but the green stripe is occupying the rest of the image and the blue doesn't appear at all. No error message.

答:
Thanks very much to SkilGG. I just reviewed my test for the green strip and deleted the redundant line in the else clause. Came up with those lines and my code is now working.</p>

```<code>    var MyImage = new
    SimpleImage("hilton.jpg");
    var ImgWidth = MyImage.getWidth();

    for (var pix of MyImage.values()){
        var Xcoordinate = pix.getX();
        if (Xcoordinate < ImgWidth/3){
            pix.setRed(255);
        }

        else if (Xcoordinate < 2*ImgWidth/3){
            pix.setGreen(255);
        }

        else{
            pix.setBlue(255);
        }
    }
    print(MyImage);
</code>```

Title: Images Processing/JavaScript

Body:
I am trying to write a javascript program that modifies  an image by putting three vertical stripes on it. A red stripe on the left one third, a green stripe in the middle and a blue stripe on the right one third.

Here is the algorithm that i am trying to implement:
1. Start with the image you want to change.

Figure out the width of the image.

For each pixel in the image:
Get the x-coordinate for that pixel
If the pixel’s x-coordinate is less than one-third of the image’s width, set the pixel’s red value to 255.
If the pixel’s x-coordinate is between one-third and two-thirds of the image’s width, set the pixel’s green value to 255.
If the pixel’s x-coordinate is more than two-thirds of the image’s width, set the pixel’s blue value to 255.

Print the image.

var MyImage = new SimpleImage("hilton.jpg");
var ImgWidth = MyImage.getWidth();

for (var pix of MyImage.values()){
    var Xcoordinate = pix.getX();
    var Ycoordinate = pix.getY();
    if (Xcoordinate < ImgWidth/3){
        pix.setRed(255);
    }

    else if (ImgWidth/3< Xcoordinate < ImgWidth/2){
        pix.setGreen(255);
    }

    else{
        Xcoordinate > ImgWidth/3;
        pix.setBlue(255);
    }
}
print(MyImage);

The red strip is coming out as expected but the green stripe is occupying the rest of the image and the blue doesn't appear at all. No error message.

Body:
Thanks very much to SkilGG. I just reviewed my test for the green strip and deleted the redundant line in the else clause. Came up with those lines and my code is now working.

    var MyImage = new
    SimpleImage("hilton.jpg");
    var ImgWidth = MyImage.getWidth();

    for (var pix of MyImage.values()){
        var Xcoordinate = pix.getX();
        if (Xcoordinate < ImgWidth/3){
            pix.setRed(255);
        }

        else if (Xcoordinate < 2*ImgWidth/3){
            pix.setGreen(255);
        }

        else{
            pix.setBlue(255);
        }
    }
    print(MyImage);


问:
Is there a difference between using between vs '> & <' when querying a hive table partitioned on date string?
I have a use of selecting data from a large hive table partitioned on date (format : yyyyMMdd), the hive query is required to fetch few fields from 6 months of data (total 180 date partitions. Currently the query looks like :

```<code>SELECT field_1, field_2
FROM table
WHERE `date` BETWEEN '20181125' and '20190525'
</code>```

Wanted to know if changing the query to use >= & <= makes any difference in terms of performance.

```<code>SELECT field_1, field_2
FROM table
WHERE `date`>='20181125' AND `date`<='20190525'
</code>```

答:
>=, <= and BETWEEN should generate the same execution plans, though it may be different in your Hive version.

Use EXPLAIN, it shows the query execution plan. Only plan can help to answer this question for sure. Check EXPLAIN DEPENDENCY, it prints input_partitions to be scanned and you will see if partition pruning works or not in each case.

If plans are the same for >=, <=, BETWEEN and IN then it works the same and the performance should be the same.

Body:
I have a use of selecting data from a large hive table partitioned on date (format : yyyyMMdd), the hive query is required to fetch few fields from 6 months of data (total 180 date partitions. Currently the query looks like :

SELECT field_1, field_2
FROM table
WHERE `date` BETWEEN '20181125' and '20190525'

Wanted to know if changing the query to use >= & <= makes any difference in terms of performance.

SELECT field_1, field_2
FROM table
WHERE `date`>='20181125' AND `date`<='20190525'


问:
Mongoose find nested object
I know that there are similar questions to this one, but the answers to those have not yielded the correct result.

I want to query a nested object with mongoose find. This is what I currently have setup:

```<code>reportRoutes.route('/:id').get(async (req, res) => {
    try{
        let id = req.params.id
        let author = req.params.author
        let regex = new RegExp( id, 'i')
        const report = await Report.find({title: regex, 'player.player_name':  "James Harden" })
            .populate({path: 'like'})
            .populate({
                path: 'player',
                populate: [{ path: 'team' },
                {
                    path: 'team',
                    populate: {
                        path: 'league'
                    }
                }
            ]
            })
            res.json(report)
    }  catch (e) {
        res.status(500).send()
    }
})
</code>```

When I run this in postman, I receive a blank array.

This is the route that query string that I'm using: localhost:4000/reports/harden

This is the schema for Report:

```<code>const mongoose = require('mongoose')
const Schema = mongoose.Schema

let Report = new Schema({
    title: {
        type: String
    },
    summary: {
        type: String
    },
    analysis: {
        type: String
    },
    source_title: {
        type: String
    },
    source_link: {
        type: String
    },
    author: {
        type: String
    },
    like: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Like'
    }],
    player: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Player'
    }
}, { timestamps: true })

module.exports = mongoose.model('Report', Report)
</code>```

And this is the schema for player:

```<code>const mongoose = require('mongoose')
const Schema = mongoose.Schema

let Player = new Schema({
    player_name: {
        type: String
    },
    player_position: {
        type: String
    },
    team: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Team'
    }
}, { timestamps: true })

module.exports = mongoose.model('Player', Player)
</code>```

答:
Since you are using populate try using the match stage:

```<code>reportRoutes.route('/:id').get(async (req, res) => {
    try{
        let id = req.params.id
        let author = req.params.author
        let regex = new RegExp( id, 'i')
        const report = await Report.find({ title: regex })
        .populate({path: 'like'})
        .populate({
           path: 'player',
           match: { 'player_name': 'James Harden'},  // <-- match here
           populate: [{ path: 'team' },
           {
             path: 'team',
             populate: {
             path: 'league'
           }
         }]
        })
        res.json(report)
    }  catch (e) {
        res.status(500).send()
    }
})
</code>```

Documentation on this can be found here

Title: Mongoose find nested object

Body:
I know that there are similar questions to this one, but the answers to those have not yielded the correct result.

I want to query a nested object with mongoose find. This is what I currently have setup:

reportRoutes.route('/:id').get(async (req, res) => {
    try{
        let id = req.params.id
        let author = req.params.author
        let regex = new RegExp( id, 'i')
        const report = await Report.find({title: regex, 'player.player_name':  "James Harden" })
            .populate({path: 'like'})
            .populate({
                path: 'player',
                populate: [{ path: 'team' },
                {
                    path: 'team',
                    populate: {
                        path: 'league'
                    }
                }
            ]
            })
            res.json(report)
    }  catch (e) {
        res.status(500).send()
    }
})

When I run this in postman, I receive a blank array.

This is the route that query string that I'm using: localhost:4000/reports/harden

This is the schema for Report:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

let Report = new Schema({
    title: {
        type: String
    },
    summary: {
        type: String
    },
    analysis: {
        type: String
    },
    source_title: {
        type: String
    },
    source_link: {
        type: String
    },
    author: {
        type: String
    },
    like: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Like'
    }],
    player: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Player'
    }
}, { timestamps: true })

module.exports = mongoose.model('Report', Report)

And this is the schema for player:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

let Player = new Schema({
    player_name: {
        type: String
    },
    player_position: {
        type: String
    },
    team: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Team'
    }
}, { timestamps: true })

module.exports = mongoose.model('Player', Player)

Body:
Since you are using populate try using the match stage:

reportRoutes.route('/:id').get(async (req, res) => {
    try{
        let id = req.params.id
        let author = req.params.author
        let regex = new RegExp( id, 'i')
        const report = await Report.find({ title: regex })
        .populate({path: 'like'})
        .populate({
           path: 'player',
           match: { 'player_name': 'James Harden'},  // <-- match here
           populate: [{ path: 'team' },
           {
             path: 'team',
             populate: {
             path: 'league'
           }
         }]
        })
        res.json(report)
    }  catch (e) {
        res.status(500).send()
    }
})

Documentation on this can be found here


问:
Read entire file in Scala?
What's a simple and canonical way to read an entire file into memory in Scala?  (Ideally, with control over character encoding.)

The best I can come up with is:

```<code>scala.io.Source.fromPath("file.txt").getLines.reduceLeft(_+_)
</code>```

or am I supposed to use one of Java's god-awful idioms, the best of which (without using an external library) seems to be:

```<code>import java.util.Scanner
import java.io.File
new Scanner(new File("file.txt")).useDelimiter("\\Z").next()
</code>```

From reading mailing list discussions, it's not clear to me that scala.io.Source is even supposed to be the canonical I/O library.  I don't understand what its intended purpose is, exactly.

... I'd like something dead-simple and easy to remember.  For example, in these languages it's very hard to forget the idiom ...

```<code>Ruby    open("file.txt").read
Ruby    File.read("file.txt")
Python  open("file.txt").read()
</code>```

答:
If you don't mind a third-party dependency, you should consider using my OS-Lib library. This makes reading/writing files and working with the filesystem very convenient:

```<code>// Make sure working directory exists and is empty
val wd = os.pwd/"out"/"splash"
os.remove.all(wd)
os.makeDir.all(wd)

// Read/write files
os.write(wd/"file.txt", "hello")
os.read(wd/"file.txt") ==> "hello"

// Perform filesystem operations
os.copy(wd/"file.txt", wd/"copied.txt")
os.list(wd) ==> Seq(wd/"copied.txt", wd/"file.txt")
</code>```

with one-line helpers for reading bytes, reading chunks, reading lines, and many other useful/common operations

Title: Read entire file in Scala?

Body:
What's a simple and canonical way to read an entire file into memory in Scala?  (Ideally, with control over character encoding.)

The best I can come up with is:

scala.io.Source.fromPath("file.txt").getLines.reduceLeft(_+_)

or am I supposed to use one of Java's god-awful idioms, the best of which (without using an external library) seems to be:

import java.util.Scanner
import java.io.File
new Scanner(new File("file.txt")).useDelimiter("\\Z").next()

From reading mailing list discussions, it's not clear to me that scala.io.Source is even supposed to be the canonical I/O library.  I don't understand what its intended purpose is, exactly.

... I'd like something dead-simple and easy to remember.  For example, in these languages it's very hard to forget the idiom ...

Ruby    open("file.txt").read
Ruby    File.read("file.txt")
Python  open("file.txt").read()

Body:
If you don't mind a third-party dependency, you should consider using my OS-Lib library. This makes reading/writing files and working with the filesystem very convenient:

// Make sure working directory exists and is empty
val wd = os.pwd/"out"/"splash"
os.remove.all(wd)
os.makeDir.all(wd)

// Read/write files
os.write(wd/"file.txt", "hello")
os.read(wd/"file.txt") ==> "hello"

// Perform filesystem operations
os.copy(wd/"file.txt", wd/"copied.txt")
os.list(wd) ==> Seq(wd/"copied.txt", wd/"file.txt")

with one-line helpers for reading bytes, reading chunks, reading lines, and many other useful/common operations


问:
PyCharm's venv relies on a physical python installation?
I trusted PyCharm to let it create a venv for me, and then shipped the code project with the venv folder. Inside my code, whenever calling a separate script, I use the venv Python uder venv/Scripts/.

To my surprise, it breaks when running on another machine, where the venv python actually points to my local installation of Python at C:\Python\Python37. This beats the purpose of creating a venv!

What have I done wrong? My project structure is like

code/*.py

venv

And this is what I shipped to another machine.

答:
Thanks to @AndreyG's answer. In addition, a bunch of others similar questions were helpful, like:

Copy complete virtualenv to another pc

Port Python virtualenv to another system

Especially after reading this tutorial: https://realpython.com/python-virtual-environments-a-primer/,

I realized my venv misconception, which was kinda due to my previous experience on shipping among Mac machines, where Python was usually preinstalled.

Now combined with the pip-freezing approach towards shipping site-packages, I also ship the Python Windows installer and automate the installation to make sure that the venv symlinks point to the exact same Python installation on all machines. Reference:

https://docs.python.org/3/using/windows.html

The automation code:

```<code>python.<version>-<arch>.exe /quiet InstallAllUser=-1 PrependPath=1 TargetDir="C:\Python\Python<version>"
</code>```

Body:
Thanks to @AndreyG's answer. In addition, a bunch of others similar questions were helpful, like:

Copy complete virtualenv to another pc

Port Python virtualenv to another system

Especially after reading this tutorial: https://realpython.com/python-virtual-environments-a-primer/,

I realized my venv misconception, which was kinda due to my previous experience on shipping among Mac machines, where Python was usually preinstalled.

Now combined with the pip-freezing approach towards shipping site-packages, I also ship the Python Windows installer and automate the installation to make sure that the venv symlinks point to the exact same Python installation on all machines. Reference:

https://docs.python.org/3/using/windows.html

The automation code:

python.<version>-<arch>.exe /quiet InstallAllUser=-1 PrependPath=1 TargetDir="C:\Python\Python<version>"


问:
Python pip path
This is a ridiculously simple question, but bear with me, because i didn't see anyone ask it.

I have Anaconda installed on my Mac. It's taking all sorts of forever to solve the environment on a package install, and I don't have time to troubleshoot now, so I decided to install via pip. Works great, only now I don't know where the package is installed.

How can I check my pip PYTHONPATH location so that I can add that location to my other paths?

答:
pip show <package name>

I am not really experienced with python but once similar thing happend with me and i used this.

Title: Python pip path


问:
How to write to a file in Scala?
For reading, there is the useful abstraction Source. How can I write lines to a text file?

答:
Unfortunately for the top answer, Scala-IO is dead. If you don't mind using a third-party dependency, consider using my OS-Lib library. This makes working with files, paths and the filesystem very easy:

```<code>// Make sure working directory exists and is empty
val wd = os.pwd/"out"/"splash"
os.remove.all(wd)
os.makeDir.all(wd)

// Read/write files
os.write(wd/"file.txt", "hello")
os.read(wd/"file.txt") ==> "hello"

// Perform filesystem operations
os.copy(wd/"file.txt", wd/"copied.txt")
os.list(wd) ==> Seq(wd/"copied.txt", wd/"file.txt")
</code>```

It has one-liners for writing to files, appending to files, overwriting files, and many other useful/common operations

ContentLicense: CC BY-SA 3.0

Title: How to write to a file in Scala?

Body:
Unfortunately for the top answer, Scala-IO is dead. If you don't mind using a third-party dependency, consider using my OS-Lib library. This makes working with files, paths and the filesystem very easy:

// Make sure working directory exists and is empty
val wd = os.pwd/"out"/"splash"
os.remove.all(wd)
os.makeDir.all(wd)

// Read/write files
os.write(wd/"file.txt", "hello")
os.read(wd/"file.txt") ==> "hello"

// Perform filesystem operations
os.copy(wd/"file.txt", wd/"copied.txt")
os.list(wd) ==> Seq(wd/"copied.txt", wd/"file.txt")

It has one-liners for writing to files, appending to files, overwriting files, and many other useful/common operations


问:
MVC bootstrap navbar not working after running NuGet updates
An MVC app broke after we updated all the NuGet packages. After trying everything I created a new MVC app, updated the NuGet packages and the basic navbar...

```<code><div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">Application name</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/">Home</a></li>
                <li><a href="/Home/About">About</a></li>
                <li><a href="/Home/Contact">Contact</a></li>
            </ul>

<ul class="nav navbar-nav navbar-right">
    <li><a href="/Account/Register" id="registerLink">Register</a></li>
    <li><a href="/Account/Login" id="loginLink">Log in</a></li>
</ul>

        </div>
    </div>
</div>
</code>```

... looks like this ...

...and clicking the icon...

Any ideas what could be causing this?

Have tried manually adding Bootstrap.css and Bootstrap.js to _Layout.vbhtml, but no difference

Thank you

答:
WORKING WITH MVC WebAPI PROJECT

File Name : _Layout.cshtml

Simply replace the body first nav-bar div tag content with the
following and check it.

```<code><div class="navbar navbar-expand-sm navbar-dark fixed-top bg-dark">
        <div class="container">
            <div class="navbar-header">
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <i class="fas fa-bars"></i>
                </button>
                @Html.ActionLink("Ebille", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse" id="navbarSupportedContent">
                <ul class="nav navbar-nav mr-auto">
                    <li class="nav-item">@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                    <li class="nav-item">@Html.ActionLink("API", "Index", "Help", new { area = "" }, new { @class = "nav-link" })</li>
                </ul>
            </div>
        </div>
    </div>
</code>```

Add Fontawesome inside head tag. Copy the code provided here

The above content is tested for initial default app created by Visual Studio 2019 MVC + WebAPI project.

Body:
An MVC app broke after we updated all the NuGet packages. After trying everything I created a new MVC app, updated the NuGet packages and the basic navbar...

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

            </button>
            Application name

Home

About

Contact

Register

Log in

... looks like this ...

...and clicking the icon...

Any ideas what could be causing this?

Have tried manually adding Bootstrap.css and Bootstrap.js to _Layout.vbhtml, but no difference

Thank you

Body:
WORKING WITH MVC WebAPI PROJECT

File Name : _Layout.cshtml

Simply replace the body first nav-bar div tag content with the
following and check it.

<div class="navbar navbar-expand-sm navbar-dark fixed-top bg-dark">
        <div class="container">
            <div class="navbar-header">
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <i class="fas fa-bars"></i>
                </button>
                @Html.ActionLink("Ebille", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse" id="navbarSupportedContent">
                <ul class="nav navbar-nav mr-auto">
                    <li class="nav-item">@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                    <li class="nav-item">@Html.ActionLink("API", "Index", "Help", new { area = "" }, new { @class = "nav-link" })</li>
                </ul>
            </div>
        </div>
    </div>

Add Fontawesome inside head tag. Copy the code provided here

The above content is tested for initial default app created by Visual Studio 2019 MVC + WebAPI project.


问:
update nested Array state reactjs
Unable to handle nested array in react state, here what I am trying I need to push value in this.state.form.contentFormArr

```<code>    let langulageform, contentObj,contentFormArr;

   contentObj={heading:'',subheading:''};
    contentFormArr=[this.contentObj]

    langulageform =[
            {key:"Ar",lang:"Arabic",contentFormArr:this.contentFormArr},
            {key:"En",lang:"English",contentFormArr:this.contentFormArr},
            {key:"Ru",lang:"Russian",contentFormArr:this.contentFormArr},
            {key:"Sp",lang:"Spanish",contentFormArr:this.contentFormArr},
            {key:"Ve",lang:"Vetnamese",contentFormArr:this.contentFormArr}
        ];

    constructor(){
            super()

            this.addContentArea = this.addContentArea.bind(this)

            this.state={
                form:this.langulageform
            }

        }

    addContentArea(index){

            this.setState((state)=>{

                const contentformArr = [...state.form[index].contentFormArr,this.contentObj]

                return{
                    ...state.form.contentFormArr,
                    contentformArr
                }
            })

        }
</code>```

I made multiple forms by the iterating this.state.form array, Now I need when the user clicks on any form box button to add more field then it will push value in particular index array and then it will iterate more fields.

答:
Well I did it but I think the way which I use is not good practice. First I made the correction on Array which I set to state as the initial value, because fore I was set array value to contentForm array when I made changes to them it set changes to everywhere on state Object.

```<code>langulageform =[
  {key:"Ar",lang:"Arabic",contentFormArr:[{heading:'',subheading:''}]},
  {key:"En",lang:"English",contentFormArr:[{heading:'',subheading:''}]},
  {key:"Ru",lang:"Russian",contentFormArr:[{heading:'',subheading:''}]},
           {key:"Sp",lang:"Spanish",contentFormArr:[{heading:'',subheading:''}]},
           {key:"Ve",lang:"Vetnamese",contentFormArr:[{heading:'',subheading:''}]}
    ];
</code>```

Secondly I create one blank array and push all values in it, so that I can push value in it, This can't be done in state because of immutable object, and after getting correct index object I made corrections and return the object.

```<code>addContentArea(index){
this.setState((state)=>{

  let Arr=[];

  state.form.map((e,i)=>{
     Arr.push(e);

     if(i===index){
        Arr.contentFormArr.push({})
     }

  })

  return{
     Arr
   }
})
}
</code>```

I did it because I feel to deal with multidimensional immutable arrays are bit tricky this is not an optimized way but it works every time and I have checked that the react component lifecycle methods are also working fine with this.

Title: update nested Array state reactjs

Body:
Unable to handle nested array in react state, here what I am trying I need to push value in this.state.form.contentFormArr

    let langulageform, contentObj,contentFormArr;

   contentObj={heading:'',subheading:''};
    contentFormArr=[this.contentObj]

    langulageform =[
            {key:"Ar",lang:"Arabic",contentFormArr:this.contentFormArr},
            {key:"En",lang:"English",contentFormArr:this.contentFormArr},
            {key:"Ru",lang:"Russian",contentFormArr:this.contentFormArr},
            {key:"Sp",lang:"Spanish",contentFormArr:this.contentFormArr},
            {key:"Ve",lang:"Vetnamese",contentFormArr:this.contentFormArr}
        ];

    constructor(){
            super()

            this.addContentArea = this.addContentArea.bind(this)

            this.state={
                form:this.langulageform
            }

        }

    addContentArea(index){

            this.setState((state)=>{

                const contentformArr = [...state.form[index].contentFormArr,this.contentObj]

                return{
                    ...state.form.contentFormArr,
                    contentformArr
                }
            })

        }

I made multiple forms by the iterating this.state.form array, Now I need when the user clicks on any form box button to add more field then it will push value in particular index array and then it will iterate more fields.

Body:
Well I did it but I think the way which I use is not good practice. First I made the correction on Array which I set to state as the initial value, because fore I was set array value to contentForm array when I made changes to them it set changes to everywhere on state Object.

langulageform =[
  {key:"Ar",lang:"Arabic",contentFormArr:[{heading:'',subheading:''}]},
  {key:"En",lang:"English",contentFormArr:[{heading:'',subheading:''}]},
  {key:"Ru",lang:"Russian",contentFormArr:[{heading:'',subheading:''}]},
           {key:"Sp",lang:"Spanish",contentFormArr:[{heading:'',subheading:''}]},
           {key:"Ve",lang:"Vetnamese",contentFormArr:[{heading:'',subheading:''}]}
    ];

Secondly I create one blank array and push all values in it, so that I can push value in it, This can't be done in state because of immutable object, and after getting correct index object I made corrections and return the object.

addContentArea(index){
this.setState((state)=>{

  let Arr=[];

  state.form.map((e,i)=>{
     Arr.push(e);

     if(i===index){
        Arr.contentFormArr.push({})
     }

  })

  return{
     Arr
   }
})
}

I did it because I feel to deal with multidimensional immutable arrays are bit tricky this is not an optimized way but it works every time and I have checked that the react component lifecycle methods are also working fine with this.


问:
Change data type while destructuring
Take the following code:

```<code>nums = ["1", "2", "3"]
one, two, three = nums
print("Sum:", one+two+three)  # >> Sum: 123
</code>```

Is there a way to change the data type of the strings while destructuring? I was hoping something like the following would work, but it unfortunately it doesn't:

```<code>nums = ["1", "2", "3"]
int(one), int(two), int(three) = nums
print("Sum:", one+two+three)  # Expected output >> Sum: 6
</code>```

I know I could simply change the data type by doing one = int(nums[0]) etc... but I'm just wondering whether something like this is possible to do within the destructuring assignment expression itself?

答:
You can do the following. map function will apply the function passed as first argument to all the values in the list or iterable.

Note: map is lazy. The result will be obtained only during iteration. You can find more detail here.

```<code>nums = map(int, ["1", "2", "3"])

print(sum(nums)) # 6

</code>```

Now all the values in the nums will be int.

Title: Change data type while destructuring

Body:
Take the following code:

nums = ["1", "2", "3"]
one, two, three = nums
print("Sum:", one+two+three)  # >> Sum: 123

Is there a way to change the data type of the strings while destructuring? I was hoping something like the following would work, but it unfortunately it doesn't:

nums = ["1", "2", "3"]
int(one), int(two), int(three) = nums
print("Sum:", one+two+three)  # Expected output >> Sum: 6

I know I could simply change the data type by doing one = int(nums[0]) etc... but I'm just wondering whether something like this is possible to do within the destructuring assignment expression itself?

Body:
You can do the following. map function will apply the function passed as first argument to all the values in the list or iterable.

Note: map is lazy. The result will be obtained only during iteration. You can find more detail here.

nums = map(int, ["1", "2", "3"])

print(sum(nums)) # 6

Now all the values in the nums will be int.


问:
Gradle sync failed. Could not find com.android.tools.build:gradle:3.4.0
I download basicSample project from below link of GitHub. When I want to sync project, I get below error. I searched and a i saw this link (How Update the gradle to 3.4.1in android studio), i try offline mode but again not worked. I was confused. Can't i sync gradle 3.4.0 online? Should i used offline sync? If yes how i set gradle and gradle plugin (I set path of gradle in settings but Android studio shows below message)?

```<code>  No cached version of com.android.tools.build:gradle:3.4.0 available for offline mode.
  Disable Gradle 'offline mode' and sync project
</code>```

Github link:

https://github.com/googlesamples/android-architecture-components/tree/master/BasicSample

Error for sync gradle 3.4.0 for online mode:

```<code> Could not find com.android.tools.build:gradle:3.4.0.
 Searched in the following locations:
</code>```

- https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
  - https://jcenter.bintray.com/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - https://jcenter.bintray.com/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
  - https://oss.sonatype.org/content/repositories/snapshots/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - https://oss.sonatype.org/content/repositories/snapshots/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
  - https://kotlin.bintray.com/kotlinx/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - https://kotlin.bintray.com/kotlinx/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
  - http://jcenter.bintray.com/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - http://jcenter.bintray.com/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
Required by:
    project :
Open File

答:
Here is your solution.

Follow the step to solve your problem.

Go to File option.

Click On Settings option. (Ctrl + Alt + S)

There is an open new popup window, look at the left panel of that window.

Expand Build, Execution, Deployment option.

Click on Gradle option.

Uncheck Offline work, Click Apply -> Ok.

Sync the project.

As you can see in below pic.

Body:
I download basicSample project from below link of GitHub. When I want to sync project, I get below error. I searched and a i saw this link (How Update the gradle to 3.4.1in android studio), i try offline mode but again not worked. I was confused. Can't i sync gradle 3.4.0 online? Should i used offline sync? If yes how i set gradle and gradle plugin (I set path of gradle in settings but Android studio shows below message)?

  No cached version of com.android.tools.build:gradle:3.4.0 available for offline mode.
  Disable Gradle 'offline mode' and sync project

Github link:

https://github.com/googlesamples/android-architecture-components/tree/master/BasicSample

Error for sync gradle 3.4.0 for online mode:

 Could not find com.android.tools.build:gradle:3.4.0.
 Searched in the following locations:

- https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
  - https://jcenter.bintray.com/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - https://jcenter.bintray.com/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
  - https://oss.sonatype.org/content/repositories/snapshots/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - https://oss.sonatype.org/content/repositories/snapshots/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
  - https://kotlin.bintray.com/kotlinx/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - https://kotlin.bintray.com/kotlinx/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
  - http://jcenter.bintray.com/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.pom
  - http://jcenter.bintray.com/com/android/tools/build/gradle/3.4.0/gradle-3.4.0.jar
Required by:
    project :
Open File


问:
Regex Problem Group Name Redefinition?
So I have this regex:

```<code>(^(\s+)?(?P<NAME>(\w)(\d{7}))((01f\.foo)|(\.bar|\.goo\.moo\.roo))$|(^(\s+)?(?P<NAME2>R1_\d{6}_\d{6}_)((01f\.foo)|(\.bar|\.goo\.moo\.roo))$))
</code>```

Now if I try and do a match against this:

```
B048661501f.foo
```

I get this error:

```
  File "C:\Python25\lib\re.py", line 188, in compile
    return _compile(pattern, flags)
  File "C:\Python25\lib\re.py", line 241, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'NAME' as group 9; was group 3
```

If I can't define the same group twice in the same regex expression for two different cases, what do I do?

答:
The following answer deals with how to make the above regex work in Python3.

Since the re2 module as suggested by Max would not work in Python3, because of the
NameError: basestring. Another alternative to this is the regex module.

regex module is just an enhanced version of re with extra added features. This
module also allows to have same group names in the regex.

You can install it via:

```<code>sudo pip install regex
</code>```

And if you have already been using re or re2 in your program. Just do the following to import regex module

```<code>import regex as re
</code>```

ContentLicense: CC BY-SA 2.5

Title: Regex Problem Group Name Redefinition?

Body:
So I have this regex:

(^(\s+)?(?P<NAME>(\w)(\d{7}))((01f\.foo)|(\.bar|\.goo\.moo\.roo))$|(^(\s+)?(?P<NAME2>R1_\d{6}_\d{6}_)((01f\.foo)|(\.bar|\.goo\.moo\.roo))$))

Now if I try and do a match against this:

B048661501f.foo

I get this error:

  File "C:\Python25\lib\re.py", line 188, in compile
    return _compile(pattern, flags)
  File "C:\Python25\lib\re.py", line 241, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'NAME' as group 9; was group 3

If I can't define the same group twice in the same regex expression for two different cases, what do I do?

LastEditorDisplayName: Jonathan Leffler

Body:
The following answer deals with how to make the above regex work in Python3.

Since the re2 module as suggested by Max would not work in Python3, because of the
NameError: basestring. Another alternative to this is the regex module.

regex module is just an enhanced version of re with extra added features. This
module also allows to have same group names in the regex.

You can install it via:

sudo pip install regex

And if you have already been using re or re2 in your program. Just do the following to import regex module

import regex as re


问:
How to add items to dynamically created select (html) Control
Hi
  How to add items to dynamically created select (html) Control..

thanks

答:
You can use javascript to do this e.g.</p>

```<code><script type="text/javascript">
    function AddItem(Text,Value)
    {
        // Create an Option object

        var opt = document.createElement("option");

        // Add an Option object to Drop Down/List Box
        document.getElementById("myDropDownList").options.add(opt);

        // Assign text and value to Option object
        opt.text = Text;
        opt.value = Value;

    }<script />
</code>```

Body:
You can use javascript to do this e.g.

<script type="text/javascript">
    function AddItem(Text,Value)
    {
        // Create an Option object

        var opt = document.createElement("option");

        // Add an Option object to Drop Down/List Box
        document.getElementById("myDropDownList").options.add(opt);

        // Assign text and value to Option object
        opt.text = Text;
        opt.value = Value;

    }<script />


问:
System.Random producing the same random number
Despite the Random generator only being created once, the output is always the same random result (for all three test outputs).

A test snippet from a slightly larger script:

```<code>   let myRandGen = System.Random()
   let getRandomObject =
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length)
      options.[randIndex]

   printfn "New one: %s" getRandomObject
   printfn "New two: %s" getRandomObject
   printfn "New three: %s" getRandomObject
</code>```

I need the output to be random for each call, which it currently isn't.

Example output:

```<code>New one: Jane
New two: Jane
New three: Jane
</code>```

答: You generated your random number once, which doesn't change throughout the whole program. To have a new random value after every use, you must re-initialize the random value.</p>

Body:
Despite the Random generator only being created once, the output is always the same random result (for all three test outputs).

A test snippet from a slightly larger script:

   let myRandGen = System.Random()
   let getRandomObject =
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length)
      options.[randIndex]

   printfn "New one: %s" getRandomObject
   printfn "New two: %s" getRandomObject
   printfn "New three: %s" getRandomObject

I need the output to be random for each call, which it currently isn't.

Example output:

New one: Jane
New two: Jane
New three: Jane


问:
How to show or hide image in HTML
In the following HTML/JS code, if I enter a valid e-mail id a command button and a tick mark should appear. But command button works fine. Tick mark is not appearing. Any one please help.</p>

```<code><html>
<head>

</head>
<body>
<form id="signUpForm">
  <input type="email" id="emailField" required>
  <button id="okButton" style="display:none">OK</button>
  <img id "img1" src="valid.jpg" width=100px style="display:none"/>

</form>

<script>
const signUpForm = document.getElementById('signUpForm');
const emailField = document.getElementById('emailField');
const flag1 = document.getElementById('okButton');
const img1 = document.getElementById('img1');

emailField.addEventListener('keyup', function (event) {
  isValidEmail = emailField.checkValidity();

  if ( isValidEmail ) {
        flag1.style="display:inline";
        img1.style="display:block"";
  } else {
        flag1.style="display:none";
        img1.style="display:none";
 }
});

okButton.addEventListener('click', function (event) {
  signUpForm.submit();
});
</script>

</body>
</html>
</code>```

答:
There are several mistakes which break the script flow in your code

No "=" for id assignment of image tag

Redundant double quote at the end of instruction

img1.style="display:block"";

If you correct them all, it should work.

Title: How to show or hide image in HTML

Body:
In the following HTML/JS code, if I enter a valid e-mail id a command button and a tick mark should appear. But command button works fine. Tick mark is not appearing. Any one please help.

<form id="signUpForm">
  <input type="email" id="emailField" required>
  <button id="okButton" style="display:none">OK</button>

</form>

Body:
There are several mistakes which break the script flow in your code

No "=" for id assignment of image tag

<img id "img1" src="valid.jpg" width=100px style="display:none"/>

Redundant double quote at the end of instruction

img1.style="display:block"";

If you correct them all, it should work.


答:
You can use the map builtin which convert all your elements to an int
by applying the typecasting function int to it

From the docs:

map(function, iterable, ...)

  Return an iterator that applies function to every item of iterable, yielding the results.

You can then use the updated iterator to assign your elements

```<code>In [234]: nums = ["1", "2", "3"]

In [235]: one, two, three = map(int,nums)

In [236]: print("Sum:", one+two+three)
Sum: 6
</code>```

Note that this is the same as doing the follows, where we iterate through nums and typecast each string to an int. map is a shorthand for that operation.

```<code>In [254]: nums = ["1", "2", "3"]

In [255]: one, two, three = [int(num) for num in nums]

In [256]: print("Sum:", one+two+three)
Sum: 6
</code>```

Title: Change data type while destructuring

Body:
You can use the map builtin which convert all your elements to an int
by applying the typecasting function int to it

From the docs:

map(function, iterable, ...)

  Return an iterator that applies function to every item of iterable, yielding the results.

You can then use the updated iterator to assign your elements

In [234]: nums = ["1", "2", "3"]

In [235]: one, two, three = map(int,nums)

In [236]: print("Sum:", one+two+three)
Sum: 6

Note that this is the same as doing the follows, where we iterate through nums and typecast each string to an int. map is a shorthand for that operation.

In [254]: nums = ["1", "2", "3"]

In [255]: one, two, three = [int(num) for num in nums]

In [256]: print("Sum:", one+two+three)
Sum: 6


问:
Extract e-mail with a certain domain from a semicolon-separated vector of e-mails
Consider the following vector of e-mails:

```<code>emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")
</code>```

Each element of the vector above is a semi-colon separated string of e-mail address for a user. In this case, for example, the first user has three e-mails: blah@my.blah.com, etc@etc.edu, and me@me.gov.

I have  a specific domain name I am interested in - let's say it's my.blah.com. I also know for a fact that, given my domain knowledge of this problem, that each user can only have one my.blah.com e-mail address, if it exists. I would like to return this e-mail address for each user as a character vector, and return NA in the cases in which a my.blah.com e-mail address does not exist.

Thus, the output should be

```<code>c("blah@my.blah.com", "yes@my.blah.com", NA)
</code>```

My best attempt at this is

```<code>emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")

regmatches(emails,
           regexec("+.*@my.blah.com",
                   emails))

[[1]]
[1] "blah@my.blah.com"

[[2]]
[1] "yay@something.gov;yes@my.blah.com"

[[3]]
character(0)
</code>```

which isn't a character vector, but I'm struggling to just get the RegEx right at this point, which is what I'd like to focus on.

答:
An option with str_extract

```<code>library(stringr)
str_extract_all(emails, "\\w+@my\\.blah\\.com")
#[[1]]
#[1] "blah@my.blah.com"

#[[2]]
#[1] "yes@my.blah.com"   "stuff@my.blah.com"

#[[3]]
#character(0)
</code>```

If we need only one email address

```<code>str_extract(emails, "\\w+@my\\.blah\\.com")
#[1] "blah@my.blah.com" "yes@my.blah.com"  NA
</code>```

Body:
Consider the following vector of e-mails:

emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")

Each element of the vector above is a semi-colon separated string of e-mail address for a user. In this case, for example, the first user has three e-mails: blah@my.blah.com, etc@etc.edu, and me@me.gov.

I have  a specific domain name I am interested in - let's say it's my.blah.com. I also know for a fact that, given my domain knowledge of this problem, that each user can only have one my.blah.com e-mail address, if it exists. I would like to return this e-mail address for each user as a character vector, and return NA in the cases in which a my.blah.com e-mail address does not exist.

Thus, the output should be

c("blah@my.blah.com", "yes@my.blah.com", NA)

My best attempt at this is

emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net",
            "someemail@nothing.gov")

regmatches(emails,
           regexec("+.*@my.blah.com",
                   emails))

[[1]]
[1] "blah@my.blah.com"

[[2]]
[1] "yay@something.gov;yes@my.blah.com"

[[3]]
character(0)

which isn't a character vector, but I'm struggling to just get the RegEx right at this point, which is what I'd like to focus on.

Body:
An option with str_extract

library(stringr)
str_extract_all(emails, "\\w+@my\\.blah\\.com")
#[[1]]
#[1] "blah@my.blah.com"

#[[2]]
#[1] "yes@my.blah.com"   "stuff@my.blah.com"

#[[3]]
#character(0)

If we need only one email address

str_extract(emails, "\\w+@my\\.blah\\.com")
#[1] "blah@my.blah.com" "yes@my.blah.com"  NA


问:
Uninstall springsource tools suite
I have installed a springsource tools suite 2.5 and I want to move to 2.6 version, so I was looking for uninstalling the older version, but i don't find the uninstaller.
So, deleting the directory in which the older version is installed is sufficient or are there other procedures to do?</p>

答:
For uninstall STS

open STS

Go to Help -> About Spring Tool Suite

Click on installation details

Check installed software

Click on Spring tool suite under installed software

Click Uninstall.

That's it.

Title: Uninstall springsource tools suite


问:
Make a column required if other column is of certain value
What I have:

```<code>CREATE TABLE [dbo].[User]
(
    [id] INT NOT NULL PRIMARY KEY,
    [name] VARCHAR(50) NOT NULL,
    [postcode] INT NOT NULL,
    [phone] INT NULL
)
</code>```

What I want is that the phone number is required ONLY if the postcode is higher than 40000. If postcode is smaller than 40000, user can insert the phone number, although it is not required.

How do I do this?

答:
You can use a check constraint:</p>

```<code>CREATE TABLE [dbo].[User]
(
    [id] INT NOT NULL PRIMARY KEY,
    [name] VARCHAR(50) NOT NULL,
    [postcode] INT NOT NULL,
    [phone] INT NULL,
    CONSTRAINT CHK_Postcode CHECK (postcode >= 4000 OR Phone IS NOT NULL)
);
</code>```

Body:
What I have:

CREATE TABLE [dbo].[User]
(
    [id] INT NOT NULL PRIMARY KEY,
    [name] VARCHAR(50) NOT NULL,
    [postcode] INT NOT NULL,
    [phone] INT NULL
)

What I want is that the phone number is required ONLY if the postcode is higher than 40000. If postcode is smaller than 40000, user can insert the phone number, although it is not required.

How do I do this?

Body:
You can use a check constraint:

CREATE TABLE [dbo].[User]
(
    [id] INT NOT NULL PRIMARY KEY,
    [name] VARCHAR(50) NOT NULL,
    [postcode] INT NOT NULL,
    [phone] INT NULL,
    CONSTRAINT CHK_Postcode CHECK (postcode >= 4000 OR Phone IS NOT NULL)
);


问:
How to convert R dataframe back to Pandas using rpy2?
I converted a pandas dataframe to R using the code below:

```<code>import pandas as pd
import pandas.rpy.common as com
import rpy2.robjects as ro
from rpy2.robjects.packages import importr

rdf = com.convert_to_r_dataframe(df)
</code>```

How do I convert rdf back to a pandas.DataFrame?

```<code>df = f(rdf)
</code>```

答:
Use pandas to read an rpy2 dataframe, r_df. It will avoid the deprecation warning "FutureWarning: from_items is deprecated. Use DataFrame.from_dict(dict(items), ...) instead"

type(r_df) is "rpy2.robjects.vectors.DataFrame".

type(pd_df) is "pandas.core.frame.DataFrame"

pd_df = pd.DataFrame.from_dict({ key : np.asarray(r_df.rx2(key)) for key in r_df.names })

Body:
I converted a pandas dataframe to R using the code below:

import pandas as pd
import pandas.rpy.common as com
import rpy2.robjects as ro
from rpy2.robjects.packages import importr

rdf = com.convert_to_r_dataframe(df)

How do I convert rdf back to a pandas.DataFrame?

df = f(rdf)


问:
ModuleNotFoundError: No module named kivy.app in Python
```<code>import kivy

from kivy import *
#kivy.require('1.10.1') # replace with your current kivy version !
#from kivy.deps import sdl2, glew

from kivy.app import App
from kivy.uix.label import Label

class MyApp(App):
    def build(self):
        return Label(text='Hello world')
if(__name__=="__main__"):
    MyApp().run()
</code>```

First :

```<code>python -m pip install --upgrade pip wheel setuptools
python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2
.deps.glew
python -m pip install kivy.deps.gstreamer
python -m pip install kivy.deps.angle
python -m pip install kivy
python -m pip install kivy_examples
python -m pip install Pillow
python -m pip install cython
</code>```

Error :

Traceback (most recent call last):

```<code> File "C:\Users\1\Desktop\kivy.py", line 1, in <module>

 import kivy

 File "C:\Users\1\Desktop\kivy.py", line 7, in <module>

 from kivy.app import App

 ModuleNotFoundError: No module named 'kivy.app'; 'kivy' is not a package
</code>```

答: Just type pip install kivy in your python terminal, you may have not installed it.

Body:
import kivy

from kivy import *
#kivy.require('1.10.1') # replace with your current kivy version !
#from kivy.deps import sdl2, glew

from kivy.app import App
from kivy.uix.label import Label

class MyApp(App):
    def build(self):
        return Label(text='Hello world')
if(__name__=="__main__"):
    MyApp().run()

First :

python -m pip install --upgrade pip wheel setuptools
python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2
.deps.glew
python -m pip install kivy.deps.gstreamer
python -m pip install kivy.deps.angle
python -m pip install kivy
python -m pip install kivy_examples
python -m pip install Pillow
python -m pip install cython

Error :

Traceback (most recent call last):

 File "C:\Users\1\Desktop\kivy.py", line 1, in <module>

 import kivy

 File "C:\Users\1\Desktop\kivy.py", line 7, in <module>

 from kivy.app import App

 ModuleNotFoundError: No module named 'kivy.app'; 'kivy' is not a package


问:
Kibana - Not able to start kibana on windows 10
I want to implement centralized configuration with ELK for our Spring boot microservices.

I have installed 3 different version of Kibana 6.3 , 6.7  and 7 version.
un-comment port and elasticsearch.url (used default value - elastic search running)

Getting following warning and error continuously on console

```<code>    log   [05:40:20.028] [warning][task_manager]
    The task maps_telemetry "Maps-maps_telemetry" is not cancellable.
    log   [05:40:24.145] [error][security]
    Error registering Kibana Privileges with Elasticsearch for kibana-.kibana:
[security_exception] current license is non-compliant for [security], with { license.expired.feature="security" }
</code>```

npm -v
5.5.1

node -v
v8.9.3

java -version
1.8.121

Your help will be appreciated to resolve this issue so that I can use kibana.

答:
If you run into this issue again, could you please ensure the src\cli\index.js does exist before starting Kibana?

C:\Users\44124986\data\soft\kibana-6.7.2-windows-x86_64\kibana-6.7.2-windows-x86_\src\cli\index.js

According to similar issue reported to elastic/kibana project on GitHub, the root
cause is starting Kibana before Kibana completely unzipped.

Body:
I want to implement centralized configuration with ELK for our Spring boot microservices.

I have installed 3 different version of Kibana 6.3 , 6.7  and 7 version.
un-comment port and elasticsearch.url (used default value - elastic search running)

Getting following warning and error continuously on console

    log   [05:40:20.028] [warning][task_manager]
    The task maps_telemetry "Maps-maps_telemetry" is not cancellable.
    log   [05:40:24.145] [error][security]
    Error registering Kibana Privileges with Elasticsearch for kibana-.kibana:
[security_exception] current license is non-compliant for [security], with { license.expired.feature="security" }

npm -v
5.5.1

node -v
v8.9.3

java -version
1.8.121

Your help will be appreciated to resolve this issue so that I can use kibana.


问:
Firebase Hosting: We couldn't verify your domain example.com. Please check your settings and try again
I tried to add my custom domain to firebase hosting. But firebase can not verify. Though I add txt record in my domain control panel. Here is the the

答:
For future reference replace host with @ instead of example.com. (for godaddy, namecheap, 1and1 ...)

Firebase help :

Value for host names may differ based on each DNS provider. For example, some DNS providers use '@' for your root domain name. For subdomains, it could be 'www' or 'www.domain.com'


问:
How to get rid of extra characters in linux process ID using shell script
I m trying to kill a process by its pid, and this is the script that I found from web.

```<code>PID=`ps -ef | grep myProcess | grep -v grep | awk '{print $2}'`
echo -e Killing myProcess with pid: $PID..
</code>```

Output: Killing myProcesswith pid: 13275^M..

Does anyone know why is there a ^M , how do I get rid of that because the kill command failed to run :

```<code>**arguments must be process or job IDs**
</code>```

I searched online but still got no idea how to overcome this..
Any help is appreciated!! Thanks!

答:
From a quick read online, the print command to awk always appends a newline (which can sometimes be represented by Control-M, or ^M).

It would appear that printf would be a suitable alternative. Maybe:

```<code>PID=ps -ef | grep myProcess | grep -v grep | awk '{printf "%i",$2}'
</code>```

Body:
I m trying to kill a process by its pid, and this is the script that I found from web.

PID=`ps -ef | grep myProcess | grep -v grep | awk '{print $2}'`
echo -e Killing myProcess with pid: $PID..

Output: Killing myProcesswith pid: 13275^M..

Does anyone know why is there a ^M , how do I get rid of that because the kill command failed to run :

**arguments must be process or job IDs**

I searched online but still got no idea how to overcome this..
Any help is appreciated!! Thanks!

Body:
From a quick read online, the print command to awk always appends a newline (which can sometimes be represented by Control-M, or ^M).

It would appear that printf would be a suitable alternative. Maybe:

PID=ps -ef | grep myProcess | grep -v grep | awk '{printf "%i",$2}'


问:
How do I write a java method that adds the digits of each number in a string
I am working on a challenge that requires us to input a string containing numbers. For example, "This 23 string has 738 numbers"

And the method needs to add the values of 2+3 to return 5 and 7+3+8 to return 18.

But I don't know how to make a loop to find each number in the input string, perform that operation, and continue through the rest of the string. Any suggestions or solutions?

A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12.

I have figured out how to use regular expressions to tease out the numbers from a string, but I don't know how to add the digits of each number teased out into an output

package reverseTest;

```<code>import java.util.Scanner;
public class ExtractNumbers {`enter code here`
      public static void main(String[] args)
      {
          String str;
          String numbers;

          Scanner SC=new Scanner(System.in);

          System.out.print("Enter string that contains numbers: ");
          str=SC.nextLine();

          //extracting string
          numbers=str.replaceAll("[^0-9]", "");

          System.out.println("Numbers are: " + numbers);
      }
}
</code>```

And this adds ALL the numbers in a string:

```<code>String a="jklmn489pjro635ops";

    int sum = 0;

    String num = "";

    for(int i = 0; i < a.length(); i++) {
        if(Character.isDigit(a.charAt(i))) {
            num = num + a.charAt(i);
        } else {
            if(!num.equals("")) {
                sum = sum + Integer.parseInt(num);
                num = "";
            }
        }
    }
    System.out.println(sum);
}
</code>```

I don't know how to combine this code with code that can add the numbers this method outputs together.

答:
You can simply split the input string to have separated tokens and then split each token to have only digits:

```<code>String s = "This 23 string has 738 numbers";
String[] st = s.split(" ");
for (int i=0 ; i<st.length ; i++) {
    if (st[i].matches("[0-9]+")) {
        String[] c = st[i].split("(?=\\d)");
        int sum = 0;
        for(int j=0 ; j<c.length ; j++) {
            sum += Integer.parseInt(c[j]);
        }
        System.out.println(sum);

    }
}
</code>```

the output is:

```<code>5
18
</code>```

Body:
I am working on a challenge that requires us to input a string containing numbers. For example, "This 23 string has 738 numbers"

And the method needs to add the values of 2+3 to return 5 and 7+3+8 to return 18.

But I don't know how to make a loop to find each number in the input string, perform that operation, and continue through the rest of the string. Any suggestions or solutions?

A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12.

I have figured out how to use regular expressions to tease out the numbers from a string, but I don't know how to add the digits of each number teased out into an output

package reverseTest;

import java.util.Scanner;
public class ExtractNumbers {`enter code here`
      public static void main(String[] args)
      {
          String str;
          String numbers;

          Scanner SC=new Scanner(System.in);

          System.out.print("Enter string that contains numbers: ");
          str=SC.nextLine();

          //extracting string
          numbers=str.replaceAll("[^0-9]", "");

          System.out.println("Numbers are: " + numbers);
      }
}

And this adds ALL the numbers in a string:

String a="jklmn489pjro635ops";

    int sum = 0;

    String num = "";

    for(int i = 0; i < a.length(); i++) {
        if(Character.isDigit(a.charAt(i))) {
            num = num + a.charAt(i);
        } else {
            if(!num.equals("")) {
                sum = sum + Integer.parseInt(num);
                num = "";
            }
        }
    }
    System.out.println(sum);
}

I don't know how to combine this code with code that can add the numbers this method outputs together.

Body:
You can simply split the input string to have separated tokens and then split each token to have only digits:

String s = "This 23 string has 738 numbers";
String[] st = s.split(" ");
for (int i=0 ; i<st.length ; i++) {
    if (st[i].matches("[0-9]+")) {
        String[] c = st[i].split("(?=\\d)");
        int sum = 0;
        for(int j=0 ; j<c.length ; j++) {
            sum += Integer.parseInt(c[j]);
        }
        System.out.println(sum);

    }
}

the output is:

5
18


问:
Error on signing-config.json (Access is denied) running an app in Android Studio
I tried to run my app but I got this error in the android studio:

D:\AndroidStudioProjects\ShelfExpert\app\build\intermediates\signing_config\debug\out\signing-config.json
  (Access is denied)

What should I do?

答: I had almost the same problem, but I use React-Native. I was trying to build a release version of my app (with the 'gradlew assembleRelease' command). Deleting this file haven't solved the problem. To solve I had to set the user permission of the file explicity to my user (even beeing  the current admin) on Windows. In other words I gave permission of reading and writing. You can do that by going in the Properties of the file. Previously, everything was working fine and after some updates this started to happen. I think Windows have made some mess with something. Hope it helps.


问:
Entity Framework Core code-first approach one to many relationship returns null
I'm new to Entity Framework Core, in my code I have a number of Questions class objects, and a list of choices to those questions. My query list of Choices always returns Null.

Here are my classes:

```<code>public class Questions
{
    [Key]
    public int QuestionID { get; set; }
    public string  Question { get; set; }

    public ICollection<Choices> choices { get; set; }
}

public class Choices
{
    [Key]
    public int ChoicesId { get; set; }
    public int QuestionId { get; set; }
    public Questions questions  { get; set; }
    public string Choice { get; set; }
}

public class SqlUserRepository : IUserRepository
{
    private readonly AppDbContext context;

    public SqlUserRepository(AppDbContext context)
    {
        this.context = context;
    }

    public List<Questions> getAllQuestions()
    {
        return context.questions.ToList();
    }
}
</code>```

I'm getting this O/p. choices always returns null

```<code>[
    { "questionID":1, "question":"which is your fav.heroien", "choices":null },
    { "questionID":2, "question":"which is your fav.hero", "choices":null  }
]
</code>```

I expect this output

```<code>[{"questionID":1,"question":"which is your fav.heroien","choices":[{"choicesId":5,"questionId":1,"questions":null,"choice":"kajol Agarwal"},{"choicesId":6,"questionId":1,"questions":null,"choice":"Thammanna Bhatia"},{"choicesId":7,"questionId":1,"questions":null,"choice":"Anushka Shetty"},{"choicesId":8,"questionId":1,"questions":null,"choice":"Keerthi Suresh"}]},{"questionID":2,"question":"which is your fav.hero","choices":[{"choicesId":1,"questionId":2,"questions":null,"choice":"upendera"},{"choicesId":2,"questionId":2,"questions":null,"choice":"real star"},{"choicesId":3,"questionId":2,"questions":null,"choice":"Super star"},{"choicesId":4,"questionId":2,"questions":null,"choice":"Only star"}]}]
</code>```

答:
```<code>public List<Questions> getAllQuestions()
  {
    return context.questions.Include(q => q.choices).ToList();
  }
</code>```

Include() allows you to indicate which related entities should be read from the database as part of the same query.

The final statement which calls Include("Choices") may look like this:

```<code>SELECT *
FROM questions JOIN Choices ON questions.Id = Choices.questionsId;
</code>```

https://stackoverflow.com/a/26661930/8006943

Body:
I'm new to Entity Framework Core, in my code I have a number of Questions class objects, and a list of choices to those questions. My query list of Choices always returns Null.

Here are my classes:

public class Questions
{
    [Key]
    public int QuestionID { get; set; }
    public string  Question { get; set; }

    public ICollection<Choices> choices { get; set; }
}

public class Choices
{
    [Key]
    public int ChoicesId { get; set; }
    public int QuestionId { get; set; }
    public Questions questions  { get; set; }
    public string Choice { get; set; }
}

public class SqlUserRepository : IUserRepository
{
    private readonly AppDbContext context;

    public SqlUserRepository(AppDbContext context)
    {
        this.context = context;
    }

    public List<Questions> getAllQuestions()
    {
        return context.questions.ToList();
    }
}

I'm getting this O/p. choices always returns null

[
    { "questionID":1, "question":"which is your fav.heroien", "choices":null },
    { "questionID":2, "question":"which is your fav.hero", "choices":null  }
]

I expect this output

[{"questionID":1,"question":"which is your fav.heroien","choices":[{"choicesId":5,"questionId":1,"questions":null,"choice":"kajol Agarwal"},{"choicesId":6,"questionId":1,"questions":null,"choice":"Thammanna Bhatia"},{"choicesId":7,"questionId":1,"questions":null,"choice":"Anushka Shetty"},{"choicesId":8,"questionId":1,"questions":null,"choice":"Keerthi Suresh"}]},{"questionID":2,"question":"which is your fav.hero","choices":[{"choicesId":1,"questionId":2,"questions":null,"choice":"upendera"},{"choicesId":2,"questionId":2,"questions":null,"choice":"real star"},{"choicesId":3,"questionId":2,"questions":null,"choice":"Super star"},{"choicesId":4,"questionId":2,"questions":null,"choice":"Only star"}]}]

Body:
public List<Questions> getAllQuestions()
  {
    return context.questions.Include(q => q.choices).ToList();
  }

Include() allows you to indicate which related entities should be read from the database as part of the same query.

The final statement which calls Include("Choices") may look like this:

SELECT *
FROM questions JOIN Choices ON questions.Id = Choices.questionsId;

https://stackoverflow.com/a/26661930/8006943


问:
Exclude directory from loading
As I know, non-Python files (i.e. file.sublime-menu, file.sublime-keymap, etc.) can be located at ANY level inside package directory:

```<code>                                   Will be loaded? (Yes/No)

Packages
|-- Foo Package
|   |-- Old version
|   |   |-- foo.sublime-menu       Y - it is the problem
|   |   |-- foo.sublime-keymap     Y - it is the problem
|   |   |-- foo.py                 N
|   |
|   |-- foo.sublime-menu           Y
|   |-- foo.sublime-keymap         Y
|   |-- foo.py                     Y
</code>```

I want to have Old version directory inside Foo Package, but the problem is that old menu and keymap files will be loaded. Is there a way to have some special file (call it package.exclude for example) with exclusion rules? Something like

```<code>exclude:
./Old version
</code>```

答: Other than changing the extension of the file to not be one that Sublime recognizes and loads, there is no way to stop it from finding and loading resources short of removing the file entirely or adding the package that they're stored in into the ignored_packages setting.

Title: Exclude directory from loading

Body:
As I know, non-Python files (i.e. file.sublime-menu, file.sublime-keymap, etc.) can be located at ANY level inside package directory:

                                   Will be loaded? (Yes/No)

Packages
|-- Foo Package
|   |-- Old version
|   |   |-- foo.sublime-menu       Y - it is the problem
|   |   |-- foo.sublime-keymap     Y - it is the problem
|   |   |-- foo.py                 N
|   |
|   |-- foo.sublime-menu           Y
|   |-- foo.sublime-keymap         Y
|   |-- foo.py                     Y

I want to have Old version directory inside Foo Package, but the problem is that old menu and keymap files will be loaded. Is there a way to have some special file (call it package.exclude for example) with exclusion rules? Something like

exclude:
./Old version


问:
When login with other user it still picks previous user uuid from nowhere
I am working with some of my projects and the problem i am facing is when i login with user "A" and use the app for some time then i logout the user and then i login with another user "B" then in some of the screens where i have to show the user profile pic (Baseurl + profilepic name). It doesn't shows up, when i took a log of the profile pic url then i found that it still picking up the uuid of  old logged in user "A".

Note :- BaseUrl is made up with concatenation with uuid.

Here are the login and logout method classes and constant class which i am using to save the data on login response and nil the data on logout reponse

Login method if status is 1 :-

```<code>                        if(status == 1)
                        {
                            DispatchQueue.main.async {
                                GAReusableClass.sharedInstance.hideActivityIndicator()
                                UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
                                let Dict = self.mainDict[KData] as!  [String: AnyObject]
                                print("self.DataDict", self.DataDict)
                                let User_ID = Dict[KUuid]as! String
                                print(User_ID)
                                let HMACSECRETKEY = self.deviceToken + "+" + User_ID
                                kHMACKey = HMACSECRETKEY
                                let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
                                print(HMACSECRETKEY)
                                UserDefaults.standard.setValue(cipher, forKey:HmacKey)
                                UserDefaults.standard.set(true, forKey: "isLogin")
                                GAloginUserInfo.shared.saveUserInfo(dict: Dict )
                                let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
                                self.navigationController?.pushViewController(tabar, animated: true)

                            }
</code>```

Logout method if status is 1 :-

```<code>                    if(status == 1)
                    {
                        DispatchQueue.main.async {
                            GAReusableClass.sharedInstance.hideActivityIndicator()

                            defaults.removeObject(forKey: MaindataKey)
                            defaults.removeObject(forKey: HmacKey)
                            defaults.set(false, forKey: "isLogin")
                            GAloginUserInfo.shared.removeUserInfo()

                            let login = self.storyboard?.instantiateViewController(withIdentifier: "GALoginViewController") as! GALoginViewController
                            self.navigationController?.pushViewController(login, animated: true)

                        }
</code>```

Constant class :-

```<code>import UIKit

let defaults = UserDefaults.standard
var kDeviceToken = String()
var kHMACKey = String()
let Headerkey = "header"
let KData = "data"
let KStatus = "status"
let KMessage = "message"
let MaindataKey = "MAINDATA"
let KUuid = "uuid"
let HmacKey = "HMACKEY"
let imageThumbBaseURL = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/video_thumbs/"
let videoFileBaseURL = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/video_files/"
let BaseURl = "http://demodemodemo.ga/index.php?api/"
let BaseURLProfilePic = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/profile_pic/"
</code>```

Login user Shared class :-

```<code>import UIKit
class GAloginUserInfo: NSObject {
    var loginUserMobileNo : String?
    var loginUserId : String?
    var loginUserUuid : String?
    var loginUserCountry : String?
    var loginUserCountryCode : String?
    var loginUserEmail : String?
    var loginUserlatitude : String?
    var loginUserLongitude : String?
    var loginUserName : String?
    var loginUserQrcode : String?
    var loginUserProfilePic : String?
    var isverify : String?
    var loginPassword : String?
    var dateOfBirth: String?
    var earnedPoints:String?
    var loginUserGender:String?
    var loginUserFollowers:Int = 0

    static let shared = GAloginUserInfo()
    func saveUserInfo (dict : [String : AnyObject?] )  {

        if let loginUserMobileNo = dict["mobile"] as? String {
            self.loginUserMobileNo = loginUserMobileNo
        }
        if let loginUserId = dict["id"] as? String {
            self.loginUserId = loginUserId
        }
        if let loginUserUuid = dict["uuid"] as? String {
            self.loginUserUuid = loginUserUuid
            print(loginUserUuid)
        }
        if let loginUserCountry = dict["countryNameCode"] as? String {
            self.loginUserCountry = loginUserCountry
        }
        if let loginUserCountryCode = dict["country_code"] as? String {
            self.loginUserCountryCode = loginUserCountryCode
        }
        if let loginUserEmail = dict["email"] as? String {
            self.loginUserEmail = loginUserEmail
        }
        if let loginUserProfilePic = dict["profile_pic"] as? String {
            self.loginUserProfilePic = loginUserProfilePic
        }
        if let loginUserLongitude = dict["logitude"] as? String {
            self.loginUserLongitude = loginUserLongitude
        }
        if let loginUserName = dict["name"] as? String {
            self.loginUserName = loginUserName
        }
        if let loginUserQrcode = dict["qr_code"] as? String {
            self.loginUserQrcode = loginUserQrcode
        }
        if let Password = dict["password"] as? String{
            self.loginPassword = Password
        }
        if let dateOfBirth = dict["dob"] as? String{
            self.dateOfBirth = dateOfBirth
        }
        if let earnedPoints = dict["points"] as? String{
            let myDouble = Double(earnedPoints)
            let doubleStr = String(format: "%.2f", myDouble!)
            self.earnedPoints = doubleStr
        }
        if let loginUserGender = dict["gender"] as? String{
            self.loginUserGender = loginUserGender
        }
        if let loginUserFollowers = dict["followersCount"] as? Int{
            self.loginUserFollowers = loginUserFollowers
        }

    }

}
extension GAloginUserInfo {
    func removeUserInfo() {
        self.loginUserMobileNo = nil
        self.loginUserId = nil
        self.loginUserUuid = nil
        self.loginUserCountry = nil
        self.loginUserCountryCode = nil
        self.loginUserEmail = nil
        self.loginUserlatitude = nil
        self.loginUserLongitude = nil
        self.loginUserName = nil
        self.loginUserQrcode = nil
        self.loginUserProfilePic = nil
        self.isverify = nil
        self.loginPassword = nil
        self.dateOfBirth = nil
        self.earnedPoints = nil
        self.loginUserGender = nil
        self.loginUserFollowers = 0
    }
}
</code>```

答:
I think the problem causes due to the threading. Move the non uikit classes operations from the main dispatch queue.

Login method if status is 1 :-

```<code>if(status == 1)
    {
        UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
        let Dict = self.mainDict[KData] as!  [String: AnyObject]
        print("self.DataDict", self.DataDict)
        let User_ID = Dict[KUuid]as! String
        print(User_ID)
        let HMACSECRETKEY = self.deviceToken + "+" + User_ID
        kHMACKey = HMACSECRETKEY
        let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
        print(HMACSECRETKEY)
        UserDefaults.standard.setValue(cipher, forKey:HmacKey)
        UserDefaults.standard.set(true, forKey: "isLogin")
        GAloginUserInfo.shared.saveUserInfo(dict: Dict )

        DispatchQueue.main.async {
            GAReusableClass.sharedInstance.hideActivityIndicator()
            let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
            self.navigationController?.pushViewController(tabar, animated: true)

        }
    }
</code>```

Logout method if status is 1 :-

```<code>if(status == 1)
    {
        defaults.removeObject(forKey: MaindataKey)
        defaults.removeObject(forKey: HmacKey)
        defaults.set(false, forKey: "isLogin")
        GAloginUserInfo.shared.removeUserInfo()

        DispatchQueue.main.async {
            GAReusableClass.sharedInstance.hideActivityIndicator()

            let login = self.storyboard?.instantiateViewController(withIdentifier: "GALoginViewController") as! GALoginViewController
            self.navigationController?.pushViewController(login, animated: true)

        }
    }
</code>```

Body:
I am working with some of my projects and the problem i am facing is when i login with user "A" and use the app for some time then i logout the user and then i login with another user "B" then in some of the screens where i have to show the user profile pic (Baseurl + profilepic name). It doesn't shows up, when i took a log of the profile pic url then i found that it still picking up the uuid of  old logged in user "A".

Note :- BaseUrl is made up with concatenation with uuid.

Here are the login and logout method classes and constant class which i am using to save the data on login response and nil the data on logout reponse

Login method if status is 1 :-

                        if(status == 1)
                        {
                            DispatchQueue.main.async {
                                GAReusableClass.sharedInstance.hideActivityIndicator()
                                UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
                                let Dict = self.mainDict[KData] as!  [String: AnyObject]
                                print("self.DataDict", self.DataDict)
                                let User_ID = Dict[KUuid]as! String
                                print(User_ID)
                                let HMACSECRETKEY = self.deviceToken + "+" + User_ID
                                kHMACKey = HMACSECRETKEY
                                let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
                                print(HMACSECRETKEY)
                                UserDefaults.standard.setValue(cipher, forKey:HmacKey)
                                UserDefaults.standard.set(true, forKey: "isLogin")
                                GAloginUserInfo.shared.saveUserInfo(dict: Dict )
                                let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
                                self.navigationController?.pushViewController(tabar, animated: true)

                            }

Logout method if status is 1 :-

                    if(status == 1)
                    {
                        DispatchQueue.main.async {
                            GAReusableClass.sharedInstance.hideActivityIndicator()

                            defaults.removeObject(forKey: MaindataKey)
                            defaults.removeObject(forKey: HmacKey)
                            defaults.set(false, forKey: "isLogin")
                            GAloginUserInfo.shared.removeUserInfo()

                            let login = self.storyboard?.instantiateViewController(withIdentifier: "GALoginViewController") as! GALoginViewController
                            self.navigationController?.pushViewController(login, animated: true)

                        }

Constant class :-

import UIKit

let defaults = UserDefaults.standard
var kDeviceToken = String()
var kHMACKey = String()
let Headerkey = "header"
let KData = "data"
let KStatus = "status"
let KMessage = "message"
let MaindataKey = "MAINDATA"
let KUuid = "uuid"
let HmacKey = "HMACKEY"
let imageThumbBaseURL = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/video_thumbs/"
let videoFileBaseURL = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/video_files/"
let BaseURl = "http://demodemodemo.ga/index.php?api/"
let BaseURLProfilePic = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/profile_pic/"

Login user Shared class :-

import UIKit
class GAloginUserInfo: NSObject {
    var loginUserMobileNo : String?
    var loginUserId : String?
    var loginUserUuid : String?
    var loginUserCountry : String?
    var loginUserCountryCode : String?
    var loginUserEmail : String?
    var loginUserlatitude : String?
    var loginUserLongitude : String?
    var loginUserName : String?
    var loginUserQrcode : String?
    var loginUserProfilePic : String?
    var isverify : String?
    var loginPassword : String?
    var dateOfBirth: String?
    var earnedPoints:String?
    var loginUserGender:String?
    var loginUserFollowers:Int = 0

    static let shared = GAloginUserInfo()
    func saveUserInfo (dict : [String : AnyObject?] )  {

        if let loginUserMobileNo = dict["mobile"] as? String {
            self.loginUserMobileNo = loginUserMobileNo
        }
        if let loginUserId = dict["id"] as? String {
            self.loginUserId = loginUserId
        }
        if let loginUserUuid = dict["uuid"] as? String {
            self.loginUserUuid = loginUserUuid
            print(loginUserUuid)
        }
        if let loginUserCountry = dict["countryNameCode"] as? String {
            self.loginUserCountry = loginUserCountry
        }
        if let loginUserCountryCode = dict["country_code"] as? String {
            self.loginUserCountryCode = loginUserCountryCode
        }
        if let loginUserEmail = dict["email"] as? String {
            self.loginUserEmail = loginUserEmail
        }
        if let loginUserProfilePic = dict["profile_pic"] as? String {
            self.loginUserProfilePic = loginUserProfilePic
        }
        if let loginUserLongitude = dict["logitude"] as? String {
            self.loginUserLongitude = loginUserLongitude
        }
        if let loginUserName = dict["name"] as? String {
            self.loginUserName = loginUserName
        }
        if let loginUserQrcode = dict["qr_code"] as? String {
            self.loginUserQrcode = loginUserQrcode
        }
        if let Password = dict["password"] as? String{
            self.loginPassword = Password
        }
        if let dateOfBirth = dict["dob"] as? String{
            self.dateOfBirth = dateOfBirth
        }
        if let earnedPoints = dict["points"] as? String{
            let myDouble = Double(earnedPoints)
            let doubleStr = String(format: "%.2f", myDouble!)
            self.earnedPoints = doubleStr
        }
        if let loginUserGender = dict["gender"] as? String{
            self.loginUserGender = loginUserGender
        }
        if let loginUserFollowers = dict["followersCount"] as? Int{
            self.loginUserFollowers = loginUserFollowers
        }

    }

}
extension GAloginUserInfo {
    func removeUserInfo() {
        self.loginUserMobileNo = nil
        self.loginUserId = nil
        self.loginUserUuid = nil
        self.loginUserCountry = nil
        self.loginUserCountryCode = nil
        self.loginUserEmail = nil
        self.loginUserlatitude = nil
        self.loginUserLongitude = nil
        self.loginUserName = nil
        self.loginUserQrcode = nil
        self.loginUserProfilePic = nil
        self.isverify = nil
        self.loginPassword = nil
        self.dateOfBirth = nil
        self.earnedPoints = nil
        self.loginUserGender = nil
        self.loginUserFollowers = 0
    }
}

Body:
I think the problem causes due to the threading. Move the non uikit classes operations from the main dispatch queue.

Login method if status is 1 :-

if(status == 1)
    {
        UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
        let Dict = self.mainDict[KData] as!  [String: AnyObject]
        print("self.DataDict", self.DataDict)
        let User_ID = Dict[KUuid]as! String
        print(User_ID)
        let HMACSECRETKEY = self.deviceToken + "+" + User_ID
        kHMACKey = HMACSECRETKEY
        let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
        print(HMACSECRETKEY)
        UserDefaults.standard.setValue(cipher, forKey:HmacKey)
        UserDefaults.standard.set(true, forKey: "isLogin")
        GAloginUserInfo.shared.saveUserInfo(dict: Dict )

        DispatchQueue.main.async {
            GAReusableClass.sharedInstance.hideActivityIndicator()
            let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
            self.navigationController?.pushViewController(tabar, animated: true)

        }
    }

Logout method if status is 1 :-

if(status == 1)
    {
        defaults.removeObject(forKey: MaindataKey)
        defaults.removeObject(forKey: HmacKey)
        defaults.set(false, forKey: "isLogin")
        GAloginUserInfo.shared.removeUserInfo()

        DispatchQueue.main.async {
            GAReusableClass.sharedInstance.hideActivityIndicator()

            let login = self.storyboard?.instantiateViewController(withIdentifier: "GALoginViewController") as! GALoginViewController
            self.navigationController?.pushViewController(login, animated: true)

        }
    }


问:
AMP-IFRAME same origin for iframe
It's an known issue that AMP Policy explicity forbides embeding Iframes with same orgin while setting the sandobox attributes:

```<code><amp-iframe ... sandbox="allow-scripts allow-same-origin" src="same-as-the origin"../>
</code>```

But as stated here:
Setting both the allow-scripts and allow-same-origin keywords together when the embedded page has the same origin as the page containing the iframe allows the embedded page to simply remove the sandbox attribute and then reload itself, effectively breaking out of the sandbox altogether.

But for some reasons it does not work and my iframe content can't be displayed.

Error: origin of  must not be equal to container...

How to overcome this Problem? (I need it only just for testing purposes so I I am well aware that this approach shouldn't be deployed live)

I had also installed an Chrom-Plugin for enabling cross-origin resource sharing but it hasn't any effect.

Either restarted the Chrom-browser with the --disable-web-security option...
nothing has really worked so far

答: It's OK for me with sandbox="allow-scripts". Do you have any CSP settings that blocks iFrames such as "frame-ancestors 'none';" or X-Frame-Options "deny" ?</p>

Title: AMP-IFRAME same origin for iframe

Body:
It's an known issue that AMP Policy explicity forbides embeding Iframes with same orgin while setting the sandobox attributes:

<amp-iframe ... sandbox="allow-scripts allow-same-origin" src="same-as-the origin"../>

But as stated here:
Setting both the allow-scripts and allow-same-origin keywords together when the embedded page has the same origin as the page containing the iframe allows the embedded page to simply remove the sandbox attribute and then reload itself, effectively breaking out of the sandbox altogether.

But for some reasons it does not work and my iframe content can't be displayed.

Error: origin of  must not be equal to container...

How to overcome this Problem? (I need it only just for testing purposes so I I am well aware that this approach shouldn't be deployed live)

I had also installed an Chrom-Plugin for enabling cross-origin resource sharing but it hasn't any effect.

Either restarted the Chrom-browser with the --disable-web-security option...
nothing has really worked so far