答:
Add all the digits together (or even just count the ones) - if the answer is odd, the number is odd; if it's even, the nmber is even.

How does that work? Each digit from the number contributes 0, 1 or 2 times (1, 3, 9, 27, ...). A 0 or a 2 adds an even number, so no effect on the oddness/evenness (parity) of the number as a whole. A 1 adds one of the powers of 3, which is always odd, and so flips the parity). And we start from 0 (even). So by counting whether the number of flips is odd or even we can tell whether the number itself is.

Title: How to check divisibility of a number not in base 10 without converting?

Body:
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?

Update

The original problem is from TopCoder

The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.

Notes

-  When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.

Constraints

-  base is between 3 and 30, inclusive.

This is my solution:

class InterestingDigits {
public:
    vector<int> digits( int base ) {
        vector<int> temp;
        for( int i = 2; i <= base; ++i )
            if( base % i == 1 )
                temp.push_back( i );
        return temp;
    }
};

The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit

Thanks,

Chan


来源: stackexchange

问:
Nested dictionary: sum values of same key of the dictionaries nested as a value of dictionary
I want to sum values of the same key: H, C, O, N, S according to dictionary composition for the string input which is a combination of letter A, C, D, E.

```<code>composition = {
    'A':  {'H': 5, 'C': 3, 'O': 1, 'N': 1},
    'C':  {'H': 5, 'C': 3, 'O': 1, 'N': 1, 'S': 1},
    'D':  {'H': 5, 'C': 4, 'O': 3, 'N': 1},
    'E':  {'H': 7, 'C': 5, 'O': 3, 'N': 1},
}

string_input = ['ACDE', 'CCCDA']
</code>```

The expected result should be

```<code>out = {
    'ACDE' : {'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1},
    'CCCDA' : {'H': 15, 'C': 9, 'O': 3, 'N': 3, 'S': 3},
}
</code>```

I am trying to use Counter but stuck at unsupported operand type(s) for +: 'int' and 'Counter'

```<code>from collections import Counter

for each in string_input:
  out = sum(Counter(composition[aa]) for aa in each)
</code>```

答:
sum() has a starting value, from which it starts the sum. This also provides a default if there are no values to sum in the first argument. That starting value is 0, an integer.

From the sum() function documentation:

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0.

When summing Counter objects, give it an empty Counter() to start off with:

```<code>sum((Counter(composition[aa]) for aa in each), Counter())
</code>```

If you then assign the result to a key in a dictionary assigned to out you get your expected result as Counter instances:

```<code>>>> out = {}
>>> for each in string_input:
...     out[each] = sum((Counter(composition[aa]) for aa in each), Counter())
...
>>> out
{'ACDE': Counter({'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1}), 'CCCDA': Counter({'H': 25, 'C': 16, 'O': 7, 'N': 5, 'S': 3})}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to sum values of the same key: H, C, O, N, S according to dictionary composition for the string input which is a combination of letter A, C, D, E.

composition = {
    'A':  {'H': 5, 'C': 3, 'O': 1, 'N': 1},
    'C':  {'H': 5, 'C': 3, 'O': 1, 'N': 1, 'S': 1},
    'D':  {'H': 5, 'C': 4, 'O': 3, 'N': 1},
    'E':  {'H': 7, 'C': 5, 'O': 3, 'N': 1},
}

string_input = ['ACDE', 'CCCDA']

The expected result should be

out = {
    'ACDE' : {'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1},
    'CCCDA' : {'H': 15, 'C': 9, 'O': 3, 'N': 3, 'S': 3},
}

I am trying to use Counter but stuck at unsupported operand type(s) for +: 'int' and 'Counter'

from collections import Counter

for each in string_input:
  out = sum(Counter(composition[aa]) for aa in each)

Body:
sum() has a starting value, from which it starts the sum. This also provides a default if there are no values to sum in the first argument. That starting value is 0, an integer.

From the sum() function documentation:

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0.

When summing Counter objects, give it an empty Counter() to start off with:

sum((Counter(composition[aa]) for aa in each), Counter())

If you then assign the result to a key in a dictionary assigned to out you get your expected result as Counter instances:

>>> out = {}
>>> for each in string_input:
...     out[each] = sum((Counter(composition[aa]) for aa in each), Counter())
...
>>> out
{'ACDE': Counter({'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1}), 'CCCDA': Counter({'H': 25, 'C': 16, 'O': 7, 'N': 5, 'S': 3})}


问:
how do i merge n .csv files(possibly 20-30 files) with 1 BIG .csv file horizontally(axis=1) using pandas?
I have a 20-30 csv files containing 3 columns like 'id','col1','col2','col3' and 1 big csv file of 20GB size that i want to read in chunks and merge with these samller csv files.
the bigger csv file has columns as 'id','name','zipdeails'.
both have ID column in same sequences,
smaple looks like

```<code> 'id','name','zipdeails'
  1,Ravi,2031345
  2,Shayam,201344
  3,Priya,20134
  .........
  1000,Pravn,204324
</code>```

chunk file 1 looks like

```<code> 'id','col1','col2','col3'
    1,Heat,,
    2,Goa,Next,
    3,,,Delhi
</code>```

all the smaller csv files are of same lenth(number of rows) except for the last file which may be smaller in length with header in each. the bigger csv file to which these are to be merged can be broken into chunksize that is equal to the length of these smaller files
so Last chunk looks like

```<code>'id','col1','col2','col3'
   1000,Jaipur,Week,Trip
</code>```

Now the output should look like

```<code>'id','name','zipdeails','col1','col2','col3'
 1,Ravi,2031345,Heat,NAN,NAN
 2,Shayam,201344,Goa,Next,NAN
 3,Priya,20134,NAN,NAN,Delhi
  .........
 1000,Pravn,204324,Jaipur,Week,Trip
</code>```

答:
I think you need create list of DataFrames for all small files, then read big file to memory and concat all together by index created by id column:

```<code>import glob

#concat 30 files
files = glob.glob('files/*.csv')
dfs = [pd.read_csv(fp, index_col=['id']) for fp in files]

#if necessary
#df_big = df_big.set_index('id')
df_fin = pd.concat([df_big, dfs], axis=1)
</code>```

There is possible solution a bit modify if there is same order of id values in all DataFrames without duplicates like 1,2,3...N with parameter nrows for read only first rows of big DataFrame by max length of smaller DataFrames:

```<code>#concat 30 files
files = glob.glob('files/*.csv')
dfs = [pd.read_csv(fp, index_col=['a']) for fp in files]

len_max= max([x.index.max() for x in dfs])

df_big= pd.read_csv('big_df_file.csv', index_col=['id'], nrows=len_max)

df_fin = pd.concat([df_big, dfs], axis=1)
</code>```

EDIT:

```<code>#concat 30 files
files = glob.glob('files/*.csv')
#order of files is important for concat values -
#in first file are id = (1,100), second (101, 200)...
print (files)

#set by max rows of file
N = 100
#loop by big fileby chunk define in N
for i, x in enumerate(pd.read_csv('files/big.csv', chunksize=N, index_col=['id'])):
    #added try for avoid errors if want seelct non exist file in list files
    try:
        df = pd.read_csv(files[i], index_col=['id'])
        df1 = pd.concat([x, df], axis=1)
        print (df1)
        #in first loop create header in output
        if i == 0:
            pd.DataFrame(columns=df1.columns).to_csv('files/out.csv')
        #append data to output file
        df1.to_csv('files/out.csv', mode='a', header=False)

    except IndexError as e:
        print ('no files in list')
