问:
How to change Android O / Oreo / api 26 app language
I want to change the language of the app and this works fine until API 26.

For api > 25 I put Locale.setDefault(Locale.Category.DISPLAY, mynewlanglocale); before setContentView(R.layout.activity_main); but nothing changes.

The docs don't explain too much about this.

答:
updateConfiguration is deprecated and you should use createConfigurationContext. I solved it this way:

```<code>    @Override
    protected void attachBaseContext(Context newBase) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Configuration config = newBase.getResources().getConfiguration();
            //Update your config with the Locale i. e. saved in SharedPreferences
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
            String language = prefs.getString(SP_KEY_LANGUAGE, "en_US");
            Locale.setDefault(locale);
            config.setLocale(new Locale(language));
            newBase = newBase.createConfigurationContext(config);
        }
        super.attachBaseContext(newBase);
    }
</code>```

Body:
updateConfiguration is deprecated and you should use createConfigurationContext. I solved it this way:

    @Override
    protected void attachBaseContext(Context newBase) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Configuration config = newBase.getResources().getConfiguration();
            //Update your config with the Locale i. e. saved in SharedPreferences
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
            String language = prefs.getString(SP_KEY_LANGUAGE, "en_US");
            Locale.setDefault(locale);
            config.setLocale(new Locale(language));
            newBase = newBase.createConfigurationContext(config);
        }
        super.attachBaseContext(newBase);
    }


来源: stackexchange

问:
How do I turn django's settings object into a dict?
What I have:

```<code>from django.conf import settings

def settings_to_dict(settings)
    cfg = {
        'BOTO3_ACCESS_KEY': settings.BOTO3_ACCESS_KEY,
        'BOTO3_SECRET_KEY': settings.BOTO3_SECRET_KEY,
        # repeat ad nauseum
    }
    return cfg

instance = SomeClassInstantiatedWithADict(**settings_to_dict(settings))
</code>```

What I'd like (using Django 1.11):

```<code>from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.to_dict())
</code>```

I've tried:

```<code>from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.__dict__)
</code>```

which is close, but __dict__ only gets a small subset of the settings, which I assume are hard coded ones as opposed to added attributes. Thanks for any help!

答: Check settings.__dict__['_wrapped'].__dict__ in your shell. It seems there is everything inside. Not sure however if it's the right way to access this.

ContentLicense: CC BY-SA 3.0

Body:
What I have:

from django.conf import settings

def settings_to_dict(settings)
    cfg = {
        'BOTO3_ACCESS_KEY': settings.BOTO3_ACCESS_KEY,
        'BOTO3_SECRET_KEY': settings.BOTO3_SECRET_KEY,
        # repeat ad nauseum
    }
    return cfg

instance = SomeClassInstantiatedWithADict(**settings_to_dict(settings))

What I'd like (using Django 1.11):

from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.to_dict())

I've tried:

from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.__dict__)

which is close, but __dict__ only gets a small subset of the settings, which I assume are hard coded ones as opposed to added attributes. Thanks for any help!


问:
extract a protion of html file
I have used dompdf to create pdf file, I have used a portion of the html file ie between  to generate pdf . (cut & pasted manual way)

since I have a valid pdf out put now, I want to further automate the process,

I want to copy all contents between  tables

```<code><table> </table>
</code>```

to a file, would like to know  what would be possible options in php.
any suggestion is highly appreciated

答:
Try This
To Extract Data between tags try this code
Here $source will be your complete html code. And $match will be the data extracted between tags.

Code:

preg_match("'
(.*?)
'si", $source, $match);
if($match) echo "result=".$match[1];

Reference: Preg match text in php between html tags

Title: extract a protion of html file

Body:
I have used dompdf to create pdf file, I have used a portion of the html file ie between  to generate pdf . (cut & pasted manual way)

since I have a valid pdf out put now, I want to further automate the process,

I want to copy all contents between  tables

to a file, would like to know  what would be possible options in php.
any suggestion is highly appreciated

Body:
Try This
To Extract Data between tags try this code
Here $source will be your complete html code. And $match will be the data extracted between tags.

Code:

preg_match("'<table>(.*?)</table>'si", $source, $match);
if($match) echo "result=".$match[1];

Reference: Preg match text in php between html tags


问:
What verb would describe the relationship between a C# class and its Attribute?
Considering the following:

```<code>[Export]
public class BudgetView : ViewBase, IView
{
    // Members Galore
}
</code>```

It is clear that you would say BudgetView extends ViewBase, and it implements IView, but what does it to to poor old Export?

Perhaps BudgetView uses Export?
Or BudgetView applies Export?

I need this for my documentation.  I'm need to be very formal and very detailed.

Edit:

My UML tool is very restrictive about what I can and cannot do.  I cannot make custom stereotypes for instance.

答: Perhaps BudgetView is attributed by Export. Or you could use a term from Java and say Export annotates BudgetView.

ContentLicense: CC BY-SA 2.5

Body:
Considering the following:

[Export]
public class BudgetView : ViewBase, IView
{
    // Members Galore
}

It is clear that you would say BudgetView extends ViewBase, and it implements IView, but what does it to to poor old Export?

Perhaps BudgetView uses Export?
Or BudgetView applies Export?

I need this for my documentation.  I'm need to be very formal and very detailed.

Edit:

My UML tool is very restrictive about what I can and cannot do.  I cannot make custom stereotypes for instance.


问:
Java : Need to get the same functionality of the Integer.toHexString() with a String parameter and not an Int parameter due to NumberFormat Exception
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.

Because:

The int data type is a 32-bit signed two's complement integer. It has
  a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

Code Throwing the NumberFormatException:

```<code>String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
</code>```

How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?

答:
If your input value can be arbitrarily large, then @dasblinkenlight's answer involving BigInteger is your best bet.

However, if your value is less than 263, then you can just use Long instead of Integer:

```<code>String dec = "9999999999";
String hex = Long.toHexString(Long.parseLong(dec));
System.out.println(hex);                             // 2540be3ff
</code>```

Live demo.

Body:
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.

Because:

The int data type is a 32-bit signed two's complement integer. It has
  a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

Code Throwing the NumberFormatException:

String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException

How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?

Body:
If your input value can be arbitrarily large, then @dasblinkenlight's answer involving BigInteger is your best bet.

However, if your value is less than 263, then you can just use Long instead of Integer:

String dec = "9999999999";
String hex = Long.toHexString(Long.parseLong(dec));
System.out.println(hex);                             // 2540be3ff

Live demo.


问:
node crached with socket io in https
i have a node server with socket in https to print tickets.
when i lunch the server it's ok, but when i send a socket to print, the server crash and show this error :

```<code>node: ../src/util-inl.h:196: TypeName* node::Unwrap(v8::Local<v8::Object>) [with TypeName = node::TLSWrap]: Assertion `(object->InternalFieldCount()) > (0)' failed.
Abandon
</code>```

i looked for on the net and the people said to change the version node, so i change the version node to 3.8, 4.4, 8.4 and now 9.2 and the error pop again...

i show you the code :

```<code>/**
 * Created by thibault on 13/09/17.
 */

'use strict';

let serverSettings    = require('./config').serverSettings;
let printers          = require('./config').printers;
let authkeyUdooServer = require('./config').authkeyUdoo;
let Log               = require('./utils/log');
let port              = serverSettings.port;
let bodyParser        = require('body-parser');
let socket            = require('socket.io');
let pdf               = require('html-pdf');
let express           = require('express');
let printer           = require('printer');
let moment            = require('moment');
var server            = (serverSettings.useSSL) ? require('https') : require('http');
let fs                = require('fs');
let he                = require('he');
let app               = express();
let logInstantce = new Log();

/*
 |------------------------------------------------------------------------------
 | Body parser
 |------------------------------------------------------------------------------
 */
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({   // to support URL-encoded bodies
    extended: true,
    type: 'application/x-www-form-urlencoded'
}));

if (serverSettings.useSSL)
{
    var credentials = {
        key:  fs.readFileSync(serverSettings.SSL_KEY),
        cert: fs.readFileSync(serverSettings.SSL_CERT)
    };
    server          = server.Server(credentials, app);
}
else
{
    server = server.Server(app);
}
server.listen(port, function()
{
    console.log('\n');
    console.log(' |------------------------------------------------------------');
    console.log(' |');
    console.log(' | Server NodeSync started');
    console.log(' |');
    console.log(' |------------------------------------------------------------');
    console.log(' |');
    console.log(' |  Port     : ' + serverSettings.port);
    console.log(' |  SSL ?    : ' + ((serverSettings.useSSL) ? 'Yes' : 'No'));
    let url = 'http://' + serverSettings.url;
    if (serverSettings.useSSL)
    {
        console.log(' |  SSL key  : ' + serverSettings.SSL_KEY);
        console.log(' |  SSL cert : ' + serverSettings.SSL_CERT);
        url = 'https://' + serverSettings.url;
    }
    console.log(' |  URL      : ' + url);
    console.log(' |');
    console.log(' |------------------------------------------------------------\n\n');
});

let io = socket(server);

