问:
Parse a text file into instances of a class based on keywords c#
I have a text file that contains a list of points:

POINT:
   TYPE 5,
   OBJECT ID 2,
   DEVICE TYPE CAT,
   TAG 'ADDRESS-1',
   DESCRIPTION 'kitty',
   UNITS 'Lb',

POINT:
   TYPE 5,
   OBJECT ID 2,
   DEVICE TYPE CAT,
   TAG 'ADDRESS-2',
   DESCRIPTION 'orange kitty',
   UNITS 'Lb',

POINT:
   TYPE 2,
   OBJECT ID 3,
   DEVICE TYPE DOG,
   TAG 'ADDRESS-5',
   DESCRIPTION 'brown dog',
   UNITS 'Lb',

From this, I want to create instances (in this case, 2) of my class 'Cat' that contain the tag and description in this text file(and then put them in a list of Cats). I only want to take the description and tag from points of Type 5 (those are the cats).

I'm not sure what the best approach is to get the strings I want. I need to search the entire file for all points of type 5, then for each of those points, take the description and tag and add it to a new Cat.

```<code> public static void Main()
    {
        string line;
        List<Cat> catList = new List<Cat>();
        StreamReader file = new StreamReader(@"C:\Config\pets.txt");
        while((line = file.ReadLine()) != null)
        {
            string[] words = line.Split(',');
            catList.Add(new Cat cat1)
        }}
</code>```

I ended up doing it this way:

```<code> public static List<List<string>> Parse()
    {
        string filePath = @"C:\Config\pets.txt";
        string readText = File.ReadAllText(filePath);
        string[] stringSeparators = new string[] { "POINT:" }; //POINT is the keyword the text will be split on
        string[] result;

        result = readText.Split(stringSeparators, StringSplitOptions.None);
        List<List<string>> catData = new List<List<string>>();
        //split the text into an list of pieces
        List<string> tags = new List<string>(); //tags go here
        List<string> descriptions = new List<string>(); //descriptions go here
        foreach (string s in result)
        {
            if (s.Contains("TYPE 5")) //TYPE 5 = CAT
            {

                string[] parts = s.Split(','); //split the cat by commas
                string chop = "'"; //once tags and descriptions have been found, only want to keep what is inside single quotes ie 'orange kitty'
                foreach (string part in parts)
                {
                    if (part.Contains("TAG"))
                    {
                        int startIndex = part.IndexOf(chop);
                        int endIndex = part.LastIndexOf(chop);
                        int length = endIndex - startIndex + 1;
                        string path = part.Substring(startIndex, length);
                        tag = tag.Replace(chop, string.Empty);
                        tags.Add(tag);
                        //need to create instance of Cat with this tag
                    }
                    if (part.Contains("DESCRIPTION"))
                    {
                        int startIndex = part.IndexOf(chop);
                        int endIndex = part.LastIndexOf(chop);
                        int length = endIndex - startIndex + 1;
                        string description = part.Substring(startIndex, length);
                        description = description.Replace(chop, string.Empty);
                        descriptions.Add(description);
                        //need to add description to Cat instance that matches associated tag
                    }

                }
            }

        }

        catData.Add(tags);
        catData.Add(descriptions);
        return catData;
</code>```

答:
What I would do is create a class that represents the fields you want to capture. For this example, I'm capturing all the fields, but you can customize it how you want. I called this class "Animal", since it seems the "points" represent an animal.

Then I would add a static Parse method to the class that will return an instance of an Animal based on some input string. This method will parse the input string and attempt to set the relevant properties of the Animal object based on the values in the string.

I also added a ToString() override on the class so we have some way of displaying the output:

```<code>class Animal
{
    public int Type { get; set; }
    public int ObjectId { get; set; }
    public string DeviceType { get; set; }
    public string Tag { get; set; }
    public string Description { get; set; }
    public string Units { get; set; }

    /// <summary>
    /// Parses an input string and returns an Animal based
    /// on any property values found in the string
    /// </summary>
    /// <param name="input">The string to parse for property values</param>
    /// <returns>An animal instance with specified properties</returns>
    public static Animal Parse(string input)
    {
        var result = new Animal();
        if (string.IsNullOrWhiteSpace(input)) return result;

        // Parse input string and set fields accordingly
        var keyValueParts = input
            .Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries)
            .Select(kvp => kvp.Trim());

        foreach (var keyValuePart in keyValueParts)
        {
            if (keyValuePart.StartsWith("Type",
                StringComparison.OrdinalIgnoreCase))
            {
                int type;
                var value = keyValuePart.Substring("Type".Length).Trim();
                if (int.TryParse(value, out type))
                {
                    result.Type = type;
                }
            }
            else if (keyValuePart.StartsWith("Object Id",
                StringComparison.OrdinalIgnoreCase))
            {
                int objectId;
                var value = keyValuePart.Substring("Object Id".Length).Trim();
                if (int.TryParse(value, out objectId))
                {
                    result.ObjectId = objectId;
                }
            }
            else if (keyValuePart.StartsWith("Device Type",
                StringComparison.OrdinalIgnoreCase))
            {
                var value = keyValuePart.Substring("Device Type".Length).Trim();
                result.DeviceType = value;
            }
            else if (keyValuePart.StartsWith("Tag",
                StringComparison.OrdinalIgnoreCase))
            {
                var value = keyValuePart.Substring("Tag".Length).Trim();
                result.Tag = value;
            }
            else if (keyValuePart.StartsWith("Description",
                StringComparison.OrdinalIgnoreCase))
            {
                var value = keyValuePart.Substring("Description".Length).Trim();
                result.Description = value;
            }
            else if (keyValuePart.StartsWith("Units",
                StringComparison.OrdinalIgnoreCase))
            {
                var value = keyValuePart.Substring("Units".Length).Trim();
                result.Units = value;
            }
        }

        return result;
    }

    public override string ToString()
    {
        // Return a string that describes this animal
        var animalProperties = new StringBuilder();
        animalProperties.Append($"Type = {Type}, Object Id = {ObjectId}, ");
        animalProperties.Append($"Device Type = {DeviceType}, Tag = {Tag}, ");
        animalProperties.Append($"Description = {Description}, Units = {Units}");
        return animalProperties.ToString();
    }
}
</code>```

Now that we have an object that can create itself from a string, we just need to read in the file contents, split it on the "Point:" keyword, and then pass each string to the Animal class to get our instances.

I added some System.Linq clause to filter on animals that have Type = 5 (which you said are all cats), since you said that was the only animal you were interested in. Of course you could remove this to get all animals, or replace it with "Dog" to get the dogs, etc..:

