问:
ES6 Promises in express app not properly resolving data
I'm writing an a async function with ES6 promises, that 1) saves the query parameters for a user 2) fetches data from mongodb using mongoose, 3) manipulates the json into a DSL, 4) and queries another db with it.
mongoose": "^4.7.7"

```<code>//myController.js
const myQuery = require('../models/myQuery_model');
require('mongoose').Promise = global.Promise
const uuidV4 = require('uuid/v4');

exports.saveNewQuery = function(req, res, next) {

  const rawQuery = req.body;
  const queryToStore = new myQuery(rawQuery);
  const uid = uuidV4();
  const queryToStore.uid = uid

  queryToStore.save().then(() => {
      fetchQueryFromMongo(uid);

    }).then((storedQuery) => {
      compileQueryToString(storedQuery);

    }).then((queryString) => {
      fetchResultsFromOtherDb(queryString);

    }).then((results) => {
      res.json({ results });

    }).catch((error) => {

      console.log(error)
    })
  }
</code>```

Currently I'm not able to resolve the response from mongodb step 2. Still, the controllter goes on to compileQueryToString rather than catch the error from fetchQueryFromMongo

```<code>// fetchQueryFromMongo.js
const myQuery = require('../models/myQuery');
require('mongoose').Promise = global.Promise

module.exports = (uid) => {
  return new Promise(
    (resolve, reject) => {
      myQuery.find({ uid }).then((err, res) => {

        if (err) {
          reject(err);
        }
        console.log('response success!')
        resolve(res);
      });
    }
  );
};
</code>```

I'm new to promises so any tips / suggestions would be appreciated!

答:
Make sure to return a value from your then handlers. The code below does this by using the concise body form of arrow functions.

```<code>queryToStore.save()
  .then(()          => fetchQueryFromMongo(uid))
  .then(storedQuery => compileQueryToString(storedQuery))
  .then(queryString => fetchResultsFromOtherDb(queryString))
  .then(results     => res.json({ results }))
  .catch(console.log);
</code>```

Body:
I'm writing an a async function with ES6 promises, that 1) saves the query parameters for a user 2) fetches data from mongodb using mongoose, 3) manipulates the json into a DSL, 4) and queries another db with it.
mongoose": "^4.7.7"

//myController.js
const myQuery = require('../models/myQuery_model');
require('mongoose').Promise = global.Promise
const uuidV4 = require('uuid/v4');

exports.saveNewQuery = function(req, res, next) {

  const rawQuery = req.body;
  const queryToStore = new myQuery(rawQuery);
  const uid = uuidV4();
  const queryToStore.uid = uid

  queryToStore.save().then(() => {
      fetchQueryFromMongo(uid);

    }).then((storedQuery) => {
      compileQueryToString(storedQuery);

    }).then((queryString) => {
      fetchResultsFromOtherDb(queryString);

    }).then((results) => {
      res.json({ results });

    }).catch((error) => {

      console.log(error)
    })
  }

Currently I'm not able to resolve the response from mongodb step 2. Still, the controllter goes on to compileQueryToString rather than catch the error from fetchQueryFromMongo

// fetchQueryFromMongo.js
const myQuery = require('../models/myQuery');
require('mongoose').Promise = global.Promise

module.exports = (uid) => {
  return new Promise(
    (resolve, reject) => {
      myQuery.find({ uid }).then((err, res) => {

        if (err) {
          reject(err);
        }
        console.log('response success!')
        resolve(res);
      });
    }
  );
};

I'm new to promises so any tips / suggestions would be appreciated!

Body:
Make sure to return a value from your then handlers. The code below does this by using the concise body form of arrow functions.

queryToStore.save()
  .then(()          => fetchQueryFromMongo(uid))
  .then(storedQuery => compileQueryToString(storedQuery))
  .then(queryString => fetchResultsFromOtherDb(queryString))
  .then(results     => res.json({ results }))
  .catch(console.log);


来源: stackexchange

问:
Optional html class in twig template
I have a simple reusable twig (generic.html.twig) template which look like:

```<code><ul>
    {% for item in list %}
        <li>
            ...
        </li>
    {% endfor %}
</ul>
</code>```

I use it many times in my code like this:

```<code>{% include "@Toto/generic.html.twig" with {"list": toto} %}
</code>```

My problem is that I sometimes want to include a CSS class on the
 generated by my twig template. So sometimes I would like for it to render like this:

```<code><ul class="myclass">
</code>```

while other times I'd like for it to render without the class, like this:

```<code><ul>
</code>```

How do I implement optional classes in my twig template?

答:
I prefer the use of defined</p>

```<code><ul{% if ulClass is defined %} class="{{ ulClass }}"{% endif %}>
    {% for item in list %}
        <li>
            ...
        </li>
    {% endfor %}
</ul>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Optional html class in twig template

Body:
I have a simple reusable twig (generic.html.twig) template which look like:

    {% for item in list %}

            ...

    {% endfor %}

I use it many times in my code like this:

{% include "@Toto/generic.html.twig" with {"list": toto} %}

My problem is that I sometimes want to include a CSS class on the
 generated by my twig template. So sometimes I would like for it to render like this:

while other times I'd like for it to render without the class, like this:

How do I implement optional classes in my twig template?

Body:
I prefer the use of defined

<ul{% if ulClass is defined %} class="{{ ulClass }}"{% endif %}>
    {% for item in list %}
        <li>
            ...
        </li>
    {% endfor %}
</ul>


问:
Using SystemJS/jspm to load async, es5 modules in production
I want to be able to asynchronously load dependencies using System.import(), but without having to transpile ES6 to ES5 during production runtime. I want these modules to be transpiled into separate, ES5 modules that are fetched only when needed. I don't want them to be a part of the main bundle.

Dev Workflow

The modules are effectively loading during my production build which is actually worrisome because I don't want to include any dependencies that allow for transpilation.

I have a workflow where I'm using jspm bundle and jspm unbundle to toggle between development and production configurations. In my development environment, I'm including the following scripts:

```<code><script src="jspm_packages/system.js"></script>
<script src="config.js"></script>

<script>
    System.import('src/main');
</script>
</code>```

Production Workflow

In production, I'm using jspm bundle --inject to inject the bundles option into System.config. This effectively loads only the necessary files:

```<code>system.js
config.js
main.bundle.js
</code>```

When I try to load a module asynchronously with System.import() during production, it loads fine, which means that transpilation is happening in the browser during production.

Questions

I can easily build each of my modules into AMD, but how can I still
asynchronously and separately fetch them using System.import()?

I also want to make sure to include as little browser overhead as
possible, which means not including any scripts that perform
transpilation. Is there a way to include system.js that does not
have transpile capabilities?

答:
Answer 1

System.import() is used for loading modules. Modules are essential .js files that export something such as a function or an Object or a Class.

If you organise your code into separate files then you can load them either in the head of another file using ..

```<code>import * as YM from 'YourModuleFile';
</code>```

this would make YM accessible in the entire file.

Or if you want YM loaded on a button click instead ..

```<code>element.onclick = function() {
    System.import('YourModuleFile').then(function(YM) {
        // YM accessible here
    })
}
</code>```

So the important thing becomes organising your code well inside files / modules.

You then might use an npm task runner such as gulp to compress the files, etc.

Of course, you will need to enter some mappings inside your systemjs.config.js file such as ..

```<code>'YourModuleFile': '/path/to/your/module/file.js'
</code>```

So that SystemJS can find it.

Answer 2

JSPM has tranpile capabilities, I'm not sure SystemJS does.

Ensure JSPM (or your tool of choice) transpiles your files. Then point SystemJS to the transpiled files.

Body:
I want to be able to asynchronously load dependencies using System.import(), but without having to transpile ES6 to ES5 during production runtime. I want these modules to be transpiled into separate, ES5 modules that are fetched only when needed. I don't want them to be a part of the main bundle.

Dev Workflow

The modules are effectively loading during my production build which is actually worrisome because I don't want to include any dependencies that allow for transpilation.

I have a workflow where I'm using jspm bundle and jspm unbundle to toggle between development and production configurations. In my development environment, I'm including the following scripts:

Production Workflow

In production, I'm using jspm bundle --inject to inject the bundles option into System.config. This effectively loads only the necessary files:

system.js
config.js
main.bundle.js

When I try to load a module asynchronously with System.import() during production, it loads fine, which means that transpilation is happening in the browser during production.

Questions

I can easily build each of my modules into AMD, but how can I still
asynchronously and separately fetch them using System.import()?

I also want to make sure to include as little browser overhead as
possible, which means not including any scripts that perform
transpilation. Is there a way to include system.js that does not
have transpile capabilities?

Body:
Answer 1

System.import() is used for loading modules. Modules are essential .js files that export something such as a function or an Object or a Class.

If you organise your code into separate files then you can load them either in the head of another file using ..

import * as YM from 'YourModuleFile';

this would make YM accessible in the entire file.

Or if you want YM loaded on a button click instead ..

element.onclick = function() {
    System.import('YourModuleFile').then(function(YM) {
        // YM accessible here
    })
}

So the important thing becomes organising your code well inside files / modules.

You then might use an npm task runner such as gulp to compress the files, etc.

Of course, you will need to enter some mappings inside your systemjs.config.js file such as ..

'YourModuleFile': '/path/to/your/module/file.js'

So that SystemJS can find it.

Answer 2

JSPM has tranpile capabilities, I'm not sure SystemJS does.

Ensure JSPM (or your tool of choice) transpiles your files. Then point SystemJS to the transpiled files.


问:
QT cast a widget to a combobox
I have a table[][] of widgets and depending on a value that I have I'll instantiate that widget to a QLabel or to a QCombobox.

```<code>QWidget *tab[9][9];

