问:
PHP MySQL while loop not returning anything
I'm quite new to php and mysql so hopefully someone with more experience will be able to give me some guidance here.

I have the following code:

```<code><?php

$npcname = $_GET['npcname'];
$npcinfo="SELECT * from npcs where name='$npcname'";
$npcinfo2=mysql_query($npcinfo) or die("could not get npc!");
$npcinfo3=mysql_fetch_array($npcinfo2);

$listquests = "SELECT * from quests where npcid = '$npcinfo3[npcid]'";
$listquests2 = mysql_query($listquests) or die("No Quests to list");
$listquests3=mysql_fetch_array($listquests2);

echo "<b>Quests Available for ".$npcname."</b><br>";

while($row=mysql_fetch_array($listquests2)) {

echo $row['name'];

}
?>
</code>```

To go with this I have some tables whcih look like this:

```<code>npcs
name|location|npcid

quests
name|qid|npcid
</code>```

So a quest is associated to a NPC via the npcid field.

I have one entry in each table.

```<code>Bob|Scrapyard|1
AND
Sort Scrap Metal|1|1
</code>```

As you can see the quest and Bob both share the npcid of 1.

In my loop I am trying to list all of the quests for Bob. However on running the code I do not get any quests listed.

If I put the code:

```<code>  $listquests3['name'];
</code>```

Outside of my loop it successfully displays "Sort Scrap Metal" as expected. The reason I have used the loop is to display multiple quests when I add them.

If somebody could be kind enough to take a look at the code and tell me what I have done wrong I would be grateful.

Thank You.

答:
You need to do a INNER JOIN or a LEFT JOIN. Yes after carefully seeing the question again, I found that when doing the "mysql_fetch_array()" code for the first time (just before the "while" loop), the value of the variable "$listquests2" gets lost. So the "while" loop does nothing fruitful.

You must remove this single line for variable "$listquests3".

Body:
I'm quite new to php and mysql so hopefully someone with more experience will be able to give me some guidance here.

I have the following code:

<?php

$npcname = $_GET['npcname'];
$npcinfo="SELECT * from npcs where name='$npcname'";
$npcinfo2=mysql_query($npcinfo) or die("could not get npc!");
$npcinfo3=mysql_fetch_array($npcinfo2);

$listquests = "SELECT * from quests where npcid = '$npcinfo3[npcid]'";
$listquests2 = mysql_query($listquests) or die("No Quests to list");
$listquests3=mysql_fetch_array($listquests2);

echo "Quests Available for ".$npcname."
";

while($row=mysql_fetch_array($listquests2)) {

echo $row['name'];

}
?>

To go with this I have some tables whcih look like this:

npcs
name|location|npcid

quests
name|qid|npcid

So a quest is associated to a NPC via the npcid field.

I have one entry in each table.

Bob|Scrapyard|1
AND
Sort Scrap Metal|1|1

As you can see the quest and Bob both share the npcid of 1.

In my loop I am trying to list all of the quests for Bob. However on running the code I do not get any quests listed.

If I put the code:

  $listquests3['name'];

Outside of my loop it successfully displays "Sort Scrap Metal" as expected. The reason I have used the loop is to display multiple quests when I add them.

If somebody could be kind enough to take a look at the code and tell me what I have done wrong I would be grateful.

Thank You.


来源: stackexchange

问:
Declaring array of objects
I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.

```<code>var sample = new Array();
sample[0] = new Object();
sample[1] = new Object();
</code>```

This works fine, but I don't want to mention any index number. I want all elements of my array to be an object. How do I declare or initialize it?

```<code>var sample = new Array();
sample[] = new Object();
</code>```

I tried the above code but it doesn't work. How do I initialize an array of objects without using an index number?

答:
```<code>//making array of book object
var books = [];
    var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
    books.push(new_book);
    new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
    books.push(new_book);
    console.log(books[0].id);
    console.log(books[0].name);
    console.log(books[0].category);
    console.log(books[0].price);

// also we have array of albums
var albums = []
    var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
    albums.push(new_album);
    new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
    albums.push(new_album);
//Now, content [0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name);

console.log(my_albums[0].name);
console.log(my_albums[1].name);
</code>```

This Example Works with me.
Snapshot for the Output on Browser Console

ContentLicense: CC BY-SA 3.0

Title: Declaring array of objects

Body:
I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.

var sample = new Array();
sample[0] = new Object();
sample[1] = new Object();

This works fine, but I don't want to mention any index number. I want all elements of my array to be an object. How do I declare or initialize it?

var sample = new Array();
sample[] = new Object();

I tried the above code but it doesn't work. How do I initialize an array of objects without using an index number?

Body:
//making array of book object
var books = [];
    var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
    books.push(new_book);
    new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
    books.push(new_book);
    console.log(books[0].id);
    console.log(books[0].name);
    console.log(books[0].category);
    console.log(books[0].price);

// also we have array of albums
var albums = []
    var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
    albums.push(new_album);
    new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
    albums.push(new_album);
//Now, content [0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name);

console.log(my_albums[0].name);
console.log(my_albums[1].name);

This Example Works with me.
Snapshot for the Output on Browser Console


问:
Apply CSS ~ combinator for first child
I have two items in a parent and need to apply CSS to first child only if second/other child exist. ~ does that, buy only to siblings of the first child and I need it vice versa.

tldr: Make  red with no
 before it, but after it

```<code>div ~ label {
  color: red;
}
</code>```

https://jsfiddle.net/q836Lev1/1/

