问:
Using different ways to implement the same function in tensorflow will get the same gradient?
For example, I want to implement the leaky relu.

There are two ways:

The first way:

x = tf.where(tf.greater(x, 0.0), x, alpha*x)

The second way:

mask = tf.cast(tf.greater(x, 0.0), dtype=tf.float32)

x = 1.0 * mask * x + alpha * (1 - mask) * x

Will two ways have the same backpropagation?

答:
The theoretical answer: If two functions are the same, meaning that they produce exactly the same outputs for all given inputs, then the gradients of the two functions will also be exactly the same.

In practice, I guess this doesn't hold because of numerical imprecisions when multiplying the gradients of several functions. But the differences should stay small for reasonable functions.


来源: stackexchange

问:
Redux + storybook throws warning about changing store on the fly even with module.hot implemtended
I'm using storybook and I want to add redux as decorator.
Whe running storybook, I got warning in console:

```<code><Provider> does not support changing `store` on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/reactjs/react-redux/releases/tag/v2.0.0 for the migration instructions.
</code>```

It's my code for config storybook:

```<code>/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */

import React from 'react';
import { configure, storiesOf } from '@storybook/react';
import { Provider as ReduxProvider } from 'react-redux';
import forEach from 'lodash/forEach';
import unset from 'lodash/unset';
import Provider from 'components/Provider';
import initStore from 'utils/initStore';
import messages from '../lang/en.json';

const req = require.context('../components', true, /_stories\.js$/);

const ProviderDecorator = (storyFn) => {
  const TheProvider = Provider(() => storyFn());

  return (
    <ReduxProvider store={initStore()}>
      <TheProvider key={Math.random()} now={1499149917064} locale="en" messages={messages} />
    </ReduxProvider>
  );
}

function loadStories() {
  req.keys().forEach((filename) => {
    const data = req(filename);

    if (data.Component !== undefined && data.name !== undefined && data.stories !== undefined) {
      const Component = data.Component;

      const stories = storiesOf(data.name, module);

      stories.addDecorator(ProviderDecorator);

      let decorator = data.stories.__decorator;

      if (data.stories.__decorator !== undefined) {
        stories.addDecorator((storyFn) => data.stories.__decorator(storyFn()));
      }

      forEach(data.stories, (el, key) => {
        if (key.indexOf('__') !== 0) {
          stories.add(key, () => (
            <Component {...el} />
          ));
        }
      });
    } else {
      console.error(`Missing test data for ${filename}!`)
    }

  });
}

configure(loadStories, module);
</code>```

and initStore file:

```<code>import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunkMiddleware from 'redux-thunk';
import { persistStore, autoRehydrate } from 'redux-persist';

import reducers from 'containers/redux/reducers';

export default () => {
  const store = createStore(
    reducers,
    {},
    composeWithDevTools(applyMiddleware(thunkMiddleware), autoRehydrate()),
  );

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../containers/redux/reducers', () => {
      const nextReducers = require('../containers/redux/reducers'); // eslint-disable-line global-require
      store.replaceReducer(nextReducers);
    });
  }

  persistStore(store);

  return store;
};
</code>```

So as you can see I followed instructions from link in warning. What have I done wrong and how can I remove this warning? I know it won't show on production server, but it's pretty annoying in dev mode. :/

答:
The reason this is happening has to do with the way Storybook hot-loads.

When you change your story, that module is hot-loaded, meaning that the code inside it is executed again.

Since you're using a store creator function and not a store instance from another module, the actual store object that is being passed to ReduxProvider on hot-load is new every time.

However, the React tree that is re-constructed is for the most part identical, meaning that the ReduxProvider instance is re-rendered with new props instead of being re-created.

Essentially, this is changing its store on the fly.

The solve is to make sure that ReduxProvider instance is new, too, on hot-load. This is easily solved by passing it a unique key prop, e.g.:

```<code>const ProviderDecorator = (storyFn) => {
  const TheProvider = Provider(() => storyFn());

  return (
    <ReduxProvider key={Math.random()} store={initStore()}>
      <TheProvider key={Math.random()} now={1499149917064} locale="en" messages={messages} />
    </ReduxProvider>
  );
}
</code>```

From React Keys:

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

ContentLicense: CC BY-SA 3.0

Body:
I'm using storybook and I want to add redux as decorator.
Whe running storybook, I got warning in console:

<Provider> does not support changing `store` on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/reactjs/react-redux/releases/tag/v2.0.0 for the migration instructions.

It's my code for config storybook:

/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */

import React from 'react';
import { configure, storiesOf } from '@storybook/react';
import { Provider as ReduxProvider } from 'react-redux';
import forEach from 'lodash/forEach';
import unset from 'lodash/unset';
import Provider from 'components/Provider';
import initStore from 'utils/initStore';
import messages from '../lang/en.json';

const req = require.context('../components', true, /_stories\.js$/);

const ProviderDecorator = (storyFn) => {
  const TheProvider = Provider(() => storyFn());

  return (
    <ReduxProvider store={initStore()}>
      <TheProvider key={Math.random()} now={1499149917064} locale="en" messages={messages} />
    </ReduxProvider>
  );
}

function loadStories() {
  req.keys().forEach((filename) => {
    const data = req(filename);

    if (data.Component !== undefined && data.name !== undefined && data.stories !== undefined) {
      const Component = data.Component;

      const stories = storiesOf(data.name, module);

      stories.addDecorator(ProviderDecorator);

      let decorator = data.stories.__decorator;

      if (data.stories.__decorator !== undefined) {
        stories.addDecorator((storyFn) => data.stories.__decorator(storyFn()));
      }

      forEach(data.stories, (el, key) => {
        if (key.indexOf('__') !== 0) {
          stories.add(key, () => (
            <Component {...el} />
          ));
        }
      });
    } else {
      console.error(`Missing test data for ${filename}!`)
    }

  });
}

configure(loadStories, module);

and initStore file:

import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunkMiddleware from 'redux-thunk';
import { persistStore, autoRehydrate } from 'redux-persist';

import reducers from 'containers/redux/reducers';

export default () => {
  const store = createStore(
    reducers,
    {},
    composeWithDevTools(applyMiddleware(thunkMiddleware), autoRehydrate()),
  );

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../containers/redux/reducers', () => {
      const nextReducers = require('../containers/redux/reducers'); // eslint-disable-line global-require
      store.replaceReducer(nextReducers);
    });
  }

  persistStore(store);

  return store;
};

So as you can see I followed instructions from link in warning. What have I done wrong and how can I remove this warning? I know it won't show on production server, but it's pretty annoying in dev mode. :/

Body:
The reason this is happening has to do with the way Storybook hot-loads.

When you change your story, that module is hot-loaded, meaning that the code inside it is executed again.

Since you're using a store creator function and not a store instance from another module, the actual store object that is being passed to ReduxProvider on hot-load is new every time.

However, the React tree that is re-constructed is for the most part identical, meaning that the ReduxProvider instance is re-rendered with new props instead of being re-created.

Essentially, this is changing its store on the fly.

The solve is to make sure that ReduxProvider instance is new, too, on hot-load. This is easily solved by passing it a unique key prop, e.g.:

const ProviderDecorator = (storyFn) => {
  const TheProvider = Provider(() => storyFn());

  return (
    <ReduxProvider key={Math.random()} store={initStore()}>
      <TheProvider key={Math.random()} now={1499149917064} locale="en" messages={messages} />
    </ReduxProvider>
  );
}

From React Keys:

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.


问:
Getting Native Android Crash /system/lib64/libc.so (tgkill+8) on Specific Devices
I am getting this stacktrace on Google Android Vitals for specific devices mostly Xiaomi's Redmi Devices. Here's the list of devices

And here's my app.gradle

