问:
AttributeError: 'module' object has no attribute 'getmro'
I try to start a python app and after many problems with dependencies I got into another problem. After googling for a few hours I turned to my fav site for answers

```<code>python manage.py runserver
</code>```

gives:

```<code>Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 303, in execute
settings.INSTALLED_APPS
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 92, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/bianca/other/DreamCatcher/dreamcatcher/__init__.py", line 1, in <module>
from .celery_dreamcatcher import app as celery_app
File "/Users/bianca/other/DreamCatcher/dreamcatcher/celery_dreamcatcher.py", line 4, in <module>
from django.utils.log import logging
File "/Library/Python/2.7/site-packages/django/utils/log.py", line 16, in <module>
from django.views.debug import ExceptionReporter, get_exception_reporter_filter
File "/Library/Python/2.7/site-packages/django/views/debug.py", line 9, in <module>
from django.core.urlresolvers import Resolver404, resolve
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 18, in <module>
from django.http import Http404
File "/Library/Python/2.7/site-packages/django/http/__init__.py", line 4, in <module>
from django.http.response import (
File "/Library/Python/2.7/site-packages/django/http/response.py", line 13, in <module>
from django.core.serializers.json import DjangoJSONEncoder
File "/Library/Python/2.7/site-packages/django/core/serializers/__init__.py", line 24, in <module>
from django.core.serializers.base import SerializerDoesNotExist
File "/Library/Python/2.7/site-packages/django/core/serializers/base.py", line 6, in <module>
from django.db import models
File "/Library/Python/2.7/site-packages/django/db/models/__init__.py", line 6, in <module>
from django.db.models.query import Q, QuerySet, Prefetch  # NOQA
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 16, in <module>
from django.db.models import sql
File "/Library/Python/2.7/site-packages/django/db/models/sql/__init__.py", line 2, in <module>
from django.db.models.sql.subqueries import *  # NOQA
File "/Library/Python/2.7/site-packages/django/db/models/sql/subqueries.py", line 9, in <module>
from django.db.models.sql.query import Query
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 17, in <module>
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 17, in <module>
from django.db.models.aggregates import Count
File "/Library/Python/2.7/site-packages/django/db/models/aggregates.py", line 5, in <module>
from django.db.models.expressions import Func, Value
File "/Library/Python/2.7/site-packages/django/db/models/expressions.py", line 7, in <module>
from django.db.models import fields
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 19, in <module>
from django import forms
File "/Library/Python/2.7/site-packages/django/forms/__init__.py", line 6, in   <module>
from django.forms.fields import *  # NOQA
File "/Library/Python/2.7/site-packages/django/forms/fields.py", line 57, in <module>
class Field(six.with_metaclass(RenameFieldMethods, object)):
File "/Library/Python/2.7/site-packages/django/utils/six.py", line 778, in __new__
return meta(name, bases, d)
File "/Library/Python/2.7/site-packages/django/utils/deprecation.py", line 53, in __new__
for base in inspect.getmro(new_class):
AttributeError: 'module' object has no attribute 'getmro'
</code>```

I searched but I could not find a file names inspect.py in the project. Any idea is much appreciated. Thanks!

EDIT:

```<code>mdfind inspect.pyc
</code>```

gives

```<code>/Library/Python/2.7/site-packages/django/utils/inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/compat/_inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/test/test_inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/compat/_inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/test/test_inspect.pyc
</code>```

EDIT:

I removed python 2.6 but that does not save the problem.

答:
Installing django-inspect worked for me but it looks like it down graded Django to 1.8.6 from 1.8.9.

My website is back up!!!

pip install pip django-inspect

```<code>Requirement already satisfied: pip in /usr/lib/python2.7/site-packages
 Collecting django-inspect
   Downloading django-inspect-0.4.1.tar.gz
 Collecting Django<=1.8.6 (from django-inspect)
     Downloading Django-1.8.6-py2.py3-none-any.whl (6.2MB)
     100% |████████████████████████████████| 6.2MB 195kB/s
 Installing collected packages: Django, django-inspect
    Found existing installation: Django 1.8.9
      Uninstalling Django-1.8.9:
       Successfully uninstalled Django-1.8.9
  Running setup.py install for django-inspect ... done
 Successfully installed Django-1.8.6 django-inspect-0.4.1
</code>```

Body:
I try to start a python app and after many problems with dependencies I got into another problem. After googling for a few hours I turned to my fav site for answers

python manage.py runserver