</code>```

Body:
I have a 20-30 csv files containing 3 columns like 'id','col1','col2','col3' and 1 big csv file of 20GB size that i want to read in chunks and merge with these samller csv files.
the bigger csv file has columns as 'id','name','zipdeails'.
both have ID column in same sequences,
smaple looks like

 'id','name','zipdeails'
  1,Ravi,2031345
  2,Shayam,201344
  3,Priya,20134
  .........
  1000,Pravn,204324

chunk file 1 looks like

 'id','col1','col2','col3'
    1,Heat,,
    2,Goa,Next,
    3,,,Delhi

all the smaller csv files are of same lenth(number of rows) except for the last file which may be smaller in length with header in each. the bigger csv file to which these are to be merged can be broken into chunksize that is equal to the length of these smaller files
so Last chunk looks like

'id','col1','col2','col3'
   1000,Jaipur,Week,Trip

Now the output should look like

'id','name','zipdeails','col1','col2','col3'
 1,Ravi,2031345,Heat,NAN,NAN
 2,Shayam,201344,Goa,Next,NAN
 3,Priya,20134,NAN,NAN,Delhi
  .........
 1000,Pravn,204324,Jaipur,Week,Trip

Body:
I think you need create list of DataFrames for all small files, then read big file to memory and concat all together by index created by id column:

import glob

#concat 30 files
files = glob.glob('files/*.csv')
dfs = [pd.read_csv(fp, index_col=['id']) for fp in files]

#if necessary
#df_big = df_big.set_index('id')
df_fin = pd.concat([df_big, dfs], axis=1)

There is possible solution a bit modify if there is same order of id values in all DataFrames without duplicates like 1,2,3...N with parameter nrows for read only first rows of big DataFrame by max length of smaller DataFrames:

#concat 30 files
files = glob.glob('files/*.csv')
dfs = [pd.read_csv(fp, index_col=['a']) for fp in files]

len_max= max([x.index.max() for x in dfs])

df_big= pd.read_csv('big_df_file.csv', index_col=['id'], nrows=len_max)

df_fin = pd.concat([df_big, dfs], axis=1)

EDIT:

#concat 30 files
files = glob.glob('files/*.csv')
#order of files is important for concat values -
#in first file are id = (1,100), second (101, 200)...
print (files)

#set by max rows of file
N = 100
#loop by big fileby chunk define in N
for i, x in enumerate(pd.read_csv('files/big.csv', chunksize=N, index_col=['id'])):
    #added try for avoid errors if want seelct non exist file in list files
    try:
        df = pd.read_csv(files[i], index_col=['id'])
        df1 = pd.concat([x, df], axis=1)
        print (df1)
        #in first loop create header in output
        if i == 0:
            pd.DataFrame(columns=df1.columns).to_csv('files/out.csv')
        #append data to output file
        df1.to_csv('files/out.csv', mode='a', header=False)

    except IndexError as e:
        print ('no files in list')


问:
Node JS res.sendFile() not working
I'm getting ReferenceError: main is not defined
when I open up the http://localhost:3000/

Here I try to open up the main.html located in views directory

This is my app.js

```<code>const express = require('express'),
  app = express(),
  config = require('./config/index'),
  routes = require('./routes/route');

app.use(express.static(`${__dirname}/public`));
app.use(express.static(`${__dirname}/views`));
app.use('/',routes);
app.listen(config.port,()=>{
console.log(`Listing at port ${config.port}`)})
</code>```

This is my route.js

```<code>const express = require('express'),
router = express.Router(),
helpers = require('../helpers/index');

router.route('/')
.get(helpers.index)

module.exports = router
</code>```

This is my helpers/index.js

```<code>var user = require('../user/user');

exports.index = (req,res)=>{
    if(user.name == ''){
        res.sendFile(main.html);
    }
    else{
        res.sendFile(chat.html)
    }
}

module.exports = exports;
</code>```

Directory Structure

```<code>>helpers
  >index.js
>routes
  >route.js
>user
  >user.js
>views
  >main.html
  >chat.html
app.js
pacakage.json
</code>```

答:
In addition to jfriend00's answer, you must also, build the correct absolute path, using the global __dirname variable in node.

So your path will be something like: res.sendFile(__dirname + "/main.html")
or, depending on your folder structure: res.sendFile(__dirname + "/someadditionalfoldrs/main.html")

or, construct the path using "./" if applicable, like "./main.html";

Title: Node JS res.sendFile() not working

Body:
I'm getting ReferenceError: main is not defined
when I open up the http://localhost:3000/

Here I try to open up the main.html located in views directory

This is my app.js

const express = require('express'),
  app = express(),
  config = require('./config/index'),
  routes = require('./routes/route');

app.use(express.static(`${__dirname}/public`));
app.use(express.static(`${__dirname}/views`));
app.use('/',routes);
app.listen(config.port,()=>{
console.log(`Listing at port ${config.port}`)})

This is my route.js

const express = require('express'),
router = express.Router(),
helpers = require('../helpers/index');

router.route('/')
.get(helpers.index)

module.exports = router

This is my helpers/index.js

var user = require('../user/user');

exports.index = (req,res)=>{
    if(user.name == ''){
        res.sendFile(main.html);
    }
    else{
        res.sendFile(chat.html)
    }
}

module.exports = exports;

Directory Structure

>helpers
  >index.js
>routes
  >route.js
>user
  >user.js
>views
  >main.html
  >chat.html
app.js
pacakage.json


问:
Datatable containing SqlGeometry is causing stored procedure execution to fail... Why?
I'm trying to save a series of SqlGeometry values to a SQL Server 2008 database.

Basically I have a tabletype in a SQL Server stored procedure which looks like this:

```<code>CREATE TYPE [dbo].[TableType_Example] AS TABLE
(
    [SpatialID] [bigint] NOT NULL,
    [RecordID] [bigint] NOT NULL,
    [geom] [geometry] NOT NULL
)
</code>```

I then build a datatable in C# and send it like this:

```<code>public static bool SaveSpatialDataElements(long recordID, List<BOSpatial> featureList)
{
        //Setup features datatable
        DataTable dtFeatures = new DataTable();
        dtFeatures.Columns.Add("SpatialID", typeof(SqlInt64));
        dtFeatures.Columns.Add("RecordID", typeof(SqlInt64));
        dtFeatures.Columns.Add("geom", typeof(SqlGeometry));

        foreach(var curFeature in featureList)
        {
            object[] curRowObjects = new object[dtFeatures.Columns.Count];
            curRowObjects[0] = curFeature.SpatialID;
            curRowObjects[1] = recordID;

            using (var reader = new StringReader(curFeature.ToGML()))
            {
                using (var xmlreader = new XmlTextReader(reader))
                {
                    curRowObjects[2] = SqlGeometry.GeomFromGml(new SqlXml(xmlreader), 0);
                }
            }

            DataRow row = dtFeatures.NewRow();
            row.ItemArray = curRowObjects;
            dtFeatures.Rows.Add(row);
        }

        DbConn conn = new DbConn();
        conn.Connect();
        conn.ExecuteStoredProcedure(false, "USP_tblSpatialLocation_Update", recordID, dtFeatures);
        conn.Disconnect();

        return true;
    }
</code>```

This works fine for all my other datatables but this one contains a SqlGeometry column and it falls over with the error message:

An exception of type 'System.ArgumentException' occurred in
  System.Data.dll but was not handled in user code

Additional information: The type of column 'geom' is not supported.
  The type is 'SqlGeometry'

This doesn't make any sense to me as that datatype seems supported by what I'm reading in the documentation.

Any thoughts?

Edit:

The comments below and the article I've linked: https://viswaug.wordpress.com/2008/09/29/inserting-spatial-data-in-sql-server-2008/ seem to suggest that I need to change the datattype of SqlGeometry to SqlDbType.Udt. Sadly as I'm using a datatable I've got no way of defining UdtTypeName = “GEOMETRY”; as this is set on the parameter.

答:
I also tried to figure out a way to extend the datatable, but didn't manage. However, I did find a good alternative using custom iterations which is probably faster than the datatable and is much more flexible.

checkout these links:

A detailed explanation of how to use custom iterators to pass a table valued param (TVP) to SQL server sproc

An example using SQL geometry in a TVP

I'ts worth noting that this approach has a lighter DB footprint than the WKT method because it doesn't require the DB to convert inputs to a usable format.

Body:
I'm trying to save a series of SqlGeometry values to a SQL Server 2008 database.

Basically I have a tabletype in a SQL Server stored procedure which looks like this:

CREATE TYPE [dbo].[TableType_Example] AS TABLE
(
    [SpatialID] [bigint] NOT NULL,
    [RecordID] [bigint] NOT NULL,
    [geom] [geometry] NOT NULL
)

I then build a datatable in C# and send it like this:

public static bool SaveSpatialDataElements(long recordID, List<BOSpatial> featureList)
{
        //Setup features datatable
        DataTable dtFeatures = new DataTable();
        dtFeatures.Columns.Add("SpatialID", typeof(SqlInt64));
        dtFeatures.Columns.Add("RecordID", typeof(SqlInt64));
        dtFeatures.Columns.Add("geom", typeof(SqlGeometry));

        foreach(var curFeature in featureList)
        {
            object[] curRowObjects = new object[dtFeatures.Columns.Count];
            curRowObjects[0] = curFeature.SpatialID;
            curRowObjects[1] = recordID;

            using (var reader = new StringReader(curFeature.ToGML()))
            {
                using (var xmlreader = new XmlTextReader(reader))
                {
                    curRowObjects[2] = SqlGeometry.GeomFromGml(new SqlXml(xmlreader), 0);
                }
            }

            DataRow row = dtFeatures.NewRow();
            row.ItemArray = curRowObjects;
            dtFeatures.Rows.Add(row);
        }

        DbConn conn = new DbConn();
        conn.Connect();
        conn.ExecuteStoredProcedure(false, "USP_tblSpatialLocation_Update", recordID, dtFeatures);
        conn.Disconnect();

        return true;
    }

This works fine for all my other datatables but this one contains a SqlGeometry column and it falls over with the error message:

An exception of type 'System.ArgumentException' occurred in
  System.Data.dll but was not handled in user code

Additional information: The type of column 'geom' is not supported.
  The type is 'SqlGeometry'

This doesn't make any sense to me as that datatype seems supported by what I'm reading in the documentation.

Any thoughts?

Edit:

The comments below and the article I've linked: https://viswaug.wordpress.com/2008/09/29/inserting-spatial-data-in-sql-server-2008/ seem to suggest that I need to change the datattype of SqlGeometry to SqlDbType.Udt. Sadly as I'm using a datatable I've got no way of defining UdtTypeName = “GEOMETRY”; as this is set on the parameter.


问:
Shell command to split large file into 10 smaller files
I have a csv import file with 33 million lines that need to be imported into my database. I can import it with a C# console app but then the stored procedures that run after the import timeout. Consequently I want to split the file into 10 smaller files.

I could do it in C# but I suspect there's a much better approach using shell utilities. I have cygwin installed and can use all the common Linux shell utilities. Is there a neat little combination of commands I could use to split the file?

答:
If your csv file have 500 rows to split two part(250+250)

download and install "Cygwin Terminal"

put comment "split -l 250 filename.csv"

ContentLicense: CC BY-SA 2.5


问:
identify lines in a file in php
I have a file, which contains passwords/usernames:

thomas 123

john 321

What would be the best way to identify lines and add to them contact information? Right in password file I dont want store, because the size of the file matters.. I thought to add an identifier string before records, like this:

[1]

thomas 123

[2]

john 321

What do you think? It is a good way to identify lines? If yes, how I can read out line after identifier [number]?

If I can read out, then in a second file I can store contact information.

[1]

email, etc

[2]

email etc

this is a config file of an offline app, sadly I cant change the structure of that file (max. change: add an identifier before lines) or use database.

Thank you so much,

Adrian

答:
As zerkms wrote in his comment to your question, you should probably use a database for that. If you don't feel comfortable with setting up a database on a server, look into SQLite (php manual) which is a file-based database which is really easy to use and setup.

If you want to stick with the text-file approach, why write your own format and parser? You could just as well use an existing format like JSON (can be parsed with json_decode) or even an INI file (use parse_ini_file).

And: Never store your text-file at a place where it's globally accessible (eg. webroot).

Title: identify lines in a file in php


问:
Building a Kotlin + Java 9 project with Gradle
I'm fairly new to Gradle (and Java 9, to be honest), and I'm trying to use Gradle to build a simple library project that is a mix of Java 9 and Kotlin. More in detail, there is an interface in Java and an implementation in Kotlin; I'd do everything in Kotlin, but the modules-info.java is java anyway, so I decided to do things this way.

I'm building on IntelliJ Idea, with the 1.2.0 kotlin plugin and gradle 4.3.1 defined externally.

Filesystem schema is:

```<code>+ src
  + main
    + java
      + some.package
        - Roundabout.java [an interface]
      - module-info.java
    + kotlin
      + some.package.impl
        - RoundaboutImpl.kt [implementing the interface]