if(modele->firstvalue(i,j) ==0) {
    tab[i][j]= new QComboBox();
    tab[i][j]->setStyleSheet("border: 1px solid red");
    ((QComboBox)tab[i][j]).addItem("Test");

}
else {
    tab[i][j] = new QLabel(QString::number(modele->firstvalue(i,j)));
}
</code>```

So in my widget after the execution I see all the comboboxes but not with the values (no items added)

PS:
It's about a sudoku game. If there are a lot multiple values then I create a combobox with all the possible values, else a QLabel with a single value.

答:
Instead of:

```<code>((QComboBox)tab[i][j]).addItem("Test");
</code>```

use:

```<code>((QComboBox*)tab[i][j]).addItem("Test");
</code>```

As your grid has pointers to widgets

Title: QT cast a widget to a combobox

Body:
I have a table[][] of widgets and depending on a value that I have I'll instantiate that widget to a QLabel or to a QCombobox.

QWidget *tab[9][9];

if(modele->firstvalue(i,j) ==0) {
    tab[i][j]= new QComboBox();
    tab[i][j]->setStyleSheet("border: 1px solid red");
    ((QComboBox)tab[i][j]).addItem("Test");

}
else {
    tab[i][j] = new QLabel(QString::number(modele->firstvalue(i,j)));
}

So in my widget after the execution I see all the comboboxes but not with the values (no items added)

PS:
It's about a sudoku game. If there are a lot multiple values then I create a combobox with all the possible values, else a QLabel with a single value.

Body:
Instead of:

((QComboBox)tab[i][j]).addItem("Test");

use:

((QComboBox*)tab[i][j]).addItem("Test");

As your grid has pointers to widgets


问:
Producing random float from negative to positive range?
I am trying to produce a random float within the range -50.0 and 50.0 inclusively, using rand(). I've looked everywhere for an answer but it deals with ints and % operator.</p>

答:
Try this:

rand() gives you a number between 0 and RAND_MAX

so divide by RAND_MAX to get a number between 0 and 1

you desire a range of 100 from -50 to 50, so multiply by 100.0

finally shift the center from 50 (between 0 and 100 per point 3) to zero by subtracting 50.0

ContentLicense: CC BY-SA 2.5


问:
Should the POSIX 'CLOCK_REALTIME' clock be referenced to the UTC epoch?
I'm using the POSIX clock_gettime(CLOCK_REALTIME, &curr_time) to get the current time of the CLOCK_REALTIME clock. I understand the difference between CLOCK_REALTIME and CLOCK_MONOTONIC. However, what I don't know is the epoch associated with CLOCK_REALTIME.

My first guess was that it would be the elapsed seconds/nanoseconds since the UTC epoch. However, the value that I'm getting is ~180000 seconds which is ~50 hours. Obviously not the time elapsed since the UTC epoch.

So my question: what is CLOCK_REALTIME referenced against? Reboot? Platform specfic? UTC and I'm just doing something wrong?

Thanks,

答:
CLOCK_REALTIME is tied to the Unix epoch ("UTC epoch" is the same thing but is not the correct way to name it.  It's just the Unix epoch in the UTC timezone).

Try this code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main(void)
{
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    printf("%ld\n", ts.tv_sec);
    exit(0);
}
</code>```