gives:

Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 303, in execute
settings.INSTALLED_APPS
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 92, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/bianca/other/DreamCatcher/dreamcatcher/__init__.py", line 1, in <module>
from .celery_dreamcatcher import app as celery_app
File "/Users/bianca/other/DreamCatcher/dreamcatcher/celery_dreamcatcher.py", line 4, in <module>
from django.utils.log import logging
File "/Library/Python/2.7/site-packages/django/utils/log.py", line 16, in <module>
from django.views.debug import ExceptionReporter, get_exception_reporter_filter
File "/Library/Python/2.7/site-packages/django/views/debug.py", line 9, in <module>
from django.core.urlresolvers import Resolver404, resolve
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 18, in <module>
from django.http import Http404
File "/Library/Python/2.7/site-packages/django/http/__init__.py", line 4, in <module>
from django.http.response import (
File "/Library/Python/2.7/site-packages/django/http/response.py", line 13, in <module>
from django.core.serializers.json import DjangoJSONEncoder
File "/Library/Python/2.7/site-packages/django/core/serializers/__init__.py", line 24, in <module>
from django.core.serializers.base import SerializerDoesNotExist
File "/Library/Python/2.7/site-packages/django/core/serializers/base.py", line 6, in <module>
from django.db import models
File "/Library/Python/2.7/site-packages/django/db/models/__init__.py", line 6, in <module>
from django.db.models.query import Q, QuerySet, Prefetch  # NOQA
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 16, in <module>
from django.db.models import sql
File "/Library/Python/2.7/site-packages/django/db/models/sql/__init__.py", line 2, in <module>
from django.db.models.sql.subqueries import *  # NOQA
File "/Library/Python/2.7/site-packages/django/db/models/sql/subqueries.py", line 9, in <module>
from django.db.models.sql.query import Query
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 17, in <module>
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 17, in <module>
from django.db.models.aggregates import Count
File "/Library/Python/2.7/site-packages/django/db/models/aggregates.py", line 5, in <module>
from django.db.models.expressions import Func, Value
File "/Library/Python/2.7/site-packages/django/db/models/expressions.py", line 7, in <module>
from django.db.models import fields
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 19, in <module>
from django import forms
File "/Library/Python/2.7/site-packages/django/forms/__init__.py", line 6, in   <module>
from django.forms.fields import *  # NOQA
File "/Library/Python/2.7/site-packages/django/forms/fields.py", line 57, in <module>
class Field(six.with_metaclass(RenameFieldMethods, object)):
File "/Library/Python/2.7/site-packages/django/utils/six.py", line 778, in __new__
return meta(name, bases, d)
File "/Library/Python/2.7/site-packages/django/utils/deprecation.py", line 53, in __new__
for base in inspect.getmro(new_class):
AttributeError: 'module' object has no attribute 'getmro'

I searched but I could not find a file names inspect.py in the project. Any idea is much appreciated. Thanks!

EDIT:

mdfind inspect.pyc

gives

/Library/Python/2.7/site-packages/django/utils/inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/compat/_inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/test/test_inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/compat/_inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.pyc
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/test/test_inspect.pyc

EDIT:

I removed python 2.6 but that does not save the problem.

Body:
Installing django-inspect worked for me but it looks like it down graded Django to 1.8.6 from 1.8.9.

My website is back up!!!

pip install pip django-inspect

Requirement already satisfied: pip in /usr/lib/python2.7/site-packages
 Collecting django-inspect
   Downloading django-inspect-0.4.1.tar.gz
 Collecting Django<=1.8.6 (from django-inspect)
     Downloading Django-1.8.6-py2.py3-none-any.whl (6.2MB)
     100% |████████████████████████████████| 6.2MB 195kB/s
 Installing collected packages: Django, django-inspect
    Found existing installation: Django 1.8.9
      Uninstalling Django-1.8.9:
       Successfully uninstalled Django-1.8.9
  Running setup.py install for django-inspect ... done
 Successfully installed Django-1.8.6 django-inspect-0.4.1


来源: stackexchange

问:
how to disable single tab in dojo tabcontainer
i want to disable single tab in tabcontainer of dojo . </p>

ContentLicense: CC BY-SA 2.5

Body: dijit.byId('tab').controlButton.domNode.disabled = true


问:
css animation change from absolute to relative
i have found this wave animation "https://codepen.io/tedmcdo/pen/PqxKXg" and would like to use it over my headerimg on my page, but the problem is that the animation is written for absolute values, but i would need a relative position since the animation should stay on top of the page.

I have tried to change to position type to relative but however i do it i break the animation, if anyone could help me i would be happy^^

thank you all for your time.

here is the css:

```<code>html, body { height: 100%; }
body {
  background:radial-gradient(ellipse at center, rgba(255,254,234,1) 0%, rgba(255,254,234,1) 35%, rgba(254,208,149,1) 100%);
  overflow: hidden;
}

.ocean {
  height: 5%;
  width:100%;
  position:absolute;
  bottom:0;
  left:0;
  background: #015871;
}

.wave {
  background: url(http://tedmcdo.com/labs/wave.svg) repeat-x;
  position: absolute;
  top: -198px;
  width: 6400px;
  height: 198px;
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) infinite;
  transform: translate3d(0, 0, 0);
}

.wave:nth-of-type(2) {
  top: -175px;
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) -.125s infinite, swell 7s ease -1.25s infinite;
  opacity: 1;
}

@keyframes wave {
  0% {
    margin-left: 0;
  }
  100% {
    margin-left: -1600px;
  }
}

@keyframes swell {
  0%, 100% {
    transform: translate3d(0,-25px,0);
  }
  50% {
    transform: translate3d(0,5px,0);
  }
}
</code>```

答:
Put it into a relative div(or other container), and the .ocean will be absolute in the relative container. That may solve your problem.</p>

```<code><div style="position: relative">
   <div class="ocean" style="position: absolute"></div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have found this wave animation "https://codepen.io/tedmcdo/pen/PqxKXg" and would like to use it over my headerimg on my page, but the problem is that the animation is written for absolute values, but i would need a relative position since the animation should stay on top of the page.

I have tried to change to position type to relative but however i do it i break the animation, if anyone could help me i would be happy^^

thank you all for your time.

here is the css:

html, body { height: 100%; }
body {
  background:radial-gradient(ellipse at center, rgba(255,254,234,1) 0%, rgba(255,254,234,1) 35%, rgba(254,208,149,1) 100%);
  overflow: hidden;
}

.ocean {
  height: 5%;
  width:100%;
  position:absolute;
  bottom:0;
  left:0;
  background: #015871;
}

.wave {
  background: url(http://tedmcdo.com/labs/wave.svg) repeat-x;
  position: absolute;
  top: -198px;
  width: 6400px;
  height: 198px;
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) infinite;
  transform: translate3d(0, 0, 0);
}

.wave:nth-of-type(2) {
  top: -175px;
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) -.125s infinite, swell 7s ease -1.25s infinite;
  opacity: 1;
}

@keyframes wave {
  0% {
    margin-left: 0;
  }
  100% {
    margin-left: -1600px;
  }
}

@keyframes swell {
  0%, 100% {
    transform: translate3d(0,-25px,0);
  }
  50% {
    transform: translate3d(0,5px,0);
  }
}

Body:
Put it into a relative div(or other container), and the .ocean will be absolute in the relative container. That may solve your problem.

<div style="position: relative">
   <div class="ocean" style="position: absolute"></div>
</div>


问:
Output by number in a for loop
What is the right syntax of this? I want to output not every result, but I want to output by number. For example from 1 to 20 of results etc. Or only 1st,3rd and 5th numbers of results. Can I make an array of the results?</p>

```<code>for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

// I want to output something like the following in the for loop:
  echo $target_path[0],
  echo $target_path[5],
  echo $target_path[3],
}
</code>```

答:
Using Modulo Arithmetic Operators you can echo based on the index.

From http://php.net/manual/en/language.operators.arithmetic.php

```<code>if(($i % 2) == 1)  //odd
}
</code>```

So this should work:

```<code>for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];
  if(($i % 2) == 1)
      echo $target_path;
  }
}
</code>```

Title: Output by number in a for loop

Body:
What is the right syntax of this? I want to output not every result, but I want to output by number. For example from 1 to 20 of results etc. Or only 1st,3rd and 5th numbers of results. Can I make an array of the results?

for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

// I want to output something like the following in the for loop:
  echo $target_path[0],
  echo $target_path[5],
  echo $target_path[3],
}

Body:
Using Modulo Arithmetic Operators you can echo based on the index.

From http://php.net/manual/en/language.operators.arithmetic.php

if(($i % 2) == 1)  //odd
}

So this should work:

for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];
  if(($i % 2) == 1)
      echo $target_path;
  }
}


问:
Shorten if statement with same condition
Is there a way to shorten an if statement like this:

if(x == 1 && y == 1 && z == 1) -> if((x && y && z) == 1) or if((x,y,z) == 1)

Edit: Sorry for the inconvenience. Did it quick on my phone. Here is a full example:

This is a part of my connect fours game.

```<code>bool checkwin(string player) {
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            if (grid[i][j] == player && grid[i + 1][j] == player && grid[i + 2][j] == player && grid[i + 3][j] == player) {
                return 1;
            }
            if (grid[i][j] == player && grid[i][j + 1] == player && grid[i][j + 2] == player && grid[i][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i + 1][j + 1] == player && grid[i + 2][j + 2] == player && grid[i + 3][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i - 1][j + 1] == player && grid[i - 2][j + 2] == player && grid[i - 3][j + 3] == player) {
                return 1;
            }
        }
    }
}
</code>```

答:
If you want to check that all variables are equal to each other, you can write this kind of helper

```<code>template <typename T>
bool all_equal(const std::initializer_list<T>& l) {
    return std::equal(l.begin() + 1, l.end(), l.begin());
}
</code>```

Usage:

```<code>if (all_equal({a, b, c}))
</code>```

online version: http://ideone.com/8OC1yq

Body:
Is there a way to shorten an if statement like this:

if(x == 1 && y == 1 && z == 1) -> if((x && y && z) == 1) or if((x,y,z) == 1)

Edit: Sorry for the inconvenience. Did it quick on my phone. Here is a full example:

This is a part of my connect fours game.

bool checkwin(string player) {
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            if (grid[i][j] == player && grid[i + 1][j] == player && grid[i + 2][j] == player && grid[i + 3][j] == player) {
                return 1;
            }
            if (grid[i][j] == player && grid[i][j + 1] == player && grid[i][j + 2] == player && grid[i][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i + 1][j + 1] == player && grid[i + 2][j + 2] == player && grid[i + 3][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i - 1][j + 1] == player && grid[i - 2][j + 2] == player && grid[i - 3][j + 3] == player) {
                return 1;
            }
        }
    }
}

Body:
If you want to check that all variables are equal to each other, you can write this kind of helper

template <typename T>
bool all_equal(const std::initializer_list<T>& l) {
    return std::equal(l.begin() + 1, l.end(), l.begin());
}

Usage:

if (all_equal({a, b, c}))

online version: http://ideone.com/8OC1yq


问:
SELECT the same date as in the datepicker
I have a datepicker with the format d/m/Y:

```<code><input type="text" name="date" id="single_cal4" class="form-control has-feedback-left" aria-describedby="inputSuccess2Status4">
</code>```

If the date is changed I want to run an SQL statement that needs to select the id from the database WHERE the year is the same year as the selected year in the datepicker.

Does someone know how I can run an SQL statement that runs an WHERE with the selected year from the datepicker?

Here is my SQL statement:

```<code>$sql = SELECT id FROM `trans` WHERE user_id='". $_SESSION['user_id'] ."' AND year(date) = ";
</code>```

答:
Since your supplied date is not the right format for SQL's YEAR() function, I would just use substr on the input as below:

```<code>$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$date = mysqli_real_escape_string($link, $_GET['date'];);
$year = substr($date, -4);
$sql = "SELECT id FROM `trans` WHERE user_id=". $_SESSION['user_id'] ." AND YEAR(date)=".$year;
</code>```

Dont forget to sanitize the input.

Body:
I have a datepicker with the format d/m/Y:

<input type="text" name="date" id="single_cal4" class="form-control has-feedback-left" aria-describedby="inputSuccess2Status4">

If the date is changed I want to run an SQL statement that needs to select the id from the database WHERE the year is the same year as the selected year in the datepicker.

Does someone know how I can run an SQL statement that runs an WHERE with the selected year from the datepicker?

Here is my SQL statement:

$sql = SELECT id FROM `trans` WHERE user_id='". $_SESSION['user_id'] ."' AND year(date) = ";

Body:
Since your supplied date is not the right format for SQL's YEAR() function, I would just use substr on the input as below:

$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$date = mysqli_real_escape_string($link, $_GET['date'];);
$year = substr($date, -4);
$sql = "SELECT id FROM `trans` WHERE user_id=". $_SESSION['user_id'] ." AND YEAR(date)=".$year;

Dont forget to sanitize the input.


问:
Google chrome and safari browser data storage
I want to know whether Google chrome and safari browsers currently support local data storage?

I need to store some data in browser level and need to query it. Is this browsers support local data storage?

Thank You,

答:
Yes they do, as part of their support for HTML 5, specifically HTML 5 Client-side Database Storage through an API.

You can see an example of it in action here. You can find a tutorial at darkcrimson.com. You can find the standard for it at W3C.


问:
Subclassing Swift Double / Operator Overloading typealias
I'd like to be able to subclass Double with some custom types in my swift code so I can do some introspection and operator overloading later on.

This is semantically what I want to be able to write:

```<code>class Frequency: Double {}