io.on('connection', (socket) => {
    logInstantce.success('New socket connection');
    console.log('socket started! At ' + serverSettings.url);

    socket.on('printTicket', (data) =>
    {
console.log('je passe');
        let htmlString          = he.decode(data.html);
        let width               = data.width;
        let height              = data.height;
        let nbPrint             = data.nbPrint;
        let typePrinter         = data.typePrinter;
        let authkeyUdooAccount  = data.authkeyUdooAccount;
        if (authkeyUdooAccount === authkeyUdooServer)
        {
            let options = {
                "height": height + 'px',        // allowed units: mm, cm, in, px
                "width":  width + 'px',
            };

            let nameFile = 'ticket_' +  moment().format('YYYYMMDDHHmmss');

            fs.writeFile('html/' + nameFile + '.html', htmlString, (err) =>
            {
                if (err)
                {
                    logInstantce.error('create html err : ' + err);
                    socket.emit('printError', 'create html err : ' + err);
                }
                else
                {
                    let html = fs.readFileSync('html/' + nameFile + '.html', 'utf8');

                    pdf.create(html, options).toFile('pdf/' + nameFile + '.pdf', (err, res) =>
                    {
                        if (err)
                        {
                            logInstantce.error('create pdf err : ' + err);
                            socket.emit('printError', 'create pdf err : ' + err);
                        }
                        else
                        {
                            for (let i = 0; i < nbPrint; i++)
                            {
                                printer.printDirect({
                                    printer: printers[typePrinter],
                                    data: fs.readFileSync('pdf/' + nameFile + '.pdf'),
                                    type: 'PDF',
                                    success: (id) =>
                                             {
                                                 logInstantce.success('printed with id ' + id);
                                                 if (i === (nbPrint - 1))
                                                 {
                                                     socket.emit('printSuccess');
                                                 }
                                             },
                                    error: (err) =>
                                             {
                                                 logInstantce.error('error on printing: ' + err);
                                                 if (i === (nbPrint - 1))
                                                 {
                                                     socket.emit('printError', 'error on printing: ' + err);
                                                 }
                                             }
                                })
                            }
                        }

                        //suppression des fichiers
                        fs.unlink('./html/' + nameFile + '.html', (err) =>
                        {
                            if(err) logInstantce.error('create html err : ' + err);

                            fs.unlink('./pdf/' + nameFile + '.pdf', (err) =>
                            {
                                if(err) logInstantce.error('create pdf err : ' + err);

                                logInstantce.success('file pdf and html deleted successfully : ' + nameFile);
                            });
                        });
                    });
                }
            });
        }
        else
        {
            logInstantce.error('wrong autkey udoo');
            socket.emit('printError', 'wrong autkey udoo');
        }
    });
});
</code>```

before i use just in http and it work fine.
the certificate is good beacause if i want i can go on the url of server and it's used on others projects.

so if you have an idea, i take it :)
thanks in advance

答:
i found the solution.
i set the node's version 6.0.0 and downlaod my node packages and it's good :)</p>

Title: node crached with socket io in https

Body:
i have a node server with socket in https to print tickets.
when i lunch the server it's ok, but when i send a socket to print, the server crash and show this error :

node: ../src/util-inl.h:196: TypeName* node::Unwrap(v8::Local<v8::Object>) [with TypeName = node::TLSWrap]: Assertion `(object->InternalFieldCount()) > (0)' failed.
Abandon

i looked for on the net and the people said to change the version node, so i change the version node to 3.8, 4.4, 8.4 and now 9.2 and the error pop again...

i show you the code :

/**
 * Created by thibault on 13/09/17.
 */

'use strict';

let serverSettings    = require('./config').serverSettings;
let printers          = require('./config').printers;
let authkeyUdooServer = require('./config').authkeyUdoo;
let Log               = require('./utils/log');
let port              = serverSettings.port;
let bodyParser        = require('body-parser');
let socket            = require('socket.io');
let pdf               = require('html-pdf');
let express           = require('express');
let printer           = require('printer');
let moment            = require('moment');
var server            = (serverSettings.useSSL) ? require('https') : require('http');
let fs                = require('fs');
let he                = require('he');
let app               = express();
let logInstantce = new Log();

/*
 |------------------------------------------------------------------------------
 | Body parser
 |------------------------------------------------------------------------------
 */
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({   // to support URL-encoded bodies
    extended: true,
    type: 'application/x-www-form-urlencoded'
}));

if (serverSettings.useSSL)
{
    var credentials = {
        key:  fs.readFileSync(serverSettings.SSL_KEY),
        cert: fs.readFileSync(serverSettings.SSL_CERT)
    };
    server          = server.Server(credentials, app);
}
else
{
    server = server.Server(app);
}
server.listen(port, function()
{
    console.log('\n');
    console.log(' |------------------------------------------------------------');
    console.log(' |');
    console.log(' | Server NodeSync started');
    console.log(' |');
    console.log(' |------------------------------------------------------------');
    console.log(' |');
    console.log(' |  Port     : ' + serverSettings.port);
    console.log(' |  SSL ?    : ' + ((serverSettings.useSSL) ? 'Yes' : 'No'));
    let url = 'http://' + serverSettings.url;
    if (serverSettings.useSSL)
    {
        console.log(' |  SSL key  : ' + serverSettings.SSL_KEY);
        console.log(' |  SSL cert : ' + serverSettings.SSL_CERT);
        url = 'https://' + serverSettings.url;
    }
    console.log(' |  URL      : ' + url);
    console.log(' |');
    console.log(' |------------------------------------------------------------\n\n');
});

let io = socket(server);

io.on('connection', (socket) => {
    logInstantce.success('New socket connection');
    console.log('socket started! At ' + serverSettings.url);

    socket.on('printTicket', (data) =>
    {
console.log('je passe');
        let htmlString          = he.decode(data.html);
        let width               = data.width;
        let height              = data.height;
        let nbPrint             = data.nbPrint;
        let typePrinter         = data.typePrinter;
        let authkeyUdooAccount  = data.authkeyUdooAccount;
        if (authkeyUdooAccount === authkeyUdooServer)
        {
            let options = {
                "height": height + 'px',        // allowed units: mm, cm, in, px
                "width":  width + 'px',
            };

            let nameFile = 'ticket_' +  moment().format('YYYYMMDDHHmmss');

            fs.writeFile('html/' + nameFile + '.html', htmlString, (err) =>
            {
                if (err)
                {
                    logInstantce.error('create html err : ' + err);
                    socket.emit('printError', 'create html err : ' + err);
                }
                else
                {
                    let html = fs.readFileSync('html/' + nameFile + '.html', 'utf8');

                    pdf.create(html, options).toFile('pdf/' + nameFile + '.pdf', (err, res) =>
                    {
                        if (err)
                        {
                            logInstantce.error('create pdf err : ' + err);
                            socket.emit('printError', 'create pdf err : ' + err);
                        }
                        else
                        {
                            for (let i = 0; i < nbPrint; i++)
                            {
                                printer.printDirect({
                                    printer: printers[typePrinter],
                                    data: fs.readFileSync('pdf/' + nameFile + '.pdf'),
                                    type: 'PDF',
                                    success: (id) =>
                                             {
                                                 logInstantce.success('printed with id ' + id);
                                                 if (i === (nbPrint - 1))
                                                 {
                                                     socket.emit('printSuccess');
                                                 }
                                             },
                                    error: (err) =>
                                             {
                                                 logInstantce.error('error on printing: ' + err);
                                                 if (i === (nbPrint - 1))
                                                 {
                                                     socket.emit('printError', 'error on printing: ' + err);
                                                 }
                                             }
                                })
                            }
                        }

                        //suppression des fichiers
                        fs.unlink('./html/' + nameFile + '.html', (err) =>
                        {
                            if(err) logInstantce.error('create html err : ' + err);

                            fs.unlink('./pdf/' + nameFile + '.pdf', (err) =>
                            {
                                if(err) logInstantce.error('create pdf err : ' + err);

                                logInstantce.success('file pdf and html deleted successfully : ' + nameFile);
                            });
                        });
                    });
                }
            });
        }
        else
        {
            logInstantce.error('wrong autkey udoo');
            socket.emit('printError', 'wrong autkey udoo');
        }
    });
});

before i use just in http and it work fine.
the certificate is good beacause if i want i can go on the url of server and it's used on others projects.

so if you have an idea, i take it :)
thanks in advance


问:
Unity sqlite c# object reference not set to an instance of an object and database locked
i really don't know what's the problem here, it always says database locked when executing query and reference not set when i try to get data from input field.
please help..</p>

```<code>public InputField username;
public InputField password;
public Button register;
SqliteConnection dbconn;
// Use this for initialization
void Start () {
    username = gameObject.GetComponent<InputField> ();
    password = gameObject.GetComponent<InputField> ();
    register = gameObject.GetComponent<Button> ();
    string conn = "URI=file:" + Application.dataPath + "/thesisdatabase.db";
    dbconn = new SqliteConnection (conn);
    dbconn.Open ();

    SqliteCommand cmd = new SqliteCommand ();

    InputField.SubmitEvent usernameValue = new InputField.SubmitEvent ();
    InputField.SubmitEvent passwordValue = new InputField.SubmitEvent ();
    username.onEndEdit = usernameValue;
    password.onEndEdit = passwordValue;
    Debug.Log (usernameValue);
    //      string usernameValue = "we";
    //      string passwordValue = "wwwe";
    string sqlInsert = "INSERT INTO user (username, password) VALUES ('" +usernameValue+ "' , '"+passwordValue+"')";
    cmd.CommandText = sqlInsert;
    cmd.Connection = dbconn;
    cmd.ExecuteNonQuery ();
    //          register.onClick.AddListener (registerMe);

    cmd.Dispose ();
    cmd = null;
    dbconn.Close ();
    dbconn = null;

}
</code>```

答:
It seems you have some difficulties with the UI API of Unity. However, I'm not an expert with MySQL, but you should give a try to the following code:</p>

```<code>// Drag & Drop the gameobject with the InputField component
public InputField username;

// Drag & Drop the gameobject with the InputField component
public InputField password;

// Drag & Drop the gameobject with the Button component
public Button register;

SqliteConnection dbconn;

// Use this for initialization
void Start ()
{
    OpenDatabaseConnection();
    register.onClick.AddListener (OnRegisterButtonClicked);
}
void OnDestroy ()
{
    CloseDatabaseConnection();
}

private void OnRegisterButtonClicked()
{
    // Make sure the username and password are not empty
    if( !string.IsNullOrEmpty( username.text ) && !string.IsNullOrEmpty( password.text ) )
    {
        InsertUser( username.text, password.text );
    }
    else
    {
        Debug.LogError("Username or password is missing");
    }
}

private void InsertUser( string username, string password )
{
    SqliteCommand cmd = new SqliteCommand ();
    string sqlInsert = "INSERT INTO user (username, password) VALUES ('" +username+ "' , '"+password+"')";
    cmd.CommandText = sqlInsert;
    cmd.Connection = dbconn;
    cmd.ExecuteNonQuery ();
    cmd.Dispose ();
    cmd = null;
}

private void OpenDatabaseConnection()
{
    string conn = "URI=file:" + Application.dataPath + "/thesisdatabase.db";
    dbconn = new SqliteConnection (conn);
    dbconn.Open ();
}

private void CloseDatabaseConnection()
{
    dbconn.Close ();
    dbconn = null;
}
</code>```

Body:
i really don't know what's the problem here, it always says database locked when executing query and reference not set when i try to get data from input field.
please help..

public InputField username;
public InputField password;
public Button register;
SqliteConnection dbconn;
// Use this for initialization
void Start () {
    username = gameObject.GetComponent<InputField> ();
    password = gameObject.GetComponent<InputField> ();
    register = gameObject.GetComponent<Button> ();
    string conn = "URI=file:" + Application.dataPath + "/thesisdatabase.db";
    dbconn = new SqliteConnection (conn);
    dbconn.Open ();

    SqliteCommand cmd = new SqliteCommand ();

    InputField.SubmitEvent usernameValue = new InputField.SubmitEvent ();
    InputField.SubmitEvent passwordValue = new InputField.SubmitEvent ();
    username.onEndEdit = usernameValue;
    password.onEndEdit = passwordValue;
    Debug.Log (usernameValue);
    //      string usernameValue = "we";
    //      string passwordValue = "wwwe";
    string sqlInsert = "INSERT INTO user (username, password) VALUES ('" +usernameValue+ "' , '"+passwordValue+"')";
    cmd.CommandText = sqlInsert;
    cmd.Connection = dbconn;
    cmd.ExecuteNonQuery ();
    //          register.onClick.AddListener (registerMe);

    cmd.Dispose ();
    cmd = null;
    dbconn.Close ();
    dbconn = null;

}