div ~ label {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset>
  <div></div>
  <label>this label is red</label>
  <div>works, but not good, there must be no first div.</div>
</fieldset>

<fieldset>
  <label>this label is red</label>
  <div>doesn't work, label should be red and div comes after.</div>
</fieldset></code>```

答:
You could use label:nth-last-child(2):

label:nth-last-child(2) {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset>
  <div></div>
  <label>this label is red</label>
  <div>works, but not good, there must be no first div.</div>
</fieldset>

<fieldset>
  <label>this label is red</label>
  <div>doesn't work, label should be red and div comes after.</div>
</fieldset></code>```

Title: Apply CSS ~ combinator for first child

Body:
I have two items in a parent and need to apply CSS to first child only if second/other child exist. ~ does that, buy only to siblings of the first child and I need it vice versa.

tldr: Make  red with no
 before it, but after it

div ~ label {
  color: red;
}

https://jsfiddle.net/q836Lev1/1/

div ~ label {
  color: red;
}

<fieldset>

  this label is red

works, but not good, there must be no first div.

</fieldset>

<fieldset>
  this label is red

doesn't work, label should be red and div comes after.

</fieldset>

Body:
You could use label:nth-last-child(2):

label:nth-last-child(2) {
  color: red;
}

<fieldset>
  <div></div>
  <label>this label is red</label>
  <div>works, but not good, there must be no first div.</div>
</fieldset>

<fieldset>
  <label>this label is red</label>
  <div>doesn't work, label should be red and div comes after.</div>
</fieldset>


问:
Callback function when clicked on "selected date" in daterangepicker
using the latest version of Daterangepicker for bootstrap

For the following calendar (standard example used in their website):

```<code>$('#demo').daterangepicker({
    "singleDatePicker": true,
    "autoApply": true,
    "startDate": "05/31/2017",
    "endDate": "06/06/2017"
}, function(start, end, label) {
  console.log("a date is selected")
});
</code>```

The given callback function is called correctly when I select a date in my calendar. However, if I select the active date which is already selected, the pop up is closed but the callback function is not called. As far as I see, there is no any opportunity provided to fire a function when the same date is selected.

So, my question would be: Is there a hacking way to have a callback function which is called when the same date is selected?

For instance, I tried the following piece of code to add a listener to the active cell but it is also not fired:

```<code> $('td.active.start-date.active.end-date.available').on('click', function () {
   console.log('the same date is selected')
 })
</code>```

答:
What you can do is bind an extra event to your input which will be called when you select an option. See the following code (assuming the element with id demo is your input) Since you already use jQuery my example uses this as well:

```<code>$('#demo').on('change.datepicker', function(ev){
  var picker = $(ev.target).data('daterangepicker');
  console.log(picker.startDate); // contains the selected start date
  console.log(picker.endDate); // contains the selected end date

  // ... here you can compare the dates and call your callback.
});
</code>```

Hope this will help!

Body:
using the latest version of Daterangepicker for bootstrap

For the following calendar (standard example used in their website):

$('#demo').daterangepicker({
    "singleDatePicker": true,
    "autoApply": true,
    "startDate": "05/31/2017",
    "endDate": "06/06/2017"
}, function(start, end, label) {
  console.log("a date is selected")
});

The given callback function is called correctly when I select a date in my calendar. However, if I select the active date which is already selected, the pop up is closed but the callback function is not called. As far as I see, there is no any opportunity provided to fire a function when the same date is selected.

So, my question would be: Is there a hacking way to have a callback function which is called when the same date is selected?

For instance, I tried the following piece of code to add a listener to the active cell but it is also not fired:

 $('td.active.start-date.active.end-date.available').on('click', function () {
   console.log('the same date is selected')
 })

Body:
What you can do is bind an extra event to your input which will be called when you select an option. See the following code (assuming the element with id demo is your input) Since you already use jQuery my example uses this as well:

$('#demo').on('change.datepicker', function(ev){
  var picker = $(ev.target).data('daterangepicker');
  console.log(picker.startDate); // contains the selected start date
  console.log(picker.endDate); // contains the selected end date

  // ... here you can compare the dates and call your callback.
});

Hope this will help!


问:
Cannot find meteor module
I am trying to run a meteor app but keep getting the Cannot find module error when I try to import one of my files.

My folder directory:

/app/client/imports/api/tasks.js

/app/server/main.js

In my main.js I am trying to import tasks.js:

import '../client/imports/api/tasks.js';

This throws the error Error: Cannot find module '../client/imports/api/tasks.js'.

My tasks.js:

```<code>import { Mongo } from 'meteor/mongo';

export const Tasks = new Mongo.collection('tasks');
</code>```

Does anyone know what might be going on?

答:
The problem is in file structure.
Your imports/ folder should be on the same level with client/ and server/.

Title: Cannot find meteor module

Body:
I am trying to run a meteor app but keep getting the Cannot find module error when I try to import one of my files.

My folder directory:

/app/client/imports/api/tasks.js

/app/server/main.js

In my main.js I am trying to import tasks.js:

import '../client/imports/api/tasks.js';

This throws the error Error: Cannot find module '../client/imports/api/tasks.js'.

My tasks.js:

import { Mongo } from 'meteor/mongo';

export const Tasks = new Mongo.collection('tasks');

Does anyone know what might be going on?


答: You only have one row, and you fetched that row when you called mysql_fetch_array the first time. When you call it the second time, there are no more rows to fetch in the result set, the function returns false and your loop exits.

ContentLicense: CC BY-SA 2.5

Title: PHP MySQL while loop not returning anything


问:
Mongo $inc on array where index is dynamic
I want to increment a value sharded by hours.

```<code>let doc = {
  $inc: {
    totalMessages: 1,
    'activity.' + (new Date()).getHours(): 1
  }
}
</code>```

My goal is to have a count for every full hour. E.g. amount of messages done between 9 and 10 o'clock.

But string concatination doesn't work.
How can I do that?

I also want to make use of $inc upsert behavior.
so:

```<code>doc.$inc.activity[(new Date()).getHours()] = 1
</code>```

does not work neither and leads to the following MongoError: Cannot increment with non-numeric argument
or to TypeError: Cannot set property 'xx' of null

Thx

答:
You can put your dynamic value within brackets: doc.$inc['activity.' + value]

  This should work.

Body:
I want to increment a value sharded by hours.

let doc = {
  $inc: {
    totalMessages: 1,
    'activity.' + (new Date()).getHours(): 1
  }
}

My goal is to have a count for every full hour. E.g. amount of messages done between 9 and 10 o'clock.

But string concatination doesn't work.
How can I do that?

I also want to make use of $inc upsert behavior.
so:

doc.$inc.activity[(new Date()).getHours()] = 1

does not work neither and leads to the following MongoError: Cannot increment with non-numeric argument
or to TypeError: Cannot set property 'xx' of null

Thx


问:
REST Design Pattern 1 endpoint, different object return types
I'm trying to determine the best approach for returning different objects from 1 REST endpoint.

Example:

Suppose the client has a Customer ID: 123 and calls GET /api/customers/123

The consuming client has no other knowledge of the customer, other than the ID

The customer returned can either be and Individual or a Business, each with their own unique properties. Each of these objects can be updated

My current design has multiple PUT endpoints to support the unique updates

PUT /api/businesses/123

PUT /api/customers/123

The problem I see is the client now has to call another endpoint to perform the update on the Business customer which makes the API more complicated to consume and I'm not sure its best practice to return different object types from 1 GET endpoint.

Are there any alternatives or does this approach seem reasonable?

EDIT: So I think my problem is more due to the fact that I'm treating these entities are truly unique when in fact, they are the same (barring some meta data properties). @Patrick Hofman and @LB2 for your answers. I will refactor

答:
You can use HATEOAS as means of directing client where respective relevant resources are.

The model that backs the GET call would pretty much be combining data properties of both models - whether that's a good idea or not really depends on how disparate are your Business and Customer models.  If justified to be close to similar with minor differences, then perhaps combining is reasonable.

For each type however, you would generate the proper link for PUT, directing the client as to where to do the update.  What to send for update would depends on contract between your service and your client.


问:
How do I create a foreign key in rails 5 if I've already created the models for the tables I want to associate?
All of the references I've found either show me how to do it upon table creation, or are for a much earlier version of rails. Ideally, I'd like like the foreign_key to be named 'author_id' in the questions table to distinguish it from other users who may be leaving comments or answers later. </p>

```<code>class Question < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :questions
end
</code>```

答:
You can create a new empty migration file in your terminal via rails generate migration RenameUserFkOnQuestion. Open it up and build your migration. This is a handy guide if you're not sure on the name of something.

```<code>def change
  change_table :questions do |t|
    t.rename :user_id, :author_id
  end
end
</code>```

Run the migration and head over to your models. You'll need to update your relationships like so:

```<code>class Question
  belongs_to :author, class_name: 'User'
end

class User
  has_many :questions, inverse_of: :author
end
</code>```

Then you should be good to go.

Body:
All of the references I've found either show me how to do it upon table creation, or are for a much earlier version of rails. Ideally, I'd like like the foreign_key to be named 'author_id' in the questions table to distinguish it from other users who may be leaving comments or answers later.

class Question < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :questions
end

Body:
You can create a new empty migration file in your terminal via rails generate migration RenameUserFkOnQuestion. Open it up and build your migration. This is a handy guide if you're not sure on the name of something.

def change
  change_table :questions do |t|
    t.rename :user_id, :author_id
  end
end

Run the migration and head over to your models. You'll need to update your relationships like so:

class Question
  belongs_to :author, class_name: 'User'
end

class User
  has_many :questions, inverse_of: :author
end

Then you should be good to go.


问:
ReflectionException: Class db does not exist
I am creating a library that uses \Illuminate\Support\Facades\DB to reference the database. I'm getting the following exception on the call to DB::table()->where()->get(): "ReflectionException: Class db does not exist." What is the problem and what do I need to do to overcome it?

I know that there is a process using \Illuminate\Database\Capsule\Manager to establish a connection to the database. But I haven't found any example on how to make this work with \Illuminate\Support\Facades\DB.

Code sample:

```<code>use \Illuminate\Support\Facades\DB;

abstract class Data
{
    public static function tables($prefix, $mode=null)
    {
        $outbound = array();
        $tables = DB::table('information_schema.tables')->where('TABLE_NAME', 'LIKE', $prefix.'_%')->get();
        foreach ($tables as $table) {
            ...
        }
        return $outbound;
    }
}
</code>```

Stack trace:

```<code>~/vendor/laravel/framework/src/Illuminate/Container/Container.php:749
~/vendor/laravel/framework/src/Illuminate/Container/Container.php:644
~/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:709
~/vendor/laravel/framework/src/Illuminate/Container/Container.php:1203
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:175
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:144
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:231
~/Data.php:XXX
</code>```

答:
Since it's a facade, add this to the top of the class to make it work:

```<code>use DB;
</code>```

Or use full namespace:

```<code>$tables = \DB::table...
</code>```

Body:
I am creating a library that uses \Illuminate\Support\Facades\DB to reference the database. I'm getting the following exception on the call to DB::table()->where()->get(): "ReflectionException: Class db does not exist." What is the problem and what do I need to do to overcome it?

I know that there is a process using \Illuminate\Database\Capsule\Manager to establish a connection to the database. But I haven't found any example on how to make this work with \Illuminate\Support\Facades\DB.

Code sample:

use \Illuminate\Support\Facades\DB;

abstract class Data
{
    public static function tables($prefix, $mode=null)
    {
        $outbound = array();
        $tables = DB::table('information_schema.tables')->where('TABLE_NAME', 'LIKE', $prefix.'_%')->get();
        foreach ($tables as $table) {
            ...
        }
        return $outbound;
    }
}

Stack trace:

~/vendor/laravel/framework/src/Illuminate/Container/Container.php:749
~/vendor/laravel/framework/src/Illuminate/Container/Container.php:644
~/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:709
~/vendor/laravel/framework/src/Illuminate/Container/Container.php:1203
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:175
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:144
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:231
~/Data.php:XXX

Body:
Since it's a facade, add this to the top of the class to make it work:

use DB;

Or use full namespace:

$tables = \DB::table...


问:
convert jcas object to json object
I require the output in json format, for which I have to convert the jcas object in json.
I tried using the method given in uima guide but was not successful.

Can anyone suggest me a solution.

答:
Using JsonCasSerializer you can do this

```<code>final String note = "Serum Cholesterol 154 150 250 mgs/dl\n-\nSerum Triglycerides 67 90 200 mgs /dl\n-\nSerum HDL: Cholesterol 38 35 55 mgs /dl\n-\nSerum LDL: Cholesterol 49 85 150 mgs/d1\n-\nSerum VLDL: Cholesterol 13 10 40 mgs/dl\n-\nTotal Cholesterol / HDL Ratio: 3.90\";
final JCas jcas = JCasFactory.createJCas();
jcas.setDocumentText(note);

final AnalysisEngineDescription aed = getFastPipeline();
SimplePipeline.runPipeline(jcas, aed);
CAS cas = jcas.getCas();

JsonCasSerializer jcs = new JsonCasSerializer();
jcs.setPrettyPrint(true); // do some configuration

StringWriter sw = new StringWriter();
jcs.serialize(cas, sw); // serialize into sw

System.out.println(sw.toString());
</code>```

This gave me an output of the document in JSON format.

Title: convert jcas object to json object

Body:
Using JsonCasSerializer you can do this

final String note = "Serum Cholesterol 154 150 250 mgs/dl\n-\nSerum Triglycerides 67 90 200 mgs /dl\n-\nSerum HDL: Cholesterol 38 35 55 mgs /dl\n-\nSerum LDL: Cholesterol 49 85 150 mgs/d1\n-\nSerum VLDL: Cholesterol 13 10 40 mgs/dl\n-\nTotal Cholesterol / HDL Ratio: 3.90\";
final JCas jcas = JCasFactory.createJCas();
jcas.setDocumentText(note);

final AnalysisEngineDescription aed = getFastPipeline();
SimplePipeline.runPipeline(jcas, aed);
CAS cas = jcas.getCas();

JsonCasSerializer jcs = new JsonCasSerializer();
jcs.setPrettyPrint(true); // do some configuration

StringWriter sw = new StringWriter();
jcs.serialize(cas, sw); // serialize into sw

System.out.println(sw.toString());

This gave me an output of the document in JSON format.


问:
HANA Left Outer Join syntax
I am trying to build a query in HANA with a left outer join. I am using a (+) sign in the where clause. I do that often in Oracle; but in HANA it is returning a syntax error. Does HANA supports this syntax?</p>

```<code>select *
FROM
   "_SYS_BIC"."FinancialReporting.ReportingViews.Tech_Analytics/CV_LOA_FINANCIAL_DETAIL_GRA" F1,
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_ACCOUNT_GRA" F2,
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COMPANY_GRA" F3,
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COSTCENTER_GRA" F4,
   "_SYS_BIC"."FinancialReporting.ReportingViews/CV_LOA_MEASURES_LEVELS_TA_GRA" F5,
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_VENDOR_GRA" F6
WHERE
   (F1."acct_nmbr" = F2."acct_nmbr")
   AND (F1."company_cd" = F3."company_cd")
   AND (F1."cost_center_cd" = F4."cost_center_cd")
   AND (F1."acct_nmbr" = F5."acct_nmbr")
   AND F1."vendor_cd" = F6."vendor_cd"(+)
   AND (F1."acctg_dt" >= '2016-01-01'
   AND F1."acctg_dt" <= '2016-02-01'))
</code>```

答:
You need to learn to use standard JOIN syntax:

```<code>select *
FROM "_SYS_BIC"."FinancialReporting.ReportingViews.Tech_Analytics/CV_LOA_FINANCIAL_DETAIL_GRA" F1 JOIN
    "_SYS_BIC"."FinancialReporting.MasterData/CV_D_ACCOUNT_GRA" F2
    ON F1."acct_nmbr" = F2."acct_nmbr" JOIN
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COMPANY_GRA" F3
    ON F1."company_cd" = F3."company_cd" JOIN
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COSTCENTER_GRA" F4
    ON F1."cost_center_cd" = F4."cost_center_cd" JOIN
   "_SYS_BIC"."FinancialReporting.ReportingViews/CV_LOA_MEASURES_LEVELS_TA_GRA" F5
   ON F1."acct_nmbr" = F5."acct_nmbr" LEFT JOIN
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_VENDOR_GRA" F6
    ON F1."vendor_cd" = F6."vendor_cd"
WHERE F1."acctg_dt" >= '2016-01-01' AND F1."acctg_dt" <= '2016-02-01';
</code>```

Title: HANA Left Outer Join syntax

Body:
I am trying to build a query in HANA with a left outer join. I am using a (+) sign in the where clause. I do that often in Oracle; but in HANA it is returning a syntax error. Does HANA supports this syntax?

select *
FROM
   "_SYS_BIC"."FinancialReporting.ReportingViews.Tech_Analytics/CV_LOA_FINANCIAL_DETAIL_GRA" F1,
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_ACCOUNT_GRA" F2,
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COMPANY_GRA" F3,
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COSTCENTER_GRA" F4,
   "_SYS_BIC"."FinancialReporting.ReportingViews/CV_LOA_MEASURES_LEVELS_TA_GRA" F5,
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_VENDOR_GRA" F6
WHERE
   (F1."acct_nmbr" = F2."acct_nmbr")
   AND (F1."company_cd" = F3."company_cd")
   AND (F1."cost_center_cd" = F4."cost_center_cd")
   AND (F1."acct_nmbr" = F5."acct_nmbr")
   AND F1."vendor_cd" = F6."vendor_cd"(+)
   AND (F1."acctg_dt" >= '2016-01-01'
   AND F1."acctg_dt" <= '2016-02-01'))

