问:
Express combined with browser-sync with node
I am very new to the world of JavaScript and i am trying to build my development environment for the first time what i want to achieve  should be simple...

I want to run an Express server along with browser-sync for hot reloading i am not using gulp or grunt

but i keep getting this error:

```<code>Starting the application in the development mode...
[BS] Proxying: http://localhost:3000
[BS] Access URLs:
 ------------------------------------
    Local: http://localhost:3000
 External: http://10.111.234.196:3000
 ------------------------------------
[BS] Watching files...
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::3000
</code>```

this is what my my scripts look like in the package.jason file

```<code>"scripts": {
"prestart": "babel-node buildScripts/startMessage.js",
"start": "npm-run-all --parallel security-check open:src",
"open:src": "babel-node buildScripts/srcServer.js & browser-sync start --proxy 'localhost:3000' --files 'src' --no-ui",
"security-check": "nsp check"
},
</code>```

in the srcServer.js :

```<code>import express from 'express';
import path  from 'path';
import open  from 'open';

const port = 3000;
const app = express();

app.get('/', function(request, response){
response.sendFile(path.join(__dirname, '../src/index.html'));
});

app.listen(port, function(err){
if(err){
console.log(err);
}else{
open('http://localhost:'+ port)
}
});
</code>```

and in the bs-config.js file is the default one i just changed ui to false

This question gave me the hint to use the proxy but i still get that error that i have no idea why ...please enlighten me i want to understand what's wrong

答:
I faced the similar issue. Looks like BrowserSync is not working with Express on the same port anymore. I managed to run both of them on different ports with connect-browser-sync middleware.

It is my server.js:

```<code>var express = require('express'),
    bodyParser = require('body-parser'),
    http = require('http'),
    path = require('path'),
    cors = require('cors');

// Express server
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);

// BrowserSync at development host
if (app.get('env') === 'development') {
    var browserSync = require('browser-sync'),
    var bsconf = {
        host: 'localhost',
        port: 3001,
        https: false,
        notify: false,
        open: false,
        online: false,
        ui: false,
        server: {
            baseDir: path.join(__dirname, '/public')
        },
        files: [path.join(__dirname, '/public/**/*.{html,css,js,json}')]
    };
    var bs = browserSync.create().init(bsconf);

    app.use(require('connect-browser-sync')(bs));
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());

// Route index.html
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Starting express server
http.createServer(app).listen(app.get('port'), function () {
    console.log('Listening on port ' + app.get('port') + '...');
});
</code>```

On port 3000 there is an Express server (with no page auto reload). And on port 3001 there is BrowserSync server serving the same content with page auto reload.

Body:
I am very new to the world of JavaScript and i am trying to build my development environment for the first time what i want to achieve  should be simple...

I want to run an Express server along with browser-sync for hot reloading i am not using gulp or grunt

but i keep getting this error:

Starting the application in the development mode...
[BS] Proxying: http://localhost:3000
[BS] Access URLs:
 ------------------------------------
    Local: http://localhost:3000
 External: http://10.111.234.196:3000
 ------------------------------------
[BS] Watching files...
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::3000

this is what my my scripts look like in the package.jason file

"scripts": {
"prestart": "babel-node buildScripts/startMessage.js",
"start": "npm-run-all --parallel security-check open:src",
"open:src": "babel-node buildScripts/srcServer.js & browser-sync start --proxy 'localhost:3000' --files 'src' --no-ui",
"security-check": "nsp check"
},

in the srcServer.js :

import express from 'express';
import path  from 'path';
import open  from 'open';

const port = 3000;
const app = express();

app.get('/', function(request, response){
response.sendFile(path.join(__dirname, '../src/index.html'));
});

app.listen(port, function(err){
if(err){
console.log(err);
}else{
open('http://localhost:'+ port)
}
});

and in the bs-config.js file is the default one i just changed ui to false

This question gave me the hint to use the proxy but i still get that error that i have no idea why ...please enlighten me i want to understand what's wrong

Body:
I faced the similar issue. Looks like BrowserSync is not working with Express on the same port anymore. I managed to run both of them on different ports with connect-browser-sync middleware.

It is my server.js:

var express = require('express'),
    bodyParser = require('body-parser'),
    http = require('http'),
    path = require('path'),
    cors = require('cors');

// Express server
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);

// BrowserSync at development host
if (app.get('env') === 'development') {
    var browserSync = require('browser-sync'),
    var bsconf = {
        host: 'localhost',
        port: 3001,
        https: false,
        notify: false,
        open: false,
        online: false,
        ui: false,
        server: {
            baseDir: path.join(__dirname, '/public')
        },
        files: [path.join(__dirname, '/public/**/*.{html,css,js,json}')]
    };
    var bs = browserSync.create().init(bsconf);

    app.use(require('connect-browser-sync')(bs));
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());

// Route index.html
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Starting express server
http.createServer(app).listen(app.get('port'), function () {
    console.log('Listening on port ' + app.get('port') + '...');
});

On port 3000 there is an Express server (with no page auto reload). And on port 3001 there is BrowserSync server serving the same content with page auto reload.


来源: stackexchange

问:
Restoring definitions and macros
Is there a way to restore macros in C, so that you can define a new macro, under which name probably other macros are already defined, and redefine it with the previous value?

so that when new defined macros are deleted and eventually redefined macros are resetted to its previous state?

Example:

```<code>// a macro parameter used in a library
#define size 10
#include <library/use_size.h>

//here the command/pragma to save the definitions
    #define size (100 / sizeof(size_t))
    // some use of size ...
//here the command/pragma to reset the definitions

#include <library/allocator_with_size.h>

#undef size

// use size as a variable name
size_t size = 0;
//...
size += 123;
</code>```

Edit: I do not want to use #undef, because it does not restore old macros. Also, if you have many macros, eg for using them in a X-macro-list (in a long repetitive code/declaration of constant arrays and structs), it looks ugly, if there are many #undef directives.

答:
Ok I researched myself and found the pragmas push_macro and pop_macro, supported by clang, gcc and visual c++. I use clang, so it is no problem to use it. The disadvantage: it does not reduce the line-count if you want to restore multiple macros ¹, but it restores the macros and can be encapsulated:

```<code>#pragma push_macro("size")
    #define size (100 / sizeof(size_t))
#pragma pop_macro("size")
</code>```

Notes:

¹ I defined multiple macros and tried to restore them with:

```<code>#pragma push_macro("size", "key", "name")
    // define them all
#pragma pop_macro("size", "key", "name")
</code>```

But that is not implemented into the compilers yet. So for each macro there must be a seperate line to do this.

ContentLicense: CC BY-SA 3.0

Title: Restoring definitions and macros

Body:
Is there a way to restore macros in C, so that you can define a new macro, under which name probably other macros are already defined, and redefine it with the previous value?

so that when new defined macros are deleted and eventually redefined macros are resetted to its previous state?

Example:

// a macro parameter used in a library
#define size 10
#include <library/use_size.h>

//here the command/pragma to save the definitions
    #define size (100 / sizeof(size_t))
    // some use of size ...
//here the command/pragma to reset the definitions

#include <library/allocator_with_size.h>

#undef size

// use size as a variable name
size_t size = 0;
//...
size += 123;

Edit: I do not want to use #undef, because it does not restore old macros. Also, if you have many macros, eg for using them in a X-macro-list (in a long repetitive code/declaration of constant arrays and structs), it looks ugly, if there are many #undef directives.

Body:
Ok I researched myself and found the pragmas push_macro and pop_macro, supported by clang, gcc and visual c++. I use clang, so it is no problem to use it. The disadvantage: it does not reduce the line-count if you want to restore multiple macros ¹, but it restores the macros and can be encapsulated:

#pragma push_macro("size")
    #define size (100 / sizeof(size_t))
#pragma pop_macro("size")

Notes:

¹ I defined multiple macros and tried to restore them with:

#pragma push_macro("size", "key", "name")
    // define them all
#pragma pop_macro("size", "key", "name")

But that is not implemented into the compilers yet. So for each macro there must be a seperate line to do this.


问:
nodejs app receive data from post and render to html
I'm just starting to use node.js and I can't quite understand few things. So please don't be mean. I tried to search the web without much results.

I want one webpage to go on wait for a post and then render the data received.
so far I was have the following app.js

```<code>    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing
    application/x-www-form-urlencoded

    app.set('view engine', 'pug');

    app.get('/', function (req, res) {
     res.render('index', {title: 'GET test',message : 'GET test'});
    });

    var data = "";

    app.post("/",function(req, res) {

    console.log(req.method);
    console.log(req.headers);
    console.log(req.url);
    data=req.body
    console.log(data);
    res.render('index', {title: 'POST test',message : 'POST test'});

    });

    app.listen(8081, function () {
      console.log('Example app listening on port 8081!');
    });
</code>```

in views/index.pug I have

```<code>    html
     head
      title = title
     body
      h1 = message
</code>```

And whenever I trigger curl --data "field=value" http://127.0.0.1:8081/
I can see the post received inside the terminal but I can't understend how to render this data in a page.

答:
You need to send dataresponses upon POST execution such as :

```<code> res.status(201).send("POST executed successufully");
</code>```