Body:
It seems you have some difficulties with the UI API of Unity. However, I'm not an expert with MySQL, but you should give a try to the following code:

// Drag & Drop the gameobject with the InputField component
public InputField username;

// Drag & Drop the gameobject with the InputField component
public InputField password;

// Drag & Drop the gameobject with the Button component
public Button register;

SqliteConnection dbconn;

// Use this for initialization
void Start ()
{
    OpenDatabaseConnection();
    register.onClick.AddListener (OnRegisterButtonClicked);
}
void OnDestroy ()
{
    CloseDatabaseConnection();
}

private void OnRegisterButtonClicked()
{
    // Make sure the username and password are not empty
    if( !string.IsNullOrEmpty( username.text ) && !string.IsNullOrEmpty( password.text ) )
    {
        InsertUser( username.text, password.text );
    }
    else
    {
        Debug.LogError("Username or password is missing");
    }
}

private void InsertUser( string username, string password )
{
    SqliteCommand cmd = new SqliteCommand ();
    string sqlInsert = "INSERT INTO user (username, password) VALUES ('" +username+ "' , '"+password+"')";
    cmd.CommandText = sqlInsert;
    cmd.Connection = dbconn;
    cmd.ExecuteNonQuery ();
    cmd.Dispose ();
    cmd = null;
}

private void OpenDatabaseConnection()
{
    string conn = "URI=file:" + Application.dataPath + "/thesisdatabase.db";
    dbconn = new SqliteConnection (conn);
    dbconn.Open ();
}

private void CloseDatabaseConnection()
{
    dbconn.Close ();
    dbconn = null;
}


问:
How to iterate in SVG?
I would like to render a watch in SVG. I have the circles and now I would like to render the index for the hours and minutes.

svg {
  width: 100vmin;
  height: 100vmin;
  overflow: hidden;
}

line, circle {
  stroke: black;
  stroke-width: 0.3px;
}

circle {
  fill: none;
}