class Period: Double {
    init(_ frequency: Frequency) {
        let period: Double = 1 / frequency
        self.init(period)
    }
}

let a = Double(1)
print(type(of: a))  // Double

let b = Frequency(2)
print(type(of: b))  // Frequency

let c = Period(a)
print(type(of: c))  // Period == 1

let d = Period(b)
print(type(of: d))  // Period == 0.5
</code>```

Feel like what I'm trying to do should be posible as Swift is a strictly typed language.

I've looked at typealiases as well, but you can't operator overload with those. Also looked at the FloatingPoint protocol but doesn't seem to help me.

答:
while this is not possible, I created a class a while ago, which addressed a similar issue. I was in need of a polyvalent variable class, for ease of synthax in currency strings, and ended up with something like bellow. So far it's working great, and I've been using it as mortar for many advanced subclasses i've built since then. It does what you wish, which if you can see in the Frequency subclass, becomes a matter of tweaking the init override for each use case.
While the class is large, and the methods bulky, feel free to tweak and modify however you see fit, or if you find simpler approaches. I uploaded it to a gist file here so it can be read easily.

Link to the class.

When used with your use case, it allows for the following, which seems to be what you want:

```<code>class Frequency : MultiVar {
    override init(_ value: Any?) {
        super.init(value)
        let current = double
        guard current != 0.0 else {
            print("Frequency Error: Something went wrong while subclassing \(self), established variable 'double' is equal to 0!")
            return
        }
        double = 1 / current
    }
}

let freq = Frequency(10)
print(freq.string) //prints 0.1
print(freq.double) //prints 0.1
</code>```

Body:
I'd like to be able to subclass Double with some custom types in my swift code so I can do some introspection and operator overloading later on.

This is semantically what I want to be able to write:

class Frequency: Double {}

class Period: Double {
    init(_ frequency: Frequency) {
        let period: Double = 1 / frequency
        self.init(period)
    }
}

let a = Double(1)
print(type(of: a))  // Double

let b = Frequency(2)
print(type(of: b))  // Frequency

let c = Period(a)
print(type(of: c))  // Period == 1

let d = Period(b)
print(type(of: d))  // Period == 0.5

Feel like what I'm trying to do should be posible as Swift is a strictly typed language.

I've looked at typealiases as well, but you can't operator overload with those. Also looked at the FloatingPoint protocol but doesn't seem to help me.

Body:
while this is not possible, I created a class a while ago, which addressed a similar issue. I was in need of a polyvalent variable class, for ease of synthax in currency strings, and ended up with something like bellow. So far it's working great, and I've been using it as mortar for many advanced subclasses i've built since then. It does what you wish, which if you can see in the Frequency subclass, becomes a matter of tweaking the init override for each use case.
While the class is large, and the methods bulky, feel free to tweak and modify however you see fit, or if you find simpler approaches. I uploaded it to a gist file here so it can be read easily.

Link to the class.

When used with your use case, it allows for the following, which seems to be what you want:

class Frequency : MultiVar {
    override init(_ value: Any?) {
        super.init(value)
        let current = double
        guard current != 0.0 else {
            print("Frequency Error: Something went wrong while subclassing \(self), established variable 'double' is equal to 0!")
            return
        }
        double = 1 / current
    }
}

let freq = Frequency(10)
print(freq.string) //prints 0.1
print(freq.double) //prints 0.1


问:
What Meaning Of This Function
```<code>function [TC]=Translate(T0,Base)
end
</code>```

I know that Translate is a function and T0 and Base his parameter but what is [TC]?

答:
Octave (and matlab) have a rather unique way of returning variables from functions. Instead of defining explicitly what to return from the function using a return keyword, they define from the outset which variables will be returned when the function exits, and octave simply looks for those variables by name at the time the function exits, and returns their values, whatever they may be by that point.

Your function may return nothing:

```<code>function returnsNothing();
  disp('hello, I return nothing');
end
</code>```

or it may return one output:

```<code>function Out = returnsOne(x)
  Out = x+5
  disp('This function will return the value of Out');
end
</code>```

or it may return more than one outputs:

```<code>function [Out1, Out2] = returnsTwo(x)
  Out1 = x+5;
  Out2 = x+10;
end
</code>```

You would call the last function from the octave terminal (or script) like this:

```<code>[a,b] = returnsTwo(5);  % this will make a = 10 and b = 15
</code>```

Title: What Meaning Of This Function

Body:
function [TC]=Translate(T0,Base)
end

I know that Translate is a function and T0 and Base his parameter but what is [TC]?

Body:
Octave (and matlab) have a rather unique way of returning variables from functions. Instead of defining explicitly what to return from the function using a return keyword, they define from the outset which variables will be returned when the function exits, and octave simply looks for those variables by name at the time the function exits, and returns their values, whatever they may be by that point.

Your function may return nothing:

function returnsNothing();
  disp('hello, I return nothing');
end

or it may return one output:

function Out = returnsOne(x)
  Out = x+5
  disp('This function will return the value of Out');
end

or it may return more than one outputs:

function [Out1, Out2] = returnsTwo(x)
  Out1 = x+5;
  Out2 = x+10;
end

You would call the last function from the octave terminal (or script) like this:

[a,b] = returnsTwo(5);  % this will make a = 10 and b = 15


问:
How to link to pages without the .html extension?
I would like to link to pages inside my website, e.g:
Not: mywebsite.com/about.html But: mywebsite.com/about/

I've seen various websites doing this but it looks like they also react differently to things:

Apple.com:
apple.com/iphone/ works, apple.com/iphone/index.html works, apple.com/iphone redirects.

Opera.com:
opera.com/mobile/ redirects, opera.com/mobile works, opera.com/mobile.html does not work.

Mozilla.com:
mozilla.org/en-US/ works, mozilla.org/en-US redirects, mozilla.org/en-US/index.html does not work.

Which leads to another question: Are there different methods for this?

Edit:
It seems that Apple uses a folder for every page, e.g. a folder called 'iphone' with an index.html file inside it?
But Opera and Mozilla use something in the .htaccess file?

答:
Make your href attribute equal to the page you want to link or .. If you need to
move up a directory.

Ex: href="contact.html"
Ex: href="../links/contact.html"


问:
Saving Multiple Plots with Different Names
I'm trying to save multiple plots to a directory. Problem is, I don't want to use a counter for the different file names because they all have different ID numbers, denoted as trk_id, or j. If you need more of the code, please let me know! Plus, I know this code just uses the same name and overwrites each file.</p>

```<code>  for i, j in enumerate(trk_id):
          t = np.arange(0, 3*3600) + t0_b[i]
          g_x = f_r(tau_b[i], t0_b[i], c0_b[i], c1_b[i], c2_b[i])
          fig,ax = plt.subplots()
          ax.plot(t, g_x(t))
          plt.yscale('log')
          plt.ylabel('Height (arcsec)')
          plt.xlabel('Time (s)')
          ax.set_title(j)
          plt.savefig('plots/j.png')
</code>```

答:
In order to use the loop variable j as filename, you can generate a string like

```<code>filename = 'plots/' + str(j) +'.png'
plt.savefig(filename)
</code>```

or

```<code>filename = 'plots/{}.png'.format(j)
plt.savefig(filename)
</code>```

Body:
I'm trying to save multiple plots to a directory. Problem is, I don't want to use a counter for the different file names because they all have different ID numbers, denoted as trk_id, or j. If you need more of the code, please let me know! Plus, I know this code just uses the same name and overwrites each file.

  for i, j in enumerate(trk_id):
          t = np.arange(0, 3*3600) + t0_b[i]
          g_x = f_r(tau_b[i], t0_b[i], c0_b[i], c1_b[i], c2_b[i])
          fig,ax = plt.subplots()
          ax.plot(t, g_x(t))
          plt.yscale('log')
          plt.ylabel('Height (arcsec)')
          plt.xlabel('Time (s)')
          ax.set_title(j)
          plt.savefig('plots/j.png')

Body:
In order to use the loop variable j as filename, you can generate a string like

filename = 'plots/' + str(j) +'.png'
plt.savefig(filename)

or

filename = 'plots/{}.png'.format(j)
plt.savefig(filename)


问:
How to integrate std::valarray<double> with gsl?
I am relatively new to C++, but I have some (scarce) coding and numerical experience.

I know that this question gets posted every now and then, how do you integrate an array. In MATLAB you can force your array to be a function (I forgot how, but I know I did it before) and send it to inbuilt integrators, so my question is how do you do it in C++.

I have this integral:

```<code>I = integral(A(z)*sin(qz)*dz)
</code>```

q is just double const, z is the integrating variable, but A(z) is an array (I'll call it actualfunction from now on) that has same number of points as z axis in my code. Integrating boundaries are z[0] and z[nz-1].

I calculated this integral by using trapezium rule, and for z-axis of 5000 points this takes 0.06 sec. My problem is that this calculation occurs roughly 300 * 30 * 20 times (I have 3 for loops), and this 0.06 sec grows very quickly to 3 hours of the simulation. And the entire bottleneck of my code is this integration (I can obviously speed up by reducing z, but that's not the point.)

I know that library functions are usually much better then user-written ones. I also know that I can't use something simpler as Simpson's rule, because the integrand is highly oscillatory, and I want to avoid my own implementation of some complicated numerical alghoritm.

GSL needs a function in form:

F = f(double x, void *params)

and I can probably use QAWO adaptive integration from gsl, but how do I make my function in form that turns my array into function?

I am thinking something as:

```<code>F(double z, void *params)
{
  std::valarray<double> actualfunction = *(std::valarray<double> *) params;
  double dz = *(double *) params; // Pretty sure this is wrong
  unsigned int actual_index = z / dz; // crazy assumption (my z[0] was 0)
  return actualfunction[actual_index];
 }