Then, within you Javascript call; you catch POST response and render what you want with something like :

```<code>$.ajax({
    success: function(data, textStatus, xhr) {
        console.log(xhr.status);
    },
    complete: function(xhr, textStatus) {
        console.log(xhr.status);
    }
});
</code>```

Body:
I'm just starting to use node.js and I can't quite understand few things. So please don't be mean. I tried to search the web without much results.

I want one webpage to go on wait for a post and then render the data received.
so far I was have the following app.js

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing
    application/x-www-form-urlencoded

    app.set('view engine', 'pug');

    app.get('/', function (req, res) {
     res.render('index', {title: 'GET test',message : 'GET test'});
    });

    var data = "";

    app.post("/",function(req, res) {

    console.log(req.method);
    console.log(req.headers);
    console.log(req.url);
    data=req.body
    console.log(data);
    res.render('index', {title: 'POST test',message : 'POST test'});

    });

    app.listen(8081, function () {
      console.log('Example app listening on port 8081!');
    });

in views/index.pug I have

    html
     head
      title = title
     body
      h1 = message

And whenever I trigger curl --data "field=value" http://127.0.0.1:8081/
I can see the post received inside the terminal but I can't understend how to render this data in a page.

Body:
You need to send dataresponses upon POST execution such as :

 res.status(201).send("POST executed successufully");

Then, within you Javascript call; you catch POST response and render what you want with something like :

$.ajax({
    success: function(data, textStatus, xhr) {
        console.log(xhr.status);
    },
    complete: function(xhr, textStatus) {
        console.log(xhr.status);
    }
});


问:
How to avoid redeclaring ticks on every file in PHP 7
Overview

In PHP 5.6 it seems that adding declare(ticks=1) and then using register_tick_function() would follow any includes and provide profiling information accordingly.

In PHP 7+ however it now seems I have to add declare(ticks=1) in every file. I use this for profiling every method call on a page load and don't now want to add this to each PHP file in my system (some I can't if they are in libraries).

I can't find anything in the docs about changes that were made to this.

Replication Steps

Create the below 2 files:

index.php

```<code><?php

declare(ticks=1);
$count = 0;

register_tick_function('ticker');
function ticker() {
  global $count;
  $count++;
}

$foo = 'foo';
$bar = 'bar';

include dirname(__FILE__) . '/inc.php';

echo $count;
</code>```

inc.php

```<code><?php

#declare(ticks=1);

$baz = "baz";
$qux = "qux";
</code>```

Results

Running php index.php in the terminal gives me:

PHP 5.6 - 7

PHP 7.0 - 5

With declare(ticks=1) uncommented in inc.php the results are:

PHP 5.6 - 8

PHP 7.0 - 8

Question

Is there any way to way to force it to follow includes and in a sense make it global in PHP 7+?

答:
According to the PHP bug filed at https://bugs.php.net/bug.php?id=71448

Due to an implementation bug, the declare(ticks=1) directive leaked into different compilation units prior to PHP 7.0. This is not how declare() directives, which are per-file or per-scope, are supposed to work.

So in fact it was a bug that it ever did work as it did in PHP 5.6 and the correct implementation has been added in PHP 7.0. Unfortunately this means it will never work but at least there is an explanation.

There is an answer on the below question that shows how to achieve this in PHP 7+

Natively profile multiple scripts in PHP7

Body:
Overview

In PHP 5.6 it seems that adding declare(ticks=1) and then using register_tick_function() would follow any includes and provide profiling information accordingly.

In PHP 7+ however it now seems I have to add declare(ticks=1) in every file. I use this for profiling every method call on a page load and don't now want to add this to each PHP file in my system (some I can't if they are in libraries).

I can't find anything in the docs about changes that were made to this.

Replication Steps

Create the below 2 files:

index.php

<?php

declare(ticks=1);
$count = 0;

register_tick_function('ticker');
function ticker() {
  global $count;
  $count++;
}

$foo = 'foo';
$bar = 'bar';

include dirname(__FILE__) . '/inc.php';

echo $count;

inc.php

<?php

#declare(ticks=1);

$baz = "baz";
$qux = "qux";

Results

Running php index.php in the terminal gives me:

PHP 5.6 - 7

PHP 7.0 - 5

With declare(ticks=1) uncommented in inc.php the results are:

PHP 5.6 - 8

PHP 7.0 - 8

Question

Is there any way to way to force it to follow includes and in a sense make it global in PHP 7+?


问:
Intel Fortran Composer XE code not running on AMD Ryzen Processor
I compile my scientific Fortran code using the following:

Windows 10,

Microsoft Visual Studio 2010,

Intel Visual Fortran Composer XE 2011.

(Newer versions are not available to me)

My new computer is using an AMD Ryzen 1700 processor. When i try to run compiled Release MKL or Release MKL - OpenMP i get the following error:

Fatal Error: This program was not built to run on the processor in
  your system. The allowed processors are: Intel(R) processors with
  SSE4.2 and POPCNT instructions support.

Any ideas on how to make this work? I was really looking forward to using my 8 cores (at an affordable price) to run the code. Best regards

答: Ok i found the solution. Right click your project -> Properties -> Select "All configurations". In configuration properties -> Fortran -> Code generation -> Intel processor-specific optimization -> Set this to "The processor performing the compilation (/QxHost)"</p>


问:
how to get the days and exact minutes,exact hours from two dates in javascript?
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

```<code>var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}
</code>```

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance

答:
Using momentjs, you can :

Parse your input string using moment(String, String)

Parse your input string using moment.utc

Get difference using diff() function

Create a duration from the difference value

Use duration days(), hours(), minutes() to get your result

Here a live sample:

var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.days() + ' days ' + dur.hours() + ' hour ' + dur.minutes() + ' minutes');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

If you want you can use moment-duration-format plug-in to get the same result using format() method on duration. Here a working sample:

