问:
Create mex for Matlab on Linux with different compilers
I know Linux Matlab only has official support for gcc 4.9 for mex.

Does anyone know how to get either the Linux Intel compilers (icc) working with mex on Linux or more recent versions of the gcc?

This is for recent versions of Matlab (2015-2017).

答:
I assume you talk about C++ projects. Yes, its possible with newer versions of gcc.

Check supported compilers to find out which Matlab uses which gcc version.

Tell your newer version of gcc to use the ABI version of the gcc version that your Matlab was made in for the compilation of your project and all dependencies.

Tell Matlab to use the standard c++ library in /usr/lib and not the one it contains itself. It is backwards compatible.

Example with gcc > 4.9.x for Matlab 2017b:

Matlab 2017b was built with gcc 4.9.x

gcc 4.9.x is compatible with CXX ABI version 8

use your gcc with compile flag -fabi-version=8 for your mex file and all dependencies

in a shell export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 before a call to matlab


来源: stackexchange

问:
Are twitter user IDs and status IDs disjoint?
Twitter object IDs (Tweets, Direct Messages, Users, Collections, Lists etc.) are described as follows:

These IDs are unique 64-bit unsigned integers, which are based on time, instead of being sequential.

Are they guaranteed to be disjoint?
IOW, can the same ID denote both a user and a tweet?

答:
Even if they are "disjoint" today, there's no guarantee that they would be tomorrow.  You would be wise to develop your application as though they were NOT disjointed.

In other words, you should assume that it is possible for the same 64-bit integer to be used for users as well as tweets.  This will make your code more resilient to future change.

ContentLicense: CC BY-SA 3.0


问:
What does map(&:name) mean in Ruby?
I found this code in a RailsCast:

```<code>def tag_names
  @tag_names || tags.map(&:name).join(' ')
end
</code>```

What does the (&:name) in map(&:name) mean?

答:
Although we have great answers already, looking through a perspective of a beginner I'd like to add the additional information:

What does map(&:name) mean in Ruby?

This means, that you are passing another method as parameter to the map function.
(In reality you're passing a symbol that gets converted into a proc. But this isn't that important in this particular case).

What is important is that you have a method named name that will be used by the map method as an argument instead of the traditional block style.

Title: What does map(&:name) mean in Ruby?

Body:
I found this code in a RailsCast:

def tag_names
  @tag_names || tags.map(&:name).join(' ')
end

What does the (&:name) in map(&:name) mean?


问:
Installing Facebook apk on Android Emulator
Has anyone managed to do this?!

I've tried various combinations of sdk/apk from this site with no luck.
https://developers.facebook.com/docs/android/downloads

When I use this SDK...

```<code>dependencies {
    compile 'com.facebook.android:facebook-android-sdk:3.23.0'
}
</code>```

... it only seems to work with targetSdkVersion "L". So fine. I run that emulator in x86 and use adb to install

```<code>./sdk/platform-tools/adb install Facebook-25.0.0.19.30.apk
</code>```

I get "INSTALL_FAILED_NO_MATCHING_ABIS". On ARM, I have not managed to get the emulator to actually start. It's been "Preparing Recommendations" for over 30 minutes now.

With a lower Facebook sdk version (com.facebook.android:facebook-android-sdk:3.21.1), I am able to run the emulator with a targetSdkVersion of 19, and install the Facebook.apk (Facebook APK 22.0)

Unfortunately, when I open the Facebook app, I get the message that

```<code>"This version of android is no longer supported. please upgrade your device and try again"
</code>```

I must be doing something wrong. Could anyone point me in the right direction?

答:
With the newer Facebook SDKs, I couldn't find the Facebook APK file bundled with the Downloads - Facebook Android SDK.

To install facebook on an emulator:

I installed the Google Play Intel Atom Image from the SDK Manager.

Created an AVD with the Google Play Intel Atom Image

Now you can install Facebook from the Play Store (after sign in)

Now you can use Facebook to test Native login, etc,.

Body:
Has anyone managed to do this?!

I've tried various combinations of sdk/apk from this site with no luck.
https://developers.facebook.com/docs/android/downloads

When I use this SDK...

dependencies {
    compile 'com.facebook.android:facebook-android-sdk:3.23.0'
}

... it only seems to work with targetSdkVersion "L". So fine. I run that emulator in x86 and use adb to install

./sdk/platform-tools/adb install Facebook-25.0.0.19.30.apk

I get "INSTALL_FAILED_NO_MATCHING_ABIS". On ARM, I have not managed to get the emulator to actually start. It's been "Preparing Recommendations" for over 30 minutes now.

With a lower Facebook sdk version (com.facebook.android:facebook-android-sdk:3.21.1), I am able to run the emulator with a targetSdkVersion of 19, and install the Facebook.apk (Facebook APK 22.0)

Unfortunately, when I open the Facebook app, I get the message that

"This version of android is no longer supported. please upgrade your device and try again"

I must be doing something wrong. Could anyone point me in the right direction?


问:
Can I set a Parse Object Pointer with the ObjectID
I have a custom cloud code method to create a parse object.  I'm doing that so I can validate the uniqueness of a few pointer objects, etc.

When I create the object I need to create, can I set the non validated pointers via the object id I get from the client side?

Something like
     object.set("user", "someuserid");

I'd like to avoid doing the extra find queries if I can when I already have the id.

答:
there is one simple shortcut method
you just pass objectId to createWithoutData function

Parse.User.createWithoutData(req.body.objectId);


问:
Execute SQL query using Groovy script
I am trying to run SQL update query using Groovy script.

```<code>//Global Properties Value
def dbServer = context.expand('${#Project#DB_Server}')
def dbPort = context.expand('${#Project#DB_Port}')
def dbName = context.expand('${#Project#DB_Name}')
def dbUser = context.expand('${#Project#DB_Username}')
def dbPass = context.expand('${#Project#DB_Password}')
def userID = context.expand('${#Project#userID}').toInteger()

//Convert HEX to Integer
def userSerialHex = context.expand('${#Project#userSerial}').toString();
BigInteger userSerialInteger = Long.parseLong(userSerialHex, 16);

log.info userSerialHex
log.info userID
log.info userSerialInteger

//Connection String
def con = Sql.newInstance("jdbc:sqlserver://$dbServer:$dbPort;" + "databaseName=" + dbName, dbUser, dbPass, 'com.microsoft.sqlserver.jdbc.SQLServerDriver')

//SQL Query
con.execute("update tblUserCardDetail set active=0 where fkUserID = $userID and cardValue = $userSerialInteger");
</code>```

Result :

```<code>Fri Dec 08 20:24:25 IST 2017:INFO:182A11A53C68BD3C
Fri Dec 08 20:24:25 IST 2017:INFO:12901
Fri Dec 08 20:24:25 IST 2017:INFO:1741223607312891196
</code>```

Expected : It should return true and update the row.

Error i am getting :

com.microsoft.sqlserver.jdbc.SQLServerException: The conversion from UNKNOWN to UNKNOWN is unsupported. error at line: 27

When i run the query from sql server then it updated successfully.

```<code>update tblUserCardDetail set active=0 where fkUserID=12901 and cardValue=1741223607312891196
</code>```

答:
I think you need to convert BigInteger userSerialInteger to String explicitly.

Something like:

con.execute("update tblUserCardDetail set active=0 where fkUserID = $userID and cardValue = ${userSerialInteger.toString()}");

From the source code of groovy.sql.Sql#execute(groovy.lang.GString)

```<code>    List<Object> params = getParameters(gstring);
    String sql = asSql(gstring, params);
    return execute(sql, params);
</code>```

The params of gstring is passed to execute without processing.

Title: Execute SQL query using Groovy script

Body:
I am trying to run SQL update query using Groovy script.

//Global Properties Value
def dbServer = context.expand('${#Project#DB_Server}')
def dbPort = context.expand('${#Project#DB_Port}')
def dbName = context.expand('${#Project#DB_Name}')
def dbUser = context.expand('${#Project#DB_Username}')
def dbPass = context.expand('${#Project#DB_Password}')
def userID = context.expand('${#Project#userID}').toInteger()

//Convert HEX to Integer
def userSerialHex = context.expand('${#Project#userSerial}').toString();
BigInteger userSerialInteger = Long.parseLong(userSerialHex, 16);

log.info userSerialHex
log.info userID
log.info userSerialInteger

//Connection String
def con = Sql.newInstance("jdbc:sqlserver://$dbServer:$dbPort;" + "databaseName=" + dbName, dbUser, dbPass, 'com.microsoft.sqlserver.jdbc.SQLServerDriver')

//SQL Query
con.execute("update tblUserCardDetail set active=0 where fkUserID = $userID and cardValue = $userSerialInteger");

Result :

Fri Dec 08 20:24:25 IST 2017:INFO:182A11A53C68BD3C
Fri Dec 08 20:24:25 IST 2017:INFO:12901
Fri Dec 08 20:24:25 IST 2017:INFO:1741223607312891196

Expected : It should return true and update the row.

Error i am getting :

com.microsoft.sqlserver.jdbc.SQLServerException: The conversion from UNKNOWN to UNKNOWN is unsupported. error at line: 27

When i run the query from sql server then it updated successfully.

update tblUserCardDetail set active=0 where fkUserID=12901 and cardValue=1741223607312891196

Body:
I think you need to convert BigInteger userSerialInteger to String explicitly.

Something like:

con.execute("update tblUserCardDetail set active=0 where fkUserID = $userID and cardValue = ${userSerialInteger.toString()}");

From the source code of groovy.sql.Sql#execute(groovy.lang.GString)

    List<Object> params = getParameters(gstring);
    String sql = asSql(gstring, params);
    return execute(sql, params);

The params of gstring is passed to execute without processing.


问:
ReferenceError: instance is not defined
This is my XML code. When I click a button it shows following error:

ReferenceError: instance is not defined

```<code><?xml version="1.0" encoding="UTF-8"?>
<templates id="template" xml:space="preserve">
  <t t-extend="ListView.buttons">
    <t t-jquery="button.o_list_button_add" t-operation="after">
      <t t-if="widget.model=='ref.reference'">
        <button class="btn btn-sm btn-default" type="button">Enable</button>
        <button class="btn btn-sm btn-primary disable_ref" type="button">Disable</button>
      </t>
    </t>
  </t>
</templates>
</code>```

This is in javascript what wrong in this code:

