问:
How is codahale metrics Meter mark() method threadsafe?
I have recently begun to learn CodaHale/DropWizard metrics library. I cannot understand how is the Meter class thread-safe (it is according to the documentation), especially mark() and tickIfNecessary() methods here:

https://github.com/dropwizard/metrics/blob/3.2-development/metrics-core/src/main/java/com/codahale/metrics/Meter.java#L54-L77

```<code>public void mark(long n) {
    tickIfNecessary();
    count.add(n);
    m1Rate.update(n);
    m5Rate.update(n);
    m15Rate.update(n);
}

private void tickIfNecessary() {
    final long oldTick = lastTick.get();
    final long newTick = clock.getTick();
    final long age = newTick - oldTick;
    if (age > TICK_INTERVAL) {
        final long newIntervalStartTick = newTick - age % TICK_INTERVAL;
        if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) {
            final long requiredTicks = age / TICK_INTERVAL;
            for (long i = 0; i < requiredTicks; i++) {
                m1Rate.tick();
                m5Rate.tick();
                m15Rate.tick();
            }
        }
    }
}
</code>```

I can see that there is a lastTick of type AtomicLong, but still there can be a situation that m1-m15 rates are ticking a little bit longer so another thread can invoke those ticks as well as a part of next TICK_INTERVAL. Wouldn't that be a race condition since tick() method of Rates is not synchronized at all? https://github.com/dropwizard/metrics/blob/3.2-development/metrics-core/src/main/java/com/codahale/metrics/EWMA.java#L86-L95

```<code>public void tick() {
    final long count = uncounted.sumThenReset();
    final double instantRate = count / interval;
    if (initialized) {
        rate += (alpha * (instantRate - rate));
    } else {
        rate = instantRate;
        initialized = true;
    }
}
</code>```

Thanks,

Marian

答:
As far as I can see you are right. If tickIfNecessary() is called such that age > TICK_INTERVAL while another call is still running, it is possible that m1Rate.tick() and the other tick() methods are called at the same time from multiple threads. So it boils down to wether tick() and its called routines/operations are safe.

Let's dissect tick():

```<code>public void tick() {
    final long count = uncounted.sumThenReset();
    final double instantRate = count / interval;
    if (initialized) {
        rate += (alpha * (instantRate - rate));
    } else {
        rate = instantRate;
        initialized = true;
    }
}
</code>```

alpha and interval are set only on instance initialization and marked final those thread-safe since read-only. count and instantRate are local and those not visible to other threads anyway. rate and initialized are marked volatile and those writes should always be visible for following reads.

If I'm not wrong, pretty much from the first read of initialized to the last write on either initialized or rate this is open for races but some are without effect like when 2 threads race for the switch of initialized to true.

It seems the majority of effective races can happen in rate += (alpha * (instantRate - rate)); especially dropped or mixed calculations like:

Assumed: initialized is true

Thread1: calculates count, instantRate, checks initialized, does the first read of rate which we call previous_rate and for whatever reason stalls

Thread2: calculates count, instantRate, checks initialized, and calculates rate += (alpha * (instantRate - rate));

Thread1: continues its operation and calculates rate += (alpha * (instantRate - previous_rate));

A drop would occur if the reads and writes somehow get ordered such that rate is read on all threads and then written on all threads, effectively dropping one or more calculations.

But the probability for such races, meaning that both age > TICK_INTERVAL matches such that 2 Threads run into the same tick() method and especially the rate += (alpha * (instantRate - rate)) may be extremely low and depending on the values not noticeable.

The mark() method seems to be thread-safe as long as the LongAdderProxy uses a thread-safe Data-structure for update/add and for the tick() method in sumThenReset.

I think the only ones who can answer the Questions left open - wether the races are without noticeable effect or otherwise mitigated - are the project authors or people who have in depth knowledge of these parts of the project and the values calculated.

Body:
I have recently begun to learn CodaHale/DropWizard metrics library. I cannot understand how is the Meter class thread-safe (it is according to the documentation), especially mark() and tickIfNecessary() methods here:

https://github.com/dropwizard/metrics/blob/3.2-development/metrics-core/src/main/java/com/codahale/metrics/Meter.java#L54-L77

public void mark(long n) {
    tickIfNecessary();
    count.add(n);
    m1Rate.update(n);
    m5Rate.update(n);
    m15Rate.update(n);
}

private void tickIfNecessary() {
    final long oldTick = lastTick.get();
    final long newTick = clock.getTick();
    final long age = newTick - oldTick;
    if (age > TICK_INTERVAL) {
        final long newIntervalStartTick = newTick - age % TICK_INTERVAL;
        if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) {
            final long requiredTicks = age / TICK_INTERVAL;
            for (long i = 0; i < requiredTicks; i++) {
                m1Rate.tick();
                m5Rate.tick();
                m15Rate.tick();
            }
        }
    }
}

I can see that there is a lastTick of type AtomicLong, but still there can be a situation that m1-m15 rates are ticking a little bit longer so another thread can invoke those ticks as well as a part of next TICK_INTERVAL. Wouldn't that be a race condition since tick() method of Rates is not synchronized at all? https://github.com/dropwizard/metrics/blob/3.2-development/metrics-core/src/main/java/com/codahale/metrics/EWMA.java#L86-L95

public void tick() {
    final long count = uncounted.sumThenReset();
    final double instantRate = count / interval;
    if (initialized) {
        rate += (alpha * (instantRate - rate));
    } else {
        rate = instantRate;
        initialized = true;
    }
}

Thanks,

Marian

Body:
As far as I can see you are right. If tickIfNecessary() is called such that age > TICK_INTERVAL while another call is still running, it is possible that m1Rate.tick() and the other tick() methods are called at the same time from multiple threads. So it boils down to wether tick() and its called routines/operations are safe.

Let's dissect tick():

public void tick() {
    final long count = uncounted.sumThenReset();
    final double instantRate = count / interval;
    if (initialized) {
        rate += (alpha * (instantRate - rate));
    } else {
        rate = instantRate;
        initialized = true;
    }
}

alpha and interval are set only on instance initialization and marked final those thread-safe since read-only. count and instantRate are local and those not visible to other threads anyway. rate and initialized are marked volatile and those writes should always be visible for following reads.

If I'm not wrong, pretty much from the first read of initialized to the last write on either initialized or rate this is open for races but some are without effect like when 2 threads race for the switch of initialized to true.

It seems the majority of effective races can happen in rate += (alpha * (instantRate - rate)); especially dropped or mixed calculations like:

Assumed: initialized is true

Thread1: calculates count, instantRate, checks initialized, does the first read of rate which we call previous_rate and for whatever reason stalls

Thread2: calculates count, instantRate, checks initialized, and calculates rate += (alpha * (instantRate - rate));

Thread1: continues its operation and calculates rate += (alpha * (instantRate - previous_rate));

A drop would occur if the reads and writes somehow get ordered such that rate is read on all threads and then written on all threads, effectively dropping one or more calculations.

But the probability for such races, meaning that both age > TICK_INTERVAL matches such that 2 Threads run into the same tick() method and especially the rate += (alpha * (instantRate - rate)) may be extremely low and depending on the values not noticeable.

The mark() method seems to be thread-safe as long as the LongAdderProxy uses a thread-safe Data-structure for update/add and for the tick() method in sumThenReset.

I think the only ones who can answer the Questions left open - wether the races are without noticeable effect or otherwise mitigated - are the project authors or people who have in depth knowledge of these parts of the project and the values calculated.


来源: stackexchange

问:
a very simple query is not working PHP
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

```<code>  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>
</code>```

答:
Your error probably resides in the fact that you don’t escape your parameters.

While you are at it, use MySQLi or PDO (maybe even some prepared statements)

Someone mentioned your use of single-quotes, that’s the real error, my bad.

But my advice still stands. Having used prepared statements, you wouldn’t have fell for that mistake

ContentLicense: CC BY-SA 2.5

Title: a very simple query is not working PHP

Body:
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>


问:
Share docker images between hosts with NFS
I'building a mesosphere infrastructure on AWS instances with 3 master servers (running zookeeper, mesos-master, marathon and haproxy) and N slaves (running mesos-slave and docker).

If I run the same container on different slaves marathon downloads on each slave the same image. I would like to share one single nfs export (say on master1) and mount it on every slave in order to have a unique storage for the images.

Im using Ubuntu on the EC2 instances, so the storage driver used by default is device-mapper. I set up the slaves to mount /var/lib/docker/devicemapper and /var/lib/docker/graph but it ends up with this error: "stale NFS file handle"

What I would like to understand is:

There is a way to do it using a different storage driver?

In any case is the docker daemon doing some look on the files in this directory?

Is my approach wrong or possible leading into "cconcurrency access issues?

答: Instead of using NFS to expose the backing file system, I think it would be easier to set up docker-registry (with a volume on the master1, so the data is persisted there) and on the other nodes pull images via docker protocol by e.g. docker pull master1:5000/image:latest

ContentLicense: CC BY-SA 3.0


问:
Cannot resolve symbol DownloaderService for APK expansion
I was following this guide :
https://developer.android.com/google/play/expansion-files.html

and in my downloaderService.java file it can't resolve to extends DownloaderService :