var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.format('d [day] h [hour] m [minutes]'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script></code>```

Body:
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance

Body:
Using momentjs, you can :

Parse your input string using moment(String, String)

Parse your input string using moment.utc

Get difference using diff() function

Create a duration from the difference value

Use duration days(), hours(), minutes() to get your result

Here a live sample:

var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.days() + ' days ' + dur.hours() + ' hour ' + dur.minutes() + ' minutes');

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

If you want you can use moment-duration-format plug-in to get the same result using format() method on duration. Here a working sample:

var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.format('d [day] h [hour] m [minutes]'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>


问:
How can I rename a database column in a Ruby on Rails migration?
I wrongly named a column hased_password instead of hashed_password.

How do I update the database schema, using migration to rename this column?

答:
```<code> def change
    rename_column :table_name, :old_column_name, :new_column_name
  end
</code>```

ContentLicense: CC BY-SA 4.0


问:
Ruby - producing a combination from two arrays *produces headache*
What I'm trying to do is take an array of service names and apply a service response of either true of false to each.

Basically I'm getting an xml with a set of booleans for each of the services checked.  So for this example they all came back as true.

I put them into an array using Nokogiri like so:

```<code>doc = Nokogiri::XML.parse(xml)
service_state = doc.css("HeartBeat Status").map(&:text)
</code>```

This results in an array with 3 ["true"] items.

What I need to is apply each of them sequentially with an array I have in the code.

```<code>name = ['svc1', 'svc2', 'svc3']
</code>```

To do this I used the following code:

```<code>status = [] ; service_state.each {|n| name.each {|l| status << [l,n]}}
status.each {|state| print state.to_s + "\n"}
</code>```

This does what I want... sort of...

I do get an output of:

["svc1", "true"]
["svc2", "true"]
["svc3", "true"]

However, it repeats all the possible combinations.
When applying this to the actual array I have a total of 13 services that have a response 17 times so I end up with an array with 221 items.

Question: How do I do what I'm doing now but without repeating for each item in both arrays?

Thanks!

ContentLicense: CC BY-SA 2.5

Body:
What I'm trying to do is take an array of service names and apply a service response of either true of false to each.

Basically I'm getting an xml with a set of booleans for each of the services checked.  So for this example they all came back as true.

I put them into an array using Nokogiri like so:

doc = Nokogiri::XML.parse(xml)
service_state = doc.css("HeartBeat Status").map(&:text)

This results in an array with 3 ["true"] items.

What I need to is apply each of them sequentially with an array I have in the code.

name = ['svc1', 'svc2', 'svc3']

To do this I used the following code:

status = [] ; service_state.each {|n| name.each {|l| status << [l,n]}}
status.each {|state| print state.to_s + "\n"}

This does what I want... sort of...

I do get an output of:

["svc1", "true"]
["svc2", "true"]
["svc3", "true"]

However, it repeats all the possible combinations.
When applying this to the actual array I have a total of 13 services that have a response 17 times so I end up with an array with 221 items.

Question: How do I do what I'm doing now but without repeating for each item in both arrays?

Thanks!

Body: name.zip service_state


问:
Execution failed app:processDebugResources Android Studio
I'm using bitbucket so I can work with other developer but it seems that we can't get it to work flawlessly. I got this error after pulling the changes from him:</p>

```<code>Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    E:\Program Files (x86)\Android\android-sdk\build-tools\19.0.0\aapt.exe package -f --no-crunch -I E:\Program Files (x86)\Android\android-sdk\platforms\android-19\android.jar -M E:\Documents\smart-my-job1\app\build\manifests\debug\AndroidManifest.xml -S E:\Documents\smart-my-job1\app\build\res\all\debug -A E:\Documents\smart-my-job1\app\build\assets\debug -m -J E:\Documents\smart-my-job1\app\build\source\r\debug -F E:\Documents\smart-my-job1\app\build\libs\app-debug.ap_ --debug-mode --custom-package com.smartmyjob
Error Code:
    -1073741819
</code>```

答: Run gradle with --stacktrace option to see more information, what's wrong.

Body:
I'm using bitbucket so I can work with other developer but it seems that we can't get it to work flawlessly. I got this error after pulling the changes from him:

Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    E:\Program Files (x86)\Android\android-sdk\build-tools\19.0.0\aapt.exe package -f --no-crunch -I E:\Program Files (x86)\Android\android-sdk\platforms\android-19\android.jar -M E:\Documents\smart-my-job1\app\build\manifests\debug\AndroidManifest.xml -S E:\Documents\smart-my-job1\app\build\res\all\debug -A E:\Documents\smart-my-job1\app\build\assets\debug -m -J E:\Documents\smart-my-job1\app\build\source\r\debug -F E:\Documents\smart-my-job1\app\build\libs\app-debug.ap_ --debug-mode --custom-package com.smartmyjob
Error Code:
    -1073741819


问:
JavaScript scope (recursion) -- argument value overwritten by return value without explicit declaration
My first solution to an in order tree traversal worked off of the return value of the recursive function calls:

```<code>BST.prototype.inOrder = function(node, array){
   if(!node){ return []; }
   if(!array){ array = []; }

   return this.inOrder(node.left).concat([node.val], this.inOrder(node.right))

}
</code>```

But then I saw that it can be also solved with the code below, and I am confused as to how the 'array' value is being persisted..

```<code>BST.prototype.inOrder = function(node, array){
  if(!node){ return []; }
  if(!array){ array = []; }
  this.inOrder(node.left, array);
  array.push(node.val);
  this.inOrder(node.right, array)
  return array
}
</code>```

When the first recursive function call returns, is it overwriting the value of array within the scope of that function? Why is it doing that?

答:
This is an overloaded function that would be called without a second argument in the first call, and in that case the variable is initialised with an empty array. A better way to write this might be</p>

```<code>BST.prototype.appendInOrder = function(node, array) {
  if (!node) return;
  this.appendInOrder(node.left, array);
  array.push(node.val);
  this.appendInOrder(node.right, array);
}
BST.prototype.inOrder = function(node) {
  var array = [];
  this.appendInOrder(node, array);
  return array;
}
</code>```

Body:
My first solution to an in order tree traversal worked off of the return value of the recursive function calls:

BST.prototype.inOrder = function(node, array){
   if(!node){ return []; }
   if(!array){ array = []; }

   return this.inOrder(node.left).concat([node.val], this.inOrder(node.right))

}

But then I saw that it can be also solved with the code below, and I am confused as to how the 'array' value is being persisted..

BST.prototype.inOrder = function(node, array){
  if(!node){ return []; }
  if(!array){ array = []; }
  this.inOrder(node.left, array);
  array.push(node.val);
  this.inOrder(node.right, array)
  return array
}

When the first recursive function call returns, is it overwriting the value of array within the scope of that function? Why is it doing that?

Body:
This is an overloaded function that would be called without a second argument in the first call, and in that case the variable is initialised with an empty array. A better way to write this might be

BST.prototype.appendInOrder = function(node, array) {
  if (!node) return;
  this.appendInOrder(node.left, array);
  array.push(node.val);
  this.appendInOrder(node.right, array);
}
BST.prototype.inOrder = function(node) {
  var array = [];
  this.appendInOrder(node, array);
  return array;
}


问:
Fetch Json Field value using Values in Django
I have a JSON field in my model and by using values option, I would like to get the key value present in the JSON field.

Assume my JSON field value is:

```<code>{"key1":"value1","key2":"value2"}

MyClass.objects.values("field1","field2","JSON Key")
</code>```

Let JSON Key be "Key1"

Expected O/P:

```<code> [{field1:Value1,field2:value2,Key1:value1}]
</code>```

答:
I have written a custom manager function in ActiveQuerySet which accepts a list of fields and give get the particular field information from the object.

I have written the script for simple json structure..but where as u can change the way of processing json according to requirement.

The ActiveQuerySet class is as below.

```<code>class ActiveQuerySet(models.QuerySet):
    def custom_values(self,*args,**kwargs):
        model_fields = self.model._meta.get_fields()
        model = [str(i.name) for i in model_fields]
        json_fields = [str(i.name) for i in model_fields if i.get_internal_type() == 'JSONField']

        responses = []
        for one in self:
            one_value = {}
            for i in args[0]:

                if i in model: # search if field is in normal model
                    one_value[i]=str(getattr(one,i))
                else:
                    for jf in json_fields: #get all json fields in model
                        try:
                            json_value = eval(getattr(one,jf)) #eval to json or dict format if required
                        except:
                            json_value = getattr(one,jf)
                        json_keys = json_value.keys() #get the keys from json data stored
                        if i in json_keys:#check if key is present
                            one_value[i] = json_value[i]
            responses.append(one_value)
        return responses

MyModel.objects.all().custom_values(['field1','field2','key(which is present in JOSN field)'])
</code>```

Assume my json data is stored as

```<code>{"cluster": "Mulchond", "2962": "2016-12-13", "2963": "1", "2964": "4", "2965": "0", "2966": "0", "2967": "0", "2968": "0.0318", "2969": "0.0705", "2970": "", "2971": "", "2972": "", "2973": "17.256", "2974": "48.8351", "2975": "142", "2976": "783", "2977": "276", "2978": "0.05237", "2979": "70", "2980": "0.05237", "2981": "", "2982": "", "2983": "", "2984": "142", "2985": "32", "2986": "", "2987": "20.773551", "2988": "73.649422"}
</code>```

from this I want to get value of key '2988', My Query be like

```<code>MyModel.objects.filter().custom_values(['id','2988'])
</code>```

o/p :

```<code>[{'2987': '20.730995', 'id': '66302'},
 {'2987': '20.766556', 'id': '66303'},
 {'2987': '20.773551', 'id': '66304'}]
</code>```

where 'id is generated by Django and '2987' is one key which is present in JSON Field

Body:
I have a JSON field in my model and by using values option, I would like to get the key value present in the JSON field.

Assume my JSON field value is:

{"key1":"value1","key2":"value2"}

MyClass.objects.values("field1","field2","JSON Key")

Let JSON Key be "Key1"

Expected O/P:

 [{field1:Value1,field2:value2,Key1:value1}]

Body:
I have written a custom manager function in ActiveQuerySet which accepts a list of fields and give get the particular field information from the object.

I have written the script for simple json structure..but where as u can change the way of processing json according to requirement.

The ActiveQuerySet class is as below.

class ActiveQuerySet(models.QuerySet):
    def custom_values(self,*args,**kwargs):
        model_fields = self.model._meta.get_fields()
        model = [str(i.name) for i in model_fields]
        json_fields = [str(i.name) for i in model_fields if i.get_internal_type() == 'JSONField']

        responses = []
        for one in self:
            one_value = {}
            for i in args[0]:

                if i in model: # search if field is in normal model
                    one_value[i]=str(getattr(one,i))
                else:
                    for jf in json_fields: #get all json fields in model
                        try:
                            json_value = eval(getattr(one,jf)) #eval to json or dict format if required
                        except:
                            json_value = getattr(one,jf)
                        json_keys = json_value.keys() #get the keys from json data stored
                        if i in json_keys:#check if key is present
                            one_value[i] = json_value[i]
            responses.append(one_value)
        return responses

MyModel.objects.all().custom_values(['field1','field2','key(which is present in JOSN field)'])

Assume my json data is stored as

{"cluster": "Mulchond", "2962": "2016-12-13", "2963": "1", "2964": "4", "2965": "0", "2966": "0", "2967": "0", "2968": "0.0318", "2969": "0.0705", "2970": "", "2971": "", "2972": "", "2973": "17.256", "2974": "48.8351", "2975": "142", "2976": "783", "2977": "276", "2978": "0.05237", "2979": "70", "2980": "0.05237", "2981": "", "2982": "", "2983": "", "2984": "142", "2985": "32", "2986": "", "2987": "20.773551", "2988": "73.649422"}

from this I want to get value of key '2988', My Query be like

MyModel.objects.filter().custom_values(['id','2988'])

o/p :

[{'2987': '20.730995', 'id': '66302'},
 {'2987': '20.766556', 'id': '66303'},
 {'2987': '20.773551', 'id': '66304'}]

where 'id is generated by Django and '2987' is one key which is present in JSON Field


问:
Calculate a group index across multiple columns of a data frame in R
What is the most efficient way to calculate a group index (group identifier) across multiple columns in a data frame  or data.table in R?

For example, in the data frame below, there are six unique combinations of columns A and B.

```<code>DF <- data.frame(a = rep(1:2,6), b = sort(letters[1:3]))

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

I'd like to add column 'index' with a group identifier, like the one produced by this (obviously inefficient method for large data frames):

```<code>DF$index <- with(DF, as.numeric(factor(paste0(a, b))))

> DF
   a b index
1  1 a     1
2  2 b     5
3  1 c     3
4  2 a     4
5  1 b     2
6  2 c     6
7  1 a     1
8  2 b     5
9  1 c     3
10 2 a     4
11 1 b     2
12 2 c     6
</code>```

What's the fastest way to do this with very large data frames?

答:
In base R, you can use interaction, which is quite a bit faster than the paste method, although the data.table method is faster still.

```<code>DF$index <- as.integer(interaction(DF))
</code>```

This returns the desired result

```<code>DF
   a b index
1  1 a     1
2  2 b     4
3  1 c     5
4  2 a     2
5  1 b     3
6  2 c     6
7  1 a     1
8  2 b     4
9  1 c     5
10 2 a     2
11 1 b     3
12 2 c     6
</code>```

timings

Here are some timings on a larger dataset:

```<code>### set up
# 60K observations
DF <- data.frame(a = rep(1:2,60000), b = letters[1:20])
# make a data table copy
library(data.table)
DT <- data.table(DF)

library(microbenchmark)
microbenchmark(paste=with(DF, as.numeric(factor(paste0(a, b)))),
               interaction=as.integer(interaction(DF)),
               grp=DT[,group :=.GRP,by = .(a,b)])
Unit: milliseconds
        expr       min        lq      mean    median        uq      max neval cld
       paste 38.664541 41.100587 46.315671 42.030301 42.903709 91.32412   100   c
 interaction  4.203244  5.788548  9.927459  6.141646  6.943635 55.15564   100  b
         grp  1.771617  1.897632  2.772984  2.138828  2.218371 49.41399   100 a
</code>```

Body:
What is the most efficient way to calculate a group index (group identifier) across multiple columns in a data frame  or data.table in R?

For example, in the data frame below, there are six unique combinations of columns A and B.

DF <- data.frame(a = rep(1:2,6), b = sort(letters[1:3]))

> DF
   a b
1  1 a
2  2 b
3  1 c
4  2 a
5  1 b
6  2 c
7  1 a
8  2 b
9  1 c
10 2 a
11 1 b
12 2 c

I'd like to add column 'index' with a group identifier, like the one produced by this (obviously inefficient method for large data frames):

DF$index <- with(DF, as.numeric(factor(paste0(a, b))))

> DF
   a b index
1  1 a     1
2  2 b     5
3  1 c     3
4  2 a     4
5  1 b     2
6  2 c     6
7  1 a     1
8  2 b     5
9  1 c     3
10 2 a     4
11 1 b     2
12 2 c     6

What's the fastest way to do this with very large data frames?

Body:
In base R, you can use interaction, which is quite a bit faster than the paste method, although the data.table method is faster still.

DF$index <- as.integer(interaction(DF))

This returns the desired result

DF
   a b index
1  1 a     1
2  2 b     4
3  1 c     5
4  2 a     2
5  1 b     3
6  2 c     6
7  1 a     1
8  2 b     4
9  1 c     5
10 2 a     2
11 1 b     3
12 2 c     6

timings

Here are some timings on a larger dataset:

### set up
# 60K observations
DF <- data.frame(a = rep(1:2,60000), b = letters[1:20])
# make a data table copy
library(data.table)
DT <- data.table(DF)

library(microbenchmark)
microbenchmark(paste=with(DF, as.numeric(factor(paste0(a, b)))),
               interaction=as.integer(interaction(DF)),
               grp=DT[,group :=.GRP,by = .(a,b)])
Unit: milliseconds
        expr       min        lq      mean    median        uq      max neval cld
       paste 38.664541 41.100587 46.315671 42.030301 42.903709 91.32412   100   c
 interaction  4.203244  5.788548  9.927459  6.141646  6.943635 55.15564   100  b
         grp  1.771617  1.897632  2.772984  2.138828  2.218371 49.41399   100 a


问:
Spark on YARN: execute driver without worker
Running Spark on YARN, cluster mode.

3 data nodes with YARN

YARN => 32 vCores, 32 GB RAM

I am submitting Spark program like this:

```<code>spark-submit \
    --class com.blablacar.insights.etl.SparkETL \
    --name ${JOB_NAME} \
    --master yarn \
    --num-executors 1 \
    --deploy-mode cluster \
    --driver-memory 512m \
    --driver-cores 1 \
    --executor-memory 2g \
    --executor-cores 20 \
    toto.jar json
</code>```

I can see 2 jobs are running fine on 2 nodes. But I can see also 2 other job with just a driver container !

Is it possible to not run driver if there no resource for worker?

答:
Actually, there is a setting to limit resources to "Application Master" (in case of Spark, this is the driver):

```<code>yarn.scheduler.capacity.maximum-am-resource-percent
</code>```

From http://maprdocs.mapr.com/home/AdministratorGuide/Hadoop2.xCapacityScheduler-RunningPendingApps.html:

Maximum percent of resources in the cluster that can be used to run
  application masters - controls the number of concurrent active
  applications.

This way, YARN will not take full resources for Spark drivers, and keep resources for workers. Youpi !

Body:
Running Spark on YARN, cluster mode.

3 data nodes with YARN

YARN => 32 vCores, 32 GB RAM

I am submitting Spark program like this:

spark-submit \
    --class com.blablacar.insights.etl.SparkETL \
    --name ${JOB_NAME} \
    --master yarn \
    --num-executors 1 \
    --deploy-mode cluster \
    --driver-memory 512m \
    --driver-cores 1 \
    --executor-memory 2g \
    --executor-cores 20 \
    toto.jar json

I can see 2 jobs are running fine on 2 nodes. But I can see also 2 other job with just a driver container !

Is it possible to not run driver if there no resource for worker?

Body:
Actually, there is a setting to limit resources to "Application Master" (in case of Spark, this is the driver):

yarn.scheduler.capacity.maximum-am-resource-percent

From http://maprdocs.mapr.com/home/AdministratorGuide/Hadoop2.xCapacityScheduler-RunningPendingApps.html:

Maximum percent of resources in the cluster that can be used to run
  application masters - controls the number of concurrent active
  applications.

This way, YARN will not take full resources for Spark drivers, and keep resources for workers. Youpi !


问:
Join that returns all left table records when the right table is connected through a linking table
I am having some trouble trying to figure out how to write a SQL statement that will return the same amount of records found in the left table. The only way to get data from the right table is to use a 3rd table.

For instance, I have three tables, Sites, Addresses, and Affiliations. Many affiliations can be active for a site (Contact, Mailing Address, Owner, and Official), but there may not be a person or address associated with the affiliation. IE. A site may have a Contact person but no Official designated, or a site may not yet have a Mailing Address assigned.
The Sites (left table) and Affiliations are linked by a common ID.
Sites.ID = Affiliations.Site_ID

The Affiliations and Addresses (right table) are linked by a common Address Record ID
Affiliations.Address_RID = Addresses.RID

The query I have is

```<code>SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A,
    AFFILIATIONS B,
    ADDRESSES C
WHERE A.ID = B.SITE_ID
    AND B.ADDRESS_RID = C.RID
    AND B.AFFILIATION_TYPE = 'MAILING ADDRESS'
ORDER BY A.ID
</code>```

The results I get if I query the sites table alone is 1580 site records. Running the above query for mailing addresses I get 1386 records.  I need to return all 1580 records with nulls for records where mailing addresses are absent.
I'm doing something wrong, but I am not seeing it.

Comments?

Thanks

答:
You should try left join and if it will not work then remove where condition.</p>

```<code>SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A,
left join AFFILIATIONS B  on A.ID = B.SITE_ID
left join ADDRESSES C on B.ADDRESS_RID = C.RID
    WHERE
     B.AFFILIATION_TYPE = 'MAILING ADDRESS'
ORDER BY A.ID
</code>```

Body:
I am having some trouble trying to figure out how to write a SQL statement that will return the same amount of records found in the left table. The only way to get data from the right table is to use a 3rd table.

For instance, I have three tables, Sites, Addresses, and Affiliations. Many affiliations can be active for a site (Contact, Mailing Address, Owner, and Official), but there may not be a person or address associated with the affiliation. IE. A site may have a Contact person but no Official designated, or a site may not yet have a Mailing Address assigned.
The Sites (left table) and Affiliations are linked by a common ID.
Sites.ID = Affiliations.Site_ID

The Affiliations and Addresses (right table) are linked by a common Address Record ID
Affiliations.Address_RID = Addresses.RID

The query I have is

SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A,
    AFFILIATIONS B,
    ADDRESSES C
WHERE A.ID = B.SITE_ID
    AND B.ADDRESS_RID = C.RID
    AND B.AFFILIATION_TYPE = 'MAILING ADDRESS'
ORDER BY A.ID

The results I get if I query the sites table alone is 1580 site records. Running the above query for mailing addresses I get 1386 records.  I need to return all 1580 records with nulls for records where mailing addresses are absent.
I'm doing something wrong, but I am not seeing it.

Comments?

Thanks

Body:
You should try left join and if it will not work then remove where condition.

SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A,
left join AFFILIATIONS B  on A.ID = B.SITE_ID
left join ADDRESSES C on B.ADDRESS_RID = C.RID
    WHERE
     B.AFFILIATION_TYPE = 'MAILING ADDRESS'
ORDER BY A.ID


问:
How can I define a Swift Protocol so that the implementation can be a property _or_ a method?
Here's what I want to do:

```<code>import Foundation
import UIKit

protocol PlayableMediaItem {
    func title() -> String
    func albumArt() -> UIImage
    func audioFileURL() -> URL
}

struct AudioTrack : Codable, PlayableMediaItem {
    var title: String
    var desc:String
    var albumArtDemoName:String
    var audioDemoFilename:String

    func albumArt() -> UIImage {
        let image = UIImage(named: albumArtDemoName)
        return image!
    }

    func audioFileURL() -> URL {
        return Bundle.main.url(forResource: audioDemoFilename, withExtension: "mp3")!
    }
}
</code>```

But I get the error that AudioTrack doesn't conform to the PlayableMediaItem protocol because the title property isn't a method, it's a property.

How can I set this up so that title, albumArt, etc. can be implemented as either properties or methods, so long as they give me back the right type?

Some of my implementations of this might just be properties, while others are computed.

答:
Not entirely sure what you need, since it depends but maybe try making them variables instead of funcs and then on classes that implement the protocol you can manipulate their get/set of the var.</p>

```<code>struct Square {
 var edge: Double = 0
 var area: Double {
get {
  return edge * edge
}
set {
  edge = sqrt(newValue)
}}
</code>```

Body:
Here's what I want to do:

import Foundation
import UIKit

protocol PlayableMediaItem {
    func title() -> String
    func albumArt() -> UIImage
    func audioFileURL() -> URL
}

struct AudioTrack : Codable, PlayableMediaItem {
    var title: String
    var desc:String
    var albumArtDemoName:String
    var audioDemoFilename:String

    func albumArt() -> UIImage {
        let image = UIImage(named: albumArtDemoName)
        return image!
    }

    func audioFileURL() -> URL {
        return Bundle.main.url(forResource: audioDemoFilename, withExtension: "mp3")!
    }
}

But I get the error that AudioTrack doesn't conform to the PlayableMediaItem protocol because the title property isn't a method, it's a property.

How can I set this up so that title, albumArt, etc. can be implemented as either properties or methods, so long as they give me back the right type?

Some of my implementations of this might just be properties, while others are computed.

Body:
Not entirely sure what you need, since it depends but maybe try making them variables instead of funcs and then on classes that implement the protocol you can manipulate their get/set of the var.

struct Square {
 var edge: Double = 0
 var area: Double {
get {
  return edge * edge
}
set {
  edge = sqrt(newValue)
}}


问:
org.xml.sax.SAXNotRecognizedException: Feature 'http://javax.xml.XMLConstants/feature/secure-processing' is not recognized
Hi in our project we are using XJC ant task for xsd2schema generation after that we are compiling the src files and grouping them into a schema jar.
the classpath we have for that is:

```<code>jaxb-ri-2.2.6 - jaxb-impl.jar,jaxb-api.jar,jaxb-xjc.jar
</code>```

This ant task is working fine in eclipse and jar got created , but it is throwing errors in unix environment.

The Error is:

java.lang.IllegalStateException: org.xml.sax.SAXNotRecognizedException: Feature 'http://javax.xml.XMLConstants/feature/secure-processing' is not recognized.

That error gone , when we added "xercesImpl-2.9.1.jar" to unix build classpath, but the jar generated was different from the jar that generated using eclipse.

eclipse build jar- it has only few classes
unix build jar- it has impl folder and so many classes

In both the cases the jaxb jars were the same.
Please help me with this issue....Please...................

答:
If you have Maven, add this to pom.xml</p>

```<code><dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
</dependency>
</code>```

Body:
Hi in our project we are using XJC ant task for xsd2schema generation after that we are compiling the src files and grouping them into a schema jar.
the classpath we have for that is:

jaxb-ri-2.2.6 - jaxb-impl.jar,jaxb-api.jar,jaxb-xjc.jar

This ant task is working fine in eclipse and jar got created , but it is throwing errors in unix environment.

The Error is:

java.lang.IllegalStateException: org.xml.sax.SAXNotRecognizedException: Feature 'http://javax.xml.XMLConstants/feature/secure-processing' is not recognized.

That error gone , when we added "xercesImpl-2.9.1.jar" to unix build classpath, but the jar generated was different from the jar that generated using eclipse.

eclipse build jar- it has only few classes
unix build jar- it has impl folder and so many classes

In both the cases the jaxb jars were the same.
Please help me with this issue....Please...................

Body:
If you have Maven, add this to pom.xml

<dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
</dependency>


问:
Hide Function in Google Apps Script Stops Working
I have a Google sheet that tracks "open issues" for our departments. I have added a script where on open it hides rows based on the first character in column N being an "x". This allows us to only view open items. The script seems to have a mind of its own. It works, then it stops. Then it works again. Any insight on why this is occurring would be appreciated.

Script Below:

```<code>function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Team 1 Unresolved");
  var maxRows = sheet.getMaxRows();

  //get data from clumn N
  var data = sheet.getRange('N:N').getValues();

  //iterate over all rows
  for(var i=0; i< data.length; i++){
    if(data[i] == 'x'){
      sheet.hideRows(i+1);
    }
  }
}
</code>```

Sheet Link Below:
https://docs.google.com/spreadsheets/d/1N7va6hF14ecchCkrc8nMFGC-bVc1ZBlP7im7qhAKZAM/edit#gid=0

答:
I feel it had something to do with the first char.
I would try to skip that part if possible.
this appears to be more accurate and working better...

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1");

  //get data from clumn N
  var data = sheet.getRange('N:N').getValues();

  //iterate over all rows
  for(var i=0; i< data.length; i++){
    if(data[i] == 'x'){
      sheet.hideRows(i+1);
    }
  }
}```

Body:
I have a Google sheet that tracks "open issues" for our departments. I have added a script where on open it hides rows based on the first character in column N being an "x". This allows us to only view open items. The script seems to have a mind of its own. It works, then it stops. Then it works again. Any insight on why this is occurring would be appreciated.

Script Below:

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Team 1 Unresolved");
  var maxRows = sheet.getMaxRows();

  //get data from clumn N
  var data = sheet.getRange('N:N').getValues();

  //iterate over all rows
  for(var i=0; i< data.length; i++){
    if(data[i] == 'x'){
      sheet.hideRows(i+1);
    }
  }
}

Sheet Link Below:
https://docs.google.com/spreadsheets/d/1N7va6hF14ecchCkrc8nMFGC-bVc1ZBlP7im7qhAKZAM/edit#gid=0


问:
How to filter on most recent value for specific column
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

```<code>Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC
</code>```

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

```<code>    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40
</code>```

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.

答:
other solution :</p>

```<code>with maxi as
(
 select [tableName], max([batchNum]) MaxNum TableNames
 group by [tableName]
)
Select f1.*
FROM TableNames f1
inner join maxi f2 on f1.tableName=f2.tableName and f1.batchNum=f2.MaxNum
</code>```

Body:
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.

Body:
other solution :

with maxi as
(
 select [tableName], max([batchNum]) MaxNum TableNames
 group by [tableName]
)
Select f1.*
FROM TableNames f1
inner join maxi f2 on f1.tableName=f2.tableName and f1.batchNum=f2.MaxNum


问:
Code Igniter SQL Injection and query structure (dynamic where clause with same column name)
I'm trying to make sure that my code igniter query is safe from sql injection but I can't really find an example illustrating this or explaining if these parameters I'm using are escaped/bound.

```<code>$inputArray = [1,2,3,4,5];
$this->db_name->select('a_column');
$this->db_name->from('a_table');
foreach ($inputArray as $item) {
    $this->db_name->or_where('id',$item);
}

$query = $this->db_name->get();
</code>```

Most importantly, are all the items that I'm checking for as a matching id from my input array bound/escaped to protect from SQL injection? If not, how should I structure it in a query like this?

I don't really care for how I've structured this query any guidance on this would be appreciated. In fact I don't really like it at all but I need to make sure I'm using query building with code igniter in such a way that it will be easily switchable to a different database system if for whatever reason I wasn't using the one I'm using now (eg. mysql to oracle) - I also realize that a where clause that simple would probably never differ and is universal if I were to just put it in with regular SQL but I'm trying to learn best practices for CI when other scenarios come up and things might be more complicated or differ between database systems and syntax.

Any help is much appreciated! Thanks.

答:
Yes it's protected. From the CodeIgniter QueryBuilder documentation

Beyond simplicity, a major benefit to using the Query Builder features is that it allows you to create database independent applications, since the query syntax is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system.

Body:
I'm trying to make sure that my code igniter query is safe from sql injection but I can't really find an example illustrating this or explaining if these parameters I'm using are escaped/bound.

$inputArray = [1,2,3,4,5];
$this->db_name->select('a_column');
$this->db_name->from('a_table');
foreach ($inputArray as $item) {
    $this->db_name->or_where('id',$item);
}

$query = $this->db_name->get();

Most importantly, are all the items that I'm checking for as a matching id from my input array bound/escaped to protect from SQL injection? If not, how should I structure it in a query like this?

I don't really care for how I've structured this query any guidance on this would be appreciated. In fact I don't really like it at all but I need to make sure I'm using query building with code igniter in such a way that it will be easily switchable to a different database system if for whatever reason I wasn't using the one I'm using now (eg. mysql to oracle) - I also realize that a where clause that simple would probably never differ and is universal if I were to just put it in with regular SQL but I'm trying to learn best practices for CI when other scenarios come up and things might be more complicated or differ between database systems and syntax.

Any help is much appreciated! Thanks.


问:
iPhone UITableView, UINavigationView and Interface Builder
I'm building an app which will eventually have many tabs, tables, maps etc, however, I want to build something very simple which is turning out to be a major headache.

I'm using XCode 3.2.5 and Interface Builder to build a simple app that will show a navigation bar, and a table view.

I know there are templates but I want to build each unit so that I can later (hopefully) link it to a tab bar controller.

What I can't seem to get to happen is getting the navigation controller and table view to work together properly when built from interface builder.

I have specific reasons for building in IB over just code - some of it a learning exercise so I can help others, some because the code has to be handed off in a way that can be easily followed.

So, I've got two sets of files, mainwindow.[h/m/xib] and categories.[h/m/xib].

mainwindows.m's main code looks like this:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchoptions {
  quickCats = [[categories alloc] initWithNibName:@"categories" bundle:nil];
  [window addSubView: quickCats.view];
  [self.window makeKeyAndVisible];
  return YES;
}
</code>```

I've declared 'quickCats' in the mainwindow.h file as a reference to the class 'categories'.

My categories.[h/m/xib] is a stock UIViewController with subclassing of UITableViewController, I've only changed the number of sections, number of cells and cells methods to appropriately return data.

The interface declaration is literally:

```<code>@interface categories : UITableViewController {
}
</code>```

When I first fire this up, it loads and displays the table so I know that works.

What I'm having problems with is getting a navigation controller to work as well.

I drop a UINavigationController on the objects panel and then drag the UITableViewController to within it so that on the IB screen it looks like i've got a nav controller and table at the same time.

Now, no matter how I wire it up, I cannot get the nav controller to fire the table view.

I have to connect the Files Owner's view to the TableView or my app crashes with an uncaught exception saying I didn't return a UITableView.

What have I missed?

I know from reading code examples that you usually add a navigation controller using initWithRootViewController but how do I hook all this up with IB?

答:
Ok, I can't find a definitive answer to this, it seems that although IB will allow you to place a UINavigationController control and then add a UITableViewController as a child of it, you can only get initWithNibName:bundle: to initiate one or the other.  I've tried everything I can think of but it just won't let me wire it up so that one initialises the other when the NIB loads.

The solution to this is to create a UIViewController project file which subclasses UITableViewController and then you create a class called MyTableWithNavigation as a sublcass of UIViewController, expose one method called 'init' and in that you programatically create a UINavigationController passing initWithRootViewController: and then return the resulting object to the AppDelegate that called it.

This achieves the same end result but is a hybrid of IB/XCode which will have to do for now.

Basically the code in my init looks like:

```<code>- (id)init {
if (self = [super init]) {
    mainTable = [[QuickCategories_iPhone_Table alloc] initWithNibName:@"QuickCategories_iPhone" bundle:nil ];
    mainNav = [[UINavigationController alloc] initWithRootViewController: mainTable ];
    return mainNav;
} else {
    return nil;
}
}
</code>```

This way, all the nice calls like self.navigationItem.title are working as well.

I'd still like to know how i'm supposed to do it the other way though.

Body:
I'm building an app which will eventually have many tabs, tables, maps etc, however, I want to build something very simple which is turning out to be a major headache.

I'm using XCode 3.2.5 and Interface Builder to build a simple app that will show a navigation bar, and a table view.

I know there are templates but I want to build each unit so that I can later (hopefully) link it to a tab bar controller.

What I can't seem to get to happen is getting the navigation controller and table view to work together properly when built from interface builder.

I have specific reasons for building in IB over just code - some of it a learning exercise so I can help others, some because the code has to be handed off in a way that can be easily followed.

So, I've got two sets of files, mainwindow.[h/m/xib] and categories.[h/m/xib].

mainwindows.m's main code looks like this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchoptions {
  quickCats = [[categories alloc] initWithNibName:@"categories" bundle:nil];
  [window addSubView: quickCats.view];
  [self.window makeKeyAndVisible];
  return YES;
}