circle.filled {
  stroke: none;
  fill: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 100 100">
  <!-- center dot -->
  <circle cx="50" cy="50" r="1" class="filled" />
  <!-- hour circle -->
  <circle cx="50" cy="50" r="35" />
  <line x1="50" y1="17" x2="50" y2="15" />
  <!-- minute circle -->
  <circle cx="50" cy="50" r="40" />
  <line x1="50" y1="10" x2="50" y2="8" />
</svg></code>```

I know that I can use the transform attribute to rotate the lines around the center. But how to express the loop in SVG to do it 59 times for the minutes and 11 times for the hours? Do I have to use JavaScript for this, or is it possible to draw the lines directly in SVG without writing 72 line elements? Something less verbose than this:

```<code>  <line x1='50' y1='17' x2='50' y2='15' id='h0' />
  <use href='#h0' transform='rotate ( 30, 50, 50)' />
  <use href='#h0' transform='rotate ( 60, 50, 50)' />
  <use href='#h0' transform='rotate ( 90, 50, 50)' />
  <use href='#h0' transform='rotate (120, 50, 50)' />
  <use href='#h0' transform='rotate (150, 50, 50)' />
  <use href='#h0' transform='rotate (180, 50, 50)' />
  <use href='#h0' transform='rotate (210, 50, 50)' />
  <use href='#h0' transform='rotate (240, 50, 50)' />
  <use href='#h0' transform='rotate (270, 50, 50)' />
  <use href='#h0' transform='rotate (300, 50, 50)' />
  <use href='#h0' transform='rotate (330, 50, 50)' />
</code>```

and this

```<code>  <line x1='50' y1='10' x2='50' y2='8' id='m0' />
  <use href='#h0' transform='rotate ( 30, 50, 50)' />
  <use href='#m0' transform='rotate (  6, 50, 50)' />
  <use href='#m0' transform='rotate ( 12, 50, 50)' />
  <use href='#m0' transform='rotate ( 18, 50, 50)' />
  <use href='#m0' transform='rotate ( 24, 50, 50)' />
  <use href='#m0' transform='rotate ( 30, 50, 50)' />
  <use href='#m0' transform='rotate ( 36, 50, 50)' />
  <use href='#m0' transform='rotate ( 42, 50, 50)' />
  <use href='#m0' transform='rotate ( 48, 50, 50)' />
  <use href='#m0' transform='rotate ( 54, 50, 50)' />
  <use href='#m0' transform='rotate ( 60, 50, 50)' />
  <use href='#m0' transform='rotate ( 66, 50, 50)' />
  <use href='#m0' transform='rotate ( 72, 50, 50)' />
  <use href='#m0' transform='rotate ( 78, 50, 50)' />
  <use href='#m0' transform='rotate ( 84, 50, 50)' />
  <use href='#m0' transform='rotate ( 90, 50, 50)' />
  <use href='#m0' transform='rotate ( 96, 50, 50)' />
  <use href='#m0' transform='rotate (102, 50, 50)' />
  <use href='#m0' transform='rotate (108, 50, 50)' />
  <use href='#m0' transform='rotate (114, 50, 50)' />
  <use href='#m0' transform='rotate (120, 50, 50)' />
  <use href='#m0' transform='rotate (126, 50, 50)' />
  <use href='#m0' transform='rotate (132, 50, 50)' />
  <use href='#m0' transform='rotate (138, 50, 50)' />
  <use href='#m0' transform='rotate (144, 50, 50)' />
  <use href='#m0' transform='rotate (150, 50, 50)' />
  <use href='#m0' transform='rotate (156, 50, 50)' />
  <use href='#m0' transform='rotate (162, 50, 50)' />
  <use href='#m0' transform='rotate (168, 50, 50)' />
  <use href='#m0' transform='rotate (174, 50, 50)' />
  <use href='#m0' transform='rotate (180, 50, 50)' />
  <use href='#m0' transform='rotate (186, 50, 50)' />
  <use href='#m0' transform='rotate (192, 50, 50)' />
  <use href='#m0' transform='rotate (198, 50, 50)' />
  <use href='#m0' transform='rotate (204, 50, 50)' />
  <use href='#m0' transform='rotate (210, 50, 50)' />
  <use href='#m0' transform='rotate (216, 50, 50)' />
  <use href='#m0' transform='rotate (222, 50, 50)' />
  <use href='#m0' transform='rotate (228, 50, 50)' />
  <use href='#m0' transform='rotate (234, 50, 50)' />
  <use href='#m0' transform='rotate (240, 50, 50)' />
  <use href='#m0' transform='rotate (246, 50, 50)' />
  <use href='#m0' transform='rotate (252, 50, 50)' />
  <use href='#m0' transform='rotate (258, 50, 50)' />
  <use href='#m0' transform='rotate (264, 50, 50)' />
  <use href='#m0' transform='rotate (270, 50, 50)' />
  <use href='#m0' transform='rotate (276, 50, 50)' />
  <use href='#m0' transform='rotate (282, 50, 50)' />
  <use href='#m0' transform='rotate (288, 50, 50)' />
  <use href='#m0' transform='rotate (294, 50, 50)' />
  <use href='#m0' transform='rotate (300, 50, 50)' />
  <use href='#m0' transform='rotate (306, 50, 50)' />
  <use href='#m0' transform='rotate (312, 50, 50)' />
  <use href='#m0' transform='rotate (318, 50, 50)' />
  <use href='#m0' transform='rotate (324, 50, 50)' />
  <use href='#m0' transform='rotate (330, 50, 50)' />
  <use href='#m0' transform='rotate (336, 50, 50)' />
  <use href='#m0' transform='rotate (342, 50, 50)' />
  <use href='#m0' transform='rotate (348, 50, 50)' />
  <use href='#m0' transform='rotate (354, 50, 50)' />
</code>```

答:
Since the javascript option hasn't been written out, here is an implementation:

```<code>var svg = document.querySelector("svg");
var xmlns = "http://www.w3.org/2000/svg";
var scales = [{ref: 'h0', ticks: 12}, {ref: 'm0', ticks: 60}];

scales.forEach(function(scale){
  var ticks = scale.ticks;
  var degrees = 360/ticks;
  while (ticks) {
    var use = document.createElementNS(xmlns, "use");
    use.setAttribute("href", "#" + scale.ref);
    use.setAttribute("transform", "rotate(" + degrees*ticks + ", 50, 50)")
    svg.appendChild(use);
    ticks--;
  }
});
</code>```

You can see it in action here: https://jsfiddle.net/dhd8g3tg/

Title: How to iterate in SVG?

Body:
I would like to render a watch in SVG. I have the circles and now I would like to render the index for the hours and minutes.

svg {
  width: 100vmin;
  height: 100vmin;
  overflow: hidden;
}

line, circle {
  stroke: black;
  stroke-width: 0.3px;
}

circle {
  fill: none;
}

circle.filled {
  stroke: none;
  fill: black;
}

<svg viewBox="0 0 100 100">

  <circle cx="50" cy="50" r="1" class="filled" />

  <circle cx="50" cy="50" r="35" />
  <line x1="50" y1="17" x2="50" y2="15" />

  <circle cx="50" cy="50" r="40" />
  <line x1="50" y1="10" x2="50" y2="8" />
</svg>

I know that I can use the transform attribute to rotate the lines around the center. But how to express the loop in SVG to do it 59 times for the minutes and 11 times for the hours? Do I have to use JavaScript for this, or is it possible to draw the lines directly in SVG without writing 72 line elements? Something less verbose than this:

  <line x1='50' y1='17' x2='50' y2='15' id='h0' />
  <use href='#h0' transform='rotate ( 30, 50, 50)' />
  <use href='#h0' transform='rotate ( 60, 50, 50)' />
  <use href='#h0' transform='rotate ( 90, 50, 50)' />
  <use href='#h0' transform='rotate (120, 50, 50)' />
  <use href='#h0' transform='rotate (150, 50, 50)' />
  <use href='#h0' transform='rotate (180, 50, 50)' />
  <use href='#h0' transform='rotate (210, 50, 50)' />
  <use href='#h0' transform='rotate (240, 50, 50)' />
  <use href='#h0' transform='rotate (270, 50, 50)' />
  <use href='#h0' transform='rotate (300, 50, 50)' />
  <use href='#h0' transform='rotate (330, 50, 50)' />

and this

  <line x1='50' y1='10' x2='50' y2='8' id='m0' />
  <use href='#h0' transform='rotate ( 30, 50, 50)' />
  <use href='#m0' transform='rotate (  6, 50, 50)' />
  <use href='#m0' transform='rotate ( 12, 50, 50)' />
  <use href='#m0' transform='rotate ( 18, 50, 50)' />
  <use href='#m0' transform='rotate ( 24, 50, 50)' />
  <use href='#m0' transform='rotate ( 30, 50, 50)' />
  <use href='#m0' transform='rotate ( 36, 50, 50)' />
  <use href='#m0' transform='rotate ( 42, 50, 50)' />
  <use href='#m0' transform='rotate ( 48, 50, 50)' />
  <use href='#m0' transform='rotate ( 54, 50, 50)' />
  <use href='#m0' transform='rotate ( 60, 50, 50)' />
  <use href='#m0' transform='rotate ( 66, 50, 50)' />
  <use href='#m0' transform='rotate ( 72, 50, 50)' />
  <use href='#m0' transform='rotate ( 78, 50, 50)' />
  <use href='#m0' transform='rotate ( 84, 50, 50)' />
  <use href='#m0' transform='rotate ( 90, 50, 50)' />
  <use href='#m0' transform='rotate ( 96, 50, 50)' />
  <use href='#m0' transform='rotate (102, 50, 50)' />
  <use href='#m0' transform='rotate (108, 50, 50)' />
  <use href='#m0' transform='rotate (114, 50, 50)' />
  <use href='#m0' transform='rotate (120, 50, 50)' />
  <use href='#m0' transform='rotate (126, 50, 50)' />
  <use href='#m0' transform='rotate (132, 50, 50)' />
  <use href='#m0' transform='rotate (138, 50, 50)' />
  <use href='#m0' transform='rotate (144, 50, 50)' />
  <use href='#m0' transform='rotate (150, 50, 50)' />
  <use href='#m0' transform='rotate (156, 50, 50)' />
  <use href='#m0' transform='rotate (162, 50, 50)' />
  <use href='#m0' transform='rotate (168, 50, 50)' />
  <use href='#m0' transform='rotate (174, 50, 50)' />
  <use href='#m0' transform='rotate (180, 50, 50)' />
  <use href='#m0' transform='rotate (186, 50, 50)' />
  <use href='#m0' transform='rotate (192, 50, 50)' />
  <use href='#m0' transform='rotate (198, 50, 50)' />
  <use href='#m0' transform='rotate (204, 50, 50)' />
  <use href='#m0' transform='rotate (210, 50, 50)' />
  <use href='#m0' transform='rotate (216, 50, 50)' />
  <use href='#m0' transform='rotate (222, 50, 50)' />
  <use href='#m0' transform='rotate (228, 50, 50)' />
  <use href='#m0' transform='rotate (234, 50, 50)' />
  <use href='#m0' transform='rotate (240, 50, 50)' />
  <use href='#m0' transform='rotate (246, 50, 50)' />
  <use href='#m0' transform='rotate (252, 50, 50)' />
  <use href='#m0' transform='rotate (258, 50, 50)' />
  <use href='#m0' transform='rotate (264, 50, 50)' />
  <use href='#m0' transform='rotate (270, 50, 50)' />
  <use href='#m0' transform='rotate (276, 50, 50)' />
  <use href='#m0' transform='rotate (282, 50, 50)' />
  <use href='#m0' transform='rotate (288, 50, 50)' />
  <use href='#m0' transform='rotate (294, 50, 50)' />
  <use href='#m0' transform='rotate (300, 50, 50)' />
  <use href='#m0' transform='rotate (306, 50, 50)' />
  <use href='#m0' transform='rotate (312, 50, 50)' />
  <use href='#m0' transform='rotate (318, 50, 50)' />
  <use href='#m0' transform='rotate (324, 50, 50)' />
  <use href='#m0' transform='rotate (330, 50, 50)' />
  <use href='#m0' transform='rotate (336, 50, 50)' />
  <use href='#m0' transform='rotate (342, 50, 50)' />
  <use href='#m0' transform='rotate (348, 50, 50)' />
  <use href='#m0' transform='rotate (354, 50, 50)' />

Body:
Since the javascript option hasn't been written out, here is an implementation:

var svg = document.querySelector("svg");
var xmlns = "http://www.w3.org/2000/svg";
var scales = [{ref: 'h0', ticks: 12}, {ref: 'm0', ticks: 60}];

scales.forEach(function(scale){
  var ticks = scale.ticks;
  var degrees = 360/ticks;
  while (ticks) {
    var use = document.createElementNS(xmlns, "use");
    use.setAttribute("href", "#" + scale.ref);
    use.setAttribute("transform", "rotate(" + degrees*ticks + ", 50, 50)")
    svg.appendChild(use);
    ticks--;
  }
});

You can see it in action here: https://jsfiddle.net/dhd8g3tg/


问:
Declaring a class inline of ASPX-age
I'm trying to set up a receive-page to collect data, which is formatted as a JSON-string, being sent to us from an external service and which we have to add to our database.

For the sake of simplicity, I would like to keep all the code in one page which is linked to this external service.

I can receive the JSON-string, but I can't seem to deserialize it because it won't accept my class.

My code is shown below.
For debugging reasons I'm also exporting the data to an external log.
If some date would not be added, I can try to see the log if there is anything special in that message which is causing issues.

If I remove my class from the code the page will load correctly.
If I put the class in it, it will throw an error (which I can't see because I'm using an online webserver).

Does anyone know what is wrong with this code?

```<code><%@ Page Language="C#" %>
<%@ import namespace="System.Data"%>
<%@ import namespace="System.Data.SqlClient"%>
<%@ import namespace="System.IO" %>
<%@ import namespace="System.Web" %>
<%@ import namespace="System.Web.Script.Serialization" %>

<%

public class MessageClass
{
    public string type;
    public string text;
    public string url;
    public string user_name;
    public int timestamp;
}

// GET THE CONTENT THAT WAS POSTED
//StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
//string requestFromPost = reader.ReadToEnd();
string requestFromPost = "{type:'image',url:'https://someservice.com/picture.jpg',user_name:'user',timestamp:1511772572733}";

Response.Write(requestFromPost);

// BACKUP THE MESSAGE IN A LOG
StreamWriter sw;
try
{
  sw = File.AppendText(Server.MapPath(".\\") + "test.log");
  sw.WriteLine("[" + DateTime.Now.ToString("HH:mm:ss") +"] " + requestFromPost);
  sw.Flush();
  sw.Close();
}
catch(Exception ex)
{
  // IGNORE
}

StringBuilder sb = new StringBuilder();
JavaScriptSerializer ser = new JavaScriptSerializer();
//var response = ser.Deserialize<MessageClass>(requestFromPost);

//Response.Write(response.url);

// DATABASE STUFF GOES BELOW

%>
</code>```

答:
I was able to find a solution for my question, eventhough I don't think it's the best solution.

I've put the class inside -tags.

```<code><%@ Page Language="C#" %>
<%@ import namespace="System.Data"%>
<%@ import namespace="System.Data.SqlClient"%>
<%@ import namespace="System.IO" %>
<%@ import namespace="System.Web" %>
<%@ import namespace="System.Web.Script.Serialization" %>

<script runat="server">

    public class MessageClass
    {
        public string type;
        public string text;
        public string url;
        public string user_name;
        public long timestamp;
    }

</script>

<%

// GET THE CONTENT THAT WAS POSTED
StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();

// DESERIALIZE THE CONTENT
JavaScriptSerializer ser = new JavaScriptSerializer();
var response = ser.Deserialize<MessageClass>(requestFromPost);
</code>```

However if someone has a better suggestion to keep it in the same code block, I'm all ears!

Title: Declaring a class inline of ASPX-age

Body:
I'm trying to set up a receive-page to collect data, which is formatted as a JSON-string, being sent to us from an external service and which we have to add to our database.

For the sake of simplicity, I would like to keep all the code in one page which is linked to this external service.

I can receive the JSON-string, but I can't seem to deserialize it because it won't accept my class.

My code is shown below.
For debugging reasons I'm also exporting the data to an external log.
If some date would not be added, I can try to see the log if there is anything special in that message which is causing issues.

If I remove my class from the code the page will load correctly.
If I put the class in it, it will throw an error (which I can't see because I'm using an online webserver).

Does anyone know what is wrong with this code?

<%@ Page Language="C#" %>
<%@ import namespace="System.Data"%>
<%@ import namespace="System.Data.SqlClient"%>
<%@ import namespace="System.IO" %>
<%@ import namespace="System.Web" %>
<%@ import namespace="System.Web.Script.Serialization" %>

<%

public class MessageClass
{
    public string type;
    public string text;
    public string url;
    public string user_name;
    public int timestamp;
}

// GET THE CONTENT THAT WAS POSTED
//StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
//string requestFromPost = reader.ReadToEnd();
string requestFromPost = "{type:'image',url:'https://someservice.com/picture.jpg',user_name:'user',timestamp:1511772572733}";

Response.Write(requestFromPost);

// BACKUP THE MESSAGE IN A LOG
StreamWriter sw;
try
{
  sw = File.AppendText(Server.MapPath(".\\") + "test.log");
  sw.WriteLine("[" + DateTime.Now.ToString("HH:mm:ss") +"] " + requestFromPost);
  sw.Flush();
  sw.Close();
}
catch(Exception ex)
{
  // IGNORE
}

StringBuilder sb = new StringBuilder();
JavaScriptSerializer ser = new JavaScriptSerializer();
//var response = ser.Deserialize<MessageClass>(requestFromPost);

//Response.Write(response.url);

// DATABASE STUFF GOES BELOW

%>

Body:
I was able to find a solution for my question, eventhough I don't think it's the best solution.

I've put the class inside -tags.

<%@ Page Language="C#" %>
<%@ import namespace="System.Data"%>
<%@ import namespace="System.Data.SqlClient"%>
<%@ import namespace="System.IO" %>
<%@ import namespace="System.Web" %>
<%@ import namespace="System.Web.Script.Serialization" %>

<script runat="server">

    public class MessageClass
    {
        public string type;
        public string text;
        public string url;
        public string user_name;
        public long timestamp;
    }

</script>

<%

// GET THE CONTENT THAT WAS POSTED
StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();

// DESERIALIZE THE CONTENT
JavaScriptSerializer ser = new JavaScriptSerializer();
var response = ser.Deserialize<MessageClass>(requestFromPost);

However if someone has a better suggestion to keep it in the same code block, I'm all ears!


问:
Iframe ContentWindow
When I try to get the contentwindow out of an iframe, using

```<code>var contentWindow = document.getElementbyId('iframe').contentWindow
</code>```

sometimes it returns "Window undefined" because the contentWindow doesn't exist.  I can't seem to run a check for it using

```<code>if (contentWindow === unidentified) or if (contentWindow === null)
</code>```

as it just errors out of the code if I try to grab values out of it.  Has anyone else run into this problem and figured out a solution?

答:
Are you typing it properly? getElementByID not getElementbyId. Did you confirm that that returns an element before querying contentWindow? Are you querying it after it loads?

Are you doing gEBI after DOM ready or page load? Did you throw in alerts on the element? Is the domain in the iframe the same as the origin domain? What browser are you using?

```<code>if (contentWindow === unidentified) or if (contentWindow === null)
</code>```

There is no such thing as unidentified it's undefined. Slow down and be accurate.

Title: Iframe ContentWindow

Body:
When I try to get the contentwindow out of an iframe, using

var contentWindow = document.getElementbyId('iframe').contentWindow

sometimes it returns "Window undefined" because the contentWindow doesn't exist.  I can't seem to run a check for it using

if (contentWindow === unidentified) or if (contentWindow === null)

as it just errors out of the code if I try to grab values out of it.  Has anyone else run into this problem and figured out a solution?

Body:
Are you typing it properly? getElementByID not getElementbyId. Did you confirm that that returns an element before querying contentWindow? Are you querying it after it loads?

Are you doing gEBI after DOM ready or page load? Did you throw in alerts on the element? Is the domain in the iframe the same as the origin domain? What browser are you using?

if (contentWindow === unidentified) or if (contentWindow === null)

There is no such thing as unidentified it's undefined. Slow down and be accurate.


问:
How to disable link time code generation in CMake
We are using CMake with the Visual Studio 2015 generator and I am trying to disable link time code generation for libraries and executables under the debug build configuration. It seems that when I modify the linker flags with

SET_TARGET_PROPERTIES(${_PROJNAME} PROPERTIES LINK_FLAGS_DEBUG "${LINK_FLAGS_DEBUG} /LTCG:OFF")

that CMake still generates solutions with /LTCG:INCREMENTAL in the linker additional options but also with /LTGC:OFF appended.  Does anyone know a way to turn LTCG off completely for all configurations so I can enable it just for those that we want it enabled for?

cmake version 3.10.0-rc2

答:
You could manually modify CMake cache variables CMAKE_EXE_LINKER_FLAGS_DEBUG, CMAKE_MODULE_LINKER_FLAGS_DEBUG, CMAKE_SHARED_LINKER_FLAGS_DEBUG  and CMAKE_STATIC_LINKER_FLAGS_DEBUG as wished.

You could remove the /INCREMENTAL flag from these variables.


问:
multiple definitions of a dynamic array declared globally in c++
I want to have a dynamic array declared globally which is initialized in
main and then to use the values in another functions which are also included in main, but I got this error "multiple definitions of.."because I included the file with global variables: "variabile.globale.h" in main and also in "functions.h", but if I don't do that the values  will not be
recognized in both files.

main.cpp

```<code>#include <iostream>

#include "variabile_globale.h"

#include "functions.h"

using namespace std;

int N = 4;
double suma;
double produsul;

int main()
{
int i;
for (i = 1; i <= N; i++)
{
pos_x[i] = i;
cout << "x="<<pos_x[i] << endl;
sum(i);
product(i);
}

return 0;

delete [] pos_x;
}
</code>```

Global variable file:

variabile_globale.h

```<code> extern  int N;
 extern double *pos_x = new double [N];
 extern double suma;
 extern double produsul;
</code>```

And functions.h

```<code>#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

void sum(int i);
void product(int i);

#endif
</code>```

function.cpp

```<code>#include<iostream>
#include<math.h>

#include"variabile_globale.h"

void sum(int i)
{
suma = 0;
for (i = 0; i < N; i++)
{
suma = suma + pos_x[i];

}

}

void product(int i)

{
 produsul = 1;
for (i = 0; i < N; i++)
{
 produsul =  produsul*pos_x[i];

 }
</code>```

Thank you in advance!

答:
```<code>extern double *pos_x = new double [N];
</code>```

A declaration that has an initializer is a definition. So this line defines pos_x in every file that includes this header.

Change the declaration to actually be a declaration:

```<code>extern double *pos_x;
</code>```

and define pos_x in exactly one source file.

Body:
I want to have a dynamic array declared globally which is initialized in
main and then to use the values in another functions which are also included in main, but I got this error "multiple definitions of.."because I included the file with global variables: "variabile.globale.h" in main and also in "functions.h", but if I don't do that the values  will not be
recognized in both files.

main.cpp

#include <iostream>

#include "variabile_globale.h"

#include "functions.h"

using namespace std;

int N = 4;
double suma;
double produsul;

int main()
{
int i;
for (i = 1; i <= N; i++)
{
pos_x[i] = i;
cout << "x="<<pos_x[i] << endl;
sum(i);
product(i);
}

return 0;

delete [] pos_x;
}

Global variable file:

variabile_globale.h

 extern  int N;
 extern double *pos_x = new double [N];
 extern double suma;
 extern double produsul;

And functions.h

#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

void sum(int i);
void product(int i);

#endif

function.cpp

#include<iostream>
#include<math.h>

#include"variabile_globale.h"

void sum(int i)
{
suma = 0;
for (i = 0; i < N; i++)
{
suma = suma + pos_x[i];

}

}

void product(int i)

{
 produsul = 1;
for (i = 0; i < N; i++)
{
 produsul =  produsul*pos_x[i];

 }

Thank you in advance!

Body:
extern double *pos_x = new double [N];

A declaration that has an initializer is a definition. So this line defines pos_x in every file that includes this header.

Change the declaration to actually be a declaration:

extern double *pos_x;

and define pos_x in exactly one source file.


问:
iOS10 __weak pointer made retainCount +1
When I use __weak pointer refer to an NSObject, the unexpected retainCount is shown.

The test code and result are as the image below.

Here is the code:

```<code>    id obj1 = [[NSObject alloc] init];
    id __weak obj2 = obj1;
    NSLog(@"obj1: %ld", CFGetRetainCount((__bridge CFTypeRef)obj1));        // line 31
    NSLog(@"obj2: %ld", CFGetRetainCount((__bridge CFTypeRef)obj2));        // line 32
    NSLog(@"obj1 again: %ld", CFGetRetainCount((__bridge CFTypeRef)obj1));  // line 33
</code>```

So～ My confusion is that, obj2's retainCount is expected to 1, Why retainCount is 2?

I've read from book: the __weak pointer registered the object to the autoreleasepool, so the retain count + 1.

However, obj1 and obj2 refer to the same memory address, in that case, the obj1's retainCount should also become 2. But, it still remain in 1.

I know retainCount is unreliable but I'm so curious about how this came. (My environment is Xcode 8.3.3, iOS 10.3)

Greatly appreciate if anyone can explain this to a beginner :)

答:
The exact value of the retain count is generally an implementation detail that depends on the compiler, the Objective-C language runtime, and any other libraries involved (like Foundation). But it's reasonable to wonder why it behaves this way, as long as you don't depend on the behavior.

Either your book is wrong, or you misunderstood it. Using __weak doesn't put the object in the autoreleasepool.

Here is what is happening on line 32 (the one with the @"obj2: %ld" format string).

To safely pass an object reference to a function or method (like NSLog), it has to be a strongly-held reference. So the compiler generates a call to objc_loadWeakRetained on obj2. This function atomically increments the retain count of the object and returns the reference. Thus the retain count of the object goes from 1 to 2 before the object reference is passed to NSLog.

Then, after NSLog returns, the compiler generates a call to objc_release. Thus the retain count goes back down from 2 to 1 by the third NSLog.

If you want to be sure what's happening, look at the assembler output of the compiler. You can ask Xcode to show it to you:

Here's the relevant part of the assembly:

```<code>    .loc    2 0 9 discriminator 1   ## /Users/mayoff/TestProjects/test/test/main.m:0:9
    leaq    -32(%rbp), %rdi
    ##DEBUG_VALUE: obj2 <- [%RBP+-32]
    .loc    2 16 66 is_stmt 1       ## /Users/mayoff/TestProjects/test/test/main.m:16:66
    callq   _objc_loadWeakRetained
    movq    %rax, %rbx
Ltmp4:
    .loc    2 16 29 is_stmt 0       ## /Users/mayoff/TestProjects/test/test/main.m:16:29
    movq    %rbx, %rdi
    callq   _CFGetRetainCount
    movq    %rax, %rcx
Ltmp5:
Ltmp20:
## BB#3:
    ##DEBUG_VALUE: obj2 <- [%RBP+-32]
    ##DEBUG_VALUE: obj1 <- %R15
Ltmp6:
    .loc    2 16 9 discriminator 1  ## /Users/mayoff/TestProjects/test/test/main.m:16:9
    leaq    L__unnamed_cfstring_.4(%rip), %rdi
    xorl    %eax, %eax
    movq    %rcx, %rsi
    callq   _NSLog
Ltmp7:
Ltmp21:
## BB#4:
    ##DEBUG_VALUE: obj2 <- [%RBP+-32]
    ##DEBUG_VALUE: obj1 <- %R15
    .loc    2 16 9 discriminator 2  ## /Users/mayoff/TestProjects/test/test/main.m:16:9
    movq    %rbx, %rdi
    callq   *_objc_release@GOTPCREL(%rip)
</code>```

Line 16 is (in my test) the one that uses obj2. You can see the call to objc_loadWeakRetained before the call to CFGetRetainCount, and the call to objc_release after NSLog returns.

Body:
When I use __weak pointer refer to an NSObject, the unexpected retainCount is shown.

The test code and result are as the image below.

Here is the code:

    id obj1 = [[NSObject alloc] init];
    id __weak obj2 = obj1;
    NSLog(@"obj1: %ld", CFGetRetainCount((__bridge CFTypeRef)obj1));        // line 31
    NSLog(@"obj2: %ld", CFGetRetainCount((__bridge CFTypeRef)obj2));        // line 32
    NSLog(@"obj1 again: %ld", CFGetRetainCount((__bridge CFTypeRef)obj1));  // line 33

So～ My confusion is that, obj2's retainCount is expected to 1, Why retainCount is 2?

I've read from book: the __weak pointer registered the object to the autoreleasepool, so the retain count + 1.

However, obj1 and obj2 refer to the same memory address, in that case, the obj1's retainCount should also become 2. But, it still remain in 1.

I know retainCount is unreliable but I'm so curious about how this came. (My environment is Xcode 8.3.3, iOS 10.3)

Greatly appreciate if anyone can explain this to a beginner :)

Body:
The exact value of the retain count is generally an implementation detail that depends on the compiler, the Objective-C language runtime, and any other libraries involved (like Foundation). But it's reasonable to wonder why it behaves this way, as long as you don't depend on the behavior.

Either your book is wrong, or you misunderstood it. Using __weak doesn't put the object in the autoreleasepool.

Here is what is happening on line 32 (the one with the @"obj2: %ld" format string).

To safely pass an object reference to a function or method (like NSLog), it has to be a strongly-held reference. So the compiler generates a call to objc_loadWeakRetained on obj2. This function atomically increments the retain count of the object and returns the reference. Thus the retain count of the object goes from 1 to 2 before the object reference is passed to NSLog.

Then, after NSLog returns, the compiler generates a call to objc_release. Thus the retain count goes back down from 2 to 1 by the third NSLog.

If you want to be sure what's happening, look at the assembler output of the compiler. You can ask Xcode to show it to you:

Here's the relevant part of the assembly:

    .loc    2 0 9 discriminator 1   ## /Users/mayoff/TestProjects/test/test/main.m:0:9
    leaq    -32(%rbp), %rdi
    ##DEBUG_VALUE: obj2 <- [%RBP+-32]
    .loc    2 16 66 is_stmt 1       ## /Users/mayoff/TestProjects/test/test/main.m:16:66
    callq   _objc_loadWeakRetained
    movq    %rax, %rbx
Ltmp4:
    .loc    2 16 29 is_stmt 0       ## /Users/mayoff/TestProjects/test/test/main.m:16:29
    movq    %rbx, %rdi
    callq   _CFGetRetainCount
    movq    %rax, %rcx
Ltmp5:
Ltmp20:
## BB#3:
    ##DEBUG_VALUE: obj2 <- [%RBP+-32]
    ##DEBUG_VALUE: obj1 <- %R15
Ltmp6:
    .loc    2 16 9 discriminator 1  ## /Users/mayoff/TestProjects/test/test/main.m:16:9
    leaq    L__unnamed_cfstring_.4(%rip), %rdi
    xorl    %eax, %eax
    movq    %rcx, %rsi
    callq   _NSLog
Ltmp7:
Ltmp21:
## BB#4:
    ##DEBUG_VALUE: obj2 <- [%RBP+-32]
    ##DEBUG_VALUE: obj1 <- %R15
    .loc    2 16 9 discriminator 2  ## /Users/mayoff/TestProjects/test/test/main.m:16:9
    movq    %rbx, %rdi
    callq   *_objc_release@GOTPCREL(%rip)

Line 16 is (in my test) the one that uses obj2. You can see the call to objc_loadWeakRetained before the call to CFGetRetainCount, and the call to objc_release after NSLog returns.


问:
Attributes in C++. Are they really required for programmers?
I read that C++11 has introduced the concept of attributes for example [[noreturn]] which is to indicate that the function doesn not return to the caller.

```<code>[[noreturn]] void fun()
{
    throw std::string("Error!!!");
}

void func()
{
    fun();
}

void aTempFunc()
{
    try
    {
        func();
    }
    catch (std::string &e)
    {
        std::cout << e << std::endl;
    }
}
</code>```

By looking at the example the reader can understand that the function throws an exception and call will not be returned to the func function.
I am bit confused to understand what are C++ attributes and why it is required? How a programmer can really make use of these attributes?

Can someone explain in detail. Please correct me if my understanding about the attributes is wrong.
Thanks.

答:
Most of the attributes are compiler hint, ABI specification or requirement relative to the target object format (visibility, section, etc.).

So most attributes do not change the observable behavior of your program: if you remove all the attributes of your source code, and if it compiles, you can reasonably expect to have a resulting program behaving as the one compiled with the attributes.

But there are also attributes that can noticeably affect the behavior or compilability of your program, for example the align attribute, even if they do not change drastically the semantic of your code.

Implementation can provide their own attributes, and these attributes can have any consequence as long as the observable behaviors of the program follow the c++ language, C++ standard[intro.compliance]:

A conforming implementation may have extensions (including additional library functions), provided they
  do not alter the behavior of any well-formed program. Implementations are required to diagnose programs
  that use such extensions that are ill-formed according to this document. Having done so, however, they can
  compile and execute such programs.

Body:
I read that C++11 has introduced the concept of attributes for example [[noreturn]] which is to indicate that the function doesn not return to the caller.

[[noreturn]] void fun()
{
    throw std::string("Error!!!");
}

void func()
{
    fun();
}

void aTempFunc()
{
    try
    {
        func();
    }
    catch (std::string &e)
    {
        std::cout << e << std::endl;
    }
}

By looking at the example the reader can understand that the function throws an exception and call will not be returned to the func function.
I am bit confused to understand what are C++ attributes and why it is required? How a programmer can really make use of these attributes?

Can someone explain in detail. Please correct me if my understanding about the attributes is wrong.
Thanks.


问:
How to format a string as a telephone number in C#
I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.

I was thinking:

```<code>String.Format("{0:###-###-####}", i["MyPhone"].ToString() );
</code>```

but that does not seem to do the trick.

** UPDATE **

Ok. I went with this solution

```<code>Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")
</code>```

Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so

```<code>1112224444 333  becomes

11-221-244 3334
</code>```

Any ideas?

答:
You may get find yourself in the situation where you have users trying to enter phone numbers with all sorts of separators between area code and the main number block (e.g., spaces, dashes, periods, ect...) So you'll want to strip the input of all characters that are not numbers so you can sterilize the input you are working with. The easiest way to do this is with a RegEx expression.

```<code>string formattedPhoneNumber = new System.Text.RegularExpressions.Regex(@"\D")
    .Replace(originalPhoneNumber, string.Empty);
</code>```

Then the answer you have listed should work in most cases.

To answer what you have about your extension issue, you can strip anything that is longer than the expected length of ten (for a regular phone number) and add that to the end using

```<code>formattedPhoneNumber = Convert.ToInt64(formattedPhoneNumber)
     .ToString("###-###-#### " + new String('#', (value.Length - 10)));
</code>```

You will want to do an 'if' check to determine if the length of your input is greater than 10 before doing this, if not, just use:

```<code>formattedPhoneNumber = Convert.ToInt64(value).ToString("###-###-####");
</code>```

OwnerDisplayName: Brian G

Body:
I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.

I was thinking:

String.Format("{0:###-###-####}", i["MyPhone"].ToString() );

but that does not seem to do the trick.

** UPDATE **

Ok. I went with this solution

Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")

Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so

1112224444 333  becomes

11-221-244 3334

Any ideas?

LastEditorDisplayName: Brian G

Body:
You may get find yourself in the situation where you have users trying to enter phone numbers with all sorts of separators between area code and the main number block (e.g., spaces, dashes, periods, ect...) So you'll want to strip the input of all characters that are not numbers so you can sterilize the input you are working with. The easiest way to do this is with a RegEx expression.

string formattedPhoneNumber = new System.Text.RegularExpressions.Regex(@"\D")
    .Replace(originalPhoneNumber, string.Empty);

Then the answer you have listed should work in most cases.

To answer what you have about your extension issue, you can strip anything that is longer than the expected length of ten (for a regular phone number) and add that to the end using

formattedPhoneNumber = Convert.ToInt64(formattedPhoneNumber)
     .ToString("###-###-#### " + new String('#', (value.Length - 10)));

You will want to do an 'if' check to determine if the length of your input is greater than 10 before doing this, if not, just use:

formattedPhoneNumber = Convert.ToInt64(value).ToString("###-###-####");


问:
Return JSX from function
I have a a component that needs to check for multiple options and return based on those options. Therefore I have created an outside function that is called in my component return statement to determine the format that will be returned:

render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (

          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (

{ policy.displayName }

                    { this.renderSp4Policies(policy) }

                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>

      )
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let firmwareDropdownNames = this.formatFirmawareDropdownNames(policy);
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      let toggleOptions = []
      Object.keys(toggles).map(toggle => {
       if(typeof(toggles[toggle]) == "boolean"){
          var obj = {};
          obj[toggle] = toggles[toggle];
        toggleOptions.push(obj);
        }
      })
      return (
        toggleOptions.map(toggleOption => {
          let toggleName = Object.keys(toggleOption).toString();
          return (
            <Form.Field key={ toggleName }>
              { toggleName }
              <Checkbox toggle />
            </Form.Field>
          )
        })
      )
    } else {
        return (
          policy.values.map(value => {
            return(
              <Form.Field key={ value.name }>
                { value.displayName || value.name }
                <Checkbox toggle />
              </Form.Field>
            )
          }
        )
      )
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

EDIT

I have applied some of the answers given with moderate success.

Within renderSp4Policies what is being returned in the else statement displays, but the beginning if(policy.displayName == "Firmware Options") returns nothing.

Appreciate all advice, thank you in advance!

答:
Just change this function with map arrow function return.</p>

```<code>renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      Object.keys(toggles).forEach(toggle => {
        if(typeof(toggles[toggle]) !== "boolean"){
            delete toggles[toggle];
        }
      })
      Object.keys(toggles).forEach(toggle => {
        return(
          <Form.Field key={ toggle }>
            <label> { toggle } </label>
            <Checkbox toggle />
          </Form.Field>
        );
      })
    } else {
        return (
          policy.values.map(value => (
            <Form.Field key={ value.name }>
              <label>{ value.displayName || value.name }</label>
              <Checkbox toggle />
            </Form.Field>
          ))
        );
      }
  }