Body:
CLOCK_REALTIME is tied to the Unix epoch ("UTC epoch" is the same thing but is not the correct way to name it.  It's just the Unix epoch in the UTC timezone).

Try this code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main(void)
{
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    printf("%ld\n", ts.tv_sec);
    exit(0);
}


问:
Get Duplicates in List and Edit Item
I need to get any items in a list that already exist and edit BOTH items to include a duplicate property.

I've attempted to get duplicates by doing:

```<code>var duplicates = LIST.Select((t, i) => new { Index = i, Text = t }).GroupBy(g => g.Text.PROPERTYTOSEARCGBY).Where(g => g.Count() > 1);
</code>```

However this returns me the property that is duplicated when however I need to get index of both of the records so that I can edit them using:

```<code>LIST[index1].FlaggedData = true;
LIST[index2].FlaggedData = true;
etc...
</code>```

How can I get the index of BOTH duplicate or multiple records?

答:
You don't need the index.
It's enough to group as you did and select the item themselves.

```<code>var duplicates = LIST.GroupBy(t => t.PROPERTYTOSEARCGBY)
                     .Where(g => g.Count() > 1)
                     .SelectMany(t=>t);

foreach (var item in duplicates)
{
    item.FlaggedData = true;
}
</code>```

Or even shorter:

```<code>LIST.GroupBy(t => t.PROPERTYTOSEARCGBY)
    .Where(g => g.Count() > 1)
    .SelectMany(t=>t)
    .ToList()
    .ForEach(t=>t.FlaggedData = true);
</code>```

Title: Get Duplicates in List and Edit Item

Body:
I need to get any items in a list that already exist and edit BOTH items to include a duplicate property.

I've attempted to get duplicates by doing:

var duplicates = LIST.Select((t, i) => new { Index = i, Text = t }).GroupBy(g => g.Text.PROPERTYTOSEARCGBY).Where(g => g.Count() > 1);

However this returns me the property that is duplicated when however I need to get index of both of the records so that I can edit them using:

LIST[index1].FlaggedData = true;
LIST[index2].FlaggedData = true;
etc...

How can I get the index of BOTH duplicate or multiple records?

Body:
You don't need the index.
It's enough to group as you did and select the item themselves.

var duplicates = LIST.GroupBy(t => t.PROPERTYTOSEARCGBY)
                     .Where(g => g.Count() > 1)
                     .SelectMany(t=>t);

foreach (var item in duplicates)
{
    item.FlaggedData = true;
}

Or even shorter:

LIST.GroupBy(t => t.PROPERTYTOSEARCGBY)
    .Where(g => g.Count() > 1)
    .SelectMany(t=>t)
    .ToList()
    .ForEach(t=>t.FlaggedData = true);


问:
Finding appropriate debug symbols
I got the memory dump from another PC.
It is also an x64 machine, but the different version of Windows.
It is a dump of usual app work.
I took it to make sure that I have all required analyzing next dump (next dump will be with problem inside)

At first, I took DebugDiag Analysis tool and run it for this dump.
Here is the summary:

Sleep API is ok. Regarding "previous .net exceptions" I have no idea what is that.

After it I run the WinDbg. After loading Microsoft and my own symbols I run !analyze -v to make sure that I have all relevant symbols to work with dump.

After runing !analyze -v I got:

```<code>FAULTING_IP:
+0
00000000`00000000 ??              ???
EXCEPTION_RECORD:  ffffffffffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 0000000000000000
   ExceptionCode: 80000003 (Break instruction exception)
  ExceptionFlags: 00000000
NumberParameters: 0

CONTEXT:  0000000000000000 -- (.cxr 0x0;r)
rax=000007fef8150aa8 rbx=0000000000000000 rcx=000000000210e618
rdx=000000000210e801 rsi=00000000ffffffff rdi=00000000000001a4
rip=0000000076e7d9fa rsp=000000000058e558 rbp=0000000000000000
 r8=0000000001a5a404  r9=00000000ffffffff r10=000007fef7f304e0
r11=0000000000000206 r12=0000000000000000 r13=000000000066be80
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei pl zr na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!ZwWaitForSingleObject+0xa:
00000000`76e7d9fa c3              ret
FAULTING_THREAD:  00000000000012b8
DEFAULT_BUCKET_ID:  WRONG_SYMBOLS
PROCESS_NAME:  IPCapture.exe
ERROR_CODE: (NTSTATUS) 0x80000003 - {EXCEPTION}  Breakpoint  A breakpoint has been reached.
EXCEPTION_CODE: (HRESULT) 0x80000003 (2147483651) - One or more arguments are invalid
NTGLOBALFLAG:  0
APPLICATION_VERIFIER_FLAGS:  0
APP:  ipcapture.exe
ANALYSIS_VERSION: 6.3.9600.17336 (debuggers(dbg).150226-1500) amd64fre
MANAGED_STACK: !dumpstack -EE
No export dumpstack found
PRIMARY_PROBLEM_CLASS:  WRONG_SYMBOLS
BUGCHECK_STR:  APPLICATION_FAULT_WRONG_SYMBOLS
LAST_CONTROL_TRANSFER:  from 000007fefcde10dc to 0000000076e7d9fa

STACK_TEXT:
00000000`0058e558 000007fe`fcde10dc : 00000000`0058e928 00000000`0058e5c0 00000000`0195bfc8 00000000`561ad250 : ntdll!ZwWaitForSingleObject+0xa
00000000`0058e560 000007fe`fdd6affb : 00000000`ffffffff 000007fe`fdd6344c 00000000`00000000 00000000`000001a4 : KERNELBASE!WaitForSingleObjectEx+0x79
00000000`0058e600 000007fe`fdd69d61 : 00000000`0060b0d0 00000000`000001a4 00000000`00000000 00000000`00000000 : sechost!ScSendResponseReceiveControls+0x13b
00000000`0058e6f0 000007fe`fdd69c16 : 00000000`0058e858 00000000`00000000 00000000`00000000 000007fe`00000000 : sechost!ScDispatcherLoop+0x121
00000000`0058e800 000007fe`f904bec7 : 00000000`00611460 00000000`0066be80 00000000`00611460 00000000`00644d60 : sechost!StartServiceCtrlDispatcherW+0x14e
00000000`0058e850 000007fe`f72cf0a8 : 000007fe`f72dc8a0 000007fe`f72a64c8 00000000`447ecfa0 00000000`00000000 : mscorwks!DoNDirectCall__PatchGetThreadCall+0x7b
00000000`0058e8f0 000007fe`f72d1478 : 00000000`006548a0 00000000`00000000 00000000`006548b8 00000000`00000000 : System_ServiceProcess_ni+0x2f0a8
00000000`0058e9b0 000007ff`00180147 : 00000000`01962888 00000000`01962768 00000000`01962768 000007fe`f82e7680 : System_ServiceProcess_ni+0x31478
00000000`0058ea50 000007fe`f904c6a2 : 000007ff`00043430 000007fe`f8f58ae9 00000000`00000000 000007ff`00043420 : 0x000007ff`00180147
00000000`0058ea80 000007fe`f8f0ff03 : 00000000`00000000 000007fe`00000026 000007fe`f8e073e0 00000000`00000000 : mscorwks!CallDescrWorker+0x82
00000000`0058eac0 000007fe`f942a291 : 00000000`0058ebf8 00000000`00000000 00000000`00000001 00000000`00000000 : mscorwks!CallDescrWorkerWithHandler+0xd3
00000000`0058eb60 000007fe`f8eb3167 : 00000000`00000000 000007ff`00043420 00000000`00000000 00000000`0058f060 : mscorwks!MethodDesc::CallDescr+0x2b1
00000000`0058eda0 000007fe`f8e8f874 : 00000000`00000000 00000000`00000000 00000003`00380017 00000000`00000000 : mscorwks!ClassLoader::RunMain+0x22b
00000000`0058f000 000007fe`f9516aed : 00000000`0058f650 00000000`00000000 00000000`00629698 00000000`00000200 : mscorwks!Assembly::ExecuteMainMethod+0xbc
00000000`0058f2f0 000007fe`f8e825f7 : 00000000`00000000 00000000`00000000 00000000`00000000 000007fe`f8e6796e : mscorwks!SystemDomain::ExecuteMainMethod+0x47d
00000000`0058f8c0 000007fe`f8e9f610 : ffffffff`fffffffe 00000000`00000000 0000f563`00000000 00000000`00000000 : mscorwks!ExecuteEXE+0x47
00000000`0058f910 000007fe`f97672fd : ffffffff`ffffffff 00000000`00611460 00000000`00000000 00000000`0058f918 : mscorwks!CorExeMain+0xac
00000000`0058f970 000007fe`f9845b21 : 00000000`00000000 000007fe`f8e9f564 00000000`00000000 00000000`00000000 : mscoreei!CorExeMain+0xe0
00000000`0058f9c0 00000000`76c25a4d : 000007fe`f9760000 00000000`00000000 00000000`00000000 00000000`00000000 : mscoree!CorExeMain_Exported+0x57
00000000`0058f9f0 00000000`76e5b831 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : kernel32!BaseThreadInitThunk+0xd
00000000`0058fa20 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!RtlUserThreadStart+0x1d

STACK_COMMAND:  ~0s; .ecxr ; kb
FOLLOWUP_IP:
sechost!ScSendResponseReceiveControls+13b
000007fe`fdd6affb 85c0            test    eax,eax
SYMBOL_STACK_INDEX:  2
SYMBOL_NAME:  sechost!ScSendResponseReceiveControls+13b
FOLLOWUP_NAME:  MachineOwner
MODULE_NAME: sechost
IMAGE_NAME:  sechost.dll
DEBUG_FLR_IMAGE_TIMESTAMP:  55636728
FAILURE_BUCKET_ID:  WRONG_SYMBOLS_80000003_sechost.dll!ScSendResponseReceiveControls
BUCKET_ID:  X64_APPLICATION_FAULT_WRONG_SYMBOLS_sechost!ScSendResponseReceiveControls+13b
ANALYSIS_SOURCE:  UM
FAILURE_ID_HASH_STRING:  um:wrong_symbols_80000003_sechost.dll!scsendresponsereceivecontrols
FAILURE_ID_HASH:  {e6dbb060-e976-9c4d-c3ce-fc837a3c58a8}
Followup: MachineOwner
</code>```

As I understand from this output:

I have some problems with debug symbols. (Maybe it is related to
sechost.dll)

Analyze stuck at the very beginning (thread 0). So maybe I have some issue with analyzing at all (not problem this thread)

I see address instead of the human name of the method in DebugDiag.

Here is part of output for lmvm sechost

```<code>0:000> lmvm sechost
start             end                 module name
000007fe`fdd60000 000007fe`fdd7f000   sechost    (pdb symbols)
C:\ProgramData\dbg\sym\sechost.pdb\3824AD19AB6C47AA8870D6E371F1738B1\sechost.pdb

Loaded symbol image file: sechost.dll
Image path: C:\Windows\System32\sechost.dll
....
</code>```

Here is call stack of thread 0 from debugdiag:

The main question is how to understand which symbols I missed?

答:
Use a newer version of WinDbg

Thank you for providing the crash dump file. I could reproduce your issue with WinDbg 6.3.9600.17298 and 6.2.9200.16384.

In WinDbg 10.0.15003.1001, !analyze -v succeeded the first time I wrote you an email. Now that I try it again, it fails with

```<code>X64_BREAKPOINT_NOSOS_sechost!ScSendResponseReceiveControls+13b
</code>```

and that stays even if I download SOS and MSCorDACWks and let .cordll -lp point there. !dumpstack works when I enter it manually, but it seems not to work for !analyze for whatever reason.

Interpretation of the message

Your interpretation of the message is wrong.

The message is:

```<code>WRONG_SYMBOLS_80000003_sechost.dll!ScSendResponseReceiveControls
</code>```

This says:

the crash happened in sechost.dll

the exception code is an INT3 breakpoint (80000003)

some symbols are wrong, so don't blindly trust the information where it happened.

It does not say "Symbols of sechost.dll are wrong".

How is that possible? It may happen that there's a frame on the call stack (above the culprit) for which symbols are not available. In that case, WinDbg might not be able to interpret the stack correctly. It then might have found an incorrect culprit.

Title: Finding appropriate debug symbols

Body:
I got the memory dump from another PC.
It is also an x64 machine, but the different version of Windows.
It is a dump of usual app work.
I took it to make sure that I have all required analyzing next dump (next dump will be with problem inside)

At first, I took DebugDiag Analysis tool and run it for this dump.
Here is the summary:

Sleep API is ok. Regarding "previous .net exceptions" I have no idea what is that.

After it I run the WinDbg. After loading Microsoft and my own symbols I run !analyze -v to make sure that I have all relevant symbols to work with dump.

After runing !analyze -v I got:

FAULTING_IP:
+0
00000000`00000000 ??              ???
EXCEPTION_RECORD:  ffffffffffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 0000000000000000
   ExceptionCode: 80000003 (Break instruction exception)
  ExceptionFlags: 00000000
NumberParameters: 0

CONTEXT:  0000000000000000 -- (.cxr 0x0;r)
rax=000007fef8150aa8 rbx=0000000000000000 rcx=000000000210e618
rdx=000000000210e801 rsi=00000000ffffffff rdi=00000000000001a4
rip=0000000076e7d9fa rsp=000000000058e558 rbp=0000000000000000
 r8=0000000001a5a404  r9=00000000ffffffff r10=000007fef7f304e0
r11=0000000000000206 r12=0000000000000000 r13=000000000066be80
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei pl zr na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!ZwWaitForSingleObject+0xa:
00000000`76e7d9fa c3              ret
FAULTING_THREAD:  00000000000012b8
DEFAULT_BUCKET_ID:  WRONG_SYMBOLS
PROCESS_NAME:  IPCapture.exe
ERROR_CODE: (NTSTATUS) 0x80000003 - {EXCEPTION}  Breakpoint  A breakpoint has been reached.
EXCEPTION_CODE: (HRESULT) 0x80000003 (2147483651) - One or more arguments are invalid
NTGLOBALFLAG:  0
APPLICATION_VERIFIER_FLAGS:  0
APP:  ipcapture.exe
ANALYSIS_VERSION: 6.3.9600.17336 (debuggers(dbg).150226-1500) amd64fre
MANAGED_STACK: !dumpstack -EE
No export dumpstack found
PRIMARY_PROBLEM_CLASS:  WRONG_SYMBOLS
BUGCHECK_STR:  APPLICATION_FAULT_WRONG_SYMBOLS
LAST_CONTROL_TRANSFER:  from 000007fefcde10dc to 0000000076e7d9fa

STACK_TEXT:
00000000`0058e558 000007fe`fcde10dc : 00000000`0058e928 00000000`0058e5c0 00000000`0195bfc8 00000000`561ad250 : ntdll!ZwWaitForSingleObject+0xa
00000000`0058e560 000007fe`fdd6affb : 00000000`ffffffff 000007fe`fdd6344c 00000000`00000000 00000000`000001a4 : KERNELBASE!WaitForSingleObjectEx+0x79
00000000`0058e600 000007fe`fdd69d61 : 00000000`0060b0d0 00000000`000001a4 00000000`00000000 00000000`00000000 : sechost!ScSendResponseReceiveControls+0x13b
00000000`0058e6f0 000007fe`fdd69c16 : 00000000`0058e858 00000000`00000000 00000000`00000000 000007fe`00000000 : sechost!ScDispatcherLoop+0x121
00000000`0058e800 000007fe`f904bec7 : 00000000`00611460 00000000`0066be80 00000000`00611460 00000000`00644d60 : sechost!StartServiceCtrlDispatcherW+0x14e
00000000`0058e850 000007fe`f72cf0a8 : 000007fe`f72dc8a0 000007fe`f72a64c8 00000000`447ecfa0 00000000`00000000 : mscorwks!DoNDirectCall__PatchGetThreadCall+0x7b
00000000`0058e8f0 000007fe`f72d1478 : 00000000`006548a0 00000000`00000000 00000000`006548b8 00000000`00000000 : System_ServiceProcess_ni+0x2f0a8
00000000`0058e9b0 000007ff`00180147 : 00000000`01962888 00000000`01962768 00000000`01962768 000007fe`f82e7680 : System_ServiceProcess_ni+0x31478
00000000`0058ea50 000007fe`f904c6a2 : 000007ff`00043430 000007fe`f8f58ae9 00000000`00000000 000007ff`00043420 : 0x000007ff`00180147
00000000`0058ea80 000007fe`f8f0ff03 : 00000000`00000000 000007fe`00000026 000007fe`f8e073e0 00000000`00000000 : mscorwks!CallDescrWorker+0x82
00000000`0058eac0 000007fe`f942a291 : 00000000`0058ebf8 00000000`00000000 00000000`00000001 00000000`00000000 : mscorwks!CallDescrWorkerWithHandler+0xd3
00000000`0058eb60 000007fe`f8eb3167 : 00000000`00000000 000007ff`00043420 00000000`00000000 00000000`0058f060 : mscorwks!MethodDesc::CallDescr+0x2b1
00000000`0058eda0 000007fe`f8e8f874 : 00000000`00000000 00000000`00000000 00000003`00380017 00000000`00000000 : mscorwks!ClassLoader::RunMain+0x22b
00000000`0058f000 000007fe`f9516aed : 00000000`0058f650 00000000`00000000 00000000`00629698 00000000`00000200 : mscorwks!Assembly::ExecuteMainMethod+0xbc
00000000`0058f2f0 000007fe`f8e825f7 : 00000000`00000000 00000000`00000000 00000000`00000000 000007fe`f8e6796e : mscorwks!SystemDomain::ExecuteMainMethod+0x47d
00000000`0058f8c0 000007fe`f8e9f610 : ffffffff`fffffffe 00000000`00000000 0000f563`00000000 00000000`00000000 : mscorwks!ExecuteEXE+0x47
00000000`0058f910 000007fe`f97672fd : ffffffff`ffffffff 00000000`00611460 00000000`00000000 00000000`0058f918 : mscorwks!CorExeMain+0xac
00000000`0058f970 000007fe`f9845b21 : 00000000`00000000 000007fe`f8e9f564 00000000`00000000 00000000`00000000 : mscoreei!CorExeMain+0xe0
00000000`0058f9c0 00000000`76c25a4d : 000007fe`f9760000 00000000`00000000 00000000`00000000 00000000`00000000 : mscoree!CorExeMain_Exported+0x57
00000000`0058f9f0 00000000`76e5b831 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : kernel32!BaseThreadInitThunk+0xd
00000000`0058fa20 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!RtlUserThreadStart+0x1d

STACK_COMMAND:  ~0s; .ecxr ; kb
FOLLOWUP_IP:
sechost!ScSendResponseReceiveControls+13b
000007fe`fdd6affb 85c0            test    eax,eax
SYMBOL_STACK_INDEX:  2
SYMBOL_NAME:  sechost!ScSendResponseReceiveControls+13b
FOLLOWUP_NAME:  MachineOwner
MODULE_NAME: sechost
IMAGE_NAME:  sechost.dll
DEBUG_FLR_IMAGE_TIMESTAMP:  55636728
FAILURE_BUCKET_ID:  WRONG_SYMBOLS_80000003_sechost.dll!ScSendResponseReceiveControls
BUCKET_ID:  X64_APPLICATION_FAULT_WRONG_SYMBOLS_sechost!ScSendResponseReceiveControls+13b
ANALYSIS_SOURCE:  UM
FAILURE_ID_HASH_STRING:  um:wrong_symbols_80000003_sechost.dll!scsendresponsereceivecontrols
FAILURE_ID_HASH:  {e6dbb060-e976-9c4d-c3ce-fc837a3c58a8}
Followup: MachineOwner

As I understand from this output:

I have some problems with debug symbols. (Maybe it is related to
sechost.dll)

Analyze stuck at the very beginning (thread 0). So maybe I have some issue with analyzing at all (not problem this thread)

I see address instead of the human name of the method in DebugDiag.

Here is part of output for lmvm sechost

0:000> lmvm sechost
start             end                 module name
000007fe`fdd60000 000007fe`fdd7f000   sechost    (pdb symbols)
C:\ProgramData\dbg\sym\sechost.pdb\3824AD19AB6C47AA8870D6E371F1738B1\sechost.pdb

Loaded symbol image file: sechost.dll
Image path: C:\Windows\System32\sechost.dll
....

Here is call stack of thread 0 from debugdiag:

The main question is how to understand which symbols I missed?

Body:
Use a newer version of WinDbg

Thank you for providing the crash dump file. I could reproduce your issue with WinDbg 6.3.9600.17298 and 6.2.9200.16384.

In WinDbg 10.0.15003.1001, !analyze -v succeeded the first time I wrote you an email. Now that I try it again, it fails with

X64_BREAKPOINT_NOSOS_sechost!ScSendResponseReceiveControls+13b

and that stays even if I download SOS and MSCorDACWks and let .cordll -lp point there. !dumpstack works when I enter it manually, but it seems not to work for !analyze for whatever reason.

Interpretation of the message

Your interpretation of the message is wrong.

The message is:

WRONG_SYMBOLS_80000003_sechost.dll!ScSendResponseReceiveControls

This says:

the crash happened in sechost.dll

the exception code is an INT3 breakpoint (80000003)

some symbols are wrong, so don't blindly trust the information where it happened.

It does not say "Symbols of sechost.dll are wrong".

How is that possible? It may happen that there's a frame on the call stack (above the culprit) for which symbols are not available. In that case, WinDbg might not be able to interpret the stack correctly. It then might have found an incorrect culprit.


Title: Producing random float from negative to positive range?

Body: I am trying to produce a random float within the range -50.0 and 50.0 inclusively, using rand(). I've looked everywhere for an answer but it deals with ints and % operator.

Body: ((float)rand())/RAND_MAX * 100.0 - 50.0


问:
Postgres on OSX - "ERROR: extension "adminpack" already exists"
using:
pgAdmin3 (1.22.2)
OSX (Sierra 10.12.4)
postgres 9.6

When I am in pgAdmin, and I delete a test db catalog, I am prompted with this message:

"server lacks instrumentation"

The Guru hint appears with a 'FixIt' button.

When I click the 'FixIt' button I get the following error:

"ERROR: extension "adminpack" already exists"

I initially installed postgres with homebrew, but later completely uninstalled (including removing plist files) then re-installed with postgresapp

any ideas on why this is happening/how to fix this?

答:
A few suggestions:

Make sure you've added export PATH="/Applications/Postgres.app/Contents/Versions/latest/bin:$PATH" to your .bash_profile.

Try pgAdmin 4 and see whether the behavior persists.


问:
When using Azure Batch Processing, what is the best way to create and use a configuration file which can change per instance?
So I'm new to Azure and currently working on a project in which I will be using azure batch processing to run an application in several instances with different configurations.

I was wondering what is the best practice for doing this, with reference to how easy it is to change the configuration files, to deploy, how to interlink them with source control etc.

Any thoughts/knowledge would be helpful as I can't seem to find much based Azure batch and configuration files.

答:
You would manage configuration in the batch client which is a normal application running on the client outside of batch job. This application creates pools, jobs and tasks i.e. sends them to Batch Queue. You can store configuration for this client in a usual way you are used to (app.config, json files etc.).

Scheduling a job to run in batch involves specifying job parameters like pool id, task id, resource files etc. and command line for an executable to run. This is where you pass required parameters for a task instance to use.


问:
onpaste event not fired on textarea for image data
I have a working page for <textarea> description with <input type="file"> upload.  I added screenshot onpaste support to the textarea which works in Firefox 52 and should work in Chrome.

However, in IE onpaste won't fire with a <textarea> focused for non-text data.

HTML test page (IE only for brevity):

```<code><!DOCTYPE html><html><head><meta charset="UTF-8"/></head><body><form>
<script type="text/ecmascript">
function tb_pasted(e) {
   document.getElementById('txtTest').value += ' evtfired ';
   var s = "data: " + clipboardData.getData("Text") + "\n";
   var numFinished = 0; var numStarted = 0;
   for( var i=0; i<clipboardData.files.length; ++i ) {
      ++numStarted;
      var file = clipboardData.files[i];
      var fileReader = new FileReader();
      fileReader.onload = function () {
          var base64Data = fileReader.result
          s += " s:" + file.size + " d:" + fileReader.result.substring(10, 30) + "\n";
          ++numFinished;
      }
      fileReader.readAsDataURL(file);
   }
   function alertWhenDone() {
      if( numFinished >= numStarted ) alert(s);
      else setTimeout(alertWhenDone, 100);
   }
   alertWhenDone();
   return false;
}
</script>
nofire on image: <br/><textarea id="txtTest" onpaste="return tb_pasted(event);"></textarea>
<br/><br/>always fires: <br/><div id="divTest" contenteditable="true"
     style="background-color:yellow; width:100px; height:100px;"
     onpaste="return tb_pasted(event);"></div>
</form></body></html>
</code>```

Is there some way I can get onpaste to fire anyways for "text only" fields regardless of content type or do I have to eradicate all <textarea> and text fields from this page?  I've read about using
 as text entry, which might work, but I'm hoping there's a better way.

EDIT: I tried returning false from onbeforepaste and that doesn't seem to help at all.  Below won't fire an onpaste event in IE for non-text:

```<code>Enter some text:
<textarea id="txtTest"
          onbeforepaste="alert('before paste'); return false;"
          onpaste="alert('pasting'); return true;"
          ></textarea>
</code>```

答:
Aha!!! onbeforepaste event is built for just this problem.

You'd think it was as simple as returning false from onbeforepaste for a <textarea> but that doesn't seem to make the onpaste event fire.

However if you combine return false with .focus() on a non-text element (like
):

```<code> nofire on image: <br/>
 <textarea id="txtTest"
     onpaste="return tb_pasted(event);"
                                                fix="*** \/ ***"
     onbeforepaste="document.getElementById('divTest').focus();  return false;"
                                                fix="*** /\ ***"
     ></textarea><br/><br/>
 always fires: <br/>
 <div id="divTest" contenteditable="true"
     style="background-color:yellow; width:100px; height:100px;"
     onpaste="return tb_pasted(event);"></div>
</code>```

Then in seems to work even in IE.

Body:
I have a working page for <textarea> description with <input type="file"> upload.  I added screenshot onpaste support to the textarea which works in Firefox 52 and should work in Chrome.

However, in IE onpaste won't fire with a <textarea> focused for non-text data.

HTML test page (IE only for brevity):

<!DOCTYPE html><meta charset="UTF-8"/><form>

nofire on image:
<textarea id="txtTest" onpaste="return tb_pasted(event);"></textarea>

always fires:

</form>

Is there some way I can get onpaste to fire anyways for "text only" fields regardless of content type or do I have to eradicate all <textarea> and text fields from this page?  I've read about using
 as text entry, which might work, but I'm hoping there's a better way.

EDIT: I tried returning false from onbeforepaste and that doesn't seem to help at all.  Below won't fire an onpaste event in IE for non-text:

Enter some text:
<textarea id="txtTest"
          onbeforepaste="alert('before paste'); return false;"
          onpaste="alert('pasting'); return true;"
          ></textarea>

Body:
Aha!!! onbeforepaste event is built for just this problem.

You'd think it was as simple as returning false from onbeforepaste for a <textarea> but that doesn't seem to make the onpaste event fire.

However if you combine return false with .focus() on a non-text element (like <div>):

 nofire on image: <br/>
 <textarea id="txtTest"
     onpaste="return tb_pasted(event);"
                                                fix="*** \/ ***"
     onbeforepaste="document.getElementById('divTest').focus();  return false;"
                                                fix="*** /\ ***"
     ></textarea><br/><br/>
 always fires: <br/>
 <div id="divTest" contenteditable="true"
     style="background-color:yellow; width:100px; height:100px;"
     onpaste="return tb_pasted(event);"></div>

Then in seems to work even in IE.


问:
php, mysql search for the website
I need a search engine for a website I am building. I decided to try my own using php and mysql. Currently it looks like the viable options is to create three tables.

One for words, one for pages, and one reference table. Then when I am inserting a new article I would scan the text and put the separate words in the words table and refernce those words on the third table.

In the end when a search is made. The script should return the pages with the most indexed words for a given word.

However it looks like this approach can only return results depending on the number of keywords. The more a keyword is used in an article the more higher it will appear on the result page. So an article with less keywords maybe more related to the search but will be placed lower on the results.

The question would be is there a better way to create a custom search engine using php/mysql? Also if you do not have access to server to install search engines like Sphinx what is the best way to tackle this problem?

答:
As others have suggested, don't roll your own; SQL is no good for searching.  We use a system based on Solr using the Solr PHP Client library.  You'll get far better performance, support for much more powerful boolean queryies (e.g this AND that AND (this OR that) etc),  searching within documents (e.g. pdfs, word, xls etc) through Tika and so on.

http://lucene.apache.org/solr/

http://code.google.com/p/solr-php-client/

If you want to crawl your own website, you can also look into nutch.

http://nutch.apache.org/

Title: php, mysql search for the website


问:
Replace jmx_exporter_config.xml in the Docker image built by Fabric8 maven plugin
The default Docker image that is being built using mvn package fabric8:build contains /opt/agent_bond/jmx_exporter_config.xml that doesn't include (filters out) JMX beans that I'm interested in exporting to the Prometheus.

How can I replace that file with my own during the build with Fabric8 maven plugin?

I know I can construct the Docker image from scratch or redefine everything using Fabric8 plugin XML config, but that's too invasive in comparison to the default "Zero-config" approach.

Update:

So one way I found is to add custom jmx_exporter_config.yml file to the src/main/fabric8-includes and then add environment variable via Kubernetes deployment in src/main/fabric8/deployment.yml:

```<code>spec:
  template:
    spec:
      containers:
        -env:
          - name: AB_JMX_EXPORTER_CONFIG
            value: /deployments/jmx_exporter_config.yml
</code>```

Unfortunately, the Docker image in this case would still not expose custom metrics by default.

I also cannot add exposed ports when using Spring Boot generator "zero-configuration" option.

Update 2

So the workaround for the ENV entry works ok and probably is sufficient for my use case.
The 4th port that I was trying to expose was the Spring Boot management port (default 8081). But it seams that it is not needed for the Kubernetes liveness probe checking, since Kubelet can access that port even if it is not exposed from the Docker image of the Spring Boot service.

答:
The way you describe is currently the recommended way, but it should be probably easier to add such config files.

For the "zero-config" mode you can set this in the configuration (so not so zero ;-):

<configuration>
   <generator>
     <config>
       <spring-boot>
          <webPort>8080</webPort>

          <jolokiaPort>-1</jolokiaPort>
          <prometheusPort>9999</prometheusPort>
       </spring-boot>
     </config>
   </generator>
</configuration>
```

If you need additional ports you would have to provide it in your resource yaml fragment. See also https://maven.fabric8.io/#generator-java-exec for the options you can use here.

Body:
The default Docker image that is being built using mvn package fabric8:build contains /opt/agent_bond/jmx_exporter_config.xml that doesn't include (filters out) JMX beans that I'm interested in exporting to the Prometheus.

How can I replace that file with my own during the build with Fabric8 maven plugin?

I know I can construct the Docker image from scratch or redefine everything using Fabric8 plugin XML config, but that's too invasive in comparison to the default "Zero-config" approach.

Update:

So one way I found is to add custom jmx_exporter_config.yml file to the src/main/fabric8-includes and then add environment variable via Kubernetes deployment in src/main/fabric8/deployment.yml:

spec:
  template:
    spec:
      containers:
        -env:
          - name: AB_JMX_EXPORTER_CONFIG
            value: /deployments/jmx_exporter_config.yml

Unfortunately, the Docker image in this case would still not expose custom metrics by default.

I also cannot add exposed ports when using Spring Boot generator "zero-configuration" option.

Update 2

So the workaround for the ENV entry works ok and probably is sufficient for my use case.
The 4th port that I was trying to expose was the Spring Boot management port (default 8081). But it seams that it is not needed for the Kubernetes liveness probe checking, since Kubelet can access that port even if it is not exposed from the Docker image of the Spring Boot service.

Body:
The way you describe is currently the recommended way, but it should be probably easier to add such config files.

For the "zero-config" mode you can set this in the configuration (so not so zero ;-):

<configuration>
   <generator>
     <config>
       <spring-boot>
          <webPort>8080</webPort>
          <!-- dont expose jolokia -->
          <jolokiaPort>-1</jolokiaPort>
          <prometheusPort>9999</prometheusPort>
       </spring-boot>
     </config>
   </generator>
</configuration>

If you need additional ports you would have to provide it in your resource yaml fragment. See also https://maven.fabric8.io/#generator-java-exec for the options you can use here.


问:
How to show multiple child records for one parent record in an HTML table
If I had a database table containing an item and whatever was wrong with that item, for example:

```<code>Car    Scratch
Car    Dent
Car    Rust
Bike   Broken light
Bike   Rust
</code>```

How would I display this in an HTML table in the following format:

```<code>Car    Scratch, Dent, Rust
Bike   Broken light, Rust
</code>```

To be insert into an HTML table as:

```<code><tr>$name(Car)</tr>
<tr>$defects(scratch, dent, rust)</tr>
</code>```

答:
you can update your mysql query which select your item_name using your category as like your requirement

```<code>SELECT category, GROUP_CONCAT(CAST(item as CHAR)) as item_name FROM `table_name` group by category;
</code>```

this is your final query

```<code>SELECT tank_no, GROUP_CONCAT(ng_id) as item_name FROM non_green GROUP BY `tank_no`;
</code>```

where category is car,bike etc and item is scratch, dent, rust

so when you select this then you can print category and item_name and no need to process in php section.Check this attach file

more details you can check this also
How to use GROUP BY to concatenate strings in MySQL?

Body:
If I had a database table containing an item and whatever was wrong with that item, for example:

Car    Scratch
Car    Dent
Car    Rust
Bike   Broken light
Bike   Rust

How would I display this in an HTML table in the following format:

Car    Scratch, Dent, Rust
Bike   Broken light, Rust

To be insert into an HTML table as:

$name(Car)

$defects(scratch, dent, rust)

Body:
you can update your mysql query which select your item_name using your category as like your requirement

SELECT category, GROUP_CONCAT(CAST(item as CHAR)) as item_name FROM `table_name` group by category;

this is your final query

SELECT tank_no, GROUP_CONCAT(ng_id) as item_name FROM non_green GROUP BY `tank_no`;

where category is car,bike etc and item is scratch, dent, rust

so when you select this then you can print category and item_name and no need to process in php section.Check this attach file

more details you can check this also
How to use GROUP BY to concatenate strings in MySQL?


问:
ADD @url.action with parameter on Table cell in AJAX
I am new to this and I want to add a action method on table cell. The problem is Table is generated by java-script(AJAX).
Here's code:

```<code>$.ajax({
            url: "GetData",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "POST",
            success: function (obj) {
                debugger;
                $tbl.empty();
                $tbl.append('<tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th></tr>');
                for (var i = 0; i < obj.length; i++) {
                    $tbl.append(' <tr><td> <a href="#">' + obj[i].senderId + '</a></td><td>' + obj[i].subject + '</td><td>' + obj[i].msg + '</td><td>TESTING</td></tr>');
                }
            }
        });
</code>```

Now instead of href="#"> I want to add Action Method @URL.Action on that . Here's my Action Method:

```<code><a href=@Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+',receiverId='+obj[i].senderId+ })>
</code>```

But it shows error, I can't use javascript variable obj[i].senderId with c# code @Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+'...
How can I fix this, or is there any other solution to add link or onClick on Table cell and pass data with it ?

答:
David is right, but a simplified way for easy understanding.

```<code>var href = @Url.Action("SingleSentShow","Home", new { msgId ="__msgID__" ,receiverId="__receiverID__" });
href = href.replace("__mgsID__",obj[i].senderId).replace("__receiverID__",obj[i].senderId);
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');
</code>```

Both will work fine.

Update: As per Comment.

Move the value of href to data-href and set href to # and add a new class for script to work. And when the link is clicked we can swap the values.

```<code>   $tbl.append(' <tr><td> <a href=# class=Test data-href="' + href + '">' + '... the rest of your line');
</code>```

And add the below script.

```<code>   $(document).on('click', '.Test', function () {
      $(this).attr('href',$(this).attr('data-href'));
   });