I've declared 'quickCats' in the mainwindow.h file as a reference to the class 'categories'.

My categories.[h/m/xib] is a stock UIViewController with subclassing of UITableViewController, I've only changed the number of sections, number of cells and cells methods to appropriately return data.

The interface declaration is literally:

@interface categories : UITableViewController {
}

When I first fire this up, it loads and displays the table so I know that works.

What I'm having problems with is getting a navigation controller to work as well.

I drop a UINavigationController on the objects panel and then drag the UITableViewController to within it so that on the IB screen it looks like i've got a nav controller and table at the same time.

Now, no matter how I wire it up, I cannot get the nav controller to fire the table view.

I have to connect the Files Owner's view to the TableView or my app crashes with an uncaught exception saying I didn't return a UITableView.

What have I missed?

I know from reading code examples that you usually add a navigation controller using initWithRootViewController but how do I hook all this up with IB?

Body:
Ok, I can't find a definitive answer to this, it seems that although IB will allow you to place a UINavigationController control and then add a UITableViewController as a child of it, you can only get initWithNibName:bundle: to initiate one or the other.  I've tried everything I can think of but it just won't let me wire it up so that one initialises the other when the NIB loads.

The solution to this is to create a UIViewController project file which subclasses UITableViewController and then you create a class called MyTableWithNavigation as a sublcass of UIViewController, expose one method called 'init' and in that you programatically create a UINavigationController passing initWithRootViewController: and then return the resulting object to the AppDelegate that called it.