```<code>buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

repositories {
    jcenter()
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
maven { url "https://raw.githubusercontent.com/smilefam/SendBird-SDK-
Android/master/" }
}

android {
lintOptions {
    checkReleaseBuilds false
}
 compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
    resConfigs "en"
    applicationId "xxxxxxxx"
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 123
    multiDexEnabled false
    versionName "1.6.8.1"
    signingConfig signingConfigs.config
}
buildTypes {
    debug {
        minifyEnabled false
        debuggable true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    release {
        minifyEnabled true
        debuggable false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.config
    }
}
dexOptions {
    javaMaxHeapSize "4g"
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
////////////////
////////////////////////////
//////////////////////////////
compile 'com.squareup.okhttp3:okhttp:3.8.0'
compile('com.twitter.sdk.android:twitter:3.0.0@aar') {
    transitive = true// Contains Picasso
}
compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true
}
compile('io.branch.sdk.android:library:2.+') {
    exclude module: 'answers-shim'
}
compile 'com.android.support:appcompat-v7:26.0.0'
compile 'com.android.support:design:26.0.0'
compile 'com.google.android.gms:play-services-location:11.0.2'
compile 'com.google.android.gms:play-services-gcm:11.0.2'
compile 'com.google.android.gms:play-services-auth:11.0.2'
compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.facebook.android:facebook-android-sdk:4.24.0'
compile 'com.facebook.android:account-kit-sdk:4.20.0'
compile 'com.sendbird.sdk:sendbird-android-sdk:3.0.28'
compile 'com.clevertap.android:clevertap-android-sdk:3.1.2'
compile 'com.kbeanie:image-chooser-library:1.6.0@aar'
compile 'com.isseiaoki:simplecropview:1.1.4'
compile 'com.wang.avi:library:2.1.3'
compile 'com.pkmmte.view:circularimageview:1.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.airbnb.android:epoxy:2.2.0'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

I need help in figuring out the way to resolve this crash or at least reproduce it on my end. It's not visible on fabric too.
I have feeling that may be its caused by the build tools 26.0.0. But not sure though.

Thanks in advance.

答:
This issue happen in S6 edge plus,
And I try use older version , My devices not happen again
You can try my solution </p>

```<code>compile 'com.google.android.gms:play-services-analytics:9.2.1'
compile 'com.google.android.gms:play-services-vision:9.2.1'
compile 'com.google.android.gms:play-services-appindexing:9.2.1'
</code>```

Body:
I am getting this stacktrace on Google Android Vitals for specific devices mostly Xiaomi's Redmi Devices. Here's the list of devices

And here's my app.gradle

buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

repositories {
    jcenter()
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
maven { url "https://raw.githubusercontent.com/smilefam/SendBird-SDK-
Android/master/" }
}

android {
lintOptions {
    checkReleaseBuilds false
}
 compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
    resConfigs "en"
    applicationId "xxxxxxxx"
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 123
    multiDexEnabled false
    versionName "1.6.8.1"
    signingConfig signingConfigs.config
}
buildTypes {
    debug {
        minifyEnabled false
        debuggable true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    release {
        minifyEnabled true
        debuggable false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.config
    }
}
dexOptions {
    javaMaxHeapSize "4g"
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
////////////////
////////////////////////////
//////////////////////////////
compile 'com.squareup.okhttp3:okhttp:3.8.0'
compile('com.twitter.sdk.android:twitter:3.0.0@aar') {
    transitive = true// Contains Picasso
}
compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true
}
compile('io.branch.sdk.android:library:2.+') {
    exclude module: 'answers-shim'
}
compile 'com.android.support:appcompat-v7:26.0.0'
compile 'com.android.support:design:26.0.0'
compile 'com.google.android.gms:play-services-location:11.0.2'
compile 'com.google.android.gms:play-services-gcm:11.0.2'
compile 'com.google.android.gms:play-services-auth:11.0.2'
compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.facebook.android:facebook-android-sdk:4.24.0'
compile 'com.facebook.android:account-kit-sdk:4.20.0'
compile 'com.sendbird.sdk:sendbird-android-sdk:3.0.28'
compile 'com.clevertap.android:clevertap-android-sdk:3.1.2'
compile 'com.kbeanie:image-chooser-library:1.6.0@aar'
compile 'com.isseiaoki:simplecropview:1.1.4'
compile 'com.wang.avi:library:2.1.3'
compile 'com.pkmmte.view:circularimageview:1.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.airbnb.android:epoxy:2.2.0'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

I need help in figuring out the way to resolve this crash or at least reproduce it on my end. It's not visible on fabric too.
I have feeling that may be its caused by the build tools 26.0.0. But not sure though.

Thanks in advance.

Body:
This issue happen in S6 edge plus,
And I try use older version , My devices not happen again
You can try my solution

compile 'com.google.android.gms:play-services-analytics:9.2.1'
compile 'com.google.android.gms:play-services-vision:9.2.1'
compile 'com.google.android.gms:play-services-appindexing:9.2.1'


问:
Can Promise.all handle results as soon as possible, not waiting for all promises done
I am using KOA2 to demo a bigpipe. I want to output a result as soon as possible when it's ready, rather than waiting until all results are ready(then output all).

I stuck here as code below: (get_users or get_posts return a promise)

```<code>async (ctx, next) => {

    ctx.res.write("<html><body>...")

    let data = await Promise.all( [res_fetch.get_users(), res_fetch.get_posts()] )

    ctx.res.write(data[0])
    ctx.res.write(data[1])
    ctx.res.write("</body></html>")
    ctx.res.end()
</code>```

}

Ideally it should be something: (which I don't know how to achieve)

```<code>let data = await Promise.oneFinished( [res_fetch.get_users(), res_fetch.get_posts()] )

if (data[0] is finished)
    ctx.res.write(data[0])
else if (data[1] is finished)
    ctx.res.write(data[1])
</code>```

答:
What you're looking for is Promise.race, which returns the promise from the collection provided that resolves (or rejects) first!</p>

```<code>let data = await Promise.race( [res_fetch.get_users(), res_fetch.get_posts()] )

if (data[0] is finished)
    ctx.res.write(data[0])
else if (data[1] is finished)
    ctx.res.write(data[1])
</code>```

Body:
I am using KOA2 to demo a bigpipe. I want to output a result as soon as possible when it's ready, rather than waiting until all results are ready(then output all).

I stuck here as code below: (get_users or get_posts return a promise)

async (ctx, next) => {

    ctx.res.write("...")

    let data = await Promise.all( [res_fetch.get_users(), res_fetch.get_posts()] )

    ctx.res.write(data[0])
    ctx.res.write(data[1])
    ctx.res.write("")
    ctx.res.end()

}

Ideally it should be something: (which I don't know how to achieve)

let data = await Promise.oneFinished( [res_fetch.get_users(), res_fetch.get_posts()] )

if (data[0] is finished)
    ctx.res.write(data[0])
else if (data[1] is finished)
    ctx.res.write(data[1])

Body:
What you're looking for is Promise.race, which returns the promise from the collection provided that resolves (or rejects) first!

let data = await Promise.race( [res_fetch.get_users(), res_fetch.get_posts()] )

if (data[0] is finished)
    ctx.res.write(data[0])
else if (data[1] is finished)
    ctx.res.write(data[1])


问:
CORBA omniorb C++ multiple servants
Hi everybody i'm new in CORBA C++, I read a tutorial for how to install CORBA on linux, its working and the code compiles fine, i wanna execute more than one server instance because i wanna create a peer-to-peer. for example when i create one server instance and multiple client instances works fine, but when i tried to execute two or more server instances in order to receiving messages from the clients only the last server instance receive the messages, please can anyone help me?

Here is my code for server and client

server.cpp

```<code>#include "MyExampleInterface_impl.h"
#include <iostream>
#include <CORBA.h>
#include <Naming.hh>

/** Server name, clients needs to know this name */
#define SERVER_NAME     "MyServerName"

using namespace std;

int main(int argc, char ** argv)
{
cerr << "CORBA SERVER RUNNING..." << endl;
try {

    //------------------------------------------------------------------------
    // Initialize CORBA ORB
    //------------------------------------------------------------------------
    CORBA::ORB_ptr orb = CORBA::ORB_init(argc, argv);

    //------------------------------------------------------------------------
    // Initialize POA: Get reference to root POA
    //
    // Servant must register with POA in order to be made available for client
    // Get reference to the RootPOA.
    //-----------------------------------------------------------------------
    CORBA::Object_var poa_obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(poa_obj);
    PortableServer::POAManager_var manager = poa->the_POAManager();

    //------------------------------------------------------------------------
    // Create service
    //------------------------------------------------------------------------
    MyExampleInterface_impl * service = new MyExampleInterface_impl;
    cerr << "ya se creo el servicio procediendo a crear instancia" << endl;
    try {
        //------------------------------------------------------------------------
        // Bind object to name service as defined by directive InitRef
        // and identifier "NameService" in config file omniORB.cfg.
        //------------------------------------------------------------------------
        CORBA::Object_var ns_obj = orb->resolve_initial_references("NameService");
        if (!CORBA::is_nil(ns_obj)) {
            //------------------------------------------------------------------------
            // Narrow this to the naming context
            //------------------------------------------------------------------------
            CosNaming::NamingContext_ptr nc = CosNaming::NamingContext::_narrow(ns_obj);

            //------------------------------------------------------------------------
            // Bind to CORBA name service. Same name to be requested by client.
            //------------------------------------------------------------------------
            CosNaming::Name name;
            name.length(1);
            name[0].id = CORBA::string_dup(SERVER_NAME);
            name[0].kind = CORBA::string_dup("");
            nc->rebind(name, service->_this());

            //------------------------------------------------------------------------
            // Intizialization ready, server runs
            //------------------------------------------------------------------------
            cout << argv[0] << " C++ (omniORB) server '" << SERVER_NAME << "' is running .." << endl;
        }
    } catch (CosNaming::NamingContext::NotFound &) {
        cerr << "Caught CORBA exception: not found" << endl;
    } catch (CosNaming::NamingContext::InvalidName &) {
        cerr << "Caught CORBA exception: invalid name" << endl;
    } catch (CosNaming::NamingContext::CannotProceed &) {
        cerr << "Caught CORBA exception: cannot proceed" << endl;
    }

    //------------------------------------------------------------------------
    // Activate the POA manager
    //------------------------------------------------------------------------
    manager->activate();
    //------------------------------------------------------------------------
    // Accept requests from clients
    //------------------------------------------------------------------------
cerr << "aceptando peticiones de cliente con run()" << endl;
    orb->run();
cerr << "hecho ahora esperando..." << endl;
    //------------------------------------------------------------------------
    // Clean up
    //------------------------------------------------------------------------
    //delete service;

    //------------------------------------------------------------------------
    // Destroy ORB
    //------------------------------------------------------------------------
    orb->destroy();

} catch (CORBA::UNKNOWN) {
    cerr << "Caught CORBA exception: unknown exception" << endl;
} catch (CORBA::SystemException &) {
    cerr << "Caught CORBA exception: system exception" << endl;
}
</code>```

}

client.cpp

```<code>#include "example.hh"
#include <iostream>
#include <CORBA.h>
#include <Naming.hh>

/** Name is defined in the server.cpp */
#define SERVER_NAME     "MyServerName"

using namespace std;

int main(int argc, char ** argv)
{
    try {
        //------------------------------------------------------------------------
        // Initialize ORB object.
        //------------------------------------------------------------------------
        CORBA::ORB_ptr orb = CORBA::ORB_init(argc, argv);

        //------------------------------------------------------------------------
        // Resolve service
        //------------------------------------------------------------------------
        ExampleInterface_ptr service_server = 0;

        try {

            //------------------------------------------------------------------------
            // Bind ORB object to name service object.
            // (Reference to Name service root context.)
            //------------------------------------------------------------------------
            CORBA::Object_var ns_obj = orb->resolve_initial_references("NameService");

            if (!CORBA::is_nil(ns_obj)) {
                //------------------------------------------------------------------------
                // Bind ORB object to name service object.
                // (Reference to Name service root context.)
                //------------------------------------------------------------------------
                CosNaming::NamingContext_ptr nc = CosNaming::NamingContext::_narrow(ns_obj);

                //------------------------------------------------------------------------
                // The "name text" put forth by CORBA server in name service.
                // This same name ("MyServerName") is used by the CORBA server when
                // binding to the name server (CosNaming::Name).
                //------------------------------------------------------------------------
                CosNaming::Name name;
                name.length(1);
                name[0].id = CORBA::string_dup(SERVER_NAME);
                name[0].kind = CORBA::string_dup("");

                //------------------------------------------------------------------------
                // Resolve "name text" identifier to an object reference.
                //------------------------------------------------------------------------
                CORBA::Object_ptr obj = nc->resolve(name);

                if (!CORBA::is_nil(obj)) {
                    service_server = ExampleInterface::_narrow(obj);
                }
            }
        } catch (CosNaming::NamingContext::NotFound &) {
            cerr << "Caught corba not found" << endl;
        } catch (CosNaming::NamingContext::InvalidName &) {
            cerr << "Caught corba invalid name" << endl;
        } catch (CosNaming::NamingContext::CannotProceed &) {
            cerr << "Caught corba cannot proceed" << endl;
        }

        //------------------------------------------------------------------------
        // Do stuff
        //------------------------------------------------------------------------
        if (!CORBA::is_nil(service_server)) {
            char * server = service_server->send_message("Message from C++ (omniORB) client");
            cout << "response from Server: " << server << endl;
            CORBA::string_free(server);
        }

        //------------------------------------------------------------------------
        // Destroy OBR
        //------------------------------------------------------------------------
        orb->destroy();

    } catch (CORBA::UNKNOWN) {
        cerr << "Caught CORBA exception: unknown exception" << endl;
    }
}
</code>```

答:
The Naming Service is like a telephone book, you store an object reference using a known name. Currently you "MyServerName" in your code and there can only be one server registered with it. Starting a second server will update the Naming Service to only use the second server, all new clients will use that from that point.

You could register each server in the Naming Service with an unique name and let the client decide which server to use.

Title: CORBA omniorb C++ multiple servants

Body:
Hi everybody i'm new in CORBA C++, I read a tutorial for how to install CORBA on linux, its working and the code compiles fine, i wanna execute more than one server instance because i wanna create a peer-to-peer. for example when i create one server instance and multiple client instances works fine, but when i tried to execute two or more server instances in order to receiving messages from the clients only the last server instance receive the messages, please can anyone help me?

Here is my code for server and client

server.cpp

#include "MyExampleInterface_impl.h"
#include <iostream>
#include <CORBA.h>
#include <Naming.hh>

/** Server name, clients needs to know this name */
#define SERVER_NAME     "MyServerName"

using namespace std;

int main(int argc, char ** argv)
{
cerr << "CORBA SERVER RUNNING..." << endl;
try {

    //------------------------------------------------------------------------
    // Initialize CORBA ORB
    //------------------------------------------------------------------------
    CORBA::ORB_ptr orb = CORBA::ORB_init(argc, argv);

    //------------------------------------------------------------------------
    // Initialize POA: Get reference to root POA
    //
    // Servant must register with POA in order to be made available for client
    // Get reference to the RootPOA.
    //-----------------------------------------------------------------------
    CORBA::Object_var poa_obj = orb->resolve_initial_references("RootPOA");
    PortableServer::POA_var poa = PortableServer::POA::_narrow(poa_obj);
    PortableServer::POAManager_var manager = poa->the_POAManager();

    //------------------------------------------------------------------------
    // Create service
    //------------------------------------------------------------------------
    MyExampleInterface_impl * service = new MyExampleInterface_impl;
    cerr << "ya se creo el servicio procediendo a crear instancia" << endl;
    try {
        //------------------------------------------------------------------------
        // Bind object to name service as defined by directive InitRef
        // and identifier "NameService" in config file omniORB.cfg.
        //------------------------------------------------------------------------
        CORBA::Object_var ns_obj = orb->resolve_initial_references("NameService");
        if (!CORBA::is_nil(ns_obj)) {
            //------------------------------------------------------------------------
            // Narrow this to the naming context
            //------------------------------------------------------------------------
            CosNaming::NamingContext_ptr nc = CosNaming::NamingContext::_narrow(ns_obj);

            //------------------------------------------------------------------------
            // Bind to CORBA name service. Same name to be requested by client.
            //------------------------------------------------------------------------
            CosNaming::Name name;
            name.length(1);
            name[0].id = CORBA::string_dup(SERVER_NAME);
            name[0].kind = CORBA::string_dup("");
            nc->rebind(name, service->_this());

            //------------------------------------------------------------------------
            // Intizialization ready, server runs
            //------------------------------------------------------------------------
            cout << argv[0] << " C++ (omniORB) server '" << SERVER_NAME << "' is running .." << endl;
        }
    } catch (CosNaming::NamingContext::NotFound &) {
        cerr << "Caught CORBA exception: not found" << endl;
    } catch (CosNaming::NamingContext::InvalidName &) {
        cerr << "Caught CORBA exception: invalid name" << endl;
    } catch (CosNaming::NamingContext::CannotProceed &) {
        cerr << "Caught CORBA exception: cannot proceed" << endl;
    }

    //------------------------------------------------------------------------
    // Activate the POA manager
    //------------------------------------------------------------------------
    manager->activate();
    //------------------------------------------------------------------------
    // Accept requests from clients
    //------------------------------------------------------------------------
cerr << "aceptando peticiones de cliente con run()" << endl;
    orb->run();
cerr << "hecho ahora esperando..." << endl;
    //------------------------------------------------------------------------
    // Clean up
    //------------------------------------------------------------------------
    //delete service;

    //------------------------------------------------------------------------
    // Destroy ORB
    //------------------------------------------------------------------------
    orb->destroy();

} catch (CORBA::UNKNOWN) {
    cerr << "Caught CORBA exception: unknown exception" << endl;
} catch (CORBA::SystemException &) {
    cerr << "Caught CORBA exception: system exception" << endl;
}

}

client.cpp

#include "example.hh"
#include <iostream>
#include <CORBA.h>
#include <Naming.hh>

/** Name is defined in the server.cpp */
#define SERVER_NAME     "MyServerName"

using namespace std;

int main(int argc, char ** argv)
{
    try {
        //------------------------------------------------------------------------
        // Initialize ORB object.
        //------------------------------------------------------------------------
        CORBA::ORB_ptr orb = CORBA::ORB_init(argc, argv);

        //------------------------------------------------------------------------
        // Resolve service
        //------------------------------------------------------------------------
        ExampleInterface_ptr service_server = 0;

        try {

            //------------------------------------------------------------------------
            // Bind ORB object to name service object.
            // (Reference to Name service root context.)
            //------------------------------------------------------------------------
            CORBA::Object_var ns_obj = orb->resolve_initial_references("NameService");

            if (!CORBA::is_nil(ns_obj)) {
                //------------------------------------------------------------------------
                // Bind ORB object to name service object.
                // (Reference to Name service root context.)
                //------------------------------------------------------------------------
                CosNaming::NamingContext_ptr nc = CosNaming::NamingContext::_narrow(ns_obj);

                //------------------------------------------------------------------------
                // The "name text" put forth by CORBA server in name service.
                // This same name ("MyServerName") is used by the CORBA server when
                // binding to the name server (CosNaming::Name).
                //------------------------------------------------------------------------
                CosNaming::Name name;
                name.length(1);
                name[0].id = CORBA::string_dup(SERVER_NAME);
                name[0].kind = CORBA::string_dup("");

                //------------------------------------------------------------------------
                // Resolve "name text" identifier to an object reference.
                //------------------------------------------------------------------------
                CORBA::Object_ptr obj = nc->resolve(name);

                if (!CORBA::is_nil(obj)) {
                    service_server = ExampleInterface::_narrow(obj);
                }
            }
        } catch (CosNaming::NamingContext::NotFound &) {
            cerr << "Caught corba not found" << endl;
        } catch (CosNaming::NamingContext::InvalidName &) {
            cerr << "Caught corba invalid name" << endl;
        } catch (CosNaming::NamingContext::CannotProceed &) {
            cerr << "Caught corba cannot proceed" << endl;
        }

        //------------------------------------------------------------------------
        // Do stuff
        //------------------------------------------------------------------------
        if (!CORBA::is_nil(service_server)) {
            char * server = service_server->send_message("Message from C++ (omniORB) client");
            cout << "response from Server: " << server << endl;
            CORBA::string_free(server);
        }

        //------------------------------------------------------------------------
        // Destroy OBR
        //------------------------------------------------------------------------
        orb->destroy();

    } catch (CORBA::UNKNOWN) {
        cerr << "Caught CORBA exception: unknown exception" << endl;
    }
}


问:
Checkbox input array values passed to insert into MySQL query based on selections
My array of checkbox inputs is displaying and working perfect:

```<code><input name="seminar[<?php echo $a; ?>]" type="checkbox" id="seminar_<?php echo $a; ?> "value="" <?php echo $checked; ?>>
</code>```

This is my MySQL insert data ($s):

```<code>if ($seminar) {
    foreach ($seminar as $s )
        $interest .= "$s ";
}
</code>```

My earlier for loop that processes the checkbox inputs above, does not store the data in $s. And I am trying to find a way to store those values to pass to that foreach.

答:
```<code><input type="checkbox" name="apple[]" value="1">
<input type="checkbox" name="apple[]" value="2">
<input type="checkbox" name="apple[]" value="3">
</code>```

your checkbox is something like this...............ok.

then in php you just post the variable

```<code><?php $apple=$_POST['apple'];
   ?>
</code>```

now the $apple is an array of your selected values.
is it ok for your project.....................

ContentLicense: CC BY-SA 2.5

Body:
My array of checkbox inputs is displaying and working perfect:

<input name="seminar[<?php echo $a; ?>]" type="checkbox" id="seminar_<?php echo $a; ?> "value="" <?php echo $checked; ?>>

This is my MySQL insert data ($s):

if ($seminar) {
    foreach ($seminar as $s )
        $interest .= "$s ";
}

My earlier for loop that processes the checkbox inputs above, does not store the data in $s. And I am trying to find a way to store those values to pass to that foreach.

Body:
<input type="checkbox" name="apple[]" value="1">
<input type="checkbox" name="apple[]" value="2">
<input type="checkbox" name="apple[]" value="3">

your checkbox is something like this...............ok.

then in php you just post the variable

<?php $apple=$_POST['apple'];
   ?>

now the $apple is an array of your selected values.
is it ok for your project.....................


问:
Apache POI XSSFWorkbook memory leak
So I'm making a large-scale prime number generator in Java (with the help of JavaFX).

It uses the Apache POI library (I believe I'm using v3.17) to output the results to Excel spreadsheets.

The static methods for this exporting logic are held in a class called ExcelWriter. Basically, it iterates through an Arraylist arguments and populates a XSSFWorkbook with it's contents. Afterwords, a FileOutputStream is used to actually make it an excel file. Here are the relevant parts of it:

```<code>public class ExcelWriter {

//Configured JFileChooser to make alert before overwriting old files
private static JFileChooser fileManager = new JFileChooser(){
@Override
public void approveSelection(){
    ...
}
};

private static FileFilter filter = new FileNameExtensionFilter("Excel files","xlsx");
private static boolean hasBeenInitialized = false;

//Only method that can be called externally to access this class's functionality
public static <T extends Object> void makeSpreadsheet
    (ArrayList<T> list,  spreadsheetTypes type, int max, String title, JFXProgressBar progressBar)
            throws IOException, InterruptedException{
    progressBar.progressProperty().setValue(0);
    switch (type){
        case rightToLeftColumnLimit:
            makeSpreadsheetRightToLeft(list, false, max, title, progressBar);
            break;
       ...
    }
}

static private <T extends Object> void makeSpreadsheetRightToLeft
    (ArrayList<T> list,  boolean maxRows, int max, String title, JFXProgressBar progressBar)
            throws IOException, InterruptedException{
    initializeChooser();
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Primus output");
    int rowPointer = 0;
    int columnPointer = 0;
    double progressIncrementValue = 1/(double)list.size();

    //Giving the spreadsheet an internal title also
    Row row = sheet.createRow(0);
    row.createCell(0).setCellValue(title);

    row = sheet.createRow(++rowPointer);

    //Making the sheet with a max column limit
    if (!maxRows){
        for (T number: list){
            if (columnPointer == max){
                columnPointer = 0;
                row = sheet.createRow(++rowPointer);
            }
            Cell cell = row.createCell(columnPointer++);
            progressBar.setProgress(progressBar.getProgress() + progressIncrementValue);
            cell.setCellValue(number.toString());
        }
    }else {
        //Making the sheet with a max row limit
        int columnWrapIndex = (int)Math.ceil(list.size()/(float)max);
        for (T number: list){
            if (columnPointer == columnWrapIndex){
                columnPointer = 0;
                row = sheet.createRow(++rowPointer);
            }
            Cell cell = row.createCell(columnPointer++);
            progressBar.setProgress(progressBar.getProgress() + progressIncrementValue);
            cell.setCellValue(number.toString());
        }
    }
    writeToExcel(workbook, progressBar);

}

static private void writeToExcel(XSSFWorkbook book, JFXProgressBar progressBar) throws IOException, InterruptedException{
    //Exporting to Excel
    int returnValue = fileManager.showSaveDialog(null);

    if (returnValue == JFileChooser.APPROVE_OPTION){
        File file = fileManager.getSelectedFile();

        //Validation logic here

        try{

            FileOutputStream out = new FileOutputStream(file);
            book.write(out);
            out.close();
            book.close();
        }catch (FileNotFoundException ex){

        }

    }
}
}
</code>```

Afterwards, my FXML document controller has a buttonListerner which calls:

```<code>longCalculationThread thread = new longCalculationThread(threadBundle);
thread.start();
</code>```

The longcalculationthread creates a list of about a million prime numbers and Exports them to the ExcelWriter using this code:

```<code>private void publishResults() throws IOException, InterruptedException{
    if (!longResults.isEmpty()){
        if (shouldExport) {
            progressText.setText("Exporting to Excel...");
            ExcelWriter.makeSpreadsheet(longResults, exportType, excelExportLimit, getTitle(), progressBar);

    }
   }
</code>```

The problem is, even though the variable holding the workbook in the XSSF workbook is a local variable to the methods it is used in, it doesn't get garbage collected afterwards.

It takes up like 1.5GB of RAM (I don't know why), and that data is only reallocated when another huge export is called (not for small exports).
My problem isn't really that the thing takes a lot of RAM, it's that even when the methods are completed the memory isn't GCed.
Here are some pictures of my NetBeans profiles:

Normal memory usage when making array of 1000000 primes:

Huge heap usage when making workbook

Memory Isn't reallocated when workbook ins't accessible anymore

Fluctuation seen when making a new workbook using the same static methods

答: I found the answer! I had to prompt the GC with System.gc(). I remember trying this out earlier, however I must have put it in a pace where the workbook was still accessible and hence couldn't be GCed.</p>

Title: Apache POI XSSFWorkbook memory leak

Body:
So I'm making a large-scale prime number generator in Java (with the help of JavaFX).

It uses the Apache POI library (I believe I'm using v3.17) to output the results to Excel spreadsheets.

The static methods for this exporting logic are held in a class called ExcelWriter. Basically, it iterates through an Arraylist arguments and populates a XSSFWorkbook with it's contents. Afterwords, a FileOutputStream is used to actually make it an excel file. Here are the relevant parts of it:

public class ExcelWriter {

//Configured JFileChooser to make alert before overwriting old files
private static JFileChooser fileManager = new JFileChooser(){
@Override
public void approveSelection(){
    ...
}
};

private static FileFilter filter = new FileNameExtensionFilter("Excel files","xlsx");
private static boolean hasBeenInitialized = false;

//Only method that can be called externally to access this class's functionality
public static <T extends Object> void makeSpreadsheet
    (ArrayList<T> list,  spreadsheetTypes type, int max, String title, JFXProgressBar progressBar)
            throws IOException, InterruptedException{
    progressBar.progressProperty().setValue(0);
    switch (type){
        case rightToLeftColumnLimit:
            makeSpreadsheetRightToLeft(list, false, max, title, progressBar);
            break;
       ...
    }
}

static private <T extends Object> void makeSpreadsheetRightToLeft
    (ArrayList<T> list,  boolean maxRows, int max, String title, JFXProgressBar progressBar)
            throws IOException, InterruptedException{
    initializeChooser();
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Primus output");
    int rowPointer = 0;
    int columnPointer = 0;
    double progressIncrementValue = 1/(double)list.size();

    //Giving the spreadsheet an internal title also
    Row row = sheet.createRow(0);
    row.createCell(0).setCellValue(title);

    row = sheet.createRow(++rowPointer);

    //Making the sheet with a max column limit
    if (!maxRows){
        for (T number: list){
            if (columnPointer == max){
                columnPointer = 0;
                row = sheet.createRow(++rowPointer);
            }
            Cell cell = row.createCell(columnPointer++);
            progressBar.setProgress(progressBar.getProgress() + progressIncrementValue);
            cell.setCellValue(number.toString());
        }
    }else {
        //Making the sheet with a max row limit
        int columnWrapIndex = (int)Math.ceil(list.size()/(float)max);
        for (T number: list){
            if (columnPointer == columnWrapIndex){
                columnPointer = 0;
                row = sheet.createRow(++rowPointer);
            }
            Cell cell = row.createCell(columnPointer++);
            progressBar.setProgress(progressBar.getProgress() + progressIncrementValue);
            cell.setCellValue(number.toString());
        }
    }
    writeToExcel(workbook, progressBar);

}

static private void writeToExcel(XSSFWorkbook book, JFXProgressBar progressBar) throws IOException, InterruptedException{
    //Exporting to Excel
    int returnValue = fileManager.showSaveDialog(null);

    if (returnValue == JFileChooser.APPROVE_OPTION){
        File file = fileManager.getSelectedFile();

        //Validation logic here

        try{

            FileOutputStream out = new FileOutputStream(file);
            book.write(out);
            out.close();
            book.close();
        }catch (FileNotFoundException ex){

        }

    }
}
}

Afterwards, my FXML document controller has a buttonListerner which calls:

longCalculationThread thread = new longCalculationThread(threadBundle);
thread.start();

The longcalculationthread creates a list of about a million prime numbers and Exports them to the ExcelWriter using this code:

private void publishResults() throws IOException, InterruptedException{
    if (!longResults.isEmpty()){
        if (shouldExport) {
            progressText.setText("Exporting to Excel...");
            ExcelWriter.makeSpreadsheet(longResults, exportType, excelExportLimit, getTitle(), progressBar);

    }
   }

The problem is, even though the variable holding the workbook in the XSSF workbook is a local variable to the methods it is used in, it doesn't get garbage collected afterwards.

It takes up like 1.5GB of RAM (I don't know why), and that data is only reallocated when another huge export is called (not for small exports).
My problem isn't really that the thing takes a lot of RAM, it's that even when the methods are completed the memory isn't GCed.
Here are some pictures of my NetBeans profiles:

Normal memory usage when making array of 1000000 primes:

Huge heap usage when making workbook

Memory Isn't reallocated when workbook ins't accessible anymore

Fluctuation seen when making a new workbook using the same static methods


问:
Boruta box plots in R
I'm doing variable selection with the Boruta package in R. Boruta gives me the standard series of boxplots in a single graph, which is useful, but given the fact that I have too many predictors, I am hoping to be able to limit the number of boxplots that appear in the boruta plot.  Something like the following image.

Basicacly, I want to "zoom" on the right end of the plot, but have no idea how to do that with the boruta plot object.

Thanks,

MR

答:
Sounds like an simple question, the solution seems surprisingly convoluted. Perhaps somebody can come up with a quicker/more elegant way...

Here, I create a new function based on the source function plot.Boruta, and add a function argument pars that takes the names of variables/predictors that we'd like to include in the plot.

As an example, I use the iris dataset to fit a model.

```<code># Fit model to the iris dataset
library(Boruta);
fit <- Boruta(Species ~ ., data = iris, doTrace = 2);
</code>```

The function generateCol is internally called by plot.Boruta, but is not exported and therefore not available outside of the package. However, we need the function for our revised plot.Boruta routine.

```<code># generateCol is needed by plot.Boruta
generateCol<-function(x,colCode,col,numShadow){
 #Checking arguments
 if(is.null(col) & length(colCode)!=4)
  stop('colCode should have 4 elements.');
 #Generating col
 if(is.null(col)){
  rep(colCode[4],length(x$finalDecision)+numShadow)->cc;
  cc[c(x$finalDecision=='Confirmed',rep(FALSE,numShadow))]<-colCode[1];
  cc[c(x$finalDecision=='Tentative',rep(FALSE,numShadow))]<-colCode[2];
  cc[c(x$finalDecision=='Rejected',rep(FALSE,numShadow))]<-colCode[3];
  col=cc;
 }
 return(col);
}
</code>```

We now modify plot.Boruta, and add a function parameter pars, by which we filter our list of variables.

```<code># Modified plot.Boruta
plot.Boruta.sel <- function(
    x,
    pars = NULL,
    colCode = c('green','yellow','red','blue'),
    sort = TRUE,
    whichShadow = c(TRUE, TRUE, TRUE),
    col = NULL, xlab = 'Attributes', ylab = 'Importance', ...) {

    #Checking arguments
    if(class(x)!='Boruta')
        stop('This function needs Boruta object as an argument.');
    if(is.null(x$ImpHistory))
        stop('Importance history was not stored during the Boruta run.');

    #Removal of -Infs and conversion to a list
    lz <- lapply(1:ncol(x$ImpHistory), function(i)
        x$ImpHistory[is.finite(x$ImpHistory[,i]),i]);
    colnames(x$ImpHistory)->names(lz);

    #Selection of shadow meta-attributes
    numShadow <- sum(whichShadow);
    lz <- lz[c(rep(TRUE,length(x$finalDecision)), whichShadow)];

    #Generating color vector
    col <- generateCol(x, colCode, col, numShadow);

    #Ordering boxes due to attribute median importance
    if (sort) {
        ii <- order(sapply(lz, stats::median));
        lz <- lz[ii];
        col <- col[ii];
    }

    # Select parameters of interest
    if (!is.null(pars)) lz <- lz[names(lz) %in% pars];

    #Final plotting
    graphics::boxplot(lz, xlab = xlab, ylab = ylab, col = col, ...);
    invisible(x);
}
</code>```

Now all we need to do is call plot.Boruta.sel instead of plot, and specify the variables that we'd like to include.

```<code>plot.Boruta.sel(fit, pars = c("Sepal.Length", "Sepal.Width"));
</code>```

Title: Boruta box plots in R

Body:
Sounds like an simple question, the solution seems surprisingly convoluted. Perhaps somebody can come up with a quicker/more elegant way...

Here, I create a new function based on the source function plot.Boruta, and add a function argument pars that takes the names of variables/predictors that we'd like to include in the plot.

As an example, I use the iris dataset to fit a model.

# Fit model to the iris dataset
library(Boruta);
fit <- Boruta(Species ~ ., data = iris, doTrace = 2);

The function generateCol is internally called by plot.Boruta, but is not exported and therefore not available outside of the package. However, we need the function for our revised plot.Boruta routine.

# generateCol is needed by plot.Boruta
generateCol<-function(x,colCode,col,numShadow){
 #Checking arguments
 if(is.null(col) & length(colCode)!=4)
  stop('colCode should have 4 elements.');
 #Generating col
 if(is.null(col)){
  rep(colCode[4],length(x$finalDecision)+numShadow)->cc;
  cc[c(x$finalDecision=='Confirmed',rep(FALSE,numShadow))]<-colCode[1];
  cc[c(x$finalDecision=='Tentative',rep(FALSE,numShadow))]<-colCode[2];
  cc[c(x$finalDecision=='Rejected',rep(FALSE,numShadow))]<-colCode[3];
  col=cc;
 }
 return(col);
}

We now modify plot.Boruta, and add a function parameter pars, by which we filter our list of variables.

# Modified plot.Boruta
plot.Boruta.sel <- function(
    x,
    pars = NULL,
    colCode = c('green','yellow','red','blue'),
    sort = TRUE,
    whichShadow = c(TRUE, TRUE, TRUE),
    col = NULL, xlab = 'Attributes', ylab = 'Importance', ...) {

    #Checking arguments
    if(class(x)!='Boruta')
        stop('This function needs Boruta object as an argument.');
    if(is.null(x$ImpHistory))
        stop('Importance history was not stored during the Boruta run.');

    #Removal of -Infs and conversion to a list
    lz <- lapply(1:ncol(x$ImpHistory), function(i)
        x$ImpHistory[is.finite(x$ImpHistory[,i]),i]);
    colnames(x$ImpHistory)->names(lz);

    #Selection of shadow meta-attributes
    numShadow <- sum(whichShadow);
    lz <- lz[c(rep(TRUE,length(x$finalDecision)), whichShadow)];

    #Generating color vector
    col <- generateCol(x, colCode, col, numShadow);

    #Ordering boxes due to attribute median importance
    if (sort) {
        ii <- order(sapply(lz, stats::median));
        lz <- lz[ii];
        col <- col[ii];
    }

    # Select parameters of interest
    if (!is.null(pars)) lz <- lz[names(lz) %in% pars];

    #Final plotting
    graphics::boxplot(lz, xlab = xlab, ylab = ylab, col = col, ...);
    invisible(x);
}

Now all we need to do is call plot.Boruta.sel instead of plot, and specify the variables that we'd like to include.

plot.Boruta.sel(fit, pars = c("Sepal.Length", "Sepal.Width"));


答:
  let data = await
    Promise.all([
        res_fetch.get_users().then(result => {
            ctx.res.write(result)
        }),
        res_fetch.get_posts().then(result => {
            ctx.res.write(result)
        }),
    ])

    ctx.res.write("")
    ctx.res.end()```

Title: Can Promise.all handle results as soon as possible, not waiting for all promises done

Body:
  let data = await
    Promise.all([
        res_fetch.get_users().then(result => {
            ctx.res.write(result)
        }),
        res_fetch.get_posts().then(result => {
            ctx.res.write(result)
        }),
    ])

    ctx.res.write("</body></html>")
    ctx.res.end()


问:
SIPP Scenario (version 1.0 don't send digits)
Folks,
I am trying to make calls to test a IVR Machine with SIPP.
First, I am using the Sipp v1.0 final version. But this version does not have support to send digits to IVR Machine. So system is unable to answer calls.
I tested using other versions too.

Here is my scenario:

```<code><!DOCTYPE scenario SYSTEM "sipp.dtd">

<scenario name="Basic Sipstone UAC">

<send>

<![CDATA[

INVITE sip:12053@10.0.8.67 SIP/2.0
Via: SIP/2.0/UDP 10.0.4.147:5060;rport;branch=z9hG4bK386088
From: "sipp" <sip:11958251026@10.0.4.147:5070>;tag=8808
To: <sip:12053@10.0.8.67>
Call-ID: 1510678743-6088-NVT4147@10.0.4.147
CSeq: 45 INVITE

Max-Forwards: 70
User-Agent: NCH Software Express Talk 4.28
Contact: <sip:11958251026@10.0.4.147:5060>
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, INFO, REFER, NOTIFY
Supported: replaces
Content-Type: application/sdp
Content-Length: 328
v=0
o=NCHSoftware-Talk 1510678729 1510678743 IN IP4 10.0.4.147
s=Express Talk Call
c=IN IP4 10.0.4.147
t=0 0
m=audio 8000 RTP/AVP 0 8 96 3 13 101
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:96 G726-32/8000
a=rtpmap:3 GSM/8000
a=rtpmap:13 CN/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-16
a=sendrecv

]]>

</send>

<recv response="100" optional="true">
</recv>

<recv response="180" optional="true">
</recv>

<recv response="183" optional="true">
</recv>

<recv response="200">
</recv>

<send>

<![CDATA[

ACK sip:12053@10.0.8.67:5060;user=phone SIP/2.0
Via: SIP/2.0/UDP 10.0.4.147:5060;rport;branch=z9hG4bK396088
To: <sip:12053@10.0.8.67>;tag=7831-08A1
From: "sipp" <sip:11958251026@10.0.4.147:5070>;tag=8808
Call-ID: 1510678743-6088-NVT4147@10.0.4.147
CSeq: 45 ACK
Max-Forwards: 20
User-Agent: NCH Software Express Talk 4.28
Content-Length: 0

]]>

</send>
<nop>
<action>
<exec play_pcap_audio="pcap/g711a.pcap"/>
</action>
</nop>
<pause milliseconds="8000"/>
<nop>
<action>
<exec play_pcap_audio="pcap/dtmf_2833_1.pcap"/>
</action>
</nop>
<pause milliseconds="3000"/>
<send>
<![CDATA[
BYE sip:12053@10.0.8.67:5060;user=phone SIP/2.0
Via: SIP/2.0/UDP 10.0.4.147:5060;rport;branch=z9hG4bK26088
From: "sipp" <sip:11958251026@10.0.4.147:5070>;tag=8795
To: <sip:12053@10.0.8.67>;tag=7831-2E51
Call-ID: 1510678730-6088-NVT4147@10.0.4.147
CSeq: 107 BYE
Max-Forwards: 20
Subject: Performance Test
Content-Length: 0
]]>
</send>
<recv response="200" crlf="true">
</recv>
<ResponseTimeRepartition value="10, 20, 30, 40, 50, 100, 150, 200"/>
<CallLengthRepartition value="10, 50, 100, 500, 1000, 5000, 10000"/>
</scenario>
</code>```

But, the answer is that (when I am using de version 1.0):

2017-11-16 19:31:46: Unknown element 'nop' in xml scenario file.

Please, help me.

答:
SIPP can do complex SIP scripts but it is very limited for Voice interactions...

If you plan to test the IVR with Voice/DTMF interactions, try with Asterisk.
You can use a Dialer Script (We can provide one) to apply to your IVR a charge, with a Dialpan you can create complex scripting (with random).

Body:
Folks,
I am trying to make calls to test a IVR Machine with SIPP.
First, I am using the Sipp v1.0 final version. But this version does not have support to send digits to IVR Machine. So system is unable to answer calls.
I tested using other versions too.

Here is my scenario:

<!DOCTYPE scenario SYSTEM "sipp.dtd">

<scenario name="Basic Sipstone UAC">

<send>

<![CDATA[

INVITE sip:12053@10.0.8.67 SIP/2.0
Via: SIP/2.0/UDP 10.0.4.147:5060;rport;branch=z9hG4bK386088
From: "sipp" <sip:11958251026@10.0.4.147:5070>;tag=8808
To: <sip:12053@10.0.8.67>
Call-ID: 1510678743-6088-NVT4147@10.0.4.147
CSeq: 45 INVITE

Max-Forwards: 70
User-Agent: NCH Software Express Talk 4.28
Contact: <sip:11958251026@10.0.4.147:5060>
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, INFO, REFER, NOTIFY
Supported: replaces
Content-Type: application/sdp
Content-Length: 328
v=0
o=NCHSoftware-Talk 1510678729 1510678743 IN IP4 10.0.4.147
s=Express Talk Call
c=IN IP4 10.0.4.147
t=0 0
m=audio 8000 RTP/AVP 0 8 96 3 13 101
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:96 G726-32/8000
a=rtpmap:3 GSM/8000
a=rtpmap:13 CN/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-16
a=sendrecv

]]>

</send>

<recv response="100" optional="true">
</recv>

<recv response="180" optional="true">
</recv>

<recv response="183" optional="true">
</recv>

<recv response="200">
</recv>

<send>

<![CDATA[

ACK sip:12053@10.0.8.67:5060;user=phone SIP/2.0
Via: SIP/2.0/UDP 10.0.4.147:5060;rport;branch=z9hG4bK396088
To: <sip:12053@10.0.8.67>;tag=7831-08A1
From: "sipp" <sip:11958251026@10.0.4.147:5070>;tag=8808
Call-ID: 1510678743-6088-NVT4147@10.0.4.147
CSeq: 45 ACK
Max-Forwards: 20
User-Agent: NCH Software Express Talk 4.28
Content-Length: 0

]]>

</send>
<nop>
<action>
<exec play_pcap_audio="pcap/g711a.pcap"/>
</action>
</nop>
<pause milliseconds="8000"/>
<nop>
<action>
<exec play_pcap_audio="pcap/dtmf_2833_1.pcap"/>
</action>
</nop>
<pause milliseconds="3000"/>
<send>
<![CDATA[
BYE sip:12053@10.0.8.67:5060;user=phone SIP/2.0
Via: SIP/2.0/UDP 10.0.4.147:5060;rport;branch=z9hG4bK26088
From: "sipp" <sip:11958251026@10.0.4.147:5070>;tag=8795
To: <sip:12053@10.0.8.67>;tag=7831-2E51
Call-ID: 1510678730-6088-NVT4147@10.0.4.147
CSeq: 107 BYE
Max-Forwards: 20
Subject: Performance Test
Content-Length: 0
]]>
</send>
<recv response="200" crlf="true">
</recv>
<ResponseTimeRepartition value="10, 20, 30, 40, 50, 100, 150, 200"/>
<CallLengthRepartition value="10, 50, 100, 500, 1000, 5000, 10000"/>
</scenario>

But, the answer is that (when I am using de version 1.0):

2017-11-16 19:31:46: Unknown element 'nop' in xml scenario file.

Please, help me.


问:
In Tableau, how do I use two parts of a pivotted column for x and y values on a graph?
I'm trying to plot some data (standard curves for analytical chemistry) where the x axis is the mass of a compound I added to a solution, and the y axis is the signal recorded from an instrument (peak height on a mass spectrometer). I'd like Tableau to color code the data by compound (compound A, compound B, compound C, etc.), so that I'd wind up with a graph that looks something like this:

The original structure of my data was like this:

```<code> SampleID   | Mass A | Mass B | ... | Signal A | Signal B | ...
 standard 0 |       0|       0| ... |         0|         0| ...
 standard 5 |   2.535|   2.555| ... |     0.494|     1.240| ...
 standard 25|  12.675|  12.775| ... |     2.426|     7.235| ...
</code>```

I know how to make graphs one compound at a time with these original data, but for the purposes of other analyses I'm doing with these data and because I want multiple compounds on the same graph, I've pivotted them so that the structure is now like this:

```<code> SampleID   | Compound | Parameter | Value
 standard 0 | A        | Mass      |     0
 standard 0 | A        | Signal    |     0
 standard 5 | A        | Mass      | 2.535
</code>```

etc.

How do I make a graph where the mass is on the x axis, the signal is on the y axis, and the points are colored by compound? I don't see a good way to do it when my data are in this format. I've tried making new calculated variables where the value = NULL if the parameter is not equal to "Mass" and another calculated variable where the value = NULL if the parameter is not equal to "Signal" and then putting those pills on the columns and rows, but that's not working. Is there a way to do this in Tableau with data structured like this pivotted form?

Alternatively, is there a way to spread my pivotted data so that the new structure is like this:

```<code> SampleID   | Compound | Mass  |  Signal
 standard 0 | A        |      0|       0
 standard 5 | A        |  2.535|   0.494
 standard 25| A        | 12.675|   2.426
 standard 0 | B        |      0|       0
</code>```

etc.

and would that work better?

(For R users, that last bit would be the equivalent of the tidyr package gather and spread functions.)

答:
If I had to deal with this, I'd prefer to pre-process the data so that it has the format "SampleID   | Compound | Mass  |  Signal", that would make Tableau chart straightforward.

I think there's a way to achieve the same with the data structure you have, but it's more tricky. So, if I understand correctly, you have the data it this form:

```<code>SampleId    Compound    Parameter   Value
standard 5  A           Mass        2.535
standard 5  A           Signal      0.494
standard 5  B           Mass        2.555
standard 5  B           Signal      1.24
standard 25 A           Mass        12.675
standard 25 A           Signal      2.426
standard 25 B           Mass        12.775
standard 25 B           Signal      7.235
</code>```

1) You can create calculated fields for Mass and Signal using level of detail expressions, that exclude the Parameter granularity:

```<code>Mass
{exclude [Parameter] : min(if [Parameter] = 'Mass' then [Value] else NULL end)}

Signal
{exclude [Parameter] : min(if [Parameter] = 'Signal' then [Value] else NULL end)}
</code>```

That will "collapse" nulls in case Parameter is not included in the view.

2) Using the Scatter Plot visualization, you can pull Mass to columns and Signal to rows, add Compound to Color pane and SampleId to Detail pane. The plot will look like this:

Body:
I'm trying to plot some data (standard curves for analytical chemistry) where the x axis is the mass of a compound I added to a solution, and the y axis is the signal recorded from an instrument (peak height on a mass spectrometer). I'd like Tableau to color code the data by compound (compound A, compound B, compound C, etc.), so that I'd wind up with a graph that looks something like this:

The original structure of my data was like this:

 SampleID   | Mass A | Mass B | ... | Signal A | Signal B | ...
 standard 0 |       0|       0| ... |         0|         0| ...
 standard 5 |   2.535|   2.555| ... |     0.494|     1.240| ...
 standard 25|  12.675|  12.775| ... |     2.426|     7.235| ...

I know how to make graphs one compound at a time with these original data, but for the purposes of other analyses I'm doing with these data and because I want multiple compounds on the same graph, I've pivotted them so that the structure is now like this:

 SampleID   | Compound | Parameter | Value
 standard 0 | A        | Mass      |     0
 standard 0 | A        | Signal    |     0
 standard 5 | A        | Mass      | 2.535

etc.

How do I make a graph where the mass is on the x axis, the signal is on the y axis, and the points are colored by compound? I don't see a good way to do it when my data are in this format. I've tried making new calculated variables where the value = NULL if the parameter is not equal to "Mass" and another calculated variable where the value = NULL if the parameter is not equal to "Signal" and then putting those pills on the columns and rows, but that's not working. Is there a way to do this in Tableau with data structured like this pivotted form?

Alternatively, is there a way to spread my pivotted data so that the new structure is like this:

 SampleID   | Compound | Mass  |  Signal
 standard 0 | A        |      0|       0
 standard 5 | A        |  2.535|   0.494
 standard 25| A        | 12.675|   2.426
 standard 0 | B        |      0|       0

etc.

and would that work better?

(For R users, that last bit would be the equivalent of the tidyr package gather and spread functions.)

Body:
If I had to deal with this, I'd prefer to pre-process the data so that it has the format "SampleID   | Compound | Mass  |  Signal", that would make Tableau chart straightforward.

I think there's a way to achieve the same with the data structure you have, but it's more tricky. So, if I understand correctly, you have the data it this form:

SampleId    Compound    Parameter   Value
standard 5  A           Mass        2.535
standard 5  A           Signal      0.494
standard 5  B           Mass        2.555
standard 5  B           Signal      1.24
standard 25 A           Mass        12.675
standard 25 A           Signal      2.426
standard 25 B           Mass        12.775
standard 25 B           Signal      7.235

1) You can create calculated fields for Mass and Signal using level of detail expressions, that exclude the Parameter granularity:

Mass
{exclude [Parameter] : min(if [Parameter] = 'Mass' then [Value] else NULL end)}

Signal
{exclude [Parameter] : min(if [Parameter] = 'Signal' then [Value] else NULL end)}

That will "collapse" nulls in case Parameter is not included in the view.

2) Using the Scatter Plot visualization, you can pull Mass to columns and Signal to rows, add Compound to Color pane and SampleId to Detail pane. The plot will look like this:


问:
How to configure my solution to show all projects collapsed on Visual Studio?
Every time I check out my solution from the SCM I have to collapse manually each project in my solution to get a good overview of it.

I know that the collapsed settings are stored in a .suo file, which is binary. I don't want to commit this file to the SCM, instead I am looking for a xml tag that I could put in the .sln file so when I open it all projects are collapsed.

How to do that?

答: Install DPack for Visual Studio and use the "collapse all projects" context menu item ;-)</p>


问:
Unable to use devise_token_auth with active_admin
I'm trying to used devise_token_auth with active_admin. When running rails g active_admin:install User I get the following error.

error

usr/local/lib/ruby/gems/2.4.0/gems/actionpack-5.1.4/lib/action_dispatch/routing/route_set.rb:578:in
  add_route': Invalid route name, already in use: 'new_user_session'
  You may have defined two routes with the same name using the:as`
  option, or you may be overriding a route already defined by a resource
  with the same naming.

routes.rb

```<code>Rails.application.routes.draw do
  devise_for :users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  mount_devise_token_auth_for 'User', at: 'auth'

  scope module: 'api' do
    namespace :v1 do
      resources :users, only: [:index, :show]
    end
  end

  get '/docs' => redirect('/swagger/dist/index.html?url=/apidocs/api-docs.json')