</code>```

Is something like this possible? I doubt that numerical algorithm will use same spatial difference as actualfunction had, should I then somehow do interpolation of actualfunction or something?

Is there something better then gsl?

答:
```<code>template<class F>
struct func_ptr_helper {
  F f;
  void* pvoid(){ return std::addressof(f); }
  template<class R, class...Args>
  using before_ptr=R(*)(void*,Args...);
  template<class R, class...Args>
  using after_ptr=R(*)(Args...,void*);
  template<class R, class...Args>
  static before_ptr<R,Args...> before_func() {
    return [](void* p, Args...args)->R{
      return (*static_cast<F*>(p))(std::forward<Args>(args)...);
    };
  }
  template<class R, class...Args>
  static after_ptr<R,Args...> after_func() {
    return [](Args...args, void* p)->R{
      return (*static_cast<F*>(p))(std::forward<Args>(args)...);
    };
  }
};
template<class F>
func_ptr_helper<F> lambda_to_pfunc( F f ){ return {std::move(f)}; }
</code>```

use:

```<code>auto f = lambda_to_pfunc([&actualfunction, &dz](double z){
  unsigned int actual_index = z / dz; // crazy assumption (my z[0] was 0)
  return actualfunction[actual_index];
});
</code>```

then

```<code>void* pvoid - f.pvoid();
void(*pfun)(double, void*) = f.after_func();
</code>```

and you can pass pfun and pvoid through.

Apologies for any typos.

The idea is we write a lambda that does what we want.  Then lambda_to_pfunc wraps it up so we can pass it as a void* and function pointer to C style APIs.

You'll have to properly manage the lifetime of everything of course.

Body:
I am relatively new to C++, but I have some (scarce) coding and numerical experience.

I know that this question gets posted every now and then, how do you integrate an array. In MATLAB you can force your array to be a function (I forgot how, but I know I did it before) and send it to inbuilt integrators, so my question is how do you do it in C++.

I have this integral:

I = integral(A(z)*sin(qz)*dz)

q is just double const, z is the integrating variable, but A(z) is an array (I'll call it actualfunction from now on) that has same number of points as z axis in my code. Integrating boundaries are z[0] and z[nz-1].

I calculated this integral by using trapezium rule, and for z-axis of 5000 points this takes 0.06 sec. My problem is that this calculation occurs roughly 300 * 30 * 20 times (I have 3 for loops), and this 0.06 sec grows very quickly to 3 hours of the simulation. And the entire bottleneck of my code is this integration (I can obviously speed up by reducing z, but that's not the point.)

I know that library functions are usually much better then user-written ones. I also know that I can't use something simpler as Simpson's rule, because the integrand is highly oscillatory, and I want to avoid my own implementation of some complicated numerical alghoritm.

GSL needs a function in form:

F = f(double x, void *params)

and I can probably use QAWO adaptive integration from gsl, but how do I make my function in form that turns my array into function?

I am thinking something as:

F(double z, void *params)
{
  std::valarray<double> actualfunction = *(std::valarray<double> *) params;
  double dz = *(double *) params; // Pretty sure this is wrong
  unsigned int actual_index = z / dz; // crazy assumption (my z[0] was 0)
  return actualfunction[actual_index];
 }

Is something like this possible? I doubt that numerical algorithm will use same spatial difference as actualfunction had, should I then somehow do interpolation of actualfunction or something?

Is there something better then gsl?

Body:
template<class F>
struct func_ptr_helper {
  F f;
  void* pvoid(){ return std::addressof(f); }
  template<class R, class...Args>
  using before_ptr=R(*)(void*,Args...);
  template<class R, class...Args>
  using after_ptr=R(*)(Args...,void*);
  template<class R, class...Args>
  static before_ptr<R,Args...> before_func() {
    return [](void* p, Args...args)->R{
      return (*static_cast<F*>(p))(std::forward<Args>(args)...);
    };
  }
  template<class R, class...Args>
  static after_ptr<R,Args...> after_func() {
    return [](Args...args, void* p)->R{
      return (*static_cast<F*>(p))(std::forward<Args>(args)...);
    };
  }
};
template<class F>
func_ptr_helper<F> lambda_to_pfunc( F f ){ return {std::move(f)}; }

use:

auto f = lambda_to_pfunc([&actualfunction, &dz](double z){
  unsigned int actual_index = z / dz; // crazy assumption (my z[0] was 0)
  return actualfunction[actual_index];
});

then

void* pvoid - f.pvoid();
void(*pfun)(double, void*) = f.after_func();

and you can pass pfun and pvoid through.

Apologies for any typos.

The idea is we write a lambda that does what we want.  Then lambda_to_pfunc wraps it up so we can pass it as a void* and function pointer to C style APIs.

You'll have to properly manage the lifetime of everything of course.

ContentLicense: CC BY-SA 4.0


问:
NHibernate Unit Of Work - Multiple Sessions (WinForms)
I am struggling with the learning curve for NHibernate.

We are currently porting our C# Winforms application to use NHibernate and are employing the Unit Of Work (UnitOfWork) as detailed by Gabriel Schenker.

NHibernate and the Unit of Work Pattern

We wish to employ the UnitofWork on a "Conversational" basis. For example when the user opens a form we would open a UnitOfWork session and then keep this open until the form is closed. Forms are just an easier way to define a business conversation, we may change this slightly depending upon the implementation but for this example, please use a form opening and closing as the example.

The problem exists when we have the scenario of a form opening on top of another form. In this instance we should have two UnitOfWork operating. One still active for the underlying form and a new UnitOfWork for the new form.

How do we implement this? The UnitOfWork functionality provided by Gabriel only allows one session per UnitOfWork? My initial thoughts are to store sessions in a Dictionary so that sessions can be called from any form or part of the application.

Your thoughts?

答: Read through Ayende's Building a Desktop To-Do Application with NHibernate in MSDN Magazine here: http://msdn.microsoft.com/en-us/magazine/ee819139.aspx. He discusses how to manage multiple units of work within a thick client application.</p>


问:
Exclude Specific Records from GLM?
I've built a GLM model that basically says the following:

```<code>glm(conversion ~ action, data = data, family = "binomial"(link="logit")
</code>```

Some of the results from the variable "action" aren't relevant to the model (i.e. "Did not use"). However, in the other models I've built, those records are still important. I don't want to filter my data frame just for this one model if at all possible.

This question tells me how to exclude columns. Is there a way to exclude specific records from GLM in the formula?

答:
You can use the subset argument that many of the modelling functions in R have. For example:

```<code>glm(conversion ~ action, data = data, family = binomial(),
    subset = action != "Did not use")
</code>```

will fit the model to the data set after removing rows where action == "Did not use". If you have additional levels in action to drop, you might use

```<code>glm(conversion ~ action, data = data, family = binomial(),
        subset = !action %in% c("Did not use", "Other"))
</code>```

which will exclude any rows where action is equal to either of the supplied options.

You might also want to look at the drop.unused.levels argument to model.frame, which is the function that will act on any subset argument you supply to glm().

PS: note how I have specified the family; you don't need to do the weird combination of quoting. one of binomial, binomial() or "binomial" should be fine as the logit link is the canonical link for the binomial family and hence it is the default in R's bionmial() family function. If you want to specify the link, use this form: binomial(link = "logit").

Title: Exclude Specific Records from GLM?

Body:
I've built a GLM model that basically says the following:

glm(conversion ~ action, data = data, family = "binomial"(link="logit")

Some of the results from the variable "action" aren't relevant to the model (i.e. "Did not use"). However, in the other models I've built, those records are still important. I don't want to filter my data frame just for this one model if at all possible.

This question tells me how to exclude columns. Is there a way to exclude specific records from GLM in the formula?

Body:
You can use the subset argument that many of the modelling functions in R have. For example:

glm(conversion ~ action, data = data, family = binomial(),
    subset = action != "Did not use")

will fit the model to the data set after removing rows where action == "Did not use". If you have additional levels in action to drop, you might use

glm(conversion ~ action, data = data, family = binomial(),
        subset = !action %in% c("Did not use", "Other"))

which will exclude any rows where action is equal to either of the supplied options.

You might also want to look at the drop.unused.levels argument to model.frame, which is the function that will act on any subset argument you supply to glm().

PS: note how I have specified the family; you don't need to do the weird combination of quoting. one of binomial, binomial() or "binomial" should be fine as the logit link is the canonical link for the binomial family and hence it is the default in R's bionmial() family function. If you want to specify the link, use this form: binomial(link = "logit").


问:
Better way for differentiating buttons Swift?
```<code>@IBAction func followUser(_ sender: Any) {
    if followBtn.titleLabel?.text == "Follow"{
        print("will follow")
    } else if followBtn.titleLabel?.text == "Following"{
    }
}
</code>```

Is there a better way of doing this? I have a function the runs on load then checks if the user is followed and changes the button's text. Naturally, if the button says "follow" it will have a different function than a button that says "following". Is this the only way I can do that? It feels wrong.

```<code>func checkFollowing(){

    let url = URL(string: "xxx")

    //request to this file
    var request = URLRequest(url: url!)

    //method to pass data
    request.httpMethod = "POST"

    //body to be appended to url
    let body = "id=\(user?["id"] as! String)&follower_id=\(imageID)"
    request.httpBody = body.data(using: String.Encoding.utf8)   //multi language support

    //launching
    URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in

        if error == nil{

            //communicate back to UI
            DispatchQueue.main.async(execute: {

                do{

                    //get json result
                    let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions .mutableContainers) as?
                    NSDictionary

                    //assign json to a new var parseJSON in guard secured way
                    guard let parseJSON = json else{

                        print("error while parsing")
                        return
                    }

                    if parseJSON["status"] as! String == "1"{
                        self.followBtn.setTitle("Following", for: .normal)
                        self.followBtn.backgroundColor = UIColor(red: 32, green: 113, blue: 165, alpha: 0.5)
                    } else if parseJSON["status"] as! String == "0"{
                        self.followBtn.setTitle("Follow", for: .normal)
                    }

                } catch{

                    print("Caught an error: \(error)")

                }

            })

            //if unable to proceed with request

        } else{

            print("error: \(error)")

        }

        //launch prepared session
    }).resume()
}
</code>```

答:
Tracking its status through a variable on the controller would be the better way of doing this.

```<code>var isFollowing: Bool!