```<code>public class downloaderService extends DownloaderService {
</code>```

Why and how to fix it?
another file can't resolve DownloaderClientMarshaller at alarmReceiver.java :

```<code>..  DownloaderClientMarshaller.startDownloadServiceIfRequired(context,
                    intent, downloaderService.class);  .....
</code>```

Thank you for your answers

答:
You need to add following libraries as modules to your project:

Google Play Licencing Library package

Google Play APK Expansion Library package

as described here in the android developers website

Body:
I was following this guide :
https://developer.android.com/google/play/expansion-files.html

and in my downloaderService.java file it can't resolve to extends DownloaderService :

public class downloaderService extends DownloaderService {

Why and how to fix it?
another file can't resolve DownloaderClientMarshaller at alarmReceiver.java :

..  DownloaderClientMarshaller.startDownloadServiceIfRequired(context,
                    intent, downloaderService.class);  .....

Thank you for your answers


问:
How to determine the length of an array in VBA
I have an array that looks like this:

```<code> students1 = Array(423.5482, 425.6641)
</code>```

Now I would like to get the length of this array. However, if I try this:

```<code> MsgBox(students1.Length)
</code>```

I get the error that an object is required. Any thoughs on how I can get the length?

答:
Use UBound and and Lbound</p>

```<code>MsgBox Ubound(students1)-Lbound(students1)+1
</code>```

Body:
I have an array that looks like this:

 students1 = Array(423.5482, 425.6641)

Now I would like to get the length of this array. However, if I try this:

 MsgBox(students1.Length)

I get the error that an object is required. Any thoughs on how I can get the length?

Body:
Use UBound and and Lbound

MsgBox Ubound(students1)-Lbound(students1)+1


问:
Delete row if row contains 000
I have the following code:

```<code>set local enabledelayedexpansion for /f "delims=" %%a in  (\\file) do (
  SET ='%%a
  SET s=!s:;'';'=;;%!
  echo !s!
)  >>   \\file"
</code>```

I need apart from the modification, to delete the row if contains 00.
So far i have tried to add the following set but is not working.

答:
Does

FIND /V "000"<"TXTFILE.TXT">"NEWFILE.TXT"
```

<p>or</p>

<pre class="lang-bat prettyprint-override"><code>TYPE "TXTFILE.TXT"|FIND /V "000">"NEWFILE.TXT"
</code>```

not do what you want?

Title: Delete row if row contains 000

Body:
I have the following code:

set local enabledelayedexpansion for /f "delims=" %%a in  (\\file) do (
  SET ='%%a
  SET s=!s:;'';'=;;%!
  echo !s!
)  >>   \\file"

I need apart from the modification, to delete the row if contains 00.
So far i have tried to add the following set but is not working.

Body:
Does

FIND /V "000"<"TXTFILE.TXT">"NEWFILE.TXT"

or

TYPE "TXTFILE.TXT"|FIND /V "000">"NEWFILE.TXT"

not do what you want?


问:
Do I have to copy libraries to jniLibs every time I update them (Android)?
I learned about JNI files through this tutorial: https://www.youtube.com/watch?v=G0vL7-_xuDM

After lots of experimentation I have figured out that in order to link a C file to Android it seems that I need to

Create an application.c file in a "jni" directory outside my src directory

Create Android.mk and Application.mk files, also in he "jni" directory

Run "ndk-build" in a terminal to create lib___.so files in a "libs" directory

Copy these lib___.so files to a "jniLibs" folder under src/main

In my activity, load the library I created in the c file

Include an unimplemented native method that I call whenever I want to get my data

My problem is that whenever I want to change anything in my C application I need to repeat steps 3 and 4 to run ndk-build (again) and then copy the newly updated files in the "libs" directory into the "jinLibs" directory (again), in order to show anything new in my activity. This seems redundant and unnecessary. Is there an easier way?

答:
If I understand you correctly, you already managed to compile your jni sources with ndk-build. Now, the "manual part", i.e. copying libs/files can be accomplished fairly easy via a gradle task. After the native build task you could add a 'copyTask', like this:

```<code>tasks.withType(JavaCompile) { compileTask ->
    compileTask.dependsOn buildNative // building via NDK
    doLast{
        // ...
        copyLibs
    }
}

task copyLibs(type: Copy) {
    from configurations.compile
    into 'pathToJNILibs'
}
</code>```

For the sake of completeness, I would further add some cleanup tasks to avoid hassling with old files

Body:
If I understand you correctly, you already managed to compile your jni sources with ndk-build. Now, the "manual part", i.e. copying libs/files can be accomplished fairly easy via a gradle task. After the native build task you could add a 'copyTask', like this:

tasks.withType(JavaCompile) { compileTask ->
    compileTask.dependsOn buildNative // building via NDK
    doLast{
        // ...
        copyLibs
    }
}

task copyLibs(type: Copy) {
    from configurations.compile
    into 'pathToJNILibs'
}

For the sake of completeness, I would further add some cleanup tasks to avoid hassling with old files


问:
Nodejs Express query mongolab for a single entry using data from a form
I am a Nodejs newbie and am trying to search my mongolab database for an entry(that I know exists) using data from a form entry. Here is my code:

```<code>var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
const MongoClient = require('mongodb').MongoClient;

var app = express();
app.set('view engine', 'ejs')
const port = 3000;

MongoClient.connect('mongodb://<user>:<password>@ds111882.mlab.com:11882/serene-brushlands-55292-db', function(err, database) {
    if(err) return console.log(err);
    db = database
    app.listen(port, function() {
    console.log('Server started at port:'+port);
    });
});

// var urlencodedParser = bodyParser.urlencoded({ extended:false });
app.use(bodyParser.urlencoded({extended:false}));
app.get('/', function(req, res) {
    res.sendFile(__dirname+'/index.html');
});

app.all('/addUser', function(req, res) {
    res.render('addUser');
    db.collection('users').save(req.body, function(err, result) {
        if (err) return console.log(err);
        console.log('saved to database');
    })
    console.log(req.body);
});

app.get('/outputAll', function(req, res) {
    db.collection('users').find().toArray(function (err, result) {
    if (err) return console.log(err);
    res.render('outputall', {users:result});
    });
});

app.get('/Search', function(req, res) {
    res.render('search');
    var query = {}
    console.log(req.body);
    if (req.body.username)
    {
    console.log("true");
    query.username = req.body.username;
    }
    db.collection('users').find({query}).toArray(function(err, result) {
    if (err) return console.log(err);
    console.log(1);
    });
});
</code>```

The search part is meant to accomplish this objective. But I am not sure how to collect the query from my input form and pass it to the this app.get and have it passed to the database where it is searched. Here is the Search ejs file:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MY APP</title>
</head>
<body>
    <div style="margin: 0 auto;width: 500px;">
    <form action="/Search" method="GET" style="margin: 0 auto; width: 200px; margin-top: 100px;">
        <input type="text" placeholder="Search" name="username"  style="margin: 20px auto; font-size: 50px;">
        <!-- <input type="file" name="picture"> -->
        <button type="submit"  style="margin: 20px auto; font-size: 50px;">Submit</button>
    </form>
    </div>
</body>
</html>
</code>```

The output on the console when I run this is:

Server started at port:3000

{}

[]

{}

[]

I was expecting the {} to be the form data and the [] to be the result of searching the query in the database.
Please help!

----------------EDIT-----------------

The response I am receiving after changing the form method to post is :

```<code>Request body  = undefined
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]
Request body  = abc
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]
</code>```

I have changed the add.get('Search',fn) to :

```<code>app.all('/Search', function(req, res) {
    res.render('search');
    db.collection('users').find().toArray(function(err, result) {
    if (err) return console.log(err);
    var query = {}
    console.log("Request body  = "+req.body.username);
    // if (req.body.username)
    // {
    //     console.log(req.body);
    //     query.username = req.body.username;
    // }

    console.log(result);
    });
});
</code>```

答:
In mongoose you should find documents in your db by sending objects as parameters.
For example if you are looking for a person in your database with name john you use

db.collection('users').find({name: 'John'}).then(function(resp){}).catch(function(err){})

{name: 'John'} is your javascript object mongoose will use while executing query

since you say you are new it is useful to learn this pattern called promises.

Body:
I am a Nodejs newbie and am trying to search my mongolab database for an entry(that I know exists) using data from a form entry. Here is my code:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
const MongoClient = require('mongodb').MongoClient;

var app = express();
app.set('view engine', 'ejs')
const port = 3000;

MongoClient.connect('mongodb://<user>:<password>@ds111882.mlab.com:11882/serene-brushlands-55292-db', function(err, database) {
    if(err) return console.log(err);
    db = database
    app.listen(port, function() {
    console.log('Server started at port:'+port);
    });
});

// var urlencodedParser = bodyParser.urlencoded({ extended:false });
app.use(bodyParser.urlencoded({extended:false}));
app.get('/', function(req, res) {
    res.sendFile(__dirname+'/index.html');
});

app.all('/addUser', function(req, res) {
    res.render('addUser');
    db.collection('users').save(req.body, function(err, result) {
        if (err) return console.log(err);
        console.log('saved to database');
    })
    console.log(req.body);
});

app.get('/outputAll', function(req, res) {
    db.collection('users').find().toArray(function (err, result) {
    if (err) return console.log(err);
    res.render('outputall', {users:result});
    });
});

app.get('/Search', function(req, res) {
    res.render('search');
    var query = {}
    console.log(req.body);
    if (req.body.username)
    {
    console.log("true");
    query.username = req.body.username;
    }
    db.collection('users').find({query}).toArray(function(err, result) {
    if (err) return console.log(err);
    console.log(1);
    });
});

The search part is meant to accomplish this objective. But I am not sure how to collect the query from my input form and pass it to the this app.get and have it passed to the database where it is searched. Here is the Search ejs file:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>MY APP</title>

    <form action="/Search" method="GET" style="margin: 0 auto; width: 200px; margin-top: 100px;">
        <input type="text" placeholder="Search" name="username"  style="margin: 20px auto; font-size: 50px;">

        <button type="submit"  style="margin: 20px auto; font-size: 50px;">Submit</button>
    </form>

The output on the console when I run this is:

Server started at port:3000

{}

[]

{}

[]

I was expecting the {} to be the form data and the [] to be the result of searching the query in the database.
Please help!

----------------EDIT-----------------

The response I am receiving after changing the form method to post is :

Request body  = undefined
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]
Request body  = abc
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]

I have changed the add.get('Search',fn) to :

app.all('/Search', function(req, res) {
    res.render('search');
    db.collection('users').find().toArray(function(err, result) {
    if (err) return console.log(err);
    var query = {}
    console.log("Request body  = "+req.body.username);
    // if (req.body.username)
    // {
    //     console.log(req.body);
    //     query.username = req.body.username;
    // }

    console.log(result);
    });
});


问:
Javascript tabs synchronization and server events
I need some help for my application and sorry for my English.

I'm working on front-end of a website. The final app should work fine with a lot of tabs (~100 in a single browser). Each tab needs to listen for a series of events sent from server and change its content dynamically.

I implemented this feature by using Websocket. Since opening a connection is very expensive. So I assigned a master tab, which will listen to events from the server and distribute them to other tabs using BroadcastChannel. And I have following questions：

How to pick a master tab from all of them and make other tabs listen
  to it?

I had these ideas:

1. Using BroadcastChannel.

During initilization tab asks using BroadcastChannel: "is there a master tab?". If it receives an answer, then it will continue working. If it won't receive any response, then it makes itself a master tab.

Problem:

If master tab will freeze inside of heavy loop, then it won't be able to respond in short amount of time, resulting 2 opened connections to the server and a conflict, which needs to be resolved.

2. Using LocalStorage.

During initilization tab will request some field called "X" or smth. If field is empty, then tab will create that field and assign some value, after it will make itself a master tab. If field "X" is not empty, then tab will make itself a slave tab.

Problem:

If two tabs will initilize in the same time, there might be a conflict:

```<code>tab_Alpha -> localStorage.getItem("haveMaster") -> undefined // There is no master, so i will make myself a master tab!
tab_Beta  -> localStorage.getItem("haveMaster") -> undefined // There is no master, so i will make myself a master tab!