Body:
You need to learn to use standard JOIN syntax:

select *
FROM "_SYS_BIC"."FinancialReporting.ReportingViews.Tech_Analytics/CV_LOA_FINANCIAL_DETAIL_GRA" F1 JOIN
    "_SYS_BIC"."FinancialReporting.MasterData/CV_D_ACCOUNT_GRA" F2
    ON F1."acct_nmbr" = F2."acct_nmbr" JOIN
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COMPANY_GRA" F3
    ON F1."company_cd" = F3."company_cd" JOIN
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_COSTCENTER_GRA" F4
    ON F1."cost_center_cd" = F4."cost_center_cd" JOIN
   "_SYS_BIC"."FinancialReporting.ReportingViews/CV_LOA_MEASURES_LEVELS_TA_GRA" F5
   ON F1."acct_nmbr" = F5."acct_nmbr" LEFT JOIN
   "_SYS_BIC"."FinancialReporting.MasterData/CV_D_VENDOR_GRA" F6
    ON F1."vendor_cd" = F6."vendor_cd"
WHERE F1."acctg_dt" >= '2016-01-01' AND F1."acctg_dt" <= '2016-02-01';


问:
jQuery scroll to anchor returns NaN as location hash
Friends,

I'm using following jQuery code which implements the animated scroll to an anchor:

```<code>(function($){
var jump=function(e)
{
    if (e){
        e.preventDefault();
        var target = $(this).attr("href");
    }else{
        var target = location.hash;
    }
    $('html,body').animate(
        {
            scrollTop: $(target).offset().top - 150
        }, 1500, 'swing', function()
        {
            location.hash = target - 150;
        });
};
$('html, body').hide();
$(document).ready(function()
{
    $('a[href^=#]:not(#toggle)').on("click", jump);
    if (location.hash){
        setTimeout(function(){
            $('html, body').scrollTop(0).show();
            jump()
        }, 0);
    }else{
        $('html, body').show()
    }
});
})(jQuery);
</code>```

As you see from the code above, I use the target offset value of 150px:

```<code>scrollTop: $(target).offset().top - 150
</code>```

In order for this code to work properly, I also need to pass the target with offset to the location.hash. This is how I do that:

```<code>location.hash = target - 150;
</code>```

Under such implementation, the code works fine. Except it always show #NaN in the URL when I scroll to anchor. This is clearly because of the line above. However, if I don't use the -150px, then it scrolls to target with offset and then suddenly jumps to original anchor location without offset.

My question is, how I can achieve both win win situation? I mean, no #NaN in URL and proper scroll to anchor with offset from top.  I heard that it's possible to use "e.preventdefault", but somehow it doesn't work for me.

Any suggestions would be very appreciated.

答:
location.hash includes the #, so you if you try to do arithmetic on it it can't be converted to a number.

Use Number(location.hash.substr(1)) instead.  You'll need to add the # back in whenever you try to use that number as a DOM ID.