```<code>var ListView = require('web.ListView');

ListView.include({
    render_buttons: function() {

        // GET BUTTON REFERENCE
        this._super.apply(this, arguments)
        if (this.$buttons) {
           var btn = this.$buttons.find('.disable_ref')
        }

        // PERFORM THE ACTION
        btn.on('click', this.proxy('do_new_button'))

    },
    do_new_button: function() {

        instance.web.Model('ref.reference')
            .call('ref_dis', [[]])
    }
})
</code>```

答:
Change it to this

js

```<code>odoo.define('reference.js', function(require) {
    'use strict';

var ListView = require('web.ListView')
var Model = require('web.Model')

    ListView.include({
        render_buttons: function() {
            this._super.apply(this, arguments)
            if (this.$buttons) {
                this.$buttons.find('.disable_ref').on('click', this.proxy('do_new_button'))
            }
        },
        do_new_button: function () {

            var model = new Model('ref.reference')
            model.call('ref_dis', [[]]);
        }
    })
})
</code>```

models

```<code>from odoo import fields, models, api

class ReferenceSource(models.Model):
    _name = "ref.reference"

    @api.model
    def ref_dis(self):
      some logic...
</code>```

Title: ReferenceError: instance is not defined

Body:
This is my XML code. When I click a button it shows following error:

ReferenceError: instance is not defined

<?xml version="1.0" encoding="UTF-8"?>
<templates id="template" xml:space="preserve">
  <t t-extend="ListView.buttons">
    <t t-jquery="button.o_list_button_add" t-operation="after">
      <t t-if="widget.model=='ref.reference'">
        <button class="btn btn-sm btn-default" type="button">Enable</button>
        <button class="btn btn-sm btn-primary disable_ref" type="button">Disable</button>
      </t>
    </t>
  </t>
</templates>

This is in javascript what wrong in this code:

var ListView = require('web.ListView');

ListView.include({
    render_buttons: function() {

        // GET BUTTON REFERENCE
        this._super.apply(this, arguments)
        if (this.$buttons) {
           var btn = this.$buttons.find('.disable_ref')
        }

        // PERFORM THE ACTION
        btn.on('click', this.proxy('do_new_button'))

    },
    do_new_button: function() {

        instance.web.Model('ref.reference')
            .call('ref_dis', [[]])
    }
})

Body:
Change it to this

js

odoo.define('reference.js', function(require) {
    'use strict';

var ListView = require('web.ListView')
var Model = require('web.Model')

    ListView.include({
        render_buttons: function() {
            this._super.apply(this, arguments)
            if (this.$buttons) {
                this.$buttons.find('.disable_ref').on('click', this.proxy('do_new_button'))
            }
        },
        do_new_button: function () {

            var model = new Model('ref.reference')
            model.call('ref_dis', [[]]);
        }
    })
})

models

from odoo import fields, models, api

class ReferenceSource(models.Model):
    _name = "ref.reference"

    @api.model
    def ref_dis(self):
      some logic...


问:
react-helmet outputting empty strings on server-side
I am using react-helmet and on the client all is good in the inspect window and the tags are being outputted correctly. However, when I boot up in production and the SSR kicks in the tags aren't shown in the source and I'm getting no errors at all.

I tried logging the 'stringified' title tag too and got:

```<code><title data-react-helmet="true"></title>
</code>```

Here is some code:

This is one of the page components where I'm setting the tags from, the 3 page components are all set up identically to this. (I've simplified the components render function and data object as they are quite large and I'm sure these aren't at fault.)

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Helmet } from 'react-helmet';

// Components
import WorkGrid from 'universal/components/Grid';
import Wrapper from 'universal/components/Wrapper';
import Container from 'universal/components/Container';
import Hero from 'universal/components/Hero';
import PageWrapper from 'universal/components/PageWrapper';
import GridHeader from 'universal/components/GridHeader';

const data = {};

class Work extends PageComponent {

  render () {
    return (
      <PageWrapper ref="root">
        <Helmet>
          <title>Work</title>
          <meta name="description" content="Work Description" />
        </Helmet>
        <h1>Work Page</h1>
      </PageWrapper>
    );
  }
}

export default connect(state => ({
  theme: state.ui.theme
}), { changeTheme }, null, { withRef: true })(Work);
</code>```

This is some of the server code, specifically where the SSR goes down and I'm calling Helmet.renderStatic();

```<code>    // Node Modules
import fs from 'fs';
import {basename, join} from 'path';

// Libraries
import React from 'react';
import {StaticRouter} from 'react-router';
import {renderToString} from 'react-dom/server';

// styled-components
import { ServerStyleSheet, ThemeProvider } from 'styled-components';
import { theme } from '../universal/constants';

// Redux
// import {push} from 'react-router-redux';
import createStore from 'data/redux/createStore.js';
import createHistory from 'history/createMemoryHistory';
import { Provider } from 'react-redux';

// Third Party Scripts
import * as thirdPartyScripts from './thirdPartyScripts.js';

// Helmet
import {Helmet} from 'react-helmet';

