问:
May a call to std::lock pass a resource that is already locked by the calling thread?
I was researching possible implementations for the std::lock function and stumbled upon an implementation posted on the code review community.

Quoting the accepted answer (emphasis mine):

No this does not meet the definition of std::lock().

It (std::lock) guarantees that no matter what order you specify the
  locks in the parameter list you will not fall into a deadlock
  situation.

[...]

This also means that if a lock in the list is already locked it must
  be released so that the locks are acquired in the correct order.

I cannot find a conclusive answer whether or not the last statement is correct.

My question: is it allowed (i.e. defined behavior) to pass a locked resource, owned by the calling thread, as an argument to the standard std::lock function?

```<code>std::mutex m1, m2;
m1.lock();
std::lock(m1, m2);
</code>```

My gut feeling says this is actually not allowed. The function expects two or more Lockable objects and there is no way to check if a Lockable object is already locked by the current thread of execution. So it seems impossible to implement std::lock that way.

答: I guess you ask your questing regarding a second std::lock in the thread on the mutex that is already locked in the same thread before. If an already locked resource is recursive_mutex, it is allowed. If it is a general mutex, you reach a deadlock.</p>

Body:
I was researching possible implementations for the std::lock function and stumbled upon an implementation posted on the code review community.

Quoting the accepted answer (emphasis mine):

No this does not meet the definition of std::lock().

It (std::lock) guarantees that no matter what order you specify the
  locks in the parameter list you will not fall into a deadlock
  situation.

[...]

This also means that if a lock in the list is already locked it must
  be released so that the locks are acquired in the correct order.

I cannot find a conclusive answer whether or not the last statement is correct.

My question: is it allowed (i.e. defined behavior) to pass a locked resource, owned by the calling thread, as an argument to the standard std::lock function?

std::mutex m1, m2;
m1.lock();
std::lock(m1, m2);

My gut feeling says this is actually not allowed. The function expects two or more Lockable objects and there is no way to check if a Lockable object is already locked by the current thread of execution. So it seems impossible to implement std::lock that way.


来源: stackexchange

问:
pandas to_csv: suppress scientific notation in csv file when writing pandas to csv
I am writing a pandas df to a csv.  When I write it to a csv file, some of the elements in one of the columns are being incorrectly converted to scientific notation/numbers.  For example, col_1 has strings such as '104D59' in it.  The strings are mostly represented as strings in the csv file, as they should be.  However, occasional strings, such as '104E59', are being converted into scientific notation (e.g., 1.04 E 61) and represented as integers in the ensuing csv file.

I am trying to export the csv file into a software package (i.e., pandas -> csv -> software_new) and this change in data type is causing problems with that export.

Is there a way to write the df to a csv, ensuring that all elements in df['problem_col'] are represented as string in the resulting csv or not converted to scientific notation?

Here is the code I have used to write the pandas df to a csv:

```<code>df.to_csv('df.csv', encoding='utf-8')
</code>```

I also check the dtype of the problem column:

```<code>for df.dtype, df['problem_column'] is an object
</code>```

答:
If you would like to use the values as formated string in a list, say as part of csvfile csv.writier, the numbers can be formated before creating a list:</p>

```<code>with open('results_actout_file','w',newline='') as csvfile:
     resultwriter = csv.writer(csvfile, delimiter=',')
     resultwriter.writerow(header_row_list)

     resultwriter.writerow(df['label'].apply(lambda x: '%.17f' % x).values.tolist())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing a pandas df to a csv.  When I write it to a csv file, some of the elements in one of the columns are being incorrectly converted to scientific notation/numbers.  For example, col_1 has strings such as '104D59' in it.  The strings are mostly represented as strings in the csv file, as they should be.  However, occasional strings, such as '104E59', are being converted into scientific notation (e.g., 1.04 E 61) and represented as integers in the ensuing csv file.

I am trying to export the csv file into a software package (i.e., pandas -> csv -> software_new) and this change in data type is causing problems with that export.

Is there a way to write the df to a csv, ensuring that all elements in df['problem_col'] are represented as string in the resulting csv or not converted to scientific notation?

Here is the code I have used to write the pandas df to a csv:

df.to_csv('df.csv', encoding='utf-8')

I also check the dtype of the problem column:

for df.dtype, df['problem_column'] is an object

Body:
If you would like to use the values as formated string in a list, say as part of csvfile csv.writier, the numbers can be formated before creating a list:

with open('results_actout_file','w',newline='') as csvfile:
     resultwriter = csv.writer(csvfile, delimiter=',')
     resultwriter.writerow(header_row_list)

     resultwriter.writerow(df['label'].apply(lambda x: '%.17f' % x).values.tolist())

ContentLicense: CC BY-SA 3.0


问:
MYSQL Updating database using maths?
My query:

```<code>UPDATE `settings_products` SET `stock_osrs` = SUM(stock_osrs - 50)
</code>```

I have a stock system in my admin panel which currently displays stock levels set by the admins, but I am creating an API so every payment that has been completed will take away the stock.

Lets say that the ordered amount is "50" like in the query and I want to take this away from the stock_osrs.

How exactly would I go about doing this?

EDIT: I am aware that I could use PHP to do the calculations and then update the table from that, but I feel this will be less reliable as I would have to do "50,000" - 50 = "45,950" and post that number to the database.

In this time there could have been another order which would cause the code to mess up, hence that I need to use SQL to achieve this!

答:
I think you are just trying to do minus 50 on a field so this should work.</p>

```<code>UPDATE `settings_products` SET `stock_osrs` = `stock_osrs` - 50
</code>```

Title: MYSQL Updating database using maths?

Body:
My query:

UPDATE `settings_products` SET `stock_osrs` = SUM(stock_osrs - 50)

I have a stock system in my admin panel which currently displays stock levels set by the admins, but I am creating an API so every payment that has been completed will take away the stock.

Lets say that the ordered amount is "50" like in the query and I want to take this away from the stock_osrs.

How exactly would I go about doing this?

EDIT: I am aware that I could use PHP to do the calculations and then update the table from that, but I feel this will be less reliable as I would have to do "50,000" - 50 = "45,950" and post that number to the database.

In this time there could have been another order which would cause the code to mess up, hence that I need to use SQL to achieve this!

Body:
I think you are just trying to do minus 50 on a field so this should work.

UPDATE `settings_products` SET `stock_osrs` = `stock_osrs` - 50


答:
use this query this might solve your problem .

you can simply execute mathematical operation directly.

```<code>UPDATE settings_product SET stock_osrs=stock_osrs-50;
</code>```

i have verified the above query it worked ,try it

Title: MYSQL Updating database using maths?

Body:
use this query this might solve your problem .

you can simply execute mathematical operation directly.

UPDATE settings_product SET stock_osrs=stock_osrs-50;

i have verified the above query it worked ,try it


问:
Alter css keyframe properties at runtime
I have a simple keyframe animation which grows a dot and transforms the background into blue. How can I dynamically alter this background color?

```<code>@keyframes growDot {
    100% {
        background-color: #23b7e5;
        -webkit-transform: scale3d(0.9, 0.9, 0.9);
        transform: scale3d(0.9, 0.9, 0.9);
    }
}
</code>```

Obviously, something like $('keyframes growDot').css("background-color", "#FF00B0"); is not working.

答:
If the animation depends on the background-color, you can do the following. I am not sure how performance-wise this is, but I can I go with dynamic
<input type="color" id="c" value="#23b7e5"/>

```

Body:
I have a simple keyframe animation which grows a dot and transforms the background into blue. How can I dynamically alter this background color?

@keyframes growDot {
    100% {
        background-color: #23b7e5;
        -webkit-transform: scale3d(0.9, 0.9, 0.9);
        transform: scale3d(0.9, 0.9, 0.9);
    }
}

Obviously, something like $('keyframes growDot').css("background-color", "#FF00B0"); is not working.

Body:
If the animation depends on the background-color, you can do the following. I am not sure how performance-wise this is, but I can I go with dynamic <style> tag, and replace its content on will.

var c = $('#c'),
    style = $('#animation'),
    color = '#23b7e5';

c.on('change', function(){

    color = this.value;
    style.html( buildStyle() );

}).trigger('change');

function buildStyle(){

  return ['@keyframes growDot {  100% {',
                   'background-color: ' + color + ';',
                   '-webkit-transform: scale3d(0.9, 0.9, 0.9);',
                   'transform: scale3d(0.9, 0.9, 0.9);',
           '}'].join('');

}