</code>```

module-info.java is:

```<code>module some.package {
  requires kotlin.stdlib;
  exports some.package;
}
</code>```

and build.gradle is:

```<code>buildscript {
    ext.kotlin_version = '1.2.0'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'some.package'
version '1.0-PRE_ALPHA'

apply plugin: 'java-library'
apply plugin: 'kotlin'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

sourceCompatibility = 9

compileJava {
    dependsOn(':compileKotlin')
    doFirst {
        options.compilerArgs = [
                '--module-path', classpath.asPath,
        ]
        classpath = files()
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: "$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
</code>```

Notice that I had to specify a module path on the java compile task, or the compilation fails with:

error: module not found: kotlin.stdlib
  requires kotlin.stdlib;

Anyway, now this build fails with this error, and I can't figure out how to solve it:

error: package some.package.impl does not exist

import some.package.impl.RoundaboutImpl;

error: cannot find symbol

return new RoundaboutImpl<>(queueSize, parallelism, worker, threadPool);

I think that the Kotlin part of the compilation is going ok, then the java part fails because it doesn't "see" the kotlin side, so to speak.

I think I should tell it somehow to to load the already compiled kotlin classes in the classpath; but (first) how do I do this in gradle? and (second) is it even possible? I think you can't mix module path and class path in Java 9.

How can I solve this? I think it is a pretty common situation, as every java9-style module will be a mixed-language module (because of module-info.java), so I think I'm missing something really basic here.

Thanks in advance!

答:
Solved! It was sufficient to set the kotlin compilation dir to the same dir as Java:

```<code>compileKotlin.destinationDir = compileJava.destinationDir
</code>```

It works now, both with the sources in the same tree or in different trees; but with a quirk: the jar task produces a jar with all the entries duplicated. I'll work on fix this, next.

Thanks to everyone!

Body:
I'm fairly new to Gradle (and Java 9, to be honest), and I'm trying to use Gradle to build a simple library project that is a mix of Java 9 and Kotlin. More in detail, there is an interface in Java and an implementation in Kotlin; I'd do everything in Kotlin, but the modules-info.java is java anyway, so I decided to do things this way.

I'm building on IntelliJ Idea, with the 1.2.0 kotlin plugin and gradle 4.3.1 defined externally.

Filesystem schema is:

+ src
  + main
    + java
      + some.package
        - Roundabout.java [an interface]
      - module-info.java
    + kotlin
      + some.package.impl
        - RoundaboutImpl.kt [implementing the interface]

module-info.java is:

module some.package {
  requires kotlin.stdlib;
  exports some.package;
}

and build.gradle is:

buildscript {
    ext.kotlin_version = '1.2.0'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'some.package'
version '1.0-PRE_ALPHA'

apply plugin: 'java-library'
apply plugin: 'kotlin'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

sourceCompatibility = 9

compileJava {
    dependsOn(':compileKotlin')
    doFirst {
        options.compilerArgs = [
                '--module-path', classpath.asPath,
        ]
        classpath = files()
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: "$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Notice that I had to specify a module path on the java compile task, or the compilation fails with:

error: module not found: kotlin.stdlib
  requires kotlin.stdlib;

Anyway, now this build fails with this error, and I can't figure out how to solve it:

error: package some.package.impl does not exist

import some.package.impl.RoundaboutImpl;

error: cannot find symbol

return new RoundaboutImpl<>(queueSize, parallelism, worker, threadPool);

I think that the Kotlin part of the compilation is going ok, then the java part fails because it doesn't "see" the kotlin side, so to speak.

I think I should tell it somehow to to load the already compiled kotlin classes in the classpath; but (first) how do I do this in gradle? and (second) is it even possible? I think you can't mix module path and class path in Java 9.

How can I solve this? I think it is a pretty common situation, as every java9-style module will be a mixed-language module (because of module-info.java), so I think I'm missing something really basic here.

Thanks in advance!

Body:
Solved! It was sufficient to set the kotlin compilation dir to the same dir as Java:

compileKotlin.destinationDir = compileJava.destinationDir

It works now, both with the sources in the same tree or in different trees; but with a quirk: the jar task produces a jar with all the entries duplicated. I'll work on fix this, next.

Thanks to everyone!


问:
Android use FFMPEG to encode h.264 from camera
I got an Android board (Nanopi M3, Android 5.1). I want to use FFMPEG to encode what I have captured from the camera to h.264 format. What input source should be put in the command in FFMPEG? I don't know how to set input source as camera in command.</p>

答:
First, you need to use the NDK compiler FFmpeg source.you can get so library.

Then you use to collect the Camera data through jni calls for H264 encoding FFmpeg.


问:
Selective role based module loading
I wanted to know if there is any way to selectively load module based on roles.

e.g:-
There are three groups of users namely- admin, biller and end-user. Based on their role, they will be authorized to use certain feature. The app is split into three modules based on same user groups with one common module shared by all of them.
Based on login, is it possible to selectively load only the module required for that particular user?

Note:- routing path is same for all, like /home, /dashboard, /sales etc

Adding a point:
In the above scenario, assume, I have generated four files- admin.chunk.js, biller.chunk.js, end-user.chunk.js and common module will be eagerly loaded with app js.
Based on the user logging in, from the backend, I am selectively sending the js suitable for that logged in user. Now paths for all the components are same, except the part that admin will have access to couple of modules more than end-user. How to manage routing in this case...?

答:
Yes,  CanLoad auth guard can be used to load the modules for authorised user or role. Implement CanLoad interface to check the permission for user then return true if user authorised otherwise redirect to error page.

Note that :  Pre-loading strategies can't load feature modules protected by CanLoad guard. The CanLoad takes precedence over the pre-load strategy. Pre-loading /eagerly loading module must rely on CanActivate guard.

Title: Selective role based module loading


问:
Phone call in background of my android app
I know how to make a phone call from my app using an intent, but the Android dial UI is shown. Is there any possibility of doing it withouth showing the Android dial UI and running the phone call on the background while my app is shown?</p>

答:
First of all make a Service then prepare a flag to check the incoming call is from your own app.
Now if a call comes, service will find it, if the the flag is true, bring your activity up.

```<code>public class OutgoingCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
    //check the flag
    if(GlobalDefinitions.IsProgramRunning) {
        //open your activity immediately after a call
        Intent intent1 = new Intent(context, YOURACTIVITY.class);
        intent1.setFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);
        GlobalDefinitions.IsProgramRunning=false;
    }
}
</code>```

For calling:

```<code>public static void Call( Context context, String phoneNumber) {

    if (!phoneNumber.equals("") ) {
        GlobalDefinitions.IsProgramRunning=true;
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("tel:" + phoneNumber));
        context.startActivity(intent);
    }
}
</code>```

Don't forget to add the Permission and the Service to your manifest

```<code><receiver android:name=".services.OutgoingCallReceiver">
        <intent-filter>
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
        </intent-filter>