// -------------------------------

if parseJSON["status"] as! String == "1"{
    self.followBtn.setTitle("Following", for: .normal)
    self.followBtn.backgroundColor = UIColor(red: 32, green: 113, blue: 165, alpha: 0.5)
    self.isFollowing = true
} else if parseJSON["status"] as! String == "0"{
    self.followBtn.setTitle("Follow", for: .normal)
    self.isFollowing = false
}

// -------------------------------

@IBAction func followUser(_ sender: Any) {
    if self.isFollowing {
        // whatever happens when you're already following
    } else {
        print("will follow")
    }
}
</code>```

(up to you whether you want to make it an optional, implicitly unwrapped optional, or set a default value, but of course if you use a regular optional you'll need to unwrap it for the last part)

Body:
@IBAction func followUser(_ sender: Any) {
    if followBtn.titleLabel?.text == "Follow"{
        print("will follow")
    } else if followBtn.titleLabel?.text == "Following"{
    }
}

Is there a better way of doing this? I have a function the runs on load then checks if the user is followed and changes the button's text. Naturally, if the button says "follow" it will have a different function than a button that says "following". Is this the only way I can do that? It feels wrong.

func checkFollowing(){

    let url = URL(string: "xxx")

    //request to this file
    var request = URLRequest(url: url!)

    //method to pass data
    request.httpMethod = "POST"

    //body to be appended to url
    let body = "id=\(user?["id"] as! String)&follower_id=\(imageID)"
    request.httpBody = body.data(using: String.Encoding.utf8)   //multi language support

    //launching
    URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in

        if error == nil{

            //communicate back to UI
            DispatchQueue.main.async(execute: {

                do{

                    //get json result
                    let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions .mutableContainers) as?
                    NSDictionary

                    //assign json to a new var parseJSON in guard secured way
                    guard let parseJSON = json else{

                        print("error while parsing")
                        return
                    }

                    if parseJSON["status"] as! String == "1"{
                        self.followBtn.setTitle("Following", for: .normal)
                        self.followBtn.backgroundColor = UIColor(red: 32, green: 113, blue: 165, alpha: 0.5)
                    } else if parseJSON["status"] as! String == "0"{
                        self.followBtn.setTitle("Follow", for: .normal)
                    }

                } catch{

                    print("Caught an error: \(error)")

                }

            })

            //if unable to proceed with request

        } else{

            print("error: \(error)")

        }

        //launch prepared session
    }).resume()
}

Body:
Tracking its status through a variable on the controller would be the better way of doing this.

var isFollowing: Bool!

// -------------------------------

if parseJSON["status"] as! String == "1"{
    self.followBtn.setTitle("Following", for: .normal)
    self.followBtn.backgroundColor = UIColor(red: 32, green: 113, blue: 165, alpha: 0.5)
    self.isFollowing = true
} else if parseJSON["status"] as! String == "0"{
    self.followBtn.setTitle("Follow", for: .normal)
    self.isFollowing = false
}

// -------------------------------

@IBAction func followUser(_ sender: Any) {
    if self.isFollowing {
        // whatever happens when you're already following
    } else {
        print("will follow")
    }
}

(up to you whether you want to make it an optional, implicitly unwrapped optional, or set a default value, but of course if you use a regular optional you'll need to unwrap it for the last part)


问:
Change Git Username to Connect to My Remote Repo
I worked a contract gig recently with a temporary email address and username for git repos. It's over now and the temp username seems to be messing up my old personal repositories in git.

When I try to push origin master

I get:

```<code>remote: Permission to <my-repo>.git denied to <wrong-username>.
</code>```

If I look in git config --list I get the proper username and email - I can't seem to find the location of [wrong-username] and I can't get rid of it. How do I connect back to my remote repository and get rid of this old username that I won't be using in the future?

答:
I found the answer here: Git's famous "ERROR: Permission to .git denied to user"

It's the second answer with five steps. Go to keychain access and delete anything that looks incorrect. That solved my problem.

Body:
I worked a contract gig recently with a temporary email address and username for git repos. It's over now and the temp username seems to be messing up my old personal repositories in git.

When I try to push origin master

I get:

remote: Permission to <my-repo>.git denied to <wrong-username>.

If I look in git config --list I get the proper username and email - I can't seem to find the location of [wrong-username] and I can't get rid of it. How do I connect back to my remote repository and get rid of this old username that I won't be using in the future?


问:
Chartkick Rails 4 Bar Chart Issue with Multiple Charts
I have a problem where I have multiple poll questions on a page.  Simply enough, after a question is answered an AJAX call is made to the controller and a js.erb is rendered displaying a chart using the Chartkick gem and the Google jaspi library.  This works fine for only a single chart.  However, having several bar charts (one for each answered question) is a problem.  What happens is the most recently answered question overwrites the chart of the question in the wrong div and just displays loading in the last answered question.

Here is the basic code.

In View:

```<code> <div id="results-<%= i %>" style="display: none; margin-top: -20px;"></div>
</code>```

Once the question is answered the above div is shown with the chart.

In the controller:

```<code> data = [
    {
        data: results_array
    }
  ]
  respond_to do |format|
    @div_id = div_id
    @poll_data = data
    format.js
  end