.a {
 width:100px;
 height:100px;
 animation: 2s growDot infinite;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<style id="animation"></style>
<input type="color" id="c" value="#23b7e5"/>
<div class="a"></div>


问:
Call classes by body class
Is it possible to call more classes inside a body class? I have an example.

I have an body class "class-for-body". With this body class I specify other classes on that page only. What I always do is like this:

```<code>body.class-for-body .other-class,
body.class-for-body .other-class-new,
body.class-for-body .other-class-more,
body.class-for-body .other-class-left {
    styling shizzle
}
</code>```

But I also have an body with class "class-for-newbody" with the same subclasses:

```<code>body.class-for-newbody .other-class,
body.class-for-newbody .other-class-new,
body.class-for-newbody .other-class-more,
body.class-for-newbody .other-class-left {
    styling shizzle
}
</code>```

Is there a way to call them together?

Regards,
Robert

答:
You could also use wildcard selectors, for example ...</p>

```<code>body[class*='class-for-'] {
  /* todo */
}
</code>```

Title: Call classes by body class

Body:
Is it possible to call more classes inside a body class? I have an example.

I have an body class "class-for-body". With this body class I specify other classes on that page only. What I always do is like this:

body.class-for-body .other-class,
body.class-for-body .other-class-new,
body.class-for-body .other-class-more,
body.class-for-body .other-class-left {
    styling shizzle
}

But I also have an body with class "class-for-newbody" with the same subclasses:

body.class-for-newbody .other-class,
body.class-for-newbody .other-class-new,
body.class-for-newbody .other-class-more,
body.class-for-newbody .other-class-left {
    styling shizzle
}

Is there a way to call them together?

Regards,
Robert

Body:
You could also use wildcard selectors, for example ...

body[class*='class-for-'] {
  /* todo */
}


问:
split strings into two columns
I am working with someone else's data with a column for which possible values are "short" and "long". Unfortunately, the data creator also added letters and question marks after those words to annotate certain things, that I want to split into a separate column. Here's some fake data to work with:

```<code>vars <- c('long','short','longG','short?','short?F','long?G')
species <- c('sp1','sp2','sp3','sp4','sp5','sp6')
testdf <- cbind(vars, species)
</code>```

I would like to split the vars column into the actual value long or short, and a new column with just the annotated characters. I can get halfway there with the following, which correctly produces a new column with just the annotating characters:

```<code>testdf %>% mutate(notes = gsub('long|short',"",vars)
</code>```

But I can't figure out how to split or subset var such that I get a column that just says short or long.

Thanks in advance for the help, SO community! ^_^

答:
It's difficult to extract pieces of a string in base R. Using stringr instead:

```<code>library(stringr)
str_extract(vars, 'long|short')
# [1] "long"  "short" "long"  "short" "short" "long"
</code>```

(You can use it in mutate or however else.)

So your complete example (I would parametrize the pattern for good measure)

```<code>pattern = "long|short"
mutate(testdf,
   notes = gsub(pattern, "", vars),
   notes2 = str_replace(vars, pattern, ""), # stringr alternative for consistent syntax
   ls = str_extract(vars, pattern))
</code>```

Title: split strings into two columns

Body:
I am working with someone else's data with a column for which possible values are "short" and "long". Unfortunately, the data creator also added letters and question marks after those words to annotate certain things, that I want to split into a separate column. Here's some fake data to work with:

vars <- c('long','short','longG','short?','short?F','long?G')
species <- c('sp1','sp2','sp3','sp4','sp5','sp6')
testdf <- cbind(vars, species)

I would like to split the vars column into the actual value long or short, and a new column with just the annotated characters. I can get halfway there with the following, which correctly produces a new column with just the annotating characters:

testdf %>% mutate(notes = gsub('long|short',"",vars)

But I can't figure out how to split or subset var such that I get a column that just says short or long.

Thanks in advance for the help, SO community! ^_^

Body:
It's difficult to extract pieces of a string in base R. Using stringr instead:

library(stringr)
str_extract(vars, 'long|short')
# [1] "long"  "short" "long"  "short" "short" "long"

(You can use it in mutate or however else.)

So your complete example (I would parametrize the pattern for good measure)

pattern = "long|short"
mutate(testdf,
   notes = gsub(pattern, "", vars),
   notes2 = str_replace(vars, pattern, ""), # stringr alternative for consistent syntax
   ls = str_extract(vars, pattern))


问:
Purpose of PHP use keyword in array_map() function?
I've the following code of lines in my application.
Can anybody please tell me what is the purpose of use keyword in the following array_map() function?

```<code>array_map( function($record) use ($edit_form, $otherfields, $otherfields_keys)
{
    User::parseData($record, $edit_form['metadata']);

    if (isset($otherfields[$record['user_id']])) {
        return $record + $otherfields[$record['user_id']];
    }

    return $record + $otherfields_keys;

}, $records);
</code>```

Thanks in advance.

答:
The callback passed to array_map() doesn't have access to outside variables so they must be passed using use.

You can read more about anonymous functions in the PHP documentation.

Body:
I've the following code of lines in my application.
Can anybody please tell me what is the purpose of use keyword in the following array_map() function?

array_map( function($record) use ($edit_form, $otherfields, $otherfields_keys)
{
    User::parseData($record, $edit_form['metadata']);

    if (isset($otherfields[$record['user_id']])) {
        return $record + $otherfields[$record['user_id']];
    }

    return $record + $otherfields_keys;

}, $records);

Thanks in advance.


问:
How To Open Another of Our iOS Apps With Branch.io DeepLink From an iOS App
We have two iOS apps under our control. Let’s call them apps ABC and XYZ. Using the Branch.io SDK, we want to know how to:

Programmatically (Swift) create a deferred deep link inside of app ABC with the goal of taking the user to app XYZ. We would be using an existing URL Scheme for app XYZ since the backend server is not involved at all right now with this effort.

We want the Branch.io deep link to activate when a UIButton has been tapped (so no WebView involved here. Just a native button)

We want to pass along a 20ish long ID (letters and digits) and perhaps login information (if we can do it safely and securely) to the receiving app aka XYZ app.

We’ve followed the steps at https://docs.branch.io/pages/apps/ios/ to ensure the basics work. This includes the “Test deep link” section. That worked fine.

I believe I have read every single API document related to iOS and the Dashboard that Branch.io provides.

The most interesting ones to me for this quest were:

iOS specific

Branch Concepts: The Branch Universal Object

Configure your dashboard

Scanned pages of the Branch.io blog too

Code is here (with content changed so as to not identify which apps in the real world we're talking about since that's not important):

```<code>    private class func createBranchIoLink(someIdentifier: String) {

        // Create content reference
        let buo = BranchUniversalObject(canonicalIdentifier: "content/\(someIdentifier)")
        buo.canonicalUrl = "xyz://content/\(someIdentifier)" // example is https://example.com/content/123
        buo.title = "Some Title"
        buo.contentDescription = "Add it to the other app"

        // Create link reference
        let lp: BranchLinkProperties = BranchLinkProperties()
        lp.channel = "ios"
        lp.feature = "some-feature"

        buo.getShortUrl(with: lp) { (url, error) in
            print(url ?? "")
            print(error ?? "")
            print("ok done")
            // when I take the url given to us here, the URL takes me back to THIS app instead of the app I want!
        }
    }
</code>```

Any help you can offer is appreciated. Thanks!

答:
Brian from Branch here!

You can generate links within app ABC to open app XYZ, but this also means that you will not be able to generate links that open app ABC. To achieve this flow, you would need to integrate the Branch SDK into both iOS apps, but create one app for XYZ on your Branch dashboard.

Here are some things to keep in mind:

Set up Branch dashboard for app XYZ (https://docs.branch.io/pages/dashboard/integrate/)

Integrate the Branch SDK for app XYZ (https://docs.branch.io/pages/apps/ios/)

Integrate the Branch SDK for app ABC, but use the Live key provided on your Branch dashboard for app XYZ

This basically creates links that are specific to app XYZ and should open that app if the URI Scheme and Universal Links are set up properly and consistent with the Branch dashboard for app XYZ. App ABC only needs the Branch key to generate the links, and the Entitlements file or Info.plist does not need to be modified for app ABC.

I hope this helps!

Body:
We have two iOS apps under our control. Let’s call them apps ABC and XYZ. Using the Branch.io SDK, we want to know how to:

Programmatically (Swift) create a deferred deep link inside of app ABC with the goal of taking the user to app XYZ. We would be using an existing URL Scheme for app XYZ since the backend server is not involved at all right now with this effort.

We want the Branch.io deep link to activate when a UIButton has been tapped (so no WebView involved here. Just a native button)

We want to pass along a 20ish long ID (letters and digits) and perhaps login information (if we can do it safely and securely) to the receiving app aka XYZ app.

We’ve followed the steps at https://docs.branch.io/pages/apps/ios/ to ensure the basics work. This includes the “Test deep link” section. That worked fine.

I believe I have read every single API document related to iOS and the Dashboard that Branch.io provides.

The most interesting ones to me for this quest were:

iOS specific

Branch Concepts: The Branch Universal Object

Configure your dashboard

Scanned pages of the Branch.io blog too

Code is here (with content changed so as to not identify which apps in the real world we're talking about since that's not important):

    private class func createBranchIoLink(someIdentifier: String) {

        // Create content reference
        let buo = BranchUniversalObject(canonicalIdentifier: "content/\(someIdentifier)")
        buo.canonicalUrl = "xyz://content/\(someIdentifier)" // example is https://example.com/content/123
        buo.title = "Some Title"
        buo.contentDescription = "Add it to the other app"

        // Create link reference
        let lp: BranchLinkProperties = BranchLinkProperties()
        lp.channel = "ios"
        lp.feature = "some-feature"

        buo.getShortUrl(with: lp) { (url, error) in
            print(url ?? "")
            print(error ?? "")
            print("ok done")
            // when I take the url given to us here, the URL takes me back to THIS app instead of the app I want!
        }
    }

Any help you can offer is appreciated. Thanks!


问:
Failing to install python-igraph
I'm trying to install python-igraph. After I run sudo pip install python-igraph I got the following log:

```<code>Downloading/unpacking python-igraph
  Downloading python-igraph-0.7.1-1.tar.gz (375kB): 375kB downloaded
  Running setup.py egg_info for package python-igraph

Installing collected packages: python-igraph
  Running setup.py install for python-igraph
    Cannot find the C core of igraph on this system using pkg-config.
    We will now try to download and compile the C core from scratch.
    Version number of the C core: 0.7.1-1

    Version 0.7.1-1 of the C core of igraph is not found among the nightly builds.
    Use the --c-core-version switch to try a different version.

    Could not download and compile the C core of igraph.

    WARNING: we were not able to detect where igraph is installed on
    your machine (if it is installed at all). We will use the fallback
    library and include pathss hardcoded in setup.py and hope that the
    C core of igraph is installed there.

    If the compilation fails and you are sure that igraph is installed
    on your machine, adjust the following two variables in setup.py
    accordingly and try again:

    - LIBIGRAPH_FALLBACK_INCLUDE_DIRS
    - LIBIGRAPH_FALLBACK_LIBRARY_DIRS

Build type: dynamic extension
    Include path: /usr/include/igraph /usr/local/include/igraph
    Library path:
    Linked dynamic libraries: igraph
    Linked static libraries:
    Extra compiler options:
    Extra linker options:
    building 'igraph._igraph' extension
    x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/igraph -I/usr/local/include/igraph -I../../build/include -I../../include -I/usr/local/include/igraph -I/usr/include/igraph -I/usr/include/python2.7 -c src/igraphmodule.c -o build/temp.linux-x86_64-2.7/src/igraphmodule.o
    src/igraphmodule.c:25:20: fatal error: igraph.h: No such file or directory
     #include <igraph.h>
                        ^
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
    Complete output from command /usr/bin/python -c "import setuptools;__file__='/tmp/pip_build_root/python-igraph/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-cTa4Ba-record/install-record.txt --single-version-externally-managed:
    running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.7

creating build/lib.linux-x86_64-2.7/igraph

copying igraph/formula.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/__init__.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/configuration.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/summary.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/layout.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/cut.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/datatypes.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/utils.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/clustering.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/statistics.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/matching.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/compat.py -> build/lib.linux-x86_64-2.7/igraph

creating build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/operators.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/isomorphism.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/__init__.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/colortests.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/conversion.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/homepage.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/attributes.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/vertexseq.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/structural.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/separators.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/atlas.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/layouts.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/rng.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/games.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/utils.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/iterators.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/edgeseq.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/indexing.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/spectral.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/cliques.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/flow.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/basic.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/generators.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/matching.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/foreign.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/bipartite.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/decomposition.py -> build/lib.linux-x86_64-2.7/igraph/test

creating build/lib.linux-x86_64-2.7/igraph/app

copying igraph/app/__init__.py -> build/lib.linux-x86_64-2.7/igraph/app

copying igraph/app/shell.py -> build/lib.linux-x86_64-2.7/igraph/app

creating build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/__init__.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/edge.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/shapes.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/coord.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/metamagic.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/utils.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/text.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/graph.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/colors.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/vertex.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/baseclasses.py -> build/lib.linux-x86_64-2.7/igraph/drawing

creating build/lib.linux-x86_64-2.7/igraph/remote

copying igraph/remote/__init__.py -> build/lib.linux-x86_64-2.7/igraph/remote

copying igraph/remote/nexus.py -> build/lib.linux-x86_64-2.7/igraph/remote

copying igraph/remote/gephi.py -> build/lib.linux-x86_64-2.7/igraph/remote

creating build/lib.linux-x86_64-2.7/igraph/vendor

copying igraph/vendor/__init__.py -> build/lib.linux-x86_64-2.7/igraph/vendor

copying igraph/vendor/texttable.py -> build/lib.linux-x86_64-2.7/igraph/vendor

running build_ext

Cannot find the C core of igraph on this system using pkg-config.

We will now try to download and compile the C core from scratch.

Version number of the C core: 0.7.1-1

Version 0.7.1-1 of the C core of igraph is not found among the nightly builds.

Use the --c-core-version switch to try a different version.

Could not download and compile the C core of igraph.

WARNING: we were not able to detect where igraph is installed on

your machine (if it is installed at all). We will use the fallback

library and include pathss hardcoded in setup.py and hope that the

C core of igraph is installed there.

If the compilation fails and you are sure that igraph is installed

on your machine, adjust the following two variables in setup.py

accordingly and try again:

- LIBIGRAPH_FALLBACK_INCLUDE_DIRS

- LIBIGRAPH_FALLBACK_LIBRARY_DIRS

Build type: dynamic extension

Include path: /usr/include/igraph /usr/local/include/igraph

Library path:

Linked dynamic libraries: igraph

Linked static libraries:

Extra compiler options:

Extra linker options:

building 'igraph._igraph' extension

creating build/temp.linux-x86_64-2.7

creating build/temp.linux-x86_64-2.7/src

x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/igraph -I/usr/local/include/igraph -I../../build/include -I../../include -I/usr/local/include/igraph -I/usr/include/igraph -I/usr/include/python2.7 -c src/igraphmodule.c -o build/temp.linux-x86_64-2.7/src/igraphmodule.o

src/igraphmodule.c:25:20: fatal error: igraph.h: No such file or directory

 #include <igraph.h>

                    ^

compilation terminated.

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools;__file__='/tmp/pip_build_root/python-igraph/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-cTa4Ba-record/install-record.txt --single-version-externally-managed failed with error code 1 in /tmp/pip_build_root/python-igraph
Storing complete log in /home/sergey/.pip/pip.log
</code>```

And I have similar situation if I do it with sudo python setup.py install.

Apparently the problem is with C core.

How can I install the correct version of it so that I can install igraph?

I use Linux Mint 16 64-bit, python 2.7.

答:
Using Ubuntu 16 and Python3.

```<code>pip3 install python-igraph
</code>```

results in error building whell. However,

```<code>sudo apt-get install python3-igraph
</code>```

worked just fine.

Title: Failing to install python-igraph

Body:
I'm trying to install python-igraph. After I run sudo pip install python-igraph I got the following log:

Downloading/unpacking python-igraph
  Downloading python-igraph-0.7.1-1.tar.gz (375kB): 375kB downloaded
  Running setup.py egg_info for package python-igraph

Installing collected packages: python-igraph
  Running setup.py install for python-igraph
    Cannot find the C core of igraph on this system using pkg-config.
    We will now try to download and compile the C core from scratch.
    Version number of the C core: 0.7.1-1

    Version 0.7.1-1 of the C core of igraph is not found among the nightly builds.
    Use the --c-core-version switch to try a different version.

    Could not download and compile the C core of igraph.

    WARNING: we were not able to detect where igraph is installed on
    your machine (if it is installed at all). We will use the fallback
    library and include pathss hardcoded in setup.py and hope that the
    C core of igraph is installed there.

    If the compilation fails and you are sure that igraph is installed
    on your machine, adjust the following two variables in setup.py
    accordingly and try again:

    - LIBIGRAPH_FALLBACK_INCLUDE_DIRS
    - LIBIGRAPH_FALLBACK_LIBRARY_DIRS

Build type: dynamic extension
    Include path: /usr/include/igraph /usr/local/include/igraph
    Library path:
    Linked dynamic libraries: igraph
    Linked static libraries:
    Extra compiler options:
    Extra linker options:
    building 'igraph._igraph' extension
    x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/igraph -I/usr/local/include/igraph -I../../build/include -I../../include -I/usr/local/include/igraph -I/usr/include/igraph -I/usr/include/python2.7 -c src/igraphmodule.c -o build/temp.linux-x86_64-2.7/src/igraphmodule.o
    src/igraphmodule.c:25:20: fatal error: igraph.h: No such file or directory
     #include <igraph.h>
                        ^
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
    Complete output from command /usr/bin/python -c "import setuptools;__file__='/tmp/pip_build_root/python-igraph/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-cTa4Ba-record/install-record.txt --single-version-externally-managed:
    running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.7

creating build/lib.linux-x86_64-2.7/igraph

copying igraph/formula.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/__init__.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/configuration.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/summary.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/layout.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/cut.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/datatypes.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/utils.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/clustering.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/statistics.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/matching.py -> build/lib.linux-x86_64-2.7/igraph

copying igraph/compat.py -> build/lib.linux-x86_64-2.7/igraph

creating build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/operators.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/isomorphism.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/__init__.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/colortests.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/conversion.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/homepage.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/attributes.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/vertexseq.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/structural.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/separators.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/atlas.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/layouts.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/rng.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/games.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/utils.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/iterators.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/edgeseq.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/indexing.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/spectral.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/cliques.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/flow.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/basic.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/generators.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/matching.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/foreign.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/bipartite.py -> build/lib.linux-x86_64-2.7/igraph/test

copying igraph/test/decomposition.py -> build/lib.linux-x86_64-2.7/igraph/test

creating build/lib.linux-x86_64-2.7/igraph/app

copying igraph/app/__init__.py -> build/lib.linux-x86_64-2.7/igraph/app

copying igraph/app/shell.py -> build/lib.linux-x86_64-2.7/igraph/app

creating build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/__init__.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/edge.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/shapes.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/coord.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/metamagic.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/utils.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/text.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/graph.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/colors.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/vertex.py -> build/lib.linux-x86_64-2.7/igraph/drawing

copying igraph/drawing/baseclasses.py -> build/lib.linux-x86_64-2.7/igraph/drawing

creating build/lib.linux-x86_64-2.7/igraph/remote

copying igraph/remote/__init__.py -> build/lib.linux-x86_64-2.7/igraph/remote

copying igraph/remote/nexus.py -> build/lib.linux-x86_64-2.7/igraph/remote

copying igraph/remote/gephi.py -> build/lib.linux-x86_64-2.7/igraph/remote

creating build/lib.linux-x86_64-2.7/igraph/vendor

copying igraph/vendor/__init__.py -> build/lib.linux-x86_64-2.7/igraph/vendor

copying igraph/vendor/texttable.py -> build/lib.linux-x86_64-2.7/igraph/vendor

running build_ext

Cannot find the C core of igraph on this system using pkg-config.

We will now try to download and compile the C core from scratch.

Version number of the C core: 0.7.1-1

Version 0.7.1-1 of the C core of igraph is not found among the nightly builds.

Use the --c-core-version switch to try a different version.

Could not download and compile the C core of igraph.

WARNING: we were not able to detect where igraph is installed on

your machine (if it is installed at all). We will use the fallback

library and include pathss hardcoded in setup.py and hope that the

C core of igraph is installed there.

If the compilation fails and you are sure that igraph is installed

on your machine, adjust the following two variables in setup.py

accordingly and try again:

- LIBIGRAPH_FALLBACK_INCLUDE_DIRS

- LIBIGRAPH_FALLBACK_LIBRARY_DIRS

Build type: dynamic extension

Include path: /usr/include/igraph /usr/local/include/igraph

Library path:

Linked dynamic libraries: igraph

Linked static libraries:

Extra compiler options:

Extra linker options:

building 'igraph._igraph' extension

creating build/temp.linux-x86_64-2.7

creating build/temp.linux-x86_64-2.7/src

x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/igraph -I/usr/local/include/igraph -I../../build/include -I../../include -I/usr/local/include/igraph -I/usr/include/igraph -I/usr/include/python2.7 -c src/igraphmodule.c -o build/temp.linux-x86_64-2.7/src/igraphmodule.o

src/igraphmodule.c:25:20: fatal error: igraph.h: No such file or directory

 #include <igraph.h>

                    ^

compilation terminated.

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools;__file__='/tmp/pip_build_root/python-igraph/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-cTa4Ba-record/install-record.txt --single-version-externally-managed failed with error code 1 in /tmp/pip_build_root/python-igraph
Storing complete log in /home/sergey/.pip/pip.log

And I have similar situation if I do it with sudo python setup.py install.

Apparently the problem is with C core.

How can I install the correct version of it so that I can install igraph?

I use Linux Mint 16 64-bit, python 2.7.

Body:
Using Ubuntu 16 and Python3.

pip3 install python-igraph

results in error building whell. However,

sudo apt-get install python3-igraph

worked just fine.


问:
How to use early stopping for training deep neural network in TensorFlow 1.4?
From some moment in the training process of a convolutional neural network, the cost function is not getting better. I want to define the condition to stop the training. I have found one solution using ValidationMonitor in TensorFlow 1.1. However, there is no way to do this in TensorFlow 1.4...

My question: How to use early stopping in TensorFlow 1.4, especially with Experiment and Estimator?

Please, checkout my code

答:
Since ValidationMonitor doesn't work well with distributed training, We decided not to implement it as a Hook. We're waiting for a distributed friendly version of it.

As a workaround you can wrap ValidationMonitor as a hook. Following code shows how to do it:

validation_hook = tf.contrib.learn.monitors.replace_monitors_with_hooks([validation_monitor], estimator)[0]


问:
Does an htaccess rewrite rule help prevent SQL Injection?
I have the following rule in htaccess:

```<code>RewriteRule ^([a-zA-Z0-9\-\_]+)/?$ test.php?&url=$1 [L]
</code>```

My question is this:

If I have the following URL http://www.example.com/this-is-a-title

Is the $url variable subject to SQL injection, or should I not worry about it because the RewriteRule only allows letters, numbers, dashes and underscores and not quotes or apostrophes or + signs?

Edit:
Follow up question

What is happening if this is the url? http://www.example.com/this'is"a+title

When I place that in the url bar I get a  404 error, but what is actually happening. Are the symbols' " + being ignored or stripped or what exactly?

答:
You should always consider yourself vulnerable to SQL injection attack if you don't properly sanitize your data before placing it into a query. Using an .htaccess rewrite is not and should never be considered a practice to prevent SQL injection.

Use mysql_real_escape_string or pg_escape_string (if using PHP) or use prepared statements on all queries using variables from a POST or GET. Always.

ContentLicense: CC BY-SA 2.5

Body:
I have the following rule in htaccess:

RewriteRule ^([a-zA-Z0-9\-\_]+)/?$ test.php?&url=$1 [L]

My question is this:

If I have the following URL http://www.example.com/this-is-a-title

Is the $url variable subject to SQL injection, or should I not worry about it because the RewriteRule only allows letters, numbers, dashes and underscores and not quotes or apostrophes or + signs?

Edit:
Follow up question

What is happening if this is the url? http://www.example.com/this'is"a+title

When I place that in the url bar I get a  404 error, but what is actually happening. Are the symbols' " + being ignored or stripped or what exactly?


问:
Multiple Permission at once not working in android
I am trying to get 2 permissions at once but Iam unable to do so.

```<code>if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(context, Array<String>(2) {
            Manifest.permission.READ_CONTACTS;
            Manifest.permission.WRITE_EXTERNAL_STORAGE},
        1);
    }
}
</code>```

It only asks for WRITE_EXTERNAL_STORAGE permission and not READ_CONTACTS. Actually, If I write WRITE_EXTERNAL_STORAGE one first and READ_CONTACTS after that then it will only ask for contact and not WRITE_EXTERNAL_STORAGE.

答:
```<code>Array<String>(2) {
    Manifest.permission.READ_CONTACTS ;
    Manifest.permission.WRITE_EXTERNAL_STORAGE
}
</code>```

This initializer always returns WRITE_EXTERNAL_STORAGE, the first line does not do anything. You should probably be using the arrayOf function to construct the array instead.

Body:
I am trying to get 2 permissions at once but Iam unable to do so.

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(context, Array<String>(2) {
            Manifest.permission.READ_CONTACTS;
            Manifest.permission.WRITE_EXTERNAL_STORAGE},
        1);
    }
}

It only asks for WRITE_EXTERNAL_STORAGE permission and not READ_CONTACTS. Actually, If I write WRITE_EXTERNAL_STORAGE one first and READ_CONTACTS after that then it will only ask for contact and not WRITE_EXTERNAL_STORAGE.

Body:
Array<String>(2) {
    Manifest.permission.READ_CONTACTS ;
    Manifest.permission.WRITE_EXTERNAL_STORAGE
}

This initializer always returns WRITE_EXTERNAL_STORAGE, the first line does not do anything. You should probably be using the arrayOf function to construct the array instead.


问:
Multi-provider authentication layman terms
I'm trying to understand what the library OmniAuth does so first I want to see if I understand "multi-provider authentication" correctly. Does this just mean that your app can use either facebook, or google as different types of providers to authenticate you as a user? Thus you can login into your app by providing your facebook id/pw OR your google id/pw and both will take you to the same account under your app?

答:
I know it's kinda late but, yes, you were correct. OmniAuth is meant to offer more options for your users to register and authenticate themselves by leveraging other auth providers. In a simple situation, the process can be describe this way:

You register your app at the provider site. So they know who you are. They normally will require a redirect url, which is where they will send the auth response back to later on.

You get an app_id and app_secret.

When user click on "Sign in with ...", it take them to their auth url (the link often have your app_id and redirect url as paramaters)

User said, ok, I authorize this app to do these things. The provider send you back the authorization code.

Now your app can confidently go to talk with the provider. Hey provider, I am this app (show app_id and app_secret) and this user has authorized me (show authorization code). The provider now send you back the success auth data (which contains tokens, uid and other information)

In a server-side flow your app can then check the uid to see if match any user in your system (suppose you have a auth_providers table that link to user). If it does, sign that user in, if not sign that user up.

Most of the time you would want user to use only one auth provider (either Facebook or Google, or something else). Using both can result in 2 separate accounts. Of course you can find a way to get around that, like detecting if the email return from auth data has already been used, but that is not reliable, cause it only works if user register both Google and Facebook with the same email. It's up to you to find a solution to deduplicate those, should you want to let user sign in with multiple providers at the same time.


问:
C# Debugging - How can I tell what created a worker thread?
I am testing a Universal Windows Platform application which has buttons. When I push a sequence of buttons and pause the program after it's done doing work, I see only the Main thread and a worker thread. If I do the same thing fast enough, I will find an additional worker thread which never goes away.

I want to find my mistake which led to this leftover worker thread, but I've been unsuccessful with the debugging tools so far. Threads window only shows ID, Managed ID, Category = Worker Thread, Name = < No Name >, Location = < not available >, Priority = Normal.

How can I find out anything more about this leftover worker thread? E.g., when it was spawned, what it was doing, why it's not destroyed.

答:
You can set data in your threads as you create them, and presumably you'll be able to access that data during debugging.  You can use that data store to hold debug information such as where it was created.

https://learn.microsoft.com/en-us/dotnet/standard/threading/creating-threads-and-passing-data-at-start-time

Also there are tips here Thread-exclusive data: how to store and access?


问:
Angular/TypeScript - http post using a custom class' toString()
I am using Angular Reactive forms, I am getting form.value and sending it to asp.net web-api. The object named len in the code snipped below is a custom class that I wrote that is a very simple version of TimeSpan.

Here is my request;

```<code>{
  "id": "a7b06cf9-36a5-4c7a-99e5-8b9661469329",
  "minCapacity": 5,
  "maxCapacity": 10,
  "len": {
    "Days": 0,
    "Hours": 2,
    "Minutes": 0
  },
}
</code>```

By default .NET TimeSpan requires an input like this:

string.Format("{0}.{1}:{2}:{3}", len.Days, len.Hours, len.Minutes, len.Seconds)

And otherwise grabs the variable len as null.

Therefore, I have implemented an override toString() to my custom TimeSpan class. Yet when using the HTTP class in my Typescript code I still get the object in JSON format.

I have fiddled around SO for a couple hours, as well as google, yet I have failed to find an answer. I am hoping this is not a duplicate

Is there a way to override this at client side?

component.ts

```<code>saveItem(model: Room) {
    let selected = this.selected;
    this.roomService.createUpdateRoom(model).subscribe(
        response => {
            Helpers.setLoading(false);
            var result = response as ServiceResult<any>;
            if (result.hasError) {
                this.toaster.error(result.message, 'Error');
            }
            else {
                alert('ok');
                this.viewForm();
            }
        },
        error => {
            this.toaster.error(error.message, 'Error');
        });
}
</code>```

service.ts

```<code>createUpdateRoom(request) {
    return this.post('api/v1.0/room/createupdate', true, request);
}
</code>```

base.service.ts

```<code>post(apiAddress: string, isAuthorizeRequest: boolean, parameter: any): Observable<any> {
        return this.intercept(this.injector.get(AuthHttp).post(this.baseUrl + apiAddress, parameter).map(
            (response) => {
                let data = response.json();
                if (data) {
                    httpSuccess = data;
                }
                return httpSuccess;
            }
        ));
    }
</code>```

timespan.ts

```<code>export class TimeSpan {
day: number = 0;
hour: number = 0;
minute: number = 0;

toTimeString(): string {
    return this.hour +':' + this.minute;
}

toString = (): string => {

    return this.day + ':' + this.toTimeString() + ':00';
}
}
</code>```

room.ts

```<code>export class Room {
    id: string;
    minCapacity: number;
    maxCapacity: number;
    len: TimeSpan;
}
</code>```

答:
Form group value is a plain object or an array in Angular reactive forms.

There is a misunderstanding that is common among developers with C# or Java background regarding how TypeScript types work, even if the syntax is similar. TypeScript is basically JavaScript (ES.Next) with type checking. TypeScript types affect only type checking on compilation time and don't affect the output that is executed at run time (with the exception of emitted decorator metadata).

model: Room doesn't make model an instance of Room class. Room class is used as interface, and saveItem(model: Room) { ... } type implies that model object conforms to Room interface. Type check will pass if TypeScript considers model a plain object that has properties listed in Room interface. It will also pass if model is any. The same applies to type assertions.

In order for a model to be a hierarchy of expected class instances (Room and TimeSpan), they should be instantiated. The recipe for that is to make a class accept properties on construction:

```<code>export class TimeSpan {
  ...
  constructor(plainObj: ITimeSpan) {
    this.day = plainObj.day;
    ...
  }
}

export class Room {
  ...
  constructor(plainObj: IRoom) {
    this.len = new TimeSpan(plainObj.len);
    ...
  }
}
</code>```

Where ITimeSpan and IRoom are interfaces and subsets of TimeSpan and Room that contain only properties and not methods.

Then Room can be instantiated when needed:

```<code>saveItem(plainModel: IRoom) {
  const model = new Room(plainModel);
  ...
}
</code>```

Unless there are other reason for Room and TimeSpan to exist except custom toString (e.g. to hydrate a form from JSON plain object on edit), they can be considered redundant. Necessary model pre-processing of plainModel: IRoom properties (date stringification, etc.) can be performed on form submit instead, e.g. in processModel method.

Body:
I am using Angular Reactive forms, I am getting form.value and sending it to asp.net web-api. The object named len in the code snipped below is a custom class that I wrote that is a very simple version of TimeSpan.

Here is my request;

{
  "id": "a7b06cf9-36a5-4c7a-99e5-8b9661469329",
  "minCapacity": 5,
  "maxCapacity": 10,
  "len": {
    "Days": 0,
    "Hours": 2,
    "Minutes": 0
  },
}

By default .NET TimeSpan requires an input like this:

string.Format("{0}.{1}:{2}:{3}", len.Days, len.Hours, len.Minutes, len.Seconds)

And otherwise grabs the variable len as null.

Therefore, I have implemented an override toString() to my custom TimeSpan class. Yet when using the HTTP class in my Typescript code I still get the object in JSON format.

I have fiddled around SO for a couple hours, as well as google, yet I have failed to find an answer. I am hoping this is not a duplicate

Is there a way to override this at client side?

component.ts

saveItem(model: Room) {
    let selected = this.selected;
    this.roomService.createUpdateRoom(model).subscribe(
        response => {
            Helpers.setLoading(false);
            var result = response as ServiceResult<any>;
            if (result.hasError) {
                this.toaster.error(result.message, 'Error');
            }
            else {
                alert('ok');
                this.viewForm();
            }
        },
        error => {
            this.toaster.error(error.message, 'Error');
        });
}

service.ts

createUpdateRoom(request) {
    return this.post('api/v1.0/room/createupdate', true, request);
}

base.service.ts

post(apiAddress: string, isAuthorizeRequest: boolean, parameter: any): Observable<any> {
        return this.intercept(this.injector.get(AuthHttp).post(this.baseUrl + apiAddress, parameter).map(
            (response) => {
                let data = response.json();
                if (data) {
                    httpSuccess = data;
                }
                return httpSuccess;
            }
        ));
    }

timespan.ts

export class TimeSpan {
day: number = 0;
hour: number = 0;
minute: number = 0;

toTimeString(): string {
    return this.hour +':' + this.minute;
}

toString = (): string => {

    return this.day + ':' + this.toTimeString() + ':00';
}
}

room.ts

export class Room {
    id: string;
    minCapacity: number;
    maxCapacity: number;
    len: TimeSpan;
}

Body:
Form group value is a plain object or an array in Angular reactive forms.

There is a misunderstanding that is common among developers with C# or Java background regarding how TypeScript types work, even if the syntax is similar. TypeScript is basically JavaScript (ES.Next) with type checking. TypeScript types affect only type checking on compilation time and don't affect the output that is executed at run time (with the exception of emitted decorator metadata).

model: Room doesn't make model an instance of Room class. Room class is used as interface, and saveItem(model: Room) { ... } type implies that model object conforms to Room interface. Type check will pass if TypeScript considers model a plain object that has properties listed in Room interface. It will also pass if model is any. The same applies to type assertions.

In order for a model to be a hierarchy of expected class instances (Room and TimeSpan), they should be instantiated. The recipe for that is to make a class accept properties on construction:

export class TimeSpan {
  ...
  constructor(plainObj: ITimeSpan) {
    this.day = plainObj.day;
    ...
  }
}

export class Room {
  ...
  constructor(plainObj: IRoom) {
    this.len = new TimeSpan(plainObj.len);
    ...
  }
}

Where ITimeSpan and IRoom are interfaces and subsets of TimeSpan and Room that contain only properties and not methods.

Then Room can be instantiated when needed:

saveItem(plainModel: IRoom) {
  const model = new Room(plainModel);
  ...
}

Unless there are other reason for Room and TimeSpan to exist except custom toString (e.g. to hydrate a form from JSON plain object on edit), they can be considered redundant. Necessary model pre-processing of plainModel: IRoom properties (date stringification, etc.) can be performed on form submit instead, e.g. in processModel method.


问:
AssertJ to log assertion's results
I'm trying to understand if is possible to configure AssertJ to log the negative result of an assertion to a file without interrupting the routing that is running the comparison.

The reason behind this request is that we are comparing the JSON generated by two version of a software to spot differences, but instead of manually creating all the checks I would like to leverage the functionalities already available in AssertJ.

As a possible solution to this I was thinking of using a try/catch for  assertion exceptions, but I'm really concerned about the overall performance of the routine.

Any idea?

答:
If we spoke about any logging frameworks:

we can use File LoggingAppender

set log level for ERROR or WARN

define TestClass or Pacakge for reduce unnecessary messages

Title: AssertJ to log assertion's results


问:
Invalid Token. Not accepting integers that start with 0
So I'm trying to make a check digit function, and embarrassingly, I've already run into a snag early on that I've been trying to search the problem for, but most of the explanations I've run into are unfortunately beyond my comprehension. I'm hoping someone could give me a specific run-down as to what my problem is right now

```<code>mam = []

def check_digit():
    a = int(input("Please enter your 10 digit book number"))
    b = str(a)
    for c in b:
        mam.append(c)
        print(c)

check_digit()
</code>```

Sorry about no set names for variables, I prefer coding this way even if it eventually gets awkward for others to read. Well anyway, every time I write in an integer which starts with 0, the Syntax error "Invalid token" appears and I don't know how to solve it. Could anyone help me? I would be grateful

Fixed. I really need to update Python, I'm running 2.7 at the moment.

raw_input solved the issue

答: in python, numbers starting with 0 are in octal base, the 'invalid token' error you're getting must be on a digit greater than 7, which is illegal in a base 8 number. Try using raw_input() instead of input() so that the value won't be evaluated as a number.

Body:
So I'm trying to make a check digit function, and embarrassingly, I've already run into a snag early on that I've been trying to search the problem for, but most of the explanations I've run into are unfortunately beyond my comprehension. I'm hoping someone could give me a specific run-down as to what my problem is right now

mam = []

def check_digit():
    a = int(input("Please enter your 10 digit book number"))
    b = str(a)
    for c in b:
        mam.append(c)
        print(c)

check_digit()

Sorry about no set names for variables, I prefer coding this way even if it eventually gets awkward for others to read. Well anyway, every time I write in an integer which starts with 0, the Syntax error "Invalid token" appears and I don't know how to solve it. Could anyone help me? I would be grateful

Fixed. I really need to update Python, I'm running 2.7 at the moment.

raw_input solved the issue


问:
Python FTP script security concerns
I'm wondering how secure this is?  I'm connecting to an FTP server that's within my company's network, and I have this Python script stored on my local computer with the connection details hard-coded into the scripts like this:

```<code>ftp = ftplib.FTP()
ftp.connect('server.mycompany.com', 21, 9600)
ftp.login('my-user-name', 'my-password')
</code>```

Is there another way I should be handling this, or is this reasonably secure as long as I'm dealing with servers within my company?  Am I personally opening my company up to risk by doing this, and if so, what is the preferred method?

答: I know this article is a couple years old, but I know that ftplib and ssl modules can handle ftps. They have a subclass FTP_TLS that has to be authenticated with Public ssl keys.</p>

Title: Python FTP script security concerns

Body:
I'm wondering how secure this is?  I'm connecting to an FTP server that's within my company's network, and I have this Python script stored on my local computer with the connection details hard-coded into the scripts like this:

ftp = ftplib.FTP()
ftp.connect('server.mycompany.com', 21, 9600)
ftp.login('my-user-name', 'my-password')

Is there another way I should be handling this, or is this reasonably secure as long as I'm dealing with servers within my company?  Am I personally opening my company up to risk by doing this, and if so, what is the preferred method?


问:
on the fly generation with Dataset api tensorflow
I have a function which produces feature and target tensors.  E.g.

```<code>x,t = myfunc() ##x,t tensors
</code>```

How can I integrate this with TensorFlow's dataset API for continuous training?  Ideally I would like to use dataset to set things like batch, transformations.

Edit for clarification: The problem being I would like to not just put x and t in my graph but make a dataset from them so that I can use the same dataset processing that I have implemented for (normal) finite datasets I can load into memory and feed into the same graph using an initializable iterator.

答:
Assuming x and t are tf.Tensor objects, and my_func() builds a TensorFlow graph, you may be able to use the following approach with `Dataset.map():

```<code># Creates an infinite dataset with a dummy value. You can make this finite by
# specifying an explicit number of elements to `repeat()`.
dummy_dataset = tf.data.Dataset.from_tensors(0).repeat(None)

# Evaluates `my_func` once for each element in `dummy_dataset`.
dataset = dummy_dataset.map(lambda _: my_func())
</code>```

Body:
I have a function which produces feature and target tensors.  E.g.

x,t = myfunc() ##x,t tensors

How can I integrate this with TensorFlow's dataset API for continuous training?  Ideally I would like to use dataset to set things like batch, transformations.

Edit for clarification: The problem being I would like to not just put x and t in my graph but make a dataset from them so that I can use the same dataset processing that I have implemented for (normal) finite datasets I can load into memory and feed into the same graph using an initializable iterator.

Body:
Assuming x and t are tf.Tensor objects, and my_func() builds a TensorFlow graph, you may be able to use the following approach with `Dataset.map():

# Creates an infinite dataset with a dummy value. You can make this finite by
# specifying an explicit number of elements to `repeat()`.
dummy_dataset = tf.data.Dataset.from_tensors(0).repeat(None)

# Evaluates `my_func` once for each element in `dummy_dataset`.
dataset = dummy_dataset.map(lambda _: my_func())


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
I think the only way to truly understand any new technology is to work with it day in and day out.  Sure, you can learn lots of new things at a high level without getting too deep, but to get that "ah ha" moment, to really grok the language and patterns, you have to invest a lot of time into just doing it.

Sadly, that means your main line of work really has to be programming in C#.  If you are just doing it here and there as a series of side projects, it's gonna be frustrating and slow going.

Just my opinion based on my own experience...

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: Jeremy McCollum


问:
Extending Javascript Arrays prototype with Max/Min to find values
Looking at different methods of how to find max/min values in Javascript Array I can often see extending prototype of Array object itself. So having:

```<code>var a=[22,33,44,32,1];

Array.max=function(v) {
    return Math.max.apply(this,v);
};

Array.max(a); // returns 44
</code>```

However I often do as below:

```<code>Array.prototype.max=function() {
    return Math.max.apply(this,this);
};

a.max(); // returns 44
</code>```

This allows me to call max() with no parameters on the Array object itself. Personally I don't see any problem with it and I keep wondering if am I missing something and this method has some major problems I overlook? Is it safe to use as Array.max(arrayhere)?

EDIT: Is it correct to say that in first example we creating static method on native Javascript Array object and in second example we extending Arrays prototype?

答:
The proper way to do this is using Object.defineProperty or Object.defineProperties. In this case I'll write how to do it with the latter. *Edit: Note this will not handle empty arrays as you would expect. See edit below.

```<code>Object.defineProperties(Array.prototype, {
    max: {
    configurable: true,
    enumerable: false,
    value: function () {return Math.max(...this)},
    writable: true
  },
    min: {
    configurable: true,
    enumerable: false,
    value: function () {return Math.min(...this)},
    writable: true
  }
});
</code>```

Then you can just do:

```<code>[4, 3, 2, 1].max() // 4
[4, 3, 2, 1].min() // 1
</code>```

This will prevent anyone from tripping into the for in gotcha, as you set those properties enumerability as false.

EDIT. Handling empty arrays

As @MikeM point out in his comment, the documented behaviour of Math.max() and Math.min() is probably not what makes more sense –at least for me–. If you don't send arguments to those functions, you get Infinity, with a different sign in each case:

```<code>Math.max(); // -Infinity
Math.min(); // Infinity
</code>```

Therefore, if the array we're calling .max() or .min() on is empty, we'll get an arguably not-so-reasonable result. To handle that edge case, the solution would be:

```<code>Object.defineProperties(Array.prototype, {
    max: {
    configurable: true,
    enumerable: false,
    value: function () {
            if (this.length === 0) return null; // or whatever makes more sense
            return Math.max(...this)
        },
    writable: true
  },
    min: {
    configurable: true,
    enumerable: false,
    value: function () {
            if (this.length === 0) return null;
            return Math.min(...this)
        },
    writtable: true
  }
});
</code>```

Body:
Looking at different methods of how to find max/min values in Javascript Array I can often see extending prototype of Array object itself. So having:

var a=[22,33,44,32,1];

Array.max=function(v) {
    return Math.max.apply(this,v);
};

Array.max(a); // returns 44

However I often do as below:

Array.prototype.max=function() {
    return Math.max.apply(this,this);
};

a.max(); // returns 44

This allows me to call max() with no parameters on the Array object itself. Personally I don't see any problem with it and I keep wondering if am I missing something and this method has some major problems I overlook? Is it safe to use as Array.max(arrayhere)?

EDIT: Is it correct to say that in first example we creating static method on native Javascript Array object and in second example we extending Arrays prototype?

Body:
The proper way to do this is using Object.defineProperty or Object.defineProperties. In this case I'll write how to do it with the latter. *Edit: Note this will not handle empty arrays as you would expect. See edit below.

Object.defineProperties(Array.prototype, {
    max: {
    configurable: true,
    enumerable: false,
    value: function () {return Math.max(...this)},
    writable: true
  },
    min: {
    configurable: true,
    enumerable: false,
    value: function () {return Math.min(...this)},
    writable: true
  }
});

Then you can just do:

[4, 3, 2, 1].max() // 4
[4, 3, 2, 1].min() // 1

This will prevent anyone from tripping into the for in gotcha, as you set those properties enumerability as false.

EDIT. Handling empty arrays

As @MikeM point out in his comment, the documented behaviour of Math.max() and Math.min() is probably not what makes more sense –at least for me–. If you don't send arguments to those functions, you get Infinity, with a different sign in each case:

Math.max(); // -Infinity
Math.min(); // Infinity

Therefore, if the array we're calling .max() or .min() on is empty, we'll get an arguably not-so-reasonable result. To handle that edge case, the solution would be:

Object.defineProperties(Array.prototype, {
    max: {
    configurable: true,
    enumerable: false,
    value: function () {
            if (this.length === 0) return null; // or whatever makes more sense
            return Math.max(...this)
        },
    writable: true
  },
    min: {
    configurable: true,
    enumerable: false,
    value: function () {
            if (this.length === 0) return null;
            return Math.min(...this)
        },
    writtable: true
  }
});


问:
Homebrew updates and app self updates
How does homebrew/cask's updates work if the app auto updates itself.

Example: Chrome or Firefox

These two apps auto update themselves.

But what happens when you run a brew update?

Does it detect that it is already updated or does it check an internal list of apps it installed (misses that it is already updated) and reupdates the app>

答: brew cask upgrade is possible as of version 1.3.9

Title: Homebrew updates and app self updates


问:
Is there a way of indenting table in markdown
I'm using the showdown.js 1.7.3 for markdown

I want to be able to indent tables in a list, is there a way of doing this with showdown, if not does anyone know of any other markdown library where it is possible to indent tables in a list

答:
It is possible to do it with showdown. Check the demo here

Here's also a snippet showing how to do it.

var conv = new showdown.Converter({tables: true});
var html = conv.makeHtml(document.getElementById('src').value);
document.getElementById('otp').value = html;
document.getElementById('otp2').innerHTML = html;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
    border-collapse: collapse;
}

table, th, td {
    border: 1px solid black;
}
th {
  background-color: lightgray;
}

th, td{
  padding: 5px;
}</code>```

<textarea id="src">
- foo

    | foo | bar | baz |
    |-----|-----|-----|
    | bla | bli | blu |

- baz
</textarea>

<textarea id="otp"></textarea>

```

Body:
It is possible to do it with showdown. Check the demo here

Here's also a snippet showing how to do it.

var conv = new showdown.Converter({tables: true});
var html = conv.makeHtml(document.getElementById('src').value);
document.getElementById('otp').value = html;
document.getElementById('otp2').innerHTML = html;

table {
    border-collapse: collapse;
}

table, th, td {
    border: 1px solid black;
}
th {
  background-color: lightgray;
}

th, td{
  padding: 5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.8.3/showdown.js"></script>
<textarea id="src">
- foo

    | foo | bar | baz |
    |-----|-----|-----|
    | bla | bli | blu |

- baz
</textarea><br>
<textarea id="otp"></textarea><br>
<div id="otp2"></div>


问:
How do I reference X controls into a FOR loop?
I have those three text boxes by the name StandardPath_TextBoxA1, StandardPath_TextBoxA2, StandardPath_TextBoxA3 and through a FOR loop I am trying to save their text values into an ms access database file. I am trying something like this below, but my syntax is wrong... Any idea?

```<code>For i = 1 To 3
Dim str(i) As String
str(i) = "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?)"

Dim cmd As OleDbCommand = New OleDbCommand(str(i), MyConnection)
cmd.Parameters.Add(New OleDbParameter("TagNum", CType("A" & i, String)))
cmd.Parameters.Add(New OleDbParameter("Title", CType(StandardPath_LabelA(i).Text), String)))
cmd.Parameters.Add(New OleDbParameter("Path", CType(StandardPath_TextBoxA(i).Text), String)))

Try
    cmd.ExecuteNonQuery()
    cmd.Dispose()
    MyConnection.Close()
Catch ex As Exception
    MsgBox(ex.Message)
End Try
Next
</code>```

EDIT:

The syntax error located here:

```<code>cmd.Parameters.Add(New OleDbParameter("Title", CType(StandardPath_LabelA(i).Text), String)))
cmd.Parameters.Add(New OleDbParameter("Path", CType(StandardPath_TextBoxA(i).Text), String)))
</code>```

答:
Try this. It fixes some type-mismatches in the original, as well as removing unnecessary variables and redundancy.

Dim sql As String = "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?)"
'DON'T RE-USE YOUR DATABASE CONNECTION, EXCEPT FOR SHORT BURSTS IN TIGHT LOOPS LIKE THIS
Using connection As New OleDbConnection("connection string here"), _
      cmd As New OleDbCommand(sql, connection)

    'Guessing at column types and lengths. Use actual types from your database here
    cmd.Parameters.Add("TagNum", OleDbType.VarChar, 2)
    cmd.Parameters.Add("Title", OleDbType.VarWChar, 100)
    cmd.Parameters.Add("Path", OleDbType.VarWChar, 512)

    'Do this just once, outside the loop, to avoid needing to repeatedly re-negotiate with the DB. Let the USING black take care of closing the connection
    connection.Open()

    For i = 1 To 3

        Dim TitleLabel As Control = Me.Controls.Find("StandardPath_LabelA" & i.ToString(), True).First()
        Dim PathBox As Control = Me.Controls.Find("StandardPath_TextBoxA" & i.ToString(), True).First()

        cmd.Parameters(0).Value = "A" & i.ToString()
        cmd.Parameters(1).Value = TitleLabel.Text
        cmd.Parameters(2).Value = PathBox.Text

        Try
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Next
End Using
```

<p>Even better if you have already grouped these controls in related panel or similar control, or added them to an array. That could allow better options than <code>Controls.Find()</code>, but I saw no indication of this in the question.</p>

<p>One other option, since the number of items is small, is to do it like this:</p>

<pre class="lang-vb prettyprint-override"><code>Dim sql As String = _
    "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);" & VbCrLf & _
    "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);" & VbCrLf & _
    "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);"

Using connection As New OleDbConnection("connection string here"), _
      cmd As New OleDbCommand(sql, connection)

    'Guessing at column types and lengths. Use actual types from your database here
    cmd.Parameters.Add("TagNum1", OleDbType.VarChar, 2).Value = "A1"
    cmd.Parameters.Add("Title1", OleDbType.VarWChar, 100).Value = StandardPath_LabelA1.Text
    cmd.Parameters.Add("Path1", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA1.Text
    cmd.Parameters.Add("TagNum2", OleDbType.VarChar, 2).Value = "A2"
    cmd.Parameters.Add("Title2", OleDbType.VarWChar, 100).Value = StandardPath_LabelA2.Text
    cmd.Parameters.Add("Path2", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA2.Text
    cmd.Parameters.Add("TagNum3", OleDbType.VarChar, 2).Value = "A3"
    cmd.Parameters.Add("Title3", OleDbType.VarWChar, 100).Value = StandardPath_LabelA3.Text
    cmd.Parameters.Add("Path3", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA3.Text

    connection.Open()

    Try
        cmd.ExecuteNonQuery()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Using
</code>```

I know the repeated code is often seen as bad, but for three items sometimes a loop is just overkill. In this case, skipping the loop also gives an advantage of reducing you to a single atomic trip to the database.

Body:
I have those three text boxes by the name StandardPath_TextBoxA1, StandardPath_TextBoxA2, StandardPath_TextBoxA3 and through a FOR loop I am trying to save their text values into an ms access database file. I am trying something like this below, but my syntax is wrong... Any idea?

For i = 1 To 3
Dim str(i) As String
str(i) = "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?)"

Dim cmd As OleDbCommand = New OleDbCommand(str(i), MyConnection)
cmd.Parameters.Add(New OleDbParameter("TagNum", CType("A" & i, String)))
cmd.Parameters.Add(New OleDbParameter("Title", CType(StandardPath_LabelA(i).Text), String)))
cmd.Parameters.Add(New OleDbParameter("Path", CType(StandardPath_TextBoxA(i).Text), String)))