tab_Alpha -> localStorage.setItem("haveMaster", true) // Now it's time to open connection and listen for events
tab_Beta  -> localStorage.setItem("haveMaster", true) // Now it's time to open connection and listen for events
</code>```

And as a result, I have a conflict and two opened connections.

Can someone point out a lightweight solution to me? I will appreciate that.

After a research.

Halcyon suggested to use code from gist.github.com/neilj/4146038. But i was not satisfied with this solution, because if Math.random() will return 2 same numbers for 2 different tabs, while they will initilize, then browser will call masterDidChange() two times. And browser will end up, with conflict and 2 connections.

Then Dimitry Boger suggested to read this: alpha.de/2012/03/javascript-concurrency-and-locking-the-html5-localstorage.

I liked this solution more, but i still have managed to find a way to break it.

If each tab will freeze in couple of places, then it will result, again, an execution of criticalSection().

Then i found a wikipedia.org/wiki/Peterson's_algorithm. I have not found a method to break this locking mechanism, but there is a problem.

For this algorithm to work browser have to know exact amount of tabs before execution. Because if it will initilize a new tab, then previous one's can just miss this event and start their criticalSection() before the new tab will finish it's own.

So, if you are not scared of 1024 tabs initilizing and freezing them selves at the same time, then you can use any of this solutions. But i need a bullet proof one, so i decided, to give a honor of finding a master tab to the backend server.

Thanks everyone for help.

After another research.

There is a bullet proof answer under the post. It can work without a backend server.

答:
I ran into this exact problem a while ago. I found this windowcontroller.js from an app called Overture.

It correctly handles race conditions and timeouts.

I think it works out of the box but I modified it a bit to suit my needs.

Body:
I need some help for my application and sorry for my English.

I'm working on front-end of a website. The final app should work fine with a lot of tabs (~100 in a single browser). Each tab needs to listen for a series of events sent from server and change its content dynamically.

I implemented this feature by using Websocket. Since opening a connection is very expensive. So I assigned a master tab, which will listen to events from the server and distribute them to other tabs using BroadcastChannel. And I have following questions：

How to pick a master tab from all of them and make other tabs listen
  to it?

I had these ideas:

1. Using BroadcastChannel.

During initilization tab asks using BroadcastChannel: "is there a master tab?". If it receives an answer, then it will continue working. If it won't receive any response, then it makes itself a master tab.

Problem:

If master tab will freeze inside of heavy loop, then it won't be able to respond in short amount of time, resulting 2 opened connections to the server and a conflict, which needs to be resolved.

2. Using LocalStorage.

During initilization tab will request some field called "X" or smth. If field is empty, then tab will create that field and assign some value, after it will make itself a master tab. If field "X" is not empty, then tab will make itself a slave tab.

Problem:

If two tabs will initilize in the same time, there might be a conflict:

tab_Alpha -> localStorage.getItem("haveMaster") -> undefined // There is no master, so i will make myself a master tab!
tab_Beta  -> localStorage.getItem("haveMaster") -> undefined // There is no master, so i will make myself a master tab!

tab_Alpha -> localStorage.setItem("haveMaster", true) // Now it's time to open connection and listen for events
tab_Beta  -> localStorage.setItem("haveMaster", true) // Now it's time to open connection and listen for events

And as a result, I have a conflict and two opened connections.

Can someone point out a lightweight solution to me? I will appreciate that.

After a research.

Halcyon suggested to use code from gist.github.com/neilj/4146038. But i was not satisfied with this solution, because if Math.random() will return 2 same numbers for 2 different tabs, while they will initilize, then browser will call masterDidChange() two times. And browser will end up, with conflict and 2 connections.

Then Dimitry Boger suggested to read this: alpha.de/2012/03/javascript-concurrency-and-locking-the-html5-localstorage.

I liked this solution more, but i still have managed to find a way to break it.

If each tab will freeze in couple of places, then it will result, again, an execution of criticalSection().

Then i found a wikipedia.org/wiki/Peterson's_algorithm. I have not found a method to break this locking mechanism, but there is a problem.

For this algorithm to work browser have to know exact amount of tabs before execution. Because if it will initilize a new tab, then previous one's can just miss this event and start their criticalSection() before the new tab will finish it's own.

So, if you are not scared of 1024 tabs initilizing and freezing them selves at the same time, then you can use any of this solutions. But i need a bullet proof one, so i decided, to give a honor of finding a master tab to the backend server.

Thanks everyone for help.

After another research.

There is a bullet proof answer under the post. It can work without a backend server.


问:
Cannot receive field from PHP query
I have the following code :

```<code> <?php
//$adress = $_POST['forgotpass'];
$adress = 'test@example.com';
$test = 'test';
$conn = oci_connect( 'con', 'con', "localhost/xe");
$array = oci_parse($conn, "select password from t1 , t2 where id  = user_id and email = :adress");
oci_bind_by_name($array, ':adress', $adress);
oci_execute($array);

while($row=oci_fetch_array($array))

{

echo $row[0];

}
</code>```

This code does not print anything, I suppose it is like this because of the symbols . or @ from my email adress.

The fact is that when I use a variable it works.

```<code><?php
//$adress = $_POST['forgotpass'];
$adress = 'test@example.com';
$test = 'test';
$conn = oci_connect( 'con', 'con', "localhost/xe");
$array = oci_parse($conn, "select password from t1 , t2 where id  = user_id and name = :test");
oci_bind_by_name($array, ':test', $test);
oci_execute($array);

while($row=oci_fetch_array($array))