</code>```

Title: Return JSX from function

Body:
I have a a component that needs to check for multiple options and return based on those options. Therefore I have created an outside function that is called in my component return statement to determine the format that will be returned:

render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (

          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (

{ policy.displayName }

                    { this.renderSp4Policies(policy) }

                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>

      )
    }
  }

renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let firmwareDropdownNames = this.formatFirmawareDropdownNames(policy);
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      let toggleOptions = []
      Object.keys(toggles).map(toggle => {
       if(typeof(toggles[toggle]) == "boolean"){
          var obj = {};
          obj[toggle] = toggles[toggle];
        toggleOptions.push(obj);
        }
      })
      return (
        toggleOptions.map(toggleOption => {
          let toggleName = Object.keys(toggleOption).toString();
          return (
            <Form.Field key={ toggleName }>
              { toggleName }
              <Checkbox toggle />
            </Form.Field>
          )
        })
      )
    } else {
        return (
          policy.values.map(value => {
            return(
              <Form.Field key={ value.name }>
                { value.displayName || value.name }
                <Checkbox toggle />
              </Form.Field>
            )
          }
        )
      )
    }
  }

EDIT

I have applied some of the answers given with moderate success.

Within renderSp4Policies what is being returned in the else statement displays, but the beginning if(policy.displayName == "Firmware Options") returns nothing.

Appreciate all advice, thank you in advance!

Body:
Just change this function with map arrow function return.

renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      Object.keys(toggles).forEach(toggle => {
        if(typeof(toggles[toggle]) !== "boolean"){
            delete toggles[toggle];
        }
      })
      Object.keys(toggles).forEach(toggle => {
        return(
          <Form.Field key={ toggle }>
            <label> { toggle } </label>
            <Checkbox toggle />
          </Form.Field>
        );
      })
    } else {
        return (
          policy.values.map(value => (
            <Form.Field key={ value.name }>
              <label>{ value.displayName || value.name }</label>
              <Checkbox toggle />
            </Form.Field>
          ))
        );
      }
  }


问:
Best box selection method for a Minecraft clone
I'm making a Minecraft clone as my very first OpenGL project and am stuck at the box selection part. What would be the best method to make a reliable box selection?

I've been going through some AABB algorithms, but none of them explain well enough what they exactly do (especially the super tweaked ones) and I don't want to use stuff I don't understand.

Since the world is composed of cubes I used octrees to remove some strain on ray cast calculations, basically the only thing I need is this function:

```<code>float cube_intersect(Vector ray, Vector origin, Vector min, Vector max)
{
    //???
}
</code>```

The ray and origin are easily obtained with

```<code>Vector ray, origin, point_far;
double mx, my, mz;