end
</code>```

答:
I got it working by moving mount_devise_token_auth_for 'User', at: 'auth'
 into the api scope. The answer was right , here.

```<code>Rails.application.routes.draw do
  devise_for :users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)

  constraints subdomain: 'api'do
    scope module: 'api' do
      namespace :v1 do
        resources :users, only: [:index, :show]
        mount_devise_token_auth_for 'User', at: 'auth'
      end
    end

    get '/docs' => redirect('/swagger/dist/index.html?url=/apidocs/api-docs.json')
  end
end
</code>```

Body:
I'm trying to used devise_token_auth with active_admin. When running rails g active_admin:install User I get the following error.

error

usr/local/lib/ruby/gems/2.4.0/gems/actionpack-5.1.4/lib/action_dispatch/routing/route_set.rb:578:in
  add_route': Invalid route name, already in use: 'new_user_session'
  You may have defined two routes with the same name using the:as`
  option, or you may be overriding a route already defined by a resource
  with the same naming.

routes.rb

Rails.application.routes.draw do
  devise_for :users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  mount_devise_token_auth_for 'User', at: 'auth'

  scope module: 'api' do
    namespace :v1 do
      resources :users, only: [:index, :show]
    end
  end

  get '/docs' => redirect('/swagger/dist/index.html?url=/apidocs/api-docs.json')