{

echo $row[0];

}
</code>```

And in this way it shows me on the screen what i do want to see. I don't see the problem with the email adress because I do the exact same thing. But , as I've said  I think that's because of those symbols.

答:
Have you tried single-quoting your :adress variable?

something like:

```<code>$array = oci_parse($conn, "select password from t1 , t2 where id  = user_id and email = ':adress'");
</code>```

Title: Cannot receive field from PHP query

Body:
I have the following code :

 <?php
//$adress = $_POST['forgotpass'];
$adress = 'test@example.com';
$test = 'test';
$conn = oci_connect( 'con', 'con', "localhost/xe");
$array = oci_parse($conn, "select password from t1 , t2 where id  = user_id and email = :adress");
oci_bind_by_name($array, ':adress', $adress);
oci_execute($array);

while($row=oci_fetch_array($array))

{

echo $row[0];

}

This code does not print anything, I suppose it is like this because of the symbols . or @ from my email adress.

The fact is that when I use a variable it works.

<?php
//$adress = $_POST['forgotpass'];
$adress = 'test@example.com';
$test = 'test';
$conn = oci_connect( 'con', 'con', "localhost/xe");
$array = oci_parse($conn, "select password from t1 , t2 where id  = user_id and name = :test");
oci_bind_by_name($array, ':test', $test);
oci_execute($array);

while($row=oci_fetch_array($array))

{

echo $row[0];

}

And in this way it shows me on the screen what i do want to see. I don't see the problem with the email adress because I do the exact same thing. But , as I've said  I think that's because of those symbols.

Body:
Have you tried single-quoting your :adress variable?

something like:

$array = oci_parse($conn, "select password from t1 , t2 where id  = user_id and email = ':adress'");


问:
Errors when retrieving request body in Mongoose WebServer
I'm working with an old version of mongoose (open source web server) in C, which did not provide native access to the requests payload. In order to support POST and PUT requests, I manually modified it: after mongoose reads the headers, I check if Content-Length is set and, if so, I read again from the socket for Content-Lenght characters.

```<code>    findCL = strstr(conn->buf, "Content-Length:");
    if (findCL)
    {
        // skip "Content-Length:" string
        findCL += 15 * sizeof(char);
        findCLEnd = (char*)strchr(findCL, delimiter);
        sizeLen = findCLEnd - findCL;
        strncpy(CLSize, findCL, sizeLen);
        CLSize[sizeLen] = '\0';

        size = strtoll(CLSize, NULL, 10);

        if (size > 0)
        {
            conn->content_len = read_request(NULL, conn->client.sock, conn->ssl,
                conn->buf, conn->buf_size, &conn->data_len);
            conn->content_len = size;
            perror("recv");
            body = (char*)malloc(sizeof(char) * (size + 1));
            strncpy(body, conn->buf + conn->request_len, size);
            body[size] = '\0';
        }
    }