function renderApp(url, res, store, assets) {
  const PROD = process.env.NODE_ENV === 'production';
  const context = {};

  const {
    manifest,
    app,
    vendor
  } = assets || {};

  let state = store.getState();

  const stylesheet = new ServerStyleSheet();

  const initialState = `window.__INITIAL_STATE__ = ${JSON.stringify(state)}`;
  const Layout =  PROD ? require( '../../build/prerender.js') : () => {};

  const root = PROD && renderToString(
    stylesheet.collectStyles(
      <Provider store={store}>
        <ThemeProvider theme={theme}>
          <StaticRouter location={url} context={context}>
            <Layout />
          </StaticRouter>
        </ThemeProvider>
      </Provider>
    )
  );

  const styleTags = stylesheet.getStyleTags();

  const seo = Helmet.renderStatic();

  console.log(seo.title.toString());

  const html = `<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        ${seo.title.toString()}
        ${seo.meta.toString()}
        ${seo.link.toString()}

        <link rel="shortcut icon" href="/favicon.ico">
        <link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico">
        <link rel="apple-touch-icon" href="/favicon-57.png">
        <link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png">
        <link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png">
        <link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png">
        <link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png">
        <link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png">
        <link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png">
        <link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png">
        <link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png">
        <meta name="msapplication-TileColor" content="#FFFFFF">
        <meta name="msapplication-TileImage" content="/favicon-144.png">
        <meta name="msapplication-config" content="/browserconfig.xml">

        ${ styleTags }

        ${PROD ? '<link rel="stylesheet" href="/static/prerender.css" type="text/css" />' : ''}

        <link href="${thirdPartyScripts.googleFont}" rel="stylesheet" type="text/css">

        <script>${thirdPartyScripts.googleAnalytics}</script>
    </head>

    <body>
      <script>${initialState}</script>
      ${PROD ? `<div id="root">${root}</div>` : '<div id="root"></div>'}

      ${PROD ? `<script>${manifest.text}</script>` : ''}

      <script>${thirdPartyScripts.facebookPixel}</script>

      <script async src="${thirdPartyScripts.googleAnalyticsSrc}"></script>
      ${PROD ? `<script src="${vendor.js}"></script>` : ''}
      <script src="${PROD ? app.js : './static/app.js'}"></script>
    </body>
    </html>`;

  res.send(html);
}
</code>```

Also, I am using React Router v4 if that's of any help.

答:
I found the solution to this the other week and thought I may as well update this so it can help anyone else having this problem...

Good news is it was surprisingly simple!

For me anyway it was down to the fact that I separate webpack bundles for the client and the server. So in layman's terms it was including react-helmet twice, once for the client and once for the server, meaning all the state holding the meta tags in the client side code didn't exist in the .rewind() call on the server.

Just add this to your server webpack config file

externals: ['react-helmet']

Body:
I am using react-helmet and on the client all is good in the inspect window and the tags are being outputted correctly. However, when I boot up in production and the SSR kicks in the tags aren't shown in the source and I'm getting no errors at all.

I tried logging the 'stringified' title tag too and got:

<title data-react-helmet="true"></title>

Here is some code:

This is one of the page components where I'm setting the tags from, the 3 page components are all set up identically to this. (I've simplified the components render function and data object as they are quite large and I'm sure these aren't at fault.)

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Helmet } from 'react-helmet';

// Components
import WorkGrid from 'universal/components/Grid';
import Wrapper from 'universal/components/Wrapper';
import Container from 'universal/components/Container';
import Hero from 'universal/components/Hero';
import PageWrapper from 'universal/components/PageWrapper';
import GridHeader from 'universal/components/GridHeader';

const data = {};

class Work extends PageComponent {

  render () {
    return (
      <PageWrapper ref="root">
        <Helmet>
          <title>Work</title>
          <meta name="description" content="Work Description" />
        </Helmet>

Work Page

      </PageWrapper>
    );
  }
}

export default connect(state => ({
  theme: state.ui.theme
}), { changeTheme }, null, { withRef: true })(Work);

This is some of the server code, specifically where the SSR goes down and I'm calling Helmet.renderStatic();

    // Node Modules
import fs from 'fs';
import {basename, join} from 'path';

// Libraries
import React from 'react';
import {StaticRouter} from 'react-router';
import {renderToString} from 'react-dom/server';

// styled-components
import { ServerStyleSheet, ThemeProvider } from 'styled-components';
import { theme } from '../universal/constants';

// Redux
// import {push} from 'react-router-redux';
import createStore from 'data/redux/createStore.js';
import createHistory from 'history/createMemoryHistory';
import { Provider } from 'react-redux';

// Third Party Scripts
import * as thirdPartyScripts from './thirdPartyScripts.js';

// Helmet
import {Helmet} from 'react-helmet';

function renderApp(url, res, store, assets) {
  const PROD = process.env.NODE_ENV === 'production';
  const context = {};

  const {
    manifest,
    app,
    vendor
  } = assets || {};

  let state = store.getState();

  const stylesheet = new ServerStyleSheet();

  const initialState = `window.__INITIAL_STATE__ = ${JSON.stringify(state)}`;
  const Layout =  PROD ? require( '../../build/prerender.js') : () => {};

  const root = PROD && renderToString(
    stylesheet.collectStyles(
      <Provider store={store}>
        <ThemeProvider theme={theme}>
          <StaticRouter location={url} context={context}>
            <Layout />
          </StaticRouter>
        </ThemeProvider>
      </Provider>
    )
  );

  const styleTags = stylesheet.getStyleTags();

  const seo = Helmet.renderStatic();

  console.log(seo.title.toString());

  const html = `<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        ${seo.title.toString()}
        ${seo.meta.toString()}
        ${seo.link.toString()}

        <link rel="shortcut icon" href="/favicon.ico">
        <link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico">
        <link rel="apple-touch-icon" href="/favicon-57.png">
        <link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png">
        <link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png">
        <link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png">
        <link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png">
        <link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png">
        <link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png">
        <link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png">
        <link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png">
        <meta name="msapplication-TileColor" content="#FFFFFF">
        <meta name="msapplication-TileImage" content="/favicon-144.png">
        <meta name="msapplication-config" content="/browserconfig.xml">

        ${ styleTags }

        ${PROD ? '<link rel="stylesheet" href="/static/prerender.css" type="text/css" />' : ''}

        <link href="${thirdPartyScripts.googleFont}" rel="stylesheet" type="text/css">

      ${PROD ? `<div id="root">${root}</div>` : '

'}

      ${PROD ? `<script>${manifest.text}</script>` : ''}

      ${PROD ? `<script src="${vendor.js}"></script>` : ''}

    `;

  res.send(html);
}

Also, I am using React Router v4 if that's of any help.


问:
Custom IP/UDP/RTP header in windows xp (and above) + general network questions
Lots of questions, I am sorry!

I am doing a voice-chat (VoIP) application and I was thinking of doing a custom implementation of the IP&UDP headers, along with small, extra information mainly seq number. Sounds alot like RTP yes, but I'm mainly just interested in the seq number or timestamp, and trying to implement my own whole RTP sounds like a nightmare with all the complexity involved and data im not likely to use.

Target OS for the application is windows xp and above. I have read http://msdn.microsoft.com/en-us/library/ms740548%28v=vs.85%29.aspx on the topic of Raw sockets in windows, and now I just want some confirmation.
I also have some general networking questions.

Here's the following questions;

1) According to MSDN, you cannot send custom IP packets with a source that is not on the network list. I understand it from a security PoV, but is there any way around this? My idea was to have for example two clients open UDP communication to a non-NAT protected server, and then have the clients spoof the source-header to make it look like packets come from the server instead of each other, thereby eliminating the need for a server as a relay of data to get through NAT, which would improve latency.
I have heard of winpcap but I don't want each client to have to install any 3rd party apps. Considering the number of DoS attacks surely there must be some way around this, like spoofing the network table the OS uses to check if source-header is legit? Will this trigger anti-virus systems?
I feel it would be really fun to actually toy with IP headers and above instead of just using predefined headers.

2) I've been having issues with free RTP libraries like JRTPLIB(which probably is very good anyway it just dosn't want to work for me) to make them work, more than I could almost tolerate, and am thinking of just writing my own interpretation ontop of UDP. Does application-level protcols like RTP simply build their header directly inside the UDP payload with the actual data afterwards? I suspect this considering the encapsulation process but just want to make sure.
If so, one does not need to create a RAW socket to implement application-level protocol, just an ordinary UDP socket and then your own payload interpretation above?

3) RTP does not give any performance boost compared to UDP since it adds more headers, all it does is making sure packets arrive in a sort-of correct manner based on timestamps and sequence numbers, right?
Is it -really- that usefull to use an RTP implementation for your basic VoIP project needs instead of adding basic sequencing yourself? I realise for video conferencing perhaps you reaally don't want frames to play out of order, but in audio conversations, would you really notice it?

4) If my solution in #1 is not applicable and I would have to use a server as a data relay between clients, would multicast be a good solution to reduce server loads? Is multicast supported enough in routing hardware?

5) It is related to question 1). Why do routers/firewalls allow things like UDP hole punching? For example, two clients first conenct to the server, then the server gives a client port / ip on to other clients, so the clients can talk to each other on those ports.
Why would firewalls allow data to be received from another IP than the one used in making the connection on that very port? Sounds like a big security hole that should easly be filtered? I understand that source IP spoofing would trick it, but this?

6) To set up a UDP session between two parties (the client which is behind NAT, server whic his non-NAT) does the client simply have to send a packet to the server and then the session is allowed through the firewall? Meaning the client can receive too from the server.
Based on article at wiki, http://en.wikipedia.org/wiki/UDP_hole_punching

7) Is SIP dependant on RTP? For some reason I got this impression but I cant find data to back it up. I may plan to add softphone functionality to my VoIP client in the future and want to make sure I have a good foundation (RTP if I really must, otherwise my own UDP interpretation)

Thanks in advance!

答:
1, Raw sockets seems unnecessary for this application

2, Yes

3, RTP runs on top of UDP, of course it adds overhead. In many ways RTP (ignoring RTCP) is pretty much the bare minimum already and if you implemented a half-way decent alternative it would save you a few bytes at best and you wouldn't be able to use any of the many RTP test tools.

7, SIP is completely independent of RTP. SIP is used to Initiate Sessions. SDP is the protocol commonly transported by SIP, and it is SDP that negotiates and controls RTP video/voice voice.

ContentLicense: CC BY-SA 2.5


问:
Normalize FHIR bundles data into separate database tables
We get FHIR bundles from vendor, mostly patient, encounter, observation, flag and a few other resources (10 total). We have an option to store resources as json values or we can come up with a process to normalize all the nested structures into separate tables. We are going to use traditional BI tools to do some analytics and build some dashboards and these tools do not support json natively. Should we do former or latter and what is the best/easiest way to build/generate these normalized tables programmatically? </p>

答:
Ultimately how you decide to store these is not part of the scope of FHIR, and any answer you get on here is going to be one person's opinion. You need to figure out what method makes the most sense for the product/business you're building.

Here are some first principles that may help you:

Different vendors will send different FHIR at you. Fields may be missing, different code systems may be used.

FHIR extensions contain a lot of valuable information and the JSON representation is an Entity Attribute Value. EAV is anti-pattern for relational databases.

FHIR versions will change overtime - fields will be added and have their names changed, and new extensions will be relevant.

As far as your second question about generating the tables - I think that you will be best served by designing the data model you need, and mapping the FHIR data to it. That said there are a number of open source FHIR implementations you can study for inspiration.


问:
Best way to allow editing of a datetime value in a jeditable environment?
I use Jeditable to allow editing of a table on my page. It updates a MySQL table and it all works fine.

I would like to add the ability to edit a datetime value as well. So I tried using jquery.jeditable.datepicker.js to do the job. But it works only with date values not datetime values.

```<code>$('.editTimeIn').editable('save.php', {
    type        : 'datepicker',
        datepicker: {
            dateFormat: 'yy-mm-dd',
            numberOfMonths: 2
        }
});
</code>```

I need to be able to give the user the ability to pick the date and time. What recommendations do you have for this functionality?
If possible please use examples.

答:
From jeditable documentation.

(String) type: Input type to use. Default input types are text,
  textarea or select. Additional input types are provided using custom
  input type API.

So if you take a closer look in jeditable additional input types you will see that you could use

timepicker type (dependency of timepicker)

or

a time input type (perhaps this is the best way in case you need
  something quick and without any other plugin dependancy).

A simple example of time input type can be found in this fiddle

EDIT

You could also try to extend additional input types by adding datetime-local input type such as below (just a simple demo)

```<code>$.editable.addInputType('datetime', {
/* Create input element. */
element : function(settings, original) {
    // pattern is fallback for browsers not supporting datetime-local
    var datetime_local = $('<input id="datetime_" type="datetime-local" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" required />');
    $(this).append(datetime_local);
var hidden = $('<input type="hidden">');
$(this).append(hidden);
return(hidden);
},
submit : function(settings, original) {
    var value = $('input:#datetime_').val();
    $("input", this).val(value);
}
});
</code>```

Please check the updated fiddle also to view the changes

Body:
I use Jeditable to allow editing of a table on my page. It updates a MySQL table and it all works fine.

I would like to add the ability to edit a datetime value as well. So I tried using jquery.jeditable.datepicker.js to do the job. But it works only with date values not datetime values.

$('.editTimeIn').editable('save.php', {
    type        : 'datepicker',
        datepicker: {
            dateFormat: 'yy-mm-dd',
            numberOfMonths: 2
        }
});

I need to be able to give the user the ability to pick the date and time. What recommendations do you have for this functionality?
If possible please use examples.

Body:
From jeditable documentation.

(String) type: Input type to use. Default input types are text,
  textarea or select. Additional input types are provided using custom
  input type API.

So if you take a closer look in jeditable additional input types you will see that you could use

timepicker type (dependency of timepicker)

or

a time input type (perhaps this is the best way in case you need
  something quick and without any other plugin dependancy).

A simple example of time input type can be found in this fiddle

EDIT

You could also try to extend additional input types by adding datetime-local input type such as below (just a simple demo)

$.editable.addInputType('datetime', {
/* Create input element. */
element : function(settings, original) {
    // pattern is fallback for browsers not supporting datetime-local
    var datetime_local = $('<input id="datetime_" type="datetime-local" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" required />');
    $(this).append(datetime_local);
var hidden = $('<input type="hidden">');
$(this).append(hidden);
return(hidden);
},
submit : function(settings, original) {
    var value = $('input:#datetime_').val();
    $("input", this).val(value);
}
});

Please check the updated fiddle also to view the changes


答:
This type of error comes from the SQL driver trying to tell you it doesn't know how to convert the values you're passing as arguments.

You can either try changing your def userID to int userID or casting your parameter as below.

Even if groovy.sql is smart enough to change it, I'd also advise in favor of using a method with parameters for your update statement (e.g. groovy.sql.Sql.executeUpdate(String, List)):

```<code>con.executeUpdate('update tblUserCardDetail set active=0 where fkUserID = ? and cardValue = ?', [userID.toInteger(), userSerialInteger])
</code>```

Edit: As noted by @aristotll, the execute(GString) is not that smart. Which reinforces my advice above, since converting to text is not a very good practice. However, you also need to make sure you are using the correct types on both sides, as documented here if you're using the Microsoft JDBC driver.

Title: Execute SQL query using Groovy script

Body:
This type of error comes from the SQL driver trying to tell you it doesn't know how to convert the values you're passing as arguments.

You can either try changing your def userID to int userID or casting your parameter as below.

Even if groovy.sql is smart enough to change it, I'd also advise in favor of using a method with parameters for your update statement (e.g. groovy.sql.Sql.executeUpdate(String, List)):

con.executeUpdate('update tblUserCardDetail set active=0 where fkUserID = ? and cardValue = ?', [userID.toInteger(), userSerialInteger])

Edit: As noted by @aristotll, the execute(GString) is not that smart. Which reinforces my advice above, since converting to text is not a very good practice. However, you also need to make sure you are using the correct types on both sides, as documented here if you're using the Microsoft JDBC driver.


问:
Issues in Internet Explorer, positioning?
Everything works fine in all other browsers than Internet Explorer, suprise!
The blue triangle is supposed to be on top of the box using position absolute/relative. And as i said it works but looks like in the picture in Internet explorer. Does anyone know thats causing this??? :)

```<code><div class="services">
    <a href="#">
        <div class="box redovisning">
            <img class="boxImage" src="../img/accounting_icon.svg" alt="redovisning.png">
            <h3>redovisning</h3>
            <div class="triangle-bottomright"></div>
        </div>
    </a>
    <a href="#">
        <div class="box consulting">
            <img src="../img/consulting_icon.svg" alt="consultation.png">
            <h3>rådgivning</h3>
            <div class="triangle-bottomright"></div>
        </div>
    </a>
    <a href="#">
        <div class="box revision">
            <img class="boxImage" src="../img/revision_icon.svg" alt="revision.png">
            <h3>revision</h3>
            <div class="triangle-bottomright"></div>
        </div>
    </a>
</div>

CSS:
.services {
    width:100%;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    flex-wrap:wrap;
    margin-bottom:40px;
}
.box {
    position: relative;
    height:300px;
    width:300px;
    border: 2px solid $black;
    display:flex;
    justify-content:center;
    flex-direction:column;
}
.box:hover > .triangle-bottomright {
    border-left: 0 solid transparent;
    right: 0;
}
.box:hover > h3 {
    color:$black;
}
.consulting img {
    width: 80%;
    height: 211px;
}
.triangle-bottomright {
    transition: all .3s ease-in-out;
    width: 0;
    height: 0;
    right: 0;
    border-bottom: 300px solid $blue;
    border-left: 298px solid transparent;
    z-index: 1;
    position:absolute;
}
</code>```

答:
It seems that IE expects you to give it the top value also for an element with absolute positioning. This should solve your problem:</p>

```<code>.triangle-bottomright {
  transition: all .3s ease-in-out;
  width: 0;
  height: 0;
  right: 0;
  top: 0;
  border-bottom: 300px solid $blue;
  border-left: 298px solid transparent;
  z-index: 1;
  position:absolute;
}
</code>```

Body:
Everything works fine in all other browsers than Internet Explorer, suprise!
The blue triangle is supposed to be on top of the box using position absolute/relative. And as i said it works but looks like in the picture in Internet explorer. Does anyone know thats causing this??? :)

redovisning

rådgivning

revision

CSS:
.services {
    width:100%;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    flex-wrap:wrap;
    margin-bottom:40px;
}
.box {
    position: relative;
    height:300px;
    width:300px;
    border: 2px solid $black;
    display:flex;
    justify-content:center;
    flex-direction:column;
}
.box:hover > .triangle-bottomright {
    border-left: 0 solid transparent;
    right: 0;
}
.box:hover > h3 {
    color:$black;
}
.consulting img {
    width: 80%;
    height: 211px;
}
.triangle-bottomright {
    transition: all .3s ease-in-out;
    width: 0;
    height: 0;
    right: 0;
    border-bottom: 300px solid $blue;
    border-left: 298px solid transparent;
    z-index: 1;
    position:absolute;
}

Body:
It seems that IE expects you to give it the top value also for an element with absolute positioning. This should solve your problem:

.triangle-bottomright {
  transition: all .3s ease-in-out;
  width: 0;
  height: 0;
  right: 0;
  top: 0;
  border-bottom: 300px solid $blue;
  border-left: 298px solid transparent;
  z-index: 1;
  position:absolute;
}


问:
Copy database with smo raise error: "user already exists"
I try to copy a database using smo, but I get the error:

"User, group, or role '%' already exists in the current database"

My code:

```<code>var conn = GetServerConnection();
var server = new Server(conn);

var sourceDb = server.Databases[sourceDatabase.Name];

var destinationDbName = GetNameForDatabase(dbName);

var destinationDb = new Database(server, destinationDbName);
destinationDb.Create();

var transfer = new Transfer(sourceDb) {
   DestinationDatabase = destinationDbName,
   DestinationServer = server.Name,
   DestinationLoginSecure = true,
   CopySchema = true,
   CopyAllTables = true,
   CopyData = true,
   CopyAllUsers = false,
};

transfer.Options.WithDependencies = true;
transfer.Options.ContinueScriptingOnError = true;
transfer.TransferData();
</code>```

Thanks in advance for any suggestions!

答:
Do you have any mappings from the database server to the source database? Try removing those before attempting the copy.

I was copying the database using the Copy Database wizard in order to create a test database on the same server, and got this error. The problem was that the source database had a user login mapped to that database. Somewhere in the mix of it all, the Copy Database wizard was trying to add a user to the destination database via a straight copy, but also add the same user through the mapping. The trick was to remove the mapping of the source database, then copy the database, then add the mapping back to the source (it was already added at the destination).

Body:
I try to copy a database using smo, but I get the error:

"User, group, or role '%' already exists in the current database"

My code:

var conn = GetServerConnection();
var server = new Server(conn);

var sourceDb = server.Databases[sourceDatabase.Name];

var destinationDbName = GetNameForDatabase(dbName);

var destinationDb = new Database(server, destinationDbName);
destinationDb.Create();

var transfer = new Transfer(sourceDb) {
   DestinationDatabase = destinationDbName,
   DestinationServer = server.Name,
   DestinationLoginSecure = true,
   CopySchema = true,
   CopyAllTables = true,
   CopyData = true,
   CopyAllUsers = false,
};

transfer.Options.WithDependencies = true;
transfer.Options.ContinueScriptingOnError = true;
transfer.TransferData();

Thanks in advance for any suggestions!


问:
update panel is updating entire page instead of just grid view
I'm trying to use an ajax timer and a update panel to update only my gridview, but it keeps resetting the entire page. What am I doing wrong? Here is my code.

aspx page:

```<code>        <div class="row text-center">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:PostBackTrigger ControlID="gvShowContent" />
            </Triggers>
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server" Interval="60000" OnTick="Timer1_Tick"></asp:Timer>
                <asp:GridView ID="gvShowContent" runat="server" OnRowCommand="gvShowContent_RowCommand" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
                    <AlternatingRowStyle BackColor="White" />
                    <Columns>
                        <asp:BoundField DataField="Course_Code" HeaderText="Course Code" />
                        <asp:BoundField DataField="Content_Name" HeaderText="Title" />
                        <asp:BoundField DataField="Content_Description" HeaderText="Description" />
                        <asp:BoundField DataField="Content_Title" HeaderText="File Name" />
                        <asp:TemplateField HeaderText="Download">
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkDownload" runat="server" CommandArgument='<%# Eval("Content_Title") %>' CommandName="cmd">Download</asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                    <SortedAscendingCellStyle BackColor="#FDF5AC" />
                    <SortedAscendingHeaderStyle BackColor="#4D0000" />
                    <SortedDescendingCellStyle BackColor="#FCF6C0" />
                    <SortedDescendingHeaderStyle BackColor="#820000" />
                </asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
</code>```

Codebehind:

```<code>protected void Timer1_Tick(object sender, EventArgs e)
    {
        gvShowContent.DataSource = proxy.ShowContent();
        gvShowContent.DataBind();
    }
</code>```

答:
There's no need to <trigger> GridView in UpdatePanel: https://msdn.microsoft.com/en-us/library/cc295400.aspx

So remove this:

```<code><Triggers>
    <asp:PostBackTrigger ControlID="gvShowContent" />
</Triggers>
</code>```

Now bind and update your UpdatePanel:

```<code>protected void Timer1_Tick(object sender, EventArgs e)
{
    gvShowContent.DataBind();
    UpdatePanel1.Update();
}
</code>```

Body:
I'm trying to use an ajax timer and a update panel to update only my gridview, but it keeps resetting the entire page. What am I doing wrong? Here is my code.

aspx page:

        <asp:ScriptManager ID="ScriptManager1" runat="server" />

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:PostBackTrigger ControlID="gvShowContent" />
            </Triggers>
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server" Interval="60000" OnTick="Timer1_Tick"></asp:Timer>
                <asp:GridView ID="gvShowContent" runat="server" OnRowCommand="gvShowContent_RowCommand" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
                    <AlternatingRowStyle BackColor="White" />
                    <Columns>
                        <asp:BoundField DataField="Course_Code" HeaderText="Course Code" />
                        <asp:BoundField DataField="Content_Name" HeaderText="Title" />
                        <asp:BoundField DataField="Content_Description" HeaderText="Description" />
                        <asp:BoundField DataField="Content_Title" HeaderText="File Name" />
                        <asp:TemplateField HeaderText="Download">
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkDownload" runat="server" CommandArgument='<%# Eval("Content_Title") %>' CommandName="cmd">Download</asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                    <SortedAscendingCellStyle BackColor="#FDF5AC" />
                    <SortedAscendingHeaderStyle BackColor="#4D0000" />
                    <SortedDescendingCellStyle BackColor="#FCF6C0" />
                    <SortedDescendingHeaderStyle BackColor="#820000" />
                </asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>

Codebehind:

protected void Timer1_Tick(object sender, EventArgs e)
    {
        gvShowContent.DataSource = proxy.ShowContent();
        gvShowContent.DataBind();
    }

Body:
There's no need to <trigger> GridView in UpdatePanel: https://msdn.microsoft.com/en-us/library/cc295400.aspx

So remove this:

<Triggers>
    <asp:PostBackTrigger ControlID="gvShowContent" />
</Triggers>

Now bind and update your UpdatePanel:

protected void Timer1_Tick(object sender, EventArgs e)
{
    gvShowContent.DataBind();
    UpdatePanel1.Update();
}


问:
How can I check if an XMLHttpRequest to my public API is from my own webapp or from a third-party client (to ensure priority)?
Does anybody know of a way of checking on the API side if a XMLHttpRequest has been made from my own web-application (ie. from the JS I have written) or from a third-party application...

The problem, to me, seems to be that because the JS is run on the client and thus accessible to anyone I have no way of secretly communicating to the API server who I am. I think this is useful because otherwise I cannot prioritize requests from my own application over third-party clients in case of high usage.

I could obviously send some non-documented parameters but these can be spoofed.

Anybody with some ideas?

答: I would have your web server application generate a token that it would pass to your clients either in JavaScript or a hidden field which they in turn would use to call your API. Those with valid tokens get priority, missing or invalid tokes wouldn't. The web server application can create & register the token in your system in a way that limits its usefulness to others trying to reuse it (e.g., time limited).</p>


问:
Check if for multiple values BUT one needs an extra line
My first question..!
Hi all, as a guy trying to learn programming/Python to be exact I have an issue that I would like to address. I have written some code that works as expected.

```<code>for i in range(81):
    if i in (30, 60, 80):
        if i == 80:
            ab += str(a) + '*' + str(b) + '<>'
        ab = ab.rstrip('<>')
        my_list += my_func(ab)
        ab = ''
    ab += str(a) + '*' + str(b) + '<>'
</code>```

Yet I don't think this part is the pythonic way to go:

```<code>if i in (30, 60, 80):
    if i == 80:
</code>```

There should be a way for me to say if i == 80 then do the standard 'if' conditions AFTER this extra code.

I hope I explained the issue properly. Thanks!

PS: This is an example code. I'm trying to find the proper logic only. Dont get stuck with the results.

Edit: I forgot to enter this line when posting my question (that's why some didn't understand the code):

```<code>my_list += my_func(ab)
</code>```

Also For extra points  :)  I'd love it if there was a way that this line doesn't have to be written twice!

```<code>ab += str(a) + '*' + str(b) + '<>'
</code>```

答:
You could move the if i == 80:... bit above the other if to avoid any nesting or duplication, but not sure if that's is what makes you think this isn't Pythonic enough:

```<code>for i in range(81):
    if i == 80:
        ab += str(a) + '*' + str(b) + '<>'
    if i in (30, 60, 80):
        ab = ab.rstrip('<>')
        my_list += my_func(ab)
        ab = ''
    ab += str(a) + '*' + str(b) + '<>'
</code>```

Body:
My first question..!
Hi all, as a guy trying to learn programming/Python to be exact I have an issue that I would like to address. I have written some code that works as expected.

for i in range(81):
    if i in (30, 60, 80):
        if i == 80:
            ab += str(a) + '*' + str(b) + '<>'
        ab = ab.rstrip('<>')
        my_list += my_func(ab)
        ab = ''
    ab += str(a) + '*' + str(b) + '<>'

Yet I don't think this part is the pythonic way to go:

if i in (30, 60, 80):
    if i == 80:

There should be a way for me to say if i == 80 then do the standard 'if' conditions AFTER this extra code.

I hope I explained the issue properly. Thanks!

PS: This is an example code. I'm trying to find the proper logic only. Dont get stuck with the results.

Edit: I forgot to enter this line when posting my question (that's why some didn't understand the code):

my_list += my_func(ab)

Also For extra points  :)  I'd love it if there was a way that this line doesn't have to be written twice!

ab += str(a) + '*' + str(b) + '<>'

Body:
You could move the if i == 80:... bit above the other if to avoid any nesting or duplication, but not sure if that's is what makes you think this isn't Pythonic enough:

for i in range(81):
    if i == 80:
        ab += str(a) + '*' + str(b) + '<>'
    if i in (30, 60, 80):
        ab = ab.rstrip('<>')
        my_list += my_func(ab)
        ab = ''
    ab += str(a) + '*' + str(b) + '<>'


问:
Python: How to row look up data from a dataframe and multiply in another dataframe based on columns match
I have a data-frame df1 which has the following structure

```<code>A   B   C   D
10  9   9   4
5   4   4   9
5   10  6   4
9   9   9   4
4   7   10  7
9   7   4   8
5   7   8   9
10  4   10  6
</code>```

I have another data-frame df2 as following,

```<code>name    factor
A   2
B   3
C   4
D   8
</code>```

How do I look up value for A, B, C, D from df2 and multiply with df1 [A, B, C, D] and get df3 such as,

```<code>A   B   C   D
20  27  36  32
10  12  16  72
10  30  24  32
18  27  36  32
8   21  40  56
18  21  16  64
10  21  32  72
20  12  40  48
</code>```

Body:
I have a data-frame df1 which has the following structure

A   B   C   D
10  9   9   4
5   4   4   9
5   10  6   4
9   9   9   4
4   7   10  7
9   7   4   8
5   7   8   9
10  4   10  6

I have another data-frame df2 as following,

name    factor
A   2
B   3
C   4
D   8

How do I look up value for A, B, C, D from df2 and multiply with df1 [A, B, C, D] and get df3 such as,

A   B   C   D
20  27  36  32
10  12  16  72
10  30  24  32
18  27  36  32
8   21  40  56
18  21  16  64
10  21  32  72
20  12  40  48

Body:
Use mul for multiple by Series created by set_index:

df3 = df1.mul(df2.set_index('name')['factor'])
print (df3)
    A   B   C   D
0  20  27  36  32
1  10  12  16  72
2  10  30  24  32
3  18  27  36  32
4   8  21  40  56
5  18  21  16  64
6  10  21  32  72
7  20  12  40  48

Detail:

print (df2.set_index('name')['factor'])
name
A    2
B    3
C    4
D    8
Name: factor, dtype: int64

EDIT:

If some category is missing is possible use fillna, thanks Wen:

s = df2.set_index('name').drop('D')['factor']
print (s)
name
A    2
B    3
C    4
Name: factor, dtype: int64

df3 = df1.mul(s).fillna(df1)
print (df3)
      A     B     C    D
0  20.0  27.0  36.0  4.0
1  10.0  12.0  16.0  9.0
2  10.0  30.0  24.0  4.0
3  18.0  27.0  36.0  4.0
4   8.0  21.0  40.0  7.0
5  18.0  21.0  16.0  8.0
6  10.0  21.0  32.0  9.0
7  20.0  12.0  40.0  6.0

EDIT1:

If want compare DataFrame by Series:

s = df2.set_index('name')['factor']
print (s)
name
A    2
B    3
C    4
D    8
Name: factor, dtype: int64

df1['A'] = (np.log(df1['A']) * s['A']) ** 3
print (df1)
           A   B   C  D
0  97.664572   9   9  4
1  33.351293   4   4  9
2  33.351293  10   6  4
3  84.862013   9   9  4
4  21.313578   7  10  7
5  84.862013   7   4  8
6  33.351293   7   8  9
7  97.664572   4  10  6

And for all columns:

df1 = (np.log(df1) * s) ** 3
print (df1)
           A           B           C            D
0  97.664572  286.409295  678.896108  1364.068975
1  33.351293   71.933325  170.508622  5431.168861
2  33.351293  329.617932  368.145163  1364.068975
3  84.862013  286.409295  678.896108  1364.068975
4  21.313578  198.944581  781.316579  3772.578718
5  84.862013  198.944581  170.508622  4603.732789
6  33.351293  198.944581  575.466599  5431.168861
7  97.664572   71.933325  781.316579  2945.161306


问:
Await Task outside of using statement
I have code:

```<code>Task<string> pageIdTask;
using (var seedSession = this.dbSessionManager.Start(agencyId))
{
    pageIdTask = seedSession.Query<ModelInfo>()
                .Where(mi=> mi.Id == modelId)
                .Select(mi=> mi.Tag)
                .SingleAsync();
}

var tokenTask = this.tokenManager.GetAsync(agencyId);

await Task.WhenAll(pageIdTask, tokenTask);

string pageId = pageIdTask.Result;
var token = tokenTask.Result;
</code>```

Is it correct? I mean is it ok to await Task if it was initialized in using statement?

Or better to await Task in using statement?

答:
There's no technical limitation in awating a task created in the scope of a using() statement outside of it, but in most cases that means the task's logic depends on whatever was inside the using() which is now disposed.
So in general something like this is ok:

```<code>Task task;
using(var something = GetSomething()){
    task = otherThing.CompletelyUnrelatedLogic();
}
task.Wait(); // no prob
</code>```

But in most actual cases will be like:

```<code>Task task;
using(var something = GetSomething()){
    task = something.TaskThatWillFailAndExplodeIfExecutedWhenSomethingIsDisplosed();
}
task.Wait(); // BOOM
</code>```

Title: Await Task outside of using statement

Body:
I have code:

Task<string> pageIdTask;
using (var seedSession = this.dbSessionManager.Start(agencyId))
{
    pageIdTask = seedSession.Query<ModelInfo>()
                .Where(mi=> mi.Id == modelId)
                .Select(mi=> mi.Tag)
                .SingleAsync();
}

var tokenTask = this.tokenManager.GetAsync(agencyId);

await Task.WhenAll(pageIdTask, tokenTask);

string pageId = pageIdTask.Result;
var token = tokenTask.Result;

Is it correct? I mean is it ok to await Task if it was initialized in using statement?

Or better to await Task in using statement?

Body:
There's no technical limitation in awating a task created in the scope of a using() statement outside of it, but in most cases that means the task's logic depends on whatever was inside the using() which is now disposed.
So in general something like this is ok:

Task task;
using(var something = GetSomething()){
    task = otherThing.CompletelyUnrelatedLogic();
}
task.Wait(); // no prob

But in most actual cases will be like:

Task task;
using(var something = GetSomething()){
    task = something.TaskThatWillFailAndExplodeIfExecutedWhenSomethingIsDisplosed();
}
task.Wait(); // BOOM


问:
Effective way of pattern matching on multiple Options Scala
I have below function which returns a flag based on some conditions.

Trying to see if there is a better Scala way to achieve the same?

Basically based on the status of the person there are different rules to be applied finally to derive on the pass_ind flag.

If person status is Student or Unemployment there are some rules on income and if the person status is not in Student or Unemployment there are different rules to be applied on score & income

```<code>def IncomeScreenStatus(status_cd: Option[String],
                                   score: Option[Int],
                                 income: Option[Double]) : String  = {

 var pass_ind : String = "F"

 if (score.isDefined && income.isDefined && status_cd.isDefined) {

        val score : Int = score.get
        val income : Double = income.get
        val status_cd : String = status_cd.get

        if (status_cd == "STUDENT" || status_cd == "UNEMPLOYMENT") {
          pass_ind = (status_cd, income) match {
            case ("UNEMPLOYMENT", income) if income <= 7000 => "P"
            case ("STUDENT", income) if income <= 18000 => "P"
            case _ => "F"
          }
        }
        else {
          pass_ind = (income, score) match {
            case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
            case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
            case _ => "F"
          }
        }

      }

    pass_ind

}
</code>```

答:
As your example requires each field to be defined, you can zip the Options together.  I also like to use extractors in place of explicit guards on my case statements.

If your status is a finite set, I would also recommend using a sealed trait to represent it.

```<code>object Example {

  sealed trait Status
  case object Student extends Status
  case object Unemployed extends Status
  case object Other extends Status

  object PoorStudent {
    def unapply(income: Int) = if (income <= 18000) Some(income) else None
  }

  object PoorUnemployed {
    def unapply(income: Int) = if (income <= 7000) Some(income) else None
  }

  object IncomeScoreRange {
    def unapply(score: Int, income: Double) =
      if (((score < 100 || score > 150) && income <= 8500) || (income <= 10500 && (100 to 167 contains score)))
        Some((score, income))
      else
        None
  }

  def compute(status: Option[Status], score: Option[Int], income: Option[Double]): String = {

    (status, score, income).zipped
      .collect {
        case (Student, _, PoorStudent(_))                    => "P"
        case (Unemployed, _, PoorUnemployed(_))              => "P"
        case (Other, IncomeScoreRange(_, _))                 => "P"
      }
      .headOption
      .getOrElse("F")
  }
}
</code>```

Body:
I have below function which returns a flag based on some conditions.

Trying to see if there is a better Scala way to achieve the same?

Basically based on the status of the person there are different rules to be applied finally to derive on the pass_ind flag.

If person status is Student or Unemployment there are some rules on income and if the person status is not in Student or Unemployment there are different rules to be applied on score & income

def IncomeScreenStatus(status_cd: Option[String],
                                   score: Option[Int],
                                 income: Option[Double]) : String  = {

 var pass_ind : String = "F"

 if (score.isDefined && income.isDefined && status_cd.isDefined) {

        val score : Int = score.get
        val income : Double = income.get
        val status_cd : String = status_cd.get

        if (status_cd == "STUDENT" || status_cd == "UNEMPLOYMENT") {
          pass_ind = (status_cd, income) match {
            case ("UNEMPLOYMENT", income) if income <= 7000 => "P"
            case ("STUDENT", income) if income <= 18000 => "P"
            case _ => "F"
          }
        }
        else {
          pass_ind = (income, score) match {
            case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
            case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
            case _ => "F"
          }
        }

      }

    pass_ind

}

Body:
As your example requires each field to be defined, you can zip the Options together.  I also like to use extractors in place of explicit guards on my case statements.

If your status is a finite set, I would also recommend using a sealed trait to represent it.

object Example {

  sealed trait Status
  case object Student extends Status
  case object Unemployed extends Status
  case object Other extends Status

  object PoorStudent {
    def unapply(income: Int) = if (income <= 18000) Some(income) else None
  }

  object PoorUnemployed {
    def unapply(income: Int) = if (income <= 7000) Some(income) else None
  }

  object IncomeScoreRange {
    def unapply(score: Int, income: Double) =
      if (((score < 100 || score > 150) && income <= 8500) || (income <= 10500 && (100 to 167 contains score)))
        Some((score, income))
      else
        None
  }

  def compute(status: Option[Status], score: Option[Int], income: Option[Double]): String = {

    (status, score, income).zipped
      .collect {
        case (Student, _, PoorStudent(_))                    => "P"
        case (Unemployed, _, PoorUnemployed(_))              => "P"
        case (Other, IncomeScoreRange(_, _))                 => "P"
      }
      .headOption
      .getOrElse("F")
  }
}


问:
How to delete a global variable from inside a function?
I have a global variable ser which I need to delete under certain circumstances:

```<code>global ser
ser = ['some', 'stuff']

def reset_ser():
    print('deleting serial configuration...')
    del ser
</code>```

If I call reset_ser() I get the error:

```<code>UnboundLocalError: local variable 'ser' referenced before assignment
</code>```

If I give the global variable to the function as an input I do not get the error, but the variable does not get deleted (I guess only inside the function itself). Is there a way of deleting the variable, or do I e.g.have to overwrite it to get rid of its contents?

答:
you could remove it from the global scope with:

```<code>del globals()['ser']
</code>```

a more complete example:

```<code>x = 3

def fn():
    var = 'x'
    g = globals()
    if var in g: del g[var]

print(x)
fn()
print(x) #NameError: name 'x' is not defined
</code>```

Body:
I have a global variable ser which I need to delete under certain circumstances:

global ser
ser = ['some', 'stuff']

def reset_ser():
    print('deleting serial configuration...')
    del ser

If I call reset_ser() I get the error:

UnboundLocalError: local variable 'ser' referenced before assignment

If I give the global variable to the function as an input I do not get the error, but the variable does not get deleted (I guess only inside the function itself). Is there a way of deleting the variable, or do I e.g.have to overwrite it to get rid of its contents?

Body:
you could remove it from the global scope with:

del globals()['ser']

a more complete example:

x = 3

def fn():
    var = 'x'
    g = globals()
    if var in g: del g[var]

print(x)
fn()
print(x) #NameError: name 'x' is not defined


问:
Cat file do some operation append from file output to first file
I'm trying to achieve the folowing:

```<code>  #!/bin/bash
  if [ -f file2 ]; then

  cat file2 > file1
  sed -i 's#some operation' file1
  cat file3 >> file1

  exit 0

  elif [ ! -f file2 ]; then

  cat file1 > file2
  sed -i 's#some operation' file1
  cat file3 >> file1

  exit 0

  else

  echo "something"
  exit 1

  fi
</code>```

Any ideas how to do it simpler ?
Without using that much cat and files ?

Thanks !

答:
```<code>sed -i 's# some operation' file1
cat file2 >> file1
</code>```

Body:
I'm trying to achieve the folowing:

  #!/bin/bash
  if [ -f file2 ]; then

  cat file2 > file1
  sed -i 's#some operation' file1
  cat file3 >> file1

  exit 0

  elif [ ! -f file2 ]; then

  cat file1 > file2
  sed -i 's#some operation' file1
  cat file3 >> file1

  exit 0

  else

  echo "something"
  exit 1

  fi

Any ideas how to do it simpler ?
Without using that much cat and files ?

Thanks !


问:
ItextSharp - RazorPdf put image on Pdf
How can I put an image on the itextSharp generated pdf?

I have a simple method at the controller...

```<code>    public ActionResult Pdf()
    {

        var pdfResult = new PdfResult(null,"Pdf");
        pdfResult.ViewBag.Title = "Title";

        return pdfResult;
    }
</code>```

And a simple view...

```<code>@{
    Layout = null;
}

<itext creationdate="@DateTime.Now.ToString()" producer="RazorPDF">

    Html Text for test.

    <img src="~/Images/sampleImage.png" />

</itext>
</code>```

Any help would be appreciated!

答:
this worked for me:</p>

```<code><div style="margin:auto;width:60%;padding:10px;">
    <img src="@Server.MapPath("~/assets/img/image.png")" />
</div>
</code>```

Title: ItextSharp - RazorPdf put image on Pdf

Body:
How can I put an image on the itextSharp generated pdf?

I have a simple method at the controller...

    public ActionResult Pdf()
    {

        var pdfResult = new PdfResult(null,"Pdf");
        pdfResult.ViewBag.Title = "Title";

        return pdfResult;
    }

And a simple view...

@{
    Layout = null;
}

<itext creationdate="@DateTime.Now.ToString()" producer="RazorPDF">

    Html Text for test.

</itext>

Any help would be appreciated!

Body:
this worked for me:

<div style="margin:auto;width:60%;padding:10px;">
    <img src="@Server.MapPath("~/assets/img/image.png")" />
</div>


问:
How to stop the sound/audio when you press the back button in the phone
how can i stop the audio from playing when i press the back button in my phone. when i go to another activity the audio is still playing unless i close the app. here's my code:</p>

```<code>    FloatingActionButton fab7 = (FloatingActionButton) this.findViewById(R.id.fab7);
    final MediaPlayer mp = MediaPlayer.create( this, R.raw.cebu);
    fab7.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {;

            if(mp.isPlaying()){
                mp.pause();
            } else {
                mp.start();
            }

        }
    });