end

Body:
I got it working by moving mount_devise_token_auth_for 'User', at: 'auth'
 into the api scope. The answer was right , here.

Rails.application.routes.draw do
  devise_for :users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)

  constraints subdomain: 'api'do
    scope module: 'api' do
      namespace :v1 do
        resources :users, only: [:index, :show]
        mount_devise_token_auth_for 'User', at: 'auth'
      end
    end

    get '/docs' => redirect('/swagger/dist/index.html?url=/apidocs/api-docs.json')
  end
end


问:
How to check if two tables are structurally same?
I have two tables in a SQL Server database. I want to check if these two tables are structurally same. I used UNION/ EXCEPT operator to check this and found that these two tables are not identical.

Here are my questions:

How do we know if two tables are the same in structure?

If they are not same, how do we get the details of differences? If a column is missing in one table how do we get the name of the missing column?

If there is a data type mismatch between a column in these two tables, can we get the name of the column with different data type?

答:
as @jarlh commented. you can find the info in information_schema.columns
or,

you could use this tool called sql-dbdiff : https://code.google.com/archive/p/sql-dbdiff/

For more idea, you could reffer this discussion: Easiest Way To Diff Two Table Schemas In SQL Server 2008?


问:
Linq query to Join tables if value not in first table fetch from second
I have 2 lists with below structure.