</code>```

Body:
I am new to this and I want to add a action method on table cell. The problem is Table is generated by java-script(AJAX).
Here's code:

$.ajax({
            url: "GetData",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "POST",
            success: function (obj) {
                debugger;
                $tbl.empty();
                $tbl.append('
ID	Name	Last Executed Date	Status
');
                for (var i = 0; i < obj.length; i++) {
                    $tbl.append('
 ' + obj[i].senderId + '	' + obj[i].subject + '	' + obj[i].msg + '	TESTING
');
                }
            }
        });

Now instead of  I want to add Action Method @URL.Action on that . Here's my Action Method:

But it shows error, I can't use javascript variable obj[i].senderId with c# code @Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+'...
How can I fix this, or is there any other solution to add link or onClick on Table cell and pass data with it ?

Body:
David is right, but a simplified way for easy understanding.

var href = @Url.Action("SingleSentShow","Home", new { msgId ="__msgID__" ,receiverId="__receiverID__" });
href = href.replace("__mgsID__",obj[i].senderId).replace("__receiverID__",obj[i].senderId);
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');

Both will work fine.

Update: As per Comment.

Move the value of href to data-href and set href to # and add a new class for script to work. And when the link is clicked we can swap the values.

   $tbl.append(' <tr><td> <a href=# class=Test data-href="' + href + '">' + '... the rest of your line');

And add the below script.

   $(document).on('click', '.Test', function () {
      $(this).attr('href',$(this).attr('data-href'));
   });


问:
dc.js numberdisplay filter percentage
I'm new into javascript and dc.js and currently having difficulty creating a numberDisplay that only looks at a particular value in a column within my data.

I have created a dashboard with a number of different charts but I'm currently stuck on the final numberDisplays that will also filter along with the rest of the charts.

My data includes two fields in a similar format to the below, and I'm looking to create a percentage numberDisplay only for SLA's that are "2 days".

So I would expect the numberDisplay to return a percentage of "2 days" within the entire group, so it would show 30% (10/30)

I've searched and tried different solutions but the only thing I've managed to do so far is to display the overall Sum for all SLA's.

```<code>var data = [{
"sla": "2 days",
    "team": "hr",
    "hits": 7
}, {
"sla": "2 days",
    "team": "finance",
    "hits": 1
}, {
"sla": "2 days",
    "team": "finance",
    "hits": 2
}, {
"sla": "3-4 days",
    "team": "hr",
    "hits": 5
}, {
"sla": "3-4 days",
    "team": "hr",
    "hits": 4
}, {
"sla": "5 days",
    "team": "finance",
    "hits": 3
}, {
"sla": "5 days",
    "team": "hr",
    "hits": 8
}];
</code>```

There are around 6-7 different possible entries in SLA, and I'm currently only looking to create number displays for 2 or 3 of them.

What would be the quickest/easiest solution to do this?

I have created a basic jsfiddle as an example: https://jsfiddle.net/kevinelphick/owx2L1wt/2/?utm_source=website&utm_medium=embed&utm_campaign=owx2L1wt

答:
I think it's a little bit cleaner to use an ordinary reduction and use a "fake group" to pull out the individual value that you want.

Here is a wrapper that takes a group and a key and returns a groupAll-style group with a value function which returns the bin at that key:

```<code>function choose_bin(group, key) {
  return {
    value: function() {
      return group.all().filter(kv => kv.key === key)[0].value;
    }
  }
}
</code>```

In order to calculate the percentage, we also need the total number of hits; we can use dimension.groupAll() to get that:

```<code>var allHits = slaDimension.groupAll().reduceSum(d => d.hits);
</code>```

I am assuming here that you don't want these numbers filtered by the pie chart (because it would only display 0% or 100% that way). So we use the same dimension and group, because a group does not observe its own dimension's filters.

We'll define sla_2days based on the wrapper function:

```<code>var sla_2days = choose_bin(slaGroup, '2 days')
</code>```

And finally we'll define the valueAccessor of the numberDisplay to calculate a percentage:

```<code>slaNumberDisplay
  .group(sla_2days)
  .valueAccessor(x => (x / allHits.value())*100)