</code>```

答:
Override Activity#onBackPress() method to stop your player when pressing Back button:

```<code>@Override
public void onBackPress() {
     if (mp != null) {
         mp.stop();
         mp.release();
         mp = null;
     }
}
</code>```

If you want to stop your player when your Activity finish, and don't care why (may be Back press, another Activity started, app crashed,..), you can override Activity#onStop() so you will make sure your music is immediately stop whenever your Activity gone!

```<code>@Override
public void onStop() {
    if (mp != null) {
         mp.stop();
         mp.release();
         mp = null;
    }
    super.onStop();
}
</code>```

Btw, note that you should use mp.stop() instead of mp.pause() then mp.release() to avoid memory/resources leak!

Body:
how can i stop the audio from playing when i press the back button in my phone. when i go to another activity the audio is still playing unless i close the app. here's my code:

    FloatingActionButton fab7 = (FloatingActionButton) this.findViewById(R.id.fab7);
    final MediaPlayer mp = MediaPlayer.create( this, R.raw.cebu);
    fab7.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {;

            if(mp.isPlaying()){
                mp.pause();
            } else {
                mp.start();
            }

        }
    });

Body:
Override Activity#onBackPress() method to stop your player when pressing Back button:

@Override
public void onBackPress() {
     if (mp != null) {
         mp.stop();
         mp.release();
         mp = null;
     }
}

If you want to stop your player when your Activity finish, and don't care why (may be Back press, another Activity started, app crashed,..), you can override Activity#onStop() so you will make sure your music is immediately stop whenever your Activity gone!

@Override
public void onStop() {
    if (mp != null) {
         mp.stop();
         mp.release();
         mp = null;
    }
    super.onStop();
}

Btw, note that you should use mp.stop() instead of mp.pause() then mp.release() to avoid memory/resources leak!


问:
ACK for 802.11 broadcast frame?
On 802.11 if I send a unicast frame, receiver will acknowledge by sending an ACK frame. But what about a broadcast frame? For example, A want to send a broadcast frame. A sends it to AP, AP acknowledges. Then AP broadcasts the frame. Does the AP listen for ACKs?

What about 802.3 Ethernet? Does Ethernet broadcasts ask for ACKs?

Thanks!

答: No. For broadcast data/frame AP won't expect and listen acks. In 802.3 Ethernet also it doesn't give ack for broadcast frame</p>

Title: ACK for 802.11 broadcast frame?


答:
1.) declare MediaPlayer mp; outside onCreate

2.) override onStop and apply the same logic of click listener inside onStop

why onStop not onBackPress?

Because you want to pause the player when you go outside app as well as when you go to another activity

```<code>MediaPlayer mp;
onCreate(..){
    mp = MediaPlayer.create( this, R.raw.cebu);
    fab7.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {;
            pausePlayer();
        }
    });
}