This achieves the same end result but is a hybrid of IB/XCode which will have to do for now.

Basically the code in my init looks like:

- (id)init {
if (self = [super init]) {
    mainTable = [[QuickCategories_iPhone_Table alloc] initWithNibName:@"QuickCategories_iPhone" bundle:nil ];
    mainNav = [[UINavigationController alloc] initWithRootViewController: mainTable ];
    return mainNav;
} else {
    return nil;
}
}

This way, all the nice calls like self.navigationItem.title are working as well.

I'd still like to know how i'm supposed to do it the other way though.


问:
why My resized Image size is not what I want and expect?
I want image width and height 250 while image is resizing into 250X150? but why?
Here is my controller code

```<code>$config =  array(
          'image_library'   => 'gd2',
          'source_image'    =>  $data['full_path'],
          'maintain_ratio'  =>  TRUE,
          'width'           =>  250,
          'height'          =>  250,
        );
        $this->image_lib->clear();
        $this->image_lib->initialize($config);
        $this->image_lib->resize();
</code>```

答:
thanks  Adrianopolis, it works.
I changed This code

```<code>$config =  array(
      'image_library'   => 'gd2',
      'source_image'    =>  $data['full_path'],
      'maintain_ratio'  =>  TRUE,
      'width'           =>  250,
      'height'          =>  250,
    );
    $this->image_lib->clear();
    $this->image_lib->initialize($config);
    $this->image_lib->resize();
</code>```

