问:
Incorrect responsive images aspect ratio in bootstrap 4
I want to put a text between two images in bootstrap grid. But images in row sections change their aspect ratio(original is 1:1) and do not resize correctly.</p>

<p>(Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100)   </p>

```<code><div class="container">
  <div class="row">
    <img class="img-fluid rounded-circle col-lg-3 col-md-3 col-sm-12" src="https://image.ibb.co/dEZA5a/true_detective1.jpg" alt="true_detective1">
    <p class="text-center col-lg-6 col-md-6 col-sm-12">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    <img class="img-fluid rounded-circle col-lg-3 col-md-3 col-sm-12" src="https://image.ibb.co/jRigBF/true_detective2.jpg" alt="true_detective2">
  </div>
</div>
</code>```

答:
The grid card columns are meant to be used on images and paragraphs. They're meant to be containers of content.

http://www.codeply.com/go/5sip6gvYFE

```<code><div class="container">
    <div class="row">
        <div class="col-lg-3 col-md-3 col-sm-12 text-center">
            <img class="img-fluid rounded-circle" src="https://image.ibb.co/dEZA5a/true_detective1.jpg" alt="true_detective1">
        </div>
        <div class="col-lg-6 col-md-6 col-sm-12 text-center">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
            dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        </div>
        <div class="col-lg-3 col-md-3 col-sm-12 text-center">
            <img class="img-fluid rounded-circle" src="https://image.ibb.co/jRigBF/true_detective2.jpg" alt="true_detective2">
        </div>
    </div>
</div>
</code>```

Body:
I want to put a text between two images in bootstrap grid. But images in row sections change their aspect ratio(original is 1:1) and do not resize correctly.

(Codepen: https://codepen.io/Oktocorp/pen/yMxpwX?editors=1100)

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

Body:
The grid card columns are meant to be used on images and paragraphs. They're meant to be containers of content.

http://www.codeply.com/go/5sip6gvYFE

<div class="container">
    <div class="row">
        <div class="col-lg-3 col-md-3 col-sm-12 text-center">
            <img class="img-fluid rounded-circle" src="https://image.ibb.co/dEZA5a/true_detective1.jpg" alt="true_detective1">
        </div>
        <div class="col-lg-6 col-md-6 col-sm-12 text-center">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
            dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        </div>
        <div class="col-lg-3 col-md-3 col-sm-12 text-center">
            <img class="img-fluid rounded-circle" src="https://image.ibb.co/jRigBF/true_detective2.jpg" alt="true_detective2">
        </div>
    </div>
</div>


来源: stackexchange

问:
How can I run an external program from C and parse its output?
I've got a utility that outputs a list of files required by a game.  How can I run that utility within a C program and grab its output so I can act on it within the same program?

UPDATE: Good call on the lack of information.  The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux.  Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout).

答:
Well, assuming you're on a command line in a windows environment, you can use pipes or command line redirects.  For instance,

```<code>commandThatOutputs.exe > someFileToStoreResults.txt
</code>```

or

```<code>commandThatOutputs.exe | yourProgramToProcessInput.exe
</code>```

Within your program, you could use the C standard input functions to read the other programs output (scanf, etc.):  http://irc.essex.ac.uk/www.iota-six.co.uk/c/c1_standard_input_and_output.asp .  You could also use the file example and use fscanf.  This should also work in Unix/Linux.

This is a very generic question, you may want to include more details, like what type of output it is (just text, or a binary file?) and how you want to process it.

Edit:  Hooray clarification!

Redirecting STDOUT looks to be troublesome,  I've had to do it in .NET, and it gave me all sorts of headaches.  It looks like the proper C way is to spawn a child process, get a file pointer, and all of a sudden my head hurts.

So heres a hack that uses temporary files.  It's simple, but it should work.  This will work well if speed isn't an issue (hitting the disk is slow), or if it's throw-away.  If you're building an enterprise program, looking into the STDOUT redirection is probably best, using what other people recommended.

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

int main(int argc, char* argv[])
{
    FILE * fptr;                    // file holder
    char c;                         // char buffer

    system("dir >> temp.txt");      // call dir and put it's contents in a temp using redirects.
    fptr = fopen("temp.txt", "r");  // open said file for reading.
                                    // oh, and check for fptr being NULL.
    while(1){
        c = fgetc(fptr);
        if(c!= EOF)
            printf("%c", c);        // do what you need to.
        else
            break;                  // exit when you hit the end of the file.
    }
    fclose(fptr);                   // don't call this is fptr is NULL.
    remove("temp.txt");             // clean up

    getchar();                      // stop so I can see if it worked.
}
</code>```

Make sure to check your file permissions:  right now this will simply throw the file in the same directory as an exe.  You might want to look into using /tmp in nix, or C:\Users\username\Local Settings\Temp in Vista, or C:\Documents and Settings\username\Local Settings\Temp in 2K/XP.  I think the /tmp will work in OSX, but I've never used one.

ContentLicense: CC BY-SA 4.0

Body:
Well, assuming you're on a command line in a windows environment, you can use pipes or command line redirects.  For instance,

commandThatOutputs.exe > someFileToStoreResults.txt

or

commandThatOutputs.exe | yourProgramToProcessInput.exe

Within your program, you could use the C standard input functions to read the other programs output (scanf, etc.):  http://irc.essex.ac.uk/www.iota-six.co.uk/c/c1_standard_input_and_output.asp .  You could also use the file example and use fscanf.  This should also work in Unix/Linux.

This is a very generic question, you may want to include more details, like what type of output it is (just text, or a binary file?) and how you want to process it.

Edit:  Hooray clarification!

Redirecting STDOUT looks to be troublesome,  I've had to do it in .NET, and it gave me all sorts of headaches.  It looks like the proper C way is to spawn a child process, get a file pointer, and all of a sudden my head hurts.

So heres a hack that uses temporary files.  It's simple, but it should work.  This will work well if speed isn't an issue (hitting the disk is slow), or if it's throw-away.  If you're building an enterprise program, looking into the STDOUT redirection is probably best, using what other people recommended.

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
    FILE * fptr;                    // file holder
    char c;                         // char buffer

    system("dir >> temp.txt");      // call dir and put it's contents in a temp using redirects.
    fptr = fopen("temp.txt", "r");  // open said file for reading.
                                    // oh, and check for fptr being NULL.
    while(1){
        c = fgetc(fptr);
        if(c!= EOF)
            printf("%c", c);        // do what you need to.
        else
            break;                  // exit when you hit the end of the file.
    }
    fclose(fptr);                   // don't call this is fptr is NULL.
    remove("temp.txt");             // clean up

    getchar();                      // stop so I can see if it worked.
}

Make sure to check your file permissions:  right now this will simply throw the file in the same directory as an exe.  You might want to look into using /tmp in nix, or C:\Users\username\Local Settings\Temp in Vista, or C:\Documents and Settings\username\Local Settings\Temp in 2K/XP.  I think the /tmp will work in OSX, but I've never used one.

OwnerDisplayName: David Sokol

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: David Sokol


问:
How to create a new variable and use it in std::tie at the same time?
Is there a good way to use std::tie and create a new variable in one go? In other words, if a function returns an std::tuple and we want to ultimately break up the result into individual components, is there a way to do these assignments without defining variables beforehand?

For example, consider the following code:

#include <tuple>

struct Foo {
    Foo(int) {}
};
struct Bar{};

std::tuple <Foo,Bar> example() {
    return std::make_tuple(Foo(1),Bar());
}

int main() {
    auto bar = Bar {};

    // Without std::tie
    {
        auto foo_bar = example();
        auto foo = std::get<0>(std::move(foo_bar));
        bar = std::get<1>(std::move(foo_bar));
    }

    // With std::tie
    #if 0
    {
        // Error: no default constructor
        Foo foo;
        std::tie(foo,bar) = example();
    }
    #endif

}
```

Basically, the function example returns a tuple.  We already have a variable of type Bar that we want to assign into, but we need a new variable of type Foo.  Without std::tie, we don't need to create a dummy instance of Foo, but the code requires us to put everything into a std::tuple first and then divide it.  With std::tie, we have to allocate a dummy Foo first, but we don't have a default constructor to do so.  Really, we're pretending that the constructors for Foo are complicated, so creating a dummy value first is undesirable.  Ultimately, we'd just like to assign into both foo and bar, but want to do this assignment and allocate memory for Foo at the same time.

答:
This feature is called structured bindings in C++17. Very welcome addition!

Sample usage:

```<code>#include <iostream>
#include <tuple>

int main()
{
    auto tuple = std::make_tuple(1, 'a', 2.3);

    // unpack the tuple into individual variables declared at the call site
    auto [ i, c, d ] = tuple;

    std::cout << "i=" << i << " c=" << c << " d=" << d << '\n';

    return 0;
}
</code>```

Tested in GCC 7.2 with -std=c++17.

ContentLicense: CC BY-SA 3.0

Body:
Is there a good way to use std::tie and create a new variable in one go? In other words, if a function returns an std::tuple and we want to ultimately break up the result into individual components, is there a way to do these assignments without defining variables beforehand?

For example, consider the following code:

#include <tuple>

struct Foo {
    Foo(int) {}
};
struct Bar{};

std::tuple <Foo,Bar> example() {
    return std::make_tuple(Foo(1),Bar());
}

int main() {
    auto bar = Bar {};

    // Without std::tie
    {
        auto foo_bar = example();
        auto foo = std::get<0>(std::move(foo_bar));
        bar = std::get<1>(std::move(foo_bar));
    }

    // With std::tie
    #if 0
    {
        // Error: no default constructor
        Foo foo;
        std::tie(foo,bar) = example();
    }
    #endif

}

Basically, the function example returns a tuple.  We already have a variable of type Bar that we want to assign into, but we need a new variable of type Foo.  Without std::tie, we don't need to create a dummy instance of Foo, but the code requires us to put everything into a std::tuple first and then divide it.  With std::tie, we have to allocate a dummy Foo first, but we don't have a default constructor to do so.  Really, we're pretending that the constructors for Foo are complicated, so creating a dummy value first is undesirable.  Ultimately, we'd just like to assign into both foo and bar, but want to do this assignment and allocate memory for Foo at the same time.

Body:
This feature is called structured bindings in C++17. Very welcome addition!

Sample usage:

#include <iostream>
#include <tuple>

int main()
{
    auto tuple = std::make_tuple(1, 'a', 2.3);

    // unpack the tuple into individual variables declared at the call site
    auto [ i, c, d ] = tuple;

    std::cout << "i=" << i << " c=" << c << " d=" << d << '\n';

    return 0;
}

Tested in GCC 7.2 with -std=c++17.