@Override
public void onStop(){
    super.onStop()
    pausePlayer();
}

void pausePlayer(){
    if(mp.isPlaying()){
        mp.pause();
    } else {
        mp.start();
    }
}

@Override
public void onBackPress() {
     pausePlayer();
     mp.stop();
}
</code>```

Title: How to stop the sound/audio when you press the back button in the phone

Body:
1.) declare MediaPlayer mp; outside onCreate

2.) override onStop and apply the same logic of click listener inside onStop

why onStop not onBackPress?

Because you want to pause the player when you go outside app as well as when you go to another activity

MediaPlayer mp;
onCreate(..){
    mp = MediaPlayer.create( this, R.raw.cebu);
    fab7.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {;
            pausePlayer();
        }
    });
}

@Override
public void onStop(){
    super.onStop()
    pausePlayer();
}

void pausePlayer(){
    if(mp.isPlaying()){
        mp.pause();
    } else {
        mp.start();
    }
}

@Override
public void onBackPress() {
     pausePlayer();
     mp.stop();
}


问:
Toggle multiple css classes on div with javascript
I have a problem to toggle between 4 color classes.
I trying to change color everytime this function is used.

```<code>function changeBackground() {
    var all = getSelected();

    var blue = document.getElementsByClassName("blue");
    for (var i = 0; i < all.length; i++) {
        all[i].classList.add("green");
        all[i].classList.remove("blue");
    }

    var red = document.getElementsByClassName("red");
    for (var i = 0; i < red.length; i++) {
        all[i].classList.add("blue");
        all[i].classList.remove("red");
    }

    var yellow = document.getElementsByClassName("yellow");
    for (var i = 0; i < yellow.length; i++) {
        all[i].classList.add("red");
        all[i].classList.remove("yellow");
    }

    for (var i = 0; i < all.length; i++) {
        all[i].classList.add("yellow");
        all[i].classList.remove("green");

    }
}
</code>```

getSelected returns document.getElementsByClassName("selected");
and make sure only divs who are selected do change background.

Html looks like this:

Works well untill it comes to blue->green and the classes won't be removed.
How do i solve this?

答:
I see a few issues with your code:

1- You loop on all of the boxes for each color. You should replace

```<code>for (var i = 0; i < blue.length; i++) {
    all[i].classList.add("green");
    all[i].classList.remove("blue");
}
</code>```

by

```<code>for (var i = 0; i < blue.length; i++) {
    blue[i].classList.add("green");
    blue[i].classList.remove("blue");
}
</code>```

2- You should select all your divs before making any modification, to make sure you only select the one that were that color before starting the function.

```<code>var blue = document.getElementsByClassName("blue");
var red = document.getElementsByClassName("red");
var yellow = document.getElementsByClassName("yellow");
var green = document.getElementsByClassName("green");
</code>```

3- You currently use getSelected to get all the selected divs but then you run the code on every element of the document.

I think instead of using 4 loops, you should only create one and check the class for each elemnts of all, it would resolve a lot of you issues. Something like:

```<code>function changeBackground() {
    var all = getSelected();

    for (var i = 0; i < all.length; i++) {
        var colorBlue = all[i].classList.contains("blue")
        var colorRed = all[i].classList.contains("red")
        var colorGreen = all[i].classList.contains("greed")
        var colorYellow = all[i].classList.contains("yellow")
        if(colorBlue){
           all[i].classList.add("green");
           all[i].classList.remove("blue");
        }
        //check other colors here the same way
    }
}
</code>```

Body:
I have a problem to toggle between 4 color classes.
I trying to change color everytime this function is used.

function changeBackground() {
    var all = getSelected();

    var blue = document.getElementsByClassName("blue");
    for (var i = 0; i < all.length; i++) {
        all[i].classList.add("green");
        all[i].classList.remove("blue");
    }

    var red = document.getElementsByClassName("red");
    for (var i = 0; i < red.length; i++) {
        all[i].classList.add("blue");
        all[i].classList.remove("red");
    }

    var yellow = document.getElementsByClassName("yellow");
    for (var i = 0; i < yellow.length; i++) {
        all[i].classList.add("red");
        all[i].classList.remove("yellow");
    }

    for (var i = 0; i < all.length; i++) {
        all[i].classList.add("yellow");
        all[i].classList.remove("green");

    }
}

getSelected returns document.getElementsByClassName("selected");
and make sure only divs who are selected do change background.

Html looks like this:

Works well untill it comes to blue->green and the classes won't be removed.
How do i solve this?

Body:
I see a few issues with your code:

1- You loop on all of the boxes for each color. You should replace

for (var i = 0; i < blue.length; i++) {
    all[i].classList.add("green");
    all[i].classList.remove("blue");
}

by

for (var i = 0; i < blue.length; i++) {
    blue[i].classList.add("green");
    blue[i].classList.remove("blue");
}

2- You should select all your divs before making any modification, to make sure you only select the one that were that color before starting the function.

var blue = document.getElementsByClassName("blue");
var red = document.getElementsByClassName("red");
var yellow = document.getElementsByClassName("yellow");
var green = document.getElementsByClassName("green");

3- You currently use getSelected to get all the selected divs but then you run the code on every element of the document.

I think instead of using 4 loops, you should only create one and check the class for each elemnts of all, it would resolve a lot of you issues. Something like:

function changeBackground() {
    var all = getSelected();

    for (var i = 0; i < all.length; i++) {
        var colorBlue = all[i].classList.contains("blue")
        var colorRed = all[i].classList.contains("red")
        var colorGreen = all[i].classList.contains("greed")
        var colorYellow = all[i].classList.contains("yellow")
        if(colorBlue){
           all[i].classList.add("green");
           all[i].classList.remove("blue");
        }
        //check other colors here the same way
    }
}


问:
Appending a value from a list to an empty list in python
One list contains values and one is empty. I want to take out two values from the list with data and place it into the empty list using a for loop. I know how to get one value. However, I am not sure how to get the other. Here is my code below:

```<code> all_fruits = ['apples', 'cherry', 'pear', 'strawberry', 'peach']
# The above list is a list of all fruits