```<code>public class Team
{
    public string Id { get; set; }
    public Driver Driver { get; set; }
    public Driver Codriver { get; set; }
}

public class Driver
{
    public string DriverId { get; set; }
}

var modifiedTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D2" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D1"} }
};

var allTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D1" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D2"}, Codriver = new Driver { DriverId = "C2"} }
};
</code>```

I want to get all the Id's of driver and codriver from modifiedTeams but if driver/codriver is not there in modifiedTeams then fetch it from allTeams based on Team ids(T1,T2) Eg: Id of codriver from Team T2

Final Output:

```<code>{D2,C1,D1,C2}
</code>```

Can some one help me how I could achieve this via LINQ(Lambda expressions) in C#.

Simple C# code:-

```<code>List<string> allDriverCodriverIds = new List<string>();
foreach (var team in modifiedTeams)
{
    if (team.Driver != null && !string.IsNullOrEmpty(team.Driver.DriverId))
    {
        allDriverCodriverIds.Add(team.Driver.DriverId);
    }
    else {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Driver != null && !string.IsNullOrEmpty(existingTeam.Driver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Driver.DriverId);
        }
    }
    if (team.Codriver != null && !string.IsNullOrEmpty(team.Codriver.DriverId))
    {
        allDriverCodriverIds.Add(team.Codriver.DriverId);
    }
    else
    {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Codriver != null && !string.IsNullOrEmpty(existingTeam.Codriver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Codriver.DriverId);
        }
    }
}
</code>```