Into

```<code>$config =  array(
      'image_library'   => 'gd2',
      'source_image'    =>  $data['full_path'],
      'maintain_ratio'  =>  FALSE,
      'width'           =>  250,
      'height'          =>  250,
    );
    $this->image_lib->clear();
    $this->image_lib->initialize($config);
    $this->image_lib->resize();
</code>```

Body:
I want image width and height 250 while image is resizing into 250X150? but why?
Here is my controller code

$config =  array(
          'image_library'   => 'gd2',
          'source_image'    =>  $data['full_path'],
          'maintain_ratio'  =>  TRUE,
          'width'           =>  250,
          'height'          =>  250,
        );
        $this->image_lib->clear();
        $this->image_lib->initialize($config);
        $this->image_lib->resize();

Body:
thanks  Adrianopolis, it works.
I changed This code

$config =  array(
      'image_library'   => 'gd2',
      'source_image'    =>  $data['full_path'],
      'maintain_ratio'  =>  TRUE,
      'width'           =>  250,
      'height'          =>  250,
    );
    $this->image_lib->clear();
    $this->image_lib->initialize($config);
    $this->image_lib->resize();

Into

$config =  array(
      'image_library'   => 'gd2',
      'source_image'    =>  $data['full_path'],
      'maintain_ratio'  =>  FALSE,
      'width'           =>  250,
      'height'          =>  250,
    );
    $this->image_lib->clear();
    $this->image_lib->initialize($config);
    $this->image_lib->resize();


问:
How to use methods to set a property in the default constructor in F#
I am trying to write a constructor that suppose to call method defined in the class and assign result to the member. In C# it would be something like:

```<code>public class Test
{
    public int Value { get; private set;}

    private static int SomeLogic(int a, int b)
    {
        return a + b;
    }

    public Test(int a, int b)
    {
        this.Value = SomeLogic(a,b);
    }
}
</code>```

But I have no idea how to do that it F#.

答:
```<code>type Test private (constructorParam) =

    let mutable value = constructorParam

    member this.Value
      with get()                = value
       and private set newValue = value <- newValue

    static member SomeLogic(a,b) = a+b

    new(a,b) = Test(Test.SomeLogic(a,b))

let a = Test(1,2)
</code>```

Note that the single param constructor is private. Consequently let a = Test(1) is not possible, as desired.

Maybe there's no need for a setter or a mutable field. If so...

```<code>type Test2 private (constructorParam) =

     let value = constructorParam

     member this.Value with get() = value

     static member SomeLogic(a,b) = a+b

     new(a,b) = Test2(Test.SomeLogic(a,b))

 let b = Test2(1,2)
</code>```

references:

properties

classes

Body:
I am trying to write a constructor that suppose to call method defined in the class and assign result to the member. In C# it would be something like:

public class Test
{
    public int Value { get; private set;}

    private static int SomeLogic(int a, int b)
    {
        return a + b;
    }

    public Test(int a, int b)
    {
        this.Value = SomeLogic(a,b);
    }
}

But I have no idea how to do that it F#.

Body:
type Test private (constructorParam) =

    let mutable value = constructorParam

    member this.Value
      with get()                = value
       and private set newValue = value <- newValue

    static member SomeLogic(a,b) = a+b

    new(a,b) = Test(Test.SomeLogic(a,b))

let a = Test(1,2)

Note that the single param constructor is private. Consequently let a = Test(1) is not possible, as desired.

Maybe there's no need for a setter or a mutable field. If so...

type Test2 private (constructorParam) =

     let value = constructorParam

     member this.Value with get() = value

     static member SomeLogic(a,b) = a+b

     new(a,b) = Test2(Test.SomeLogic(a,b))

 let b = Test2(1,2)

references:

properties

classes


问:
Delphi IRC Component
Are there any fully functional IRC Components out there for Delphi? I have looked at the TIDIRC component (Indy 10), and it is missing too many things to be usable for me.

I basically have an application and I would like to add in the IRC functionality to it, to automatically connect to an IRC server and join 2 channels and allow the participants to interact on those 2 channels. I initially set up the a test application using TIDIRC, and connected to the IRC server, and joined a channel. Unfortunately IDIRC would not return the names of the participants of the channel, and it kept generating 200 errors, and a fair amount of the data returned from the server is being cut. I need to get this up and running quickly and I do not have the time to sit and debug the Indy component and build everything into it, would be nice but not possible at this time.

答:
TIdIRC is actually not free of some smaller Bugs but Indy10 supports you also as a big InternetFramework - you can get Indy10 TIdIRC right running up to Win10:

https://www.youtube.com/watch?v=70O4gkLy_ZY&t=140s

Elmar Baumann

Title: Delphi IRC Component


问:
Centering div inside a background image div
I have a div that has a image that will stretch with the browser. I have a div that's a logo when the wrapper div(image) is shrunk the div should stay centered but its off to one side . I used left:42%; to center. It its fine when big just when u shrink it goes off to one side..

Do I have any other options besides left:42%;? margin: 0 auto; did not work...

@font-face {
    font-family: myFirstFont;
    src: url(jewler/Allura-Regular.otf);
}
body {
 b111ackground-color: #000000;
}

 h1 {
    color: maroon;
    margin-left: 40px;
}
  h2 {
    color: maroon;
    margin-left: 40px;
}
 h3 {
    color: maroon;
    margin-left: 40px;
}

#wrapper{
 width:80%;
 height:80%;
  margin: 0 auto;
 ;
 }
* {
  margin: 0;
  padding: 0;
}

#logo{

margin: 0 auto;
border: px solid green;
color:#FFF;
position:absolute;
margin-left:10px;
margin-top:10px;
display:table;
width:21%;

max-width:250px;
height:122px;
top:0%;
left:42%;

}

#info{
 margin: 0 auto;
 border: 1px solid green;
color:#FFF;
display:table;
width:250px;
height:250px;
border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> | Coming Soon!</title>

</head>

<body>
<div id="wrapper">
<IMG SRC="jewler/BackGround.png" width="100%" height="100%"/>

<div id="logo">
<IMG SRC="jewler/logo.png" width="100%" height="100%"/>
</div>

<div id="info">
Coming Soon
Adress:
Phone:
E-mail:
</div>

</div>

</body>
</html></code>```

答:
Use left: 50% with transform: translateX(-50%) to center an absolutely positioned element horizontally. Also remove the left margin so it's truly centered.

@font-face {
    font-family: myFirstFont;
    src: url(jewler/Allura-Regular.otf);
}
body {
 b111ackground-color: #000000;
}

 h1 {
    color: maroon;
    margin-left: 40px;
}
  h2 {
    color: maroon;
    margin-left: 40px;
}
 h3 {
    color: maroon;
    margin-left: 40px;
}

#wrapper{
 width:80%;
 height:80%;
  margin: 0 auto;
 ;
 }
* {
  margin: 0;
  padding: 0;
}

#logo{

margin: 0 auto;
border: px solid green;
color:#FFF;
position:absolute;
/* margin-left:10px; */
margin-top:10px;
display:table;
width:21%;

max-width:250px;
height:122px;
top:0%;
left:50%;
transform: translateX(-50%);

}

#info{
 margin: 0 auto;
 border: 1px solid green;
color:#FFF;
display:table;
width:250px;
height:250px;
border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> | Coming Soon!</title>

</head>

<body>
<div id="wrapper">
<IMG SRC="jewler/BackGround.png" width="100%" height="100%"/>

<div id="logo">
<IMG SRC="jewler/logo.png" width="100%" height="100%"/>
</div>

<div id="info">
Coming Soon
Adress:
Phone:
E-mail:
</div>

</div>

</body>
</html></code>```

Body:
I have a div that has a image that will stretch with the browser. I have a div that's a logo when the wrapper div(image) is shrunk the div should stay centered but its off to one side . I used left:42%; to center. It its fine when big just when u shrink it goes off to one side..

Do I have any other options besides left:42%;? margin: 0 auto; did not work...

@font-face {
    font-family: myFirstFont;
    src: url(jewler/Allura-Regular.otf);
}
body {
 b111ackground-color: #000000;
}

 h1 {
    color: maroon;
    margin-left: 40px;
}
  h2 {
    color: maroon;
    margin-left: 40px;
}
 h3 {
    color: maroon;
    margin-left: 40px;
}

#wrapper{
 width:80%;
 height:80%;
  margin: 0 auto;
 ;
 }
* {
  margin: 0;
  padding: 0;
}

#logo{

margin: 0 auto;
border: px solid green;
color:#FFF;
position:absolute;
margin-left:10px;
margin-top:10px;
display:table;
width:21%;

max-width:250px;
height:122px;
top:0%;
left:42%;

}

#info{
 margin: 0 auto;
 border: 1px solid green;
color:#FFF;
display:table;
width:250px;
height:250px;
border: 1px solid red;
}

<!doctype html>

<meta charset="utf-8">
<title> | Coming Soon!</title>

Coming Soon
Adress:
Phone:
E-mail:

Body:
Use left: 50% with transform: translateX(-50%) to center an absolutely positioned element horizontally. Also remove the left margin so it's truly centered.

@font-face {
    font-family: myFirstFont;
    src: url(jewler/Allura-Regular.otf);
}
body {
 b111ackground-color: #000000;
}

 h1 {
    color: maroon;
    margin-left: 40px;
}
  h2 {
    color: maroon;
    margin-left: 40px;
}
 h3 {
    color: maroon;
    margin-left: 40px;
}

#wrapper{
 width:80%;
 height:80%;
  margin: 0 auto;
 ;
 }
* {
  margin: 0;
  padding: 0;
}

#logo{

margin: 0 auto;
border: px solid green;
color:#FFF;
position:absolute;
/* margin-left:10px; */
margin-top:10px;
display:table;
width:21%;

max-width:250px;
height:122px;
top:0%;
left:50%;
transform: translateX(-50%);

}

#info{
 margin: 0 auto;
 border: 1px solid green;
color:#FFF;
display:table;
width:250px;
height:250px;
border: 1px solid red;
}

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> | Coming Soon!</title>

</head>

<body>
<div id="wrapper">
<IMG SRC="jewler/BackGround.png" width="100%" height="100%"/>

<div id="logo">
<IMG SRC="jewler/logo.png" width="100%" height="100%"/>
</div>

<div id="info">
Coming Soon
Adress:
Phone:
E-mail:
</div>

</div>

</body>
</html>


问:
Laravel HTTPS routes
today I decided to move my website to HTTPS. Early my website work on HTTP.

My problem is in misunderstood how Laravel pass HTTP and https in helpers function route('name')

I change my website URL in config/app.php to https://www.domain.name and I think, this solution helps me. But I got a strange result.

In php artisan tinker if I pass route('ROUTE.NAME') I got right link https://www.domain.name/route/path
but in blade template I got http://www.domain.name/route/path