问:
Swift equivalent of C#'s IsAssignableFrom
In C#, given two types, I can say something like

```<code>var stringType = typeof(string)
var intType = typeof(int)
var assignable = stringType.IsAssignableFrom(intType)
</code>```

The value of assignable would be false since an int cannot be assigned to a string.

Is there any way to do this in Swift?

```<code>func isAssignable<T1, T2>(_ type1: T1.Type, from type2: T2.Type) -> Bool {
    // What's the implementation here?
}

let assignable = isAssignable(String.self, from: Int.self)
</code>```

My suspicion is that this is not currently possible.

Why do I need this?

Some have asked why I need this. I've written a dependency resolution framework called Guise. Each registration returns a unique Key. While it's actually unusual to use the Key for resolution—there are more elegant ways—there are times when it is useful, such as when resolving multiple registrations.

In the code below, look at the line that says if type != key.type { continue }. This just compares the reflected string representations of the registered types. It would be a lot more useful if instead I could test assignability directly, so that the generic parameter T would not have to be the specific type under which the registration was made. Something like if !key.typeIsAssignableTo(type: T.self) { continue }. Where typeIsAssignableTo is a thunk over the type in Key.

At this point I don't have an instance and don't want one. In fact, that's the whole point. Any good DR framework should resolve lazily, and this one does. I don't want to have to create an instance first before testing type compatibility.

```<code>public static func resolve<T, K: Sequence>(keys: K, parameter: Any = (), cached: Bool? = nil) -> [T] where K.Iterator.Element == Key {
    return lock.read {
        let type = String(reflecting: T.self)
        var resolutions = [T]()
        for (key, dependency) in registrations {
            if type != key.type { continue }
            if !keys.contains(key) { continue }
            resolutions.append(dependency.resolve(parameter: parameter, cached: cached))
        }
        return resolutions
    }
}
</code>```

Probably clear as mud, but that's the best explanation I can give.

答:
Try this function from NSObject:

```<code>class func isSubclass(of aClass: Swift.AnyClass) -> Bool
</code>```

For instance:

```<code>UILabel.self.isSubclass(of: UIView.self) // true
UIView.self.isSubclass(of: UILabel.self) // false
UIView.self.isSubclass(of: UIView.self)  // true
</code>```

PS. This method is from the NSObject class so this only works within its subtypes.

Body:
In C#, given two types, I can say something like

var stringType = typeof(string)
var intType = typeof(int)
var assignable = stringType.IsAssignableFrom(intType)

The value of assignable would be false since an int cannot be assigned to a string.

Is there any way to do this in Swift?

func isAssignable<T1, T2>(_ type1: T1.Type, from type2: T2.Type) -> Bool {
    // What's the implementation here?
}

let assignable = isAssignable(String.self, from: Int.self)

My suspicion is that this is not currently possible.

Why do I need this?

Some have asked why I need this. I've written a dependency resolution framework called Guise. Each registration returns a unique Key. While it's actually unusual to use the Key for resolution—there are more elegant ways—there are times when it is useful, such as when resolving multiple registrations.

In the code below, look at the line that says if type != key.type { continue }. This just compares the reflected string representations of the registered types. It would be a lot more useful if instead I could test assignability directly, so that the generic parameter T would not have to be the specific type under which the registration was made. Something like if !key.typeIsAssignableTo(type: T.self) { continue }. Where typeIsAssignableTo is a thunk over the type in Key.

At this point I don't have an instance and don't want one. In fact, that's the whole point. Any good DR framework should resolve lazily, and this one does. I don't want to have to create an instance first before testing type compatibility.

public static func resolve<T, K: Sequence>(keys: K, parameter: Any = (), cached: Bool? = nil) -> [T] where K.Iterator.Element == Key {
    return lock.read {
        let type = String(reflecting: T.self)
        var resolutions = [T]()
        for (key, dependency) in registrations {
            if type != key.type { continue }
            if !keys.contains(key) { continue }
            resolutions.append(dependency.resolve(parameter: parameter, cached: cached))
        }
        return resolutions
    }
}

Probably clear as mud, but that's the best explanation I can give.

Body:
Try this function from NSObject:

class func isSubclass(of aClass: Swift.AnyClass) -> Bool

For instance:

UILabel.self.isSubclass(of: UIView.self) // true
UIView.self.isSubclass(of: UILabel.self) // false
UIView.self.isSubclass(of: UIView.self)  // true

PS. This method is from the NSObject class so this only works within its subtypes.


问:
When should be process context switching faster over thread's one?
Is there a case where process context switching is faster than thread's one?
In all cases thread switching seems faster.</p>

答:
So i got the answer of this question. (From teacher)
Process Switching can be Faster than Thread Switching in 1 case
When there are 2 Processes:
The thread switching between two threads of two different processes is slower than Process switching between two processes</p>


问:
can asset folder be accessed by the user when the apk is installed?
For example i have an android program which contains important files in the assets folder , can the user who installed the apk access the assets folder or not ? for hacking purpose

答: Anyone can open your .apk just by changing the extension to .rar, what you can do to protect your code is releasing it using proguard rules, but still in that case an image for instance in the drawable folder  can be compromised, however an string in your strings.xml is bit more protected. </p>


问:
Binding Variables in Ruby
I currently have a table that is listed as follows:

```<code>projects = Project.find(:all, :conditions => [conditions + "AND (name LIKE ? OR description LIKE ?)", "%#{params[:query]}%", "%#{params[:query]}%"])
</code>```

where

```<code> conditions = Project.in_used_projects(:alias => "projects")
</code>```

However I need to include a 3rd variable which is not from the Project table but from a Tags table. The column I need is Tag - > Names. Is there anyway I can bind variables from another table in Ruby? The Project.find(all) automatically passes the SELECT * FROM Project into MYSQL. Someone has suggested using a join function, but I'm not sure how this would work. Any ideas?

EDIT 1

I have tried the suggested answer of using

```<code>projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)
</code>```

but now I am getting another error

Mysql::Error: Unknown table 'projects': SELECTprojects.* FROMprojectstags WHERE ((projects.status = 2)AND (projects.name LIKE '%%' OR projects.description LIKE '%%' OR tags.name LIKE '%%')

Very strange considering the projects table exists. Why isn't Ruby recognizing it now that i've included another table?

答:
Try this out for size:

```<code>projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)
</code>```

The :joins option tells Active Record to perform an SQL join onto the tags table, which will allow you to perform queries on the tags column. Also take note in this example how I've added the projects. prefix to your original name column. This is so your database doesn't get confused what name column you want; the one from the  projects or the tags table.

Title: Binding Variables in Ruby

Body:
I currently have a table that is listed as follows:

projects = Project.find(:all, :conditions => [conditions + "AND (name LIKE ? OR description LIKE ?)", "%#{params[:query]}%", "%#{params[:query]}%"])

where

 conditions = Project.in_used_projects(:alias => "projects")

However I need to include a 3rd variable which is not from the Project table but from a Tags table. The column I need is Tag - > Names. Is there anyway I can bind variables from another table in Ruby? The Project.find(all) automatically passes the SELECT * FROM Project into MYSQL. Someone has suggested using a join function, but I'm not sure how this would work. Any ideas?

EDIT 1

I have tried the suggested answer of using

projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)

but now I am getting another error