```<code>private static void Main()
{
    var filePath = @"f:\public\temp\temp.txt";

    // Read all file contents and split it on the word "Point:"
    var fileContents = Regex
        .Split(File.ReadAllText(filePath), "Point:", RegexOptions.IgnoreCase)
        .Where(point => !string.IsNullOrWhiteSpace(point))
        .Select(point => point.Trim());

    // Get all animals that are cats from the results
    var catList = fileContents
        .Select(Animal.Parse)
        .Where(animal => animal.Type == 5)
        .ToList();

    // Output results
    catList.ForEach(Console.WriteLine);

    // Wait for input before closing
    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Output

Body:
I have a text file that contains a list of points:

POINT:
   TYPE 5,
   OBJECT ID 2,
   DEVICE TYPE CAT,
   TAG 'ADDRESS-1',
   DESCRIPTION 'kitty',
   UNITS 'Lb',

POINT:
   TYPE 5,
   OBJECT ID 2,
   DEVICE TYPE CAT,
   TAG 'ADDRESS-2',
   DESCRIPTION 'orange kitty',
   UNITS 'Lb',

POINT:
   TYPE 2,
   OBJECT ID 3,
   DEVICE TYPE DOG,
   TAG 'ADDRESS-5',
   DESCRIPTION 'brown dog',
   UNITS 'Lb',

From this, I want to create instances (in this case, 2) of my class 'Cat' that contain the tag and description in this text file(and then put them in a list of Cats). I only want to take the description and tag from points of Type 5 (those are the cats).

I'm not sure what the best approach is to get the strings I want. I need to search the entire file for all points of type 5, then for each of those points, take the description and tag and add it to a new Cat.

 public static void Main()
    {
        string line;
        List<Cat> catList = new List<Cat>();
        StreamReader file = new StreamReader(@"C:\Config\pets.txt");
        while((line = file.ReadLine()) != null)
        {
            string[] words = line.Split(',');
            catList.Add(new Cat cat1)
        }}

I ended up doing it this way:

 public static List<List<string>> Parse()
    {
        string filePath = @"C:\Config\pets.txt";
        string readText = File.ReadAllText(filePath);
        string[] stringSeparators = new string[] { "POINT:" }; //POINT is the keyword the text will be split on
        string[] result;

        result = readText.Split(stringSeparators, StringSplitOptions.None);
        List<List<string>> catData = new List<List<string>>();
        //split the text into an list of pieces
        List<string> tags = new List<string>(); //tags go here
        List<string> descriptions = new List<string>(); //descriptions go here
        foreach (string s in result)
        {
            if (s.Contains("TYPE 5")) //TYPE 5 = CAT
            {

                string[] parts = s.Split(','); //split the cat by commas
                string chop = "'"; //once tags and descriptions have been found, only want to keep what is inside single quotes ie 'orange kitty'
                foreach (string part in parts)
                {
                    if (part.Contains("TAG"))
                    {
                        int startIndex = part.IndexOf(chop);
                        int endIndex = part.LastIndexOf(chop);
                        int length = endIndex - startIndex + 1;
                        string path = part.Substring(startIndex, length);
                        tag = tag.Replace(chop, string.Empty);
                        tags.Add(tag);
                        //need to create instance of Cat with this tag
                    }
                    if (part.Contains("DESCRIPTION"))
                    {
                        int startIndex = part.IndexOf(chop);
                        int endIndex = part.LastIndexOf(chop);
                        int length = endIndex - startIndex + 1;
                        string description = part.Substring(startIndex, length);
                        description = description.Replace(chop, string.Empty);
                        descriptions.Add(description);
                        //need to add description to Cat instance that matches associated tag
                    }

                }
            }

        }

        catData.Add(tags);
        catData.Add(descriptions);
        return catData;

Body:
What I would do is create a class that represents the fields you want to capture. For this example, I'm capturing all the fields, but you can customize it how you want. I called this class "Animal", since it seems the "points" represent an animal.

Then I would add a static Parse method to the class that will return an instance of an Animal based on some input string. This method will parse the input string and attempt to set the relevant properties of the Animal object based on the values in the string.

I also added a ToString() override on the class so we have some way of displaying the output:

class Animal
{
    public int Type { get; set; }
    public int ObjectId { get; set; }
    public string DeviceType { get; set; }
    public string Tag { get; set; }
    public string Description { get; set; }
    public string Units { get; set; }

    /// <summary>
    /// Parses an input string and returns an Animal based
    /// on any property values found in the string
    /// </summary>
    /// <param name="input">The string to parse for property values</param>
    /// <returns>An animal instance with specified properties</returns>
    public static Animal Parse(string input)
    {
        var result = new Animal();
        if (string.IsNullOrWhiteSpace(input)) return result;

        // Parse input string and set fields accordingly
        var keyValueParts = input
            .Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries)
            .Select(kvp => kvp.Trim());

        foreach (var keyValuePart in keyValueParts)
        {
            if (keyValuePart.StartsWith("Type",
                StringComparison.OrdinalIgnoreCase))
            {
                int type;
                var value = keyValuePart.Substring("Type".Length).Trim();
                if (int.TryParse(value, out type))
                {
                    result.Type = type;
                }
            }
            else if (keyValuePart.StartsWith("Object Id",
                StringComparison.OrdinalIgnoreCase))
            {
                int objectId;
                var value = keyValuePart.Substring("Object Id".Length).Trim();
                if (int.TryParse(value, out objectId))
                {
                    result.ObjectId = objectId;
                }
            }
            else if (keyValuePart.StartsWith("Device Type",
                StringComparison.OrdinalIgnoreCase))
            {
                var value = keyValuePart.Substring("Device Type".Length).Trim();
                result.DeviceType = value;
            }
            else if (keyValuePart.StartsWith("Tag",
                StringComparison.OrdinalIgnoreCase))
            {
                var value = keyValuePart.Substring("Tag".Length).Trim();
                result.Tag = value;
            }
            else if (keyValuePart.StartsWith("Description",
                StringComparison.OrdinalIgnoreCase))
            {
                var value = keyValuePart.Substring("Description".Length).Trim();
                result.Description = value;
            }
            else if (keyValuePart.StartsWith("Units",
                StringComparison.OrdinalIgnoreCase))
            {
                var value = keyValuePart.Substring("Units".Length).Trim();
                result.Units = value;
            }
        }

        return result;
    }

    public override string ToString()
    {
        // Return a string that describes this animal
        var animalProperties = new StringBuilder();
        animalProperties.Append($"Type = {Type}, Object Id = {ObjectId}, ");
        animalProperties.Append($"Device Type = {DeviceType}, Tag = {Tag}, ");
        animalProperties.Append($"Description = {Description}, Units = {Units}");
        return animalProperties.ToString();
    }
}

Now that we have an object that can create itself from a string, we just need to read in the file contents, split it on the "Point:" keyword, and then pass each string to the Animal class to get our instances.

I added some System.Linq clause to filter on animals that have Type = 5 (which you said are all cats), since you said that was the only animal you were interested in. Of course you could remove this to get all animals, or replace it with "Dog" to get the dogs, etc..:

private static void Main()
{
    var filePath = @"f:\public\temp\temp.txt";

    // Read all file contents and split it on the word "Point:"
    var fileContents = Regex
        .Split(File.ReadAllText(filePath), "Point:", RegexOptions.IgnoreCase)
        .Where(point => !string.IsNullOrWhiteSpace(point))
        .Select(point => point.Trim());

    // Get all animals that are cats from the results
    var catList = fileContents
        .Select(Animal.Parse)
        .Where(animal => animal.Type == 5)
        .ToList();

    // Output results
    catList.ForEach(Console.WriteLine);

    // Wait for input before closing
    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output


来源: stackexchange

问:
How to use jquery-migrate with webpack?
After npm install jquery-migrate, I could just require('jquery-migrate'); in the main scripts.js file. This works fine:

```<code>console.log(jQuery.migrateVersion); // JQMIGRATE: Migrate is installed with logging active, version 3.0.0
</code>```

Now, I would like to set it so jquery-migrate is not present on the production version.

webpack.config.js:

```<code>var dev = process.env.NODE_ENV !== 'prod';
var webpack = require('webpack');
var dist = '/dist/js';

module.exports = {
    context: __dirname,
    entry: __dirname + '/src/js/scripts.js',
    output: {
        path: __dirname + dist,
        filename: 'scripts.js'
    },
    resolve: {
        alias: {
            'jquery': 'jquery/src/jquery',
            'jquery-migrate': 'jquery-migrate'
        }
    },
    plugins: dev ? [
        new webpack.ProvidePlugin({
            '$': 'jquery',
            'jQuery': 'jquery',
            'jquery-migrate': 'jquery-migrate'
        })
    ] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
        new webpack.ProvidePlugin({
            '$': 'jquery',
            'jQuery': 'jquery'
        })
    ]
};
</code>```

This is not working:

```<code>console.log(jQuery.migrateVersion); // Undefined
</code>```

How is it possible to load jquery-migrate form the webpack.config?

答:
You can create a global __DEV__ variable accessible throughout your application via webpack.config.js.  Just add the following to your plugins array:

```<code>plugins: [
    new webpack.DefinePlugin({
        __DEV__: dev
    }),
    // other plugins
]
</code>```

Webpack - DefinePlugin

Install jquery-migrate with:

```<code>npm install jquery-migrate --save-dev
</code>```

Then in the entry point of your application (perhaps app.js) just add:

```<code>if (__DEV__) {
    require("jquery-migrate");
}
</code>```

Also, some jquery plugins, like the latest version (at the time of this writing) of jqueryCaret, reference window.jQuery rather than just jQuery, so you may need to add the 'window.jQuery': 'jquery' line to your webpack.ProvidePlugin constructor:

```<code>plugins: [
    new webpack.ProvidePlugin({
        jQuery: 'jquery',
        '$': 'jquery',
        'window.jQuery': 'jquery',
    }),
    // other plugins
]
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to use jquery-migrate with webpack?

Body:
After npm install jquery-migrate, I could just require('jquery-migrate'); in the main scripts.js file. This works fine:

console.log(jQuery.migrateVersion); // JQMIGRATE: Migrate is installed with logging active, version 3.0.0

Now, I would like to set it so jquery-migrate is not present on the production version.

webpack.config.js:

var dev = process.env.NODE_ENV !== 'prod';
var webpack = require('webpack');
var dist = '/dist/js';

module.exports = {
    context: __dirname,
    entry: __dirname + '/src/js/scripts.js',
    output: {
        path: __dirname + dist,
        filename: 'scripts.js'
    },
    resolve: {
        alias: {
            'jquery': 'jquery/src/jquery',
            'jquery-migrate': 'jquery-migrate'
        }
    },
    plugins: dev ? [
        new webpack.ProvidePlugin({
            '$': 'jquery',
            'jQuery': 'jquery',
            'jquery-migrate': 'jquery-migrate'
        })
    ] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
        new webpack.ProvidePlugin({
            '$': 'jquery',
            'jQuery': 'jquery'
        })
    ]
};

This is not working:

console.log(jQuery.migrateVersion); // Undefined

How is it possible to load jquery-migrate form the webpack.config?

Body:
You can create a global __DEV__ variable accessible throughout your application via webpack.config.js.  Just add the following to your plugins array:

plugins: [
    new webpack.DefinePlugin({
        __DEV__: dev
    }),
    // other plugins
]

Webpack - DefinePlugin

Install jquery-migrate with:

npm install jquery-migrate --save-dev

Then in the entry point of your application (perhaps app.js) just add:

if (__DEV__) {
    require("jquery-migrate");
}

Also, some jquery plugins, like the latest version (at the time of this writing) of jqueryCaret, reference window.jQuery rather than just jQuery, so you may need to add the 'window.jQuery': 'jquery' line to your webpack.ProvidePlugin constructor:

plugins: [
    new webpack.ProvidePlugin({
        jQuery: 'jquery',
        '$': 'jquery',
        'window.jQuery': 'jquery',
    }),
    // other plugins
]


问:
How to delete Tkinter widgets from a window?
I have a list of tkinter widgets that I want to change dynamically.

How to delete the widgets from the window?

答:
One way you can do it, is to get the slaves list from the frame that needs to be cleared and destroy or "hide" them according to your needs. To get a clear frame you can do it like this:

```<code>from tkinter import *

root = Tk()

def clear():
    list = root.grid_slaves()
    for l in list:
        l.destroy()

Label(root,text='Hello World!').grid(row=0)
Button(root,text='Clear',command=clear).grid(row=1)

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

You should call grid_slaves(), pack_slaves() or slaves() depending on the method you used to add the widget to the frame.

ContentLicense: CC BY-SA 4.0

Body:
One way you can do it, is to get the slaves list from the frame that needs to be cleared and destroy or "hide" them according to your needs. To get a clear frame you can do it like this:

from tkinter import *

root = Tk()

def clear():
    list = root.grid_slaves()
    for l in list:
        l.destroy()

Label(root,text='Hello World!').grid(row=0)
Button(root,text='Clear',command=clear).grid(row=1)

root.mainloop()

You should call grid_slaves(), pack_slaves() or slaves() depending on the method you used to add the widget to the frame.


问:
How to go from DataFrame to multiple Series efficiently in Dask?
I'm trying to find an efficient way to transform a DataFrame into a bunch of persisted Series (columns) in Dask.

Consider a scenario where the data size is much larger than the sum of worker memory and most operations will be wrapped by read-from-disk / spill-to-disk. For algorithms which operate only on individual columns (or pairs of columns), reading-in the entire DataFrame from disk for every column operation is inefficient. In such a case, it would be nice to locally switch from a (possibly persisted) DataFrame to persisted columns instead. Implemented naively:

persisted_columns = {}
for column in subset_of_columns_to_persist:
    persisted_columns[column] = df[column].persist()
```