</receiver>

<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
</code>```

Body:
First of all make a Service then prepare a flag to check the incoming call is from your own app.
Now if a call comes, service will find it, if the the flag is true, bring your activity up.

public class OutgoingCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
    //check the flag
    if(GlobalDefinitions.IsProgramRunning) {
        //open your activity immediately after a call
        Intent intent1 = new Intent(context, YOURACTIVITY.class);
        intent1.setFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);
        GlobalDefinitions.IsProgramRunning=false;
    }
}

For calling:

public static void Call( Context context, String phoneNumber) {

    if (!phoneNumber.equals("") ) {
        GlobalDefinitions.IsProgramRunning=true;
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("tel:" + phoneNumber));
        context.startActivity(intent);
    }
}

Don't forget to add the Permission and the Service to your manifest

<receiver android:name=".services.OutgoingCallReceiver">
        <intent-filter>
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
        </intent-filter>
</receiver>

<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />


问:
Best match REGEXP pattern
I need to look for 3 kinds of formats that might occur in a string (A = Letter; # = digit):

```<code>A###A
A####
A#####
</code>```

Example:

```<code>This booking has the ID of A#####.
</code>```

The string can contain only one of the three example patterns. I wrote this REGEXP with OR operators, so I can check and extract the IDs I need:

```<code>([a-zA-Z]\d{4})|([a-zA-Z]\d{3}[a-zA-Z])|([a-zA-Z]\d{5})
</code>```

The problem is, that it does not return the best match from the REGEXP, but the first match. For example, if the string contains A#####, it will return A####, ignoring the last digit – becaused it already matched a pattern before.

What am I missing?
Thanks in advance!

答:
You could check for matching 5 characters before you match for 4 characters.
This way it will always detect 5 before it detects 4.
You can just switch the 5 and 4.</p>

```<code>([a-zA-Z]\d{5})|([a-zA-Z]\d{4})|([a-zA-Z]\d{3}[a-zA-Z])
</code>```

Title: Best match REGEXP pattern

Body:
I need to look for 3 kinds of formats that might occur in a string (A = Letter; # = digit):

A###A
A####
A#####

Example:

This booking has the ID of A#####.

The string can contain only one of the three example patterns. I wrote this REGEXP with OR operators, so I can check and extract the IDs I need:

([a-zA-Z]\d{4})|([a-zA-Z]\d{3}[a-zA-Z])|([a-zA-Z]\d{5})

The problem is, that it does not return the best match from the REGEXP, but the first match. For example, if the string contains A#####, it will return A####, ignoring the last digit – becaused it already matched a pattern before.

What am I missing?
Thanks in advance!

Body:
You could check for matching 5 characters before you match for 4 characters.
This way it will always detect 5 before it detects 4.
You can just switch the 5 and 4.

([a-zA-Z]\d{5})|([a-zA-Z]\d{4})|([a-zA-Z]\d{3}[a-zA-Z])


问:
Performance considerations of ECEF vs. Polar coordinates in a modern Earth scale simulation
I am sketching out a new simulation that will involve thousands of ships moving around on Earth's oceans and interacting over long periods of time. So, lots of "intersection detection" for sensor and communications ranges, as well as region detection for various environmental conditions. We'll assume a spherical earth, not WGS84. This is an event-step simulation that spits out metrics, not a real time game or anything like that.

A question is to use Cartesian coordinates (Earth-Centered, Earth-Fixed) or Geodic/polar coordinates. With polar coordinates a ship's track would be internally represented as a series of lat/lon waypoints with times and a great circle paths between them. With a Cartesian representation the waypoints would be connected with polyline renderings of the great circle between them.

The reason this is a question is I suspect that by sticking to a Cartesian data model it becomes possible to use various geometry libraries that are performance tuned, and even offer up SIMD/GPU performance advantages. The polar coordinates would probably be the more natural way to proceed if writing everything from scratch. But I suspect that by keeping things Cartesian I will have greater access to better and faster libraries. Is this an invalid line of thought? Another consideration is that I know polar coordinate calculations tend to get really screwy when near the poles.

Just curious if somebody with experience could save me a whole lot of time prototyping some scenarios both ways.

答:
It often works well to represent directions as unit vectors instead of angles.  Rotation of a vector by another angle becomes a 2x2 or 3x3 matmul (efficient with SIMD, but still more expensive than an FP add of two numbers in radians), but you very rarely need sin/cos.

You may occasionally want atan2 to get an angle, but usually not inside tight loops.

Intersection-detection can be very efficient (with SIMD) for XYZ coordinates given another XYZ + range.  I'm not sure how efficiently you could check which lat/lon pairs were within range of a given point, not a problem I've looked at.

IDK what kind of stuff you'd find in existing libraries, or what you'd want to do with it.


问:
"Prepare for segue" for WatchKit
I am attempting to transfer a string from one view controller to another. The Problem that I having is that it is required to set the string 'as any object'.

The code I have below returns a nil in the console. Is there any way to send data across VC's as strings? Thanks in advance.

In MainVc-

```<code>func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {
    // You may want to set the context's identifier in Interface Builder and check it here to make sure you're returning data at the proper times

    // Return data to be accessed in ResultsController
    var currentValue = "Hellooo"
    return currentValue as String as AnyObject
}
</code>```

In receiving VC.

```<code>override func awake(withContext context: Any?) {
    super.awake(withContext: context)
    if let val: Any = context as? Any {
        print(val)
    } else {
        print("An error occurred")
    }        // Configure interface objects here.
}
</code>```

The output is simply nil.

答:
I came across with the same problem. The solution was as Larme suggested, used the appropriate function for swift 3 or 4, in this case, I assume you tried to use this code

override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {

but the compiler suggests that doesn't have to be overridden because Method does not override any method from its superclass

The easy solution is to remove the override. The app compiles but the contextForSegue function is never dispatched.

The correct structure is as follow:

override func contextForSegue(withIdentifier segueIdentifier: String) -> Any?
    {

Title: "Prepare for segue" for WatchKit

Body:
I am attempting to transfer a string from one view controller to another. The Problem that I having is that it is required to set the string 'as any object'.

The code I have below returns a nil in the console. Is there any way to send data across VC's as strings? Thanks in advance.

In MainVc-

func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {
    // You may want to set the context's identifier in Interface Builder and check it here to make sure you're returning data at the proper times

    // Return data to be accessed in ResultsController
    var currentValue = "Hellooo"
    return currentValue as String as AnyObject
}

In receiving VC.

override func awake(withContext context: Any?) {
    super.awake(withContext: context)
    if let val: Any = context as? Any {
        print(val)
    } else {
        print("An error occurred")
    }        // Configure interface objects here.
}

The output is simply nil.


问:
Javascript function call from  not working
I want to pass the src url of a image via javascript function.

```<code><head>
<script>
function myFunction() {
    var str1 = "somepictureurl.png";
    return str1;
}
</script>
</head>

<body>
    <img src="myFunction()" alt="notworking">
</body>
</code>```

Unfortunately it is not working and the alt "notworking" is displaying.

答:
HTML just doesn't work that way. The JavaScript function can not be called from an element that way.

You'll have to add a method call at the bottom of the page, and pass some kind of id:

```<code><html>
  <head>
    <script>
      function myFunction(id) {
        var str1 = "somepictureurl.png";
        document.getElementById(id).src = str1;
      }
    </script>
  </head>
  <body>
    <img id="img1" alt="notworking">
    <script>
      myFunction("img1");
    </script>
  </body>
</html>
</code>```

Title: Javascript function call from <img src="myFunction()"> not working

Body:
I want to pass the src url of a image via javascript function.

Unfortunately it is not working and the alt "notworking" is displaying.

Body:
HTML just doesn't work that way. The JavaScript function can not be called from an element that way.

You'll have to add a method call at the bottom of the page, and pass some kind of id:

<html>
  <head>
    <script>
      function myFunction(id) {
        var str1 = "somepictureurl.png";
        document.getElementById(id).src = str1;
      }
    </script>
  </head>
  <body>
    <img id="img1" alt="notworking">
    <script>
      myFunction("img1");
    </script>
  </body>
</html>


问:
NuGet: What's the appropriate "FrameworkName" for creating packages with Windows Phone 7 binaries?
I just created a NuGet package for one of my open source projects and it includes a Windows Phone 7 binary. I just tested it and instead of adding the Windows Phone 7-specific library, it added the Silverlight library.

My question is, how can I set up my folder architecture such that the NuGet package manager recognizes my WP7-specific binaries and installs those instead of the Silverlight binaries?

I followed the instructions listed here for targeting multiple frameworks in NuGet packages.

Here's what my folder tree currently looks like:

```<code>\lib
    \.NetFramework 4.0
        \MyAssembly.dll
    \Silverlight 4.0
        \MyAssembly.Silverlight.dll
    \Windows Phone 7
        \MyAssembly.Mobile.dll