Try
    cmd.ExecuteNonQuery()
    cmd.Dispose()
    MyConnection.Close()
Catch ex As Exception
    MsgBox(ex.Message)
End Try
Next

EDIT:

The syntax error located here:

cmd.Parameters.Add(New OleDbParameter("Title", CType(StandardPath_LabelA(i).Text), String)))
cmd.Parameters.Add(New OleDbParameter("Path", CType(StandardPath_TextBoxA(i).Text), String)))

Body:
Try this. It fixes some type-mismatches in the original, as well as removing unnecessary variables and redundancy.

Dim sql As String = "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?)"
'DON'T RE-USE YOUR DATABASE CONNECTION, EXCEPT FOR SHORT BURSTS IN TIGHT LOOPS LIKE THIS
Using connection As New OleDbConnection("connection string here"), _
      cmd As New OleDbCommand(sql, connection)

    'Guessing at column types and lengths. Use actual types from your database here
    cmd.Parameters.Add("TagNum", OleDbType.VarChar, 2)
    cmd.Parameters.Add("Title", OleDbType.VarWChar, 100)
    cmd.Parameters.Add("Path", OleDbType.VarWChar, 512)

    'Do this just once, outside the loop, to avoid needing to repeatedly re-negotiate with the DB. Let the USING black take care of closing the connection
    connection.Open()

    For i = 1 To 3

        Dim TitleLabel As Control = Me.Controls.Find("StandardPath_LabelA" & i.ToString(), True).First()
        Dim PathBox As Control = Me.Controls.Find("StandardPath_TextBoxA" & i.ToString(), True).First()

        cmd.Parameters(0).Value = "A" & i.ToString()
        cmd.Parameters(1).Value = TitleLabel.Text
        cmd.Parameters(2).Value = PathBox.Text

        Try
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Next
End Using