This works, but it is very inefficient because df[column] will re-read the entire DataFrame N = len(subset_of_columns_to_persist) times from disk. Is it possible to extract and persist multiple columns individually based on a single read-from-disk deserialization operation?

Note: len(subset_of_columns_to_persist) is >> 1, i.e., simply projecting the DataFrame to df[subset_of_columns_to_persist] is not the solution I'm looking for, because it still has a significant I/O overhead over persisting individual columns.

答:
You can persist many collections at the same time with the dask.persist function.  This will share intermediates.

```<code>columns = [df[column] for column in df.columns]
persisted_columns = dask.persist(*columns)
d = dict(zip(df.columns, persisted_columns))
</code>```

Body:
I'm trying to find an efficient way to transform a DataFrame into a bunch of persisted Series (columns) in Dask.

Consider a scenario where the data size is much larger than the sum of worker memory and most operations will be wrapped by read-from-disk / spill-to-disk. For algorithms which operate only on individual columns (or pairs of columns), reading-in the entire DataFrame from disk for every column operation is inefficient. In such a case, it would be nice to locally switch from a (possibly persisted) DataFrame to persisted columns instead. Implemented naively:

persisted_columns = {}
for column in subset_of_columns_to_persist:
    persisted_columns[column] = df[column].persist()

This works, but it is very inefficient because df[column] will re-read the entire DataFrame N = len(subset_of_columns_to_persist) times from disk. Is it possible to extract and persist multiple columns individually based on a single read-from-disk deserialization operation?

Note: len(subset_of_columns_to_persist) is >> 1, i.e., simply projecting the DataFrame to df[subset_of_columns_to_persist] is not the solution I'm looking for, because it still has a significant I/O overhead over persisting individual columns.

Body:
You can persist many collections at the same time with the dask.persist function.  This will share intermediates.

columns = [df[column] for column in df.columns]
persisted_columns = dask.persist(*columns)
d = dict(zip(df.columns, persisted_columns))


问:
Need help to create sql query MySQLi PHP
I have two tables
COMPANY: company_id, company_name
REVIEW: review_id, company_id, review_text

I am trying to make search functional on site. I try to display all reviews of specific company. Example, I have search field, I enter there "Microsoft" and then I need all reviews about Microsoft.

I try to do such query, but it is not working

```<code>            $company_name = $_POST["company_name"] ?? '';
            $review_text = $_POST["review_text"] ?? '';
            $searchc = $_POST["searchc"] ?? '';

            if(isset($_POST['show'])){
                $result2 = $mysqli->prepare(
                    "SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (HERE I THINK I NEED EMBED QUERY... BUT NOT SURE..) ?");
                $result2->bind_param("s", $searchc);
                $result2->execute();
                $result2->store_result();
                $row2 = mysqli_fetch_assoc($result2);
            }

            <div class="right">
                <form method="post">
                    <br/>
                    <input name="searchc" type="text" value=""><br/>
                    <input type="submit" value="show" name="show">

                  </form>

                    Text: <?=$row2['review_text']?><br />
            </div>
</code>```

答:
You will need a nested query like this:</p>

```<code>$result2 = $mysqli->prepare("SELECT review_text FROM review WHERE company_id
IN (SELECT company_id from company where company_name=?");
$result2 = bind_param("s", $searchc);
$result2->execute();
</code>```

Body:
I have two tables
COMPANY: company_id, company_name
REVIEW: review_id, company_id, review_text

I am trying to make search functional on site. I try to display all reviews of specific company. Example, I have search field, I enter there "Microsoft" and then I need all reviews about Microsoft.

I try to do such query, but it is not working

            $company_name = $_POST["company_name"] ?? '';
            $review_text = $_POST["review_text"] ?? '';
            $searchc = $_POST["searchc"] ?? '';

            if(isset($_POST['show'])){
                $result2 = $mysqli->prepare(
                    "SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (HERE I THINK I NEED EMBED QUERY... BUT NOT SURE..) ?");
                $result2->bind_param("s", $searchc);
                $result2->execute();
                $result2->store_result();
                $row2 = mysqli_fetch_assoc($result2);
            }

                <form method="post">

                    <input name="searchc" type="text" value="">

                    <input type="submit" value="show" name="show">

                  </form>

                    Text: <?=$row2['review_text']?>

Body:
You will need a nested query like this:

$result2 = $mysqli->prepare("SELECT review_text FROM review WHERE company_id
IN (SELECT company_id from company where company_name=?");
$result2 = bind_param("s", $searchc);
$result2->execute();


问:
Yii2: Kartik FileInput Widget set id to catch events
I try to set the id for the Kartik FileInput Widget but it seems like it won't set it.. because I'm unable to catch the fileuploaded events after an successfull upload.

view.php

```<code>echo $form->field($ebook, 'imageFile')->widget(FileInput::classname(), [
    'id'            => 'imageFile',
    'options'       => ['accept' => 'pdf/*'],
    'pluginOptions' => [
        'allowedFileExtensions' => ['pdf'],
        'showPreview'           => false,
        'showUpload'            => true,
        'uploadAsync'           => true,
        'uploadUrl'             => Url::to(['site/upload']),
    ]
]);
</code>```

catchevent.js

```<code>$('#imageFile').on('fileuploaded', function(event, data, previewId, index) {
    var form = data.form, files = data.files, extra = data.extra,
        response = data.response, reader = data.reader;
    console.log('File uploaded triggered');
});
</code>```

答:
move the id inside the option list:

```<code>echo $form->field($ebook, 'imageFile')->widget(FileInput::classname(), [
    'options'       => ['accept' => 'pdf/*', 'id' => 'imageFile',],
    'pluginOptions' => [
        // ...
    ]
]);
</code>```

you can find it in the docs

Body:
I try to set the id for the Kartik FileInput Widget but it seems like it won't set it.. because I'm unable to catch the fileuploaded events after an successfull upload.

view.php

echo $form->field($ebook, 'imageFile')->widget(FileInput::classname(), [
    'id'            => 'imageFile',
    'options'       => ['accept' => 'pdf/*'],
    'pluginOptions' => [
        'allowedFileExtensions' => ['pdf'],
        'showPreview'           => false,
        'showUpload'            => true,
        'uploadAsync'           => true,
        'uploadUrl'             => Url::to(['site/upload']),
    ]
]);

catchevent.js

$('#imageFile').on('fileuploaded', function(event, data, previewId, index) {
    var form = data.form, files = data.files, extra = data.extra,
        response = data.response, reader = data.reader;
    console.log('File uploaded triggered');
});

Body:
move the id inside the option list:

echo $form->field($ebook, 'imageFile')->widget(FileInput::classname(), [
    'options'       => ['accept' => 'pdf/*', 'id' => 'imageFile',],
    'pluginOptions' => [
        // ...
    ]
]);

you can find it in the docs


问:
How to figure out who owns a worker thread that is still running when my app exits?
Not long after upgrading to VS2010, my application won't shut down cleanly.  If I close the app and then hit pause in the IDE, I see this:

The problem is, there's no context.  The call stack just says [External code], which isn't too helpful.

Here's what I've done so far to try to narrow down the problem:

deleted all extraneous plugins to minimize the number of worker threads launched

set breakpoints in my code anywhere I create worker threads (and delegates + BeginInvoke, since I think they are labeled "Worker Thread" in the debugger anyway).  None were hit.

set IsBackground = true for all threads

While I could do the next brute force step, which is to roll my code back to a point where this didn't happen and then look over all of the change logs, this isn't terribly efficient.  Can anyone recommend a better way to figure this out, given the notable lack of information presented by the debugger?

The only other things I can think of include:

read up on WinDbg and try to use it to stop anytime a thread is started.  At least, I thought that was possible...  :)

comment out huge blocks of code until the app closes properly, then start uncommenting until it doesn't.

UPDATE

Perhaps this information will be of use.  I decided to use WinDbg and attach to my application.  I then closed it, and switched to thread 0 and dumped the stack contents.  Here's what I have:

```<code>ThreadCount:      6
UnstartedThread:  0
BackgroundThread: 1
PendingThread:    0
DeadThread:       4
Hosted Runtime:   no
                                   PreEmptive   GC Alloc                Lock
       ID  OSID ThreadOBJ    State GC           Context       Domain   Count APT Exception
   0    1  1c70 005a65c8      6020 Enabled  02dac6e0:02dad7f8 005a03c0     0 STA
   2    2  1b20 005b1980      b220 Enabled  00000000:00000000 005a03c0     0 MTA (Finalizer)
XXXX    3       08504048     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    4       08504540     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    5       08516a90     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    6       08517260     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
0:008> ~0s
eax=c0674960 ebx=00000000 ecx=00000000 edx=00000000 esi=0040f320 edi=005a65c8
eip=76c37e47 esp=0040f23c ebp=0040f258 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
USER32!NtUserGetMessage+0x15:
76c37e47 83c404          add     esp,4
0:000> !clrstack
OS Thread Id: 0x1c70 (0)
Child SP IP       Call Site
0040f274 76c37e47 [InlinedCallFrame: 0040f274]
0040f270 6baa8976 DomainBoundILStubClass.IL_STUB_PInvoke(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\WindowsBase\d17606e813f01376bd0def23726ecc62\WindowsBase.ni.dll

0040f274 6ba924c5 [InlinedCallFrame: 0040f274] MS.Win32.UnsafeNativeMethods.IntGetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2c4 6ba924c5 MS.Win32.UnsafeNativeMethods.GetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2dc 6ba8e5f8 System.Windows.Threading.Dispatcher.GetMessage(System.Windows.Interop.MSG ByRef, IntPtr, Int32, Int32)
0040f318 6ba8d579 System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
0040f368 6ba8d2a1 System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
0040f374 6ba7fba0 System.Windows.Threading.Dispatcher.Run()
0040f380 62e6ccbb System.Windows.Application.RunDispatcher(System.Object)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\PresentationFramewo#\7f91eecda3ff7ce478146b6458580c98\PresentationFramework.ni.dll

0040f38c 62e6c8ff System.Windows.Application.RunInternal(System.Windows.Window)
0040f3b0 62e6c682 System.Windows.Application.Run(System.Windows.Window)
0040f3c0 62e6c30b System.Windows.Application.Run()
0040f3cc 001f00bc MyApplication.App.Main() [C:\code\trunk\MyApplication\obj\Debug\GeneratedInternalTypeHelper.g.cs @ 24]
0040f608 66c421db [GCFrame: 0040f608]
</code>```

EDIT -- not sure if this helps, but the main thread's call stack looks like this:

```<code>    [Managed to Native Transition]
>   WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x85 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes
    PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x17 bytes
    PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
    PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
    PresentationFramework.dll!System.Windows.Application.Run() + 0x1b bytes
</code>```

I did a search on it and found some posts related to WPF GUIs hanging, and maybe that'll give me some more clues.

答: If you are creating the worker threads (rather than pool threads), set their Name to something descriptive on creation.</p>

ContentLicense: CC BY-SA 2.5

Body:
Not long after upgrading to VS2010, my application won't shut down cleanly.  If I close the app and then hit pause in the IDE, I see this:

The problem is, there's no context.  The call stack just says [External code], which isn't too helpful.

Here's what I've done so far to try to narrow down the problem:

deleted all extraneous plugins to minimize the number of worker threads launched

set breakpoints in my code anywhere I create worker threads (and delegates + BeginInvoke, since I think they are labeled "Worker Thread" in the debugger anyway).  None were hit.

set IsBackground = true for all threads

While I could do the next brute force step, which is to roll my code back to a point where this didn't happen and then look over all of the change logs, this isn't terribly efficient.  Can anyone recommend a better way to figure this out, given the notable lack of information presented by the debugger?

The only other things I can think of include:

read up on WinDbg and try to use it to stop anytime a thread is started.  At least, I thought that was possible...  :)