# Now lets creat a blank list called favorite fruit
favorite_fruit = []

# The objective is to choose two fruits from the all fruits list and append them to the favorite fruit list

for fruit in all_fruits:
    if fruit == 'apples':
        favorite_fruit.append(fruit)

print favorite_fruit

Output: ['apples']
</code>```

I want the favorite_fruit variable to output ['apples', 'peaches'] or ['apples', 'cherry']. How do I go about doing this? Thanks

答:
You simply have to add a condition in your for loop to detect the second favorite fruit.

```<code>for fruit in all_fruits:

    if fruit == 'apples' or fruit == 'peach':
        favorite_fruit.append(fruit)

print favorite_fruit

Output: ['apples', 'peach']
</code>```

Or in general you can build your favorite fruit list as a filtered list of the initial one like so.

```<code>def is_a_favorite_fruit(fruit):
    return fruit == 'apples' or fruit == 'peach'

favorite_fruits = [fruit for fruit in all_fruits if is_a_favorite_fruit(fruit)]

print favorite_fruit

Output: ['apples', 'peach']
</code>```

Body:
One list contains values and one is empty. I want to take out two values from the list with data and place it into the empty list using a for loop. I know how to get one value. However, I am not sure how to get the other. Here is my code below:

 all_fruits = ['apples', 'cherry', 'pear', 'strawberry', 'peach']
# The above list is a list of all fruits

# Now lets creat a blank list called favorite fruit
favorite_fruit = []

# The objective is to choose two fruits from the all fruits list and append them to the favorite fruit list

for fruit in all_fruits:
    if fruit == 'apples':
        favorite_fruit.append(fruit)

print favorite_fruit

Output: ['apples']

I want the favorite_fruit variable to output ['apples', 'peaches'] or ['apples', 'cherry']. How do I go about doing this? Thanks

Body:
You simply have to add a condition in your for loop to detect the second favorite fruit.

for fruit in all_fruits:

    if fruit == 'apples' or fruit == 'peach':
        favorite_fruit.append(fruit)

print favorite_fruit

Output: ['apples', 'peach']

Or in general you can build your favorite fruit list as a filtered list of the initial one like so.

def is_a_favorite_fruit(fruit):
    return fruit == 'apples' or fruit == 'peach'

favorite_fruits = [fruit for fruit in all_fruits if is_a_favorite_fruit(fruit)]

print favorite_fruit

Output: ['apples', 'peach']


问:
JS: functions arguments default values
In some languages you can set default values for function's arguments:

```<code>function Foo(arg1 = 50, arg2 = 'default') {
    //...
}
</code>```

How do you do it in JavaScript?

答:
I prefer the == null check instead of typeof(arg1) === undefined (as the jQuery library does internally: http://docs.jquery.com/JQuery_Core_Style_Guidelines#JSLint). Not only is it more concise, it also handles both null and undefined, so that client code can pass in null and get the default applied.

It is also possible to wrap the function in another function that supplies defaults. The prototypejs library has a function that supplies the argumentNames() (or if you don't want to use prototype, you can just borrow the implementation -- it's just a regex applied against the results of the function's toString()).

So you could do something like this:

```<code>var Foo = defaults(Foo, { arg1: 50, arg2: 'default' });
function Foo(arg1, arg2) {
  //...
}
</code>```

And the implementation of defaults() would look something like this:

```<code>function defaults(fn, def) {
  return function() {
    var arg_names = fn.argumentNames();
    var nArgs = args.length;
    for (var nArg = 0; nArg < nArgs; ++nArg) {
      if (arguments[nArg] == null && arg_names[nArg] in def)
        arguments[nArg] = def[arg_names[nArg]];
    }
    fn.apply(this, arguments);
  }
}
</code>```

Of course, that's untested code and the way it's written, it requires the Prototype library. But all that said, the == null approach inside the function is more natural to Javascript, is easier to debug (you don't have another function layer to step through), and I find it easier to read:

```<code>function Foo(arg1, arg2) {
  if (arg1 == null) arg1 = 50;
  if (arg2 == null) arg2 = 'default';
}
</code>```

Title: JS: functions arguments default values

Body:
In some languages you can set default values for function's arguments:

function Foo(arg1 = 50, arg2 = 'default') {
    //...
}

How do you do it in JavaScript?

Body:
I prefer the == null check instead of typeof(arg1) === undefined (as the jQuery library does internally: http://docs.jquery.com/JQuery_Core_Style_Guidelines#JSLint). Not only is it more concise, it also handles both null and undefined, so that client code can pass in null and get the default applied.

It is also possible to wrap the function in another function that supplies defaults. The prototypejs library has a function that supplies the argumentNames() (or if you don't want to use prototype, you can just borrow the implementation -- it's just a regex applied against the results of the function's toString()).

So you could do something like this:

var Foo = defaults(Foo, { arg1: 50, arg2: 'default' });
function Foo(arg1, arg2) {
  //...
}

And the implementation of defaults() would look something like this:

function defaults(fn, def) {
  return function() {
    var arg_names = fn.argumentNames();
    var nArgs = args.length;
    for (var nArg = 0; nArg < nArgs; ++nArg) {
      if (arguments[nArg] == null && arg_names[nArg] in def)
        arguments[nArg] = def[arg_names[nArg]];
    }
    fn.apply(this, arguments);
  }
}

Of course, that's untested code and the way it's written, it requires the Prototype library. But all that said, the == null approach inside the function is more natural to Javascript, is easier to debug (you don't have another function layer to step through), and I find it easier to read:

function Foo(arg1, arg2) {
  if (arg1 == null) arg1 = 50;
  if (arg2 == null) arg2 = 'default';
}


问:
Simple download file /update it
I want to update my app without google store I have already checking if there's new version. Now I need to download and install file I don't have idea how. I saw some librares but they don't download file :(. Is there any simple idea to download file ? I saw I post about this but it didn't help me at all.. I saw Some posts with codes but this didn't work for me.</p>

答: Put the app in a special directory in your web server then make a flag-version in the server and your app too. Whenever you put the new version in the special directory, just change the version. In your app side check that if the flag has changed then download it from the link.</p>

Title: Simple download file /update it


问:
Get index of object in python using value without looping
So basically I have this:

```<code>data = [
    {
        "id" : "hello",
        ...
    },
    {
        "id" : "world",
         ...
    }
]
</code>```

and I want to get the result:

```<code>"1"
</code>```

if I enter something like:

```<code>get_index(id="world")
</code>```

And the main thing is that I don't want to loop through the array since there is a lot of data in it. If I were to loop it would be easy and I would end up with some code like:

```<code>for obj in data:
    if obj['id'] == 'hello':
        print(obj['id'])