Even better if you have already grouped these controls in related panel or similar control, or added them to an array. That could allow better options than Controls.Find(), but I saw no indication of this in the question.

One other option, since the number of items is small, is to do it like this:

Dim sql As String = _
    "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);" & VbCrLf & _
    "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);" & VbCrLf & _
    "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);"

Using connection As New OleDbConnection("connection string here"), _
      cmd As New OleDbCommand(sql, connection)

    'Guessing at column types and lengths. Use actual types from your database here
    cmd.Parameters.Add("TagNum1", OleDbType.VarChar, 2).Value = "A1"
    cmd.Parameters.Add("Title1", OleDbType.VarWChar, 100).Value = StandardPath_LabelA1.Text
    cmd.Parameters.Add("Path1", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA1.Text
    cmd.Parameters.Add("TagNum2", OleDbType.VarChar, 2).Value = "A2"
    cmd.Parameters.Add("Title2", OleDbType.VarWChar, 100).Value = StandardPath_LabelA2.Text
    cmd.Parameters.Add("Path2", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA2.Text
    cmd.Parameters.Add("TagNum3", OleDbType.VarChar, 2).Value = "A3"
    cmd.Parameters.Add("Title3", OleDbType.VarWChar, 100).Value = StandardPath_LabelA3.Text
    cmd.Parameters.Add("Path3", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA3.Text

    connection.Open()

    Try
        cmd.ExecuteNonQuery()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Using

I know the repeated code is often seen as bad, but for three items sometimes a loop is just overkill. In this case, skipping the loop also gives an advantage of reducing you to a single atomic trip to the database.


问:
Find how many minutes old a file is
First of all, I know I am not supposed to as "code sample" here. Sadly, I am not a programmer and I have a situation where I need to update a line in a report to present to the customer, but I do not know how to do it.

I have access to PHP file report.php. In the same server and folder as report.php there is a file called report.csv. When report.php is loaded in browser, I want to show one line which will say:

Report.cvs is X minutes old that is all.

If the report is 10 days old, then also I can show the age in minutes. I dont need any complicated X days, Y hours, Z mins etc.

I am worried i might break something in server if I try to add myself since I am not programmer. Is there anyone who can show me what I need to add to report.php to make this work?

答:
Ok so basically you need to get the time when the file was last modified, subtract it from the current time, convert the result to minutes and voilà.

Here's what that should look like:

```<code>$file = ''; // --- Path to the file

$filetime = filemtime($file); // --- File time

$now = time(); // --- Current Time
$fileAge = round(($now - $filetime)/60); // --- Subtract file time from current time, divide by 60 for the minutes and round the result.

echo basename($file).' is '.$fileAge.' minutes old.';
</code>```

Title: Find how many minutes old a file is

Body:
Ok so basically you need to get the time when the file was last modified, subtract it from the current time, convert the result to minutes and voilà.

Here's what that should look like:

$file = ''; // --- Path to the file

$filetime = filemtime($file); // --- File time

$now = time(); // --- Current Time
$fileAge = round(($now - $filetime)/60); // --- Subtract file time from current time, divide by 60 for the minutes and round the result.

echo basename($file).' is '.$fileAge.' minutes old.';


问:
node and reactjs axios server request returning index.html file instead of json
I have setup my project with a react frontend being compiled by webpack and the server running on node and express.

When I deploy to production my requests to the server are returning the index.html file in the 'dist' folder rather than the json with the data.

My webpack compiled output is at the location ./dist.

Here is the routing part of my server.js file:

```<code>if (process.env.NODE_ENV === 'production') {
  app.use(express.static('dist'));
  const path = require('path');
  app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
  });
}
// Use our router configuration when we call /
app.use('/', router);
</code>```

Here is part of my webpack config file:

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './client/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  devServer: {
    inline: true,
    contentBase: './dist',
    port: 8080,
    proxy: { '/api/**': { target: 'http://localhost:3000', secure: false } }
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['es2015','react'], plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread']}},
        {test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i, loader: 'file-loader?name=/images/[name].[ext]'},
        {test: /\.css$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader','resolve-url-loader']},
        {test: /\.scss$/, loaders: ['style-loader', 'css-loader','postcss-loader', 'sass-loader','resolve-url-loader']}
        ]
  },
  plugins: [HTMLWebpackPluginConfig]
};
</code>```

My request is as follows (the api route /api/chefs returns a json with user profiles (tested in development):

```<code>export function listChefs() {
  return function (dispatch) {
    axios.get('/api/chefs')
      .then((response) => {
        dispatch({
          type: LIST_CHEFS,
          payload: response.data
        });
      })
      .catch((err) => {
        errorHandler(dispatch, 'There was a problem. Please refresh and try again.');
      });
  };
}
</code>```

It seems as though the call that I am making from my client using axios is actually hitting the api url that isn't being recognised and therefore is being redirected to simply server the index.html file.

Any help?

Cheers

答:
According to the webpack docs, you can specify the proxy setting as follows

```<code>proxy: {
  "/api": {
    target: "https://other-server.example.com",
    secure: false
  }
}
</code>```

Notice the "/api" rather than "/api/**".

Also, it may be worth noting that they recommend using absolute paths via path.join(__dirname, "dist") for the contentBase setting.

Body:
I have setup my project with a react frontend being compiled by webpack and the server running on node and express.

When I deploy to production my requests to the server are returning the index.html file in the 'dist' folder rather than the json with the data.

My webpack compiled output is at the location ./dist.

Here is the routing part of my server.js file:

if (process.env.NODE_ENV === 'production') {
  app.use(express.static('dist'));
  const path = require('path');
  app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
  });
}
// Use our router configuration when we call /
app.use('/', router);

Here is part of my webpack config file:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './client/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  devServer: {
    inline: true,
    contentBase: './dist',
    port: 8080,
    proxy: { '/api/**': { target: 'http://localhost:3000', secure: false } }
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['es2015','react'], plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread']}},
        {test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i, loader: 'file-loader?name=/images/[name].[ext]'},
        {test: /\.css$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader','resolve-url-loader']},
        {test: /\.scss$/, loaders: ['style-loader', 'css-loader','postcss-loader', 'sass-loader','resolve-url-loader']}
        ]
  },
  plugins: [HTMLWebpackPluginConfig]
};

My request is as follows (the api route /api/chefs returns a json with user profiles (tested in development):

export function listChefs() {
  return function (dispatch) {
    axios.get('/api/chefs')
      .then((response) => {
        dispatch({
          type: LIST_CHEFS,
          payload: response.data
        });
      })
      .catch((err) => {
        errorHandler(dispatch, 'There was a problem. Please refresh and try again.');
      });
  };
}

It seems as though the call that I am making from my client using axios is actually hitting the api url that isn't being recognised and therefore is being redirected to simply server the index.html file.

Any help?

Cheers

Body:
According to the webpack docs, you can specify the proxy setting as follows

proxy: {
  "/api": {
    target: "https://other-server.example.com",
    secure: false
  }
}

Notice the "/api" rather than "/api/**".

Also, it may be worth noting that they recommend using absolute paths via path.join(__dirname, "dist") for the contentBase setting.


问:
Regular Expressions in DB2 SQL
(Other than using a UDF) Any REGEXP-In-SQL support for DB2 9.7 ?</p>

答:
There is no built-in support for regular expressions in DB2 9.7.

The only way is using UDFs or table functions as described in the article 'OMG Ponies' added in the comment.

@dan1111: I do not appreciate my post being edited, especially if people can't read the question correctly. The OP asked Any REGEXP-In-SQL support for DB2 9.7

SQL is not XQuery !!!

Sorry, don't delete the text of my 100% correct answer. You can add a comment or write your own answer.

Title: Regular Expressions in DB2 SQL


问:
Picked image bitmap return in a method
I am new to Android.I have a problem with select an image and return result. I have a method is getImageFromGallery() my scope is this method call then i will choose a image from gallery and return as bitmap.But the problem is onActivityResult() set the bitmap after that bitmap is return. If i pick a image then, should return that selected image bitmap file.please help to find out the solution.

Here is my code.

private Bitmap bitmap;

```<code> public Bitmap getImageFromGallery(){
    Intent i = new Intent(
            Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, RESULT_LOAD_IMAGE);
    return  bitmap;}
</code>```

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();

        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        bitmap = BitmapFactory.decodeFile(picturePath);
    }

}
</code>```

I want to return selected bitmap value.

答:
Try this:

```<code>public void getImageFromGallery(){
    Intent i = new Intent(Intent.ACTION_PICK);
    i.setType("image/*");
    startActivityForResult(i, RESULT_LOAD_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
        Uri imageUri = intent.getData();
        mBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}
</code>```

Your getImageFromGallery can't return the Bitmap as you haven't selected it yet. You can only set it in the onActivityResult.

See more here.

Title: Picked image bitmap return in a method

Body:
I am new to Android.I have a problem with select an image and return result. I have a method is getImageFromGallery() my scope is this method call then i will choose a image from gallery and return as bitmap.But the problem is onActivityResult() set the bitmap after that bitmap is return. If i pick a image then, should return that selected image bitmap file.please help to find out the solution.

Here is my code.

private Bitmap bitmap;

 public Bitmap getImageFromGallery(){
    Intent i = new Intent(
            Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, RESULT_LOAD_IMAGE);
    return  bitmap;}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();

        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        bitmap = BitmapFactory.decodeFile(picturePath);
    }

}