Mysql::Error: Unknown table 'projects': SELECTprojects.* FROMprojectstags WHERE ((projects.status = 2)AND (projects.name LIKE '%%' OR projects.description LIKE '%%' OR tags.name LIKE '%%')

Very strange considering the projects table exists. Why isn't Ruby recognizing it now that i've included another table?

Body:
Try this out for size:

projects = Project.find(:all, :joins => "tags", :conditions => [conditions + "AND (projects.name LIKE ? OR description LIKE ? OR tags.name LIKE ?", ["%#{params[:query]}%" * 3]].flatten)

The :joins option tells Active Record to perform an SQL join onto the tags table, which will allow you to perform queries on the tags column. Also take note in this example how I've added the projects. prefix to your original name column. This is so your database doesn't get confused what name column you want; the one from the  projects or the tags table.


问:
syntax error in select from where mysql statement
I got an syntax error in this code:

```<code>msql=("SELECT FILE_NAME FROM file_processed WHERE FILE_NAME = %s ;")

if cursor.execute(msql,name):
    return True
else:
    return False
</code>```

i got an error near '%s'
can anybody tell me wherE? thanks!

error:
mysql.connector.errors.ProgrammingError: 1064(42000): You have an error in SQL syntax: check Mysql server version for the right syntax to use near '%s' at line 1 Im using mysql 5.6

Now I try this:

```<code>msql=("SELECT FILE_NAME FROM file_processed WHERE FILE_NAME='HCTC3153_INF.TXT'; ")
if cursor.execute(msql):
    print "its is in the db"
    return True
else:
    print "its not in db"
    return False
</code>```

Always return its not in db even is in there...
The error raise now is:
 raise errors.InternalError("Unread result found.")
 mysql.connector.errors.InternalError: Unread result found.

答:
I did

```<code>enter code here
</code>```

got this!!

Body:
I got an syntax error in this code:

msql=("SELECT FILE_NAME FROM file_processed WHERE FILE_NAME = %s ;")

if cursor.execute(msql,name):
    return True
else:
    return False

i got an error near '%s'
can anybody tell me wherE? thanks!

error:
mysql.connector.errors.ProgrammingError: 1064(42000): You have an error in SQL syntax: check Mysql server version for the right syntax to use near '%s' at line 1 Im using mysql 5.6

Now I try this:

msql=("SELECT FILE_NAME FROM file_processed WHERE FILE_NAME='HCTC3153_INF.TXT'; ")
if cursor.execute(msql):
    print "its is in the db"
    return True
else:
    print "its not in db"
    return False

Always return its not in db even is in there...
The error raise now is:
 raise errors.InternalError("Unread result found.")
 mysql.connector.errors.InternalError: Unread result found.

Body:
I did

enter code here

got this!!


答:
Though your question has been answered, I still wanted to give it a try (for practice sake). The function is giving the expected output but Paul Panzer's solution is by far the most optimal one. :)

```<code>    def MatchesLenghtSums(L, lst):
        """
        Compares a list, lst with a list of lists, L. If elements of lst are in L
        Returns matching elements of lst, lenght of unpacked L, sum of lst
        Precondition: len(L) = 3"""

        # unpack L
        easy, medium, hard = L
        # traverse lst and find if there are matching elements between lst and
        # unpacked lists
        easyA = [e for e in lst if e in easy]
        mediumB = [m for m in lst if m in medium]
        hardC = [h for h in lst if h in hard]

        return "(Easy Matches {} Lenght {} sum {}) (Medium Matches {} Length {} sum {}) (Hard Matches {} Lenght {} sum {})".format(
                len(easyA), len(easy), sum(easyA), len(mediumB),
        len(medium), sum(mediumB), len(hardC), len(hard), sum(hardC))

L = [easy, med, hard]
lst = input_scores
MatchesLenghtSums(L, lst)

>>>'(Easy Matches 4 Lenght 10 sum 3.520415053910622e+24) (Medium Matches 6 Length 10 sum 143744715.77690864) (Hard Matches 6 Lenght 10 sum 37326.0)'
</code>```

Title: Counting no. of matches from two lists given a condition to split the original list

Body:
I have a lists of floats with some hidden "level" information encoded in the scale of the float, and I can split the "levels" of floats as such:

import math
import numpy as np

all_scores = [1.0369411057174144e+22, 2.7997409854370188e+23, 1.296176382146768e+23,
6.7401171871631936e+22, 6.7401171871631936e+22, 2.022035156148958e+24, 8.65845823274041e+23,
1.6435516525621017e+24, 2.307193960221247e+24, 1.285806971089594e+24, 9603539.08653573,
17489013.841076534, 11806185.6660164, 16057293.564414097, 8546268.728385007, 53788629.47091801,
31828243.07349571, 51740168.15200098, 53788629.47091801, 22334836.315934014,
4354.0, 7474.0, 4354.0, 4030.0, 6859.0, 8635.0, 7474.0, 8635.0, 9623.0, 8479.0]

easy, med, hard = [], [], []

for i in all_scores:
    if i > math.exp(50):
        easy.append(i)
    elif i > math.exp(10):
        med.append(i)
    else:
        hard.append(i)

print ([easy, med, hard])

[out]:

[[1.0369411057174144e+22, 2.7997409854370188e+23, 1.296176382146768e+23, 6.7401171871631936e+22, 6.7401171871631936e+22, 2.022035156148958e+24, 8.65845823274041e+23, 1.6435516525621017e+24, 2.307193960221247e+24, 1.285806971089594e+24], [9603539.08653573, 17489013.841076534, 11806185.6660164, 16057293.564414097, 8546268.728385007, 53788629.47091801, 31828243.07349571, 51740168.15200098, 53788629.47091801, 22334836.315934014], [4354.0, 7474.0, 4354.0, 4030.0, 6859.0, 8635.0, 7474.0, 8635.0, 9623.0, 8479.0]]

And I have another list that will correspond to the all_scores list:

input_scores = [0.0, 2.7997409854370188e+23, 0.0, 6.7401171871631936e+22, 0.0, 0.0, 8.6584582327404103e+23, 0.0, 2.3071939602212471e+24, 0.0, 0.0, 17489013.841076534, 11806185.6660164, 0.0, 8546268.728385007, 0.0, 31828243.073495708, 51740168.152000979, 0.0, 22334836.315934014, 4354.0, 7474.0, 4354.0, 4030.0, 0.0, 8635.0, 0.0, 0.0, 0.0, 8479.0]

I need to check how many of the easy, med and hard matches the all scores, I could do this to get the boolean of whether there's a match on the flatten all_scores list as such:

matches = [i == j for i, j in zip(input_scores, all_scores)]
print ([i == j for i, j in zip(input_scores, all_scores)])

[out]:

[False, True, False, True, False, False, True, False, True, False, False, True, True, False, True, False, True, True, False, True, True, True, True, True, False, True, False, False, False, True]

Is there a way to know how many easy/med/hard there are in the matches and the sum of the matches per level?

I have tried this and it works:

matches = [int(i == j) for i, j in zip(input_scores, all_scores)]

print(sum(matches[:len(easy)]) , len(easy), sum(np.array(easy) * matches[:len(easy)]) )
print(sum(matches[len(easy):len(easy)+len(med)]), len(med), sum(np.array(med) * matches[len(easy):len(easy)+len(med)]) )
print (sum(matches[len(easy)+len(med):]) , len(hard), sum(np.array(hard) * matches[len(easy)+len(med):]) )

[out]:

4 10 3.52041505391e+24
6 10 143744715.777
6 10 37326.0

But there must be a less verbose way to achieve the same output.

Body:
Though your question has been answered, I still wanted to give it a try (for practice sake). The function is giving the expected output but Paul Panzer's solution is by far the most optimal one. :)

    def MatchesLenghtSums(L, lst):
        """
        Compares a list, lst with a list of lists, L. If elements of lst are in L
        Returns matching elements of lst, lenght of unpacked L, sum of lst
        Precondition: len(L) = 3"""

        # unpack L
        easy, medium, hard = L
        # traverse lst and find if there are matching elements between lst and
        # unpacked lists
        easyA = [e for e in lst if e in easy]
        mediumB = [m for m in lst if m in medium]
        hardC = [h for h in lst if h in hard]

        return "(Easy Matches {} Lenght {} sum {}) (Medium Matches {} Length {} sum {}) (Hard Matches {} Lenght {} sum {})".format(
                len(easyA), len(easy), sum(easyA), len(mediumB),
        len(medium), sum(mediumB), len(hardC), len(hard), sum(hardC))

L = [easy, med, hard]
lst = input_scores
MatchesLenghtSums(L, lst)

>>>'(Easy Matches 4 Lenght 10 sum 3.520415053910622e+24) (Medium Matches 6 Length 10 sum 143744715.77690864) (Hard Matches 6 Lenght 10 sum 37326.0)'


问:
How can I insert a character after every 2 characters?
I want to insert a slash after every two characters, but just for the first two instances. The following regex inserts after every occurrence. Does anyone know how to limit it to two occurrences? The amount will be entered by the user through an input element. So if a user entered 30032017 it would be something like the following.

```<code>function insertSlash(val) {
    return val.match(new RegExp('.{1,2}', 'g')).join("/");
}

insertSlash(input);
</code>```

so for the first character the user would enter 3. On the next input it will be 0. this should then insert a slash.

this should then return 30/03/2017.

答:
Ignoring that it might not match,

```<code>"30032017".match(new RegExp("(..)(..)(....)")).slice(1).join("/")
</code>```

The value returned from match is a match group array. The first element will have the entire matched string, so it needs to be sliced out so we can join.

Body:
I want to insert a slash after every two characters, but just for the first two instances. The following regex inserts after every occurrence. Does anyone know how to limit it to two occurrences? The amount will be entered by the user through an input element. So if a user entered 30032017 it would be something like the following.

function insertSlash(val) {
    return val.match(new RegExp('.{1,2}', 'g')).join("/");
}

insertSlash(input);

so for the first character the user would enter 3. On the next input it will be 0. this should then insert a slash.

this should then return 30/03/2017.

Body:
Ignoring that it might not match,

"30032017".match(new RegExp("(..)(..)(....)")).slice(1).join("/")

The value returned from match is a match group array. The first element will have the entire matched string, so it needs to be sliced out so we can join.


问:
:after content displaying over original element
The .back-btn servers as a background image of an arrow. I am wanting the :after content to display under the image. I am unsure what I am doing wrong. I have tried adding margin-top and position:relative to the :after element, but nothing seems to work. Does anyone see what I am doing wrong?

.back-btn {
    position: fixed;
    left: 2%;
    display: block;
    cursor: pointer;
    background-image: url("https://d30y9cdsu7xlg0.cloudfront.net/png/41-200.png");
    background-repeat: no-repeat;
    background-size: 35px 35px;
    height: 35px;
    width: 35px;
}
.back-btn:after {
    content: "Back";
    color: #303030;
    font-size: .8em;
    display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="back-btn"></div></code>```

答:
Instead of giving .back-btn a height, change that height to padding top:

.back-btn {
    position: fixed;
    left: 2%;
    display: block;
    cursor: pointer;
    background-image: url("https://d30y9cdsu7xlg0.cloudfront.net/png/41-200.png");
    background-repeat: no-repeat;
    background-size: 35px 35px;
    padding-top: 35px;
    width: 35px;
    text-align:center; /* optional if you want to centre your text */
}
.back-btn:after {
    content: "Back";
    color: #303030;
    font-size: .8em;
    display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="back-btn"></div></code>```

Body:
Instead of giving .back-btn a height, change that height to padding top:

.back-btn {
    position: fixed;
    left: 2%;
    display: block;
    cursor: pointer;
    background-image: url("https://d30y9cdsu7xlg0.cloudfront.net/png/41-200.png");
    background-repeat: no-repeat;
    background-size: 35px 35px;
    padding-top: 35px;
    width: 35px;
    text-align:center; /* optional if you want to centre your text */
}
.back-btn:after {
    content: "Back";
    color: #303030;
    font-size: .8em;
    display: block;
}

<div class="back-btn"></div>


问:
Mutex locking between multiple threads
I am a chip designer and we use mutex in our circuits all the time for atomic memory accesses. I am learning to code in CPP and I am having hard time understanding how the Mutex works in CPP.

I understand that any program is a process and threads under a process have their own local objects, in addition to global objects that are accessible from any thread under this process.

In my attempt to understand mutex more intimately, I found this example at http://www.cplusplus.com/reference/condition_variable/condition_variable/

```<code>1  // condition_variable example
2  #include <iostream>           // std::cout
3  #include <thread>             // std::thread
4  #include <mutex>              // std::mutex, std::unique_lock
5  #include <condition_variable> // std::condition_variable
6
7  std::mutex mtx;
8  std::condition_variable cv;
9  bool ready = false;
10
11 void print_id (int id) {
12   std::unique_lock<std::mutex> lck(mtx);
13   while (!ready) cv.wait(lck);
14   // ...
15   std::cout << "thread " << id << '\n';
16 }
17
18 void go() {
19   std::unique_lock<std::mutex> lck(mtx);
20   ready = true;
21   cv.notify_all();
22 }
23
24 int main ()
25 {
26   std::thread threads[10];
27   // spawn 10 threads:
28   for (int i=0; i<10; ++i)
29     threads[i] = std::thread(print_id,i);
30
31   std::cout << "10 threads ready to race...\n";
32   go();                       // go!
33
34   for (auto& th : threads) th.join();
35
36   return 0;
37 }
</code>```

Possible output (thread order may vary):

```<code>10 threads ready to race...
thread 2
thread 0
thread 9
thread 4
thread 6
thread 8
thread 7
thread 5
thread 3
thread 1
</code>```

In line 28 and 29, 10 threads are scheduled. All of them are trying to lock same mutex (mtx). As I understand, one of the 10 thread will get the lock and will wait at line 13, while other 9 threads will try to get the lock and get blocked at line 12 itself.

Then comes the call to function go() at line 32. Go() also is trying to get the lock for the same mutex at line 19. But it should not get it as one print_id() thread is owning the lock. As per my understanding, this should result in a deadlock as go() is blocked at line 19, and can't get past that line, and consequently, can't send the cv.notify_all();

But the result in the link claims otherwise. It shows that go() effortlessly acquired the lock and sent the notify that in turn started the domino effect on 10 threads.

What am I missing? Is there some specific rule embedded in CPP specification that is allowing go() function to acquire the lock from the thread that was owning it? I have spent many hours in net searching for an answer, but in vain.

I will really appreciate some explanation of this phenomenon.

答: cv.wait(lock) will release the lock while the condition variable is waiting, and it'll reacquire the lock (or block while trying to reacquire the lock) when notify_all is called.

Title: Mutex locking between multiple threads

Body:
I am a chip designer and we use mutex in our circuits all the time for atomic memory accesses. I am learning to code in CPP and I am having hard time understanding how the Mutex works in CPP.

I understand that any program is a process and threads under a process have their own local objects, in addition to global objects that are accessible from any thread under this process.

In my attempt to understand mutex more intimately, I found this example at http://www.cplusplus.com/reference/condition_variable/condition_variable/

1  // condition_variable example
2  #include <iostream>           // std::cout
3  #include <thread>             // std::thread
4  #include <mutex>              // std::mutex, std::unique_lock
5  #include <condition_variable> // std::condition_variable
6
7  std::mutex mtx;
8  std::condition_variable cv;
9  bool ready = false;
10
11 void print_id (int id) {
12   std::unique_lock<std::mutex> lck(mtx);
13   while (!ready) cv.wait(lck);
14   // ...
15   std::cout << "thread " << id << '\n';
16 }
17
18 void go() {
19   std::unique_lock<std::mutex> lck(mtx);
20   ready = true;
21   cv.notify_all();
22 }
23
24 int main ()
25 {
26   std::thread threads[10];
27   // spawn 10 threads:
28   for (int i=0; i<10; ++i)
29     threads[i] = std::thread(print_id,i);
30
31   std::cout << "10 threads ready to race...\n";
32   go();                       // go!
33
34   for (auto& th : threads) th.join();
35
36   return 0;
37 }

Possible output (thread order may vary):

10 threads ready to race...
thread 2
thread 0
thread 9
thread 4
thread 6
thread 8
thread 7
thread 5
thread 3
thread 1

In line 28 and 29, 10 threads are scheduled. All of them are trying to lock same mutex (mtx). As I understand, one of the 10 thread will get the lock and will wait at line 13, while other 9 threads will try to get the lock and get blocked at line 12 itself.

Then comes the call to function go() at line 32. Go() also is trying to get the lock for the same mutex at line 19. But it should not get it as one print_id() thread is owning the lock. As per my understanding, this should result in a deadlock as go() is blocked at line 19, and can't get past that line, and consequently, can't send the cv.notify_all();

But the result in the link claims otherwise. It shows that go() effortlessly acquired the lock and sent the notify that in turn started the domino effect on 10 threads.

What am I missing? Is there some specific rule embedded in CPP specification that is allowing go() function to acquire the lock from the thread that was owning it? I have spent many hours in net searching for an answer, but in vain.

I will really appreciate some explanation of this phenomenon.


问:
Generate Resource Designer cs programmatically
I alter the "Resource.resx" files in different projects from my application and generate them.

The changes won´t be recognized until I select the"Resource.resx" file in Visual Studio and run the custom tool (ResXFileCodeGenerator).

Is there a way to run the custom tool or to generate the "Resource.Designer.cs" file programmatically?

I tried to make it happen with the "ResGen.exe", but it just produces resource files. To generate the"Resource.resx" files I use the System.ResourcesResXResourceWriter.

答:
Yes, this can be done in code:
See this link from msdn

Basically this is the code:

```<code>StreamWriter sw = new StreamWriter(@".\DemoResources.cs");
  string[] errors = null;
  CSharpCodeProvider provider = new CSharpCodeProvider();
  CodeCompileUnit code = StronglyTypedResourceBuilder.Create("Demo.resx", "DemoResources",
                                                             "DemoApp", provider,
                                                             false, out errors);
  if (errors.Length > 0)
     foreach (var error in errors)
        Console.WriteLine(error);

  provider.GenerateCodeFromCompileUnit(code, sw, new CodeGeneratorOptions());
  sw.Close();
</code>```

Body:
Yes, this can be done in code:
See this link from msdn

Basically this is the code:

StreamWriter sw = new StreamWriter(@".\DemoResources.cs");
  string[] errors = null;
  CSharpCodeProvider provider = new CSharpCodeProvider();
  CodeCompileUnit code = StronglyTypedResourceBuilder.Create("Demo.resx", "DemoResources",
                                                             "DemoApp", provider,
                                                             false, out errors);
  if (errors.Length > 0)
     foreach (var error in errors)
        Console.WriteLine(error);

  provider.GenerateCodeFromCompileUnit(code, sw, new CodeGeneratorOptions());
  sw.Close();


问:
Calculations in childs using pipes
My task is

a. A parent and two childs

b. Parent take data from the user

c. Send to a child for addition and subtraction.

d. Again take input from user and send to another child for multiplication and division.

e. First child process creates another child C3.

f. Both the childs send result to the child process C3 to show output.

g. Parent process after completion of each child process task kill the process.

I've write the following code but i don't know where I'm doing wrong, I tried to debug it but I do not know what is wrong with it, it not showing the multiplication and division result.

Here is my code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
#include <stdlib.h>

int main()
{
    int status = 0;
    int pfds[2];
    int pfds2[2];
    int pfds3[2];
    int pfds4[2];
    int val = 0;
    int val2 = 0;
    pipe(pfds);
    pipe(pfds2);
    pipe(pfds3);
    pipe(pfds4);
    printf("Enter FIRST Number:  ");
    scanf("%i", &val);
    printf("Enter SECOND Number:  ");
    scanf("%i", &val2);
    if (fork() == 0)
    {
//Child
        printf("I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers\n");
        read(pfds[0], &val, sizeof(val));
        read(pfds2[0], &val2, sizeof(val));
        int sum = val + val2;
        int sub = val - val2;
        write(pfds3[1], &sum, sizeof(val));
        write(pfds4[1], &sub, sizeof(val));
        if (fork() == 0)
        {
            read(pfds3[0], &val, sizeof(val));
            printf("Sum Of Numbers Is : %i\n", val);
            read(pfds4[0], &val, sizeof(val));
            printf("Sub Of Numbers Is : %i\n", val);
            read(pfds[0], &val, sizeof(val));
            printf("Mul Of Numbers Is : %i\n", val);
            read(pfds2[0], &val, sizeof(val));
            printf("Div Of Numbers Is : %i\n", val);
            exit(1);
        }
        else
        {
            wait(&status);
        }
        exit(1);
    }
    else
    {
        if (fork() == 0)
        {
//Child2
            printf("I'm Child 2 and I'm Calculating Multiplication and Division Of Number\n");
            read(pfds[0], &val, sizeof(val));
            read(pfds2[0], &val2, sizeof(val));
            int mul = val * val2;
            int div = val / val2;
            write(pfds[1], &mul, sizeof(val));
            write(pfds2[1], &div, sizeof(val));
            exit(0);
        }
        else
        {
//wait(&status);
            write(pfds[1], &val, sizeof(val));
            write(pfds2[1], &val2, sizeof(val));
            wait(&status);
        } //else1
    } //else2
} //main
</code>```

It's giving me the following output:

```<code>Enter FIRST Number:  4
Enter SECOND Number:  2
I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers
I'm Child 2 and I'm Calculating Multiplication and Division Of Number
Sum Of Numbers Is : 6
Sub Of Numbers Is : 2
</code>```

If someone can help thankyou very much.

答:
The problem looks like you've misunderstood how pipes work. All your child processes are sharing the same pipes. When child 1 reads from pfds[0] that means that when child 2 tries reading from it, the data is already gone. Or maybe child 2 reads the data first and child 1 goes without. Either way, only 1 child can read the data.

You should create each pipe for one use only - ie for parent to talk to child 1.

Maybe create a function that creates a pipe and forks a child process that you can re-use as required, something along the lines of.

```<code>pid_t create_child(int *pipefds[2])
  {
  pipe(*pipefds);
  return fork();
  }
</code>```

Title: Calculations in childs using pipes

Body:
My task is

a. A parent and two childs

b. Parent take data from the user

c. Send to a child for addition and subtraction.

d. Again take input from user and send to another child for multiplication and division.

e. First child process creates another child C3.

f. Both the childs send result to the child process C3 to show output.

g. Parent process after completion of each child process task kill the process.

I've write the following code but i don't know where I'm doing wrong, I tried to debug it but I do not know what is wrong with it, it not showing the multiplication and division result.

Here is my code:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
#include <stdlib.h>

int main()
{
    int status = 0;
    int pfds[2];
    int pfds2[2];
    int pfds3[2];
    int pfds4[2];
    int val = 0;
    int val2 = 0;
    pipe(pfds);
    pipe(pfds2);
    pipe(pfds3);
    pipe(pfds4);
    printf("Enter FIRST Number:  ");
    scanf("%i", &val);
    printf("Enter SECOND Number:  ");
    scanf("%i", &val2);
    if (fork() == 0)
    {
//Child
        printf("I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers\n");
        read(pfds[0], &val, sizeof(val));
        read(pfds2[0], &val2, sizeof(val));
        int sum = val + val2;
        int sub = val - val2;
        write(pfds3[1], &sum, sizeof(val));
        write(pfds4[1], &sub, sizeof(val));
        if (fork() == 0)
        {
            read(pfds3[0], &val, sizeof(val));
            printf("Sum Of Numbers Is : %i\n", val);
            read(pfds4[0], &val, sizeof(val));
            printf("Sub Of Numbers Is : %i\n", val);
            read(pfds[0], &val, sizeof(val));
            printf("Mul Of Numbers Is : %i\n", val);
            read(pfds2[0], &val, sizeof(val));
            printf("Div Of Numbers Is : %i\n", val);
            exit(1);
        }
        else
        {
            wait(&status);
        }
        exit(1);
    }
    else
    {
        if (fork() == 0)
        {
//Child2
            printf("I'm Child 2 and I'm Calculating Multiplication and Division Of Number\n");
            read(pfds[0], &val, sizeof(val));
            read(pfds2[0], &val2, sizeof(val));
            int mul = val * val2;
            int div = val / val2;
            write(pfds[1], &mul, sizeof(val));
            write(pfds2[1], &div, sizeof(val));
            exit(0);
        }
        else
        {
//wait(&status);
            write(pfds[1], &val, sizeof(val));
            write(pfds2[1], &val2, sizeof(val));
            wait(&status);
        } //else1
    } //else2
} //main

It's giving me the following output:

Enter FIRST Number:  4
Enter SECOND Number:  2
I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers
I'm Child 2 and I'm Calculating Multiplication and Division Of Number
Sum Of Numbers Is : 6
Sub Of Numbers Is : 2

If someone can help thankyou very much.

Body:
The problem looks like you've misunderstood how pipes work. All your child processes are sharing the same pipes. When child 1 reads from pfds[0] that means that when child 2 tries reading from it, the data is already gone. Or maybe child 2 reads the data first and child 1 goes without. Either way, only 1 child can read the data.

You should create each pipe for one use only - ie for parent to talk to child 1.

Maybe create a function that creates a pipe and forks a child process that you can re-use as required, something along the lines of.

pid_t create_child(int *pipefds[2])
  {
  pipe(*pipefds);
  return fork();
  }


问:
Why is this caterpillar algorithm O(n^2) not O(n^3)?
Can someone explain why this algorithm is O(n^2)? According to this, it's O(n^2).
The reason why I think it's O(n^3) is because outer loop (for x) runs n times, inner loop (for y) runs n-1 times, and in the worst scenario e.g. A = [8, 100, 101, 102, 103, 104, 105, 106, 107], the while loop (for z) will run n-2 times hence overall O(n^3).

For completeness, A is a sorted array with positive elements, a triplet (x, y, z) is a triangle if A[x] + A[y] > A[z]. Find how many triangles can be built from A.

```<code>        int TrianglesCount(int[] A)
        {
            int result = 0;
            for (int x = 0; x < A.Length; x++)
            {
                int z = x + 2;
                for (int y = x + 1; y < A.Length; y++)
                {
                    while (z < A.Length && A[x] + A[y] > A[z])
                        z++;
                    result += z - y - 1;
                }
            }
            return result;
        }
</code>```

答:
Let's take a closer look at the below snippet

```<code>int z = x + 2;
for (int y = x + 1; y < A.Length; y++)
{
   while (z < A.Length && A[x] + A[y] > A[z])
      z++;
   result += z - y - 1;
}
</code>```

The for loop is clearly executed A.lenght - (x+1) times, which is O(n). However, the inner while loop is executed at most A.length - (x+2) times in total, because each such execution increments value of z, and it can be incremented at most A.length - (x+2) times until the while condition fails. Again, this is at most O(n). Thus, the total time complexity of this snippet can be bounded by O(n) + O(n) = O(n).

Since the snippet is run for every of O(n) values of x, the overall time complexity is O(n^2).

A similar idea is used in KMP algorithm for string matching.

Body:
Can someone explain why this algorithm is O(n^2)? According to this, it's O(n^2).
The reason why I think it's O(n^3) is because outer loop (for x) runs n times, inner loop (for y) runs n-1 times, and in the worst scenario e.g. A = [8, 100, 101, 102, 103, 104, 105, 106, 107], the while loop (for z) will run n-2 times hence overall O(n^3).

For completeness, A is a sorted array with positive elements, a triplet (x, y, z) is a triangle if A[x] + A[y] > A[z]. Find how many triangles can be built from A.

        int TrianglesCount(int[] A)
        {
            int result = 0;
            for (int x = 0; x < A.Length; x++)
            {
                int z = x + 2;
                for (int y = x + 1; y < A.Length; y++)
                {
                    while (z  A[z])
                        z++;
                    result += z - y - 1;
                }
            }
            return result;
        }

Body:
Let's take a closer look at the below snippet

int z = x + 2;
for (int y = x + 1; y < A.Length; y++)
{
   while (z < A.Length && A[x] + A[y] > A[z])
      z++;
   result += z - y - 1;
}

The for loop is clearly executed A.lenght - (x+1) times, which is O(n). However, the inner while loop is executed at most A.length - (x+2) times in total, because each such execution increments value of z, and it can be incremented at most A.length - (x+2) times until the while condition fails. Again, this is at most O(n). Thus, the total time complexity of this snippet can be bounded by O(n) + O(n) = O(n).

Since the snippet is run for every of O(n) values of x, the overall time complexity is O(n^2).

A similar idea is used in KMP algorithm for string matching.


问:
Convert rgb strings to hex in Javascript
I am using the TweenMax JS library with the ColorPropsPlugin which will tween color values which are specified in many formats, the problem I have is that the result is always in the form of a string:

```<code>"rgb(255,255,255)"
</code>```

How can that be converted in to a hex number like:

```<code>0xffffff
</code>```

答:
A codegolfed approach:

```<code>var h = x => '#' + x.match(/\d+/g).map(y = z => ((+z < 16)?'0':'') + (+z).toString(16)).join('');
</code>```

Now, running h("rgb(255, 60, 60)") will return #ff3c3c.

You can replace '#' with '0x' to get outputs in the form of 0xff3c3c.

EXTRA: how it works.

h, declared as an arrow function (new in ES6) takes an RGB value (string) and stores it in x.
Then, all instances of numbers in x are found by the regex equation /\d+/g, and used further as an array (returned by match, used by map).

map loops processes all the elements of the returned array by a function y.
The function takes a value (which was stored in the array as a string) as z converts it to a number (+z), checks if it is less than 16 (((+z < 16)?'0':''), that is, the hex representation has a single digit), and if true, adds a '0' to the element's start.

Then, it converts it to a string of base 16 (hex, by .toString(16)), and returns it to map. So essentially, all the decimal strings in the array are now changed to hex strings.

Finally, the array's elements are joined together (join('')), with no delimiter and '#' is added to the beginning of the string.

Note: If the code is supplied a value greater than 255, the output will be more than 6 hex digits. Like, the output for rgb(256, 0, 0) will be #1000000.

To constraint the value to 255, this would be the code:

```<code>var h = x => '#' + x.match(/\d+/g).map(y = z => ((+z < 16)?'0':'') + ((+z > 255)?255:+z).toString(16)).join('');
</code>```

Body:
I am using the TweenMax JS library with the ColorPropsPlugin which will tween color values which are specified in many formats, the problem I have is that the result is always in the form of a string:

"rgb(255,255,255)"

How can that be converted in to a hex number like:

0xffffff

Body:
A codegolfed approach:

var h = x => '#' + x.match(/\d+/g).map(y = z => ((+z < 16)?'0':'') + (+z).toString(16)).join('');

Now, running h("rgb(255, 60, 60)") will return #ff3c3c.

You can replace '#' with '0x' to get outputs in the form of 0xff3c3c.

EXTRA: how it works.

h, declared as an arrow function (new in ES6) takes an RGB value (string) and stores it in x.
Then, all instances of numbers in x are found by the regex equation /\d+/g, and used further as an array (returned by match, used by map).

map loops processes all the elements of the returned array by a function y.
The function takes a value (which was stored in the array as a string) as z converts it to a number (+z), checks if it is less than 16 (((+z < 16)?'0':''), that is, the hex representation has a single digit), and if true, adds a '0' to the element's start.

Then, it converts it to a string of base 16 (hex, by .toString(16)), and returns it to map. So essentially, all the decimal strings in the array are now changed to hex strings.

Finally, the array's elements are joined together (join('')), with no delimiter and '#' is added to the beginning of the string.

Note: If the code is supplied a value greater than 255, the output will be more than 6 hex digits. Like, the output for rgb(256, 0, 0) will be #1000000.

To constraint the value to 255, this would be the code:

var h = x => '#' + x.match(/\d+/g).map(y = z => ((+z < 16)?'0':'') + ((+z > 255)?255:+z).toString(16)).join('');


问:
CSS3 Rounded and Dotted borders?
Is it possible to create a border in CSS3 such that they are rounded and dotted?

I'm rounding my corners but they appear solid with:

```<code>border: 1px dotted gray;
-moz-border-radius-topright: 30px 20px;
-moz-border-radius-topleft: 30px 20px;
</code>```

The rest of the border is dotted but the corners are solid.

I understand that this is specific to Firefox but that's fine for now.

Thanks

答:
My solution for this issue is

```<code>background: url('../images/dot.png');
background-size: 4px;
background-position: bottom left;
background-repeat: repeat-x;
</code>```

make sure the dot image is just one dot with some white space on wither side of it. After that you should be good.

Title: CSS3 Rounded and Dotted borders?

Body:
Is it possible to create a border in CSS3 such that they are rounded and dotted?

I'm rounding my corners but they appear solid with:

border: 1px dotted gray;
-moz-border-radius-topright: 30px 20px;
-moz-border-radius-topleft: 30px 20px;

The rest of the border is dotted but the corners are solid.

I understand that this is specific to Firefox but that's fine for now.

Thanks

Body:
My solution for this issue is

background: url('../images/dot.png');
background-size: 4px;
background-position: bottom left;
background-repeat: repeat-x;

make sure the dot image is just one dot with some white space on wither side of it. After that you should be good.


问:
Select two null columns in a row and insert value in any one of these columns
I have sid = xxxx.

And a table with tablename 'room' and columnnames sid1,sid2 and sid3 .
How i can check which column is null and insert sid value in any one of these null columns.

```<code>sid1    sid2    sid3    roomno
NULL    2222    NULL    1
5432    NULL    NULL    2
</code>```

答:
If you have just 3 columns, this isn't too bad . . .

```<code>update room
    set sid1 = (case when sid1 is null then $newval else sid1 end),
        sid2 = (case when sid1 is not null and sid2 is null then $newval else sid2 end),
        sid3 = (case when sid1 is not null and sid2 is not null and sid3 is null then $newval else sid3 end)
    where roomno = $roomno;
</code>```

However, I strongly recommend that you create a junction table, with one row per sid and one per room.

Body:
I have sid = xxxx.

And a table with tablename 'room' and columnnames sid1,sid2 and sid3 .
How i can check which column is null and insert sid value in any one of these null columns.

sid1    sid2    sid3    roomno
NULL    2222    NULL    1
5432    NULL    NULL    2

Body:
If you have just 3 columns, this isn't too bad . . .

update room
    set sid1 = (case when sid1 is null then $newval else sid1 end),
        sid2 = (case when sid1 is not null and sid2 is null then $newval else sid2 end),
        sid3 = (case when sid1 is not null and sid2 is not null and sid3 is null then $newval else sid3 end)
    where roomno = $roomno;

However, I strongly recommend that you create a junction table, with one row per sid and one per room.


问:
python map vs list comprehsnion
I am trying to return the min and max of a string of numbers, ie. ("1 2 3 4 5 6")

The code that I came up with is as follows

```<code>def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))
</code>```

This code does not work for the following example:

```<code>print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
6 -214
</code>```

However, a similar function crafted as:

```<code>def min_and_max(numbers):
    nn = [int(s) for s in numbers.split(' ')]
    return "%i %i" % (max(nn),min(nn))