</code>```

What should I be doing differently?

答:
We don't support wp7 natively yet since there is no profile support (the profile part of the framework name isn't supported in folders). See this issue for more details http://nuget.codeplex.com/workitem/219.

FWIW: Windows phone 7 is Silverlight 4, Profile=Windows Phone.

For now you'll have to create another package for wp7.

Body:
I just created a NuGet package for one of my open source projects and it includes a Windows Phone 7 binary. I just tested it and instead of adding the Windows Phone 7-specific library, it added the Silverlight library.

My question is, how can I set up my folder architecture such that the NuGet package manager recognizes my WP7-specific binaries and installs those instead of the Silverlight binaries?

I followed the instructions listed here for targeting multiple frameworks in NuGet packages.

Here's what my folder tree currently looks like:

\lib
    \.NetFramework 4.0
        \MyAssembly.dll
    \Silverlight 4.0
        \MyAssembly.Silverlight.dll
    \Windows Phone 7
        \MyAssembly.Mobile.dll

What should I be doing differently?


问:
MongoDB: How to get the last updated timestamp of the last updated document in a collection
Is there a simple OR elegant method (or query that I can write) to retrieve the last updated timestamp (of the last updated document) in a collection. I can write a query like this to find the last inserted document

```<code>db.collection.find().limit(1).sort({$natural:-1})
</code>```

but I need information about the last updated document (it could be an insert or an update).

I know that one way is to query the oplog collection for the last record from a collection. But it seems like an expensive operation given the fact that oplog could be of very large size (also not trustworthy as it is a capped collection). Is there a better way to do this?

Thanks!

答:
You can try with ,</p>

```<code>db.collection.findOne().sort({$natural:-1}).limit(1);
</code>```

Body:
Is there a simple OR elegant method (or query that I can write) to retrieve the last updated timestamp (of the last updated document) in a collection. I can write a query like this to find the last inserted document

db.collection.find().limit(1).sort({$natural:-1})

but I need information about the last updated document (it could be an insert or an update).

I know that one way is to query the oplog collection for the last record from a collection. But it seems like an expensive operation given the fact that oplog could be of very large size (also not trustworthy as it is a capped collection). Is there a better way to do this?

Thanks!

Body:
You can try with ,

db.collection.findOne().sort({$natural:-1}).limit(1);


问:
How Deadlock Happen resolved on Same Table insertion and update
I have a SSIS package with a task to load data. For some reason i need to update and insert same destination table. This happen deadlock

I use SSIS MULTI-CAST control.

What to do? how to resolve this situation?

答:
Your way seems strange, as billinkc said, you are effectively double data rows and perform INSERT and UPDATE actions with the same table concurrently from two different connections/contexts. This have to end in a deadlock.

I would use alternative approach - do required transforms with the data, and then write it to an intermediate table in the DataFlow. Then on the next SSIS task - execute MS SQL MERGE - Microsoft table upsert - with OLE DB Command. This will assure you do not have a deadlock between concurrent operations, logic of the MERGE could be quite flexible.

Last but not the least - use dedicated or global ##temp table for an intermediate table, Working with regular MS SQL #temp tables in SSIS is little tricky. Do not forget to clean up intermediate before and after MERGE, or create and dispose of ##temp table properly.


问:
How to Call URL in API Nested Array
I'm new to REST API and am having some trouble. I'm trying to call data from an array that's nested within a dictionary. While I've been able to pull data from other variables fine, this is giving me some problems. For reference, the URL I need is labeled "front default," inside the "sprites" array. Furthermore, the URL is that of an image, and I am using Alamofire Image to display images. I will include the code I've used thus far to call other variables, along with a screenshot of the API's structure.

Screenshot of API hierarchy

```<code>import Foundation
import Alamofire
import AlamofireImage
import SwiftyJSON
import Siesta

class PokeInfo {
var name: String
var id: Int
var abilities: [String]
var types: [String]

// converts dictionary into string
init?(jsonDictionary: [String: Any]) {
    //guard used to check if value entered in search bar matches a name in API data
    guard let name = jsonDictionary["name"] as? String,

        let id = jsonDictionary["id"] as? Int,
        //abilities data nested. First must be set to string
        let abilities = jsonDictionary["abilities"] as? [[String: Any]],
    let types = jsonDictionary["types"] as? [[String: Any]]
    else {
            return nil
    };

    var abilityNames: [String] = []
     var typeNames: [String] = []

    //targets nested data, going inside dictionary to find attributes of that element
    for abilityDictionary in abilities {

        guard let ability = abilityDictionary["ability"] as? [String: Any], let name = ability["name"] as? String else { break }

        abilityNames.append(name)
    };
    for typeDictionary in types {

        guard let type = typeDictionary["type"] as? [String: Any], let name = type["name"] as? String else { break }

        typeNames.append(name)
    }

    self.name = name
    self.id = id
    self.abilities = abilityNames
    self.types = typeNames

}

}
</code>```

答:
As of Swift 4 you should be using Codable for JSON which is now part of the language.  Here is a Playground example:

```<code>import PlaygroundSupport
import UIKit

class PokeInfo: Codable {
    var name: String
    var id: Int
    var abilities: [String]
    var types: [String]
}

let pokeString = """
{
"name": "test",
"id": 1,
"abilities": ["a", "b", "c"],
"types": ["x", "y", "z"]
}
"""
let pokeData = pokeString.data(using: .utf8)!

let decoder = JSONDecoder()
let pokeInfo = try! decoder.decode(PokeInfo.self, from: pokeData)
print(pokeInfo.abilities)
</code>```

the output is:

```<code>["a", "b", "c"]
</code>```

Title: How to Call URL in API Nested Array

Body:
I'm new to REST API and am having some trouble. I'm trying to call data from an array that's nested within a dictionary. While I've been able to pull data from other variables fine, this is giving me some problems. For reference, the URL I need is labeled "front default," inside the "sprites" array. Furthermore, the URL is that of an image, and I am using Alamofire Image to display images. I will include the code I've used thus far to call other variables, along with a screenshot of the API's structure.

Screenshot of API hierarchy

import Foundation
import Alamofire
import AlamofireImage
import SwiftyJSON
import Siesta

class PokeInfo {
var name: String
var id: Int
var abilities: [String]
var types: [String]

// converts dictionary into string
init?(jsonDictionary: [String: Any]) {
    //guard used to check if value entered in search bar matches a name in API data
    guard let name = jsonDictionary["name"] as? String,

        let id = jsonDictionary["id"] as? Int,
        //abilities data nested. First must be set to string
        let abilities = jsonDictionary["abilities"] as? [[String: Any]],
    let types = jsonDictionary["types"] as? [[String: Any]]
    else {
            return nil
    };

    var abilityNames: [String] = []
     var typeNames: [String] = []

    //targets nested data, going inside dictionary to find attributes of that element
    for abilityDictionary in abilities {

        guard let ability = abilityDictionary["ability"] as? [String: Any], let name = ability["name"] as? String else { break }

        abilityNames.append(name)
    };
    for typeDictionary in types {

        guard let type = typeDictionary["type"] as? [String: Any], let name = type["name"] as? String else { break }

        typeNames.append(name)
    }

    self.name = name
    self.id = id
    self.abilities = abilityNames
    self.types = typeNames

}

}

Body:
As of Swift 4 you should be using Codable for JSON which is now part of the language.  Here is a Playground example:

import PlaygroundSupport
import UIKit

class PokeInfo: Codable {
    var name: String
    var id: Int
    var abilities: [String]
    var types: [String]
}

let pokeString = """
{
"name": "test",
"id": 1,
"abilities": ["a", "b", "c"],
"types": ["x", "y", "z"]
}
"""
let pokeData = pokeString.data(using: .utf8)!

let decoder = JSONDecoder()
let pokeInfo = try! decoder.decode(PokeInfo.self, from: pokeData)
print(pokeInfo.abilities)

the output is:

["a", "b", "c"]


问:
SQL Where with Binary(n) column
I have a stored procedure:

```<code>ALTER PROCEDURE [dbo].[spUpdateOrInsertNotification]
    @ContentJsonHash BINARY(32)
AS
    DECLARE @NotificationId INT;

    SET @NotificationId = (SELECT @NotificationId
                           FROM dbo.tblNotifications n
                           WHERE n.ContentJsonHash = @ContentJsonHash);

    IF @NotificationId IS NOT NULL
    BEGIN
        -- Increment Count
    END
    ELSE
    BEGIN
         -- Insert new row.
    END