(You might consider changing your code to not use the same variable to indicate both DOM nodes and scroll position, though; it's fairly confusing.  If I were refactoring this I'd change those IDs to meaningful labels, and set the scroll position based on those element's offset().top instead of on the numeric content of the hash itself.)

Body:
Friends,

I'm using following jQuery code which implements the animated scroll to an anchor:

(function($){
var jump=function(e)
{
    if (e){
        e.preventDefault();
        var target = $(this).attr("href");
    }else{
        var target = location.hash;
    }
    $('html,body').animate(
        {
            scrollTop: $(target).offset().top - 150
        }, 1500, 'swing', function()
        {
            location.hash = target - 150;
        });
};
$('html, body').hide();
$(document).ready(function()
{
    $('a[href^=#]:not(#toggle)').on("click", jump);
    if (location.hash){
        setTimeout(function(){
            $('html, body').scrollTop(0).show();
            jump()
        }, 0);
    }else{
        $('html, body').show()
    }
});
})(jQuery);

As you see from the code above, I use the target offset value of 150px:

scrollTop: $(target).offset().top - 150

In order for this code to work properly, I also need to pass the target with offset to the location.hash. This is how I do that:

location.hash = target - 150;

Under such implementation, the code works fine. Except it always show #NaN in the URL when I scroll to anchor. This is clearly because of the line above. However, if I don't use the -150px, then it scrolls to target with offset and then suddenly jumps to original anchor location without offset.

My question is, how I can achieve both win win situation? I mean, no #NaN in URL and proper scroll to anchor with offset from top.  I heard that it's possible to use "e.preventdefault", but somehow it doesn't work for me.

Any suggestions would be very appreciated.


问:
Protected External Resource Usage
I'm working with some code where I have the following setup.

```<code>struct data
{
      void change_safe_member(){}
      void read_data(){}
      void change_unsafe_member(){}
};

struct data_processor
{
     std::shared_ptr<data> get_data(){}
     void return_data(std::shared_ptr<data> my_data)
     {
           my_data->change_unsafe_member(); // ONLY data_processor should call this function.
     }
};

struct client
{
     void foo(std::shared_ptr<data_processor>& my_processor)
     {
           auto my_data = my_processor->get_data();
           my_data->change_safe_member();
           //my_data->change_unsafe_member(); SHOULD NOT BE POSSIBLE TO CALL
           my_processor->return_data(my_data);
     }
};
</code>```

The change_unsafe_member should only be used internally by the processor so I would like to hide it or disable it for the client. But I don't know of any nice ways of doing this without resorting to ugly casts...

```<code>struct internal_data
{
      void change_unsafe_member(){}
};

struct data : public internal_data
{
      void change_safe_member(){}
      void read_data(){}
};

struct data_processor
{
     std::shared_ptr<data> get_data(){}
     void return_data(std::shared_ptr<data> my_data)
     {
           auto internal_data = std::static_pointer_cast<internal_data>(my_data);
           internal_data->change_unsafe_member();
     }
};
</code>```

Anyone know of a good pattern to use in situations like this? Maybe visitor pattern or something similar?

EDIT:

As pointed out in the comments one could declare friend classes, there is however one problem... the following will not work.

```<code>struct data
{
      void change_safe_member(){}
      void read_data(){}
private:
      friend class data_processor;
      virtual void change_unsafe_member(){}
};

struct data_decorator : public data
{
      data_decorator(const std::shared_ptr<data>& decoratee) : decoratee_(decoratee){}
      void change_safe_member(){decoratee_->change_safe_member();}
      void read_data(){decoratee_->read_data();}
private:
      virtual void change_unsafe_member()
      {
             std::cout << "Hello!"; // Add functionality
             decoratee_->change_unsafe_member(); // Won't work... compiler error
      }
      std::shared_ptr<data> decoratee_;
};

// Another example
struct data_group_decorator : public data
{
      data_group_decorator (const std::vector<std::shared_ptr<data>>& decoratees) : decoratees_(decoratees){}
      void change_safe_member(){decoratee_->change_safe_member();}
      void read_data(){decoratee_->read_data();}
private:
      virtual void change_unsafe_member()
      {
             for(size_t n = 0; n < decoratees_.size(); ++n)
                   decoratees_[n]->change_unsafe_member(); // Won't work... compiler error
      }
      std::vector<std::shared_ptr<data>> decoratees_;;
};
</code>```

答:
You can make this happen with inheritance.

```<code>struct Y;
struct X {
    friend struct Y;
private:
    change_unsafe_member() {}
};
struct Y {
protected:
    change_unsafe_member(X& x) { x.change_unsafe_member(); }
};
struct some_other : Y {
    X x;
    change_safe_member() { change_unsafe_member(x); }
};
</code>```

Any class that inherits from Y can gain X's friendship for any functions that Y defines as effectively forwards from X.

Title: Protected External Resource Usage

Body:
I'm working with some code where I have the following setup.

struct data
{
      void change_safe_member(){}
      void read_data(){}
      void change_unsafe_member(){}
};

struct data_processor
{
     std::shared_ptr<data> get_data(){}
     void return_data(std::shared_ptr<data> my_data)
     {
           my_data->change_unsafe_member(); // ONLY data_processor should call this function.
     }
};

struct client
{
     void foo(std::shared_ptr<data_processor>& my_processor)
     {
           auto my_data = my_processor->get_data();
           my_data->change_safe_member();
           //my_data->change_unsafe_member(); SHOULD NOT BE POSSIBLE TO CALL
           my_processor->return_data(my_data);
     }
};

The change_unsafe_member should only be used internally by the processor so I would like to hide it or disable it for the client. But I don't know of any nice ways of doing this without resorting to ugly casts...

struct internal_data
{
      void change_unsafe_member(){}
};

struct data : public internal_data
{
      void change_safe_member(){}
      void read_data(){}
};

struct data_processor
{
     std::shared_ptr<data> get_data(){}
     void return_data(std::shared_ptr<data> my_data)
     {
           auto internal_data = std::static_pointer_cast<internal_data>(my_data);
           internal_data->change_unsafe_member();
     }
};

Anyone know of a good pattern to use in situations like this? Maybe visitor pattern or something similar?

EDIT:

As pointed out in the comments one could declare friend classes, there is however one problem... the following will not work.

struct data
{
      void change_safe_member(){}
      void read_data(){}
private:
      friend class data_processor;
      virtual void change_unsafe_member(){}
};

struct data_decorator : public data
{
      data_decorator(const std::shared_ptr<data>& decoratee) : decoratee_(decoratee){}
      void change_safe_member(){decoratee_->change_safe_member();}
      void read_data(){decoratee_->read_data();}
private:
      virtual void change_unsafe_member()
      {
             std::cout << "Hello!"; // Add functionality
             decoratee_->change_unsafe_member(); // Won't work... compiler error
      }
      std::shared_ptr<data> decoratee_;
};

// Another example
struct data_group_decorator : public data
{
      data_group_decorator (const std::vector<std::shared_ptr<data>>& decoratees) : decoratees_(decoratees){}
      void change_safe_member(){decoratee_->change_safe_member();}
      void read_data(){decoratee_->read_data();}
private:
      virtual void change_unsafe_member()
      {
             for(size_t n = 0; n < decoratees_.size(); ++n)
                   decoratees_[n]->change_unsafe_member(); // Won't work... compiler error
      }
      std::vector<std::shared_ptr<data>> decoratees_;;
};

Body:
You can make this happen with inheritance.

struct Y;
struct X {
    friend struct Y;
private:
    change_unsafe_member() {}
};
struct Y {
protected:
    change_unsafe_member(X& x) { x.change_unsafe_member(); }
};
struct some_other : Y {
    X x;
    change_safe_member() { change_unsafe_member(x); }
};

Any class that inherits from Y can gain X's friendship for any functions that Y defines as effectively forwards from X.


问:
Why does Python optimize out "if 0", but not "if None"?
Why is it that if you compile a conditional expression like

```<code>def f():
    if None:
        print(222)
    if 0:
        print(333)
</code>```

the branches that use numbers get optimized out, but those that use None don't? Example:

```<code> 3        0 LOAD_CONST               0 (None)
          3 POP_JUMP_IF_FALSE       14

 4        6 LOAD_CONST               1 (222)
          9 PRINT_ITEM
         10 PRINT_NEWLINE
         11 JUMP_FORWARD             0 (to 14)

 5  >>   14 LOAD_CONST               0 (None)
         17 RETURN_VALUE
</code>```

In which scenarios could if 0 and if None behave differently?

答:
My guess: It's an oversight that happened because None is just a special-cased name (or global) in python-2.x.

If you take a look at the bytecode-optimizer code in python-2.x:

switch (opcode) {

   /* ... More cases ... */

        /* Replace LOAD_GLOBAL/LOAD_NAME None
           with LOAD_CONST None */
    case LOAD_NAME:
    case LOAD_GLOBAL:
        j = GETARG(codestr, i);
        name = PyString_AsString(PyTuple_GET_ITEM(names, j));
        if (name == NULL  ||  strcmp(name, "None") != 0)
            continue;
        for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
            if (PyList_GET_ITEM(consts, j) == Py_None)
                break;
        }
        if (j == PyList_GET_SIZE(consts)) {
            if (PyList_Append(consts, Py_None) == -1)
                goto exitError;
        }
        assert(PyList_GET_ITEM(consts, j) == Py_None);
        codestr[i] = LOAD_CONST;
        SETARG(codestr, i, j);
        cumlc = lastlc + 1;
        break;      /* Here it breaks, so it can't fall through into the next case */

        /* Skip over LOAD_CONST trueconst
           POP_JUMP_IF_FALSE xx. This improves
           "while 1" performance. */
    case LOAD_CONST:
        cumlc = lastlc + 1;
        j = GETARG(codestr, i);
        if (codestr[i+3] != POP_JUMP_IF_FALSE  ||
            !ISBASICBLOCK(blocks,i,6)  ||
            !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
            continue;
        memset(codestr+i, NOP, 6);
        cumlc = 0;
        break;

   /* ... More cases ... */

}
```

<p>You may notice that <code>None</code> is loaded with <code>LOAD_GLOBAL</code> or <code>LOAD_NAME</code> and then replaced by <code>LOAD_CONST</code>. </p>

<p>However: After it is replaced it <code>break</code>s, so it can't go into the <code>LOAD_CONST</code> case in which the block would be replaced with a <code>NOP</code> if the constant isn't <code>True</code>. </p>

<hr>

<p>In python-3.x the optimizer doesn't need to special case the name (or global) <code>None</code> because it's always loaded with <code>LOAD_CONST</code> and the bytecode-optimizer reads:</p>

<pre class="lang-c prettyprint-override"><code>switch (opcode) {

   /* ... More cases ... */

        /* Skip over LOAD_CONST trueconst
           POP_JUMP_IF_FALSE xx.  This improves
           "while 1" performance.  */
    case LOAD_CONST:
        CONST_STACK_PUSH_OP(i);
        if (nextop != POP_JUMP_IF_FALSE  ||
            !ISBASICBLOCK(blocks, op_start, i + 1)  ||
            !PyObject_IsTrue(PyList_GET_ITEM(consts, get_arg(codestr, i))))
            break;
        fill_nops(codestr, op_start, nexti + 1);
        CONST_STACK_POP(1);
        break;

   /* ... More cases ... */

}
</code>```

There's no special case for LOAD_NAME and LOAD_GLOBAL anymore so if None (but also if False - False was also made a constant in python-3.x) will go into the LOAD_CONST case and then replaced by a NOP.

Body:
Why is it that if you compile a conditional expression like

def f():
    if None:
        print(222)
    if 0:
        print(333)

the branches that use numbers get optimized out, but those that use None don't? Example:

 3        0 LOAD_CONST               0 (None)
          3 POP_JUMP_IF_FALSE       14

 4        6 LOAD_CONST               1 (222)
          9 PRINT_ITEM
         10 PRINT_NEWLINE
         11 JUMP_FORWARD             0 (to 14)

 5  >>   14 LOAD_CONST               0 (None)
         17 RETURN_VALUE

In which scenarios could if 0 and if None behave differently?

Body:
My guess: It's an oversight that happened because None is just a special-cased name (or global) in python-2.x.

If you take a look at the bytecode-optimizer code in python-2.x:

switch (opcode) {

   /* ... More cases ... */

        /* Replace LOAD_GLOBAL/LOAD_NAME None
           with LOAD_CONST None */
    case LOAD_NAME:
    case LOAD_GLOBAL:
        j = GETARG(codestr, i);
        name = PyString_AsString(PyTuple_GET_ITEM(names, j));
        if (name == NULL  ||  strcmp(name, "None") != 0)
            continue;
        for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
            if (PyList_GET_ITEM(consts, j) == Py_None)
                break;
        }
        if (j == PyList_GET_SIZE(consts)) {
            if (PyList_Append(consts, Py_None) == -1)
                goto exitError;
        }
        assert(PyList_GET_ITEM(consts, j) == Py_None);
        codestr[i] = LOAD_CONST;
        SETARG(codestr, i, j);
        cumlc = lastlc + 1;
        break;      /* Here it breaks, so it can't fall through into the next case */

        /* Skip over LOAD_CONST trueconst
           POP_JUMP_IF_FALSE xx. This improves
           "while 1" performance. */
    case LOAD_CONST:
        cumlc = lastlc + 1;
        j = GETARG(codestr, i);
        if (codestr[i+3] != POP_JUMP_IF_FALSE  ||
            !ISBASICBLOCK(blocks,i,6)  ||
            !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
            continue;
        memset(codestr+i, NOP, 6);
        cumlc = 0;
        break;

   /* ... More cases ... */

}

You may notice that None is loaded with LOAD_GLOBAL or LOAD_NAME and then replaced by LOAD_CONST.

However: After it is replaced it breaks, so it can't go into the LOAD_CONST case in which the block would be replaced with a NOP if the constant isn't True.

In python-3.x the optimizer doesn't need to special case the name (or global) None because it's always loaded with LOAD_CONST and the bytecode-optimizer reads:

switch (opcode) {

   /* ... More cases ... */

        /* Skip over LOAD_CONST trueconst
           POP_JUMP_IF_FALSE xx.  This improves
           "while 1" performance.  */
    case LOAD_CONST:
        CONST_STACK_PUSH_OP(i);
        if (nextop != POP_JUMP_IF_FALSE  ||
            !ISBASICBLOCK(blocks, op_start, i + 1)  ||
            !PyObject_IsTrue(PyList_GET_ITEM(consts, get_arg(codestr, i))))
            break;
        fill_nops(codestr, op_start, nexti + 1);
        CONST_STACK_POP(1);
        break;

   /* ... More cases ... */

}

There's no special case for LOAD_NAME and LOAD_GLOBAL anymore so if None (but also if False - False was also made a constant in python-3.x) will go into the LOAD_CONST case and then replaced by a NOP.


问:
Java MergeSort Binary files
I have several sorted binary files which store information in some variable length format (meaning one of the segments contains the length of the variable length segment).

I need to merge them into one sorted file. I can do so with BufferedInputStream successfully. Nevertheless, it takes very long time on a mechanical disk. On a machine with SSD its much faster, as expected.

What bothers me is the fact that even on SSD, the CPU utilization is very low, and makes me suspect there's a way to improve the speed. I assume this happens because most of the time the CPU waits on the disk. I tried to increase the buffers to hundreds of MBs to no avail.

I have tried to use MemoryMapped buffer and file channel but it didn't improve the runtime.

Any ideas?

Edit: Using MemoryMappedByteBuffer failed because the merged file size is over 2 GB, which is the size limitation of MemoryMappedByteBuffer. But even before having merged the smaller files into GB files, I didn't notice an improvement in speed or CPU utilization.

Thanks

答:
Perhaps you can compress the files better or is that not an option? If the bottleneck is I/O then reducing the amount is a good attack angle.
http://www.oracle.com/technetwork/articles/java/compress-1565076.html</p>

Title: Java MergeSort Binary files


问:
C++ Template : Choosing overloaded functions using implicit conversion to template instantiated type!
Consider these overloaded functions,

```<code>void fun(Int2Type<1>) {}
void fun(Int2Type<2>) {}
void fun(Int2Type<3>) {}
void fun(Int2Type<4>) {}
</code>```

I want to call these in this way,

```<code>fun(1); // this should call first function
fun(4); // this should call fourth function
</code>```

Is there a way to do that? If yes, so can we do the same with some runtime value, say this,
(please note that in the above calls, the argument is known at compile-time)

```<code>fun(value); // value can be decided at runtime!
</code>```

Or any alternative if that is not possible? The goal is, different function should be called based on different integral value!

EDIT

By the way, I cannot use any of the following:

Using switch(value)

using some SomeFuncTable funTable[] = {fun(Int2Type<1>(), fun(Int2Type<2>()} etc

答:
You can do it a little differently:

```<code>template<int N> void func();
template<> void func<1>(){/*the body*/}
template<> void func<2>(){/*the body*/}
</code>```

And then you may call: func<1>().

Or you may call the original code this way: func(Int2Type<1>()).

Anyway all of this only works with compile time constants.

Body:
Consider these overloaded functions,

void fun(Int2Type<1>) {}
void fun(Int2Type<2>) {}
void fun(Int2Type<3>) {}
void fun(Int2Type<4>) {}

I want to call these in this way,

fun(1); // this should call first function
fun(4); // this should call fourth function

Is there a way to do that? If yes, so can we do the same with some runtime value, say this,
(please note that in the above calls, the argument is known at compile-time)

fun(value); // value can be decided at runtime!

Or any alternative if that is not possible? The goal is, different function should be called based on different integral value!

EDIT

By the way, I cannot use any of the following:

Using switch(value)

using some SomeFuncTable funTable[] = {fun(Int2Type<1>(), fun(Int2Type<2>()} etc

Body:
You can do it a little differently:

template<int N> void func();
template<> void func<1>(){/*the body*/}
template<> void func<2>(){/*the body*/}

And then you may call: func<1>().

Or you may call the original code this way: func(Int2Type<1>()).

Anyway all of this only works with compile time constants.


问:
Using Microsoft Cognitive Services Emotion API for local video in Android
I am building a application in android which would record the video, store it in local storage and send it for analysis to the Emotion API. However, I am unable to form the request body. I am using the following example:
https://westus.dev.cognitive.microsoft.com/docs/services/5639d931ca73072154c1ce89/operations/56f8d40e1984551ec0a0984e/console

I just need to know how to form the request and for a video file.

答:
In addition to the comment by Maria, I tried the first two solutions from the following question:

How do I send a file in Android from a mobile device to server using http?

I would suggest to go through top 2 solutions, as they would most probably work. In RESPONSE, a Operation-Location and OID is received, to which a HTTP GET call can be made:

```<code>https://westus.api.cognitive.microsoft.com/emotion/v1.0/operations/{oid}
</code>```

Documentation: https://westus.dev.cognitive.microsoft.com/docs/services/5639d931ca73072154c1ce89/operations/56f8d4471984551ec0a0984f

The code I used for GET request:

```<code>    URIBuilder statusBuilder = new URIBuilder("https://westus.api.cognitive.microsoft.com/emotion/v1.0/operations/{oid});
statusBuilder.setParameter("oid", {oid});

URI uriStatus = statusBuilder.build();
HttpGet statusRequest = new HttpGet(uriStatus);
statusRequest.setHeader("Ocp-Apim-Subscription-Key", {key});

HttpResponse statusResponse = httpclient.execute( statusRequest );
HttpEntity entity = statusResponse.getEntity();
Header[] statusHeaders = statusResponse.getAllHeaders();
    for (Header header : statusHeaders) {
        System.out.println( "Key : " + header.getName()
            + " ,Value : " + header.getValue() );
    }
</code>```

Body:
In addition to the comment by Maria, I tried the first two solutions from the following question:

How do I send a file in Android from a mobile device to server using http?

I would suggest to go through top 2 solutions, as they would most probably work. In RESPONSE, a Operation-Location and OID is received, to which a HTTP GET call can be made:

https://westus.api.cognitive.microsoft.com/emotion/v1.0/operations/{oid}

Documentation: https://westus.dev.cognitive.microsoft.com/docs/services/5639d931ca73072154c1ce89/operations/56f8d4471984551ec0a0984f

The code I used for GET request:

    URIBuilder statusBuilder = new URIBuilder("https://westus.api.cognitive.microsoft.com/emotion/v1.0/operations/{oid});
statusBuilder.setParameter("oid", {oid});

URI uriStatus = statusBuilder.build();
HttpGet statusRequest = new HttpGet(uriStatus);
statusRequest.setHeader("Ocp-Apim-Subscription-Key", {key});

HttpResponse statusResponse = httpclient.execute( statusRequest );
HttpEntity entity = statusResponse.getEntity();
Header[] statusHeaders = statusResponse.getAllHeaders();
    for (Header header : statusHeaders) {
        System.out.println( "Key : " + header.getName()
            + " ,Value : " + header.getValue() );
    }


问:
Ways of unit testing data access layer
I have be trying to look for an effective way in unit testing my data access layer in C#. I'm primary a Java developer and have only used C# for about 6 months, in the past i've used a library called DBUnit to test against a known state database. I haven't been able to find a similar active library that can be used, closest seems to be nDBUnit but it hasn't been active for awhile now.

There seems to be a lot of conflicting methods on how and why in C#. Ideally I want to test the data access layer using mocking without the need to connect to a database and then unit test the store procedure in a separate set of tests.

In the system I'm working on, the data access layer is to use ADO.net (without the use of the Entity Framework) to call store procedures on a SQL Server.

Below is a sample code of what I have to work with; to go down the mocking path, I would have to be able to mock the SqlCommand (using IDbCommand) and/or mock the SqlConnection.

So my question is what seems to be the best way (if there is such a thing) to do this? So far the only way would be to make Proxy object that is passed into the constructor so it can return the mocked Sql* objects for testing.

I haven't had a chance to look at all the available C# mock libraries available yet.

```<code>public class CustomerRepository : ICustomerRepository
{
   private string connectionString;

   public CustomerRepository (string connectionString)
   {
     this.connectionString = connectionString;
   }

   public int Create(Customer customer)
   {

     SqlParameter paramOutId = new SqlParameter("@out_id", SqlDbType.Int);
     paramOutId.Direction = ParameterDirection.Output;
     List<SqlParameter> sqlParams = new List<SqlParameter>()
     {
       paramOutId,
       new SqlParameter("@name", customer.Name)
     }

     SqlConnection connection = GetConnection();
     try
     {
       SqlCommand command = new SqlCommand("store_proc_name", connection);

       command.CommandType = CommandType.StoredProcedure;

       command.Parameters.AddRange(sqlParams.ToArray());

       int results = command.ExecuteNonQuery();

       return (int) paramOutId.Value;
     }
     finally
     {
       CloseConnection(connection);
     }

   }

}
</code>```

答:
To test DataAccess Layer you will need a more complex structure.

DataAccess Layer will call references from Repository objects.
Repo object will call references from Entity Framework DbSets via UnitOfWork design pattern.

DataAccess Layer  (TOP)

|

UnitOfWork

|

Repository Pattern Classes

|

EF Context

|

Actual Database

After you set structure, then you will mock repository classes. For example, items will be inserted to DB instead will go to mock object. Later you will assert against your mock object to see item inserted or not.

Please take a look at Implementing the Repository and Unit of Work Patterns

Title: Ways of unit testing data access layer

Body:
I have be trying to look for an effective way in unit testing my data access layer in C#. I'm primary a Java developer and have only used C# for about 6 months, in the past i've used a library called DBUnit to test against a known state database. I haven't been able to find a similar active library that can be used, closest seems to be nDBUnit but it hasn't been active for awhile now.

There seems to be a lot of conflicting methods on how and why in C#. Ideally I want to test the data access layer using mocking without the need to connect to a database and then unit test the store procedure in a separate set of tests.

In the system I'm working on, the data access layer is to use ADO.net (without the use of the Entity Framework) to call store procedures on a SQL Server.

Below is a sample code of what I have to work with; to go down the mocking path, I would have to be able to mock the SqlCommand (using IDbCommand) and/or mock the SqlConnection.

So my question is what seems to be the best way (if there is such a thing) to do this? So far the only way would be to make Proxy object that is passed into the constructor so it can return the mocked Sql* objects for testing.

I haven't had a chance to look at all the available C# mock libraries available yet.

public class CustomerRepository : ICustomerRepository
{
   private string connectionString;

   public CustomerRepository (string connectionString)
   {
     this.connectionString = connectionString;
   }

   public int Create(Customer customer)
   {

     SqlParameter paramOutId = new SqlParameter("@out_id", SqlDbType.Int);
     paramOutId.Direction = ParameterDirection.Output;
     List<SqlParameter> sqlParams = new List<SqlParameter>()
     {
       paramOutId,
       new SqlParameter("@name", customer.Name)
     }

     SqlConnection connection = GetConnection();
     try
     {
       SqlCommand command = new SqlCommand("store_proc_name", connection);

       command.CommandType = CommandType.StoredProcedure;

       command.Parameters.AddRange(sqlParams.ToArray());

       int results = command.ExecuteNonQuery();

       return (int) paramOutId.Value;
     }
     finally
     {
       CloseConnection(connection);
     }

   }

}


问:
Python Beautiful Soup: Target tag only within another
I've been looking for an answer to this question but I'm having little luck. Here is the HTML which I will explain:

```<code><div class="news-overflow-hidden">
    <h3>
        <i class="pholder"></i>
        <a href="/news/view/141524/" style="">ЕСПЧ присудил €15 000 экс-главе службы безопасности ЮКОСа</a> </h3>
    <p class="news-text">
        <a href="/news/view/141524/">В такую сумму Европейский суд по правам человека оценил несоблюдение в отношении мужчины презумпции невиновности и нарушение при исследовании свидетельских показаний в судах.</a> </p>
    <i class="news-type-icon"></i>
</div>
</code>```

What I want to do is grab the inside of
. The problem is that
 exists in other places so if I grab just that, I will grab things I do not need. How can I target  tags that only exist within this type of paragraph? Could I grab all the paragraphs with this class and then make an if statement for each to see if the contents contain  or not? Ideas?

答:
You can apply multiple conditions to multiple elements in a single CSS selector:

```<code>soup.select("p.news-text a")
</code>```

This will locate all a elements that are children of the p element that has a news-text class.

Demo:

```<code>In [11]: from bs4 import BeautifulSoup

In [12]: data = """<div class="news-overflow-hidden">
    ...:     <h3>
    ...:         <i class="pholder"></i>
    ...:         <a href="/news/view/141524/" style="">ЕСПЧ присудил €15 000 экс-главе службы безопас
    ...: ности ЮКОСа</a> </h3>
    ...:     <p class="news-text">
    ...:         <a href="/news/view/141524/">В такую сумму Европейский суд по правам человека оценил
    ...:  несоблюдение в отношении мужчины презумпции невиновности и нарушение при исследовании свиде
    ...: тельских показаний в судах.</a> </p>
    ...:     <i class="news-type-icon"></i>
    ...: </div>"""

In [13]: soup = BeautifulSoup(data, "html.parser")

In [14]: for a in soup.select("p.news-text a"):
    ...:     print(a.get_text(strip=True))
    ...:
В такую сумму Европейский суд по правам человека оценил несоблюдение в отношении мужчины презумпции невиновности и нарушение при исследовании свидетельских показаний в судах.
</code>```

Body:
I've been looking for an answer to this question but I'm having little luck. Here is the HTML which I will explain:

        ЕСПЧ присудил €15 000 экс-главе службы безопасности ЮКОСа

        В такую сумму Европейский суд по правам человека оценил несоблюдение в отношении мужчины презумпции невиновности и нарушение при исследовании свидетельских показаний в судах.

What I want to do is grab the inside of
. The problem is that
 exists in other places so if I grab just that, I will grab things I do not need. How can I target  tags that only exist within this type of paragraph? Could I grab all the paragraphs with this class and then make an if statement for each to see if the contents contain  or not? Ideas?

Body:
You can apply multiple conditions to multiple elements in a single CSS selector:

soup.select("p.news-text a")

This will locate all a elements that are children of the p element that has a news-text class.

Demo:

In [11]: from bs4 import BeautifulSoup

In [12]: data = """<div class="news-overflow-hidden">
    ...:     <h3>
    ...:         <i class="pholder"></i>
    ...:         <a href="/news/view/141524/" style="">ЕСПЧ присудил €15 000 экс-главе службы безопас
    ...: ности ЮКОСа</a> </h3>
    ...:     <p class="news-text">
    ...:         <a href="/news/view/141524/">В такую сумму Европейский суд по правам человека оценил
    ...:  несоблюдение в отношении мужчины презумпции невиновности и нарушение при исследовании свиде
    ...: тельских показаний в судах.</a> </p>
    ...:     <i class="news-type-icon"></i>
    ...: </div>"""

In [13]: soup = BeautifulSoup(data, "html.parser")

In [14]: for a in soup.select("p.news-text a"):
    ...:     print(a.get_text(strip=True))
    ...:
В такую сумму Европейский суд по правам человека оценил несоблюдение в отношении мужчины презумпции невиновности и нарушение при исследовании свидетельских показаний в судах.


问:
Extract and save attachment from email (via SES) into AWS S3
I want to extract the attachment from email and save it into my new S3 bucket. So far, I have configured AWS Simple Email Service to intercept incoming emails. Now I have an AWS lambda python function, which gets triggered on S3 Put.

Until this it is working. But my lambda is giving error saying: "[Errno 2] No such file or directory: 'abc.docx': OSError". I see that the attachment with the name abc.docx is mentioned in the raw email in S3.

I assume the problem is in my upload_file. Could you please help me here.

Please find below the relevant parts of my code.

```<code>s3 = boto3.client('s3')
s3resource = boto3.resource('s3')

waiterFlg = s3.get_waiter('object_exists')
waiterFlg.wait(Bucket=bucket, Key=key)

response = s3resource.Bucket(bucket).Object(key)

message = email.message_from_string(response.get()["Body"].read())

    if len(message.get_payload()) == 2:

        attachment = msg.get_payload()[1]
        s3resource.meta.client.upload_file(attachment.get_filename(), outputBucket, attachment.get_filename())

    else:
        print("Could not see file/attachment.")
</code>```

答: You can download the attachment to /tmp directory in Lambda and then upload to S3.</p>

Body:
I want to extract the attachment from email and save it into my new S3 bucket. So far, I have configured AWS Simple Email Service to intercept incoming emails. Now I have an AWS lambda python function, which gets triggered on S3 Put.

Until this it is working. But my lambda is giving error saying: "[Errno 2] No such file or directory: 'abc.docx': OSError". I see that the attachment with the name abc.docx is mentioned in the raw email in S3.

I assume the problem is in my upload_file. Could you please help me here.

Please find below the relevant parts of my code.

s3 = boto3.client('s3')
s3resource = boto3.resource('s3')

waiterFlg = s3.get_waiter('object_exists')
waiterFlg.wait(Bucket=bucket, Key=key)

response = s3resource.Bucket(bucket).Object(key)

message = email.message_from_string(response.get()["Body"].read())

    if len(message.get_payload()) == 2:

        attachment = msg.get_payload()[1]
        s3resource.meta.client.upload_file(attachment.get_filename(), outputBucket, attachment.get_filename())

    else:
        print("Could not see file/attachment.")


问:
Grails 3 and GORM 6 for MongoDB - duplicated key error
Environment:

Grails 3.2.9

GORM 6.1.2 for MongoDB 3.4.2

This is my (simplified) domain class

```<code>class Cluster {

    String name
    String slug

    static constraints = {
        name        blank: false, unique: true
        slug        blank: false, unique: true, validator: { return it == it.toLowerCase().replaceAll(/[^\w-]/, '') }
    }

    static mapping = {
        collection 'Cluster'
        id name: 'slug'
    }

}
</code>```

As you can see I mapped the slug property to be the document _id.

I can successfully add a document with

```<code>Cluster cluster = new Cluster(name: 'Dallas', slug: 'dal05')
cluster.insert(failOnError: true)
</code>```

and everything works fine. But if I execute the same insert command again I get a duplicated key exception:

```<code>com.mongodb.MongoBulkWriteException: Bulk write operation error on server localhost:27017. Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key error index: db.Cluster.$_id_ dup key: { : "dal05" }', details={ }}]
</code>```

while I would have expected a simple validation error, stating duplicated key.

However, although the unique constraint fails, validation is correctly triggered for the other two (empty value or e.g. 'Dal05' -capital letters not allowed-).

Without mapping the id on slug property, so leaving the default assigned logic, everything works as expected.

Am I missing something? Thanks in advance!

答:
It seems this is actually a bug, scheduled to be fixed in upcoming GORM release 6.1.5.

Ref. issue: https://github.com/grails/grails-data-mapping/issues/951

Body:
Environment:

Grails 3.2.9

GORM 6.1.2 for MongoDB 3.4.2

This is my (simplified) domain class

class Cluster {

    String name
    String slug

    static constraints = {
        name        blank: false, unique: true
        slug        blank: false, unique: true, validator: { return it == it.toLowerCase().replaceAll(/[^\w-]/, '') }
    }

    static mapping = {
        collection 'Cluster'
        id name: 'slug'
    }

}

As you can see I mapped the slug property to be the document _id.

I can successfully add a document with

Cluster cluster = new Cluster(name: 'Dallas', slug: 'dal05')
cluster.insert(failOnError: true)

and everything works fine. But if I execute the same insert command again I get a duplicated key exception:

com.mongodb.MongoBulkWriteException: Bulk write operation error on server localhost:27017. Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key error index: db.Cluster.$_id_ dup key: { : "dal05" }', details={ }}]

while I would have expected a simple validation error, stating duplicated key.

However, although the unique constraint fails, validation is correctly triggered for the other two (empty value or e.g. 'Dal05' -capital letters not allowed-).

Without mapping the id on slug property, so leaving the default assigned logic, everything works as expected.

Am I missing something? Thanks in advance!


问:
Established methods for websites to serve database results
Are there established methods or frameworks for serving database rows to web clients?  So far I just have them submit a JSON object ex

```<code>{
  Query: "SELECT",
  Schema: "icecream",
  Table: "cones",
  Fields: ["price", "flavor"],
  Filters: [
    {
      "Comparison": "=",
      "Field": "flavor",
      "Value": "chocolate"
    }
  ]
}
</code>```

I verify that the fields mentioned are authorized/correct, then construct a prepared statement mysql string, but are there any frameworks, or standard methods of implementing this?

答:
It looks like you're reinventing a query language!

Why not allow your users to type SQL queries directly? Or mongodb queries, or whatever DBMS you use. There is much less overhead.

When it comes to security, a good practice is to setup a clone of your database (a read-only replica), and have your clients hit the read-only replica instead of the main database node.

Your main node and your read-only replica can stay in sync using replication. Any good DBMS supports it.

A good example of this is the Stack Exchange Data Explorer

Body:
Are there established methods or frameworks for serving database rows to web clients?  So far I just have them submit a JSON object ex

{
  Query: "SELECT",
  Schema: "icecream",
  Table: "cones",
  Fields: ["price", "flavor"],
  Filters: [
    {
      "Comparison": "=",
      "Field": "flavor",
      "Value": "chocolate"
    }
  ]
}

I verify that the fields mentioned are authorized/correct, then construct a prepared statement mysql string, but are there any frameworks, or standard methods of implementing this?


问:
PHP MySQL while loop not returning anything
I'm quite new to php and mysql so hopefully someone with more experience will be able to give me some guidance here.

I have the following code:

```<code><?php

$npcname = $_GET['npcname'];
$npcinfo="SELECT * from npcs where name='$npcname'";
$npcinfo2=mysql_query($npcinfo) or die("could not get npc!");
$npcinfo3=mysql_fetch_array($npcinfo2);

$listquests = "SELECT * from quests where npcid = '$npcinfo3[npcid]'";
$listquests2 = mysql_query($listquests) or die("No Quests to list");
$listquests3=mysql_fetch_array($listquests2);

echo "<b>Quests Available for ".$npcname."</b><br>";

while($row=mysql_fetch_array($listquests2)) {

echo $row['name'];

}
?>
</code>```

To go with this I have some tables whcih look like this:

```<code>npcs
name|location|npcid

quests
name|qid|npcid
</code>```

So a quest is associated to a NPC via the npcid field.

I have one entry in each table.

```<code>Bob|Scrapyard|1
AND
Sort Scrap Metal|1|1
</code>```

As you can see the quest and Bob both share the npcid of 1.

In my loop I am trying to list all of the quests for Bob. However on running the code I do not get any quests listed.

If I put the code:

```<code>  $listquests3['name'];
</code>```

Outside of my loop it successfully displays "Sort Scrap Metal" as expected. The reason I have used the loop is to display multiple quests when I add them.

If somebody could be kind enough to take a look at the code and tell me what I have done wrong I would be grateful.

Thank You.

答:
This statement: "$listquests3=mysql_fetch_array($listquests2);" already fetches the first. Sicne you have only one, there's nothing more to fetch, so the next call to mysql_fetch_array will return nothing.

That should fix it, but for your own 'experience', this might be a good moment to start learning about MySQL joins (LEFT JOIN in particular). You can easily find a lot about it on the internet!

Body:
I'm quite new to php and mysql so hopefully someone with more experience will be able to give me some guidance here.

I have the following code:

<?php

$npcname = $_GET['npcname'];
$npcinfo="SELECT * from npcs where name='$npcname'";
$npcinfo2=mysql_query($npcinfo) or die("could not get npc!");
$npcinfo3=mysql_fetch_array($npcinfo2);

$listquests = "SELECT * from quests where npcid = '$npcinfo3[npcid]'";
$listquests2 = mysql_query($listquests) or die("No Quests to list");
$listquests3=mysql_fetch_array($listquests2);

echo "Quests Available for ".$npcname."
";

while($row=mysql_fetch_array($listquests2)) {

echo $row['name'];

}
?>

To go with this I have some tables whcih look like this:

npcs
name|location|npcid

quests
name|qid|npcid

So a quest is associated to a NPC via the npcid field.

I have one entry in each table.

Bob|Scrapyard|1
AND
Sort Scrap Metal|1|1

As you can see the quest and Bob both share the npcid of 1.

In my loop I am trying to list all of the quests for Bob. However on running the code I do not get any quests listed.

If I put the code:

  $listquests3['name'];

Outside of my loop it successfully displays "Sort Scrap Metal" as expected. The reason I have used the loop is to display multiple quests when I add them.

If somebody could be kind enough to take a look at the code and tell me what I have done wrong I would be grateful.

Thank You.


问:
TypeError: Cannot read property 'pipesCount' of undefined
I'm using ionic to build a hybrid app and just updated everything.

```<code>global packages:

@ionic/cli-utils : 1.2.0
Cordova CLI      : 7.0.1
Ionic CLI        : 3.2.0

local packages:

@ionic/app-scripts              : 1.3.7
@ionic/cli-plugin-cordova       : 1.2.1
@ionic/cli-plugin-ionic-angular : 1.2.0
Cordova Platforms               : android 6.2.3 ios 4.4.0
Ionic Framework                 : ionic-angular 3.3.0

System:

Node       : v8.0.0
OS         : macOS Sierra
Xcode      : Xcode 8.3.2 Build version 8E2002
ios-deploy : 1.9.1
ios-sim    : 5.0.13
</code>```

I installed my android and ios platform then I ran 'ionic cordova resources' to install my new icon and splash. I'm trying to run 'ionic upload and I'm getting this error:

```<code>`Running app-scripts build:

[15:06:57]  build dev started ...
[15:06:57]  clean started ...
[15:06:57]  clean finished in 2 ms
[15:06:57]  copy started ...
[15:06:57]  transpile started ...
[15:07:00]  transpile finished in 2.82 s
[15:07:00]  preprocess started ...
[15:07:00]  deeplinks started ...
[15:07:00]  deeplinks finished in 23 ms
[15:07:00]  preprocess finished in 24 ms
[15:07:00]  webpack started ...
[15:07:00]  copy finished in 3.13 s
[15:07:09]  webpack finished in 9.33 s
[15:07:09]  sass started ...
[15:07:11]  sass finished in 1.45 s
[15:07:11]  postprocess started ...
[15:07:11]  postprocess finished in 13 ms
[15:07:11]  lint started ...
[15:07:11]  build dev finished in 13.74 s

_stream_readable.js:545
  switch (state.pipesCount) {
               ^

TypeError: Cannot read property 'pipesCount' of undefined
    at module.exports.Readable.pipe (_stream_readable.js:545:16)
    at module.exports.ZipArchiveOutputStream._smartStream (/usr/local/lib/node_modules/ionic/node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js:184:11)
    at module.exports.ZipArchiveOutputStream._appendStream (/usr/local/lib/node_modules/ionic/node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js:96:20)
    at module.exports.ArchiveOutputStream.entry (/usr/local/lib/node_modules/ionic/node_modules/compress-commons/lib/archivers/archive-output-stream.js:88:10)
    at module.exports.ZipStream.entry (/usr/local/lib/node_modules/ionic/node_modules/zip-stream/index.js:138:49)
    at Zip.append (/usr/local/lib/node_modules/ionic/node_modules/archiver/lib/plugins/zip.js:53:15)
    at Archiver._moduleAppend (/usr/local/lib/node_modules/ionic/node_modules/archiver/lib/core.js:172:16)
    at Archiver._onQueueTask (/usr/local/lib/node_modules/ionic/node_modules/archiver/lib/core.js:370:8)
    at /usr/local/lib/node_modules/ionic/node_modules/async/dist/async.js:4045:9
    at process (/usr/local/lib/node_modules/ionic/node_modules/async/dist/async.js:2316:17)`
</code>```

Any ideas on how to fix this?

**update: I ran 'ionic package build android' and got some new information

(node:18146) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error [ERR_IPC_CHANNEL_CLOSED]: channel closed
(node:18146) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

答: install node@6 current lts from https://nodejs.org/en/</p>

Body:
I'm using ionic to build a hybrid app and just updated everything.

global packages:

@ionic/cli-utils : 1.2.0
Cordova CLI      : 7.0.1
Ionic CLI        : 3.2.0

local packages:

@ionic/app-scripts              : 1.3.7
@ionic/cli-plugin-cordova       : 1.2.1
@ionic/cli-plugin-ionic-angular : 1.2.0
Cordova Platforms               : android 6.2.3 ios 4.4.0
Ionic Framework                 : ionic-angular 3.3.0

System:

Node       : v8.0.0
OS         : macOS Sierra
Xcode      : Xcode 8.3.2 Build version 8E2002
ios-deploy : 1.9.1
ios-sim    : 5.0.13

I installed my android and ios platform then I ran 'ionic cordova resources' to install my new icon and splash. I'm trying to run 'ionic upload and I'm getting this error:

`Running app-scripts build:

[15:06:57]  build dev started ...
[15:06:57]  clean started ...
[15:06:57]  clean finished in 2 ms
[15:06:57]  copy started ...
[15:06:57]  transpile started ...
[15:07:00]  transpile finished in 2.82 s
[15:07:00]  preprocess started ...
[15:07:00]  deeplinks started ...
[15:07:00]  deeplinks finished in 23 ms
[15:07:00]  preprocess finished in 24 ms
[15:07:00]  webpack started ...
[15:07:00]  copy finished in 3.13 s
[15:07:09]  webpack finished in 9.33 s
[15:07:09]  sass started ...
[15:07:11]  sass finished in 1.45 s
[15:07:11]  postprocess started ...
[15:07:11]  postprocess finished in 13 ms
[15:07:11]  lint started ...
[15:07:11]  build dev finished in 13.74 s

_stream_readable.js:545
  switch (state.pipesCount) {
               ^

TypeError: Cannot read property 'pipesCount' of undefined
    at module.exports.Readable.pipe (_stream_readable.js:545:16)
    at module.exports.ZipArchiveOutputStream._smartStream (/usr/local/lib/node_modules/ionic/node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js:184:11)
    at module.exports.ZipArchiveOutputStream._appendStream (/usr/local/lib/node_modules/ionic/node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js:96:20)
    at module.exports.ArchiveOutputStream.entry (/usr/local/lib/node_modules/ionic/node_modules/compress-commons/lib/archivers/archive-output-stream.js:88:10)
    at module.exports.ZipStream.entry (/usr/local/lib/node_modules/ionic/node_modules/zip-stream/index.js:138:49)
    at Zip.append (/usr/local/lib/node_modules/ionic/node_modules/archiver/lib/plugins/zip.js:53:15)
    at Archiver._moduleAppend (/usr/local/lib/node_modules/ionic/node_modules/archiver/lib/core.js:172:16)
    at Archiver._onQueueTask (/usr/local/lib/node_modules/ionic/node_modules/archiver/lib/core.js:370:8)
    at /usr/local/lib/node_modules/ionic/node_modules/async/dist/async.js:4045:9
    at process (/usr/local/lib/node_modules/ionic/node_modules/async/dist/async.js:2316:17)`

Any ideas on how to fix this?

**update: I ran 'ionic package build android' and got some new information

(node:18146) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error [ERR_IPC_CHANNEL_CLOSED]: channel closed
(node:18146) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


问:
Node-Webkit Application: Loading thousands of images from disk
I have created a node-webkit application that loads thousands of images (7,480 to be exact) from disk into an HTML table. After about 3500 images, the loading stops. In the console, I see ERR_INSUFFICIENT_RESOURCES. According to Task Manager, the memory (private working set) for my app is at around 1.37 GB when this happens. How can I prevent this from happening? Is there a way for me to increase this limit? What additional details should I provide to receive help?

答:
In the past when i have faced a similar problem, i held the images in memory, and inserted them into the dom as they scrolled into view.

I created two queues one for images not the scroll down to, and one for images that have been scrolled past. this way only images that are visible are present in the page.

If the download time is an issue try loading them into memory and see what happens, there is a chance the limit you have encountered is about placing images in the dom, and not necessarily loading the images into memory, worth a try.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image

```<code>var myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
</code>```

Body:
In the past when i have faced a similar problem, i held the images in memory, and inserted them into the dom as they scrolled into view.

I created two queues one for images not the scroll down to, and one for images that have been scrolled past. this way only images that are visible are present in the page.

If the download time is an issue try loading them into memory and see what happens, there is a chance the limit you have encountered is about placing images in the dom, and not necessarily loading the images into memory, worth a try.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image

var myImage = new Image(100, 200);
myImage.src = 'picture.jpg';


问:
Remove last numbers in rows in R
This is a fragment of my data.frame:

```<code>MC0_1_N.1   a   c
MC0_1_N.2   d   b
MC0_5_N.1   b   c
MC0_5_N.2   c   d
MC0_5_N.3   a   b
MC0_5_N.4   e   f
MC0_5_N.5   a   h
MC0_5_N.6   k   m
MC0_5_N.7   s   z
MC0_5_N.8   o   p
MC0_5_N.9   p   r
MC0_5_N.10  r   t
</code>```

Is there any way to remove the last numbers of rows (1,2,3,4...) which formed after creating data.frame?

答:
Given df and col1 your dataframe and name of the column you wish to alter:

```<code>unlist(lapply(stringi::stri_split(str = df$col1,regex = "\\."),function(x) x[[1]]))
</code>```

resulting in:

```<code>MC0_1_N
MC0_1_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
</code>```

Title: Remove last numbers in rows in R

Body:
This is a fragment of my data.frame:

MC0_1_N.1   a   c
MC0_1_N.2   d   b
MC0_5_N.1   b   c
MC0_5_N.2   c   d
MC0_5_N.3   a   b
MC0_5_N.4   e   f
MC0_5_N.5   a   h
MC0_5_N.6   k   m
MC0_5_N.7   s   z
MC0_5_N.8   o   p
MC0_5_N.9   p   r
MC0_5_N.10  r   t

Is there any way to remove the last numbers of rows (1,2,3,4...) which formed after creating data.frame?

Body:
Given df and col1 your dataframe and name of the column you wish to alter:

unlist(lapply(stringi::stri_split(str = df$col1,regex = "\\."),function(x) x[[1]]))

resulting in:

MC0_1_N
MC0_1_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N
MC0_5_N


问:
Trigger validation of a field when another field is changed
I have a custom validation directive that is being called properly when one field is changed. However, whether this field is valid is also based on another field's value. This second field is a select list if that is of importance.

I was wondering if there was some way I could trigger validation manually when the second form is changed. Perhaps by using the ng-change event. What is the proper way to handle something like this?

Here is my directive:

```<code>angular.module('myApp', []).
    directive('validage', function () {
        return {
            require: 'ngModel',
            link: function (scope, elem, attr, ngModel) {

                function validate(value) {
                    var valid = true;
                    if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
                    && scope.dep.DependantType == "Spouse") {
                        valid = false;
                    }
                    ngModel.$setValidity('validage', valid);
                    return value;
                }

                //For DOM -> model validation
                ngModel.$parsers.unshift(function (value) {
                    var valid = true;
                    if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
                    && scope.dep.DependantType == "Spouse") {
                        valid = false;
                    }
                    ngModel.$setValidity('validage', valid);
                    return value;
                });

                //For model -> DOM validation
                ngModel.$formatters.unshift(function (value) {
                    var valid = true;
                    if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
                    && scope.dep.DependantType == "Spouse") {
                        valid = false;
                    }
                    ngModel.$setValidity('validage', valid);
                    return value;
                });
            }
        };
    });
</code>```

If you're new to AngularJS, I would definitely recommend reading these 2 articles: part 1 & part 2. They are an overview of AngularJS forms.

答:
I was unable to get ng-blur="myForm.myField.$validate()" working in AngularJS 1.5, possibly because the model for myField was empty.

However, ng-blur="myForm.myField.$setTouched()" did work.

Body:
I have a custom validation directive that is being called properly when one field is changed. However, whether this field is valid is also based on another field's value. This second field is a select list if that is of importance.

I was wondering if there was some way I could trigger validation manually when the second form is changed. Perhaps by using the ng-change event. What is the proper way to handle something like this?

Here is my directive:

angular.module('myApp', []).
    directive('validage', function () {
        return {
            require: 'ngModel',
            link: function (scope, elem, attr, ngModel) {

                function validate(value) {
                    var valid = true;
                    if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
                    && scope.dep.DependantType == "Spouse") {
                        valid = false;
                    }
                    ngModel.$setValidity('validage', valid);
                    return value;
                }

                //For DOM -> model validation
                ngModel.$parsers.unshift(function (value) {
                    var valid = true;
                    if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
                    && scope.dep.DependantType == "Spouse") {
                        valid = false;
                    }
                    ngModel.$setValidity('validage', valid);
                    return value;
                });

                //For model -> DOM validation
                ngModel.$formatters.unshift(function (value) {
                    var valid = true;
                    if ((GetDateDifference(new Date(value), new Date()) < 16 || GetDateDifference(new Date(value), new Date()) > 129)
                    && scope.dep.DependantType == "Spouse") {
                        valid = false;
                    }
                    ngModel.$setValidity('validage', valid);
                    return value;
                });
            }
        };
    });

If you're new to AngularJS, I would definitely recommend reading these 2 articles: part 1 & part 2. They are an overview of AngularJS forms.


问:
Picker gives me an ArgumentOutOfRangeException, why is this happening?
I need my picker to hide elements if authorization == true.

```<code>    private async void Picker_Unfocused(object sender, FocusEventArgs e)
    {
        try
        {
            await DisplayAlert("try", picker.SelectedIndex.ToString(), "OK");

            if (response.domains[picker.SelectedIndex].authorization == true)
            {
                userNameEntry.IsVisible = false;
                passwordEntry.IsVisible = false;
                userLabel.IsVisible = false;
            }
            else
            {
                userNameEntry.IsVisible = true;
                passwordEntry.IsVisible = true;
                userLabel.IsVisible = true;
            }
        }
        catch(System.ArgumentOutOfRangeException)
        {
            await DisplayAlert("catch", picker.SelectedIndex.ToString(), "OK");
        }
    }
</code>```

This won't help. I get an ArgumentOutOfRangeException. Does anyone know why? It is important to me that this works.

Edit: Code is now current code. displayalerts just give me 0 if I select the first item, 1 if I select the second, etc. I still don't know what's going on. If the value of SelectedIndex is 0(or whatever I select) I shouldn't get an ArgumentOutOfRangeException, right?

答:
When the picker is not yet initialized or can view a null value and is thus empty, the SelectedIndex property will give you a value of -1. This value is not valid for use in an array.

You should enrich your code to account for this possibility, for instance like this:

```<code>if (picker.SelectedIndex > -1 && response.domains[picker.SelectedIndex].authorization == true)
{
    userNameEntry.IsVisible = false;
    passwordEntry.IsVisible = false;
    userLabel.IsVisible = false;
}
else
{
    userNameEntry.IsVisible = true;
    passwordEntry.IsVisible = true;
    userLabel.IsVisible = true;
}
</code>```

Body:
I need my picker to hide elements if authorization == true.

    private async void Picker_Unfocused(object sender, FocusEventArgs e)
    {
        try
        {
            await DisplayAlert("try", picker.SelectedIndex.ToString(), "OK");

            if (response.domains[picker.SelectedIndex].authorization == true)
            {
                userNameEntry.IsVisible = false;
                passwordEntry.IsVisible = false;
                userLabel.IsVisible = false;
            }
            else
            {
                userNameEntry.IsVisible = true;
                passwordEntry.IsVisible = true;
                userLabel.IsVisible = true;
            }
        }
        catch(System.ArgumentOutOfRangeException)
        {
            await DisplayAlert("catch", picker.SelectedIndex.ToString(), "OK");
        }
    }

This won't help. I get an ArgumentOutOfRangeException. Does anyone know why? It is important to me that this works.

Edit: Code is now current code. displayalerts just give me 0 if I select the first item, 1 if I select the second, etc. I still don't know what's going on. If the value of SelectedIndex is 0(or whatever I select) I shouldn't get an ArgumentOutOfRangeException, right?

Body:
When the picker is not yet initialized or can view a null value and is thus empty, the SelectedIndex property will give you a value of -1. This value is not valid for use in an array.

You should enrich your code to account for this possibility, for instance like this:

if (picker.SelectedIndex > -1 && response.domains[picker.SelectedIndex].authorization == true)
{
    userNameEntry.IsVisible = false;
    passwordEntry.IsVisible = false;
    userLabel.IsVisible = false;
}
else
{
    userNameEntry.IsVisible = true;
    passwordEntry.IsVisible = true;
    userLabel.IsVisible = true;
}


问:
How do i include multiple libraries on my local node.js server html page
So i have a html page with some facial recognition libraries on it and it works fine. But when i put the html page on a node.js local server, all the pictures and javascript libraries are not included anymore. For every library include i get an: "Uncaught SyntaxError: Unexpected token <" error, on the first line of the html page.

I tried to include them from within the node.js file like this:

```<code>var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , five = require("johnny-five"),
  led;

//iets met poort 80
app.listen(80);

// webserver handler
function handler (req, res) {

  fs.readFile(__dirname + '/emotie.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

function handler (req, res) {

  fs.readFile(__dirname + '/js/emotionmodel.js',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading emotionmodel.js');
    }

    res.writeHead(200);
    res.end(data);
  });
}

function handler (req, res) {

  fs.readFile(__dirname + '/js/emotion_classifier.js',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading emotionClassifier.js');
    }

    res.writeHead(200);
    res.end(data);
  });
}
</code>```

But it still doesnt work, and the filepath is right for sure.

答:
The error that you get is when your browser expects client-side JavaScript and gets HTML instead.

First of all, you have two functions named handler and only one of them is actually used. You should consider using a linter to help you detect problems like that.

Also, you are trying to write separate handlers to serve all of the individual files separately - what you should do instead is to put all of your static content (HTML, JS and everything else that you want to serve) into one directory and serve all of the files in there.

If you put everything in a directory called public then you could use something like this using Express:

```<code>var path = require('path');
var express = require('express');
var app = express();

var dir = path.join(__dirname, 'public');

app.use(express.static(dir));

app.listen(3000, function () {
  console.log('Listening on http://localhost:3000/');
});
</code>```

If you don't want to use Express then see this answer for more options of serving files:

How to serve an image using nodejs

What I also noticed is that you listen directly on port 80 which usually means that you run the Node app as root. Consider running it as an unprivileged user and use a reverse proxy to listen on port 80 and pass the traffic to your app that listens on some other port.

Body:
So i have a html page with some facial recognition libraries on it and it works fine. But when i put the html page on a node.js local server, all the pictures and javascript libraries are not included anymore. For every library include i get an: "Uncaught SyntaxError: Unexpected token <" error, on the first line of the html page.

I tried to include them from within the node.js file like this:

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , five = require("johnny-five"),
  led;

//iets met poort 80
app.listen(80);

// webserver handler
function handler (req, res) {

  fs.readFile(__dirname + '/emotie.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

function handler (req, res) {

  fs.readFile(__dirname + '/js/emotionmodel.js',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading emotionmodel.js');
    }

    res.writeHead(200);
    res.end(data);
  });
}

function handler (req, res) {

  fs.readFile(__dirname + '/js/emotion_classifier.js',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading emotionClassifier.js');
    }

    res.writeHead(200);
    res.end(data);
  });
}

But it still doesnt work, and the filepath is right for sure.

Body:
The error that you get is when your browser expects client-side JavaScript and gets HTML instead.

First of all, you have two functions named handler and only one of them is actually used. You should consider using a linter to help you detect problems like that.

Also, you are trying to write separate handlers to serve all of the individual files separately - what you should do instead is to put all of your static content (HTML, JS and everything else that you want to serve) into one directory and serve all of the files in there.

If you put everything in a directory called public then you could use something like this using Express:

var path = require('path');
var express = require('express');
var app = express();

var dir = path.join(__dirname, 'public');

app.use(express.static(dir));

app.listen(3000, function () {
  console.log('Listening on http://localhost:3000/');
});

If you don't want to use Express then see this answer for more options of serving files:

How to serve an image using nodejs

What I also noticed is that you listen directly on port 80 which usually means that you run the Node app as root. Consider running it as an unprivileged user and use a reverse proxy to listen on port 80 and pass the traffic to your app that listens on some other port.


问:
Java file conversion
I have a video recording in Android and the file generated is 3gp. I want to send mp4 file to server, how can I convert 3gp file to mp4, is there any jar for this purpose?</p>

答: These kind of conversions are usually CPU intensive, therefore the battery can be consumed pretty fast. Leave the conversion to the server. You may use Youtube for this</p>

Title: Java file conversion


问:
Laravel Error: Could not open input file: partisan
I know there are a lot of Laravel questions mentioning 'Could not open file: artisan'. That is not my problem. Mine specifically states 'partisan'.

I'm inputting the following code in my terminal to migrate a separate database migration to be run alone.

```<code>php partisan migrate --path="database/migrations/third_migrations"
</code>```

and I get the error message identified above. What is the correct syntax for running a migration that is in its own separate folder? Thanks guys.

答:
It's artisan, not partisan:

```<code>php artisan
</code>```

You can find this PHP file in the root of the Laravel project.

https://laravel.com/docs/5.4/artisan

Body:
I know there are a lot of Laravel questions mentioning 'Could not open file: artisan'. That is not my problem. Mine specifically states 'partisan'.

I'm inputting the following code in my terminal to migrate a separate database migration to be run alone.

php partisan migrate --path="database/migrations/third_migrations"

and I get the error message identified above. What is the correct syntax for running a migration that is in its own separate folder? Thanks guys.

Body:
It's artisan, not partisan:

php artisan

You can find this PHP file in the root of the Laravel project.

https://laravel.com/docs/5.4/artisan


答:
The following code solved the issue:

open('/tmp/newFile.docx', 'wb') as f:
    f.write(attachment.get_payload(decode=True))
s3r.meta.client.upload_file('/tmp/newFile.docx', outputBucket, attachment.get_filename())
```

Title: Extract and save attachment from email (via SES) into AWS S3

ContentLicense: CC BY-SA 4.0


问:
String or binary data would be truncated, even though the string is shorter than column length
I had a table with a column which is a VARCHAR(4). In SQL Server (Right-click > Design) I changed this to VARCHAR(10).

Now when I try to update the the value from AAAA to BBBBBB it gives me the error message:

String or binary data would be truncated. The statement has been terminated.

Is there anything else than the column's length in VARCHAR(10) that might be causing this error?

答:
Some things you need to confirm.

Is the column actually resized (does it register as varchar(10)) ?

Are you updating the correct table ?

Are you updating in the correct database ?

Check in profiler the update command that is send to the database, maybe your client does something to it ?

Are there any other string fields in your update, maybe one of them is too long ?

Are you updating the correct field with BBBBBB ?