</code>```

But is there a direct way of doing this without looping?

答:
You'll have to at least go through the whole array once.

However, if you need to search for many different keys in the array, you could build an index:

```<code>>>> data = [
...     {
...         "id" : "hello",
...     },
...     {
...         "id" : "world",
...     }
... ]
>>> get_index= {item["id"]:counter for (counter, item) in enumerate(data)}
>>> get_index["hello"]
0
>>> get_index["world"]
1
>>>
</code>```

As you now have a lookup table, queries to ids should now be constant time operations:
How expensive are Python dictionaries to handle?

Body:
So basically I have this:

data = [
    {
        "id" : "hello",
        ...
    },
    {
        "id" : "world",
         ...
    }
]

and I want to get the result:

"1"

if I enter something like:

get_index(id="world")

And the main thing is that I don't want to loop through the array since there is a lot of data in it. If I were to loop it would be easy and I would end up with some code like:

for obj in data:
    if obj['id'] == 'hello':
        print(obj['id'])

But is there a direct way of doing this without looping?

Body:
You'll have to at least go through the whole array once.

However, if you need to search for many different keys in the array, you could build an index:

>>> data = [
...     {
...         "id" : "hello",
...     },
...     {
...         "id" : "world",
...     }
... ]
>>> get_index= {item["id"]:counter for (counter, item) in enumerate(data)}
>>> get_index["hello"]
0
>>> get_index["world"]
1
>>>

As you now have a lookup table, queries to ids should now be constant time operations:
How expensive are Python dictionaries to handle?


问:
Get the name of the current database from Heroku via command line
Is there a command that gets the name of the current Postgres in a Heroku application?
I am writing a batch file that should be used in multiple stages of my application. Each time the only difference is the name of the database.
Using heroku pg, I could retrieve the complete URL of the database:

```<code>heroku pg:credentials:url DATABASE
</code>```

Maybe I could extract the name from the URL using some Linux tools, but in the context of batch files, I prefer not to use anything but Heroku tools to keep environment independency.

答: Heroku doesn't provide a parsed version of $DATABASE_URL (which you can also get with heroku config:get DATABASE_URL. If you need the database name, you'll need to parse it yourself or use a tool to do so.

Body:
Is there a command that gets the name of the current Postgres in a Heroku application?
I am writing a batch file that should be used in multiple stages of my application. Each time the only difference is the name of the database.
Using heroku pg, I could retrieve the complete URL of the database:

heroku pg:credentials:url DATABASE

Maybe I could extract the name from the URL using some Linux tools, but in the context of batch files, I prefer not to use anything but Heroku tools to keep environment independency.


问:
linprog in scipy.optimize - checking solution
I tried to solve linear system with constraints using linprog from  scipy.optimize, but got answer contradicting some inequalities.
Here is my set up:

```<code>import numpy as np
from scipy.optimize import linprog
c = np.array([1,0,0,0,0,0,0])
A_ub = np.identity(7)*(-1)
b_ub = np.array([[-2],[-2],[-2],[-2],[-2],[-2],[-2]])
A_eq = np.array([[1,1,1,1,1,1,0],[0.3,1.3,0.9,0,0,0,-1],[0.3,0,0,0,0,0,-2/3],
                 [0,0.65,0,0,0,0,-1/15],[0,0,0.3,0,0,0,-1/15]])