</code>```

Returns the correct answer

```<code>print(min_and_max("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
542 -214
</code>```

Shouldn't

```<code>map(int, numbers)
</code>```

be the same as

```<code>[int(number) for number in numbers]
</code>```

Why do the two functions not return the same values?

答:
No, it shouldn't because you don't assign the result of map anywhere so min and max use numbers from numbers.split(' '). That is, you're using string comparisons.

The list comprehension is saved to nn and that is the name that is used in min and max.

Despite that, even if you did save numbers as the result of map:

```<code>numbers = map(int, numbers)
</code>```

you'd still get an error since max will first consume the iterable (until it's exhausted) and then min will complain because it'll receive an empty iterable.

You'd probably need to use something like itertools.tee, supply both min and max with map(int, numbers) or use a list-comprehension as you've already done.

Title: python map vs list comprehsnion

Body:
I am trying to return the min and max of a string of numbers, ie. ("1 2 3 4 5 6")

The code that I came up with is as follows

def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))

This code does not work for the following example:

print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
6 -214

However, a similar function crafted as:

def min_and_max(numbers):
    nn = [int(s) for s in numbers.split(' ')]
    return "%i %i" % (max(nn),min(nn))

Returns the correct answer

print(min_and_max("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
542 -214

Shouldn't

map(int, numbers)

be the same as

[int(number) for number in numbers]

Why do the two functions not return the same values?

Body:
No, it shouldn't because you don't assign the result of map anywhere so min and max use numbers from numbers.split(' '). That is, you're using string comparisons.

The list comprehension is saved to nn and that is the name that is used in min and max.

Despite that, even if you did save numbers as the result of map:

numbers = map(int, numbers)

you'd still get an error since max will first consume the iterable (until it's exhausted) and then min will complain because it'll receive an empty iterable.

You'd probably need to use something like itertools.tee, supply both min and max with map(int, numbers) or use a list-comprehension as you've already done.


问:
How do i record the occurances of 'Y' in a txt file in Python 3.2
I'm trying to record how many times the letter Y appears in the 6th column of a .txt file and assign that to a variable. How would I go about doing that? Thx in advance!

.txt file:

```<code>119,29/12/15,18:00,Ripley,Magnitude,Y,Magnitude
120,30/12/15,18:00,Jenkins,Kes,Y,Kes
121,31/12/15,18:00,Big Boss,Ingsoc,Y,Ingsoc
122,01/01/16,18:00,Einstein100,RNGesus,,
123,02/01/16,18:00,Macho Man,Napoleon Wilson,,
124,03/01/16,18:00,Dennis,Billy Casper,,
</code>```

I've set the whole file to a variable and have created variables for each column in the file.

```<code>    NextRecord = data[x]
    Number = NextRecord[0]
    Date = NextRecord[1]
    Time = NextRecord[2]
    P1Nickname = NextRecord[3]
    P2Nickname = NextRecord[4]
    Status = NextRecord[5]
</code>```

答:
THIS should work as expected:

```<code>noOfY=0
for line in open("thatTextFile.txt"):
    try:
        if 'Y' in line.split(',')[5]: noOfY+=1
    except:
        pass
print(noOfY)
</code>```

This gives for the text provided above:

```<code>3
</code>```

and works even in case of malformed lines in the input text file.

Body:
I'm trying to record how many times the letter Y appears in the 6th column of a .txt file and assign that to a variable. How would I go about doing that? Thx in advance!

.txt file:

119,29/12/15,18:00,Ripley,Magnitude,Y,Magnitude
120,30/12/15,18:00,Jenkins,Kes,Y,Kes
121,31/12/15,18:00,Big Boss,Ingsoc,Y,Ingsoc
122,01/01/16,18:00,Einstein100,RNGesus,,
123,02/01/16,18:00,Macho Man,Napoleon Wilson,,
124,03/01/16,18:00,Dennis,Billy Casper,,

I've set the whole file to a variable and have created variables for each column in the file.

    NextRecord = data[x]
    Number = NextRecord[0]
    Date = NextRecord[1]
    Time = NextRecord[2]
    P1Nickname = NextRecord[3]
    P2Nickname = NextRecord[4]
    Status = NextRecord[5]

Body:
THIS should work as expected:

noOfY=0
for line in open("thatTextFile.txt"):
    try:
        if 'Y' in line.split(',')[5]: noOfY+=1
    except:
        pass
print(noOfY)

This gives for the text provided above:

3

and works even in case of malformed lines in the input text file.


问:
How to solve a linear interpolation data by time step in R : (list) object can not be coerced to type 'double'
I have data of instantaneous water discharge under a file data.txt (data below)

(list) object can not be coerced to type 'double'

  I think the problem is due to the format of the dates, please how to solve this problem?

```<code>write.table(TAB4, file="Q.txt", sep=";",quote=FALSE,row.names=FALSE)
</code>```

答:
Two changes needed.  The list problem can be solved by converting x to POSIXct, not POSIXlt in section 6 of your code: x=as.POSIXct(TAB3$V1).

Then, in section 7, remove the NA values from x and y: TAB4=approx(x[-z],y[-z], xout= x[z]).

There is also a spurious p in pTAB4 in the following line that looks wrong.

Body:
I have data of instantaneous water discharge under a file data.txt (data below)

(list) object can not be coerced to type 'double'

  I think the problem is due to the format of the dates, please how to solve this problem?

write.table(TAB4, file="Q.txt", sep=";",quote=FALSE,row.names=FALSE)


问:
Can GoogleAds.dll be re written for windows uwp
I know there's a admob GoogleAds.dll for windows phone 8, can we decompile it and rewrite by changing the adview control with some uwp control ? Will it be a violation ? Is it possible to do this ?</p>

答: If you already have ad boxes created before the announcement has been issued that you could no longer generate ad for wp from admob you can re-insert the code, but otherwise it is no longer possible, regards.</p>


问:
AbstractSet.removeAll() method not working properly
The code shown below does output:

[b]

[a, b]

However I would expect it to print two identical lines in the output.

```<code>import java.util.*;

public class Test{
    static void test(String... abc) {
        Set<String> s = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        s.addAll(Arrays.asList("a", "b"));
        s.removeAll(Arrays.asList(abc));
        System.out.println(s);
    }

    public static void main(String[] args) {
        test("A");
        test("A", "C");
    }
}
</code>```

The spec clearly states that removeAll

"Removes all this collection's elements that are also contained in the
  specified collection."

So from my understanding current behavior is unpredictable . Please help me understand this

答:
You only read documentation partly. You forgot one important paragraph from TreeSet:

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Now removeAll implementation comes from AbstractSet and utilizes equals method. According to your code you will have that "a".equals("A") is not true so that elements are not considered equal even if you provided a comparator which manages them when used in the TreeSet itself. If you try with a wrapper then the problem goes away:

```<code>import java.util.*;
import java.lang.*;

class Test
{
    static class StringWrapper implements Comparable<StringWrapper>
    {
      public final String string;

      public StringWrapper(String string)
      {
        this.string = string;
      }

      @Override public boolean equals(Object o)
      {
        return o instanceof StringWrapper &&
            ((StringWrapper)o).string.compareToIgnoreCase(string) == 0;
      }

      @Override public int compareTo(StringWrapper other) {
        return string.compareToIgnoreCase(other.string);
      }

      @Override public String toString() { return string; }
    }

    static void test(StringWrapper... abc)
    {
        Set<StringWrapper> s = new TreeSet<>();
        s.addAll(Arrays.asList(new StringWrapper("a"), new StringWrapper("b")));
        s.removeAll(Arrays.asList(abc));
        System.out.println(s);
    }

    public static void main(String[] args)
    {
        test(new StringWrapper("A"));
        test(new StringWrapper("A"), new StringWrapper("C"));
    }
}
</code>```

This because you are now providing a consistent implementation between equals and compareTo of your object so you never have incoherent behavior between how the objects are added inside the sorted set and how all the abstract behavior of the set uses them.

This is true in general, a sort of rule of three for Java code: if you implement compareTo or equals or hashCode you should always implement all of them to avoid problems with standard collections (even if hashCode is less crucial unless you are using these objects in any hashed collection). This is specified many times around java documentation.

Body:
The code shown below does output:

[b]

[a, b]

However I would expect it to print two identical lines in the output.

import java.util.*;

public class Test{
    static void test(String... abc) {
        Set<String> s = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        s.addAll(Arrays.asList("a", "b"));
        s.removeAll(Arrays.asList(abc));
        System.out.println(s);
    }

    public static void main(String[] args) {
        test("A");
        test("A", "C");
    }
}

The spec clearly states that removeAll

"Removes all this collection's elements that are also contained in the
  specified collection."

So from my understanding current behavior is unpredictable . Please help me understand this

Body:
You only read documentation partly. You forgot one important paragraph from TreeSet:

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Now removeAll implementation comes from AbstractSet and utilizes equals method. According to your code you will have that "a".equals("A") is not true so that elements are not considered equal even if you provided a comparator which manages them when used in the TreeSet itself. If you try with a wrapper then the problem goes away:

import java.util.*;
import java.lang.*;

class Test
{
    static class StringWrapper implements Comparable<StringWrapper>
    {
      public final String string;

      public StringWrapper(String string)
      {
        this.string = string;
      }

      @Override public boolean equals(Object o)
      {
        return o instanceof StringWrapper &&
            ((StringWrapper)o).string.compareToIgnoreCase(string) == 0;
      }

      @Override public int compareTo(StringWrapper other) {
        return string.compareToIgnoreCase(other.string);
      }

      @Override public String toString() { return string; }
    }

    static void test(StringWrapper... abc)
    {
        Set<StringWrapper> s = new TreeSet<>();
        s.addAll(Arrays.asList(new StringWrapper("a"), new StringWrapper("b")));
        s.removeAll(Arrays.asList(abc));
        System.out.println(s);
    }

    public static void main(String[] args)
    {
        test(new StringWrapper("A"));
        test(new StringWrapper("A"), new StringWrapper("C"));
    }
}

This because you are now providing a consistent implementation between equals and compareTo of your object so you never have incoherent behavior between how the objects are added inside the sorted set and how all the abstract behavior of the set uses them.

This is true in general, a sort of rule of three for Java code: if you implement compareTo or equals or hashCode you should always implement all of them to avoid problems with standard collections (even if hashCode is less crucial unless you are using these objects in any hashed collection). This is specified many times around java documentation.


问:
Sending List into Partial View
I'm still trying to get my head wrapped around .net MVC, and maybe I'm just not searching the right key words to find my answer.

In short, I have a partial view that has a list that I want to include in the main view.

Index.cshtml:

```<code>@Html.Action("Checklist")
</code>```

Checklist.cshtml:

```<code>@model List<Area>
<div class="row">
    <div class="col-md-4">
        <h4 class="text-center">Outcomes</h4>
        @foreach (var item in Model)
        {
            <p>@Html.DisplayFor(modelItem => item)</p>
        }
    </div>
</div>
</code>```

Controller:

```<code>public PartialViewResult Checklist()
    {
        var outcomeAreas = db.OutcomeArea.Select(oa => oa.Area).Distinct();
        return PartialView("Checklist", outcomeAreas.ToList());
    }
</code>```

Edit: I get a weird rendering now in the html when testing the website.  if you look at the page source code, I see:

```<code>System.Collections.Generic.List`1[System.String] List<Area>
</code>```

答:
Your view is expecting a model of type List<Namespace.toModel> but the type of the outcomeAreas variable passed to it appears to be either IEnumerable<OutcomeArea> or IQueryable<OutcomeArea>

Try changing Checklist.cshtml to have this at the top:

```<code>@Model List<OutcomeArea>
</code>```

And then change your controller action to return:

```<code>return PartialView("Checklist", outcomeAreas.ToList());
</code>```

Edit: Just noticed that you're doing .Select(oa => oa.Area), so you'll actually want to use whatever type the 'Area' property is. @Model List<Area> or @Model List<string> if it's a string, etc..

Title: Sending List into Partial View

Body:
I'm still trying to get my head wrapped around .net MVC, and maybe I'm just not searching the right key words to find my answer.

In short, I have a partial view that has a list that I want to include in the main view.

Index.cshtml:

@Html.Action("Checklist")

Checklist.cshtml:

@model List<Area>

Outcomes

        @foreach (var item in Model)
        {

@Html.DisplayFor(modelItem => item)

        }

Controller:

public PartialViewResult Checklist()
    {
        var outcomeAreas = db.OutcomeArea.Select(oa => oa.Area).Distinct();
        return PartialView("Checklist", outcomeAreas.ToList());
    }

Edit: I get a weird rendering now in the html when testing the website.  if you look at the page source code, I see:

System.Collections.Generic.List`1[System.String] List<Area>

Body:
Your view is expecting a model of type List<Namespace.toModel> but the type of the outcomeAreas variable passed to it appears to be either IEnumerable<OutcomeArea> or IQueryable<OutcomeArea>

Try changing Checklist.cshtml to have this at the top:

@Model List<OutcomeArea>

And then change your controller action to return:

return PartialView("Checklist", outcomeAreas.ToList());

Edit: Just noticed that you're doing .Select(oa => oa.Area), so you'll actually want to use whatever type the 'Area' property is. @Model List<Area> or @Model List<string> if it's a string, etc..


答:
Condition variables unlock the lock they are passed internally during the wait, and relock it before they return.

The general pattern for a condition variable is a triplet of mutex, condition variable, and message.

The listener locks the mutex, then spins on the cv.wait(lck) until it detects a message.  It leaves the .wait spin with the mutex locked, and can process the message (which could involve modifying it).

The sender locks the mutex, modifies the message, optionally unlocks the mutex, then does a cv.notify of some kind (depending on how many it wants to wake up).

While cv.wait(lck) the lck is sometimes unlocked, including when they are suspended waiting for a signal.

So what actually happens is that a bunch of threads all line up on the condition variable with the mutex unlocked.

The main thread then gets the lock, sets the message (ready=true), then does a .notify_all().

In practice, the main thread might set the message & .notify_all() before one of the listening threads manages to reach the cv.wait(lck).  There is no problem, because if .notify_all() has been called, the ready=true was sequenced-before, so the listening thread will not .wait as the while(!ready) loop is while(false).

Title: Mutex locking between multiple threads

Body:
I am a chip designer and we use mutex in our circuits all the time for atomic memory accesses. I am learning to code in CPP and I am having hard time understanding how the Mutex works in CPP.

I understand that any program is a process and threads under a process have their own local objects, in addition to global objects that are accessible from any thread under this process.

In my attempt to understand mutex more intimately, I found this example at http://www.cplusplus.com/reference/condition_variable/condition_variable/

1  // condition_variable example
2  #include <iostream>           // std::cout
3  #include <thread>             // std::thread
4  #include <mutex>              // std::mutex, std::unique_lock
5  #include <condition_variable> // std::condition_variable
6
7  std::mutex mtx;
8  std::condition_variable cv;
9  bool ready = false;
10
11 void print_id (int id) {
12   std::unique_lock<std::mutex> lck(mtx);
13   while (!ready) cv.wait(lck);
14   // ...
15   std::cout << "thread " << id << '\n';
16 }
17
18 void go() {
19   std::unique_lock<std::mutex> lck(mtx);
20   ready = true;
21   cv.notify_all();
22 }
23
24 int main ()
25 {
26   std::thread threads[10];
27   // spawn 10 threads:
28   for (int i=0; i<10; ++i)
29     threads[i] = std::thread(print_id,i);
30
31   std::cout << "10 threads ready to race...\n";
32   go();                       // go!
33
34   for (auto& th : threads) th.join();
35
36   return 0;
37 }

Possible output (thread order may vary):

10 threads ready to race...
thread 2
thread 0
thread 9
thread 4
thread 6
thread 8
thread 7
thread 5
thread 3
thread 1

In line 28 and 29, 10 threads are scheduled. All of them are trying to lock same mutex (mtx). As I understand, one of the 10 thread will get the lock and will wait at line 13, while other 9 threads will try to get the lock and get blocked at line 12 itself.

Then comes the call to function go() at line 32. Go() also is trying to get the lock for the same mutex at line 19. But it should not get it as one print_id() thread is owning the lock. As per my understanding, this should result in a deadlock as go() is blocked at line 19, and can't get past that line, and consequently, can't send the cv.notify_all();

But the result in the link claims otherwise. It shows that go() effortlessly acquired the lock and sent the notify that in turn started the domino effect on 10 threads.

What am I missing? Is there some specific rule embedded in CPP specification that is allowing go() function to acquire the lock from the thread that was owning it? I have spent many hours in net searching for an answer, but in vain.

I will really appreciate some explanation of this phenomenon.


问:
why onCallStateChanged() on Android is invoked more than one time in a single call？
I wanted to implement an app that prevents calls like a firewall. When I debug my app, I found that when there is a call in, the onCallStateChanged() function in interface PhoneStateListener is invoked three times. As a result, preventing one call can result in three logs. I'm so confused!!

my code:

```<code>    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        try {
            if (state == TelephonyManager.CALL_STATE_RINGING &&
                PhoneUtil.getITelephony(tpm).isRinging()) {
                String flag = isBlockCall(myContext, myHelper, myTypes, incomingNumber);
                if (flag.length() > 0) {
                    blockCall();
                    myHelper.insertLog(new String[] { flag, incomingNumber, String.valueOf(System.currentTimeMillis()), null });
                    showNotification(myContext, incomingNumber, System.currentTimeMillis());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        super.onCallStateChanged(state, incomingNumber);
    }
}, PhoneStateListener.LISTEN_CALL_STATE);
</code>```

答:
According to official documents

Callback invoked when device call state changes.

This means that whenever incoming call rings your phone, this will
change the state.

Incoming call is rejected, this will invoke a state change as well

Incoming call is picked up, state changes !

Finally no action, will also cause a state change

That is said, once a state is changed, it makes sense to be seen as fired twice upon any resulting reaction.

Body:
I wanted to implement an app that prevents calls like a firewall. When I debug my app, I found that when there is a call in, the onCallStateChanged() function in interface PhoneStateListener is invoked three times. As a result, preventing one call can result in three logs. I'm so confused!!

my code:

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        try {
            if (state == TelephonyManager.CALL_STATE_RINGING &&
                PhoneUtil.getITelephony(tpm).isRinging()) {
                String flag = isBlockCall(myContext, myHelper, myTypes, incomingNumber);
                if (flag.length() > 0) {
                    blockCall();
                    myHelper.insertLog(new String[] { flag, incomingNumber, String.valueOf(System.currentTimeMillis()), null });
                    showNotification(myContext, incomingNumber, System.currentTimeMillis());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        super.onCallStateChanged(state, incomingNumber);
    }
}, PhoneStateListener.LISTEN_CALL_STATE);


问:
sum only on certain dimension
I have a Fortran 90array (matrix) like:

REAL(8),DIMENSION(Xmax, Ymax, Zmax, Xmax, Ymax, Zmax) :: Mat

I read through my matrix in this way:

```<code>    DO X1=1,Xmax
      Do Y1=1,Ymax
        DO Z1=1,Zmax

           DO Xv=1,Xmax
              Do Yv=1,Ymax
                DO Zv=1,Zmax

                   Mat(X1, Y1, Z1, Xv, Yv, Zv)

           END DO
         END DO
        END DO
      END DO
    END DO
  END DO
</code>```

I would like to create a new matrix NewMat (dimension(Xmax, Ymax, Zmax) only) which will contain for each (Xv, Yv, Zv) the sum of all respectively (X1, Y1, Z1) from my initial matrix.

My question is: Do I need to iterate to sum? Or is there a way to use some function? what would be more efficient?

答:
You're almost certainly looking for the intrinsic sum function which can be used to reduce an array (by addition) from rank n to rank n-1.  So the expression

```<code> sum(mat, dim=6)
</code>```

will 'flatten' the 6th dimension of mat.  I'm not entirely sure that I understand exactly what you are trying to do, but the assignment

```<code> newmat = sum(sum(sum(mat, dim=6), dim=5), dim=4)
</code>```

might satisfy your needs.  I haven't got Fortran on this machine, and if I had I'd probably balk at setting up a rank-6 array to test it.  So, if it isn't quite what you want fiddle around until you get it..

This probably isn't any faster than nesting loops, and it's arguably harder to read, but it does look like it was written by someone who understands modern Fortran's array operations.

Title: sum only on certain dimension

Body:
I have a Fortran 90array (matrix) like:

REAL(8),DIMENSION(Xmax, Ymax, Zmax, Xmax, Ymax, Zmax) :: Mat

I read through my matrix in this way:

    DO X1=1,Xmax
      Do Y1=1,Ymax
        DO Z1=1,Zmax

           DO Xv=1,Xmax
              Do Yv=1,Ymax
                DO Zv=1,Zmax

                   Mat(X1, Y1, Z1, Xv, Yv, Zv)

           END DO
         END DO
        END DO
      END DO
    END DO
  END DO

I would like to create a new matrix NewMat (dimension(Xmax, Ymax, Zmax) only) which will contain for each (Xv, Yv, Zv) the sum of all respectively (X1, Y1, Z1) from my initial matrix.

My question is: Do I need to iterate to sum? Or is there a way to use some function? what would be more efficient?

Body:
You're almost certainly looking for the intrinsic sum function which can be used to reduce an array (by addition) from rank n to rank n-1.  So the expression

 sum(mat, dim=6)

will 'flatten' the 6th dimension of mat.  I'm not entirely sure that I understand exactly what you are trying to do, but the assignment

 newmat = sum(sum(sum(mat, dim=6), dim=5), dim=4)

might satisfy your needs.  I haven't got Fortran on this machine, and if I had I'd probably balk at setting up a rank-6 array to test it.  So, if it isn't quite what you want fiddle around until you get it..

This probably isn't any faster than nesting loops, and it's arguably harder to read, but it does look like it was written by someone who understands modern Fortran's array operations.


问:
TinyMCE set view -> show blocks
i like the show blocks feature under view - is there a way i can set it on as default when the editor loads

THank you

答:
I believe you want to set the visualblocks_default_state to true?

The documentation is your friend on this question:

https://www.tinymce.com/docs/plugins/visualblocks/#visualblocks_default_state

Title: TinyMCE set view -> show blocks


问:
Please explain me the below query
I have Mysql query to be used in a php script. I just need to know how is it processing and producing output..</p>

```<code>$sql = "SELECT events_id, events_name, control_id, (TO_DAYS(events_when) - TO_DAYS(NOW())) dayto "
      ."FROM events "
      ."WHERE events_active = 1 AND events_start = 1 AND "
      ." (TO_DAYS(events_when) - TO_DAYS(NOW())) IN $noticeeventsday ";
</code>```

答:
It is hard to explain the query as it relates to you/your project/code without understanding the context, and whether you are experiencing a trouble with the SQL which you wish resolved.

What are you trying to do?

What is the underlying data structure?

How are your tables configured?

This considered:

What is the content of
$noticeeventsday

Are you asking how to handle the
returned results of the query? Or how the SQL actually functions/operates on your DB?

Title: Please explain me the below query

Body:
I have Mysql query to be used in a php script. I just need to know how is it processing and producing output..

$sql = "SELECT events_id, events_name, control_id, (TO_DAYS(events_when) - TO_DAYS(NOW())) dayto "
      ."FROM events "
      ."WHERE events_active = 1 AND events_start = 1 AND "
      ." (TO_DAYS(events_when) - TO_DAYS(NOW())) IN $noticeeventsday ";


问:
How can I insert a character after every 2 characters?
I want to insert a slash after every two characters, but just for the first two instances. The following regex inserts after every occurrence. Does anyone know how to limit it to two occurrences? The amount will be entered by the user through an input element. So if a user entered 30032017 it would be something like the following.

```<code>function insertSlash(val) {
    return val.match(new RegExp('.{1,2}', 'g')).join("/");
}

insertSlash(input);
</code>```

so for the first character the user would enter 3. On the next input it will be 0. this should then insert a slash.

this should then return 30/03/2017.

答:
It's easier if you slice the string when you know the specific character positions:</p>

```<code>return val.slice(0, 2) + "/" + val.slice(2, 4) + "/" + val.slice(4)
</code>```

Body:
I want to insert a slash after every two characters, but just for the first two instances. The following regex inserts after every occurrence. Does anyone know how to limit it to two occurrences? The amount will be entered by the user through an input element. So if a user entered 30032017 it would be something like the following.

function insertSlash(val) {
    return val.match(new RegExp('.{1,2}', 'g')).join("/");
}

insertSlash(input);

so for the first character the user would enter 3. On the next input it will be 0. this should then insert a slash.

this should then return 30/03/2017.

Body:
It's easier if you slice the string when you know the specific character positions:

return val.slice(0, 2) + "/" + val.slice(2, 4) + "/" + val.slice(4)


问:
Already used one ng-view, should I use ng-include now?
I am creating a SPA using Angular 1.

User will have a login template to access the portal.

Now on this portal, user will be able to perform CRUD operations.

for switching templates during CRUD operations, I'm already using ng-view in particular div.
Now I'm confused what should I use to switch template inside  with login, register and portal template. One options is ng-include.

Please share a better approach if you have.

答: Used nested and multiple views using ui-router, worked like charm.


问:
Golang interface conversion error when trying to iterate through map of json array
I'm having an issue when I'm try to iterate through a map of some json.

The original JSON data looks like this:

```<code>"dataArray": [
    {
      "name": "default",
      "url": "/some/url"
    },
    {
      "name": "second",
      "url": "/another/url"
    }
]
</code>```

the map looks like this:

```<code>[map[name:default url:/some/url] map[name:second url:/another/url]]
</code>```

The code looks like this:

```<code>for _, urlItem := range item.(map[string]interface{}){
   do some stuff
}
</code>```

This normally works when it's a JSON object, but this is an array in the JSON and I get the following error:

panic: interface conversion: interface {} is []interface {}, not map[string]interface {}

Any help would be greatly appreciated

答:
The error is :

panic: interface conversion: interface {} is []interface {}, not
  map[string]interface {}

in your code you're converting item into map[string]interface{} :

```<code>for _, urlItem := range item.(map[string]interface{}){
   do some stuff
}
</code>```

But the actual item is []interface {} : change your covert type to this.

Because as you can see your result data is :

```<code>[map[name:default url:/some/url] map[name:second url:/another/url]]
</code>```

it is an array that has map. not map.

First you can convert your data to []interface{} and then get the index of that and convert it to map[string]interface{}.
so an example will look like this :

```<code>data := item.([]interface{})
for _,value := range data{
  yourMap := value.(map[string]interface{})
  //name value
  name := yourMap["name"].(string) // and so on
}
</code>```

Body:
I'm having an issue when I'm try to iterate through a map of some json.

The original JSON data looks like this:

"dataArray": [
    {
      "name": "default",
      "url": "/some/url"
    },
    {
      "name": "second",
      "url": "/another/url"
    }
]

the map looks like this:

[map[name:default url:/some/url] map[name:second url:/another/url]]

The code looks like this:

for _, urlItem := range item.(map[string]interface{}){
   do some stuff
}

This normally works when it's a JSON object, but this is an array in the JSON and I get the following error:

panic: interface conversion: interface {} is []interface {}, not map[string]interface {}

Any help would be greatly appreciated

Body:
The error is :

panic: interface conversion: interface {} is []interface {}, not
  map[string]interface {}

in your code you're converting item into map[string]interface{} :

for _, urlItem := range item.(map[string]interface{}){
   do some stuff
}

But the actual item is []interface {} : change your covert type to this.

Because as you can see your result data is :

[map[name:default url:/some/url] map[name:second url:/another/url]]

it is an array that has map. not map.

First you can convert your data to []interface{} and then get the index of that and convert it to map[string]interface{}.
so an example will look like this :

data := item.([]interface{})
for _,value := range data{
  yourMap := value.(map[string]interface{})
  //name value
  name := yourMap["name"].(string) // and so on
}


问:
iOS - System Alert Location use in Background
Sometimes I get an alert message, reminding me that my App is using the location service in the background.

If I read the Official Documentation, in the Give apps permission to use your Location section.

Other apps will ask for access to your location even when the app isn't in use. When you allow an app to always use your location, iOS will remind you which apps are able to use your location after an app uses your location in the background.

We can clearly admit that this alert will only be displayed when your App is using your location in the background.

So why am I asking this question ? Because this alert message just appeared when I woke up my phone, with no Apps in Background (all Apps were swiped up from the double tap Home button).

Does Background has other definition or maybe I am missing something?

答:
Your app can be woken up (launched implicitly) by the system depending on the background modes it supports.

Even if you manually kill it in memory by swiping up, it still can be triggered in background if there is an incoming data for it to process (such as silent notification with payload).


问:
Xcode8.3 constantly crashes after update
After update Xcode 8.3 is crashing constantly. At start it was 30 to 40 minutes but today it is crashing after just 10 seconds. Any help will be highly appreciated. Below is crash report.</p>

```<code>Process:               Xcode [555]
Path:                  /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:            com.apple.dt.Xcode
Version:               8.3 (12169)
Build Info:            IDEFrameworks-12169000000000000~2
App Item ID:           497799835
App External ID:       821487965
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [555]
User ID:               501

Date/Time:             2017-03-29 17:52:50.427 +0500
OS Version:            Mac OS X 10.12.4 (16E195)
Report Version:        12
Anonymous UUID:        C95FFD88-0B61-915D-E373-1F31A265D400

Time Awake Since Boot: 250 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
MainQueue: _compat_sourcekitd_set_notification_handler_block_invoke_2
ProductBuildVersion: 8E162
ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-12150/DVTFoundation/FilePaths/DVTFilePath.m:905
Details:  Path must be absolute but is not: <built-in>
Object:   <DVTFilePath>
Method:   +filePathForPathString:
Thread:   <NSThread: 0x7fc33ae02970>{number = 1, name = main}
</code>```

答:
I have experienced a similar issue, with Xcode 8.3, and it was crashing shortly after I began to edit my code in any swift files in my project, editing Objective-C files never caused a crash

There are a few steps that seems to help with fixing the issue:

Quit Xcode

Delete xcuserdata folder (Navigate to your project in Finder, right click on YourProject.xcworkspace, choose Show package contents, then delete xcuserdata folder).

Delete DerivedData

I'm not 100% sure you need to actually quit Xcode before deleting these though.

Body:
After update Xcode 8.3 is crashing constantly. At start it was 30 to 40 minutes but today it is crashing after just 10 seconds. Any help will be highly appreciated. Below is crash report.

Process:               Xcode [555]
Path:                  /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:            com.apple.dt.Xcode
Version:               8.3 (12169)
Build Info:            IDEFrameworks-12169000000000000~2
App Item ID:           497799835
App External ID:       821487965
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [555]
User ID:               501

Date/Time:             2017-03-29 17:52:50.427 +0500
OS Version:            Mac OS X 10.12.4 (16E195)
Report Version:        12
Anonymous UUID:        C95FFD88-0B61-915D-E373-1F31A265D400

Time Awake Since Boot: 250 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
MainQueue: _compat_sourcekitd_set_notification_handler_block_invoke_2
ProductBuildVersion: 8E162
ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-12150/DVTFoundation/FilePaths/DVTFilePath.m:905
Details:  Path must be absolute but is not: <built-in>
Object:   <DVTFilePath>
Method:   +filePathForPathString:
Thread:   <NSThread: 0x7fc33ae02970>{number = 1, name = main}