</code>```

It's supposed to check if the Hash already exists and if it does, increment the count for the row, otherwise insert the row. However, it never finds the Hash and the corresponding NotificationId. NotificationId is always null.

If I run it twice, passing it the same data (a C# array byte[32]). It never finds the same NotificationId and I end up with duplicate entries being put in.

e.g.

```<code>NotificationId | ContentJsonHash
9                0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
10               0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
</code>```

Can I not do comparisons on Binary(n) fields like this WHERE n.ContentJsonHash = @ContentJsonhash ?

The C# code:

```<code>using (var conn = new SqlConnection(Sql.ConnectionString))
{
     await conn.OpenAsync();

     using (var cmd = new SqlCommand(Sql.SqlUpdateOrInsertNotification, conn))
     {
          cmd.CommandType = CommandType.StoredProcedure;

          cmd.Parameters.AddWithValue("@Source", notificationMessage.Source);
          cmd.Parameters.AddWithValue("@Sender", notificationMessage.Sender);
          cmd.Parameters.AddWithValue("@NotificationType", notificationMessage.NotificationType);
          cmd.Parameters.AddWithValue("@ReceivedTimestamp", notificationMessage.Timestamp);
          cmd.Parameters.AddWithValue("@ContentJSon", notificationMessage.NotificationContent);
          cmd.Parameters.AddWithValue("@ContentJsonHash", notificationMessage.ContentHashBytes);

          await cmd.ExecuteNonQueryAsync();
    }
}
</code>```

I've also tried calling the stored procedure from SQL like this:

```<code>exec dbo.spUpdateOrInsertNotification 'foo', 'bar',  0,
                                      '2017-12-05 15:23:41.207', '{}',
                              0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
</code>```

Calling this twice returns 2 rows :(

I can do this, which works, hard coding the binary field I want to check

```<code>select *
from dbo.tblNotifications
where ContentJsonhash = 0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
</code>```

答:
I had an @ where I shouldn't have had an ampersand.

```<code>SET @NotificationId = (SELECT @NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));
</code>```

Should be

```<code>SET @NotificationId = (SELECT NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));
</code>```

I feel so stupid for not noticing this sooner :(

Title: SQL Where with Binary(n) column

Body:
I have a stored procedure:

ALTER PROCEDURE [dbo].[spUpdateOrInsertNotification]
    @ContentJsonHash BINARY(32)
AS
    DECLARE @NotificationId INT;

    SET @NotificationId = (SELECT @NotificationId
                           FROM dbo.tblNotifications n
                           WHERE n.ContentJsonHash = @ContentJsonHash);

    IF @NotificationId IS NOT NULL
    BEGIN
        -- Increment Count
    END
    ELSE
    BEGIN
         -- Insert new row.
    END

It's supposed to check if the Hash already exists and if it does, increment the count for the row, otherwise insert the row. However, it never finds the Hash and the corresponding NotificationId. NotificationId is always null.

If I run it twice, passing it the same data (a C# array byte[32]). It never finds the same NotificationId and I end up with duplicate entries being put in.

e.g.

NotificationId | ContentJsonHash
9                0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
10               0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A

Can I not do comparisons on Binary(n) fields like this WHERE n.ContentJsonHash = @ContentJsonhash ?

The C# code:

using (var conn = new SqlConnection(Sql.ConnectionString))
{
     await conn.OpenAsync();

     using (var cmd = new SqlCommand(Sql.SqlUpdateOrInsertNotification, conn))
     {
          cmd.CommandType = CommandType.StoredProcedure;

          cmd.Parameters.AddWithValue("@Source", notificationMessage.Source);
          cmd.Parameters.AddWithValue("@Sender", notificationMessage.Sender);
          cmd.Parameters.AddWithValue("@NotificationType", notificationMessage.NotificationType);
          cmd.Parameters.AddWithValue("@ReceivedTimestamp", notificationMessage.Timestamp);
          cmd.Parameters.AddWithValue("@ContentJSon", notificationMessage.NotificationContent);
          cmd.Parameters.AddWithValue("@ContentJsonHash", notificationMessage.ContentHashBytes);

          await cmd.ExecuteNonQueryAsync();
    }
}

I've also tried calling the stored procedure from SQL like this:

exec dbo.spUpdateOrInsertNotification 'foo', 'bar',  0,
                                      '2017-12-05 15:23:41.207', '{}',
                              0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A

Calling this twice returns 2 rows :(

I can do this, which works, hard coding the binary field I want to check

select *
from dbo.tblNotifications
where ContentJsonhash = 0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A

Body:
I had an @ where I shouldn't have had an ampersand.

SET @NotificationId = (SELECT @NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));

Should be

SET @NotificationId = (SELECT NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));

I feel so stupid for not noticing this sooner :(


问:
Arranging numbers in a file using C
I need to take the numbers listed in the two files "numbers1.txt" and "numbers2.txt" (where the numbers are listed in ascending order) and move them to a file named "output.txt" where they are arranged in ascending order.

Here is what I have so far:

```<code>void appendToOutput(FILE *numFile1, FILE *numFile2, FILE *outputFile)
{
int num1 = 0;
int num2 = 0;

do {
    fscanf(numFile1, "%d", &num1);
    fscanf(numFile2, "%d", &num2);
    while ((num1 < num2) && !feof(numFile1))
    {
        fprintf(outputFile, "%d\n", num1);
        fscanf(numFile1, "%d", &num1);
    }
    while ((num2 < num1) && !feof(numFile2))
    {
        fprintf(outputFile, "%d\n", num2);
        fscanf(numFile2, "%d", &num2);
    }
    if (num1 == num2)
    {
        fprintf(outputFile, "%d\n%d\n", num1, num2);
    }
} while (!feof(numFile1) || !feof(numFile2));

return;
}
</code>```

my files look like the following:

numbers1.txt

```<code>1
2
3
4
5
6
7
8
9
10
11
12
</code>```

numbers2.txt:

```<code>2
4
6
8
10
12
14
16
18
20
22
24
</code>```

The issue I am having is that the output file ends up looking like this:
output.txt

```<code>1
2
2
3
4
4
5
6
6
7
8
8
9
10
10
11
12
12
</code>```

So my issue is that the program is not continuing to read/write numbers from numbers2.txt even though it has not yet hit the end of it's file. I've looked through it and I can't seem to find out why it's stopping, so help would be appreciated!

答:
There are a few problems with the current code

Initialization of the 2 numbers should be performed before the main loop

Use of feof() here

Test of strict < insteaf of <= (could lock your algo)

Keep reading a file if the other one becomes empty

Regarding 2., fscanf returns a number >0 if it could read the number, so you can test this instead of checking feof (that says that EOF (a stop condition) happened before, and this might trigger one more unwanted iteration).

Suggested fixed code:

```<code>int read1 = fscanf(numFile1, "%d", &num1);
int read2 = fscanf(numFile2, "%d", &num2);

while (read1 > 0 || read2 > 0) {
    while (read1 > 0 && (read2<=0 || num1 <= num2))
    {
        fprintf(outputFile, "%d\n", num1);
        read1 = fscanf(numFile1, "%d", &num1);
    }
    while (read2 > 0 && (read1<=0 || num2 <= num1))
    {
        fprintf(outputFile, "%d\n", num2);
        read2 = fscanf(numFile2, "%d", &num2);
    }
}
</code>```

Further explanations

readX<=0 || numY <= numX addresses 4.

readX = fscanf(...) addresses2.

Title: Arranging numbers in a file using C

Body:
I need to take the numbers listed in the two files "numbers1.txt" and "numbers2.txt" (where the numbers are listed in ascending order) and move them to a file named "output.txt" where they are arranged in ascending order.

Here is what I have so far:

void appendToOutput(FILE *numFile1, FILE *numFile2, FILE *outputFile)
{
int num1 = 0;
int num2 = 0;

do {
    fscanf(numFile1, "%d", &num1);
    fscanf(numFile2, "%d", &num2);
    while ((num1 < num2) && !feof(numFile1))
    {
        fprintf(outputFile, "%d\n", num1);
        fscanf(numFile1, "%d", &num1);
    }
    while ((num2 < num1) && !feof(numFile2))
    {
        fprintf(outputFile, "%d\n", num2);
        fscanf(numFile2, "%d", &num2);
    }
    if (num1 == num2)
    {
        fprintf(outputFile, "%d\n%d\n", num1, num2);
    }
} while (!feof(numFile1) || !feof(numFile2));

return;
}

my files look like the following:

numbers1.txt

1
2
3
4
5
6
7
8
9
10
11
12

numbers2.txt:

2
4
6
8
10
12
14
16
18
20
22
24

The issue I am having is that the output file ends up looking like this:
output.txt

1
2
2
3
4
4
5
6
6
7
8
8
9
10
10
11
12
12

So my issue is that the program is not continuing to read/write numbers from numbers2.txt even though it has not yet hit the end of it's file. I've looked through it and I can't seem to find out why it's stopping, so help would be appreciated!

Body:
There are a few problems with the current code

Initialization of the 2 numbers should be performed before the main loop

Use of feof() here

Test of strict < insteaf of <= (could lock your algo)

Keep reading a file if the other one becomes empty

Regarding 2., fscanf returns a number >0 if it could read the number, so you can test this instead of checking feof (that says that EOF (a stop condition) happened before, and this might trigger one more unwanted iteration).

Suggested fixed code:

int read1 = fscanf(numFile1, "%d", &num1);
int read2 = fscanf(numFile2, "%d", &num2);

while (read1 > 0 || read2 > 0) {
    while (read1 > 0 && (read2<=0 || num1 <= num2))
    {
        fprintf(outputFile, "%d\n", num1);
        read1 = fscanf(numFile1, "%d", &num1);
    }
    while (read2 > 0 && (read1<=0 || num2 <= num1))
    {
        fprintf(outputFile, "%d\n", num2);
        read2 = fscanf(numFile2, "%d", &num2);
    }
}

Further explanations

readX<=0 || numY <= numX addresses 4.

readX = fscanf(...) addresses2.


问:
Would OnPush strategy be useless/wrong if a component has no input bindings?
I'm a newbie to Angular environment and recently, I've been struggling with the change detection strategy. According to many articles I've read, with OnPush strategy, a component tells Angular that you can skip change detection for me unless there's a change on my input bindings. Here comes my question: As the title says, would OnPush strategy be useless/wrong if a component has no input bindings?</p>

答:
No, OnPush still makes sense.

With OnPush change detection also is automatically invoked if an event binding or an |asnyc pipe of the component receives an event.

OnPush also prevents, as you mentioned, change detection to be run automatically when it is run on parent components, which might be inefficient.


问:
Spring Jackson java.time Deserialization: arguments mismatched
How do I deserialize Java 8 time API classes?

Here's what I've done:

Included dependency: compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

Request body to be deserialized into:

```<code>import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.joda.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;