答:
Ok, apparently you have a method to check whether a Driver is "not there" and whether a CoDriver is "not there". Although you don't specify when a Driver is not there, from your exemple I gather that this is if the property equals null.

But let's assume a Team has two functions:

```<code>bool DriverIsThere();
bool CoDriverIsThere();
</code>```

Now you have a sequence of TeamIds, and you want to every TeamId to produce the DriverIds of two Drivers

If there is a modifiedTeam with TeamId:
  1 If IsDriverThere(), produce Driver.DriverId, else find the Team from the collection of AllTeams with the same Id and return Driver.DriverId
  2 If IsCodDriverThere(), produce CoDriver.DriverId, else find the Teadm from the collection of AllTeams with the same 'Id' and produce 'CoDriver.DriverId`.

You didn't mention what to do if there is no modifiedTeam with the requested Id, or if there is no AllTeams with this Id. Let's assume you want to throw exception.

This code for this requirement could be written in one LINQ statement. And I'm sure others will try to answer it this way. As an alternative, I'd like to promote the Yield method, because I think in this case it would be much more readable and maintainable.

I assume your IDs are unique. To enhance lookup, I'll put your modifiedTeams and allTeams into dictionaries, to enhance lookup.

I don't want to change your classes, so let's use extension methods.

See Extension Methods Demystified

Let's first define IsThere:

```<code>// returns true if Driver "is there"
public static bool IsThere(this Driver driver)
{
     return driver != null;
    // might be for some other reason, for instance: && !driver.IsSick
}
</code>```

The function that takes a Team, and produces the two DriverIdsaccording to the requirements defined above is fairly straightforward:

```<code>public static IEnumerable<string> ToDriverIds(this Team team,
    Dictionary<string, Team> allTeams)
{
    if (team.Driver.IsThere())
        // Driver is there, yield return the Id
        yield return team.Driver.DriverId;
    else
    {   // Driver not available, fetch the Driver from allTeams
        // throw exception if there is no alternative team with this team ID
        Team alternativeTeam = allTeams[team.Id];
        if (alternativeTeam.IsDriverThere())
            yield return alternativeTeam.Driver.Id;
        else
           // Driver also not in alternative team: exception
           throw new InvalidOperationException("...");

        // do the same for coDriver
    }
}
</code>```

An even nicer method: use a delegate to select whether you want the Driver or the Codriver:

```<code>public static Driver ToDriver(this Team team,
    Dictionary<string, Team> allTeams,
    Func<Team, Driver> driverSelector)
{
    Driver driver = driverSelector(team);
    if (driver.IsThere())
        return driver.Id;
    else
    {   // use allTeams:
        Team allternativeTeam = allTeams[team.Id];
        driver = friverSelector(alternativeTeam);
        if (driver.IsThere())
            return driver.Id;
        else
            throw new InvalidOperationException(...);
    }
}
</code>```

Usage:

```<code>public static IEnumerable<string> ToDriverIds(this Team,
   Dictionary<string, Team> allTeams)
{
    // return the driverId of the driver:
    yield return Team.ToDriverId(allTeams, team => team.Driver);
    // yield return the driverId of the CoDriver:
    yield return Team.ToDriverId(allTeams, team => team.CoDriver);
}
</code>```

Now from teamId to the requested driverIds:

```<code>public static IEnumerable<string> ToDriverIds(this string teamId,
    Dictionary<string, Team> modifiedTeams
    Dictionary<string, Team> allTeams)
{
    return modifiedTeams[teamId].ToDriverids(allTeams);
    // exception if there is no team with teamId
}
</code>```

After all this, the final function that takes a sequence of teamIds, the modifiedTeams, and allTeams and converts into the requested output is a short one:

```<code>public static IEnumerable<string> ToIds(this IEnumerable<string> teamIds,
   IEnumerable<Team> modifiedTeams, IEnumerable<Team> allTeams)
{
    var modifiedTeamsLookup = modifiedTeams.ToDictionary(team => team.Id);
    var allTeamsLookup = allTeams.ToDictionary(team => team.Id);

    return teamIds
        .SelectMany(teamId => teamId.ToDriverIds(modifiedTeamsLookup,
            allTeamsLookup);

}
</code>```

Body:
I have 2 lists with below structure.

public class Team
{
    public string Id { get; set; }
    public Driver Driver { get; set; }
    public Driver Codriver { get; set; }
}

public class Driver
{
    public string DriverId { get; set; }
}

var modifiedTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D2" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D1"} }
};

var allTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D1" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D2"}, Codriver = new Driver { DriverId = "C2"} }
};

I want to get all the Id's of driver and codriver from modifiedTeams but if driver/codriver is not there in modifiedTeams then fetch it from allTeams based on Team ids(T1,T2) Eg: Id of codriver from Team T2

Final Output:

{D2,C1,D1,C2}

Can some one help me how I could achieve this via LINQ(Lambda expressions) in C#.

Simple C# code:-

List<string> allDriverCodriverIds = new List<string>();
foreach (var team in modifiedTeams)
{
    if (team.Driver != null && !string.IsNullOrEmpty(team.Driver.DriverId))
    {
        allDriverCodriverIds.Add(team.Driver.DriverId);
    }
    else {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Driver != null && !string.IsNullOrEmpty(existingTeam.Driver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Driver.DriverId);
        }
    }
    if (team.Codriver != null && !string.IsNullOrEmpty(team.Codriver.DriverId))
    {
        allDriverCodriverIds.Add(team.Codriver.DriverId);
    }
    else
    {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Codriver != null && !string.IsNullOrEmpty(existingTeam.Codriver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Codriver.DriverId);
        }
    }
}

Body:
Ok, apparently you have a method to check whether a Driver is "not there" and whether a CoDriver is "not there". Although you don't specify when a Driver is not there, from your exemple I gather that this is if the property equals null.

But let's assume a Team has two functions:

bool DriverIsThere();
bool CoDriverIsThere();

Now you have a sequence of TeamIds, and you want to every TeamId to produce the DriverIds of two Drivers

If there is a modifiedTeam with TeamId:
  1 If IsDriverThere(), produce Driver.DriverId, else find the Team from the collection of AllTeams with the same Id and return Driver.DriverId
  2 If IsCodDriverThere(), produce CoDriver.DriverId, else find the Teadm from the collection of AllTeams with the same 'Id' and produce 'CoDriver.DriverId`.

You didn't mention what to do if there is no modifiedTeam with the requested Id, or if there is no AllTeams with this Id. Let's assume you want to throw exception.

This code for this requirement could be written in one LINQ statement. And I'm sure others will try to answer it this way. As an alternative, I'd like to promote the Yield method, because I think in this case it would be much more readable and maintainable.

I assume your IDs are unique. To enhance lookup, I'll put your modifiedTeams and allTeams into dictionaries, to enhance lookup.

I don't want to change your classes, so let's use extension methods.

See Extension Methods Demystified

Let's first define IsThere:

// returns true if Driver "is there"
public static bool IsThere(this Driver driver)
{
     return driver != null;
    // might be for some other reason, for instance: && !driver.IsSick
}

The function that takes a Team, and produces the two DriverIdsaccording to the requirements defined above is fairly straightforward:

public static IEnumerable<string> ToDriverIds(this Team team,
    Dictionary<string, Team> allTeams)
{
    if (team.Driver.IsThere())
        // Driver is there, yield return the Id
        yield return team.Driver.DriverId;
    else
    {   // Driver not available, fetch the Driver from allTeams
        // throw exception if there is no alternative team with this team ID
        Team alternativeTeam = allTeams[team.Id];
        if (alternativeTeam.IsDriverThere())
            yield return alternativeTeam.Driver.Id;
        else
           // Driver also not in alternative team: exception
           throw new InvalidOperationException("...");

        // do the same for coDriver
    }
}

An even nicer method: use a delegate to select whether you want the Driver or the Codriver:

public static Driver ToDriver(this Team team,
    Dictionary<string, Team> allTeams,
    Func<Team, Driver> driverSelector)
{
    Driver driver = driverSelector(team);
    if (driver.IsThere())
        return driver.Id;
    else
    {   // use allTeams:
        Team allternativeTeam = allTeams[team.Id];
        driver = friverSelector(alternativeTeam);
        if (driver.IsThere())
            return driver.Id;
        else
            throw new InvalidOperationException(...);
    }
}