</code>```

So far so good, even if the code is not that beautiful it does the dirty job. Problem is, while in debug the code works fine, but when the code runs as a simple background process the body is not parsed correctly: sometimes the resulting body is truncated, some other times it is just empty. It seems that the problem is caused by the fast queries from the clients.

答:
Not a real answer, but that's how I solved.
The web server module started as a Mongoose web server; I ported it to Civetweb some months ago, hoping that the latest versions of the project also supported the parsing of the body. It was not so, and I had to implement it manually. After some times I discovered that Civetweb had issues in serving Javascript files to IE8 browsers (for some mysterious reason). I reverted to Mongoose and all worked, except the body parsing, which brought to the code above and the subsequent errors. I finally solved by reverting back to Civetweb, stable version 1.9.1, keeping the manual body parsing procedure. This solved both the truncated requests body and the truncated served javascript files. Probably the first version of Civetweb was a not-so-stable beta, although I wonder how did it manage to work for months.

I still haven't checked the diffs between the two versions, but I expect it to be something related to maximum response sizes depending on platform or request headers or whatever else.

Body:
I'm working with an old version of mongoose (open source web server) in C, which did not provide native access to the requests payload. In order to support POST and PUT requests, I manually modified it: after mongoose reads the headers, I check if Content-Length is set and, if so, I read again from the socket for Content-Lenght characters.

    findCL = strstr(conn->buf, "Content-Length:");
    if (findCL)
    {
        // skip "Content-Length:" string
        findCL += 15 * sizeof(char);
        findCLEnd = (char*)strchr(findCL, delimiter);
        sizeLen = findCLEnd - findCL;
        strncpy(CLSize, findCL, sizeLen);
        CLSize[sizeLen] = '\0';

        size = strtoll(CLSize, NULL, 10);

        if (size > 0)
        {
            conn->content_len = read_request(NULL, conn->client.sock, conn->ssl,
                conn->buf, conn->buf_size, &conn->data_len);
            conn->content_len = size;
            perror("recv");
            body = (char*)malloc(sizeof(char) * (size + 1));
            strncpy(body, conn->buf + conn->request_len, size);
            body[size] = '\0';
        }
    }

So far so good, even if the code is not that beautiful it does the dirty job. Problem is, while in debug the code works fine, but when the code runs as a simple background process the body is not parsed correctly: sometimes the resulting body is truncated, some other times it is just empty. It seems that the problem is caused by the fast queries from the clients.


问:
How to detect mouse moving while left button down?
I would like to detect mouse movement while the left button is pressed.

I'm simply creating a drawing application. I can detect mouse movement without any mouse being pressed. But I want to detect it WITH left mouse pressed.

I don't think there's a listener for this. So, what is the idea to do that?

答:
In your MouseMotionListener you can check for this using:

```<code>SwingUtilities.isLeftMouseButton(me.getPoint())
</code>```

and you would listen for the mouseDragged event.

ContentLicense: CC BY-SA 4.0

Body:
In your MouseMotionListener you can check for this using:

SwingUtilities.isLeftMouseButton(me.getPoint())

and you would listen for the mouseDragged event.


问:
Convert Angular SpaTemplate Core to Core .Net Framework
I am working on converting the SpaTemplate provided by Microsoft. This template is an Angular 2 implementation using Asp.Net Core. Core is fine and all but I could care less about using it and it limits some of my code base. So with that in mind I want to use Angular 2 but I want to use Asp.Net Core with the .Net Framework.

I created the template, then a blank .Net Core w/.Net Framework project.

I have been copying files to the blank project but still cannot get it to run.

Copied:

wwwroot

ClientApp

Controllers

Views

package.json

webpack.config.js

Startup.cs contents

I get this error when launching my new project:

```<code>Exception: Call to Node module failed with error: Error: No ResourceLoader implementation has been provided. Can't read the url "app.component.html"
at Object.get (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:60768:15)
at DirectiveNormalizer.module.exports.DirectiveNormalizer._fetch (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:47872:45)
at DirectiveNormalizer.module.exports.DirectiveNormalizer.normalizeTemplateAsync (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:47927:21)
at DirectiveNormalizer.module.exports.DirectiveNormalizer.normalizeTemplate (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:47899:44)
at CompileMetadataResolver.module.exports.CompileMetadataResolver._loadDirectiveMetadata (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:48830:75)
at D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:49026:54
at Array.forEach (native)
at CompileMetadataResolver.module.exports.CompileMetadataResolver.loadNgModuleDirectiveAndPipeMetadata (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:49025:41)
at D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:60221:58
at Array.forEach (native)
Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance+<InvokeExportAsync>d__7.MoveNext()
</code>```

答: The easiest solution was to generate the .Net Core SpaTemplate, edit csproj to net46, use Nuget to install some packages, and rebuild. </p>

Body:
I am working on converting the SpaTemplate provided by Microsoft. This template is an Angular 2 implementation using Asp.Net Core. Core is fine and all but I could care less about using it and it limits some of my code base. So with that in mind I want to use Angular 2 but I want to use Asp.Net Core with the .Net Framework.

I created the template, then a blank .Net Core w/.Net Framework project.

I have been copying files to the blank project but still cannot get it to run.

Copied:

wwwroot

ClientApp

Controllers

Views

package.json

webpack.config.js

Startup.cs contents

I get this error when launching my new project:

Exception: Call to Node module failed with error: Error: No ResourceLoader implementation has been provided. Can't read the url "app.component.html"
at Object.get (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:60768:15)
at DirectiveNormalizer.module.exports.DirectiveNormalizer._fetch (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:47872:45)
at DirectiveNormalizer.module.exports.DirectiveNormalizer.normalizeTemplateAsync (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:47927:21)
at DirectiveNormalizer.module.exports.DirectiveNormalizer.normalizeTemplate (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:47899:44)
at CompileMetadataResolver.module.exports.CompileMetadataResolver._loadDirectiveMetadata (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:48830:75)
at D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:49026:54
at Array.forEach (native)
at CompileMetadataResolver.module.exports.CompileMetadataResolver.loadNgModuleDirectiveAndPipeMetadata (D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:49025:41)
at D:\Source\Susquehanna-Software\EarlyScTrackerDemos\NetFrameScTrackerDemo\ClientApp\dist\vendor.js:60221:58
at Array.forEach (native)
Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance+<InvokeExportAsync>d__7.MoveNext()


问:
Is there an easier way than nested iifs to count mismatched conditions in SQL server
The picture below shows a table of accounts and the outcomes that I want to count. Ie every time the account number is 106844 and the outcome is "MESSAGE" or "ESCALATION EMAIL" that should count as 1 where any other outcome counts as 0. What I would normally do is a horrible mess of iifs like

```<code>   sum( iif([account] = '106719' and [Outcome] in ('MESSAGE','ESCALATION_EMAIL'),1,iif([account] = '310827' and [outcome] <> 'ABORT' and 'CALL_OUTCOME_LB' in ("Call patched to Customer Care","Message Taken"),1,iif( ... , 0) as [Total Outcomes]
</code>```

and so on but man it feel like there's got to be an easier way or one less prone to making a random mistake in the 7th nested iif and messing the whole thing up. Any ideas?

答:
Don't use iif().  It is a function brought into SQL Server for back-compatibility to MS ACCESS.  Why would you want to be backwards compatible to such a thing?

Use the ANSI standard CASE expression:

```<code>  sum(case when account = '106719' and Outcome in ('MESSAGE', 'ESCALATION_EMAIL')
           then 1
           when account = '310827' and outcome <> 'ABORT' and
                'CALL_OUTCOME_LB' in ("Call patched to Customer Care", "Message Taken")
           then 1
           . . .
           else 0
       end) as Total_Outcomes
</code>```

I would also advise you to name your columns so they don't need to be escaped (why "Total Outcomes" became "Total_Outcomes").  That simplifies the code.

Body:
The picture below shows a table of accounts and the outcomes that I want to count. Ie every time the account number is 106844 and the outcome is "MESSAGE" or "ESCALATION EMAIL" that should count as 1 where any other outcome counts as 0. What I would normally do is a horrible mess of iifs like

   sum( iif([account] = '106719' and [Outcome] in ('MESSAGE','ESCALATION_EMAIL'),1,iif([account] = '310827' and [outcome] <> 'ABORT' and 'CALL_OUTCOME_LB' in ("Call patched to Customer Care","Message Taken"),1,iif( ... , 0) as [Total Outcomes]

and so on but man it feel like there's got to be an easier way or one less prone to making a random mistake in the 7th nested iif and messing the whole thing up. Any ideas?

Body:
Don't use iif().  It is a function brought into SQL Server for back-compatibility to MS ACCESS.  Why would you want to be backwards compatible to such a thing?

Use the ANSI standard CASE expression:

  sum(case when account = '106719' and Outcome in ('MESSAGE', 'ESCALATION_EMAIL')
           then 1
           when account = '310827' and outcome <> 'ABORT' and
                'CALL_OUTCOME_LB' in ("Call patched to Customer Care", "Message Taken")
           then 1
           . . .
           else 0
       end) as Total_Outcomes

I would also advise you to name your columns so they don't need to be escaped (why "Total Outcomes" became "Total_Outcomes").  That simplifies the code.


问:
OnClick: Passing String as Parameter
I would like to pass a string as a parameter of the following:

How would I make "hello" become a parameter. The integers pass without problem.

Thank you.

答:
You have to add quotes to the string parameter:

```<code><div id="menubutton1" class="menubutton lightbox" onclick="lightbox(1000, 410, 'hello')">
</code>```

will work.

Title: OnClick: Passing String as Parameter

Body:
You have to add quotes to the string parameter:

<div id="menubutton1" class="menubutton lightbox" onclick="lightbox(1000, 410, 'hello')">

will work.


问:
Why Phpmyadmin don't understand MD5?
I have phpmyadmin version 4.0.10.20 in debian Squeeze. it's LAMP server.

If I run SQL Query: in PHPMYADMIN

```<code>SELECT MD5('testing');

The result is :
MD5('testing')
6165326231666361353135393439653564353466623232623865643935353735
</code>```

In Mysql consol directly: (in the same Server)

```<code>mysql> SELECT MD5('testing');
    +----------------------------------+
    | MD5('testing')                   |
    +----------------------------------+
    | ae2b1fca515949e5d54fb22b8ed95575 |
    +----------------------------------+
    1 row in set (0.00 sec)
</code>```

What do you think about it ?
--> I have never seen that !

Title: Why Phpmyadmin don't understand MD5?

Body:
I have phpmyadmin version 4.0.10.20 in debian Squeeze. it's LAMP server.

If I run SQL Query: in PHPMYADMIN

SELECT MD5('testing');

The result is :
MD5('testing')
6165326231666361353135393439653564353466623232623865643935353735

In Mysql consol directly: (in the same Server)

mysql> SELECT MD5('testing');
    +----------------------------------+
    | MD5('testing')                   |
    +----------------------------------+
    | ae2b1fca515949e5d54fb22b8ed95575 |
    +----------------------------------+
    1 row in set (0.00 sec)

What do you think about it ?
--> I have never seen that !

Body:
It is just different representation of the same.

A=61
E=65
2=32
B=62
...
5=35

61 65 32 62 31 66 63 61 35 31 35 39 34 39 65 35 64 35 34 66 62 32 32 62 38 65 64 39 35 35 37 35
 a  e  2  b  1  f  c  a  5  1  5  9  4  9  e  5  d  5  4  f  b  2  2  b  8  e  d  9  5  5  7  5


问:
Boostrap popover trigger focus not working on SVG <g> tag
I have used SVG in my project, Inside SVG there is  tag used, on which I have called bootstrap popover which is working fine on data-trigger click and hover. But it is not working on data-trigger="focus".

Any help much appreciate.

答:
This might be answered through this question: Bootstrap 3 Popover: display on hover AND on click, aka. Pin a Popover

It's hard to tell without code example.


问:
Linq query with multiple subqueries
I'm working on converting an Oracle Sql query to Linq, and not sure how to proceed. Here is the Sql query:

```<code>SELECT *
FROM   CustomerShip,
    (SELECT DISTINCT b.ShipSeq AS shipSeq
     FROM   Orders a,
            CustomerShip b
     WHERE  a.OrderId IN (SELECT OrderId
                          FROM   Orders
                          WHERE  CustomerId = @CustomerId
                          AND    OrderType <> 'A')
     AND    b.CustomerId = @CustomerId
     AND    b.ShipSeq = a.CustShip
     AND    OrderStatus <> 'C'
     GROUP BY b.ShipSeq) i
WHERE  CustomerId = @CustomerId
AND    (Address NOT LIKE '%RETAIL%STORE%')
AND    ShipSeq = i.ShipSeq(+)
ORDER BY ShipTo DESC, OrderDate DESC;
</code>```

I have tried to break it down into three separate queries when converting to linq.

```<code>var query1 = from c in CustomerShip
            where c.CustomerId == customerId
            && !c.Address.Contains("RETAIL")
            && !c.Address.Contains("STORE")
            orderby c.ShipTo descending, c.OrderDate descending
            select c;

var query2 = from o in Orders
         where o.CustomerId == customerId
         && !o.OrderType.Equals("A")
         select o.OrderId;

var query3 = (from o in Orders
         from c in CustomerShip
         where c.CustomerId == customerId
         && c.ShipSeq == o.CustShip
         && !o.OrderStatus.Equals("A")
         select c.ShipSeq).Distinct();
</code>```

Now I'm trying to assemble them all into one query, but unsure how to do it. Here is the direction I am going:

```<code>var query = from c in CustomerShip

let subquery = from o in Orders
               where o.CustomerId == customerId
               && !o.OrderType.Equals("A")
               select o.OrderId

    from or in model.Orders
    where subquery.Contains(or.OrderId)
    && c.CustomerId == customerId
    && c.ShipSeq == or.CustShip
    && !or.OrderStatus.Equals("A")
    group c by c.ShipSeq
    into i
    select c.ShipSeq

where c.CustomerId == customerId
&& !c.Address.Contains("RETAIL")
&& !c.Address.Contains("STORE")
orderby c.ShipTo descending, c.OrderDate descending
select c, i;
</code>```

UPDATE

I have a query that kinds works, but the it takes almost two minutes to execute (compared to .02s for the Oracle query) and the order of the results is incorrect. Anyone see what I'm missing?

```<code>var innerQuery = from x in model.Orders
                    where x.CustomerId == customerId
                    && !x.OrderType.Equals("A")
                    select x.OrderId;

var result = from c in model.CustomerShip
            join subQuery in
            (
                (from o in model.Orders
                from c in model.CustomerShip
                where c.CustomerId == customerId
                && innerQuery.Contains(o.OrderId)
                && !o.FLAG_ORD_STATUS.Equals("C")
                && c.ShipSeq == o.CustShip
                select c.ShipSeq).Distinct()

            ) on c.ShipSeq equals subQuery into temp
            from x in temp.DefaultIfEmpty()
            where c.CustomerId == customerId
            && !c.Address.Contains("RETAIL")
            && !c.Address.Contains("STORE")
            orderby c.ShipTo descending, c.OrderDate descending
            select c;
</code>```

答:
Try something like this. I model some classes just for getting the error out.  If you group by ShipSeq you don't need distinct.  Just take first item from group will give same results.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication60
{
    class Program
    {
        static void Main(string[] args)
        {
            int customerID = 1234;
            List<Order> CustomTypeA = Order.orders
                .Where(x => (x.CustomerId == customerID) && (x.OrderType == "A") && (x.OrderStatus == "C")).ToList();

            var results = (from CustA in CustomTypeA
                          join CustShip in Ship.CustomerShip on CustA.CustomerId equals CustShip.CustomerId
                          select new { CustA = CustA, CustShip = CustShip})
                          .Where(x => (!RetailStore(x.CustShip.Address)) && (x.CustA.CustShip == x.CustShip.ShipSeq))
                          .OrderByDescending(x => x.CustShip.OrderDate)
                          .GroupBy(x => x.CustShip.ShipSeq)
                          .Select(x => x.FirstOrDefault())
                          .Select(x => new {
                              CustomerID = x.CustShip.CustomerId,
                              Address = x.CustShip.Address,
                              OrderDate = x.CustShip.OrderDate
                          }).ToList();

        }
        static Boolean RetailStore(string address)
        {
            string pattern = "RETAIL.*STORE";
            return Regex.IsMatch(address, pattern);
        }
    }
    public class Order
    {
        public static List<Order> orders = new List<Order>();

        public int CustomerId { get; set; }
        public string OrderType { get; set; }
        public string CustShip { get; set; }
        public string OrderStatus { get; set; }
    }
    public class Ship
    {
        public static List<Ship> CustomerShip = new List<Ship>();

        public int CustomerId { get; set; }
        public string ShipSeq { get; set; }
        public string Address { get; set; }
        public DateTime OrderDate { get; set; }
     }
}
</code>```

Title: Linq query with multiple subqueries

Body:
I'm working on converting an Oracle Sql query to Linq, and not sure how to proceed. Here is the Sql query:

SELECT *
FROM   CustomerShip,
    (SELECT DISTINCT b.ShipSeq AS shipSeq
     FROM   Orders a,
            CustomerShip b
     WHERE  a.OrderId IN (SELECT OrderId
                          FROM   Orders
                          WHERE  CustomerId = @CustomerId
                          AND    OrderType <> 'A')
     AND    b.CustomerId = @CustomerId
     AND    b.ShipSeq = a.CustShip
     AND    OrderStatus <> 'C'
     GROUP BY b.ShipSeq) i
WHERE  CustomerId = @CustomerId
AND    (Address NOT LIKE '%RETAIL%STORE%')
AND    ShipSeq = i.ShipSeq(+)
ORDER BY ShipTo DESC, OrderDate DESC;

I have tried to break it down into three separate queries when converting to linq.

var query1 = from c in CustomerShip
            where c.CustomerId == customerId
            && !c.Address.Contains("RETAIL")
            && !c.Address.Contains("STORE")
            orderby c.ShipTo descending, c.OrderDate descending
            select c;

var query2 = from o in Orders
         where o.CustomerId == customerId
         && !o.OrderType.Equals("A")
         select o.OrderId;

var query3 = (from o in Orders
         from c in CustomerShip
         where c.CustomerId == customerId
         && c.ShipSeq == o.CustShip
         && !o.OrderStatus.Equals("A")
         select c.ShipSeq).Distinct();

Now I'm trying to assemble them all into one query, but unsure how to do it. Here is the direction I am going:

var query = from c in CustomerShip

let subquery = from o in Orders
               where o.CustomerId == customerId
               && !o.OrderType.Equals("A")
               select o.OrderId

    from or in model.Orders
    where subquery.Contains(or.OrderId)
    && c.CustomerId == customerId
    && c.ShipSeq == or.CustShip
    && !or.OrderStatus.Equals("A")
    group c by c.ShipSeq
    into i
    select c.ShipSeq

where c.CustomerId == customerId
&& !c.Address.Contains("RETAIL")
&& !c.Address.Contains("STORE")
orderby c.ShipTo descending, c.OrderDate descending
select c, i;

UPDATE

I have a query that kinds works, but the it takes almost two minutes to execute (compared to .02s for the Oracle query) and the order of the results is incorrect. Anyone see what I'm missing?

var innerQuery = from x in model.Orders
                    where x.CustomerId == customerId
                    && !x.OrderType.Equals("A")
                    select x.OrderId;

var result = from c in model.CustomerShip
            join subQuery in
            (
                (from o in model.Orders
                from c in model.CustomerShip
                where c.CustomerId == customerId
                && innerQuery.Contains(o.OrderId)
                && !o.FLAG_ORD_STATUS.Equals("C")
                && c.ShipSeq == o.CustShip
                select c.ShipSeq).Distinct()

            ) on c.ShipSeq equals subQuery into temp
            from x in temp.DefaultIfEmpty()
            where c.CustomerId == customerId
            && !c.Address.Contains("RETAIL")
            && !c.Address.Contains("STORE")
            orderby c.ShipTo descending, c.OrderDate descending
            select c;

Body:
Try something like this. I model some classes just for getting the error out.  If you group by ShipSeq you don't need distinct.  Just take first item from group will give same results.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication60
{
    class Program
    {
        static void Main(string[] args)
        {
            int customerID = 1234;
            List<Order> CustomTypeA = Order.orders
                .Where(x => (x.CustomerId == customerID) && (x.OrderType == "A") && (x.OrderStatus == "C")).ToList();

            var results = (from CustA in CustomTypeA
                          join CustShip in Ship.CustomerShip on CustA.CustomerId equals CustShip.CustomerId
                          select new { CustA = CustA, CustShip = CustShip})
                          .Where(x => (!RetailStore(x.CustShip.Address)) && (x.CustA.CustShip == x.CustShip.ShipSeq))
                          .OrderByDescending(x => x.CustShip.OrderDate)
                          .GroupBy(x => x.CustShip.ShipSeq)
                          .Select(x => x.FirstOrDefault())
                          .Select(x => new {
                              CustomerID = x.CustShip.CustomerId,
                              Address = x.CustShip.Address,
                              OrderDate = x.CustShip.OrderDate
                          }).ToList();

        }
        static Boolean RetailStore(string address)
        {
            string pattern = "RETAIL.*STORE";
            return Regex.IsMatch(address, pattern);
        }
    }
    public class Order
    {
        public static List<Order> orders = new List<Order>();

        public int CustomerId { get; set; }
        public string OrderType { get; set; }
        public string CustShip { get; set; }
        public string OrderStatus { get; set; }
    }
    public class Ship
    {
        public static List<Ship> CustomerShip = new List<Ship>();

        public int CustomerId { get; set; }
        public string ShipSeq { get; set; }
        public string Address { get; set; }
        public DateTime OrderDate { get; set; }
     }
}


问:
PHP Doctrine with SQL Server Always On
I am developing an application using Symfony 3 (php 7.1) with SQL Server database with AlwaysOn. AlwaysOn is a SQL server support for high-availability and disaster recovery, and Doctrine 2 is not working well with this paradigm.

I've developed a CRUD to test it for the infrastructure section at my job that implemented this database. At the first time, it was working correctly and persisting ok. But, when they change the instance for another one, like when happens if the first one stops working, automatically go to the other instance with the same database structure and data. When it happens I receive an error message from doctrine:

```<code>Fatal error: Invalid handle returned. in C:\xampp\htdocs\testesql\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOConnection.php on line 43
</code>```

It looks like Doctrine caches something that is not working with this paradigm of database. I am using Microsoft SQL Server driver (pdo_sqlsrv). Could someone help me? I would be glad.

答:
Problem solved! It is very hard to work with SQL Server Always On considering it is a new tecnology and PHP 7.1 is too. (08/06/17)

I solved the problem changing symfony doctrine driver from "pdo_sqlsrv" to just "sqlsrv" follwing Doctrine 2 Documentation infos.

If anyone has a problem with SQL Server Always On using PHP, remember:

It is only possible to login different instances with Windows User (AD or LDAP). You would not be able to login using DB user and pass using different instances.

To login in SQL Server Always On to make it work correctly, you have to login in the database using Apache authentication.

Title: PHP Doctrine with SQL Server Always On

Body:
I am developing an application using Symfony 3 (php 7.1) with SQL Server database with AlwaysOn. AlwaysOn is a SQL server support for high-availability and disaster recovery, and Doctrine 2 is not working well with this paradigm.

I've developed a CRUD to test it for the infrastructure section at my job that implemented this database. At the first time, it was working correctly and persisting ok. But, when they change the instance for another one, like when happens if the first one stops working, automatically go to the other instance with the same database structure and data. When it happens I receive an error message from doctrine:

Fatal error: Invalid handle returned. in C:\xampp\htdocs\testesql\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOConnection.php on line 43

It looks like Doctrine caches something that is not working with this paradigm of database. I am using Microsoft SQL Server driver (pdo_sqlsrv). Could someone help me? I would be glad.


问:
Uncaught SyntaxError JSON.parse
I am trying to parse a JSON string and it throws
Uncaught SyntaxError : Unexpected token error. Below is the content am having in a variable as a string.

Note : I checked the typeof() for the jsonString variable and it returned string. So the variable is of string type and no doubt in
  that

JSON String :

```<code>{"title":"This is my Title","body":"<div class="ExternalClassB5F21AC89A1F40D0BCA5A8DBB6F738ED"><span style="font-size:11.0pt;font-family:"Calibri",sans-serif;">Our commitment to the development of this feature is
delayed  due to the unexpected JSON parse error.  </span></div>","byline":"This issue is killing me now for more than 2 days.  ","tile":0,"showText":true,"showImage":true,"image":{"ImageUrl":"/Path/to/imgFolder/hero%20background.png","Hyperlink":"","OpenHyperlinkInNewWindow":false,"Alignment":"","AlternateText":"","BorderWidth":0,"Height":0,"HorizontalSpacing":0,"VerticalSpacing":0,"Width":0},"publishedDate":"/Date(1496864514000)/","labels":["Character and Values"],"peopleList":[]}
</code>```

I couldn't identify whats the problem is. Does any one have the clue?

Based on the line and column number in the error, it shows that the unexpected character is in ending of line 1 i.e at the end of this feature is in line 1. So all I can guess is that the line break might be the problem. Even if the line break causes, is there any way to handle this parsing issue.

Thanks in advance.

答:
You can use https://jsonlint.com/ to validate your JSON. With fixed newlines it looks like:</p>

```<code>{
    "title": "This is my Title",
    "body": "<div class="ExternalClassB5F21AC89A1F40D0BCA5A8DBB6F738ED"><span style="font-size&#58;11.0pt;font-family&#58;&quot;Calibri&quot;,sans-serif;">Our commitment to the development of this feature is delayed due to the unexpected JSON parse error. & amp;#160;</span></div>",
    "byline": "This issue is killing me now for more than 2 days.  ",
    "tile": 0,
    "showText": true,
    "showImage": true,
    "image": {
        "ImageUrl": "/Path/to/imgFolder/hero%20background.png",
        "Hyperlink": "",
        "OpenHyperlinkInNewWindow": false,
        "Alignment": "",
        "AlternateText": "",
        "BorderWidth": 0,
        "Height": 0,
        "HorizontalSpacing": 0,
        "VerticalSpacing": 0,
        "Width": 0
    },
    "publishedDate": "/Date(1496864514000)/",
    "labels": ["Character and Values"],
    "peopleList": []
}
</code>```

Title: Uncaught SyntaxError JSON.parse

Body:
I am trying to parse a JSON string and it throws
Uncaught SyntaxError : Unexpected token error. Below is the content am having in a variable as a string.

Note : I checked the typeof() for the jsonString variable and it returned string. So the variable is of string type and no doubt in
  that

JSON String :

{"title":"This is my Title","body":"
Our commitment to the development of this feature is
delayed  due to the unexpected JSON parse error. &#160;
","byline":"This issue is killing me now for more than 2 days.  ","tile":0,"showText":true,"showImage":true,"image":{"ImageUrl":"/Path/to/imgFolder/hero%20background.png","Hyperlink":"","OpenHyperlinkInNewWindow":false,"Alignment":"","AlternateText":"","BorderWidth":0,"Height":0,"HorizontalSpacing":0,"VerticalSpacing":0,"Width":0},"publishedDate":"/Date(1496864514000)/","labels":["Character and Values"],"peopleList":[]}

I couldn't identify whats the problem is. Does any one have the clue?

Based on the line and column number in the error, it shows that the unexpected character is in ending of line 1 i.e at the end of this feature is in line 1. So all I can guess is that the line break might be the problem. Even if the line break causes, is there any way to handle this parsing issue.

Thanks in advance.

Body:
You can use https://jsonlint.com/ to validate your JSON. With fixed newlines it looks like:

{
    "title": "This is my Title",
    "body": "&lt;div class=&quot;ExternalClassB5F21AC89A1F40D0BCA5A8DBB6F738ED&quot;&gt;&lt;span style=&quot;font-size&amp;#58;11.0pt;font-family&amp;#58;&amp;quot;Calibri&amp;quot;,sans-serif;&quot;&gt;Our commitment to the development of this feature is delayed due to the unexpected JSON parse error. & amp;#160;&lt;/span&gt;&lt;/div&gt;",
    "byline": "This issue is killing me now for more than 2 days.  ",
    "tile": 0,
    "showText": true,
    "showImage": true,
    "image": {
        "ImageUrl": "/Path/to/imgFolder/hero%20background.png",
        "Hyperlink": "",
        "OpenHyperlinkInNewWindow": false,
        "Alignment": "",
        "AlternateText": "",
        "BorderWidth": 0,
        "Height": 0,
        "HorizontalSpacing": 0,
        "VerticalSpacing": 0,
        "Width": 0
    },
    "publishedDate": "/Date(1496864514000)/",
    "labels": ["Character and Values"],
    "peopleList": []
}


问:
Gitlab: gem not found
I am trying to deploy our app to Heroku and our settings in .gitlab-ci.yml looks like

```<code>staging_heroku:
  stage: deploy
  script:
  - git remote add heroku https://heroku:$STAGING_HEROKU_KEY@git.heroku.com/staging-myapp.git
  - git push -f heroku master
</code>```

This is what we see in logs

```<code>Cloning repository...
Cloning into '/builds/org/project'...
Checking out 340111af as dev/feature1...
Skipping Git submodules setup
Downloading artifacts for maven-build (17234382)...
Downloading artifacts from coordinator... ok        id=17234382 responseStatus=200 OK token=2YSHdANA
/bin/sh: eval: line 46: apt-get: not found
$ apt-get update -yqqq
ERROR: Job failed: exit code 127
</code>```

These runners do not even have apt-get and so I can not install gem.

I even tried git command, but even that is not found. Can someone help?

答:
You need to install ruby and ruby-dev first! (and rubygems-integration for Debian 8)

```<code>staging:
  type: deploy
  script:
  - apt-get update -yq
  - apt-get install -y ruby ruby-dev rubygems-integration
  - gem install dpl
  - dpl --provider=heroku --app=teeth-taroko --api-key=$HEROKU_STAGING_API_KEY
  only:
  - develop
</code>```

Title: Gitlab: gem not found

Body:
I am trying to deploy our app to Heroku and our settings in .gitlab-ci.yml looks like

staging_heroku:
  stage: deploy
  script:
  - git remote add heroku https://heroku:$STAGING_HEROKU_KEY@git.heroku.com/staging-myapp.git
  - git push -f heroku master

This is what we see in logs

Cloning repository...
Cloning into '/builds/org/project'...
Checking out 340111af as dev/feature1...
Skipping Git submodules setup
Downloading artifacts for maven-build (17234382)...
Downloading artifacts from coordinator... ok        id=17234382 responseStatus=200 OK token=2YSHdANA
/bin/sh: eval: line 46: apt-get: not found
$ apt-get update -yqqq
ERROR: Job failed: exit code 127

These runners do not even have apt-get and so I can not install gem.

I even tried git command, but even that is not found. Can someone help?

Body:
You need to install ruby and ruby-dev first! (and rubygems-integration for Debian 8)

staging:
  type: deploy
  script:
  - apt-get update -yq
  - apt-get install -y ruby ruby-dev rubygems-integration
  - gem install dpl
  - dpl --provider=heroku --app=teeth-taroko --api-key=$HEROKU_STAGING_API_KEY
  only:
  - develop


问:
compilation Error CS0176 (static member cannot be accessed) on non static method
my problem is the following :

when I try to compile my c# apps it run into this exception :

Static member 'ResponseManager.manage(Response)' cannot be accessed
  with an instance reference; qualify it with a type name instead

on this

```<code>ResponseManager responseManager = new ResponseManager();
responseManager.manage(response);
</code>```

As you can see I'm using a new instance of the ResponseManager.

here is his "manage" method's declaration :

public void manage(Response response)

I checked in project and it's the only method with this name, she's not static and ResponseManager don't have any static fields/methods and yet it won't compile.

When i try to rename my method everywhere in my code (declaration and usage) I get the following error :

ResponseManager does not contain a definition for 'sometest' and no
  extension method 'sometest' accepting a first argument of type
  'ResponseManager ' could be found (are you missing a using
  directive or an assembly reference?)

I hope I provided enought information to help me resolve this.
Many thanks !

Edit :

```<code>public class ResponseManager
{

    TransactionDAO transactionDAO = new TransactionDAO();
    LignesDAO ligneDAO = new LignesDAO();
    SimDAO simDAO = new SimDAO();
    MailSender mailSender = new MailSender();
    HttpClient httpClient = new HttpClient();
    ApplicationDAO appDAO = new ApplicationDAO();

    //RENAME !!!!!!!!
    public void manage(Response response)
    {

        if (response.responseStatus.status == "SUCCESS")
        {
            transactionDAO.updateTransactionById(response.header.transactionId, response.responseStatus.status);

            string type = transactionDAO.getTransactionTypeById(response.header.transactionId);

            if(type != null) {

                switch (type) {
                    case "activate":
                        ligneDAO.setActivatedSim(response.simIdendity.simSerial);
                        //simDAO.setActivatedSim(response.simIdendity.simSerial);

                        break;
                    case "suspend":
                        ligneDAO.setSuspendedSim(response.simIdendity.simSerial);
                        //simDAO.setSuspendedSim(response.simIdendity.simSerial);

                        break;
                    case "reactivate":
                        ligneDAO.setActivatedSim(response.simIdendity.simSerial);
                        //simDAO.setActivatedSim(response.simIdendity.simSerial);

                        break;
                    case "detail-subscription":

                        break;
                    case "detail-sim":
                        //Mapping between Response and Sim classes

                        break;
                    case "bar" :

                        break;
                    case "unbar" :

                        break;
                }
            }

            int appId = transactionDAO.getIdAppFromTransactionId(response.header.transactionId);

            string url = appDAO.getUrlFromAppId(appId);

            httpClient.send(null, url);

        }
        else
        {
            transactionDAO.updateTransactionById(response.header.transactionId, response.responseStatus.status, response.responseStatus.errorCode);

            string type = transactionDAO.getTransactionTypeById(response.header.transactionId);

            mailSender.createTransatelProvisionningErrorMail(response.header.transactionId, response.simIdendity.simSerial, response.simIdendity.msisdn, type, response.responseStatus.errorCode, response.responseStatus.reason);
        }

    }

}
</code>```

答:
You can try doing a clean solution. Build > Clean Solution.

You can also try deleting all obj folders in your solution and rebuilding solution.

Body:
my problem is the following :

when I try to compile my c# apps it run into this exception :

Static member 'ResponseManager.manage(Response)' cannot be accessed
  with an instance reference; qualify it with a type name instead

on this

ResponseManager responseManager = new ResponseManager();
responseManager.manage(response);

As you can see I'm using a new instance of the ResponseManager.

here is his "manage" method's declaration :

public void manage(Response response)

I checked in project and it's the only method with this name, she's not static and ResponseManager don't have any static fields/methods and yet it won't compile.

When i try to rename my method everywhere in my code (declaration and usage) I get the following error :

ResponseManager does not contain a definition for 'sometest' and no
  extension method 'sometest' accepting a first argument of type
  'ResponseManager ' could be found (are you missing a using
  directive or an assembly reference?)

I hope I provided enought information to help me resolve this.
Many thanks !

Edit :

public class ResponseManager
{

    TransactionDAO transactionDAO = new TransactionDAO();
    LignesDAO ligneDAO = new LignesDAO();
    SimDAO simDAO = new SimDAO();
    MailSender mailSender = new MailSender();
    HttpClient httpClient = new HttpClient();
    ApplicationDAO appDAO = new ApplicationDAO();

    //RENAME !!!!!!!!
    public void manage(Response response)
    {

        if (response.responseStatus.status == "SUCCESS")
        {
            transactionDAO.updateTransactionById(response.header.transactionId, response.responseStatus.status);

            string type = transactionDAO.getTransactionTypeById(response.header.transactionId);

            if(type != null) {

                switch (type) {
                    case "activate":
                        ligneDAO.setActivatedSim(response.simIdendity.simSerial);
                        //simDAO.setActivatedSim(response.simIdendity.simSerial);

                        break;
                    case "suspend":
                        ligneDAO.setSuspendedSim(response.simIdendity.simSerial);
                        //simDAO.setSuspendedSim(response.simIdendity.simSerial);

                        break;
                    case "reactivate":
                        ligneDAO.setActivatedSim(response.simIdendity.simSerial);
                        //simDAO.setActivatedSim(response.simIdendity.simSerial);

                        break;
                    case "detail-subscription":

                        break;
                    case "detail-sim":
                        //Mapping between Response and Sim classes

                        break;
                    case "bar" :

                        break;
                    case "unbar" :

                        break;
                }
            }

            int appId = transactionDAO.getIdAppFromTransactionId(response.header.transactionId);

            string url = appDAO.getUrlFromAppId(appId);

            httpClient.send(null, url);

        }
        else
        {
            transactionDAO.updateTransactionById(response.header.transactionId, response.responseStatus.status, response.responseStatus.errorCode);

            string type = transactionDAO.getTransactionTypeById(response.header.transactionId);

            mailSender.createTransatelProvisionningErrorMail(response.header.transactionId, response.simIdendity.simSerial, response.simIdendity.msisdn, type, response.responseStatus.errorCode, response.responseStatus.reason);
        }

    }

}


问:
How to get project language from sonarqube API?
How can I get the main programming language of a project, using sonarqube API? Or a list of all of the project's programming languages?</p>

答:
Per SonarQube Metric Definitions documentation :

ncloc_language_distribution - Non Commenting Lines of Code Distributed By Language.

Use that with SonarQube WebAPI api/measures (documentation embedded in your SonarQube server) and you should be good to go.


问:
Passing input text back to parent from component
I am using an auto expanding text input field (Link) and I am creating it as a component. My question is when the text is changed how do I pass the value of the data back to the parent? I want to be able to submit the input via the parent so I was thinking of storing the input value in the parents state.

Parent

Calling the child component by using <InputExpand />

```<code>render() {

    const { navigate } = this.props.navigation;

    console.log("Rendering");

    return (
        <KeyboardAvoidingView behavior="padding" style={{flex: 1}}>
        <View style={{flex: 1}}>
            <StatusBar hidden={true} />
            <View style={styles.headerBar}>
                <NavBar navigation={this.props.navigation} goBack={this.goBack} title="MESSAGE DETAILS" backButton={true} showNewMessage={true} />
            </View>
            <View style={styles.contentWrapper}>
                <ListView
                        dataSource={this.state.dataSource}
                        renderRow={this.renderRow}
                        enableEmptySections={true}
                        style={styles.listWrapper}
                    />
            </View>
            <View style={styles.footerBar}>
                    <View style={styles.footerBtnContainer}></View>
                    <View style={styles.footerInputContainer}>
                        <InputExpand />
                    </View>
                    <View style={styles.footerBtnContainer}>
                        <Image source={require('../../images/icons/IconSend.png')} style={{width: 20, height: 20}}/>
                    </View>
            </View>
        </View>
        </KeyboardAvoidingView>
    );
  }
</code>```

Component - (Child)

```<code>import React, { Component } from 'react'

const {
  TextInput,
  StyleSheet,
} = require('react-native');

export default class AutoExpandingTextInput extends React.Component {
  state: any;

  constructor(props) {
    super(props);
    this.state = {text: '', height: 0};
  }
  render() {
    return (
      <TextInput
        {...this.props}
        multiline={true}
        onChange={(event) => {
          this.setState({
            text: event.nativeEvent.text,
            height: event.nativeEvent.contentSize.height,
          });
        }}
        style={[styles.default, {height: Math.max(35, this.state.height)}]}
        value={this.state.text}
        placeholder={"Type a message..."}
        placeholderTextColor={"#fff"}
      />
    );
  }
}

var styles = StyleSheet.create({
  default: {
    color: "#fff",
    fontSize: 10,
    fontFamily: "Avenir-Light",
  },
});
</code>```

答: You should pass via props a callback for handle input text changes to the component, and use the onChange event of the input text to call that handle from the child component. If the input text doesn't have onChange (or something like that) you could use a onKeyUp. But the general idea is that you send a callback via props from the parent to the child, and you call it from the child to send data to the parent.</p>

Body:
I am using an auto expanding text input field (Link) and I am creating it as a component. My question is when the text is changed how do I pass the value of the data back to the parent? I want to be able to submit the input via the parent so I was thinking of storing the input value in the parents state.

Parent

Calling the child component by using <InputExpand />

render() {

    const { navigate } = this.props.navigation;

    console.log("Rendering");

    return (
        <KeyboardAvoidingView behavior="padding" style={{flex: 1}}>
        <View style={{flex: 1}}>
            <StatusBar hidden={true} />
            <View style={styles.headerBar}>
                <NavBar navigation={this.props.navigation} goBack={this.goBack} title="MESSAGE DETAILS" backButton={true} showNewMessage={true} />
            </View>
            <View style={styles.contentWrapper}>
                <ListView
                        dataSource={this.state.dataSource}
                        renderRow={this.renderRow}
                        enableEmptySections={true}
                        style={styles.listWrapper}
                    />
            </View>
            <View style={styles.footerBar}>
                    <View style={styles.footerBtnContainer}></View>
                    <View style={styles.footerInputContainer}>
                        <InputExpand />
                    </View>
                    <View style={styles.footerBtnContainer}>
                        <Image source={require('../../images/icons/IconSend.png')} style={{width: 20, height: 20}}/>
                    </View>
            </View>
        </View>
        </KeyboardAvoidingView>
    );
  }

Component - (Child)

import React, { Component } from 'react'

const {
  TextInput,
  StyleSheet,
} = require('react-native');

export default class AutoExpandingTextInput extends React.Component {
  state: any;

  constructor(props) {
    super(props);
    this.state = {text: '', height: 0};
  }
  render() {
    return (
      <TextInput
        {...this.props}
        multiline={true}
        onChange={(event) => {
          this.setState({
            text: event.nativeEvent.text,
            height: event.nativeEvent.contentSize.height,
          });
        }}
        style={[styles.default, {height: Math.max(35, this.state.height)}]}
        value={this.state.text}
        placeholder={"Type a message..."}
        placeholderTextColor={"#fff"}
      />
    );
  }
}

var styles = StyleSheet.create({
  default: {
    color: "#fff",
    fontSize: 10,
    fontFamily: "Avenir-Light",
  },
});


问:
Stacking up rows from tow tables using mysql select statement
I have two tables and wish to join them together so I can query them together. Is there anyway that I can achieve this?

For illustration purpose, see the figures below.

Table Structure

PLEASE NOTE THAT time_enrolled FOLLOWS THE PATTERN ON BOTH TABLES

答:
try this : </p>

```<code>Select
id,name,age,time_enrolled,date_joined, null as occupation from students
union
select
id,name,null as age,time_enrolled,null as date_joined, occupation
from parents
</code>```

Body:
try this :

Select
id,name,age,time_enrolled,date_joined, null as occupation from students
union
select
id,name,null as age,time_enrolled,null as date_joined, occupation
from parents