gluUnProject(viewport[2]/2, viewport[3]/2, 1.0, (double*)modelview, (double*)projection, viewport, &mx, &my, &mz);
point_far = Vector(mx, my, mz);
gluUnProject(viewport[2]/2, viewport[3]/2, 0.0, (double*)modelview, (double*)projection, viewport, &mx, &my, &mz);
origin = Vector(mx, my, mz);
ray = point_far-origin;
</code>```

min and max are the opposite corners of a cube.

I'm not even sure this is the right way to do this, considering the number of cubes I'd have to check, even with octrees.

I've also tried gluProject, it works, but is very unreliable and doesn't give me the selected face of the cube.

EDIT

So this is what I've done: calculate a position in space with the ray:

```<code>float t = 0;
for(int i=0; i<10; i++)
{
    Vector p = ray*t+origin;
    while(visible octree)
    {
        if(p inside octree)
        {
            // then call recursive function until a cube is found
            break;
        }
        octree = octree->next;
    }
    if(found a cube)
    {
        break;
    }
    t += .5;
}
</code>```

It's actually surprisingly fast and stops after the first found cube.

As you can see the ray has to go trough multiple octrees before it finds a cube (actually a position in space) - there is a crosshair in the middle of the screen. The lower the increment step the more precise the selection, but also slower.

答: You don't need any explicit octree structure in memory. All that is needed is byte[,,]. Just generate 8 children of a box lazily during search (like a chess engine generates children game states).</p>

Body:
I'm making a Minecraft clone as my very first OpenGL project and am stuck at the box selection part. What would be the best method to make a reliable box selection?

I've been going through some AABB algorithms, but none of them explain well enough what they exactly do (especially the super tweaked ones) and I don't want to use stuff I don't understand.

Since the world is composed of cubes I used octrees to remove some strain on ray cast calculations, basically the only thing I need is this function:

float cube_intersect(Vector ray, Vector origin, Vector min, Vector max)
{
    //???
}

The ray and origin are easily obtained with

Vector ray, origin, point_far;
double mx, my, mz;

gluUnProject(viewport[2]/2, viewport[3]/2, 1.0, (double*)modelview, (double*)projection, viewport, &mx, &my, &mz);
point_far = Vector(mx, my, mz);
gluUnProject(viewport[2]/2, viewport[3]/2, 0.0, (double*)modelview, (double*)projection, viewport, &mx, &my, &mz);
origin = Vector(mx, my, mz);
ray = point_far-origin;

min and max are the opposite corners of a cube.

I'm not even sure this is the right way to do this, considering the number of cubes I'd have to check, even with octrees.

I've also tried gluProject, it works, but is very unreliable and doesn't give me the selected face of the cube.

EDIT

So this is what I've done: calculate a position in space with the ray:

float t = 0;
for(int i=0; i<10; i++)
{
    Vector p = ray*t+origin;
    while(visible octree)
    {
        if(p inside octree)
        {
            // then call recursive function until a cube is found
            break;
        }
        octree = octree->next;
    }
    if(found a cube)
    {
        break;
    }
    t += .5;
}

It's actually surprisingly fast and stops after the first found cube.

As you can see the ray has to go trough multiple octrees before it finds a cube (actually a position in space) - there is a crosshair in the middle of the screen. The lower the increment step the more precise the selection, but also slower.


问:
Scapy: check the message type of a captured DHCP packet
I'm totally new to scapy, I'm trying to use it to build a DHCP monitor for my LAN. I'm using sniff to capture packets that are sent to a callback via the prn= parameter. Inside the callback, I check if the packet has the DHCP layer and then I check the type of request.

I'm currently doing it like this:

```<code>def manage(pkt):
    if pkt.haslayer(DHCP):
        req_type = [x[1] for x in pkt[DHCP].options if x[0] == 'message-type'][0]

        # Message type: request
        if req_type == 3:
            print ("Request from {}".format(pkt[Ether].src))