The same situation with \URL::to('/')

Maybe someone can explain to me why this happened?

答:
The @dekts response is correct, but the "right" place to put this kind of stuff is the "app/Providers/AppServiceProvider.php" on the boot method.

```<code>//file: app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\URL;

class AppServiceProvider extends ServiceProvider {

    public function boot()
    {
        if (app()->environment('remote')) {
            URL::forceScheme('https');
        }
    }

    ...
}
</code>```

You can also add a new variable on your ".env" file, something like:

```<code>#file: .env
FORCE_HTTPS=true
</code>```

And change the condition to

```<code>//file: app/Providers/AppServiceProvider.php
public function boot()
{
    if(env('FORCE_HTTPS',false)) { // Default value should be false for local server
        URL::forceScheme('https');
    }
}
</code>```

Hope this help.

edit: corrected forceSchema to forceScheme as noted on the comments. ;)

Title: Laravel HTTPS routes

Body:
The @dekts response is correct, but the "right" place to put this kind of stuff is the "app/Providers/AppServiceProvider.php" on the boot method.

//file: app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\URL;

class AppServiceProvider extends ServiceProvider {

    public function boot()
    {
        if (app()->environment('remote')) {
            URL::forceScheme('https');
        }
    }

    ...
}

You can also add a new variable on your ".env" file, something like:

#file: .env
FORCE_HTTPS=true

And change the condition to

//file: app/Providers/AppServiceProvider.php
public function boot()
{
    if(env('FORCE_HTTPS',false)) { // Default value should be false for local server
        URL::forceScheme('https');
    }
}

Hope this help.

edit: corrected forceSchema to forceScheme as noted on the comments. ;)


问:
Why does my loop use 100% CPU and never end?
I have this method:

```<code>    private delegate void watcherReader(StreamReader sr);
    private void watchProc(StreamReader sr) {
        while (true) {
            string line = sr.ReadLine();
            while (line != null) {
                if (stop) {
                    return;
                }
                //Console.WriteLine(line);
                line = stripColors(line);
                txtOut.Text += line + "\n";

                line = sr.ReadLine();
            }
        }
    }
</code>```

And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.

Here's some more code of the project if you need it.

```<code>    [DllImport("User32")]
    private static extern int ShowWindow(int hwnd, int nCmdShow);   //this will allow me to hide a window

    public ConsoleForm(Process p) {
        this.p = p;
        p.Start();
        ShowWindow((int)p.MainWindowHandle, 0);   //0 means to hide the window.

        this.inStream = p.StandardInput;
        this.outStream = p.StandardOutput;
        this.errorStream = p.StandardError;

        InitializeComponent();

        wr = new watcherReader(watchProc);
        wr.BeginInvoke(this.outStream, null, null);
        wr.BeginInvoke(this.errorStream, null, null);
    }

    public void start(string[] folders, string serverPath) {

        this.inStream.WriteLine("chdir C:\\cygwin\\bin");
        this.inStream.WriteLine("bash --login -i");
        this.inStream.WriteLine("");
    }

    //code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
    //to make the textbox autoscroll I don't understand what it does, but it works.
    #region autoscroll
    [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    const int WM_VSCROLL = 277;
    const int SB_BOTTOM = 7;

    private void txtOut_TextChanged(object sender, EventArgs e) {
        IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
        IntPtr ptrLparam = new IntPtr(0);
        SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
    }
    #endregion

    private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
        this.stop = true;
        try {
            this.p.Kill();
        } catch (InvalidOperationException) {
            return;
        }
    }
</code>```

Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.

Any suggestions on how to fix this?

答:
Having while(true) with no sleep in the loop will cause 100% CPU usage.

You need to sleep for some amount of time or break out of the loop at some point so the CPU can do something else.

At the very least you should be doing something along the lines of:

```<code>while (sr.Peek() >= 0)
{
    Console.WriteLine(sr.ReadLine());
    Thread.Sleep(0);
}
</code>```

OwnerDisplayName: Malfist

Body:
I have this method:

    private delegate void watcherReader(StreamReader sr);
    private void watchProc(StreamReader sr) {
        while (true) {
            string line = sr.ReadLine();
            while (line != null) {
                if (stop) {
                    return;
                }
                //Console.WriteLine(line);
                line = stripColors(line);
                txtOut.Text += line + "\n";

                line = sr.ReadLine();
            }
        }
    }

And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.

Here's some more code of the project if you need it.

    [DllImport("User32")]
    private static extern int ShowWindow(int hwnd, int nCmdShow);   //this will allow me to hide a window

    public ConsoleForm(Process p) {
        this.p = p;
        p.Start();
        ShowWindow((int)p.MainWindowHandle, 0);   //0 means to hide the window.

        this.inStream = p.StandardInput;
        this.outStream = p.StandardOutput;
        this.errorStream = p.StandardError;

        InitializeComponent();

        wr = new watcherReader(watchProc);
        wr.BeginInvoke(this.outStream, null, null);
        wr.BeginInvoke(this.errorStream, null, null);
    }

    public void start(string[] folders, string serverPath) {

        this.inStream.WriteLine("chdir C:\\cygwin\\bin");
        this.inStream.WriteLine("bash --login -i");
        this.inStream.WriteLine("");
    }

    //code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
    //to make the textbox autoscroll I don't understand what it does, but it works.
    #region autoscroll
    [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    const int WM_VSCROLL = 277;
    const int SB_BOTTOM = 7;

    private void txtOut_TextChanged(object sender, EventArgs e) {
        IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
        IntPtr ptrLparam = new IntPtr(0);
        SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
    }
    #endregion

    private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
        this.stop = true;
        try {
            this.p.Kill();
        } catch (InvalidOperationException) {
            return;
        }
    }

Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.

Any suggestions on how to fix this?

LastEditorDisplayName: Rich B

Body:
Having while(true) with no sleep in the loop will cause 100% CPU usage.

You need to sleep for some amount of time or break out of the loop at some point so the CPU can do something else.

At the very least you should be doing something along the lines of:

while (sr.Peek() >= 0)
{
    Console.WriteLine(sr.ReadLine());
    Thread.Sleep(0);
}

OwnerDisplayName: Rich B


问:
react native java.lang.ExceptionInInitializerError
I'm trying to make React Native work on an emulator. I'm using Genymotion it works fine, the virtual machines opens without any problem and i have added the SDK to its configuration.

I have the emulator opened and working but when i run react-native run-android i get the following error.

```<code>Starting JS server...
Building and installing the app on the device (cd android && ./gradlew installDebug)...

FAILURE: Build failed with an exception.

What went wrong:
java.lang.ExceptionInInitializerError (no error message)

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html
</code>```

I've found out that a possible problem is that i was runnig java 9 and React Native requires java 8 instead (https://github.com/facebook/react-native/issues/11755)

So i did the following

I tried changing the version by doing this
sudo update-java-alternatives --set java-8-oracle

then checking the version with
javac -version

it returns javac 1.8.0_131

If i run the app again i still get the error from above

But when i echo $PATH i see that it is still referencing the java 9 folder

```<code>echo $PATH /home/andrei/.nvm/versions/node/v7.5.0/bin:/home/andrei/bin:/home/andrei/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-9-oracle/bin:/usr/lib/jvm/java-9-oracle/db/bin:/home/andrei/Android/Sdk
</code>```

How do I change that or fix this problem?

答:
To fix this problem

But when i echo $PATH i see that it is still referencing the java 9 folder
    echo $PATH /home/andrei/.nvm/versions/node/v7.5.0/bin:/home/andrei/bin:/home/andrei/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-9-oracle/bin:/usr/lib/jvm/java-9-oracle/db/bin:/home/andrei/Android/Sdk

in The Home directory open .profile

add the following

PATH="$PATH:~/usr/lib/jvm/java-8-openjdk-amd64/bin"

in this case i'm adding the path to java 8 folder because that is the one i need to use The React-Native according it its specification
https://facebook.github.io/react-native/docs/getting-started.html

after setting the PATH you need to make it available inside the terminal you are executing the react-native app by using the following script

source .~/.profile

this should get you passed the initial problem with the java 9

Body:
I'm trying to make React Native work on an emulator. I'm using Genymotion it works fine, the virtual machines opens without any problem and i have added the SDK to its configuration.

I have the emulator opened and working but when i run react-native run-android i get the following error.

Starting JS server...
Building and installing the app on the device (cd android && ./gradlew installDebug)...

FAILURE: Build failed with an exception.

What went wrong:
java.lang.ExceptionInInitializerError (no error message)

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

I've found out that a possible problem is that i was runnig java 9 and React Native requires java 8 instead (https://github.com/facebook/react-native/issues/11755)

So i did the following

I tried changing the version by doing this
sudo update-java-alternatives --set java-8-oracle

then checking the version with
javac -version

it returns javac 1.8.0_131

If i run the app again i still get the error from above

But when i echo $PATH i see that it is still referencing the java 9 folder

echo $PATH /home/andrei/.nvm/versions/node/v7.5.0/bin:/home/andrei/bin:/home/andrei/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-9-oracle/bin:/usr/lib/jvm/java-9-oracle/db/bin:/home/andrei/Android/Sdk

How do I change that or fix this problem?