b_eq = np.array([[100],[0],[0],[0],[0]])
res = linprog(c = c, A_ub=A_ub, b_ub=b_ub, A_eq = A_eq, b_eq = b_eq)
</code>```

Here is the answer:

```<code>fun: -0.0
 message: 'Optimization terminated successfully.'
     nit: 15
   slack: array([ -2.,  -2.,  -2.,  94.,   0.,   0.,  -2.])
  status: 0
 success: True
       x: array([  0.00000000e+00,  -8.88178420e-16,  -1.77635684e-15,
         9.60000000e+01,   2.00000000e+00,   2.00000000e+00,
        -7.10542736e-15])
</code>```

As you can see x_2 => 8.88178420e-16 is not smaller than -2.

Can somebody clarify why it happens?

Here is link to documentation:
linprog

答:
In general, scipy's linprog (method='simplex') is somewhat broken and not maintained much anymore.

Negative slacks like:

```<code>slack: array([ -2.,  -2.,  -2.,  94.,   0.,   0.,  -2.])
</code>```

should never result in a valid solution!

While i saw some bad things in linprog (not finding an existing feasible solution), this looks very very bad (claiming an infeasible solution to be correct)!

So three things:

scipy >= 1.0 has a new Interior-point based LP-solver method='interior-point' which is more robust and more advanced

algorithmic-wise very different!

for use-cases like yours the only difference (apart from robustness and performance) is in the nature of solutions:

not guaranteed to be basic solutions (no support for cross-over; commercial solvers allow that)!

use the bounds argument instead of those inequalities to describe variable-bounds!

more specialized handling!

you described: -x <= -2 <-> x >= 2

the expected and correct solution is x >= 2!

IPM on your code:

```<code>     con: array([ 2.77992740e-10, -1.52664548e-11,  3.69659858e-12, -5.92570437e-12,
       -2.37077025e-12])
     fun: 43.3333333331385
 message: 'Optimization terminated successfully.'
     nit: 5
   slack: array([4.13333333e+01, 6.92779167e-13, 2.33333333e+00, 1.47777778e+01,
       1.47777778e+01, 1.47777778e+01, 1.75000000e+01])
  status: 0
 success: True
       x: array([43.33333333,  2.        ,  4.33333333, 16.77777778, 16.77777778,
       16.77777778, 19.5       ])
</code>```

Body:
I tried to solve linear system with constraints using linprog from  scipy.optimize, but got answer contradicting some inequalities.
Here is my set up:

import numpy as np
from scipy.optimize import linprog
c = np.array([1,0,0,0,0,0,0])
A_ub = np.identity(7)*(-1)
b_ub = np.array([[-2],[-2],[-2],[-2],[-2],[-2],[-2]])
A_eq = np.array([[1,1,1,1,1,1,0],[0.3,1.3,0.9,0,0,0,-1],[0.3,0,0,0,0,0,-2/3],
                 [0,0.65,0,0,0,0,-1/15],[0,0,0.3,0,0,0,-1/15]])
b_eq = np.array([[100],[0],[0],[0],[0]])
res = linprog(c = c, A_ub=A_ub, b_ub=b_ub, A_eq = A_eq, b_eq = b_eq)

Here is the answer:

fun: -0.0
 message: 'Optimization terminated successfully.'
     nit: 15
   slack: array([ -2.,  -2.,  -2.,  94.,   0.,   0.,  -2.])
  status: 0
 success: True
       x: array([  0.00000000e+00,  -8.88178420e-16,  -1.77635684e-15,
         9.60000000e+01,   2.00000000e+00,   2.00000000e+00,
        -7.10542736e-15])

As you can see x_2 => 8.88178420e-16 is not smaller than -2.

Can somebody clarify why it happens?

Here is link to documentation:
linprog

Body:
In general, scipy's linprog (method='simplex') is somewhat broken and not maintained much anymore.

Negative slacks like:

slack: array([ -2.,  -2.,  -2.,  94.,   0.,   0.,  -2.])

should never result in a valid solution!

While i saw some bad things in linprog (not finding an existing feasible solution), this looks very very bad (claiming an infeasible solution to be correct)!

So three things:

scipy >= 1.0 has a new Interior-point based LP-solver method='interior-point' which is more robust and more advanced

algorithmic-wise very different!

for use-cases like yours the only difference (apart from robustness and performance) is in the nature of solutions:

not guaranteed to be basic solutions (no support for cross-over; commercial solvers allow that)!

use the bounds argument instead of those inequalities to describe variable-bounds!

more specialized handling!

you described: -x <= -2 <-> x >= 2

the expected and correct solution is x >= 2!

IPM on your code:

     con: array([ 2.77992740e-10, -1.52664548e-11,  3.69659858e-12, -5.92570437e-12,
       -2.37077025e-12])
     fun: 43.3333333331385
 message: 'Optimization terminated successfully.'
     nit: 5
   slack: array([4.13333333e+01, 6.92779167e-13, 2.33333333e+00, 1.47777778e+01,
       1.47777778e+01, 1.47777778e+01, 1.75000000e+01])
  status: 0
 success: True
       x: array([43.33333333,  2.        ,  4.33333333, 16.77777778, 16.77777778,
       16.77777778, 19.5       ])