public class TestRequest {
    @JsonSerialize(using = LocalDateSerializer.class)
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "YYYY-MM-dd")
    LocalDate localDate;
}
</code>```

Spring Controller:

```<code>public ResponseEntity test(@RequestBody TestRequest testRequest) {
    return ResponseEntity.ok(testRequest);
}
</code>```

JSON Request Body:

```<code>{ "localDate": "2017-11-01" }
</code>```

The Exception:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of TestRequest, problem: argument type mismatch

答: you should use jackson-modules-java8 instead of jackson-datatype-jsr310 to serialize or deserialize java 8 classes.</p>

Body:
How do I deserialize Java 8 time API classes?

Here's what I've done:

Included dependency: compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

Request body to be deserialized into:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.joda.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;

public class TestRequest {
    @JsonSerialize(using = LocalDateSerializer.class)
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "YYYY-MM-dd")
    LocalDate localDate;
}

Spring Controller:

public ResponseEntity test(@RequestBody TestRequest testRequest) {
    return ResponseEntity.ok(testRequest);
}

JSON Request Body:

{ "localDate": "2017-11-01" }

The Exception:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of TestRequest, problem: argument type mismatch


问:
Nested dictionary: sum values of same key of the dictionaries nested as a value of dictionary
I want to sum values of the same key: H, C, O, N, S according to dictionary composition for the string input which is a combination of letter A, C, D, E.

```<code>composition = {
    'A':  {'H': 5, 'C': 3, 'O': 1, 'N': 1},
    'C':  {'H': 5, 'C': 3, 'O': 1, 'N': 1, 'S': 1},
    'D':  {'H': 5, 'C': 4, 'O': 3, 'N': 1},
    'E':  {'H': 7, 'C': 5, 'O': 3, 'N': 1},
}