</code>```

Fork of your fiddle here: https://jsfiddle.net/gordonwoodhull/sa2mL8wh/3/

Title: dc.js numberdisplay filter percentage

Body:
I'm new into javascript and dc.js and currently having difficulty creating a numberDisplay that only looks at a particular value in a column within my data.

I have created a dashboard with a number of different charts but I'm currently stuck on the final numberDisplays that will also filter along with the rest of the charts.

My data includes two fields in a similar format to the below, and I'm looking to create a percentage numberDisplay only for SLA's that are "2 days".

So I would expect the numberDisplay to return a percentage of "2 days" within the entire group, so it would show 30% (10/30)

I've searched and tried different solutions but the only thing I've managed to do so far is to display the overall Sum for all SLA's.

var data = [{
"sla": "2 days",
    "team": "hr",
    "hits": 7
}, {
"sla": "2 days",
    "team": "finance",
    "hits": 1
}, {
"sla": "2 days",
    "team": "finance",
    "hits": 2
}, {
"sla": "3-4 days",
    "team": "hr",
    "hits": 5
}, {
"sla": "3-4 days",
    "team": "hr",
    "hits": 4
}, {
"sla": "5 days",
    "team": "finance",
    "hits": 3
}, {
"sla": "5 days",
    "team": "hr",
    "hits": 8
}];

There are around 6-7 different possible entries in SLA, and I'm currently only looking to create number displays for 2 or 3 of them.

What would be the quickest/easiest solution to do this?

I have created a basic jsfiddle as an example: https://jsfiddle.net/kevinelphick/owx2L1wt/2/?utm_source=website&utm_medium=embed&utm_campaign=owx2L1wt

Body:
I think it's a little bit cleaner to use an ordinary reduction and use a "fake group" to pull out the individual value that you want.

Here is a wrapper that takes a group and a key and returns a groupAll-style group with a value function which returns the bin at that key:

function choose_bin(group, key) {
  return {
    value: function() {
      return group.all().filter(kv => kv.key === key)[0].value;
    }
  }
}

In order to calculate the percentage, we also need the total number of hits; we can use dimension.groupAll() to get that:

var allHits = slaDimension.groupAll().reduceSum(d => d.hits);

I am assuming here that you don't want these numbers filtered by the pie chart (because it would only display 0% or 100% that way). So we use the same dimension and group, because a group does not observe its own dimension's filters.

We'll define sla_2days based on the wrapper function:

var sla_2days = choose_bin(slaGroup, '2 days')

And finally we'll define the valueAccessor of the numberDisplay to calculate a percentage:

slaNumberDisplay
  .group(sla_2days)
  .valueAccessor(x => (x / allHits.value())*100)

Fork of your fiddle here: https://jsfiddle.net/gordonwoodhull/sa2mL8wh/3/


问:
Spring-Cloud Zuul breaks UTF-8 symbols in forwarded multipart request filename
this is first time for me on SO, so please be patient for my first question.

I think i have some kind of configuration problem, but after a day of experiments i'm stuck. Our application is based on Spring-Cloud [Brixton release]. We have configuration like this: Portal (web application serving angular-based web-ui), which has zuul proxy with single route configured to our gateway service, like so:

```<code>zuul:
   ignoredServices: '*'
   prefix: /api
   routes:
       api-proxy:
          path: /**
          serviceId: api-gateway
</code>```

which has another Zuul configured and relays requests to inner bussiness logic services:

```<code>zuul:
  ignoredServices: '*'
  routes:
     service1:
       path: /service1/**
       serviceId: service1
     service2:
       path: /service2/**
       serviceId: service2
</code>```

All this configuration is working with no problem.
The problem now that i am facing is with file upload multipart requests. To be more precise - those multipart requests, when file to be uploaded has non latin symbols (e.g. ąčęėįš) from UTF-8. When request reaches service which has to deal with @RequestPart MultipartFile file, then file.getOriginalFilename() returns questionmarks in the places of aforementioned symbols. Now, i have tried to directly upload such file to such controller, and filename comes without questionmarks, that is, not broken, which suggests, that some bad interpretation/parsing of multipart request occurs somewhere in Zuul filters, when proxy relays incomming request.

Maybe someone had similar experience with Zuul and can direct me some way to resolve this problem?

答:
I just ran into the same issue myself, and created the following issue:

https://jira.spring.io/browse/SPR-15396

Hopefully this is getting configurable in Spring 4.3.8.

In the meantime, you have to create a bean of type FormBodyWrapperFilter (that overrides the one in ZuulConfiguration). In the constructor, you pass a copy of FormHttpMessageConverter, which extends from FormHttpMessageConverter, and you change the encoding used in FormHttpMessageConverter.MultipartHttpOutputMessage#getAsciiBytes(String) to UTF-8 (you might also want to delete any references to javax-mail, unless you have that on classpath). You need a pretty recent version of Spring Cloud Netflix to do this.

Example:

```<code>@Bean
FormBodyWrapperFilter formBodyWrapperFilter() {
    return new FormBodyWrapperFilter(new MyFormHttpMessageConverter());
}
</code>```

Then you create a copy of FormHttpMessageConverter, and change the following method:

```<code>    private byte[] getAsciiBytes(String name) {
        try {
            // THIS IS THE ONLY MODIFICATION:
            return name.getBytes("UTF-8");
        } catch (UnsupportedEncodingException ex) {
            // Should not happen - US-ASCII is always supported.
            throw new IllegalStateException(ex);
        }
    }
</code>```

Body:
this is first time for me on SO, so please be patient for my first question.

I think i have some kind of configuration problem, but after a day of experiments i'm stuck. Our application is based on Spring-Cloud [Brixton release]. We have configuration like this: Portal (web application serving angular-based web-ui), which has zuul proxy with single route configured to our gateway service, like so:

zuul:
   ignoredServices: '*'
   prefix: /api
   routes:
       api-proxy:
          path: /**
          serviceId: api-gateway

which has another Zuul configured and relays requests to inner bussiness logic services:

zuul:
  ignoredServices: '*'
  routes:
     service1:
       path: /service1/**
       serviceId: service1
     service2:
       path: /service2/**
       serviceId: service2

All this configuration is working with no problem.
The problem now that i am facing is with file upload multipart requests. To be more precise - those multipart requests, when file to be uploaded has non latin symbols (e.g. ąčęėįš) from UTF-8. When request reaches service which has to deal with @RequestPart MultipartFile file, then file.getOriginalFilename() returns questionmarks in the places of aforementioned symbols. Now, i have tried to directly upload such file to such controller, and filename comes without questionmarks, that is, not broken, which suggests, that some bad interpretation/parsing of multipart request occurs somewhere in Zuul filters, when proxy relays incomming request.

Maybe someone had similar experience with Zuul and can direct me some way to resolve this problem?

Body:
I just ran into the same issue myself, and created the following issue:

https://jira.spring.io/browse/SPR-15396

Hopefully this is getting configurable in Spring 4.3.8.

In the meantime, you have to create a bean of type FormBodyWrapperFilter (that overrides the one in ZuulConfiguration). In the constructor, you pass a copy of FormHttpMessageConverter, which extends from FormHttpMessageConverter, and you change the encoding used in FormHttpMessageConverter.MultipartHttpOutputMessage#getAsciiBytes(String) to UTF-8 (you might also want to delete any references to javax-mail, unless you have that on classpath). You need a pretty recent version of Spring Cloud Netflix to do this.

Example:

@Bean
FormBodyWrapperFilter formBodyWrapperFilter() {
    return new FormBodyWrapperFilter(new MyFormHttpMessageConverter());
}

Then you create a copy of FormHttpMessageConverter, and change the following method:

    private byte[] getAsciiBytes(String name) {
        try {
            // THIS IS THE ONLY MODIFICATION:
            return name.getBytes("UTF-8");
        } catch (UnsupportedEncodingException ex) {
            // Should not happen - US-ASCII is always supported.
            throw new IllegalStateException(ex);
        }
    }


答:
Try this:</p>

```<code>float RandomNumber(float Min, float Max)
{
    return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}
</code>```

Body:
Try this:

float RandomNumber(float Min, float Max)
{
    return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}


问:
finding an element from one list in another list in python
Is there a way to have two lists named list1 and list2 and be able to look up the position of one entry in another. i.e.

```<code>list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

list_two = ["h","e","l","l","o"]
</code>```

my aim is to allow the user to enter a word which the program will then convert in a set of numbers corresponding to the letters entries in list_one

so if the user did input hello the computer would return 85121215 (being the position of the entries)

is there a possible way to do this

答:
Looking up the position of an item in a list is not a very efficient operation.  A dict is a better data structure for this kind of task.

```<code>>>> d = {k:v for v,k in enumerate(list_one)}
>>> print(*(d[k] for k in list_two))
8 5 12 12 15
</code>```

If your list_one is always just the alphabet, in alphabetical order, it's probably better and simpler to get something working by using the builtin function ord.

Body:
Is there a way to have two lists named list1 and list2 and be able to look up the position of one entry in another. i.e.

list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

list_two = ["h","e","l","l","o"]

my aim is to allow the user to enter a word which the program will then convert in a set of numbers corresponding to the letters entries in list_one

so if the user did input hello the computer would return 85121215 (being the position of the entries)

is there a possible way to do this

Body:
Looking up the position of an item in a list is not a very efficient operation.  A dict is a better data structure for this kind of task.

>>> d = {k:v for v,k in enumerate(list_one)}
>>> print(*(d[k] for k in list_two))
8 5 12 12 15

If your list_one is always just the alphabet, in alphabetical order, it's probably better and simpler to get something working by using the builtin function ord.


问:
Seggregation of Json Schema Validation and Json Validation
I have a use case where I will take a json-schema as input, validate it, then keep in my system. Later I will get json data which I need to validate with above mentioned json-schema. given the scenario, I need to do two level of validations:

```<code>1. provided json-schema is valid or not.
2. Json is valid or not.
</code>```

I am using json-schema-validator jar and could find only second level of validation, couldn't find json-schema validation in documentation. for example: lets say we have below sample json-schema:

```<code>{
"title": "Person",
"type": "object",
"properties": {
    "firstName": {
        "type": "string"
    },
    "lastName": {
        "type": "string"
    },
    "age": {
        "description": "Age in years",
        "type": "integer",
        "minimum": 0
    }
},
"required": ["firstName", "lastName"]
}
</code>```

so how to validate this json-schema itself is valid or not?

答: You have to validate schema against meta-schema: http://json-schema.org/draft-04/schema</p>

Body:
I have a use case where I will take a json-schema as input, validate it, then keep in my system. Later I will get json data which I need to validate with above mentioned json-schema. given the scenario, I need to do two level of validations:

1. provided json-schema is valid or not.
2. Json is valid or not.

I am using json-schema-validator jar and could find only second level of validation, couldn't find json-schema validation in documentation. for example: lets say we have below sample json-schema:

{
"title": "Person",
"type": "object",
"properties": {
    "firstName": {
        "type": "string"
    },
    "lastName": {
        "type": "string"
    },
    "age": {
        "description": "Age in years",
        "type": "integer",
        "minimum": 0
    }
},
"required": ["firstName", "lastName"]
}

so how to validate this json-schema itself is valid or not?


问:
ROBLOX Cframe How do I do it?
How do I Cframe any type of brick on ROBLOX ![alt text][1]</p>

答:
See http://wiki.roblox.com/index.php/CFrame_positioning

game.Workspace.Brick.CFrame = CFrame.new(0, 10, 0) for positioning

game.Workspace.Brick.CFrame = Workspace.Brick.CFrame * CFrame.fromEulerAnglesXYZ(0, 0, 0) for tilting

just edit the values in between the ()

Title: ROBLOX Cframe How do I do it?


问:
Mark revision as non-eligible to be merged
I'm currently doing a pretty heavy task: merging a bunch of revision from the project trunk to some branches, full of conflicts.

I would like to take this process to perform some cleanup once some revisions, will never be merged from the trunk to the branches.

It is possible to mark some specific revision(s) as non-eligible to merged?

答:
As @jeremy-whitlock answered, committing the merge as "record-only" is they way to go.

For those of you using TortoiseSVN, this option will be on the second Merge dialog:


问:
SQL Server - Get Parent and Ancestor PK
I am using SQL Server 2012, I have a table called [Area]. This table contains a PK and a ParentPK. The ParentPk references the PK from the same [Area] table recursively. If there is no parent, then null is filled in for ParentPk.

```<code>Pk     ParentPk
----------------
1      null
2      null
3      1
4      3
...
</code>```

I know that the ancestor-child relationship is exactly 3 levels deep. In the above example, The Pk:4 has its parentPk:3 and grandParentPk:1.

I want to be able have a SELECT query be in the form:

```<code>SELECT GrandParentPk, ParentPk, ChildPk
...
...
...
where ChildPk = <childPk>
</code>```

Is there a non stored procedure, non recursive solution to achieve this?

答:
If you are always querying using the last child pk, and the hierarchy is always three levels, you can just use two inner joins.

```<code>select gp.pk as GrandParentPk, p.pk as ParentPk, c.pk as ChildPk
from Area c
  inner join Area p
    on c.parentPk = p.pk
  inner join Area gp
    on p.parentPk = gp.pk
where c.pk = 4
</code>```

rextester demo: http://rextester.com/MSXTVR55260

returns:

```<code>+---------------+----------+---------+
| GrandParentPk | ParentPk | ChildPk |
+---------------+----------+---------+
|             1 |        3 |       4 |
+---------------+----------+---------+
</code>```

Title: SQL Server - Get Parent and Ancestor PK

Body:
I am using SQL Server 2012, I have a table called [Area]. This table contains a PK and a ParentPK. The ParentPk references the PK from the same [Area] table recursively. If there is no parent, then null is filled in for ParentPk.

Pk     ParentPk
----------------
1      null
2      null
3      1
4      3
...

I know that the ancestor-child relationship is exactly 3 levels deep. In the above example, The Pk:4 has its parentPk:3 and grandParentPk:1.

I want to be able have a SELECT query be in the form:

SELECT GrandParentPk, ParentPk, ChildPk
...
...
...
where ChildPk = <childPk>

Is there a non stored procedure, non recursive solution to achieve this?

Body:
If you are always querying using the last child pk, and the hierarchy is always three levels, you can just use two inner joins.

select gp.pk as GrandParentPk, p.pk as ParentPk, c.pk as ChildPk
from Area c
  inner join Area p
    on c.parentPk = p.pk
  inner join Area gp
    on p.parentPk = gp.pk
where c.pk = 4

rextester demo: http://rextester.com/MSXTVR55260

returns:

+---------------+----------+---------+
| GrandParentPk | ParentPk | ChildPk |
+---------------+----------+---------+
|             1 |        3 |       4 |
+---------------+----------+---------+


问:
All Old Order Emails are going to all customers when setting cron.php on server Magento
When i set cron.php on server with SSH, all customers are getting old order emails.
How can i get which emails are in queue so that i can tell my client that these emails are now in queue.
Can someone help me on this.

Thank you

答: Check the core_queue_table and the core_email_queue_recipients tables on your server. Those tables may contain emails already sent so you have to run the core_email_queue_clean_up cron first.</p>


问:
ZeroMQ Simple Broker
I am trying to make a simple broker (i.e. star topology) that allows any DEALER node to talk to any other DEALER node that has also connected to the broker. Here is the current setup:

```<code>// Simple broker
#include <string>
#include <zmq.hpp>
#include <zhelpers.hpp>

using namespace std;

int main()
{
    zmq::context_t context(1);
    zmq::socket_t router(context, ZMQ_ROUTER);
    router.bind("ipc://router.ipc");

    while (true)
    {
        string from_address = s_recv(router);
        string to_address   = s_recv(router);
        string message      = s_recv(router);

        s_sendmore(router, to_address);
        s_sendmore(router, from_address);
        s_send(router, message);
    }

    return 0;
}
</code>```

This works, however, I feel like I just made this up and that it is inefficient to copy the incoming frames (esp. the data) into strings when I'm just swapping the positions of the first two frames and sending it right back out.

My question is - is there a standard way of doing what I am trying to do here?

It seems like every single google query sends me back to the monolithic Guide/Bible instead of implementation examples...

答:
AFAIK there's no other way.

Fundamentally you are reading data from a socket, changing it (swapping to_address & from_address around), and sending it back out.

The change (the swap) is important. ZMQ is a transport, it simply shifts your program's data from A to B. That's all it does. It doesn't have an ability to change the data in any way.

So it's inevitable that the messages have to come out of the transport, and be put back into it again.

You could try the zerocopy alternatives. That avoids some of the copying that's going on.

Title: ZeroMQ Simple Broker

Body:
I am trying to make a simple broker (i.e. star topology) that allows any DEALER node to talk to any other DEALER node that has also connected to the broker. Here is the current setup:

// Simple broker
#include <string>
#include <zmq.hpp>
#include <zhelpers.hpp>

using namespace std;

int main()
{
    zmq::context_t context(1);
    zmq::socket_t router(context, ZMQ_ROUTER);
    router.bind("ipc://router.ipc");

    while (true)
    {
        string from_address = s_recv(router);
        string to_address   = s_recv(router);
        string message      = s_recv(router);

        s_sendmore(router, to_address);
        s_sendmore(router, from_address);
        s_send(router, message);
    }

    return 0;
}

This works, however, I feel like I just made this up and that it is inefficient to copy the incoming frames (esp. the data) into strings when I'm just swapping the positions of the first two frames and sending it right back out.

My question is - is there a standard way of doing what I am trying to do here?

It seems like every single google query sends me back to the monolithic Guide/Bible instead of implementation examples...


问:
.exe file throws exception when opening file
I'm trying to write a CGI script in c++ which prints the reverse network path (using
traceroute) from the web server to the IP address of the client invoking the CGI script.

When I run the program in Visual Studio, it works fine(creates the process, prints the result into "C:/result.out" file, opens the file, prints each line from file, closes file) BUT after compiling and trying to run just its .exe file, it throws an exception. What could I do to make the .exe work properly ?
    Just as a note, I'm using Windows XP and Visual C++ 2008

Here`s the code:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <conio.h>

int main()
{
    char *line, *command, *userIp;

    printf("Content-Type:text/html\n\n");
    printf("<html><head></head><br/>");
    printf("<body><br/>");

    line    = (char*)malloc(255*sizeof(char));
    command = (char*)malloc(10*sizeof(char));
    userIp  = (char*)malloc(30*sizeof(char));
    //userIp = getenv("REMOTE_ADDR"); // use a default IP until program works
    strcpy(command,"tracert ");
    strcpy(userIp,"74.125.87.104");

    strcat(command,userIp);
    strcat(command," > C:/result.out");
    // create command "tracert 74.125.87.104 > C:/result.out"

    printf("%s",command);
    system(command);
    FILE *f;
    f = fopen("C:/result.out","r");  // open C:/result.out and read line - by - line
    strcpy(line,"");
    while(!feof(f)){
      fgets(line,255,f);
      printf("%s\n",line);
    }
    fclose(f);
    printf("<br/>Test running OK<br/>");
    printf("</body></html>");
    getch();
    return 0;
}
</code>```

答: Most likely your web server (sanely) doesn't have permission to write to c:\. Either use a proper location for temporary files, or have tracert stream the results back to the executable so you can capture them.

Body:
I'm trying to write a CGI script in c++ which prints the reverse network path (using
traceroute) from the web server to the IP address of the client invoking the CGI script.

When I run the program in Visual Studio, it works fine(creates the process, prints the result into "C:/result.out" file, opens the file, prints each line from file, closes file) BUT after compiling and trying to run just its .exe file, it throws an exception. What could I do to make the .exe work properly ?
    Just as a note, I'm using Windows XP and Visual C++ 2008

Here`s the code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <conio.h>

int main()
{
    char *line, *command, *userIp;

    printf("Content-Type:text/html\n\n");
    printf("
");
    printf("
");

    line    = (char*)malloc(255*sizeof(char));
    command = (char*)malloc(10*sizeof(char));
    userIp  = (char*)malloc(30*sizeof(char));
    //userIp = getenv("REMOTE_ADDR"); // use a default IP until program works
    strcpy(command,"tracert ");
    strcpy(userIp,"74.125.87.104");

    strcat(command,userIp);
    strcat(command," > C:/result.out");
    // create command "tracert 74.125.87.104 > C:/result.out"

    printf("%s",command);
    system(command);
    FILE *f;
    f = fopen("C:/result.out","r");  // open C:/result.out and read line - by - line
    strcpy(line,"");
    while(!feof(f)){
      fgets(line,255,f);
      printf("%s\n",line);
    }
    fclose(f);
    printf("
Test running OK
");
    printf("");
    getch();
    return 0;
}


问:
Java string templatizer / formatter with named arguments
Is there a standard or at least widespread implementation of something like String.format, but with named arguments?

I'd like to format a templatized string in a way like that:

```<code>Map<String, Object> args = new HashMap<String, Object>();
args.put("PATH", "/usr/bin");
args.put("file", "foo");
String s = someHypotheticalMethod("#{PATH}/ls #{file}");
// "/usr/bin/ls foo"
</code>```

Technically, it's almost the same as:

```<code>String[] args = new String[] { "/usr/bin", "foo" };
String s = String.format("%1$s/ls %2$s", args);
// "/usr/bin/ls foo"
</code>```

but with named arguments.

I'm aware of:

String.format

Formatter

MessageFormat

but all of them use ordered or at least numbered arguments, not named ones. I know it's trivial to implement one, but is there a mechanism I'm looking for in standard Java libraries or at least in Apache Commons / Guava / something similar, without bringing in high-profile template engines?

NOTE: I'm not really interested in full-blown template engines, with features like some imperative / functional logic, flow control, modifiers, sub-templates / inclusions, iterators, etc. Generally the following method is a working 4-line implementation - that's all I need:

```<code>public static String interpolate(String format, Map<String, ? extends Object> args) {
    String out = format;
    for (String arg : args.keySet()) {
        out = Pattern.compile(Pattern.quote("#{" + arg + "}")).
                matcher(out).
                replaceAll(args.get(arg).toString());
    }
    return out;
}
</code>```

答:
I know my answer comes a little late, but if you still need this functionality, without the need to download a full-fledged template engine you can take a look at aleph-formatter (I am one of the authors):

```<code>Student student = new Student("Andrei", 30, "Male");

String studStr = template("#{id}\tName: #{st.getName}, Age: #{st.getAge}, Gender: #{st.getGender}")
                    .arg("id", 10)
                    .arg("st", student)
                    .format();
System.out.println(studStr);
</code>```

Or you can chain the arguments:

```<code>String result = template("#{x} + #{y} = #{z}")
                    .args("x", 5, "y", 10, "z", 15)
                    .format();
System.out.println(result);

// Output: "5 + 10 = 15"
</code>```

Internally it works using a StringBuilder creating the result by "parsing" the expression, no string concatenation, regex/replace is performed.

Body:
Is there a standard or at least widespread implementation of something like String.format, but with named arguments?

I'd like to format a templatized string in a way like that:

Map<String, Object> args = new HashMap<String, Object>();
args.put("PATH", "/usr/bin");
args.put("file", "foo");
String s = someHypotheticalMethod("#{PATH}/ls #{file}");
// "/usr/bin/ls foo"

Technically, it's almost the same as:

String[] args = new String[] { "/usr/bin", "foo" };
String s = String.format("%1$s/ls %2$s", args);
// "/usr/bin/ls foo"

but with named arguments.

I'm aware of:

String.format

Formatter

MessageFormat

but all of them use ordered or at least numbered arguments, not named ones. I know it's trivial to implement one, but is there a mechanism I'm looking for in standard Java libraries or at least in Apache Commons / Guava / something similar, without bringing in high-profile template engines?

NOTE: I'm not really interested in full-blown template engines, with features like some imperative / functional logic, flow control, modifiers, sub-templates / inclusions, iterators, etc. Generally the following method is a working 4-line implementation - that's all I need:

public static String interpolate(String format, Map<String, ? extends Object> args) {
    String out = format;
    for (String arg : args.keySet()) {
        out = Pattern.compile(Pattern.quote("#{" + arg + "}")).
                matcher(out).
                replaceAll(args.get(arg).toString());
    }
    return out;
}

Body:
I know my answer comes a little late, but if you still need this functionality, without the need to download a full-fledged template engine you can take a look at aleph-formatter (I am one of the authors):

Student student = new Student("Andrei", 30, "Male");

String studStr = template("#{id}\tName: #{st.getName}, Age: #{st.getAge}, Gender: #{st.getGender}")
                    .arg("id", 10)
                    .arg("st", student)
                    .format();
System.out.println(studStr);

Or you can chain the arguments:

String result = template("#{x} + #{y} = #{z}")
                    .args("x", 5, "y", 10, "z", 15)
                    .format();
System.out.println(result);

// Output: "5 + 10 = 15"

Internally it works using a StringBuilder creating the result by "parsing" the expression, no string concatenation, regex/replace is performed.


问:
Architecture for luigi tasks with multiple inputs
I have number of pickle files, one for each date between 2005 and 2010. Each file contains a dictionary of words with their respective frequencies for that date. I also have a "master file" with all unique words for the whole period. There are about 5 million words in total.

I need to take all that data and produce one CSV file per word, which will have one row per date. E.g., for example file some_word.txt:

```<code>2005-01-01,0.0003
2005-01-02,0.00034
2005-01-03,0.008
</code>```

I'm having trouble organizing this process with the luigi framework. My current top-level task takes a word, looks up it's associated frequency for every date and stores the result in a CSV file. I guess I could just loop through every word in my master file and run the task with that word, but I estimate that would take months, if not longer. Here's my top-level AggregateTokenFreqs task in a simplified version.

```<code>class AggregateTokenFreqs(luigi.Task):
    word = luigi.Parameter()

    def requires(self):
        pass  # not sure what to require here, master file?

    def output(self):
        return luigi.LocalTarget('data/{}.csv'.format(self.word))

    def run(self):
        results = []
        for date_ in some_list_of_dates:
            with open('pickles/{}.p'.format(date_), 'rb') as f:
                freqs = pickle.load(f)
                results.append((date_, freqs.get(self.word))

        # Write results list to output CSV file
</code>```

答:
@MattMcKnight says you might be better using multiprocessing. However if you want to use Luigi here's what you can do:

Luigi has the concept of workers that you configure. That's the number of local process to run different task in parallel.

You can model the task instead of "looping" through all the pickles, pass one single pickle to the task (as parameter). You will have to write the result to a TSV in a directory with an unique name.

The have a loop that create a task per each pickle (date). An configure the number of workers (i.e. 5). that way you would be able to process 5 files at the same time.

You will require an additional task that "joins" all the individual CSV files into one.

Hope this helps.

Body:
I have number of pickle files, one for each date between 2005 and 2010. Each file contains a dictionary of words with their respective frequencies for that date. I also have a "master file" with all unique words for the whole period. There are about 5 million words in total.

I need to take all that data and produce one CSV file per word, which will have one row per date. E.g., for example file some_word.txt:

2005-01-01,0.0003
2005-01-02,0.00034
2005-01-03,0.008

I'm having trouble organizing this process with the luigi framework. My current top-level task takes a word, looks up it's associated frequency for every date and stores the result in a CSV file. I guess I could just loop through every word in my master file and run the task with that word, but I estimate that would take months, if not longer. Here's my top-level AggregateTokenFreqs task in a simplified version.

class AggregateTokenFreqs(luigi.Task):
    word = luigi.Parameter()

    def requires(self):
        pass  # not sure what to require here, master file?

    def output(self):
        return luigi.LocalTarget('data/{}.csv'.format(self.word))

    def run(self):
        results = []
        for date_ in some_list_of_dates:
            with open('pickles/{}.p'.format(date_), 'rb') as f:
                freqs = pickle.load(f)
                results.append((date_, freqs.get(self.word))

        # Write results list to output CSV file


答:
the x.index(i) returns the position of the element i of the list x

```<code>print("".join([str(list_one.index(i)) for i in list_two]))
85121215
</code>```

Title: finding an element from one list in another list in python

Body:
the x.index(i) returns the position of the element i of the list x

print("".join([str(list_one.index(i)) for i in list_two]))
85121215


问:
Variationnal auto-encoder: implementing warm-up in Keras
I recently read this paper which introduces a process called "Warm-Up" (WU), which consists in multiplying the loss in the KL-divergence by a variable whose value depends on the number of epoch (it evolves linearly from 0 to 1)

I was wondering if this is the good way to do that:

```<code>beta = K.variable(value=0.0)

def vae_loss(x, x_decoded_mean):
    # cross entropy
    xent_loss = K.mean(objectives.categorical_crossentropy(x, x_decoded_mean))

    # kl divergence
    for k in range(n_sample):
        epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.,
                              std=1.0)  # used for every z_i sampling
        # Sample several layers of latent variables
        for mean, var in zip(means, variances):
            z_ = mean + K.exp(K.log(var) / 2) * epsilon

            # build z
            try:
                z = tf.concat([z, z_], -1)
            except NameError:
                z = z_
            except TypeError:
                z = z_

            # sum loss (using a MC approximation)
            try:
                loss += K.sum(log_normal2(z_, mean, K.log(var)), -1)
            except NameError:
                loss = K.sum(log_normal2(z_, mean, K.log(var)), -1)
        print("z", z)
        loss -= K.sum(log_stdnormal(z) , -1)
        z = None
    kl_loss = loss / n_sample
    print('kl loss:', kl_loss)

    # result
    result = beta*kl_loss + xent_loss
    return result

# define callback to change the value of beta at each epoch
def warmup(epoch):
    value = (epoch/10.0) * (epoch <= 10.0) + 1.0 * (epoch > 10.0)
    print("beta:", value)
    beta = K.variable(value=value)

from keras.callbacks import LambdaCallback
wu_cb = LambdaCallback(on_epoch_end=lambda epoch, log: warmup(epoch))

# train model
vae.fit(
    padded_X_train[:last_train,:,:],
    padded_X_train[:last_train,:,:],
    batch_size=batch_size,
    nb_epoch=nb_epoch,
    verbose=0,
    callbacks=[tb, wu_cb],
    validation_data=(padded_X_test[:last_test,:,:], padded_X_test[:last_test,:,:])
)
</code>```

答:
This will not work. I tested it to figure out exactly why it was not working. The key thing to remember is that Keras creates a static graph once at the beginning of training.

Therefore, the vae_loss function is called only once to create the loss tensor, which means that the reference to the beta variable will remain the same every time the loss is calculated. However, your warmup function reassigns beta to a new K.variable. Thus, the beta that is used for calculating loss is a different beta than the one that gets updated, and the value will always be 0.

It is an easy fix. Just change this line in your warmup callback:

beta = K.variable(value=value)

to:

K.set_value(beta, value)

This way the actual value in beta gets updated "in place" rather than creating a new variable, and the loss will be properly re-calculated.

Body:
I recently read this paper which introduces a process called "Warm-Up" (WU), which consists in multiplying the loss in the KL-divergence by a variable whose value depends on the number of epoch (it evolves linearly from 0 to 1)

I was wondering if this is the good way to do that:

beta = K.variable(value=0.0)

def vae_loss(x, x_decoded_mean):
    # cross entropy
    xent_loss = K.mean(objectives.categorical_crossentropy(x, x_decoded_mean))

    # kl divergence
    for k in range(n_sample):
        epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.,
                              std=1.0)  # used for every z_i sampling
        # Sample several layers of latent variables
        for mean, var in zip(means, variances):
            z_ = mean + K.exp(K.log(var) / 2) * epsilon

            # build z
            try:
                z = tf.concat([z, z_], -1)
            except NameError:
                z = z_
            except TypeError:
                z = z_

            # sum loss (using a MC approximation)
            try:
                loss += K.sum(log_normal2(z_, mean, K.log(var)), -1)
            except NameError:
                loss = K.sum(log_normal2(z_, mean, K.log(var)), -1)
        print("z", z)
        loss -= K.sum(log_stdnormal(z) , -1)
        z = None
    kl_loss = loss / n_sample
    print('kl loss:', kl_loss)

    # result
    result = beta*kl_loss + xent_loss
    return result

# define callback to change the value of beta at each epoch
def warmup(epoch):
    value = (epoch/10.0) * (epoch <= 10.0) + 1.0 * (epoch > 10.0)
    print("beta:", value)
    beta = K.variable(value=value)

from keras.callbacks import LambdaCallback
wu_cb = LambdaCallback(on_epoch_end=lambda epoch, log: warmup(epoch))

# train model
vae.fit(
    padded_X_train[:last_train,:,:],
    padded_X_train[:last_train,:,:],
    batch_size=batch_size,
    nb_epoch=nb_epoch,
    verbose=0,
    callbacks=[tb, wu_cb],
    validation_data=(padded_X_test[:last_test,:,:], padded_X_test[:last_test,:,:])
)