comment out huge blocks of code until the app closes properly, then start uncommenting until it doesn't.

UPDATE

Perhaps this information will be of use.  I decided to use WinDbg and attach to my application.  I then closed it, and switched to thread 0 and dumped the stack contents.  Here's what I have:

ThreadCount:      6
UnstartedThread:  0
BackgroundThread: 1
PendingThread:    0
DeadThread:       4
Hosted Runtime:   no
                                   PreEmptive   GC Alloc                Lock
       ID  OSID ThreadOBJ    State GC           Context       Domain   Count APT Exception
   0    1  1c70 005a65c8      6020 Enabled  02dac6e0:02dad7f8 005a03c0     0 STA
   2    2  1b20 005b1980      b220 Enabled  00000000:00000000 005a03c0     0 MTA (Finalizer)
XXXX    3       08504048     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    4       08504540     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    5       08516a90     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    6       08517260     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
0:008> ~0s
eax=c0674960 ebx=00000000 ecx=00000000 edx=00000000 esi=0040f320 edi=005a65c8
eip=76c37e47 esp=0040f23c ebp=0040f258 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
USER32!NtUserGetMessage+0x15:
76c37e47 83c404          add     esp,4
0:000> !clrstack
OS Thread Id: 0x1c70 (0)
Child SP IP       Call Site
0040f274 76c37e47 [InlinedCallFrame: 0040f274]
0040f270 6baa8976 DomainBoundILStubClass.IL_STUB_PInvoke(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\WindowsBase\d17606e813f01376bd0def23726ecc62\WindowsBase.ni.dll

0040f274 6ba924c5 [InlinedCallFrame: 0040f274] MS.Win32.UnsafeNativeMethods.IntGetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2c4 6ba924c5 MS.Win32.UnsafeNativeMethods.GetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2dc 6ba8e5f8 System.Windows.Threading.Dispatcher.GetMessage(System.Windows.Interop.MSG ByRef, IntPtr, Int32, Int32)
0040f318 6ba8d579 System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
0040f368 6ba8d2a1 System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
0040f374 6ba7fba0 System.Windows.Threading.Dispatcher.Run()
0040f380 62e6ccbb System.Windows.Application.RunDispatcher(System.Object)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\PresentationFramewo#\7f91eecda3ff7ce478146b6458580c98\PresentationFramework.ni.dll

0040f38c 62e6c8ff System.Windows.Application.RunInternal(System.Windows.Window)
0040f3b0 62e6c682 System.Windows.Application.Run(System.Windows.Window)
0040f3c0 62e6c30b System.Windows.Application.Run()
0040f3cc 001f00bc MyApplication.App.Main() [C:\code\trunk\MyApplication\obj\Debug\GeneratedInternalTypeHelper.g.cs @ 24]
0040f608 66c421db [GCFrame: 0040f608]

EDIT -- not sure if this helps, but the main thread's call stack looks like this:

    [Managed to Native Transition]
>   WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x85 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes
    PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x17 bytes
    PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
    PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
    PresentationFramework.dll!System.Windows.Application.Run() + 0x1b bytes

I did a search on it and found some posts related to WPF GUIs hanging, and maybe that'll give me some more clues.


问:
AWS Console > switch to user
How would you switch to a user in the AWS console?

I've set up an IAM policy for a user and I'd like to test whether they're working or not.

I've tried switching roles http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html

using the account id from the User ARN (e.g.

```<code>arn:aws:iam::<account id>:user/<username>
</code>```

in

```<code>https://signin.aws.amazon.com/switchrole
</code>```

using:

```<code>Account: <account id>
Role: test_user
Display Name: Test User
</code>```

then clicking Switch Role but I get:

```<code>Could not switch roles using the provided information. Please check your settings and try again. If you continue to have problems, contact your administrator.
</code>```

Note: I am an Admin with full access.

答: The best way to do this is fully log out of the AWS console. Or you can use a different browser so you can be logged into both at the same time.</p>

Title: AWS Console > switch to user

Body:
How would you switch to a user in the AWS console?

I've set up an IAM policy for a user and I'd like to test whether they're working or not.

I've tried switching roles http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html

using the account id from the User ARN (e.g.

arn:aws:iam::<account id>:user/<username>

in

https://signin.aws.amazon.com/switchrole

using:

Account: <account id>
Role: test_user
Display Name: Test User

then clicking Switch Role but I get:

Could not switch roles using the provided information. Please check your settings and try again. If you continue to have problems, contact your administrator.

Note: I am an Admin with full access.


问:
Dynamically append DOM element and if already added then no need to append
I am trying to dynamically add a div to parent div when a button is clicked.But once it is created another same child div should not be created again when the button is clicked. So this is what I tried to do

```<code>$("#b1").click(function(){
        $("#d1").has("#d2").remove($(this));
        $("#d1").append($("<div>",{id:"d2",text:"Dynamically added Second DIV"}));
    });
</code>```

It is working but I am getting "TypeError: expr.replace is not a function" in the console...Please suggest.
Thank you...

答:
It seems like you want to remove your button #b1 when you've clicked it once. Why not just remove it and add the element when the button is clicked? Like this:

$("#b1").click(function(){
    $(this).remove();
    $("#d1").append($("
",{id:"d2",text:"Dynamically added Second DIV"}));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#d1{
  background-color: gray;
}</code>```

<button id="b1">Button</button>```
</div>
</div>
</p>

<p>If you really want to see if an element with id <code>d2</code> exists within <code>d1</code> you can do that with the following if-statement:</p>

```if ($('#d1').find('#d2').length) {
   // Element found
}
```

<p>With that method, you can do another variant where the button isn't removed but won't work after one element is created:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("#b1").click(function(){
  if (!$('#d1').find('#d2').length) {
    $("#d1").append($("<div>",{id:"d2",text:"Dynamically added Second DIV"}));
  }
});</code>```

#d1{
  background-color: gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="d1"></div>
<button id="b1">Button</button></code>```

Body:
I am trying to dynamically add a div to parent div when a button is clicked.But once it is created another same child div should not be created again when the button is clicked. So this is what I tried to do

$("#b1").click(function(){
        $("#d1").has("#d2").remove($(this));
        $("#d1").append($("
",{id:"d2",text:"Dynamically added Second DIV"}));
    });

It is working but I am getting "TypeError: expr.replace is not a function" in the console...Please suggest.
Thank you...

Body:
It seems like you want to remove your button #b1 when you've clicked it once. Why not just remove it and add the element when the button is clicked? Like this:

$("#b1").click(function(){
    $(this).remove();
    $("#d1").append($("<div>",{id:"d2",text:"Dynamically added Second DIV"}));
});

#d1{
  background-color: gray;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="d1"></div>
<button id="b1">Button</button>

If you really want to see if an element with id d2 exists within d1 you can do that with the following if-statement:

if ($('#d1').find('#d2').length) {
   // Element found
}

With that method, you can do another variant where the button isn't removed but won't work after one element is created:

$("#b1").click(function(){
  if (!$('#d1').find('#d2').length) {
    $("#d1").append($("<div>",{id:"d2",text:"Dynamically added Second DIV"}));
  }
});

#d1{
  background-color: gray;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="d1"></div>
<button id="b1">Button</button>


问:
When do you use map vs flatMap in RxJava?
When do you use map vs flatMap in RxJava?

Say, for example, we want to map Files containing JSON into Strings that contain the JSON--

Using map, we have to deal with the Exception somehow. But how?:

```<code>Observable.from(jsonFile).map(new Func1<File, String>() {
    @Override public String call(File file) {
        try {
            return new Gson().toJson(new FileReader(file), Object.class);
        } catch (FileNotFoundException e) {
            // So Exception. What to do ?
        }
        return null; // Not good :(
    }
});
</code>```

Using flatMap, it's much more verbose, but we can forward the problem down the chain of Observables and handle the error if we choose somewhere else and even retry:

```<code>Observable.from(jsonFile).flatMap(new Func1<File, Observable<String>>() {
    @Override public Observable<String> call(final File file) {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override public void call(Subscriber<? super String> subscriber) {
                try {
                    String json = new Gson().toJson(new FileReader(file), Object.class);

                    subscriber.onNext(json);
                    subscriber.onCompleted();
                } catch (FileNotFoundException e) {
                    subscriber.onError(e);
                }
            }
        });
    }
});
</code>```

I like the simplicity of the map, but the error handling of flatmap (not the verbosity). I haven't seen any best practices on this floating around and I'm curious how this is being used in practice.

答:
Here is a simple thumb-rule that I use help me decide as when to use flatMap() over map() in Rx's Observable.

Once you come to a decision that you're going to employ a map transformation, you'd write your transformation code to return some Object right?

If what you're returning as end result of your transformation is:

a non-observable object then you'd use just map(). And map() wraps that object in an Observable and emits it.

an Observable object, then you'd use flatMap(). And flatMap() unwraps the Observable, picks the returned object, wraps it with its own Observable and emits it.

Say for example we've a method titleCase(String inputParam) that returns Titled Cased String object of the input param. The return type of this method can be String or Observable<String>.

If the return type of titleCase(..) were to be mere String, then you'd use map(s -> titleCase(s))

If the return type of titleCase(..) were to be Observable<String>, then you'd use flatMap(s -> titleCase(s))

Hope that clarifies.

Body:
When do you use map vs flatMap in RxJava?

Say, for example, we want to map Files containing JSON into Strings that contain the JSON--

Using map, we have to deal with the Exception somehow. But how?:

Observable.from(jsonFile).map(new Func1<File, String>() {
    @Override public String call(File file) {
        try {
            return new Gson().toJson(new FileReader(file), Object.class);
        } catch (FileNotFoundException e) {
            // So Exception. What to do ?
        }
        return null; // Not good :(
    }
});

Using flatMap, it's much more verbose, but we can forward the problem down the chain of Observables and handle the error if we choose somewhere else and even retry:

Observable.from(jsonFile).flatMap(new Func1<File, Observable<String>>() {
    @Override public Observable<String> call(final File file) {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override public void call(Subscriber<? super String> subscriber) {
                try {
                    String json = new Gson().toJson(new FileReader(file), Object.class);

                    subscriber.onNext(json);
                    subscriber.onCompleted();
                } catch (FileNotFoundException e) {
                    subscriber.onError(e);
                }
            }
        });
    }
});

I like the simplicity of the map, but the error handling of flatmap (not the verbosity). I haven't seen any best practices on this floating around and I'm curious how this is being used in practice.


问:
Django rest api: how to return a JsonArray of jsonObjects as a model field?
I have two django models as shown

model 1

```<code>class Big(models.Model):
    name = models.CharField(max_length=50, null=True, blank=True)
</code>```

model2

```<code>class Small(models.Model):
    name = models.CharField(max_length=50, null=True, blank=True)
    address = models.CharField(max_length=200, null=True, blank=True)
    big = models.ForeignKey(Big, related_name='small',null=True,on_delete=models.CASCADE)
</code>```

There can be more than one Small items inside a Big item. The Bigserializer looks like below

```<code>class BigSerializer(serializers.ModelSerializer):

class Meta:
    model = Hotel
    fields = ('name','small')
</code>```

Now on accessing the Big items,i am getting name and small fields. But the small field returns only the id of the Small model. I need the whole details like name and address of Small item inside the small field. How could i achieve it?

答:
You need to define Small serializer class:

```<code>class SmallSerializer(serializers.ModelSerializer):

    class Meta:
        model = Small
        fields = ('name','address')
</code>```

and use this serializer in BigSerializer class:

```<code>class BigSerializer(serializers.ModelSerializer):
    small = SmallSerializer(many=True, read_only=True)

    class Meta:
        model = Hotel
        fields = ('name','small')
</code>```

See details here.

Note that if you need writable nested serialization, you should implement custom create and update methods inside BigSerializer, see section writable nested serialization.

Body:
I have two django models as shown

model 1

class Big(models.Model):
    name = models.CharField(max_length=50, null=True, blank=True)

model2

class Small(models.Model):
    name = models.CharField(max_length=50, null=True, blank=True)
    address = models.CharField(max_length=200, null=True, blank=True)
    big = models.ForeignKey(Big, related_name='small',null=True,on_delete=models.CASCADE)

There can be more than one Small items inside a Big item. The Bigserializer looks like below

class BigSerializer(serializers.ModelSerializer):

class Meta:
    model = Hotel
    fields = ('name','small')

Now on accessing the Big items,i am getting name and small fields. But the small field returns only the id of the Small model. I need the whole details like name and address of Small item inside the small field. How could i achieve it?

Body:
You need to define Small serializer class:

class SmallSerializer(serializers.ModelSerializer):

    class Meta:
        model = Small
        fields = ('name','address')

and use this serializer in BigSerializer class:

class BigSerializer(serializers.ModelSerializer):
    small = SmallSerializer(many=True, read_only=True)

    class Meta:
        model = Hotel
        fields = ('name','small')

See details here.

Note that if you need writable nested serialization, you should implement custom create and update methods inside BigSerializer, see section writable nested serialization.


答:
You can check children.length to find if a child exist

$("#b1").click(function() {
  if ($("#d1").children("#d2").length <= 0) {
    console.log(1)
    $("#d1").append($("
", {
      id: "d2",
      text: "Dynamically added Second DIV"
    }));
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1">Paremt Dom</div>
<button id="b1">Click</button></code>```

Title: Dynamically append DOM element and if already added then no need to append

Body:
You can check children.length to find if a child exist

$("#b1").click(function() {
  if ($("#d1").children("#d2").length <= 0) {
    console.log(1)
    $("#d1").append($("<div>", {
      id: "d2",
      text: "Dynamically added Second DIV"
    }));
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1">Paremt Dom</div>
<button id="b1">Click</button>


问:
How to link to pages without the .html extension?
I would like to link to pages inside my website, e.g:
Not: mywebsite.com/about.html But: mywebsite.com/about/

I've seen various websites doing this but it looks like they also react differently to things:

Apple.com:
apple.com/iphone/ works, apple.com/iphone/index.html works, apple.com/iphone redirects.

Opera.com:
opera.com/mobile/ redirects, opera.com/mobile works, opera.com/mobile.html does not work.

Mozilla.com:
mozilla.org/en-US/ works, mozilla.org/en-US redirects, mozilla.org/en-US/index.html does not work.

Which leads to another question: Are there different methods for this?

Edit:
It seems that Apple uses a folder for every page, e.g. a folder called 'iphone' with an index.html file inside it?
But Opera and Mozilla use something in the .htaccess file?

答:
In the .htaccess file in your sites root folder just add the following line:</p>

```<code># ---- Render pages without urls
Options +MultiViews
</code>```

Body:
In the .htaccess file in your sites root folder just add the following line:

# ---- Render pages without urls
Options +MultiViews


问:
How to make your c# app work as windows service?
How to make your c# app work as windows service? (matereals, todos wanted)</p>

答: From the Visual Studio "New Project window, select Windows Service.  This will set you up with a template which you can use to turn your app into a service.


问:
Instantiating ActiveRecord models without a database connection
I'm currently in the process of replacing a self-made hack-y MVC approach's Model component with php-activerecord. I have a separate page that displays in the event that the database server goes down, and that page used to display a user badge with a guest avatar, name and role. The code is as follows:

```<code>if (Auth::$signed_in)
    echo Auth::$user->getAvatarWrap();
else echo (new \App\Models\User([
    'name' => 'Guest',
    'role' => 'guest',
    'avatar_url' => GUEST_AVATAR
]))->getAvatarWrap();
</code>```

Auth::$signed_in is set to true when a user is logged in, which - in case of a DB outage - is impossible, so the else branch executes with the predefined data.

Pre-ActiveRecord this would simply add the properties to the object and the call to the getAvatarWrap method would execute without any issues. Now, with the model being controlled by ActiveRecord, a set of additional calls take place for whatever reason. This could be because the model has relations defined, but I'm not sure.

ActiveRecord\DatabaseException: PDOException: SQLSTATE[08006] [7] could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432? in /var/www/vendor/php-activerecord/php-activerecord/lib/Connection.php:260
Stack trace:
#0 /var/www/vendor/php-activerecord/php-activerecord/lib/Connection.php(260): PDO->__construct('pgsql:host=loca...', '<username>', '<password>', Array)
#1 /var/www/vendor/php-activerecord/php-activerecord/lib/Connection.php(122): ActiveRecord\Connection->__construct(Object(stdClass))
#2 /var/www/vendor/php-activerecord/php-activerecord/lib/ConnectionManager.php(33): ActiveRecord\Connection::instance('pgsql://databas...')
#3 /var/www/vendor/php-activerecord/php-activerecord/lib/Table.php(114): ActiveRecord\ConnectionManager::get_connection('pgsql')
#4 /var/www/vendor/php-activerecord/php-activerecord/lib/Table.php(90): ActiveRecord\Table->reestablish_connection(false)
#5 /var/www/vendor/php-activerecord/php-activerecord/lib/Table.php(71): ActiveRecord\Table->__construct('App\\Models\\User')
#6 /var/www/vendor/php-activerecord/php-activerecord/lib/Model.php(765): ActiveRecord\Table::load('App\\Models\\User')
#7 /var/www/vendor/php-activerecord/php-activerecord/lib/Model.php(271): ActiveRecord\Model::table()
#8 /var/www/includes/views/_sidebar.php(20): ActiveRecord\Model->__construct(Array)
#9 /var/www/includes/views/_layout.php(148): include('/var/www...')
#10 /var/www/includes/views/fatalerr.php(46): require('/var/www...')
#11 /var/www/includes/init.php(32): require('/var/www...')
#12 /var/www/includes/do.php(3): require('/var/www...')
#13 /var/www/public/index.php(1): require('/var/www...')
#14 {main} in /var/www/vendor/php-activerecord/php-activerecord/lib/Connection.php on line 262
```

How do I tell ActiveRecord to stop looking for a connection when I know for a fact that it won't find one, and that it should be content with the data I'm feeding it? Do I have to wave goodbye to using any of my models during an outage?

答:
Thanks to a comment I found out about SQLite memory databases which put me on the path to success. Given that the pull request to enable support for this kind of database has been collecting dust for almost a year I decided to take matters into my own hands.

If you're reading this later on, be sure to check whether said PR was merged yet, and leave a comment if it has so that I can update this answer.

First, I forked the original repository repository on GitHub. I'm intentionally not linking my fork, because it can get outdated or deleted eventually, so I suggest you make a fork for yourself. Then, I used a combination of this answer and this answer to get the magic branch into my fork from the fork of the PR's submitter. You can get the <url> by pressing the "Clone or download" button on the forked repository's home page.

$ git clone <url>
$ git remote add target https://github.com/claytonrcarter/php-activerecord.git
$ git fetch --all
$ git checkout master
$ git merge --squash target/sqlite-memory-support
$ git commit -m "Add support for SQLite :memory: databases"
$ git push
```

<p>Now that my fork had the latest changes I took to my project's <code>composer.json</code> and changed the version of <code>php-activerecord/php-activerecord</code> in my <code>require</code> block to <code>"dev-master"</code>, then added a <code>repositories</code> block with my fork in it. Again, replace <code><url></code> with the fork's clone URL.</p>

<p></p>

```{
    // ...
    "require": {
        // ...
        "php-activerecord/php-activerecord": "dev-master",
        // ...
    },
    "repositories": [
        {
            "type": "vcs",
            "url":  "<url>"
        }
    ]
}
```

<p>But wait, the fun doesn't end there! Now that we have support for the memory SQLite DB adapter, we actually have to define it. So amend to your initialization config:</p>

```ActiveRecord\Config::initialize(function ($cfg){
    $cfg->set_connections([
        'pgsql' => 'pgsql://'.DB_USER.':'.DB_PASS.'@'.DB_HOST.'/database?charset=utf8',

        // Add this line below. 'failsafe' can be changed to something else, of course
        'failsafe' => 'sqlite://:memory:',
    ], 'pgsql');
});
```

<p>Turns out it's pretty difficult to hot swap the default connection, so I did the next best thing, and made a child class that had its <code>$connection</code> set to the <code>failsafe</code> defined earlier. Note that the required fields have to be manually defined, because the lib has no means of knowing what fields to allow you to use from the empty database. Interestingly, the <code>$has_many</code> and similar relations that were present on the main class had no negative effect on the subclass' behavior, so I could keep it relatively short.</p>

```namespace App\Models;

/** @inheritdoc */
class FailsafeUser extends User {
    static $connection = 'failsafe';

    public $name, $role, $avatar_url;
}
```

<p>Finally, I had to change the call to use the newly defined class:</p>

```if (Auth::$signed_in)
    echo Auth::$user->getAvatarWrap();
else echo (new \App\Models\FailsafeUser([
    'name' => 'Guest',
    'role' => 'guest',
    'avatar_url' => GUEST_AVATAR
]))->getAvatarWrap();
```

Low and behold, the script no longer breaks and I can finally get on with the ActiveRecord-ification of my codebase. If you'd like go through this torture yourself and have more than one model that you want to have an "offline" variant of then you might want to make an abstract class of some sort that automatically sets the properties you passed in the constructor along with pre-setting the $connection, making child instances ever so slightly less verbose.

Body:
I'm currently in the process of replacing a self-made hack-y MVC approach's Model component with php-activerecord. I have a separate page that displays in the event that the database server goes down, and that page used to display a user badge with a guest avatar, name and role. The code is as follows:

if (Auth::$signed_in)
    echo Auth::$user->getAvatarWrap();
else echo (new \App\Models\User([
    'name' => 'Guest',
    'role' => 'guest',
    'avatar_url' => GUEST_AVATAR
]))->getAvatarWrap();

Auth::$signed_in is set to true when a user is logged in, which - in case of a DB outage - is impossible, so the else branch executes with the predefined data.

Pre-ActiveRecord this would simply add the properties to the object and the call to the getAvatarWrap method would execute without any issues. Now, with the model being controlled by ActiveRecord, a set of additional calls take place for whatever reason. This could be because the model has relations defined, but I'm not sure.

ActiveRecord\DatabaseException: PDOException: SQLSTATE[08006] [7] could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432? in /var/www/vendor/php-activerecord/php-activerecord/lib/Connection.php:260
Stack trace:
#0 /var/www/vendor/php-activerecord/php-activerecord/lib/Connection.php(260): PDO->__construct('pgsql:host=loca...', '<username>', '<password>', Array)
#1 /var/www/vendor/php-activerecord/php-activerecord/lib/Connection.php(122): ActiveRecord\Connection->__construct(Object(stdClass))
#2 /var/www/vendor/php-activerecord/php-activerecord/lib/ConnectionManager.php(33): ActiveRecord\Connection::instance('pgsql://databas...')
#3 /var/www/vendor/php-activerecord/php-activerecord/lib/Table.php(114): ActiveRecord\ConnectionManager::get_connection('pgsql')
#4 /var/www/vendor/php-activerecord/php-activerecord/lib/Table.php(90): ActiveRecord\Table->reestablish_connection(false)
#5 /var/www/vendor/php-activerecord/php-activerecord/lib/Table.php(71): ActiveRecord\Table->__construct('App\\Models\\User')
#6 /var/www/vendor/php-activerecord/php-activerecord/lib/Model.php(765): ActiveRecord\Table::load('App\\Models\\User')
#7 /var/www/vendor/php-activerecord/php-activerecord/lib/Model.php(271): ActiveRecord\Model::table()
#8 /var/www/includes/views/_sidebar.php(20): ActiveRecord\Model->__construct(Array)
#9 /var/www/includes/views/_layout.php(148): include('/var/www...')
#10 /var/www/includes/views/fatalerr.php(46): require('/var/www...')
#11 /var/www/includes/init.php(32): require('/var/www...')
#12 /var/www/includes/do.php(3): require('/var/www...')
#13 /var/www/public/index.php(1): require('/var/www...')
#14 {main} in /var/www/vendor/php-activerecord/php-activerecord/lib/Connection.php on line 262

How do I tell ActiveRecord to stop looking for a connection when I know for a fact that it won't find one, and that it should be content with the data I'm feeding it? Do I have to wave goodbye to using any of my models during an outage?

Body:
Thanks to a comment I found out about SQLite memory databases which put me on the path to success. Given that the pull request to enable support for this kind of database has been collecting dust for almost a year I decided to take matters into my own hands.

If you're reading this later on, be sure to check whether said PR was merged yet, and leave a comment if it has so that I can update this answer.

First, I forked the original repository repository on GitHub. I'm intentionally not linking my fork, because it can get outdated or deleted eventually, so I suggest you make a fork for yourself. Then, I used a combination of this answer and this answer to get the magic branch into my fork from the fork of the PR's submitter. You can get the <url> by pressing the "Clone or download" button on the forked repository's home page.

$ git clone <url>
$ git remote add target https://github.com/claytonrcarter/php-activerecord.git
$ git fetch --all
$ git checkout master
$ git merge --squash target/sqlite-memory-support
$ git commit -m "Add support for SQLite :memory: databases"
$ git push

Now that my fork had the latest changes I took to my project's composer.json and changed the version of php-activerecord/php-activerecord in my require block to "dev-master", then added a repositories block with my fork in it. Again, replace <url> with the fork's clone URL.

{
    // ...
    "require": {
        // ...
        "php-activerecord/php-activerecord": "dev-master",
        // ...
    },
    "repositories": [
        {
            "type": "vcs",
            "url":  "<url>"
        }
    ]
}

But wait, the fun doesn't end there! Now that we have support for the memory SQLite DB adapter, we actually have to define it. So amend to your initialization config:

ActiveRecord\Config::initialize(function ($cfg){
    $cfg->set_connections([
        'pgsql' => 'pgsql://'.DB_USER.':'.DB_PASS.'@'.DB_HOST.'/database?charset=utf8',

        // Add this line below. 'failsafe' can be changed to something else, of course
        'failsafe' => 'sqlite://:memory:',
    ], 'pgsql');
});

Turns out it's pretty difficult to hot swap the default connection, so I did the next best thing, and made a child class that had its $connection set to the failsafe defined earlier. Note that the required fields have to be manually defined, because the lib has no means of knowing what fields to allow you to use from the empty database. Interestingly, the $has_many and similar relations that were present on the main class had no negative effect on the subclass' behavior, so I could keep it relatively short.

namespace App\Models;

/** @inheritdoc */
class FailsafeUser extends User {
    static $connection = 'failsafe';

    public $name, $role, $avatar_url;
}

Finally, I had to change the call to use the newly defined class:

if (Auth::$signed_in)
    echo Auth::$user->getAvatarWrap();
else echo (new \App\Models\FailsafeUser([
    'name' => 'Guest',
    'role' => 'guest',
    'avatar_url' => GUEST_AVATAR
]))->getAvatarWrap();

Low and behold, the script no longer breaks and I can finally get on with the ActiveRecord-ification of my codebase. If you'd like go through this torture yourself and have more than one model that you want to have an "offline" variant of then you might want to make an abstract class of some sort that automatically sets the properties you passed in the constructor along with pre-setting the $connection, making child instances ever so slightly less verbose.


问:
How to sort the following array of objects and strings?
I have the following:

```<code>myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]
</code>```

What is the best way to sort the list such that strings are in the front, and objects come after?

```<code>["Abigail", "Kelsey", {'name':'Adam'}, {'name': 'Jennifer'}, {'name': 'Jorden'}]
</code>```

答:
```<code>// Assign to a variable
myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]
// Sort them
myitems = myitems.sort((x, y) => typeof(x) === 'string' ? -1 : 1)
</code>```

Read more about the sort method and see how it works.

Basically, the sorting function takes two arguments x and y to sort. If the x is of type string, -1 is returned so that x has higher priority than y, otherwise +1 is returned to put y before x

Body:
I have the following:

myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]

What is the best way to sort the list such that strings are in the front, and objects come after?

["Abigail", "Kelsey", {'name':'Adam'}, {'name': 'Jennifer'}, {'name': 'Jorden'}]

Body:
// Assign to a variable
myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]
// Sort them
myitems = myitems.sort((x, y) => typeof(x) === 'string' ? -1 : 1)

Read more about the sort method and see how it works.

Basically, the sorting function takes two arguments x and y to sort. If the x is of type string, -1 is returned so that x has higher priority than y, otherwise +1 is returned to put y before x


问:
Creating a promise chain in a for loop
I would expect the code below to print one number on the console, then wait a second and then print another number. Instead, it prints all 10 numbers immediately and then waits ten seconds. What is the correct way to create a promise chain that behaves as described?</p>

```<code>function getProm(v) {
    return new Promise(resolve => {
        console.log(v);
        resolve();
    })
}

function Wait() {
    return new Promise(r => setTimeout(r, 1000))
}

function createChain() {
    let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    let chain = Promise.resolve();
    for (let i of a) {
        chain.then(()=>getProm(i))
            .then(Wait)

    }
    return chain;
}

createChain();
</code>```

答:
You have to assign the return value of .then back to chain:

```<code>chain = chain.then(()=>getProm(i))
         .then(Wait)
</code>```

Now you will basically be doing

```<code>chain
  .then(()=>getProm(1))
  .then(Wait)
  .then(()=>getProm(2))
  .then(Wait)
  .then(()=>getProm(3))
  .then(Wait)
  // ...
</code>```

instead of

```<code>chain
  .then(()=>getProm(1))
  .then(Wait)

chain
  .then(()=>getProm(2))
  .then(Wait)

chain
  .then(()=>getProm(3))
  .then(Wait)
// ...
</code>```

You can see that the first one is actually a chain, while the second one is parallel.

Title: Creating a promise chain in a for loop

Body:
I would expect the code below to print one number on the console, then wait a second and then print another number. Instead, it prints all 10 numbers immediately and then waits ten seconds. What is the correct way to create a promise chain that behaves as described?

function getProm(v) {
    return new Promise(resolve => {
        console.log(v);
        resolve();
    })
}

function Wait() {
    return new Promise(r => setTimeout(r, 1000))
}

function createChain() {
    let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    let chain = Promise.resolve();
    for (let i of a) {
        chain.then(()=>getProm(i))
            .then(Wait)

    }
    return chain;
}

createChain();

Body:
You have to assign the return value of .then back to chain:

chain = chain.then(()=>getProm(i))
         .then(Wait)

Now you will basically be doing

chain
  .then(()=>getProm(1))
  .then(Wait)
  .then(()=>getProm(2))
  .then(Wait)
  .then(()=>getProm(3))
  .then(Wait)
  // ...

instead of

chain
  .then(()=>getProm(1))
  .then(Wait)

chain
  .then(()=>getProm(2))
  .then(Wait)

chain
  .then(()=>getProm(3))
  .then(Wait)
// ...

You can see that the first one is actually a chain, while the second one is parallel.


问:
Does ApplicationRessource.properties file can be in another locale than EN
Is the Struts2 file applicationRessource.properties can be in another locale than English. I know I can have some other files like ApplicationRessource_fr.properties or ApplicationRessource_es.properties.

My main question concerns only the ApplicationRessource.properties. My default language will be French and I don't want to have a file like ApplicationRessource_fr.properties. Is there a way to do that?

答: Here was the solution we found. We use 3 files. ApplicationRessource.properties who are in french, ApplicationRessource_fr.properties who is empty and ApplicationRessource_en.properties who contains the english translations</p>


问:
How to check if the JSON is correctly receives
I'm sending a JSON with the POST AJAX method to a PHP file and I would like to know how can I check if the JSON is correctly sent before using the json_decode function ?

The isset($_POST['myJSON']) and !empty($_POST['myJSON']) functions are they correct for this case or I cannot use them because my variable is a JSON?

答:
You can check by using JavaScript function JSON.parse($val) before sending to php file

If it shows error then your json is not correct


问:
jQuery inputmask datetime not work
I'm trying to apply the datetime mask on an input but this didn't work
the jQuery plugin I used is inputmask
I did my code on codepen site and include all needed js libraries but don't have any idea why this not work</p>

```<code><input id="datetime" />

$('#datetime').inputmask({
    mask: "2/1/y h:s t\\m",
    placeholder: "mm/dd/yyyy hh:mm xm",
    alias: "datetime",
    hourFormat: "12"
});
</code>```

答:
I'm not familiar with Inputmask, but fiddling around with your Pen... this seems to work for me:

```<code><input id="datetime" />

$('#datetime').inputmask({
    placeholder: "mm/dd/yyyy hh:mm xm",
    alias: "mm/dd/yyyy hh:mm xm",
    hourFormat: "12"
});
</code>```

Title: jQuery inputmask datetime not work

Body:
I'm trying to apply the datetime mask on an input but this didn't work
the jQuery plugin I used is inputmask
I did my code on codepen site and include all needed js libraries but don't have any idea why this not work

<input id="datetime" />

$('#datetime').inputmask({
    mask: "2/1/y h:s t\\m",
    placeholder: "mm/dd/yyyy hh:mm xm",
    alias: "datetime",
    hourFormat: "12"
});

Body:
I'm not familiar with Inputmask, but fiddling around with your Pen... this seems to work for me:

<input id="datetime" />

$('#datetime').inputmask({
    placeholder: "mm/dd/yyyy hh:mm xm",
    alias: "mm/dd/yyyy hh:mm xm",
    hourFormat: "12"
});


问:
Change every single element in Numpy object
I have a Numpy object with random N*M elements, and I also have two numbers A and B.

Now I want to access every element in this N*M array and make a change, i.e., if the element > 0, replace this element to A (i.e., element <- A), and if this element < 0, replace this element to B (i.e., element <- B).

I know there is a naive way to implement this method, that is accessing every single element using for loop, but it is very slow.

Can we use more fancy code to implement this ?

Body:
IIUC:

narr = np.random.randint(-100,100,(10,5))
array([[ 70, -20,  96,  73, -94],
       [ 42,  35, -55,  56,  54],
       [ 97, -16,  24,  32,  78],
       [ 49,  49, -11, -82,  82],
       [-10,  59, -42, -68, -70],
       [ 95,  23,  22,  58, -38],
       [ -2, -64,  27, -33, -95],
       [ 98,  42,   8, -83,  85],
       [ 23,  51, -99, -82,  -7],
       [-28, -11, -44,  95,  93]])
A = 1000
B = -999

Use np.where:

np.where(narr > 0, A, np.where(narr < 0, B , narr))

Output:

array([[1000, -999, 1000, 1000, -999],
       [1000, 1000, -999, 1000, 1000],
       [1000, -999, 1000, 1000, 1000],
       [1000, 1000, -999, -999, 1000],
       [-999, 1000, -999, -999, -999],
       [1000, 1000, 1000, 1000, -999],
       [-999, -999, 1000, -999, -999],
       [1000, 1000, 1000, -999, 1000],
       [1000, 1000, -999, -999, -999],
       [-999, -999, -999, 1000, 1000]])


问:
Array of Objects Won't Clear
I have an array that's a property called .phrases of an object called a Passage.  I have a function that's a property of that same object.  In the function, I have code like this:

```<code>var returnPassage=new Passage();
returnPassage.phrases=[];
console.log(returnPassage.phrases);
</code>```

The console log in Google Chrome shows an empty array on one level, but if I click the drop-down it shows that the array hasn't changed at all.  This is true whether I try to clear the array with .pop() or .splice() or by replacing it with a new Array().  It's also, bizarrely(!!!) true if I do this:

```<code>var returnPassage=new Passage();
returnPassage.phrases=null;
returnPassage.phrases=[];
console.log(returnPassage.phrases);
</code>```

The console log shows the array same as original, not a blank array like i expect.  What could possibly be going on here???

答: Here's what was happening: Chrome was logging the array and showing it in the top line, then my method changed it, then the drop-down shows it the most recent way it has been. So it's not a problem with how the javascript was working, it's a problem with how I was reading Chrome's display. </p>

Title: Array of Objects Won't Clear

Body:
I have an array that's a property called .phrases of an object called a Passage.  I have a function that's a property of that same object.  In the function, I have code like this:

var returnPassage=new Passage();
returnPassage.phrases=[];
console.log(returnPassage.phrases);

The console log in Google Chrome shows an empty array on one level, but if I click the drop-down it shows that the array hasn't changed at all.  This is true whether I try to clear the array with .pop() or .splice() or by replacing it with a new Array().  It's also, bizarrely(!!!) true if I do this:

var returnPassage=new Passage();
returnPassage.phrases=null;
returnPassage.phrases=[];
console.log(returnPassage.phrases);

The console log shows the array same as original, not a blank array like i expect.  What could possibly be going on here???


答:
var myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}];

myitems.sort(function(a, b) {
  if(typeof a === "string") {                                       // if a is a string
     if(typeof b === "string") return a.localeCompare(b);           // and b is a string, then compare the 2 strings a and b
     return -1;                                                     // otherwise (a is a string and b is an object) then make a go above b
  }
  else {                                                            // if a is an object
     if(typeof b === "object") return a.name.localeCompare(b.name); // and b is an object, then compare the 2 objects' names a.name and b.name
     return 1;                                                      // otherwise (a is an object and b is a string) then make a go bellow b
  }
});

console.log(myitems);```

Title: How to sort the following array of objects and strings?


问:
Bootstrap menu fully shows when viewing in mobile.
Many thanks in advance! I am a graphic designer working with a SIMA bootstrapped template. I was unsuccessful at contacting the author of the template. All is kosher except for when you view the site on mobile, the navigation menu is fully displayed. The user has to manually click the nav tab to hide the menu (poor usability). I have searched similar questions and found that I have the correct Meta View tags and my navigation classes and id's seem to be all there. The link to my site is at www.thesunkenweb.com/loteksystems The link to the authors site (which has the same outcome) is https://readytheme.net/item/sima-one-page-multipage-template/
HTML Snippet: </p>

```<code>    <!-- Start Header Section -->
    <header class="main_menu_sec navbar navbar-default navbar-fixed-top">
        <div class="container">
            <div class="row">
                <div class="col-lg-3 col-md-3 col-sm-12">
                    <div class="lft_hd">
                        <a href="index.html"><img src="http://www.thesunkenweb.com/loteksystems/img/LotekSystemsLogo_1.png" alt="Lotek Systems"/></a>
                </div>
            </div>
            <div class="col-lg-9 col-md-9 col-sm-12">
                <div class="rgt_hd">
                    <div class="main_menu">
                        <nav id="nav_menu">
                            <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            </button>
                        <div id="navbar">
                            <ul>
                                <li><a class="page-scroll" href="index.html">Home</a></li>
                                <li><a class="page-scroll" href="#abt_sec">About Us<i class="fa fa-angle-down"></i></a>
                                    <ul>
                                        <li><a class="page-scroll" href="#tm_sec">Meet Andy</a></li>
                                        <li><a class="page-scroll" href="#tstm_sec">Testimonials</a></li>
                                        <li><a class="page-scroll" href="#clt_sec">Experience</a></li>
                                    </ul>
                                </li>
                                <li><a class="page-scroll" href="#pr_sec">Services<i class="fa fa-angle-down"></i></a>
                                    <ul>
                                        <li><a class="page-scroll" href="CustomCloudManagement.html">Custom Managed Cloud Hosting</a></li>
                                        <li><a class="page-scroll" href="CloudMigration.html">Cloud Migration</a></li>
                                        <li><a class="page-scroll" href="ApplicationManagement.html">Application Management</a></li>
                                        <li><a class="page-scroll" href="ComputerRepairs.html">Computer Repairs</a></li>
                                    </ul>
                                </li>
                                <li><a class="page-scroll" href="#ctn_sec">Contact Us</a></li>
                            </ul>
                        </div>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>
<!-- End Header Section -->
</code>```

答:
```<code>@media (max-width:767px){
  #navbar{display:none}
}
</code>```

Add this and all would be kosher ☺

Body:
Many thanks in advance! I am a graphic designer working with a SIMA bootstrapped template. I was unsuccessful at contacting the author of the template. All is kosher except for when you view the site on mobile, the navigation menu is fully displayed. The user has to manually click the nav tab to hide the menu (poor usability). I have searched similar questions and found that I have the correct Meta View tags and my navigation classes and id's seem to be all there. The link to my site is at www.thesunkenweb.com/loteksystems The link to the authors site (which has the same outcome) is https://readytheme.net/item/sima-one-page-multipage-template/
HTML Snippet:

                            <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" class="navbar-toggle collapsed" type="button">

                            </button>

Home

About Us

Meet Andy

Testimonials

Experience

Services

Custom Managed Cloud Hosting

Cloud Migration

Application Management

Computer Repairs

Contact Us

Body:
@media (max-width:767px){
  #navbar{display:none}
}

Add this and all would be kosher ☺


问:
Adding missing records to total count (integer) while grouping by in LINQ
I have an odd situation where I have two collections. One Collection basically contains all ItemID's from my items, where the other one contains only ItemID's who had sales (including the sales data).

Now I've determined that ItemID's from Collections #1 that are not present in Collection #2 has 0 sales. Now the situation where I'm not sure what to do is following:

```<code>var items = new List<Collection1>(); // Contains all ItemIDs where ItemID is a plain string

var itemsTransactions = new List<Collection2>(); // contains item id's that have sales.
</code>```

now in third step I'm grouping by itemsTransationCollection by property called Username like this:

```<code>var groupedByUsername = itemTransactions
    .GroupBy( x => x.Username )
    .Select( item => new MyClass
    {
        TotalItems = item
            .Select( x => x.ItemID )
            .Count(), // sub query should be performed here... ?

        SuccessfulItems = item
            .Select( x => x.ItemID )
            .Count()
    } )
    .ToList();
</code>```

Now the trick is here is that calculation for successful items is already correct because the itemsTransactions collection already contains ONLY item id's that actually have sales...

I'm not sure how to make that comparison that I just mentioned above to include the missing items into the count for this property TotalItems?

So my question here is, is it possible to do a subquery while grouping by in LINQ to add the missing items into the count of property TotalItems?

Can someone help me out?

@DavidLee so the output should look something like this:

```<code>Username  TotalItems(sold + unsold)  Successful items( only ones with sales)
DavidLee    5                                                   2

xyz         4                                                   1
Ronaldo     19                                                  12
</code>```

Successful items shouldn't be larger than TotalListings (it couldn't be mathematically possible)

For @Vlad sample input and desired output:

Items collection

ItemID     Username

1          Seller1
2          Seller2
3          Seller3
4          Seller4
5          Seller5

itemsTransactions collection:

```<code>ItemID     Username     Sales

1          Seller1       2
2          Seller2       4
3          Seller3       5
4          Seller4       6
5          Seller5       7
5          Seller5       4
</code>```

The itemsTransactions collection contains ungrouped data for sales... That's why I'm grouping it in 3rd step...

答:
I would make two subqueries and then join them.  I think the main issue is using the itemsTransaction collection as the starting query, although can be done, IMO it is easier to start with the items collection.  Very verbose and can be shortened but I find it much easier to understand what is going on.

```<code>var itemsByUser = items
    .GroupBy(x => x.Username)
    .Select(x => new
    {
        Username = x.Key,
        Count = x.Count()
    };

var itemsWithSalesByUser = itemTransactions
    .GroupBy(x => x.Username)
    .Select(x => new
    {
        Username = x.Key,
        Count = x.Count()
    };

var joinedDataQuery =
    from i in itemsByUser
    join s in itemsWithSalesByUser
        on i.Username equals s.Username into sj
    from s in sj.DefaultIfEmpty() // left join
    select new MyClass
    {
         Username = i.Username
         TotalItems = i.Count,
         SuccessfulItems = s == null ? 0 : s.Count
    };

// this when it goes to memory so building up the queries
// in separate variables will not have any performance impacts.
var joinedData = joinedDataQuery.ToList();
</code>```

EDIT: changed = to equals

EDIT: account for possible missing successful items.

Body:
I have an odd situation where I have two collections. One Collection basically contains all ItemID's from my items, where the other one contains only ItemID's who had sales (including the sales data).

Now I've determined that ItemID's from Collections #1 that are not present in Collection #2 has 0 sales. Now the situation where I'm not sure what to do is following:

var items = new List<Collection1>(); // Contains all ItemIDs where ItemID is a plain string

var itemsTransactions = new List<Collection2>(); // contains item id's that have sales.

now in third step I'm grouping by itemsTransationCollection by property called Username like this:

var groupedByUsername = itemTransactions
    .GroupBy( x => x.Username )
    .Select( item => new MyClass
    {
        TotalItems = item
            .Select( x => x.ItemID )
            .Count(), // sub query should be performed here... ?

        SuccessfulItems = item
            .Select( x => x.ItemID )
            .Count()
    } )
    .ToList();

Now the trick is here is that calculation for successful items is already correct because the itemsTransactions collection already contains ONLY item id's that actually have sales...

I'm not sure how to make that comparison that I just mentioned above to include the missing items into the count for this property TotalItems?

So my question here is, is it possible to do a subquery while grouping by in LINQ to add the missing items into the count of property TotalItems?

Can someone help me out?

@DavidLee so the output should look something like this:

Username  TotalItems(sold + unsold)  Successful items( only ones with sales)
DavidLee    5                                                   2

xyz         4                                                   1
Ronaldo     19                                                  12

Successful items shouldn't be larger than TotalListings (it couldn't be mathematically possible)

For @Vlad sample input and desired output:

Items collection

ItemID     Username

1          Seller1
2          Seller2
3          Seller3
4          Seller4
5          Seller5

itemsTransactions collection:

ItemID     Username     Sales

1          Seller1       2
2          Seller2       4
3          Seller3       5
4          Seller4       6
5          Seller5       7
5          Seller5       4

The itemsTransactions collection contains ungrouped data for sales... That's why I'm grouping it in 3rd step...

Body:
I would make two subqueries and then join them.  I think the main issue is using the itemsTransaction collection as the starting query, although can be done, IMO it is easier to start with the items collection.  Very verbose and can be shortened but I find it much easier to understand what is going on.

var itemsByUser = items
    .GroupBy(x => x.Username)
    .Select(x => new
    {
        Username = x.Key,
        Count = x.Count()
    };

var itemsWithSalesByUser = itemTransactions
    .GroupBy(x => x.Username)
    .Select(x => new
    {
        Username = x.Key,
        Count = x.Count()
    };

var joinedDataQuery =
    from i in itemsByUser
    join s in itemsWithSalesByUser
        on i.Username equals s.Username into sj
    from s in sj.DefaultIfEmpty() // left join
    select new MyClass
    {
         Username = i.Username
         TotalItems = i.Count,
         SuccessfulItems = s == null ? 0 : s.Count
    };

// this when it goes to memory so building up the queries
// in separate variables will not have any performance impacts.
var joinedData = joinedDataQuery.ToList();

EDIT: changed = to equals

EDIT: account for possible missing successful items.