sniff(prn=manage, count=0, store=0)
</code>```

The way I'm accessing the options in the DHCP layer is kind of awkward, but it's the only one I've come up with that works. However I believe there must be a better, more pythonic way, like via a dict or something.

What's the appropriate way of accessing those options?

答:
I think this is the almost the most efficient way to do what you want. I would use next() and a generator expression rather than a list, to avoid parsing the whole options list when it's not necessary:

```<code>req_type = next(opt[1] for opt in pkt[DHCP].options if isinstance(opt, tuple) and opt[0] == 'message-type')
</code>```

Note that I've also added a check against the type of opt, as some are string objects.

You could use a dict() but you would then have, again, to parse the whole options list.

As a side note, the way DHCP options are handled in Scapy is a bit old and the correct way to do that now would probably be to use a PacketListField with cleaner methods to access the options.

Body:
I'm totally new to scapy, I'm trying to use it to build a DHCP monitor for my LAN. I'm using sniff to capture packets that are sent to a callback via the prn= parameter. Inside the callback, I check if the packet has the DHCP layer and then I check the type of request.

I'm currently doing it like this:

def manage(pkt):
    if pkt.haslayer(DHCP):
        req_type = [x[1] for x in pkt[DHCP].options if x[0] == 'message-type'][0]

        # Message type: request
        if req_type == 3:
            print ("Request from {}".format(pkt[Ether].src))

sniff(prn=manage, count=0, store=0)

The way I'm accessing the options in the DHCP layer is kind of awkward, but it's the only one I've come up with that works. However I believe there must be a better, more pythonic way, like via a dict or something.

What's the appropriate way of accessing those options?

Body:
I think this is the almost the most efficient way to do what you want. I would use next() and a generator expression rather than a list, to avoid parsing the whole options list when it's not necessary:

req_type = next(opt[1] for opt in pkt[DHCP].options if isinstance(opt, tuple) and opt[0] == 'message-type')

Note that I've also added a check against the type of opt, as some are string objects.

You could use a dict() but you would then have, again, to parse the whole options list.

As a side note, the way DHCP options are handled in Scapy is a bit old and the correct way to do that now would probably be to use a PacketListField with cleaner methods to access the options.


问:
Packages missing in shiny-server
I am trying to create a web application using shiny. It requires me to load a package I have installed on my computer. For example:

```<code>## Contents ui.R:
library(shiny)
library(plyr)

shinyUI(pageWithSidebar(

  headerPanel("Hello Shiny!"),

  sidebarPanel(
    sliderInput("obs",
                "Number of observations:",
                min = 0,
                max = 1000,
                value = 500)
  ),

  mainPanel(
    plotOutput("distPlot")
  )
))

## Contents server.R:
library(shiny)
library(plyr)

shinyServer(function(input, output) {

  output$distPlot <- renderPlot({

    # generate an rnorm distribution and plot it
    dist <- rnorm(input$obs)
    hist(dist)
  })
})
</code>```

This works fine if I run it locally (using runApp) but when I try to run it via my server (same computer) I get the error that the plyr package (or any other package I try to use this way) is not installed. How could I use extra packages in shiny server?

答:
Here might be a solution that doesn't mess up with the system library. Put the following code at the beginning of the server.R.

```<code>user <- unname(Sys.info()["user"])
if (user == "shiny") {

  # Set library locations
  .libPaths(c(
    "/path/to/your/own/library"
  )
  )

}
</code>```

This lets Shiny look for packages installed in your own library preferentially and also keeps the packages you use to develop the app and the packages used when the app is deployed in sync.

Note that you may need to tweak permissions of your library folder for the shiny user to see it properly. Otherwise it will fail to look into your specified location without any error message.

Title: Packages missing in shiny-server

Body:
I am trying to create a web application using shiny. It requires me to load a package I have installed on my computer. For example:

## Contents ui.R:
library(shiny)
library(plyr)

shinyUI(pageWithSidebar(

  headerPanel("Hello Shiny!"),

  sidebarPanel(
    sliderInput("obs",
                "Number of observations:",
                min = 0,
                max = 1000,
                value = 500)
  ),

  mainPanel(
    plotOutput("distPlot")
  )
))

## Contents server.R:
library(shiny)
library(plyr)

shinyServer(function(input, output) {

  output$distPlot <- renderPlot({

    # generate an rnorm distribution and plot it
    dist <- rnorm(input$obs)
    hist(dist)
  })
})

This works fine if I run it locally (using runApp) but when I try to run it via my server (same computer) I get the error that the plyr package (or any other package I try to use this way) is not installed. How could I use extra packages in shiny server?

Body:
Here might be a solution that doesn't mess up with the system library. Put the following code at the beginning of the server.R.

user <- unname(Sys.info()["user"])
if (user == "shiny") {

  # Set library locations
  .libPaths(c(
    "/path/to/your/own/library"
  )
  )

}

This lets Shiny look for packages installed in your own library preferentially and also keeps the packages you use to develop the app and the packages used when the app is deployed in sync.

Note that you may need to tweak permissions of your library folder for the shiny user to see it properly. Otherwise it will fail to look into your specified location without any error message.


问:
Unresolved reference to <symbol> in C. Makefile seems to be in order: gcc command is perfectly fine according to the suggestions
I keep getting the errors:

```<code>/tmp/cccpx6tz.o: In function `main':
main.c:(.text+0x35): undefined reference to `SCPinstance_construct'
main.c:(.text+0x41): undefined reference to `SCPinstance_print'
main.c:(.text+0x4d): undefined reference to `SCPinstance_destruct'
collect2: error: ld returned 1 exit status
</code>```

in main.c:

```<code>    /* Load SCP data file from OR Library */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "scpinstance.h"