I want to return selected bitmap value.

Body:
Try this:

public void getImageFromGallery(){
    Intent i = new Intent(Intent.ACTION_PICK);
    i.setType("image/*");
    startActivityForResult(i, RESULT_LOAD_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
        Uri imageUri = intent.getData();
        mBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}

Your getImageFromGallery can't return the Bitmap as you haven't selected it yet. You can only set it in the onActivityResult.

See more here.


问:
Is it possible to use NSMutableAttributedString with SKLabelNode?
I'm trying to change the kerning on a couple of SKLabelNodes. I tried to use some code from another answer:

```<code>NSMutableAttributedString *attributedString;
attributedString = [[NSMutableAttributedString alloc] initWithString:@"Please get wider"];
[attributedString addAttribute:NSKernAttributeName value:@5 range:NSMakeRange(10, 5)];
[self.label setAttributedText:attributedString];
</code>```

This isn't allowed:

```<code>[myLabelNode setAttributedText:attributedString];
</code>```

And this doesn't carry over the changes I made:

```<code>myLabelNode.text = attributedString.string;
</code>```

Is it possible to change kerning on an SKLabelNode?

答: As of iOS 11, NSAttributedStrings are supported in SKLabelNode. So kerning and other options should now be available to you.</p>

Body:
I'm trying to change the kerning on a couple of SKLabelNodes. I tried to use some code from another answer:

NSMutableAttributedString *attributedString;
attributedString = [[NSMutableAttributedString alloc] initWithString:@"Please get wider"];
[attributedString addAttribute:NSKernAttributeName value:@5 range:NSMakeRange(10, 5)];
[self.label setAttributedText:attributedString];

This isn't allowed:

[myLabelNode setAttributedText:attributedString];

And this doesn't carry over the changes I made:

myLabelNode.text = attributedString.string;

Is it possible to change kerning on an SKLabelNode?