</code>```

And then in the js.erb file that is rendereed in the above block:

```<code> $("#results-<%= @div_id%>").html('<%= escape_javascript(bar_chart(@poll_data, library: {legend: "none"})) %>').show();
</code>```

Any help would be greatly appreciated.  I need to display the correct charts for each question and have them dependably loaded. Is there a way to distinguish between instances of charts or objects that I am missing? Thanks.

答:
I had same problem with Chartkick, I have just changed the 'id' of every chart I wanted to use. The solution I found is on link below: https://github.com/ankane/chartkick/issues/193
I know is bit to late for this answer, but maybe it will help someone else.</p>

Body:
I have a problem where I have multiple poll questions on a page.  Simply enough, after a question is answered an AJAX call is made to the controller and a js.erb is rendered displaying a chart using the Chartkick gem and the Google jaspi library.  This works fine for only a single chart.  However, having several bar charts (one for each answered question) is a problem.  What happens is the most recently answered question overwrites the chart of the question in the wrong div and just displays loading in the last answered question.

Here is the basic code.

In View:

 <div id="results-<%= i %>" style="display: none; margin-top: -20px;">

Once the question is answered the above div is shown with the chart.

In the controller:

 data = [
    {
        data: results_array
    }
  ]
  respond_to do |format|
    @div_id = div_id
    @poll_data = data
    format.js
  end

And then in the js.erb file that is rendereed in the above block:

 $("#results-<%= @div_id%>").html('<%= escape_javascript(bar_chart(@poll_data, library: {legend: "none"})) %>').show();

Any help would be greatly appreciated.  I need to display the correct charts for each question and have them dependably loaded. Is there a way to distinguish between instances of charts or objects that I am missing? Thanks.


问:
Spring batch mechanism for CORBA
Is there an established way a CORBA client API could be invoked part of the Spring-Batch mechanism?

I have a requirement for mass data be processed through the APIs hosted via CORBA from a database. I am considering the API call as an Item Processor or Item Writer.

For Item processor, I may need to just call the API in the processing phase by injecting the necessary CORBA stuff.

For Item Writer, Is there a writer that is suitable? I didn't find one. Maybe I can build a writer generically so that it could be used as any other writer or just write a custom writer and get over it.

Could anyone help by evaluating the approaches and suggest the best possible way?
If I could write a generic CorbaItemWriter how can I contribute to the Spring Batch community?

Note: I was able to successfully get the CORBA client configured in Spring and use the ItemProcessor to connect the API.

答: There is no CORBA based ItemWriter (or ItemReader for that matter) so you'll need to write your own.  With regards to contributing it to the core framework, you can follow the guidelines for creating a contribution here: https://github.com/spring-projects/spring-batch/blob/master/CONTRIBUTING.md

Title: Spring batch mechanism for CORBA


问:
What does {0} mean when found in a key-value pair in C# config file?
I have run into the use of {0} in the App.config of a project I'm working on and I can't find anything on how it works. The only other question on it I found is the this question which explains how composite formatting works but nothing about its use in the .config file</p>

```<code><?xml version="1.0" encoding="utf-8"?>
  <configuration>
    <appSettings>
      <add key="UriUpdateProfile" value="{0}/profiles/{1}" />
      ...
    </appSettings>
  </configuration>
</code>```

答:
For hard-coded strings that depend on user data, these sorts of configurations play very well with format strings.  Your example configuration would be read and updated with

```<code>String.Format(uriUpdateProfile, variable0, variable1);
</code>```

String.Format takes a large number of variables and repacles {0} and {1} with the passed in arguments.  There are other ways to replicate this, and even simple replacements such as String.Replace("{0}", userID); could suffice.

Body:
I have run into the use of {0} in the App.config of a project I'm working on and I can't find anything on how it works. The only other question on it I found is the this question which explains how composite formatting works but nothing about its use in the .config file

<?xml version="1.0" encoding="utf-8"?>
  <configuration>
    <appSettings>
      <add key="UriUpdateProfile" value="{0}/profiles/{1}" />
      ...
    </appSettings>
  </configuration>

Body:
For hard-coded strings that depend on user data, these sorts of configurations play very well with format strings.  Your example configuration would be read and updated with

String.Format(uriUpdateProfile, variable0, variable1);

String.Format takes a large number of variables and repacles {0} and {1} with the passed in arguments.  There are other ways to replicate this, and even simple replacements such as String.Replace("{0}", userID); could suffice.


问:
Get python script to run on boot up in mac
How would I get a python script to run everytime the computer boots?</p>

答:
How to run a shell script on startup (OSX)

And in that script just call your program

```<code>python path/to/yourScript.py
</code>```

EDIT: Since 2010 the above link has gone sour. But also since 2010 have some answers popped up the describe similar methods, eg.

Running script upon login mac

How to get shell scripts to run on startup - Yosemite

Body:
How to run a shell script on startup (OSX)

And in that script just call your program

python path/to/yourScript.py

EDIT: Since 2010 the above link has gone sour. But also since 2010 have some answers popped up the describe similar methods, eg.

Running script upon login mac

How to get shell scripts to run on startup - Yosemite


问:
How to use multiple data types within the same ADT in C?
For example, if I defined a Stack ADT in C, normally my type definition -using an array based implementation- is like this:

```<code>typedef char StackEntry;

typedef struct stack {
    int top;
    StackEntry entry[MAXSTACK];
} Stack;
</code>```

How can I make my Stack such that I can have one Stack for characters and another Stack -in the same program- that handles integers for example ?

答:
You could use a stack-structure that is initialized with the size of the elements and that reserves a memory block in terms of bytes to store the elements:</p>

```<code>typedef struct stack {
    int top;
    size_t size;
    size_t maxElems;
    char content[];
} Stack;

Stack *createStack(size_t size, size_t maxElems) {
    Stack *result = malloc(sizeof(Stack)+size*maxElems);
    result->top=0;
    result->size=size;
    result->maxElems=maxElems;
    return result;
}

int push(Stack *stack, void *elem) {
    if (stack->top == stack->maxElems)
        return -1;

    memcpy(stack->content + stack->top * stack->size, elem, stack->size);
    stack->top++;
    return stack->top;
}

int pop(Stack *stack, void *elem) {
    if (stack->top == 0)
        return -1;

    stack->top--;
    memcpy(elem, stack->content + stack->top * stack->size, stack->size);
    return stack->top;
}

int main() {

    Stack *charStack = createStack(sizeof(char), 10);
    for (int i=0; i<10; i++) {
        char c = 'A'+i;
        push(charStack, &c);
    }
    char c;
    while (pop(charStack, &c) >= 0) {
        printf("%c\n", c);
    }
    free(charStack);

    Stack *intStack = createStack(sizeof(int), 10);
    for (int i=0; i<10; i++) {
        push(intStack, &i);
    }
    int i;
    while (pop(intStack, &i) >= 0) {
        printf("%d\n", i);
    }
    free(intStack);
}
</code>```

Body:
For example, if I defined a Stack ADT in C, normally my type definition -using an array based implementation- is like this:

typedef char StackEntry;

typedef struct stack {
    int top;
    StackEntry entry[MAXSTACK];
} Stack;

How can I make my Stack such that I can have one Stack for characters and another Stack -in the same program- that handles integers for example ?

Body:
You could use a stack-structure that is initialized with the size of the elements and that reserves a memory block in terms of bytes to store the elements:

typedef struct stack {
    int top;
    size_t size;
    size_t maxElems;
    char content[];
} Stack;

Stack *createStack(size_t size, size_t maxElems) {
    Stack *result = malloc(sizeof(Stack)+size*maxElems);
    result->top=0;
    result->size=size;
    result->maxElems=maxElems;
    return result;
}

int push(Stack *stack, void *elem) {
    if (stack->top == stack->maxElems)
        return -1;

    memcpy(stack->content + stack->top * stack->size, elem, stack->size);
    stack->top++;
    return stack->top;
}

int pop(Stack *stack, void *elem) {
    if (stack->top == 0)
        return -1;

    stack->top--;
    memcpy(elem, stack->content + stack->top * stack->size, stack->size);
    return stack->top;
}

int main() {

    Stack *charStack = createStack(sizeof(char), 10);
    for (int i=0; i<10; i++) {
        char c = 'A'+i;
        push(charStack, &c);
    }
    char c;
    while (pop(charStack, &c) >= 0) {
        printf("%c\n", c);
    }
    free(charStack);

    Stack *intStack = createStack(sizeof(int), 10);
    for (int i=0; i<10; i++) {
        push(intStack, &i);
    }
    int i;
    while (pop(intStack, &i) >= 0) {
        printf("%d\n", i);
    }
    free(intStack);
}


问:
Translating decryption function from Python to C#
I am translating a decryption function that I have found on the internet. The function is written in Python, and I am translating it to C#. I have a fair amount of it done (hopefully correctly), but some of the syntax I'm having a hard time reading.

Here's the original function:

```<code>def decrypt_signature(s):
arr = list(s)
   arr[0], arr[52] = arr[52%len(arr)], arr[0]
   arr.reverse()
   arr = arr[3:]
   arr[0], arr[21] = arr[21%len(arr)], arr[0]
   arr.reverse()
   arr = arr[3:]
   arr.reverse()

   return "".join(arr)
</code>```

And here's what I have translated so far:

```<code>private string DecryptSig(string s)
        {
            //arr = list(s)
            char[] arr = s.ToArray();

            //arr[0], arr[52] = arr[52%len(arr)], arr[0]
            var temp = arr[0];
            arr[0] = arr[52 % arr.Length];
            arr[52 % arr.Length] = temp;

            //arr.reverse()
            arr.Reverse();

            //arr = arr[3:]
            //?????????????????

            //arr[0], arr[21] = arr[21 % len(arr)], arr[0]
            temp = arr[0];
            arr[0] = arr[21 % arr.Length];
            arr[21 % arr.Length] = temp;

            //arr.reverse()
            arr.Reverse();

            //arr = arr[3:]
            //??????????????????

            //arr.reverse()
            arr.Reverse();

            //return "".join(arr)
            return "" + new string(arr);
        }