Usage:

public static IEnumerable<string> ToDriverIds(this Team,
   Dictionary<string, Team> allTeams)
{
    // return the driverId of the driver:
    yield return Team.ToDriverId(allTeams, team => team.Driver);
    // yield return the driverId of the CoDriver:
    yield return Team.ToDriverId(allTeams, team => team.CoDriver);
}

Now from teamId to the requested driverIds:

public static IEnumerable<string> ToDriverIds(this string teamId,
    Dictionary<string, Team> modifiedTeams
    Dictionary<string, Team> allTeams)
{
    return modifiedTeams[teamId].ToDriverids(allTeams);
    // exception if there is no team with teamId
}

After all this, the final function that takes a sequence of teamIds, the modifiedTeams, and allTeams and converts into the requested output is a short one:

public static IEnumerable<string> ToIds(this IEnumerable<string> teamIds,
   IEnumerable<Team> modifiedTeams, IEnumerable<Team> allTeams)
{
    var modifiedTeamsLookup = modifiedTeams.ToDictionary(team => team.Id);
    var allTeamsLookup = allTeams.ToDictionary(team => team.Id);

    return teamIds
        .SelectMany(teamId => teamId.ToDriverIds(modifiedTeamsLookup,
            allTeamsLookup);

}


问:
javascript errors when i call a function with String as parameter
can you tell me what I'm doing bad? I'm calling a javascript function from a html page managed by laravel but it returns me all time Uncaught SyntaxError: missing ) after argument list or Uncaught SyntaxError: Invalid or unexpected token when I put in between quotation marks the return of $connexio->dispositiu->descendents()["credencial"].

$connexio->dispositiu->descendents()["credencial"] returns me that:

```<code>return [
        [
            'id' => 22,
            'tipus' => 'Antena',
            'name' => 'Ubikiti',
            'tab' => 0,
            'credencial' => "'".Dispositiu::find(22)->credencial->__toString()."'"
        ],......
</code>```

Dispositiu::find(22)->credencial->__toString() returns me the next:

```<code>{
    $text = "IP: $this->ip:$this->port\n".
        "IP Interna: $this->ip_interna\n".
        "User: $this->user\n".
        "Password: $this->pass\n".
        "Observacions: $this->observacio\n\n".
        $this->credenciable->__toString();
    return $text;
}
</code>```

The next code is in the html page.

```<code><?php $comptador = 2 ?>
@foreach($connexio->dispositiu->descendents() as $fill)
    <tr class="<?php if($comptador%2 == 0) echo 'par'; else echo'impar'; $comptador++;?>"
        title="{{ $fill["credencial"] }}">
        <td class="connexioTab{{$fill["tab"]}} ">{{$fill["tipus"]}}</td>
        <td class="connexioTab{{$fill["tab"]}} ">{{$fill["name"]}}</td>
        <td>
            <a onclick="mostraInformacio({{ $fill["credencial"]}})"><i class="fa fa-unlock" aria-hidden="true"></i></a>
        </td>
    </tr>
@endforeach
</code>```

The javascript function is:

```<code>function mostraInformacio(info){
    if(typeof info === "undefined") info = 'No credential found!';
    console.log(info);
    alert(info);
}
</code>```

Can you tell me what is the error? When I execute dd($fill["credencial"); it returns me the String, but between 6 quotation marks """ String.... """. Can be that the error?

答:
I found the error. It was in my PHP code,__toString() method of 'Dispositiu->credencial' had code similar like this:

```<code>$text = "IP: $this->ip:$this->port\n".
    "IP interna: $this->ip_interna\n".
    "User: $this->user\n".
    "Pass: $this->pass\n".
    "Observació: $this->observacio\n".
    $this->credenciable->__toString();
return $text;
</code>```

I changed the form to input new lines to this:

```<code>$text = "IP: $this->ip:$this->port".'\n'.
    "IP interna: $this->ip_interna".'\n'.
    "User: $this->user".'\n'.
    "Pass: $this->pass".'\n'.
    "Observació: $this->observacio".'\n\n'.
    $this->credenciable->__toString();
return $text;
</code>```

And it works, I can see the string into alert javascript.

Thanks to all who tried to help me.

Body:
can you tell me what I'm doing bad? I'm calling a javascript function from a html page managed by laravel but it returns me all time Uncaught SyntaxError: missing ) after argument list or Uncaught SyntaxError: Invalid or unexpected token when I put in between quotation marks the return of $connexio->dispositiu->descendents()["credencial"].

$connexio->dispositiu->descendents()["credencial"] returns me that:

return [
        [
            'id' => 22,
            'tipus' => 'Antena',
            'name' => 'Ubikiti',
            'tab' => 0,
            'credencial' => "'".Dispositiu::find(22)->credencial->__toString()."'"
        ],......

Dispositiu::find(22)->credencial->__toString() returns me the next:

{
    $text = "IP: $this->ip:$this->port\n".
        "IP Interna: $this->ip_interna\n".
        "User: $this->user\n".
        "Password: $this->pass\n".
        "Observacions: $this->observacio\n\n".
        $this->credenciable->__toString();
    return $text;
}

The next code is in the html page.

<?php $comptador = 2 ?>
@foreach($connexio->dispositiu->descendents() as $fill)
    <tr class="<?php if($comptador%2 == 0) echo 'par'; else echo'impar'; $comptador++;?>"
        title="{{ $fill["credencial"] }}">
        {{$fill["tipus"]}}
        {{$fill["name"]}}

@endforeach

The javascript function is:

function mostraInformacio(info){
    if(typeof info === "undefined") info = 'No credential found!';
    console.log(info);
    alert(info);
}

Can you tell me what is the error? When I execute dd($fill["credencial"); it returns me the String, but between 6 quotation marks """ String.... """. Can be that the error?

Body:
I found the error. It was in my PHP code,__toString() method of 'Dispositiu->credencial' had code similar like this:

$text = "IP: $this->ip:$this->port\n".
    "IP interna: $this->ip_interna\n".
    "User: $this->user\n".
    "Pass: $this->pass\n".
    "Observació: $this->observacio\n".
    $this->credenciable->__toString();
return $text;

I changed the form to input new lines to this:

$text = "IP: $this->ip:$this->port".'\n'.
    "IP interna: $this->ip_interna".'\n'.
    "User: $this->user".'\n'.
    "Pass: $this->pass".'\n'.
    "Observació: $this->observacio".'\n\n'.
    $this->credenciable->__toString();
return $text;

And it works, I can see the string into alert javascript.

Thanks to all who tried to help me.


问:
How to convert this String to Timestamp
i have a column with the Data like this "08.06.2017/10:20:46". Data Type is string. i want to convert it into timestamp.
i tried CAST("08.06.2017/10:20:46" AS TIMESTAMP) but it doesn't work
Can you please help me to convert it??
Thanks</p>

答:
For mysql, there is a function called STR_TO_DATE

You should call it like this:

```<code>STR_TO_DATE(string , format)
</code>```

Take a look at
Format specifiers

In your case I'd try with

```<code>STR_TO_DATE('08.06.2017/10:20:46','%d.%m.%Y/%H:%i:%s')
</code>```

Edit: sorry about the mysql stuff, don't know if I'm supposed to remove it or not... Anyways, for impala, this could get you started:

```<code>cast(unix_timestamp('08.06.2017/10:20:46', "dd.MM.yyyy/HH:mm:ss") as timestamp)
</code>```

The casting is because unix_timestamp function returns a bigint (take a look here for more information about the impala datetime functions)

Title: How to convert this String to Timestamp

Body:
For mysql, there is a function called STR_TO_DATE

You should call it like this:

STR_TO_DATE(string , format)

Take a look at
Format specifiers

In your case I'd try with

STR_TO_DATE('08.06.2017/10:20:46','%d.%m.%Y/%H:%i:%s')

Edit: sorry about the mysql stuff, don't know if I'm supposed to remove it or not... Anyways, for impala, this could get you started:

cast(unix_timestamp('08.06.2017/10:20:46', "dd.MM.yyyy/HH:mm:ss") as timestamp)

The casting is because unix_timestamp function returns a bigint (take a look here for more information about the impala datetime functions)


问:
How to get substring between nth and n+1th occurrence of pipe '|' in shell script
I have a large text file (20 million records) with all rows in below format

```<code>task|action||r1_c1|r1_c2|r1_c3
task|action||r2_c1|r2_c2|r2_c3
task|action||r3_c1|r3_c2|r3_c3
task|action||r4_c1|r4_c2|r4_c3
</code>```

My requirement is to print column 2 from nth row where n is my input. Column number is fixed but row number will change based on input.

Expected Output  if Input parameter (Line Number) is 3 -

```<code>r3_c2
</code>```

I can read file line by line and read nth line in variable

```<code>LineOfInterest=$(awk 'NR == n' n=$line $InputFile)
</code>```

Next I need to print values between 4th and 5th occurrence of pipe.

I believe it can be achieved using sed but now sure how to write pattern for same.

答:
Since you have mentioned there are millions of lines in Input_file then better NOT to read the complete Input_file once command meets the condition(to read the specific mentioned line), we could save sometime.

```<code>awk -v line=3 -F"|" 'FNR==line{print $(NF-1);exit}'   Input_file
</code>```

$(NF-1) indicates second last column of a line in Input_file, you could change it as per your need too. Also exit will make sure once this condition met it should come out of the command and we could save some cycles by NOT reading a huge Input_file.

Body:
I have a large text file (20 million records) with all rows in below format

task|action||r1_c1|r1_c2|r1_c3
task|action||r2_c1|r2_c2|r2_c3
task|action||r3_c1|r3_c2|r3_c3
task|action||r4_c1|r4_c2|r4_c3

My requirement is to print column 2 from nth row where n is my input. Column number is fixed but row number will change based on input.

Expected Output  if Input parameter (Line Number) is 3 -

r3_c2

I can read file line by line and read nth line in variable

LineOfInterest=$(awk 'NR == n' n=$line $InputFile)

Next I need to print values between 4th and 5th occurrence of pipe.

I believe it can be achieved using sed but now sure how to write pattern for same.

Body:
Since you have mentioned there are millions of lines in Input_file then better NOT to read the complete Input_file once command meets the condition(to read the specific mentioned line), we could save sometime.

awk -v line=3 -F"|" 'FNR==line{print $(NF-1);exit}'   Input_file

$(NF-1) indicates second last column of a line in Input_file, you could change it as per your need too. Also exit will make sure once this condition met it should come out of the command and we could save some cycles by NOT reading a huge Input_file.