int main(int argc, char ** argv){

    char * datasrc = "ORLib/scpc1.txt";

    SCPinstance scpinstance = SCPinstance_construct(datasrc);
    SCPinstance_print(&scpinstance);
    SCPinstance_destruct(&scpinstance);
    //
    return EXIT_SUCCESS;
}
</code>```

in  scpinstance.h:

```<code>#ifndef SCPINSTANCE_H
#define SCPINSTANCE_H

typedef struct {
    char * name;
    int m; /* number of rows */
    int n; /* number of columns */
    int * c; /* costs */
    int ** J; /* list of columns that cover row i.
                J[i][0] = length of list, index
                list starts at 1 */
} SCPinstance;

/* SCPinstance_construct: constructor,
    returns a SCPinstance object with data from src where src is a filename */
SCPinstance SCPinstance_construct(char * src);

/* SCPinstance_print: print values in SCPinstance */
void SCPinstance_print(SCPinstance *);

/* SCPinstance_destruct: destructor of SCPinstance.
    returns 0 if successful. */
int SCPinstance_destruct(SCPinstance *);
#endif
</code>```

in scpinstance.c:

```<code>#include "scpinstance.h"

/* SCPinstance_construct: constructor,
    returns a SCPinstance object with data from src where src is a filename */
SCPinstance SCPinstance_construct(char * src);

/* SCPinstance_print: print values in SCPinstance */
void SCPinstance_print(SCPinstance * scpinstance);

/* SCPinstance_destruct: destructor of SCPinstance.
    returns 0 if successful. */
int SCPinstance_destruct(SCPinstance * scpinstance);
</code>```

in Makefile:

```<code>GCC = gcc
CFLAGS = -g -Wall -Wshadow
OBJS = main.o scpinstance.o

scploader: $(OBJS)
    $(GCC) $(CFLAGS) $(OBJS) -o $@

.c.o:
    $(GCC) $(CFLAGS) -c *.c
</code>```

The gcc commands seems to be in order. I've looked around but the only relevant suggestions seems to be to link my files properly. But i checked my directory, the files in OBJS already exists.

Please help. I really appreciate it, thanks.

Update:
(Solution)

Have to make sure functions are defined, not just declared. So in scpinstance.c, I did this:

```<code>#include "scpinstance.h"

/* SCPinstance_construct: constructor,
    returns a SCPinstance object with data from src where src is a filename */
SCPinstance SCPinstance_construct(char * src){
    SCPinstance scpinstance;
    return scpinstance;
}

/* SCPinstance_print: print values in SCPinstance */
void SCPinstance_print(SCPinstance * scpinstance){

}

/* SCPinstance_destruct: destructor of SCPinstance.
    returns 0 if successful. */
int SCPinstance_destruct(SCPinstance * scpinstance){
    return 0;
}
</code>```

答: Your C source file only contains declarations of the functions, not definitions of them. As such, they have no definitions, and thus the symbols are undefined at link time.</p>

Body:
I keep getting the errors:

/tmp/cccpx6tz.o: In function `main':
main.c:(.text+0x35): undefined reference to `SCPinstance_construct'
main.c:(.text+0x41): undefined reference to `SCPinstance_print'
main.c:(.text+0x4d): undefined reference to `SCPinstance_destruct'
collect2: error: ld returned 1 exit status

in main.c:

    /* Load SCP data file from OR Library */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "scpinstance.h"

int main(int argc, char ** argv){

    char * datasrc = "ORLib/scpc1.txt";

    SCPinstance scpinstance = SCPinstance_construct(datasrc);
    SCPinstance_print(&scpinstance);
    SCPinstance_destruct(&scpinstance);
    //
    return EXIT_SUCCESS;
}

in  scpinstance.h:

#ifndef SCPINSTANCE_H
#define SCPINSTANCE_H

typedef struct {
    char * name;
    int m; /* number of rows */
    int n; /* number of columns */
    int * c; /* costs */
    int ** J; /* list of columns that cover row i.
                J[i][0] = length of list, index
                list starts at 1 */
} SCPinstance;

/* SCPinstance_construct: constructor,
    returns a SCPinstance object with data from src where src is a filename */
SCPinstance SCPinstance_construct(char * src);

/* SCPinstance_print: print values in SCPinstance */
void SCPinstance_print(SCPinstance *);

/* SCPinstance_destruct: destructor of SCPinstance.
    returns 0 if successful. */
int SCPinstance_destruct(SCPinstance *);
#endif

in scpinstance.c:

#include "scpinstance.h"

/* SCPinstance_construct: constructor,
    returns a SCPinstance object with data from src where src is a filename */
SCPinstance SCPinstance_construct(char * src);

/* SCPinstance_print: print values in SCPinstance */
void SCPinstance_print(SCPinstance * scpinstance);

/* SCPinstance_destruct: destructor of SCPinstance.
    returns 0 if successful. */
int SCPinstance_destruct(SCPinstance * scpinstance);

in Makefile:

GCC = gcc
CFLAGS = -g -Wall -Wshadow
OBJS = main.o scpinstance.o

scploader: $(OBJS)
    $(GCC) $(CFLAGS) $(OBJS) -o $@

.c.o:
    $(GCC) $(CFLAGS) -c *.c

The gcc commands seems to be in order. I've looked around but the only relevant suggestions seems to be to link my files properly. But i checked my directory, the files in OBJS already exists.

Please help. I really appreciate it, thanks.

Update:
(Solution)

Have to make sure functions are defined, not just declared. So in scpinstance.c, I did this:

#include "scpinstance.h"

/* SCPinstance_construct: constructor,
    returns a SCPinstance object with data from src where src is a filename */
SCPinstance SCPinstance_construct(char * src){
    SCPinstance scpinstance;
    return scpinstance;
}

/* SCPinstance_print: print values in SCPinstance */
void SCPinstance_print(SCPinstance * scpinstance){

}

/* SCPinstance_destruct: destructor of SCPinstance.
    returns 0 if successful. */
int SCPinstance_destruct(SCPinstance * scpinstance){
    return 0;
}


问:
Objective C: SetNeedsDisplay
I've been reading this book on game programming, but the examples are not that great. I'm working on one that calls [self setNeedsDisplay] but it cause the app the crash.

This is all the code I have, copied verbatim from the book:

```<code>-(void)awakeFromNib {
//start timer that will fire every second
[car setAlpha:0];
[road setAlpha:0];
currentImage = [UIImage imageNamed:@"road.png"];

//start timer that fires every second
[NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];

//start timer that fires every hundreth of a second
[NSTimer scheduledTimerWithTimeInterval:(0.01) target:self selector:@selector(onTimerRoad) userInfo:nil repeats:YES];
}

-(void)onTimerRoad
{
    int tileIndex;
tileIndex += 1;
[self setNeedsDisplay];
}

-(void)onTimer {
[self update];
[self draw];
}

-(void)update {
[self updateRoad];
}

-(void)updateRoad {
[self randomRoadUpdate];
}

-(void)randomRoadUpdate {
int distance = (random() % 11) -5;
CGPoint oldPosition = road.center;
if (oldPosition.x + distance < 96 || oldPosition.x + distance > 224)
    return;
road.center = CGPointMake(oldPosition.x + distance, oldPosition.y);
}

-(void)draw {

}

- (id) initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
    //init code
}
return self;
}

-(void)drawRect:(CGRect)rect {
CGImageRef image = CGImageRetain(currentImage.CGImage);
CGRect imageRect;
imageRect.origin = CGPointMake(160, 240);
imageRect.size = CGSizeMake(320.0, 480.0);
CGContextRef uiContext = UIGraphicsGetCurrentContext();
CGContextClipToRect(uiContext, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height));
CGContextDrawTiledImage(uiContext, imageRect, image);

}
</code>```

答: Turns out instead of [self setNeedsDisplay] I need to do [self.view setNeedsDisplay]

Title: Objective C: SetNeedsDisplay

Body:
I've been reading this book on game programming, but the examples are not that great. I'm working on one that calls [self setNeedsDisplay] but it cause the app the crash.

This is all the code I have, copied verbatim from the book:

-(void)awakeFromNib {
//start timer that will fire every second
[car setAlpha:0];
[road setAlpha:0];
currentImage = [UIImage imageNamed:@"road.png"];

//start timer that fires every second
[NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];

//start timer that fires every hundreth of a second
[NSTimer scheduledTimerWithTimeInterval:(0.01) target:self selector:@selector(onTimerRoad) userInfo:nil repeats:YES];
}

-(void)onTimerRoad
{
    int tileIndex;
tileIndex += 1;
[self setNeedsDisplay];
}

-(void)onTimer {
[self update];
[self draw];
}

-(void)update {
[self updateRoad];
}

-(void)updateRoad {
[self randomRoadUpdate];
}

-(void)randomRoadUpdate {
int distance = (random() % 11) -5;
CGPoint oldPosition = road.center;
if (oldPosition.x + distance < 96 || oldPosition.x + distance > 224)
    return;
road.center = CGPointMake(oldPosition.x + distance, oldPosition.y);
}

-(void)draw {

}

- (id) initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
    //init code
}
return self;
}

-(void)drawRect:(CGRect)rect {
CGImageRef image = CGImageRetain(currentImage.CGImage);
CGRect imageRect;
imageRect.origin = CGPointMake(160, 240);
imageRect.size = CGSizeMake(320.0, 480.0);
CGContextRef uiContext = UIGraphicsGetCurrentContext();
CGContextClipToRect(uiContext, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height));
CGContextDrawTiledImage(uiContext, imageRect, image);

}


问:
Using BlueSnap on more than one Magento store
I have a BlueSnap account that I use on a Magento 2 online store. It works well, but now I plan to open a separate Magento online store with a different domain. I don't know if it's possible to use the same BlueSnap account for the new store's payment gateway, or should I just open some sub-section in BlueSnap to handle the new business?

If I copy the setup of the Magento BlueSnap plugin to the new store I have a few issues - I get notifications to the old domain, for example. After a few test tries, I'm not sure how to set it up.

Does anyone have experience with this?

答:
there is no problem excepting payments from more then one store on the same bluesnap account.
the only issue that I can think of is with the notifications,
In your BlueSnap account, under settings-general settings you can Add a second IPN URL and define the URL of your second store. this will mean that all notifications will be sent to both of your stores.

I don't know if on magento side the BlueSnap plugin will ignore notifications on orders that where not made from the same store.
If on your testing you just see the notification in the logs of your "original" store but there is no other affect, then you can add the URL of your new store to the notification settings and each store will handle the notifications that are relevant to the orders that where created on it only.