</code>```

What does the author do when they write arr = arr[3:]? To me it appears like it's just taking the first three values of the array and writing them back to their original indices.

答:
He's taking all of the items, except for the first 3. You can use the C# LINQ equivalent, Skip:

```<code>arr = arr.Skip(3).ToArray();
</code>```

Body:
I am translating a decryption function that I have found on the internet. The function is written in Python, and I am translating it to C#. I have a fair amount of it done (hopefully correctly), but some of the syntax I'm having a hard time reading.

Here's the original function:

def decrypt_signature(s):
arr = list(s)
   arr[0], arr[52] = arr[52%len(arr)], arr[0]
   arr.reverse()
   arr = arr[3:]
   arr[0], arr[21] = arr[21%len(arr)], arr[0]
   arr.reverse()
   arr = arr[3:]
   arr.reverse()

   return "".join(arr)

And here's what I have translated so far:

private string DecryptSig(string s)
        {
            //arr = list(s)
            char[] arr = s.ToArray();

            //arr[0], arr[52] = arr[52%len(arr)], arr[0]
            var temp = arr[0];
            arr[0] = arr[52 % arr.Length];
            arr[52 % arr.Length] = temp;

            //arr.reverse()
            arr.Reverse();

            //arr = arr[3:]
            //?????????????????

            //arr[0], arr[21] = arr[21 % len(arr)], arr[0]
            temp = arr[0];
            arr[0] = arr[21 % arr.Length];
            arr[21 % arr.Length] = temp;

            //arr.reverse()
            arr.Reverse();

            //arr = arr[3:]
            //??????????????????

            //arr.reverse()
            arr.Reverse();

            //return "".join(arr)
            return "" + new string(arr);
        }

What does the author do when they write arr = arr[3:]? To me it appears like it's just taking the first three values of the array and writing them back to their original indices.

Body:
He's taking all of the items, except for the first 3. You can use the C# LINQ equivalent, Skip:

arr = arr.Skip(3).ToArray();


问:
Can't translate custom GA segment to Bigquery
I am currently trying to write the following custom segment from GA in Bigquery:

GA Segment

I wrote the following code but it is generating different numbers than GA:

```<code>SELECT date,
sum(new_visits) as new_visits
FROM
(SELECT date,
first_session_login,
first_session_email,
landing_page_customer,
first_session_cms_referral,
new_visits
FROM
(SELECT
date,
case when visitNumber = 1 and hits.page.pagePath like '/login%' then 1 else 0 end as first_session_login,
case when visitNumber = 1 and trafficSource.medium = 'email' then 1 else 0 end as first_session_email,
case when visitNumber = 1 and hits.isEntrance is true and REGEXP_MATCH(hits.page.pagePath, r'/support/.*|/app/.*|/billing/.*|/goal/.*|/login/.*|/signup-flow/.*') is true then 1 else 0 end as landing_page_customer,
case when visitNumber = 1 and trafficSource.medium = 'cms referral' then 1 else 0 end as first_session_cms_referral,
totals.newVisits as new_visits
FROM
(SELECT
  date, visitNumber, hits.page.pagePath, trafficSource.medium, hits.isEntrance, hits.type, hits.hitNumber, geoNetwork.country, totals.newVisits
FROM (TABLE_DATE_RANGE([81532559.ga_sessions_], DATE_ADD(CURRENT_TIMESTAMP(), -2, 'DAY'), DATE_ADD(CURRENT_TIMESTAMP(), -1, 'DAY'))))
)
WHERE
first_session_login = 0
AND
first_session_email = 0
AND
landing_page_customer = 0
AND
first_session_cms_referral = 0)
GROUP BY date
</code>```

What is wrong in my code? Any help is highly appreciated.

答:
If you can use the Standard Version, this might work for you:

```<code>SELECT
  date,
  COUNT(1) new_visits
FROM `dataset_id.ga_sessions*`
WHERE 1 = 1
  AND CASE WHEN (REGEXP_CONTAINS(_table_suffix, 'intraday') AND REGEXP_EXTRACT(_table_suffix, r'.*_(.*)') BETWEEN FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))AND FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))) THEN TRUE
           WHEN (NOT REGEXP_CONTAINS(_table_suffix, 'intraday') AND REGEXP_EXTRACT(_table_suffix, r'.*_(.*)') BETWEEN FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 2 DAY))AND FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))) THEN TRUE END
  AND totals.visits = 1
  AND totals.newVisits = 1
  AND NOT trafficSource.medium IN ('email', 'cms referral')
  AND NOT EXISTS(select 1 from UNNEST(hits) where REGEXP_CONTAINS(page.pagePath, r'$/login') OR (isEntrance and REGEXP_CONTAINS(page.pagePath, r'/support/.*|/app/.*|/billing/.*|/goal/.*|/login/.*|/signup-flow/.*')))
GROUP BY
  date
</code>```

As Elliott pointed out, working with Legacy is a bit harder as it already flattens all arrays automatically. In Standard SQL, running this type of analyzes is quite straightforward.

Body:
I am currently trying to write the following custom segment from GA in Bigquery:

GA Segment

I wrote the following code but it is generating different numbers than GA:

SELECT date,
sum(new_visits) as new_visits
FROM
(SELECT date,
first_session_login,
first_session_email,
landing_page_customer,
first_session_cms_referral,
new_visits
FROM
(SELECT
date,
case when visitNumber = 1 and hits.page.pagePath like '/login%' then 1 else 0 end as first_session_login,
case when visitNumber = 1 and trafficSource.medium = 'email' then 1 else 0 end as first_session_email,
case when visitNumber = 1 and hits.isEntrance is true and REGEXP_MATCH(hits.page.pagePath, r'/support/.*|/app/.*|/billing/.*|/goal/.*|/login/.*|/signup-flow/.*') is true then 1 else 0 end as landing_page_customer,
case when visitNumber = 1 and trafficSource.medium = 'cms referral' then 1 else 0 end as first_session_cms_referral,
totals.newVisits as new_visits
FROM
(SELECT
  date, visitNumber, hits.page.pagePath, trafficSource.medium, hits.isEntrance, hits.type, hits.hitNumber, geoNetwork.country, totals.newVisits
FROM (TABLE_DATE_RANGE([81532559.ga_sessions_], DATE_ADD(CURRENT_TIMESTAMP(), -2, 'DAY'), DATE_ADD(CURRENT_TIMESTAMP(), -1, 'DAY'))))
)
WHERE
first_session_login = 0
AND
first_session_email = 0
AND
landing_page_customer = 0
AND
first_session_cms_referral = 0)
GROUP BY date

What is wrong in my code? Any help is highly appreciated.

Body:
If you can use the Standard Version, this might work for you:

SELECT
  date,
  COUNT(1) new_visits
FROM `dataset_id.ga_sessions*`
WHERE 1 = 1
  AND CASE WHEN (REGEXP_CONTAINS(_table_suffix, 'intraday') AND REGEXP_EXTRACT(_table_suffix, r'.*_(.*)') BETWEEN FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))AND FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))) THEN TRUE
           WHEN (NOT REGEXP_CONTAINS(_table_suffix, 'intraday') AND REGEXP_EXTRACT(_table_suffix, r'.*_(.*)') BETWEEN FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 2 DAY))AND FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))) THEN TRUE END
  AND totals.visits = 1
  AND totals.newVisits = 1
  AND NOT trafficSource.medium IN ('email', 'cms referral')
  AND NOT EXISTS(select 1 from UNNEST(hits) where REGEXP_CONTAINS(page.pagePath, r'$/login') OR (isEntrance and REGEXP_CONTAINS(page.pagePath, r'/support/.*|/app/.*|/billing/.*|/goal/.*|/login/.*|/signup-flow/.*')))
GROUP BY
  date

As Elliott pointed out, working with Legacy is a bit harder as it already flattens all arrays automatically. In Standard SQL, running this type of analyzes is quite straightforward.


问:
Alternate blinking with CSS3 animation
I am trying to find a CSS-only way to make specific tags (like p or img) blink in alternating patterns. While I have been able to find a means to make anything blink (see .blinky) in code sample, I have not been able to make two separate classes alternate the blinking.

Part of the solution might be the animation-delay property shown in .blinky2, but after the specified delay in seconds, it blinks in sync with .blinky and not offset by the delay.

I found some related SO links that got me started -- Imitating a blink tag with CSS3 animations and CSS Tricks -- but I have not yet seen any instructions to define offset blinking for .blink2. Is such a thing supported, or does it require further tricks?

.blinky {
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;
  font-size: x-large;
  color: blue;
  display: inline;
}

.blinky2 {
  /* Need make this alternate blinking*/
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;
  /* This just postpones blinking for 1-sec, then it's in sync with .blinky*/
  animation-delay: 1s;
  -webkit-animation-delay: 1s;
  font-size: x-large;
  color: red;
  display: inline;
}

@keyframes blink-animation {
  to {
    visibility: hidden;
  }
}

@-webkit-keyframes blink-animation {
  to {
    visibility: hidden;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>The <var>blinky</var> and <var>blinky2</var> classes should alternate blinking.</p>

<div>
  <p class="blinky">Blinky</p>
  <p class="blinky2">Blinky 2</p>
  <p class="blinky">Blinky</p>
  <p class="blinky2">Blinky 2</p>
  <p class="blinky">Blinky</p>
</div></code>```