string_input = ['ACDE', 'CCCDA']
</code>```

The expected result should be

```<code>out = {
    'ACDE' : {'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1},
    'CCCDA' : {'H': 15, 'C': 9, 'O': 3, 'N': 3, 'S': 3},
}
</code>```

I am trying to use Counter but stuck at unsupported operand type(s) for +: 'int' and 'Counter'

```<code>from collections import Counter

for each in string_input:
  out = sum(Counter(composition[aa]) for aa in each)
</code>```

答:
Three nested for loops should do the work.</p>

```<code>out = {}
for x in string_input: # for each string in list
    current = out[x] = {}
    for char in x: # for each character in the string
        cur_composition=composition[char]
        for val in cur_composition: # for all the entry in the composition dictionary for that character
            current[char]= cur_composition[val] if val not in current[char] else cur_composition[val]+current[char]
</code>```

Body:
I want to sum values of the same key: H, C, O, N, S according to dictionary composition for the string input which is a combination of letter A, C, D, E.

composition = {
    'A':  {'H': 5, 'C': 3, 'O': 1, 'N': 1},
    'C':  {'H': 5, 'C': 3, 'O': 1, 'N': 1, 'S': 1},
    'D':  {'H': 5, 'C': 4, 'O': 3, 'N': 1},
    'E':  {'H': 7, 'C': 5, 'O': 3, 'N': 1},
}

string_input = ['ACDE', 'CCCDA']

The expected result should be

out = {
    'ACDE' : {'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1},
    'CCCDA' : {'H': 15, 'C': 9, 'O': 3, 'N': 3, 'S': 3},
}

I am trying to use Counter but stuck at unsupported operand type(s) for +: 'int' and 'Counter'

from collections import Counter

for each in string_input:
  out = sum(Counter(composition[aa]) for aa in each)

Body:
Three nested for loops should do the work.

out = {}
for x in string_input: # for each string in list
    current = out[x] = {}
    for char in x: # for each character in the string
        cur_composition=composition[char]
        for val in cur_composition: # for all the entry in the composition dictionary for that character
            current[char]= cur_composition[val] if val not in current[char] else cur_composition[val]+current[char]


问:
codeigniter's controller to main controller in a specific div
```<code><li><a href="maine/home#services">SERVICES</a></li>
<li><a href="maine/home#about">ABOUT</a></li>
<li><a href="maine/home#contact">CONTACT</a></li>
</code>```

I'm using CodeIgniter and this code was in a different controller. suppose http://localhost/defctrl/function1

I want to return to my homepage "maine/home" in a specific div when you click on the list but the above code doesn't work. neither ../maine/home#services.

How can I solve this problem?

答:
if it's on the same page you can use

```<code><li><a href="#services"
</code>```

if another page

```<code><li><a href="<?php echo base_url() ?>{route or controller name}#services"
</code>```

Make sure URL helper is loaded and site load with index.php

Body:
SERVICES

ABOUT

CONTACT

I'm using CodeIgniter and this code was in a different controller. suppose http://localhost/defctrl/function1

I want to return to my homepage "maine/home" in a specific div when you click on the list but the above code doesn't work. neither ../maine/home#services.

How can I solve this problem?

Body:
if it's on the same page you can use

<li><a href="#services"

if another page

<li><a href="<?php echo base_url() ?>{route or controller name}#services"

Make sure URL helper is loaded and site load with index.php


问:
Ext js 6.2, Pin the west panel so that It won't collapse?
I'm using Ext Js v6.2, In my application, I have West panel, It can collapsed or expand, But In that I have Pin Tools Button, so if user click the Pin, Panel stay until user click unpin, I'm newbie to Ext js, I've tried using panel expanded or collapsed but It doesn't help, please solve the problem. Thanks in advance.

```<code>tools: [{
    type: 'pin',
    cls: 'leftPanelPin',
    tooltip: 'Pin Panel',
    handler: function() {
        toggleCollapse: function() {
            if (this.lockedPanel) {
                this[this.collapsed ? 'expand' : 'collapse'](animate);
                return this;
            }
        }
    }
}]
</code>```

答:
You can use the beforecollapse listener to check whether the panel is pinned and return false, which will prevent the collapsing. Fiddle:

https://fiddle.sencha.com/#view/editor&fiddle/2aj8

Body:
I'm using Ext Js v6.2, In my application, I have West panel, It can collapsed or expand, But In that I have Pin Tools Button, so if user click the Pin, Panel stay until user click unpin, I'm newbie to Ext js, I've tried using panel expanded or collapsed but It doesn't help, please solve the problem. Thanks in advance.

tools: [{
    type: 'pin',
    cls: 'leftPanelPin',
    tooltip: 'Pin Panel',
    handler: function() {
        toggleCollapse: function() {
            if (this.lockedPanel) {
                this[this.collapsed ? 'expand' : 'collapse'](animate);
                return this;
            }
        }
    }
}]


问:
Turning tags on and off?
I'm just getting started with GTM.  I'd like to use it primarily to send custom Analytics events about user actions.  However, I think I'm missing something obvious - is there a way to turn an event or a trigger on and off?  Like if I want to stop tracking some user action, but I might want to do it again later without having to delete/recreate everything.</p>

答: There is no off setting for tags. Best workaround IMO is to create a trigger of the type "Custom Event", enable regular expressions and use ".*" as pattern for the event name. Then add this as trigger exception to the tag you want to pause. Since the exceptions fires on every event the tag will now never be fired. You still need to publish this, though, there is no quick on/off thing.</p>

Title: Turning tags on and off?


问:
Performance test for salesforce
I am working on salesforce UI’s.

How can I ensure that whatever UI’s created are able to handle a load.

Do I need to do performance testing?

Please suggest tools , process so that 500 user load / performance testing if any?

答:
Tool choice depends on many factors, i.e.

ability to integrate flawlessly into your existing SDLC (i.e. if you have Java stack a Python-based tool would be an "alien)

support of all required use cases (nearly all load testing tools are suitable for web applications testing, however when it comes to more "exotic" tasks like communicating with database, WebSockets, handle AJAX requests, etc.) the choice might be less wide

bugdet (there are some proprietary solutions which cost millions of coins and free/open source options)

skills (the tool might require coding skills which you and your team may or may not have)

You can find quite a list for instance here: http://www.opensourcetesting.org/category/testing-tools-overview/performance/?menu-page=overview

Given you have java tag I would recommend to stick to one of the following:

The Grinder

Gatling

Apache JMeter

Check out Open Source Load Testing Tools: Which One Should You Use? article which highlights main features of the above tools followed by comparison matrix, sample scripts, reports, etc., hopefully it will help you to choose the right option.

ContentLicense: CC BY-SA 4.0

Title: Performance test for salesforce


问:
My page scrolls horizontally on mobile
I just found out that my website is scrolling horizontally on mobile. However, I am not able to find out why this is happening.

The containers and body seem to have the correct width when I check it in my browser.

Any idea?

https://www.urban-zweirad.de

Cheers,
Mark

答:
Your problem lies in this part of your HTML. @pons awnsered correct.

```<code><div class="container-fluid center teaser" data-plim="495">
    <div class="row">
        <div class="col-xs-12">
            ...
        </div>
    </div>
</div>
</code>```

How can you fix it? You could remove the .row class. As this is not neccessary because its a full width bootstrap col. And the .container-fluid allready  clearfixes the floats.

You also just could change the CSS of the .teaser class into:

```<code>.teaser {
    padding: 0 !important;
    overflow: hidden; // This fixes the negative margin on the row to be hidden inside its parent.
}
</code>```

Title: My page scrolls horizontally on mobile

Body:
Your problem lies in this part of your HTML. @pons awnsered correct.

<div class="container-fluid center teaser" data-plim="495">
    <div class="row">
        <div class="col-xs-12">
            ...
        </div>
    </div>
</div>

How can you fix it? You could remove the .row class. As this is not neccessary because its a full width bootstrap col. And the .container-fluid allready  clearfixes the floats.

You also just could change the CSS of the .teaser class into:

.teaser {
    padding: 0 !important;
    overflow: hidden; // This fixes the negative margin on the row to be hidden inside its parent.
}


问:
Getting Value of Scroll Not Outputting
Why is the value of scroll outputting as undefined?  I'm making an extension with chrome.</p>

```<code>var scroll = document.body.scrollTop;
console.log(scroll);
</code>```

答:
W3C Documentation is at:

https://www.w3schools.com/jsref/prop_element_scrolltop.asp

From the documentation:

```<code>var body = document.body; // Safari
var html = document.documentElement;
    // Chrome, Firefox, IE and Opera places the overflow at
    // the <html> level, unless else is specified. Therefore,
    // we use the documentElement property for these browsers
body.scrollLeft += 30;
body.scrollTop += 10;
html.scrollLeft += 30;
html.scrollTop += 10;
</code>```

Title: Getting Value of Scroll Not Outputting

Body:
Why is the value of scroll outputting as undefined?  I'm making an extension with chrome.

var scroll = document.body.scrollTop;
console.log(scroll);

Body:
W3C Documentation is at:

https://www.w3schools.com/jsref/prop_element_scrolltop.asp

From the documentation:

var body = document.body; // Safari
var html = document.documentElement;
    // Chrome, Firefox, IE and Opera places the overflow at
    // the <html> level, unless else is specified. Therefore,
    // we use the documentElement property for these browsers
body.scrollLeft += 30;
body.scrollTop += 10;
html.scrollLeft += 30;
html.scrollTop += 10;


问:
How do I prevent libtorrent from creating a folder with a name?
When downloading a torrent via libtorrent (a library for C ++), a folder with the name of the torrent is created, into which all the files are downloaded. In uTorrent, for example, you can remove the "Create subfolder" check mark when adding a torrent and everything will be fine. How to do it in libtorrent?

Is it possible to change the names of the torrent (folder)?

答:
To remove the directory from the file hierarchy, you can rename every file to the same name but with the torrent name root directory stripped off.

You should be able to do this both on the torrent_info before adding the torrent, or on the torrent_handle after adding it. But if you add it first the root directory will still be created.

See rename_file()


问:
Arrays unique element and Mobile apps data structure
Recently below questions were asked in an interview

You are given an array of integer with all elements repeated twice except one element which occurs only once, you need to find the unique element with O(nlogn)time complexity. Suppose array is {2,47,2,36,3,47,36} the output should be 3 here. I told we can perform merge sort(as it takes(nlogn)) after that we can check next element, but he said it will take O(nlogn)+O(n). I also told we can use HashMap to keep count of elements but again he said no as we have to iterate over hashmap again to get results. After some research, I came to know that using xor operation will give output in O(n). Is there any better solution other than sorting which can give the answer in O(nlogn) time?

As we use smartphones we can open many apps at a time. when we look at what all apps are open currently we see a list where the recently opened app is at the front and we can remove or close an app from anywhere on the list. There is some Collection available in java which can perform all these tasks in a very efficient way. I told we can use LinkedList or LinkedHashMap but he was not convinced. What could be the best Collection to use?

答:
Firstly, if the interviewer used Big-O notation and expected a O(n log n) solution, there's nothing wrong with your answer. We know that O(x + y) = O(max(x, y)). Therefore, although your algorithm is O(n log n + n), it's okay if we just call O(n log n). However, it's possible to find the element that appears once in a sorted array can be achieved in O(log n) using binary search. As a hint, exploit odd and even indices while performing search. Also, if the interviewer expected a O(n log n) solution, the objection for traversing is absurd. The hash map solution is already O(n), and if there's a problem with this, it's the requirement of extra space. For this reason, the best one is to use XOR as you mentioned. There're still some more O(n) solutions but they're not better than the XOR solution.

To me, LinkedList is proper to use for this task as well. We want to remove from any location and also want to use some stack operations (push, pop, peek). A custom stack can be built from a LinkedList.


问:
Laravel remove column rollback
How to rollback if i remove specific column, for example

```<code>public function up()
{
    Schema::dropColumn('status');
}
public function down()
{
    // What goes here
}
</code>```

I see there is no way to bring back the data so how to handle this.
Thanks

答:
yes you are right once you've deleted a column, there is no way back to restore this column.

I would recommend to make laravel backup before droping a column

```<code>php artisan backup:run --only-db
</code>```

or in migration

```<code>public function up()
{
    Artisan::command('backup:run, ['--only-db' => true]);
    Schema::dropColumn('status');

}
</code>```

Title: Laravel remove column rollback

Body:
How to rollback if i remove specific column, for example

public function up()
{
    Schema::dropColumn('status');
}
public function down()
{
    // What goes here
}

I see there is no way to bring back the data so how to handle this.
Thanks

Body:
yes you are right once you've deleted a column, there is no way back to restore this column.

I would recommend to make laravel backup before droping a column

php artisan backup:run --only-db

or in migration

public function up()
{
    Artisan::command('backup:run, ['--only-db' => true]);
    Schema::dropColumn('status');

}


问:
Check for the existence of any other POST variable that it is not the required one
I noticed (reading logs of websites I administer), hackers try to submit post requests, literally "inventing" post variables names.

Some website features old PHP code, eg.

```<code>if (isset($_POST["mail"]) && !empty($_POST["mail"])) {
    //...
}else{
    exit;
}
</code>```

This basically checks if there is a $_POST variable "mail" and it is not empty.

Is it possible to check for the existence of any $_POST variable that it is NOT "mail" and exit the script in that case?

答:
Use array_diff_key to check for differences:</p>

```<code>$whitelist = ['mail' => null];

$hasOthers = !empty(array_diff_key($whitelist, $_POST));
</code>```

Body:
I noticed (reading logs of websites I administer), hackers try to submit post requests, literally "inventing" post variables names.

Some website features old PHP code, eg.

if (isset($_POST["mail"]) && !empty($_POST["mail"])) {
    //...
}else{
    exit;
}

This basically checks if there is a $_POST variable "mail" and it is not empty.

Is it possible to check for the existence of any $_POST variable that it is NOT "mail" and exit the script in that case?

Body:
Use array_diff_key to check for differences:

$whitelist = ['mail' => null];

$hasOthers = !empty(array_diff_key($whitelist, $_POST));