答:
I think you could use keyframes to get the effect you're after.

What I've done below is define two different animations, blink-animation and alt-blink-animation. blink-animation gets applied to p tags, and alt-blink-animation gets applied to div tags.

blink-animation starts with the element hidden, and alt-blink-animation starts with the element visible. Simply alternating the keyframes so blink-animation is visible while alt-blink-animation is hidden and vice versa produces an alternating blinking effect.

```<code><p>First blink</p>

<div>Alt Blinking</div>

<style>
  p{
    animation: blink-animation 1s infinite;
  }

  div{
    animation: alt-blink-animation 1s infinite;
  }

  @keyframes blink-animation {
    0% { opacity: 0;}
    100% { opacity: 1;}
  }

  @keyframes alt-blink-animation {
    0% { opacity: 1;}
    100% { opacity: 0;}
  }

</style>
</code>```

Title: Alternate blinking with CSS3 animation

Body:
I am trying to find a CSS-only way to make specific tags (like p or img) blink in alternating patterns. While I have been able to find a means to make anything blink (see .blinky) in code sample, I have not been able to make two separate classes alternate the blinking.

Part of the solution might be the animation-delay property shown in .blinky2, but after the specified delay in seconds, it blinks in sync with .blinky and not offset by the delay.

I found some related SO links that got me started -- Imitating a blink tag with CSS3 animations and CSS Tricks -- but I have not yet seen any instructions to define offset blinking for .blink2. Is such a thing supported, or does it require further tricks?

.blinky {
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;
  font-size: x-large;
  color: blue;
  display: inline;
}

.blinky2 {
  /* Need make this alternate blinking*/
  animation: blink-animation 1s steps(5, start) infinite;
  -webkit-animation: blink-animation 1s steps(5, start) infinite;
  /* This just postpones blinking for 1-sec, then it's in sync with .blinky*/
  animation-delay: 1s;
  -webkit-animation-delay: 1s;
  font-size: x-large;
  color: red;
  display: inline;
}

@keyframes blink-animation {
  to {
    visibility: hidden;
  }
}

@-webkit-keyframes blink-animation {
  to {
    visibility: hidden;
  }
}

The <var>blinky</var> and <var>blinky2</var> classes should alternate blinking.

Blinky

Blinky 2

Blinky

Blinky 2

Blinky

Body:
I think you could use keyframes to get the effect you're after.

What I've done below is define two different animations, blink-animation and alt-blink-animation. blink-animation gets applied to p tags, and alt-blink-animation gets applied to div tags.

blink-animation starts with the element hidden, and alt-blink-animation starts with the element visible. Simply alternating the keyframes so blink-animation is visible while alt-blink-animation is hidden and vice versa produces an alternating blinking effect.

<p>First blink</p>

<div>Alt Blinking</div>

<style>
  p{
    animation: blink-animation 1s infinite;
  }

  div{
    animation: alt-blink-animation 1s infinite;
  }

  @keyframes blink-animation {
    0% { opacity: 0;}
    100% { opacity: 1;}
  }

  @keyframes alt-blink-animation {
    0% { opacity: 1;}
    100% { opacity: 0;}
  }

</style>


问:
Using xrange to Reduce Memory Usage, For Loop
I've got a line of code that is producing a pretty huge memory drain.

Here is the line:

```<code>X_train = (np.array(a).reshape(1000,100) for a in X_train)
</code>```

Simply put, I'm reshaping each row of my dataset. The problem is, this creates a memory error that crashes my kernel, both locally and on AWS.

How can I rewrite that line using the xrange function, to reduce memory usage?

(Or any other way that would reduce memory usage)

Thanks!!!

答:
As mentioned by @ali_m, that line by itself is a generator expression. This means that none of the elements of X_train are evaluated until the elements of that generator expression are evaluated. You must be evaluating all of the elements of X_train and storing them in memory somewhere later in your code, possibly by doing list(X_train), appending every element of X_train to a list, or something similar. This will create a list which is equal in length to your original X_train before the generator expression, hence causing a memory error if it is too big.

The original X_traincannot be garbage collected while the generator expression is still being evaluated, so by creating a list of the new X_train, you are creating two huge lists, which is probably why it runs out of memory.

In this case, you can't use xrange to make your code more efficient, because it is already a generator expression. The best thing to do would be to look at how X_train is used later in your code and try to iterate over it (for _ in X_train) as opposed to making it into a list (list(X_train)) wherever possible.

Body:
I've got a line of code that is producing a pretty huge memory drain.

Here is the line:

X_train = (np.array(a).reshape(1000,100) for a in X_train)

Simply put, I'm reshaping each row of my dataset. The problem is, this creates a memory error that crashes my kernel, both locally and on AWS.

How can I rewrite that line using the xrange function, to reduce memory usage?

(Or any other way that would reduce memory usage)

Thanks!!!


问:
using evosuite from command line
When I try to use the EvoSuite testing tool from the command line, I get the following error:

```<code>Fatal crash on main EvoSuite process. Class using seed 1428172877144. Configuration id : null
java.lang.RunTimeExceptionConfiguration:Did not manage to automatically find tools.jar. Use –Dtools_jar_location = <path> properly
    at org.evosuite.runtime.agent.ToolsJarLocator.getLoaderForToolsJar<ToolsJarLocator.java:71> ~[evosuite-0.1.1.jar:na]
    at org.evosuite.Evosuite.parseCommandLine<Evosuite.java:152> ~[evosuite-0.1.1.jar:na]
    at org.evosuite.Evosuite.main<Evosuite.java:304> ~[evosuite-0.1.1.jar:na]
</code>```

Could someone help me with this?

答: Make sure you use your JDK to run Evosuite, not the JRE. That may mean either going into the JDK /bin dir and running from there or fully quantifying the executable java binary file when you run (JDK..../bin/java.exe on windows for example).</p>

Title: using evosuite from command line

Body:
When I try to use the EvoSuite testing tool from the command line, I get the following error:

Fatal crash on main EvoSuite process. Class using seed 1428172877144. Configuration id : null
java.lang.RunTimeExceptionConfiguration:Did not manage to automatically find tools.jar. Use –Dtools_jar_location = <path> properly
    at org.evosuite.runtime.agent.ToolsJarLocator.getLoaderForToolsJar<ToolsJarLocator.java:71> ~[evosuite-0.1.1.jar:na]
    at org.evosuite.Evosuite.parseCommandLine<Evosuite.java:152> ~[evosuite-0.1.1.jar:na]
    at org.evosuite.Evosuite.main<Evosuite.java:304> ~[evosuite-0.1.1.jar:na]

Could someone help me with this?


问:
Output by number in a for loop
What is the right syntax of this? I want to output not every result, but I want to output by number. For example from 1 to 20 of results etc. Or only 1st,3rd and 5th numbers of results. Can I make an array of the results?</p>

```<code>for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

// I want to output something like the following in the for loop:
  echo $target_path[0],
  echo $target_path[5],
  echo $target_path[3],
}
</code>```

答:
For first 20:

```<code>for($i = 0; $i < count($_FILES['file']['name']) && $i < 20; $i++) {
    // ...
}
</code>```

For first, third, fifth, etc. elements:

```<code>for($i = 0; $i < count($_FILES['file']['name']); $i += 2) {
    // ...
}
</code>```

Or generally for any condition:

```<code>for($i = 0; $i < count($_FILES['file']['name']); $i++) {
    if(/* condition */) {
        // ...
    }
}
</code>```

Or this form prevents unnecessary indentation:

```<code>for($i = 0; $i < count($_FILES['file']['name']); $i++) {
    if(/* !condition */) {
        continue;
    }
    // ...
}
</code>```

Title: Output by number in a for loop

Body:
What is the right syntax of this? I want to output not every result, but I want to output by number. For example from 1 to 20 of results etc. Or only 1st,3rd and 5th numbers of results. Can I make an array of the results?

for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
  $ext = explode('.', basename($_FILES['file']['name'][$i]))
  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];

// I want to output something like the following in the for loop:
  echo $target_path[0],
  echo $target_path[5],
  echo $target_path[3],
}

Body:
For first 20:

for($i = 0; $i < count($_FILES['file']['name']) && $i < 20; $i++) {
    // ...
}

For first, third, fifth, etc. elements:

for($i = 0; $i < count($_FILES['file']['name']); $i += 2) {
    // ...
}

Or generally for any condition:

for($i = 0; $i < count($_FILES['file']['name']); $i++) {
    if(/* condition */) {
        // ...
    }
}

Or this form prevents unnecessary indentation:

for($i = 0; $i < count($_FILES['file']['name']); $i++) {
    if(/* !condition */) {
        continue;
    }
    // ...
}