问:
Get list as array from Firebase with angularfire2(v5) and ngrx effects
I have to tell you I'm getting crazy with it. I'm trying to get data from Firebase with AngularFire2(v.5) then work with it on @ngrx/effects and store it on @ngrx/store. Well, as I need the data with the keys, my code of effects looks like this:

spaces.effects.ts

```<code>@Effect()
  getSpaces$ = this.actions$.ofType(SpacesActions.GET_SPACES_REQUEST)
  .switchMap((action: SpacesActions.GetSpacesRequest) => {
    return this.afs.list<Space>('/spaces').snapshotChanges()
      .switchMap(actions => {
      console.log('action is ', actions);
      return actions.map(space => {
      const $key = space.payload.key;
      const data: Space = { $key, ...space.payload.val() };
      console.log('snapshot is: ', data);
      return new SpacesActions.GetSpacesSuccess(data);
      });
    }
  );
</code>```

My "actions" comes with the data and the key, then I get the key for each item because then I could update and delete items easily. My database has 3 items with 3 keys. If I run this code and log it, first I can see all items in 1 array with their payloads and with the second log I see each payload as snapshot.

When I call GetSpacesSuccess, I'd like to send all snapshots I got (with key and item) then store it. The way I'm doing now dispatch this action 3 times and I can see only 2 items on the screen because the first one is overridden by the second one.

So, two questions: Is there any easier way to get the items from firebase with their keys then store them with @ngrx? If not, what am I doing wrong that my first item is being overridden and my action is being dispatched 3 times?

Please, I'm doing my best with it as I'm learning. Thank you!

spaces.reducers.ts

```<code>    case SpacesActions.GET_SPACES_REQUEST:
    return {
      state,
      spaces: null,
      loading: true
  };
    case SpacesActions.GET_SPACES_SUCCESS:
    return {
      ...state,
      ...action.payload,
      spaces: [state, action.payload],
      loading: false
    };
</code>```

spaces.actions.ts

```<code>export class GetSpacesRequest implements Action {
  readonly type = GET_SPACES_REQUEST;

}

export class GetSpacesSuccess implements Action {
  readonly type = GET_SPACES_SUCCESS;

  constructor(public payload: Space) {} <<<<<HERE I'D LIKE TO GET THE FULL ARRAY WITH EACH KEY
}
</code>```

答:
Thanks @AndreaM16 for the most complete answer. I went through the night working on it and I ended up doing it different. Actually, in the learning process we make mistakes in order to get the knowledge. Probably your solution is better than mine and I'll study that, thanks. Please, if possible, I'd love to hear your comments about my solution.

Finally, after reading lots of documentation, my effects is now this one, I don't have any error catcher though:

```<code>private spacesList = 'spaces/';
@Effect()
  getSpaces$ = this.actions$.ofType(SpacesActions.GET_SPACES_REQUEST)
  .switchMap(payload => this.afs.list(this.spacesList).snapshotChanges()
    .map(spaces => {
      return spaces.map(
          res => {
            const $key = res.payload.key;
            const space: Space = {$key, ...res.payload.val()};
            return space;
          }
    );
    })
    .map(res =>
      new SpacesActions.GetSpacesSuccess(res)
    ));
</code>```

Reducer

```<code>    case SpacesActions.GET_SPACES_REQUEST:
    return Object.assign({}, state, {
      spaces: null,
      loading: true
  });
    case SpacesActions.GET_SPACES_SUCCESS:
    return Object.assign({}, state, {
      spaces: action.payload,
      loading: false
  });
</code>```

Actions

```<code>export class GetSpacesRequest implements Action {
  readonly type = GET_SPACES_REQUEST;

}

export class GetSpacesSuccess implements Action {
  readonly type = GET_SPACES_SUCCESS;

  constructor(public payload: Space[]) {}
}
</code>```

And, in my component, where I need the list:

```<code> constructor(private store: Store<fromSpaces.FeatureState>) {}
ngOnInit() {
    this.store.dispatch(new SpacesActions.GetSpacesRequest());
    this.spacesState = this.store.select('spaces');
}
</code>```

Body:
I have to tell you I'm getting crazy with it. I'm trying to get data from Firebase with AngularFire2(v.5) then work with it on @ngrx/effects and store it on @ngrx/store. Well, as I need the data with the keys, my code of effects looks like this:

spaces.effects.ts

@Effect()
  getSpaces$ = this.actions$.ofType(SpacesActions.GET_SPACES_REQUEST)
  .switchMap((action: SpacesActions.GetSpacesRequest) => {
    return this.afs.list<Space>('/spaces').snapshotChanges()
      .switchMap(actions => {
      console.log('action is ', actions);
      return actions.map(space => {
      const $key = space.payload.key;
      const data: Space = { $key, ...space.payload.val() };
      console.log('snapshot is: ', data);
      return new SpacesActions.GetSpacesSuccess(data);
      });
    }
  );

My "actions" comes with the data and the key, then I get the key for each item because then I could update and delete items easily. My database has 3 items with 3 keys. If I run this code and log it, first I can see all items in 1 array with their payloads and with the second log I see each payload as snapshot.

When I call GetSpacesSuccess, I'd like to send all snapshots I got (with key and item) then store it. The way I'm doing now dispatch this action 3 times and I can see only 2 items on the screen because the first one is overridden by the second one.

So, two questions: Is there any easier way to get the items from firebase with their keys then store them with @ngrx? If not, what am I doing wrong that my first item is being overridden and my action is being dispatched 3 times?

Please, I'm doing my best with it as I'm learning. Thank you!

spaces.reducers.ts

    case SpacesActions.GET_SPACES_REQUEST:
    return {
      state,
      spaces: null,
      loading: true
  };
    case SpacesActions.GET_SPACES_SUCCESS:
    return {
      ...state,
      ...action.payload,
      spaces: [state, action.payload],
      loading: false
    };

spaces.actions.ts

export class GetSpacesRequest implements Action {
  readonly type = GET_SPACES_REQUEST;

}

export class GetSpacesSuccess implements Action {
  readonly type = GET_SPACES_SUCCESS;

  constructor(public payload: Space) {} <<<<<HERE I'D LIKE TO GET THE FULL ARRAY WITH EACH KEY
}

Body:
Thanks @AndreaM16 for the most complete answer. I went through the night working on it and I ended up doing it different. Actually, in the learning process we make mistakes in order to get the knowledge. Probably your solution is better than mine and I'll study that, thanks. Please, if possible, I'd love to hear your comments about my solution.

Finally, after reading lots of documentation, my effects is now this one, I don't have any error catcher though:

private spacesList = 'spaces/';
@Effect()
  getSpaces$ = this.actions$.ofType(SpacesActions.GET_SPACES_REQUEST)
  .switchMap(payload => this.afs.list(this.spacesList).snapshotChanges()
    .map(spaces => {
      return spaces.map(
          res => {
            const $key = res.payload.key;
            const space: Space = {$key, ...res.payload.val()};
            return space;
          }
    );
    })
    .map(res =>
      new SpacesActions.GetSpacesSuccess(res)
    ));

Reducer

    case SpacesActions.GET_SPACES_REQUEST:
    return Object.assign({}, state, {
      spaces: null,
      loading: true
  });
    case SpacesActions.GET_SPACES_SUCCESS:
    return Object.assign({}, state, {
      spaces: action.payload,
      loading: false
  });

Actions

export class GetSpacesRequest implements Action {
  readonly type = GET_SPACES_REQUEST;

}

export class GetSpacesSuccess implements Action {
  readonly type = GET_SPACES_SUCCESS;

  constructor(public payload: Space[]) {}
}

And, in my component, where I need the list:

 constructor(private store: Store<fromSpaces.FeatureState>) {}
ngOnInit() {
    this.store.dispatch(new SpacesActions.GetSpacesRequest());
    this.spacesState = this.store.select('spaces');
}


来源: stackexchange

问:
ValueError: invalid literal for int() with base 10: ' ' [Django]
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database.
But while migrating the app I'm getting this error:

```<code>ValueError: invalid literal for int() with base 10: ''
</code>```

What should I change in code to resolve this error?
Here's the traceback:

```<code>Traceback (most recent call last):

File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards
    field,
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 415, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 155, in column_sql
    default_value = self.effective_default(field)
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 229, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save
    prepared=False)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 762, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1853, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''
</code>```

How to fix this problem?

Here's my code for models.py:

```<code>from django.db import models
from django.contrib.postgres.fields import JSONField

class Projects(models.Model):
        data = JSONField(null=False)
        project_id=models.CharField(max_length=100)
        project_name=models.CharField(max_length=100)
        status=models.CharField(max_length=10)
        country=models.CharField(max_length=100)
        locations=JSONField()
        mjtheme=models.CharField(max_length=50)
        project_docs=JSONField()
        source=models.CharField(max_length=10)
        mjtheme_namecode=models.CharField(max_length=10)
        docty=models.TextField()
        countryname=models.CharField(max_length=100)
        countrycode=models.CharField(max_length=10)
        themecode=models.IntegerField()
        theme_namecode=models.IntegerField()
        project_url=models.TextField()
        totalcommamt=models.IntegerField()
        mjthemecode=models.IntegerField()
        sector1=models.CharField(max_length=10)
        theme1=models.CharField(max_length=10)
        theme2=models.CharField(max_length=10)
        theme3=models.CharField(max_length=10)
        projectinfo=models.TextField()
        country_namecode=models.CharField(max_length=5)
        p2a_updated_date=models.IntegerField()
        p2a_flag=models.CharField(max_length=5)
        project_abstract=JSONField()
</code>```

And here's the code for fetch.py file which is stored under /management/commands/fetch.py:

```<code>import requests
from django.core.management.base import BaseCommand
from worldBank.worldBankApp.models import Projects

class Command(BaseCommand):
    def handle(self, **options):
        response = requests.get("https://search.worldbank.org/api/v2/projects?format=json&countryshortname_exact=India&source=IBRD&kw=N&rows=7")
        data = response.json()
        projects = data['projects']

        #print(data)

        for project in projects:
            print(projects[project])
            print("\n\n")

            data = projects[project]

            Projects.objects.create(

                project_id = data['id'],
                project_name = data['project_name'],
                status = data['status'],
                country = data['countryshortname'],
                locations = data['locations'],
                mjtheme = data['mjtheme'],
                project_docs = data['projectdocs'],
                source = data['source'],
                mjtheme_namecode = data['mjtheme_namecode'],
                docty = data['docty'],
                countryname = data['countryname'],
                countrycode = data['countrycode'],
                themecode = data['themecode'],
                theme_namecode = data['theme_namecode'],
                project_url = data['url'],
                totalcommamt = data['totalcommamt'],
                mjthemecode = data['mjthemecode'],
                sector1 = data['sector1'],
                theme1 = data['theme1'],
                theme2 = data['theme2'],
                theme3 = data['theme3'],
                projectinfo = data['projectinfo'],
                country_namecode = ['country_namecode'],
                p2a_updated_date = data['p2a_updated_date'],
                p2a_flag = data['p2a_flag'],
                project_abstract = data['project_abstract']

                )
</code>```

答:
Navyad is largely correct, you are trying to assign strings to integer fields (themecode is a good example).

Looking through the JSON, I'm seeing things like "themecode": "79,77,66". This simply cannot be inserted into an integer field. You need to change those to models.CharField or somehow pre-process the data (extract the first number, for example).

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database.
But while migrating the app I'm getting this error:

ValueError: invalid literal for int() with base 10: ''

What should I change in code to resolve this error?
Here's the traceback:

Traceback (most recent call last):

File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards
    field,
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 415, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 155, in column_sql
    default_value = self.effective_default(field)
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 229, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save
    prepared=False)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 762, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1853, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''

How to fix this problem?

Here's my code for models.py:

from django.db import models
from django.contrib.postgres.fields import JSONField

class Projects(models.Model):
        data = JSONField(null=False)
        project_id=models.CharField(max_length=100)
        project_name=models.CharField(max_length=100)
        status=models.CharField(max_length=10)
        country=models.CharField(max_length=100)
        locations=JSONField()
        mjtheme=models.CharField(max_length=50)
        project_docs=JSONField()
        source=models.CharField(max_length=10)
        mjtheme_namecode=models.CharField(max_length=10)
        docty=models.TextField()
        countryname=models.CharField(max_length=100)
        countrycode=models.CharField(max_length=10)
        themecode=models.IntegerField()
        theme_namecode=models.IntegerField()
        project_url=models.TextField()
        totalcommamt=models.IntegerField()
        mjthemecode=models.IntegerField()
        sector1=models.CharField(max_length=10)
        theme1=models.CharField(max_length=10)
        theme2=models.CharField(max_length=10)
        theme3=models.CharField(max_length=10)
        projectinfo=models.TextField()
        country_namecode=models.CharField(max_length=5)
        p2a_updated_date=models.IntegerField()
        p2a_flag=models.CharField(max_length=5)
        project_abstract=JSONField()

And here's the code for fetch.py file which is stored under /management/commands/fetch.py:

import requests
from django.core.management.base import BaseCommand
from worldBank.worldBankApp.models import Projects

class Command(BaseCommand):
    def handle(self, **options):
        response = requests.get("https://search.worldbank.org/api/v2/projects?format=json&countryshortname_exact=India&source=IBRD&kw=N&rows=7")
        data = response.json()
        projects = data['projects']

        #print(data)

        for project in projects:
            print(projects[project])
            print("\n\n")

            data = projects[project]

            Projects.objects.create(

                project_id = data['id'],
                project_name = data['project_name'],
                status = data['status'],
                country = data['countryshortname'],
                locations = data['locations'],
                mjtheme = data['mjtheme'],
                project_docs = data['projectdocs'],
                source = data['source'],
                mjtheme_namecode = data['mjtheme_namecode'],
                docty = data['docty'],
                countryname = data['countryname'],
                countrycode = data['countrycode'],
                themecode = data['themecode'],
                theme_namecode = data['theme_namecode'],
                project_url = data['url'],
                totalcommamt = data['totalcommamt'],
                mjthemecode = data['mjthemecode'],
                sector1 = data['sector1'],
                theme1 = data['theme1'],
                theme2 = data['theme2'],
                theme3 = data['theme3'],
                projectinfo = data['projectinfo'],
                country_namecode = ['country_namecode'],
                p2a_updated_date = data['p2a_updated_date'],
                p2a_flag = data['p2a_flag'],
                project_abstract = data['project_abstract']

                )


问:
Chromecast v3: Mini Controller showing progressbar instead of Play/Pause button
I am using below way to integrate mini_controller in my chromecast app. However, I always seeing progressbar instead of pause/play button in mini controller.

```<code><fragment
        android:id="@+id/cast_mini_controller"
        class="com.google.android.gms.cast.framework.media.widget.MiniControllerFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"
        app:castControlButtons="@array/cast_mini_controller_control_buttons"
        app:castProgressBarColor="@color/colorPrimary"
        app:castShowImageThumbnail="true" />
</code>```

Can anybody please suggest what can be the issue it might be?

I tried various articles and none of them able to resolve this issue. All is working fine except the fact that I can not pause the chromecast video through mini controller inside my app as its showing progressbar always.

Note: My application is using queuing mechanism in order to load the chunk of videos at once.

答:
Make sure you are specifying the correct set of buttons for the fragment:</p>

```<code><array name="cast_mini_controller_control_buttons">
    <item>@id/cast_button_type_rewind_30_seconds</item>
    <item>@id/cast_button_type_play_pause_toggle</item>
    <item>@id/cast_button_type_forward_30_seconds</item>
</array>
</code>```

Body:
I am using below way to integrate mini_controller in my chromecast app. However, I always seeing progressbar instead of pause/play button in mini controller.

<fragment
        android:id="@+id/cast_mini_controller"
        class="com.google.android.gms.cast.framework.media.widget.MiniControllerFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"
        app:castControlButtons="@array/cast_mini_controller_control_buttons"
        app:castProgressBarColor="@color/colorPrimary"
        app:castShowImageThumbnail="true" />

Can anybody please suggest what can be the issue it might be?

I tried various articles and none of them able to resolve this issue. All is working fine except the fact that I can not pause the chromecast video through mini controller inside my app as its showing progressbar always.

Note: My application is using queuing mechanism in order to load the chunk of videos at once.

Body:
Make sure you are specifying the correct set of buttons for the fragment:

<array name="cast_mini_controller_control_buttons">
    <item>@id/cast_button_type_rewind_30_seconds</item>
    <item>@id/cast_button_type_play_pause_toggle</item>
    <item>@id/cast_button_type_forward_30_seconds</item>
</array>


问:
Create a query for special characters MINUS . and - in access
I am using this Like "[!A-Z0-9]", to find special characters in mailing namelines however it picks up "." and "-" which I do not want to see

答:
Try this instead:

```<code>Like "*[!A-Z0-9.-]*"
</code>```

If you want to check email addresses on validity, I'd suggest using VBA and Regular Expressions.
I guess there's plenty of posts on Stackoverflow regarding checking email addresses.
Otherwise have a look as this article on Geeksengine:

How to validate email addresses

Body:
Try this instead:

Like "*[!A-Z0-9.-]*"

If you want to check email addresses on validity, I'd suggest using VBA and Regular Expressions.
I guess there's plenty of posts on Stackoverflow regarding checking email addresses.
Otherwise have a look as this article on Geeksengine:

How to validate email addresses


问:
Soft Keyboard opens then closes in clicking edittext
I have a Recyclerview and one of the items has an edittext , but everytime i clcik on field to start typing the Soft Keyboard opens then closes right away. Has anyone experienced this before ?</p>

答:
Maybe a little too late but I've just had this issue. I solved by adding android:windowSoftInputMode="adjustPan" to YourActivity in AndroidManifest.xml, like:

```<code><activity android:name=".YourActivity" android:windowSoftInputMode="adjustPan"/>
</code>```

Body:
Maybe a little too late but I've just had this issue. I solved by adding android:windowSoftInputMode="adjustPan" to YourActivity in AndroidManifest.xml, like:

<activity android:name=".YourActivity" android:windowSoftInputMode="adjustPan"/>


问:
Xamarin.Forms x:Shared
I have an issue with a Xamarin.Forms application I am currently working on. The resource I have created is being used within multiple controls, the controls are using the same object to render out onto the screen. I thought using the x:Shared="False" attribute (as per https://learn.microsoft.com/en-us/dotnet/framework/xaml-services/x-shared-attribute) would get around this. It does not :( Any ideas how to create the same object in .xaml without having to define multiple resources?

```<code><Grid.Resources>
 <ResourceDictionary>
   <SharedShapes:Circle x:Shared="False" x:Key="SpecCircle" Color="{StaticResource AccentColor}"/>
 </ResourceDictionary>
</Grid.Resources>

<SharedControls:ImageButton Grid.Row="0" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
<SharedControls:ImageButton Grid.Row="1" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
.
.
.
</code>```

Many thanks in advance!

答:
The link you mentioned talks primarily about WPF framework - I don't think x:Shared is supported in Xamarin forms.

To avoid having to declare shape multiple times - you can make use of DataTemplate, and register that as a StaticResource.

And, modify/extend ImageButton to add a bindable property of type DataTemplate, which when set inflates the template into Shape object using CreateContent() method.

```<code>public DataTemplate ShapeTemplate
{
    get { return (DataTemplate)GetValue(ShapeTemplateProperty); }
    set { SetValue(ShapeTemplateProperty, value); }
}

public static readonly BindableProperty ShapeTemplateProperty = BindableProperty.Create(
    nameof(ShapeTemplate),
    typeof(DataTemplate),
    typeof(ImageButton),
    propertyChanged: (bObj, oldValue, newValue) =>
    {
        var view = bObj as ImageButton;
        if (view != null && newValue != null)
            view.Shape = (View)newValue.CreateContent();
    }
);
</code>```

Sample usage

```<code><Grid.Resources>
 <ResourceDictionary>
   <DataTemplate x:Key="SpecCircleTemplate">
      <SharedShapes:Circle Color="{StaticResource AccentColor}"/>
   </DataTemplate>
 </ResourceDictionary>
</Grid.Resources>

<SharedControls:ImageButton Grid.Row="0" Grid.Column="0"
    ShapeTemplate="{StaticResource SpecCircleTemplate}"...
<SharedControls:ImageButton Grid.Row="1" Grid.Column="0"
    ShapeTemplate="{StaticResource SpecCircleTemplate}"...
</code>```

Title: Xamarin.Forms x:Shared

Body:
I have an issue with a Xamarin.Forms application I am currently working on. The resource I have created is being used within multiple controls, the controls are using the same object to render out onto the screen. I thought using the x:Shared="False" attribute (as per https://learn.microsoft.com/en-us/dotnet/framework/xaml-services/x-shared-attribute) would get around this. It does not :( Any ideas how to create the same object in .xaml without having to define multiple resources?

<Grid.Resources>
 <ResourceDictionary>
   <SharedShapes:Circle x:Shared="False" x:Key="SpecCircle" Color="{StaticResource AccentColor}"/>
 </ResourceDictionary>
</Grid.Resources>

<SharedControls:ImageButton Grid.Row="0" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
<SharedControls:ImageButton Grid.Row="1" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
.
.
.

Many thanks in advance!

Body:
The link you mentioned talks primarily about WPF framework - I don't think x:Shared is supported in Xamarin forms.

To avoid having to declare shape multiple times - you can make use of DataTemplate, and register that as a StaticResource.

And, modify/extend ImageButton to add a bindable property of type DataTemplate, which when set inflates the template into Shape object using CreateContent() method.

public DataTemplate ShapeTemplate
{
    get { return (DataTemplate)GetValue(ShapeTemplateProperty); }
    set { SetValue(ShapeTemplateProperty, value); }
}

public static readonly BindableProperty ShapeTemplateProperty = BindableProperty.Create(
    nameof(ShapeTemplate),
    typeof(DataTemplate),
    typeof(ImageButton),
    propertyChanged: (bObj, oldValue, newValue) =>
    {
        var view = bObj as ImageButton;
        if (view != null && newValue != null)
            view.Shape = (View)newValue.CreateContent();
    }
);

Sample usage

<Grid.Resources>
 <ResourceDictionary>
   <DataTemplate x:Key="SpecCircleTemplate">
      <SharedShapes:Circle Color="{StaticResource AccentColor}"/>
   </DataTemplate>
 </ResourceDictionary>
</Grid.Resources>

<SharedControls:ImageButton Grid.Row="0" Grid.Column="0"
    ShapeTemplate="{StaticResource SpecCircleTemplate}"...
<SharedControls:ImageButton Grid.Row="1" Grid.Column="0"
    ShapeTemplate="{StaticResource SpecCircleTemplate}"...


问:
`link_to` with parameters for an Engine route
(While this discusses Blacklight engine, I believe the question is actually purely about Rails.)

Continuing my quest from scope around mount ineffective? (tl;dr: make the engine routes obey the same :locale scope as application routes), after digging through Rails source.

Currently, I have this setup:

```<code># config/routes.rb
Rails.application.routes.draw do
  Blacklight::Engine.routes.default_scope = { path: "(:locale)", locale: /en|ja/ }
  mount Blacklight::Engine => '/'

  scope "(:locale)", locale: /en|ja/ do
    # ...
  end
end
</code>```

This makes the routes work properly. However, I had this view code to generate the alternate-language links to the current page (guided by link_to the current page plus/merged with a param [duplicate]):

```<code><div id="languages_nav_popup" class="navbar-inverse">
  <% locales.each do |locale| %>
    <% next if locale == I18n.locale %>
    <%= link_to params.permit!.merge(locale: locale) do %>
      <img src="<%= url_for "/img/flag/#{locale}.png" %>"/>
    <% end %>
  <% end %>
</div>
</code>```

That link_to fails when the current page is an Engine route. This is due to this piece of code in actionpack:

```<code># lib/action_dispatch/journey/formatter.rb
# Skip this route unless a name has been provided or it is a
# standard Rails route since we can't determine whether an options
# hash passed to url_for matches a Rack application or a redirect.
next unless name || route.dispatcher?
</code>```

With link_to options, &block syntax that I use above, name is nil; and dispatcher? is false for an engine route. (If I pass that check by inserting a name by force, I get a nonsensical URL like .../assets?action=index&controller=saved_searches&locale=ja).

I'm getting desperate here, almost to the point where I'm thinking the best way to deal with this is regexp. This atrocity works:

```<code><%= link_to request.base_url + request.original_fullpath.sub(%r{(?<=/)#{I18n.locale}}, locale.to_s) do %
</code>```

Is there no way to generate the correct URL properly?

答: Another totally hacky solution is to copy the engine routes to your local routes.rb and add a warning that triggers on gem update to check them for changes. :(</p>

Body:
(While this discusses Blacklight engine, I believe the question is actually purely about Rails.)

Continuing my quest from scope around mount ineffective? (tl;dr: make the engine routes obey the same :locale scope as application routes), after digging through Rails source.

Currently, I have this setup:

# config/routes.rb
Rails.application.routes.draw do
  Blacklight::Engine.routes.default_scope = { path: "(:locale)", locale: /en|ja/ }
  mount Blacklight::Engine => '/'

  scope "(:locale)", locale: /en|ja/ do
    # ...
  end
end

This makes the routes work properly. However, I had this view code to generate the alternate-language links to the current page (guided by link_to the current page plus/merged with a param [duplicate]):

  <% locales.each do |locale| %>
    <% next if locale == I18n.locale %>
    <%= link_to params.permit!.merge(locale: locale) do %>
      <img src="<%= url_for "/img/flag/#{locale}.png" %>"/>
    <% end %>
  <% end %>

That link_to fails when the current page is an Engine route. This is due to this piece of code in actionpack:

# lib/action_dispatch/journey/formatter.rb
# Skip this route unless a name has been provided or it is a
# standard Rails route since we can't determine whether an options
# hash passed to url_for matches a Rack application or a redirect.
next unless name || route.dispatcher?

With link_to options, &block syntax that I use above, name is nil; and dispatcher? is false for an engine route. (If I pass that check by inserting a name by force, I get a nonsensical URL like .../assets?action=index&controller=saved_searches&locale=ja).

I'm getting desperate here, almost to the point where I'm thinking the best way to deal with this is regexp. This atrocity works:

<%= link_to request.base_url + request.original_fullpath.sub(%r{(?<=/)#{I18n.locale}}, locale.to_s) do %

Is there no way to generate the correct URL properly?


问:
Difference between Configurable and Writable attributes of an Object
I saw the following regarding javascript, object data property attributes

—
Configurable: Specifies whether the property can be deleted or changed.

— Enumerable: Specifies whether the property can be returned in a for/in loop.

— Writable: Specifies whether the property can be changed.

Here "Configurable" and "Writable" are representing the same (whether the property can be changed), then why do we need two separate attributes?

答:
configurable and writable are NOT representing the same thing.

configurable means property descriptor and existence.

writable means property value only.

A property's descriptor contains value, enumerable, configurable and writable.

scenario 1: create property by assignment

```<code>'use strict';  // non-strict mode behaves slightly different

var foo = {};
foo.bar = 1;  // operated by CreateDataProperty*

// the above is the same as
Object.defineProperty(foo, 'bar', {
  value: 1,
  configurable: true,
  writable: true,
  // ...
});
</code>```

CreateDataProperty is an operation defined together with ECMAScript spec.

scenario 2: create property by descriptor

```<code>'use strict';  // non-strict mode behaves slightly different

var foo = {};
Object.defineProperty(foo, 'bar', {
  value: 1,
  // configurable => false
  // writable => false
});

foo.bar = 2;    // throw TypeError: Cannot assign to read only property

Object.defineProperty(foo, 'bar', {
  value: 2
  // ...
}); // throw TypeError: Cannot redefine property

delete foo.bar; // throw TypeError: Cannot delete property
</code>```

ContentLicense: CC BY-SA 4.0

Body:
configurable and writable are NOT representing the same thing.

configurable means property descriptor and existence.

writable means property value only.

A property's descriptor contains value, enumerable, configurable and writable.

scenario 1: create property by assignment

'use strict';  // non-strict mode behaves slightly different

var foo = {};
foo.bar = 1;  // operated by CreateDataProperty*

// the above is the same as
Object.defineProperty(foo, 'bar', {
  value: 1,
  configurable: true,
  writable: true,
  // ...
});

CreateDataProperty is an operation defined together with ECMAScript spec.

scenario 2: create property by descriptor

'use strict';  // non-strict mode behaves slightly different

var foo = {};
Object.defineProperty(foo, 'bar', {
  value: 1,
  // configurable => false
  // writable => false
});

foo.bar = 2;    // throw TypeError: Cannot assign to read only property

Object.defineProperty(foo, 'bar', {
  value: 2
  // ...
}); // throw TypeError: Cannot redefine property

delete foo.bar; // throw TypeError: Cannot delete property


问:
dask distributed 1.19 client logging?
The following code used to emit logs at some point, but no longer seems to do so. Shouldn't configuration of the logging mechanism in each worker permit logs to appear on stdout? If not, what am I overlooking?

```<code>import logging
from distributed import Client, LocalCluster
import numpy as np

def func(args):
    i, x = args
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(name)s %(levelname)s %(message)s')
    logger = logging.getLogger('func %i' % i)
    logger.info('computing svd')
    return np.linalg.svd(x)

if __name__ == '__main__':
    lc = LocalCluster(10)
    c = Client(lc)
    data = [np.random.rand(50, 50) for i in range(50)]
    fut = c.map(func, zip(range(len(data)), data))
    results = c.gather(fut)
    lc.close()
</code>```

As per this question, I tried putting the logger configuration code into a separate function invoked via c.run(init_logging) right after instantiation of the client, but that didn't make any difference either.

I'm using distributed 1.19.3 with Python 3.6.3 on Linux. I have

```<code>logging:
    distributed: info
    distributed.client: info
</code>```

in ~/.dask/config.yaml.

答:
Evidently the submitted functions do not actually execute until one tries to retrieve the results from the generated futures, i.e., using the line

```<code>print(list(results))
</code>```

before shutting down the local cluster. I'm not sure how to reconcile this with the section in the online docs that seems to state that direct submissions to a cluster are executed immediately.

Title: dask distributed 1.19 client logging?

Body:
The following code used to emit logs at some point, but no longer seems to do so. Shouldn't configuration of the logging mechanism in each worker permit logs to appear on stdout? If not, what am I overlooking?

import logging
from distributed import Client, LocalCluster
import numpy as np

def func(args):
    i, x = args
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(name)s %(levelname)s %(message)s')
    logger = logging.getLogger('func %i' % i)
    logger.info('computing svd')
    return np.linalg.svd(x)

if __name__ == '__main__':
    lc = LocalCluster(10)
    c = Client(lc)
    data = [np.random.rand(50, 50) for i in range(50)]
    fut = c.map(func, zip(range(len(data)), data))
    results = c.gather(fut)
    lc.close()

As per this question, I tried putting the logger configuration code into a separate function invoked via c.run(init_logging) right after instantiation of the client, but that didn't make any difference either.

I'm using distributed 1.19.3 with Python 3.6.3 on Linux. I have

logging:
    distributed: info
    distributed.client: info

in ~/.dask/config.yaml.

Body:
Evidently the submitted functions do not actually execute until one tries to retrieve the results from the generated futures, i.e., using the line

print(list(results))

before shutting down the local cluster. I'm not sure how to reconcile this with the section in the online docs that seems to state that direct submissions to a cluster are executed immediately.


问:
Is it possible to combine SharePoint with .net 4 code
We are designing a system.

We would like to use SharePoint webparts which are .net framework 3.5 as the UI. We also have some access to the database which we would like to use EF4 which is framework 4.

Is this possible? Or do we need to put as web service hop in between?

答:
At the time, no version of SharePoint is compatible with .Net 4.
An explanation can be found here: http://mossblogger.blogspot.com/2010/06/sharepoint-2010-and-net-4-confused.html

So, yes - you have to put an extra layer between your UI layer and the DB layer.

ContentLicense: CC BY-SA 2.5


问:
Transform a MovieClip containing one PNG image intro sprite - AS3 Adobe air
Hy, i have tried to search all around the internet to find a very basic solution to a simple question, in which i end up getting either lots of more details or even lesser, considering i am fairly new to AS3 and trying my best.

In the Library, i have created a movie clip, in which i loaded one single PNG image. No animations in the clip, no fancy stuff.

Since i have lots of movie clips created with the same concept, i am experiencing some sort of slow response from the game.

I have read that using GPU mode ( which i already do ) along with using sprites would increase the performance intensively.

Can someone please try to explain to me, a newb in as3, how can i load the image inside of a sprite instead of using movie clips.

答:
Your mistake is that you are assuming you are fully utilizing GPU render with Hardware Acceleration option set to GPU. In fact, that greatly depends on your hardware as described here (search for GPU keyword): https://helpx.adobe.com/animate/using/publish-settings.html

To get the full advantage of GPU processing you need to use the Stage3D technique. Also, I doubt one could use it as is - Adobe have implemented it on a low level, so you need to use some GPU-enabled framework, like Gamua Starling. The next problem you will be facing is that Starling (as well as the other GPU frameworks) does not think in terms of timelines and MovieClips and all the other classic Flash objects, they think in terms of textures, atlases and - yes - sprites (probably you've been advised about them) and other GPU-related stuff.

I know this sounds pretty complicated, but as far as I know you cannot avoid Starling or such as long as you want to build a fast, responsive and graphically rich mobile application with Flash/AIR. The thing is that Flash uses a lot of CPU power to render things, while mobile devices do not come with CPU powers (but with decent GPUs at the same time), so classic Flash will be slow as soon as it needs to redraw the content each frame.


问:
Neverending restore of database
I have SQL Server version 14.0 (SSMS v17.3) and I wanted to copy and paste (duplicate) database for testing purposes. I did what is explained here (How can I clone an SQL Server database on the same server in SQL Server 2008 Express?) in the first answer (222 votes, version 2014). I managed to create duplicate called MYDB2, but main database MYDB become unavailable. In SSMS I can see:

MYDB (Restoring...)

that never ends (system restart didn't help), and when I open this database I get this error:

"The database MYDB is not accessible. (ObjectExplorer)".

How can I fix first database and what is possible reason of corruption? Thank you in advance!

答: Please try running this: RESTORE DATABASE MYDB WITH RECOVERY. I've had that happen before and the WITH RECOVERY resolved the issue.

Title: Neverending restore of database


问:
Moving bits to left
```<code>    byte right =0xf; // 00001111
    System.out.println(Integer.toBinaryString(right)); // 00001111

    right = (byte)(right << 4);
    System.out.println(Integer.toBinaryString(right)); // 11111111111111111111111111110000
</code>```

why right is equal to 11111111111111111111111111110000? I explicitly cast it to byte = 8 bits.

I'm excpecting for an output: 11110000.

答:
If you hadn't cast to byte, all would be well.

There are no shift operators defined for byte, so the value is first promoted to int - which is fine, and still 0000[...]1111.

You then shift left 4 bits, giving 0000[...]111000.

You then cast to byte, giving a byte of 11110000.

You then call Integer.toBinaryString, which takes an int parameter. That means the byte 1111000 is convert to int - at which point it's sign-extended to 11111111111111111111111111110000 (as per JLS 5.1.2), which is then printed.

Options:

Don't cast down to byte, so you don't end up with a conversion back to int. (e.g. use int shifted = right << 4; and then pass shifted into Integer.toBinaryString.)

Instead of leaving the conversion implicit, use right & 0xff to apply a bit-mask so you can only have the bottom 8 bits set.

Either of those prints 11110000 instead.

Title: Moving bits to left

Body:
    byte right =0xf; // 00001111
    System.out.println(Integer.toBinaryString(right)); // 00001111

    right = (byte)(right << 4);
    System.out.println(Integer.toBinaryString(right)); // 11111111111111111111111111110000

why right is equal to 11111111111111111111111111110000? I explicitly cast it to byte = 8 bits.

I'm excpecting for an output: 11110000.


问:
Showing an input in a view depending on role
I have a fat view (add) with a lot of inputs (it's a form).

For a role , there is a user_id input that is necessary, but for another role it isn't necessary. Here it comes my question, I know that elements are used for this kind of things, but I would be duplicating a lot of code if I make a view with this input and another one without it. Is there any way to just replace a line of code depending on the role? How would it be?

Thank you very much in advance, have a nice day!

答:
What's wrong with a good old if?

```<code><?php if ($theRoleOfTheUser == 'someSpecificRole') : ?>
    <div><?php echo $this->Form->input(…); ?></div>
<?php endif; ?>
</code>```

Body:
What's wrong with a good old if?

<?php if ($theRoleOfTheUser == 'someSpecificRole') : ?>
    <div><?php echo $this->Form->input(…); ?></div>
<?php endif; ?>


问:
How to get cookies with guzzle?
The Guzzle site is very weak documentation. I realized that I needed to look at the source code to use all the features of the library, but I still can not fully understand the source code.

How to get cookies with Guzzle from any website? What class to look at?

答:
The cookies representation in guzzle is part of the PSR-7's ServerRequestInterface implementation, e.g of the ServerRequest class. In the class is defined an array property $cookieParams. To this variable you can either assign the $_COOKIE variable (through the call to the static method fromGlobals()) or an array of your choice (inclusive $_COOKIE) by calling withCookieParams(). To read the content of the $cookieParams array you just need to call getCookieParams().

Example using fromGlobals() - having the role of a ServerRequest factory:

```<code><?php

use GuzzleHttp\Psr7\ServerRequest;

/**
 * Create a ServerRequest instance, populated with superglobals:
 * $_GET
 * $_POST
 * $_COOKIE
 * $_FILES
 * $_SERVER
 */
$serverRequest = ServerRequest::fromGlobals();

// Display the content of $_COOKIE.
var_dump($serverRequest->getCookieParams());
</code>```

Example of directly creating a ServerRequest instance and assigning a cookies array to a copy of it - in order to maintain the immutability of the request object:

```<code><?php

use GuzzleHttp\Psr7\ServerRequest;

// Directly create a ServerRequest instance.
$serverRequest = new ServerRequest('GET', 'http://localhost/mypath?var=somevar#myfragment', [], NULL, '1.1', $_SERVER);

// Create a clone instance with the specified cookies array.
$serverRequest = $serverRequest->withCookieParams($_COOKIE);

// Display the content of the cookies list.
var_dump($serverRequest->getCookieParams());
</code>```

There is also another implementation, the one of GuzzleHttp\Cookie\CookieJarInterface, e.g the class GuzzleHttp\Cookie\CookieJar (see here) This is documented on http://docs.guzzlephp.org, at:

Quickstart Cookies

Request Options - Cookies

Handlers

In CookieJar class you can assign a $cookieArray in constructor and have some methods to handle its values (getCookieValue(), getCookieByName(), setCookie() etc).

Title: How to get cookies with guzzle?

Body:
The cookies representation in guzzle is part of the PSR-7's ServerRequestInterface implementation, e.g of the ServerRequest class. In the class is defined an array property $cookieParams. To this variable you can either assign the $_COOKIE variable (through the call to the static method fromGlobals()) or an array of your choice (inclusive $_COOKIE) by calling withCookieParams(). To read the content of the $cookieParams array you just need to call getCookieParams().

Example using fromGlobals() - having the role of a ServerRequest factory:

<?php

use GuzzleHttp\Psr7\ServerRequest;

/**
 * Create a ServerRequest instance, populated with superglobals:
 * $_GET
 * $_POST
 * $_COOKIE
 * $_FILES
 * $_SERVER
 */
$serverRequest = ServerRequest::fromGlobals();

// Display the content of $_COOKIE.
var_dump($serverRequest->getCookieParams());

Example of directly creating a ServerRequest instance and assigning a cookies array to a copy of it - in order to maintain the immutability of the request object:

<?php

use GuzzleHttp\Psr7\ServerRequest;

// Directly create a ServerRequest instance.
$serverRequest = new ServerRequest('GET', 'http://localhost/mypath?var=somevar#myfragment', [], NULL, '1.1', $_SERVER);

// Create a clone instance with the specified cookies array.
$serverRequest = $serverRequest->withCookieParams($_COOKIE);

// Display the content of the cookies list.
var_dump($serverRequest->getCookieParams());

There is also another implementation, the one of GuzzleHttp\Cookie\CookieJarInterface, e.g the class GuzzleHttp\Cookie\CookieJar (see here) This is documented on http://docs.guzzlephp.org, at:

Quickstart Cookies

Request Options - Cookies

Handlers

In CookieJar class you can assign a $cookieArray in constructor and have some methods to handle its values (getCookieValue(), getCookieByName(), setCookie() etc).


问:
C client-server application and battery saving on linux
Could someone explain me please, how i can achieve the most efficient battery saving: I want to code a simple client-server app. Server sending periodic messages to client (let's say 'hello'), and client just showing it. What will happen exactly in case client call poll / select and wait for incoming message? Will i waist resources on net ( 4g / wi-fi)? Or app should sleep and awake just sometimes to check for updates? May be some other solutions?</p>

答: Calling select or poll doesn't use any significant resources. There's no looping, the process is simply blocked until the condition it's waiting for occurs. If you specify a timeout, it will only run that often.


问:
Getting Time Remaining
Say something happens at a rate of 5000 per hour and there's some amount remaining (let's say 2500 for example's sake).

How would I get the hours, minutes, and seconds remaining?

I would think it'd be something along the lines of:

```<code>hour = floor(remaining / perHour)
mins = floor(remaining % perHour / 60)
secs = floor(remaining % perHour % 60)
</code>```

However calculating that back up using the below returns the incorrect amount.

```<code>time = hour + (mins / 60) + (secs / 60 / 60)
time * perHour // 3472.2 - not 2500
</code>```

The time should be shorter so I'm obviously calculating this wrong. I would appreciate it if someone were to explain where I went wrong.

EDIT: I'm aware this isn't the Maths SE but the Maths SE is supposed to be for high level maths, and this is the next best fit.

Figured out a method, but it may not be the best so I'll leave this question up for a while longer.

```<code>hour = floor(remaining / perHour)
mins = floor(remaining / perHour * 60) - hour * 60
secs = floor(remaining / perHour * 3600) - mins * 60 - hour * 3600
</code>```

答:
Our question is how much time remains, and we know the rate of the process. No sweat, we establish a rate ( Items/minute, Items/sec) and divide the number of remaining elements by the rate. We could use any unit of time we want as long as we keep it consistent -- personally, I like rates in per-second because Hz.

A Demo

function getRemainingTime(remainingItems) {
  const processRatePerHour = 5000;
  const processRate = (processRatePerHour / 60 / 60); // 1.3888 per second

  remainingSeconds = remainingItems / processRate;

  return {
    hours: (remainingSeconds / 3600),
    minutes: (remainingSeconds / 60),
    seconds: remainingSeconds
  };

}

function showProgress(remainingItems) {
  var time = getRemainingTime(remainingItems);

  var list = document.createElement('ul');

  var processEnd = moment().add(time.seconds, 's');

  list.innerHTML = `

 With ${remainingItems} remaining, we will be finished ${processEnd.fromNow()}.

 Hours Remaining: ${time.hours}

 Minutes Remaining: ${time.minutes}

 Seconds Remaining: ${time.seconds}

`;

  document.body.appendChild(list);

}

// Let's try it out!

showProgress(4999);
showProgress(2500);
showProgress(100);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: 'Helvetica', sans-serif;
}</code>```

 Please Accept My Answer v.0.2.
```

Title: Getting Time Remaining

Body:
Say something happens at a rate of 5000 per hour and there's some amount remaining (let's say 2500 for example's sake).

How would I get the hours, minutes, and seconds remaining?

I would think it'd be something along the lines of:

hour = floor(remaining / perHour)
mins = floor(remaining % perHour / 60)
secs = floor(remaining % perHour % 60)

However calculating that back up using the below returns the incorrect amount.

time = hour + (mins / 60) + (secs / 60 / 60)
time * perHour // 3472.2 - not 2500

The time should be shorter so I'm obviously calculating this wrong. I would appreciate it if someone were to explain where I went wrong.

EDIT: I'm aware this isn't the Maths SE but the Maths SE is supposed to be for high level maths, and this is the next best fit.

Figured out a method, but it may not be the best so I'll leave this question up for a while longer.

hour = floor(remaining / perHour)
mins = floor(remaining / perHour * 60) - hour * 60
secs = floor(remaining / perHour * 3600) - mins * 60 - hour * 3600

Body:
Our question is how much time remains, and we know the rate of the process. No sweat, we establish a rate ( Items/minute, Items/sec) and divide the number of remaining elements by the rate. We could use any unit of time we want as long as we keep it consistent -- personally, I like rates in per-second because Hz.

A Demo

function getRemainingTime(remainingItems) {
  const processRatePerHour = 5000;
  const processRate = (processRatePerHour / 60 / 60); // 1.3888 per second

  remainingSeconds = remainingItems / processRate;

  return {
    hours: (remainingSeconds / 3600),
    minutes: (remainingSeconds / 60),
    seconds: remainingSeconds
  };

}

function showProgress(remainingItems) {
  var time = getRemainingTime(remainingItems);

  var list = document.createElement('ul');

  var processEnd = moment().add(time.seconds, 's');

  list.innerHTML = `
    <ul>
      <h3> With ${remainingItems} remaining, we will be finished ${processEnd.fromNow()}. </h3>
      <li> Hours Remaining: ${time.hours} </li>
      <li> Minutes Remaining: ${time.minutes} </li>
      <li> Seconds Remaining: ${time.seconds} </li>
    </ul>`;

  document.body.appendChild(list);

}

// Let's try it out!

showProgress(4999);
showProgress(2500);
showProgress(100);

body {
  font-family: 'Helvetica', sans-serif;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>

<h2> Please Accept My Answer v.0.2. </h2>


问:
What is best practice for running multiple Docker containers with code from different repos?
I have a web app that consists of multiple services (including a postgres db and redis), in multiple repos. Ideally I'd like to have all the Docker stuff in one repo, and build from there. However, I'm running into trouble since building the containers involves compiling code in other directories (or repositories), and you can't ADD from a different directory. Symlinking doesn't work either. And I don't want to pull from github into a container to avoid having ssh keys in the wild. Is there a way to accomplish what I'm trying to do? Or does each repo need its own Dockerfile?

答:
Its preferable to maintain one dockerfile for each project and keep each project independent of the others so that you can build each project separately.

However, if you cannot do that there can be some workarounds.

Your problem is that the docker build context is limiting the scope in which files can be accessed. I recommend that you wrap you docker build inside a script, that collects all dependencies and issues a build command. The script might look something like this:

```<code>mkdir build-dir

cp <path-to-file1> build-dir/file1
cp <path-to-file2> build-dirfile2
cp <path-to-Dockerfile> build-dir/Dockerfile
...
docker build -t image .
rm -rf build-dir
</code>```

And the Dockerfile will be transparent as it assumes that all dependecies are in the build context.

```<code>FROM ...
ADD file1 file1
ADD file2 file2

...
</code>```

Body:
Its preferable to maintain one dockerfile for each project and keep each project independent of the others so that you can build each project separately.

However, if you cannot do that there can be some workarounds.

Your problem is that the docker build context is limiting the scope in which files can be accessed. I recommend that you wrap you docker build inside a script, that collects all dependencies and issues a build command. The script might look something like this:

mkdir build-dir

cp <path-to-file1> build-dir/file1
cp <path-to-file2> build-dirfile2
cp <path-to-Dockerfile> build-dir/Dockerfile
...
docker build -t image .
rm -rf build-dir

And the Dockerfile will be transparent as it assumes that all dependecies are in the build context.

FROM ...
ADD file1 file1
ADD file2 file2

...


问:
Checking if 2 variables out 3 are equal in python
I am making a code where three dice are rolled and if all three dice are equal the values are added. If 2 of the dice are equal then the 2 equal dice values are added and the odd dice value is subtracted from the sum.

This is my code so far

```<code>import random

d1 = random.randint(1,6)
d2 = random.randint(1,6)
d3 = random.randint(1,6)

print(d1)
print(d2)
print(d3)

if d1 == d2 and d2 == d3:
    score = d1 + d2 + d3
elif d1 == d2 or d1 == d3 or d2 == d3:
</code>```

Now I don't know how I would find out which of the 2 dice are equal to be able to add them together. How would I do this?

答:
I might use collections.Counter for this.

A Counter is a dict subclass that counts objects. In the resulting dictionary, the keys are the objects being counted while the values are the number of times those objects appear.

We can create a count of dice rolls by passing a list of the results of random.randint() to Counter's constructor, like so:

```<code>Counter(random.randint(1,6) for _ in range(3)) # 3 6-sided rolls
</code>```

In addition to accessing the counts via dict's [] operator, we can also access them via Counter.most_common(), which returns a list containing all of the rolls and their associated counts.

In our program, rolls[0] is the most common roll and its count, rolls[0][0] is the value of the roll, rolls[0][1] is the number of times it was rolled. Similarly, rolls[1][0] is the second-most common value.

```<code>import random
from collections import Counter

rolls = Counter(random.randint(1,6) for _ in range(3)).most_common()

if len(rolls) == 1:
    score = rolls[0][0] * 3
elif len(rolls) == 2:
    score = rolls[0][0] * 2 - rolls[1][0]
else:
    score = 0

print (rolls, score)
</code>```

You haven't specified what the correct score is when there are no matches. The above algorithm gives a score of 0 if there are no matches.

Here is another algorithm which scores the negative sum of all the dice if there are no matches. In essence, it adds up all of the matching dice and subtracts each singleton die. This gives the answer you request for each of the cases you describe but punishes non-matching rolls more severely. Notice how this version generalizes easily to different numbers of dice and different numbers of sides.

```<code>import random
from collections import Counter

rolls = Counter(random.randint(1, 6) for _ in range(3)).most_common()

score = sum(roll[0] * (-1 if roll[1]==1 else 1) * roll[1] for roll in rolls)

print(rolls, score)
</code>```

Body:
I am making a code where three dice are rolled and if all three dice are equal the values are added. If 2 of the dice are equal then the 2 equal dice values are added and the odd dice value is subtracted from the sum.

This is my code so far

import random

d1 = random.randint(1,6)
d2 = random.randint(1,6)
d3 = random.randint(1,6)

print(d1)
print(d2)
print(d3)

if d1 == d2 and d2 == d3:
    score = d1 + d2 + d3
elif d1 == d2 or d1 == d3 or d2 == d3:

Now I don't know how I would find out which of the 2 dice are equal to be able to add them together. How would I do this?

Body:
I might use collections.Counter for this.

A Counter is a dict subclass that counts objects. In the resulting dictionary, the keys are the objects being counted while the values are the number of times those objects appear.

We can create a count of dice rolls by passing a list of the results of random.randint() to Counter's constructor, like so:

Counter(random.randint(1,6) for _ in range(3)) # 3 6-sided rolls

In addition to accessing the counts via dict's [] operator, we can also access them via Counter.most_common(), which returns a list containing all of the rolls and their associated counts.

In our program, rolls[0] is the most common roll and its count, rolls[0][0] is the value of the roll, rolls[0][1] is the number of times it was rolled. Similarly, rolls[1][0] is the second-most common value.

import random
from collections import Counter

rolls = Counter(random.randint(1,6) for _ in range(3)).most_common()

if len(rolls) == 1:
    score = rolls[0][0] * 3
elif len(rolls) == 2:
    score = rolls[0][0] * 2 - rolls[1][0]
else:
    score = 0

print (rolls, score)

You haven't specified what the correct score is when there are no matches. The above algorithm gives a score of 0 if there are no matches.

Here is another algorithm which scores the negative sum of all the dice if there are no matches. In essence, it adds up all of the matching dice and subtracts each singleton die. This gives the answer you request for each of the cases you describe but punishes non-matching rolls more severely. Notice how this version generalizes easily to different numbers of dice and different numbers of sides.

import random
from collections import Counter

rolls = Counter(random.randint(1, 6) for _ in range(3)).most_common()

score = sum(roll[0] * (-1 if roll[1]==1 else 1) * roll[1] for roll in rolls)

print(rolls, score)


问:
Server error with unsupported URL
To delete an item from a list, here is my client code:

```<code>deleteResource(resType: String, patientId: String): Observable<IFhirAck> {
        console.log("DeleteResource");
        let headers = new Headers({ 'Content-Type': 'application/json' });
        headers.append("Accept", "application/json");
        headers.append("USER_KEY", "cGgwGRCzdGXGMtV7WjcW"); //TOUCHSTONE KEY
        let options = new RequestOptions({ headers: headers });

        return this.http.delete(this.baseUrl + resType + "/id/" + patientId, options)
            .map((res: Response) => res.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server error from Observable http.put call'))
    }
</code>```

The logic reached the server and the server throws the error as

Unsupported URL: [/Patient/id/8bb3163e-4f2f-4c31-8c14-0afc3d0a7842]

The value after id is correct as shown in mongodb. What could be the cause for "unsupported URL"? How do I fix this issue?

答: It turned out that the server side missed "/id" in the router module.</p>

Title: Server error with unsupported URL

Body:
To delete an item from a list, here is my client code:

deleteResource(resType: String, patientId: String): Observable<IFhirAck> {
        console.log("DeleteResource");
        let headers = new Headers({ 'Content-Type': 'application/json' });
        headers.append("Accept", "application/json");
        headers.append("USER_KEY", "cGgwGRCzdGXGMtV7WjcW"); //TOUCHSTONE KEY
        let options = new RequestOptions({ headers: headers });

        return this.http.delete(this.baseUrl + resType + "/id/" + patientId, options)
            .map((res: Response) => res.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server error from Observable http.put call'))
    }

The logic reached the server and the server throws the error as

Unsupported URL: [/Patient/id/8bb3163e-4f2f-4c31-8c14-0afc3d0a7842]

The value after id is correct as shown in mongodb. What could be the cause for "unsupported URL"? How do I fix this issue?


问:
jQuery each() behavior if changing DOM within loop
What is the behavior of jquery when using each() loop? Is it:

look for the first object, execute function, look for the next object...

gather all objects in a container, then execute the function on each of them

other (what exactly?)

An example, where it is relevant:

```<code><div id="a">
   A
   <div id="b">
      B
   </div>
</div>
<div id="c">
    C
</div>
</code>```

If I execute this javascript:

```<code>$('div').each(function(index){
   alert($(this).html());
   $(this).remove();
}
</code>```

Will I see three alerts or only two?

答:
2 is the answer.

jQuery gathers a list of matching elements, then loops over the list.

One important think though, do not remove any element that can be mached that has not already been processed or you will risk getting a reference not found error.

Body:
What is the behavior of jquery when using each() loop? Is it:

look for the first object, execute function, look for the next object...

gather all objects in a container, then execute the function on each of them

other (what exactly?)

An example, where it is relevant:

   A

      B

    C

If I execute this javascript:

$('div').each(function(index){
   alert($(this).html());
   $(this).remove();
}

Will I see three alerts or only two?


问:
How do I fill out the iov_iter structure for use with msghdr?
I am trying to send a UDP packet from a driver using sock_sendmsg().

There are several guides on how to use sock_sendmsg() and msghdr to fill out at a UDP packet and transmit it, but they are all for older kernel versions. Sometime between 3.13 and 4.8, the struct msghdr changed from:

```<code>struct msghdr {
    void    *   msg_name;   /* Socket name          */
    int     msg_namelen;    /* Length of name       */
    struct iovec *  msg_iov;    /* Data blocks          */
    __kernel_size_t msg_iovlen; /* Number of blocks     */
    void    *   msg_control;    /* Per protocol magic (eg BSD file descriptor passing) */
    __kernel_size_t msg_controllen; /* Length of cmsg list */
    unsigned int    msg_flags;
};
</code>```

To:

```<code>struct msghdr {
    void        *msg_name;  /* ptr to socket address structure */
    int     msg_namelen;    /* size of socket address structure */
    struct iov_iter msg_iter;   /* data */
    void        *msg_control;   /* ancillary data */
    __kernel_size_t msg_controllen; /* ancillary data buffer length */
    unsigned int    msg_flags;  /* flags on received message */
    struct kiocb    *msg_iocb;  /* ptr to iocb for async requests */
};
</code>```

Instead of setting  msg_iov to point to an iovec with the data:

```<code>struct msghdr msg = {};
struct iovec iov = {};

iov.iov_base = data;
iov.iov_len = dataLen;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
</code>```

There is now an iov_iter structure:

```<code>struct iov_iter {
    int type;
    size_t iov_offset;
    size_t count;
    union {
        const struct iovec *iov;
        const struct kvec *kvec;
        const struct bio_vec *bvec;
        struct pipe_inode_info *pipe;
    };
    union {
        unsigned long nr_segs;
        struct {
            int idx;
            int start_idx;
        };
    };
};
</code>```

How do I fill out the iov_iter structure inside of msghdr with data so that I can pass it to sock_sendmsg?

答:
After some playing around and reading the guide posted by Ctx (lwn.net/Articles/625077), I figured it out.</p>

```<code>unsigned long nr_segments = 1;
size_t count = 1;
struct msghdr msg = {};
struct iovec iov = {};

iov.iov_base = data;
iov.iov_len = dataLen;

iov_iter_init(&msg.msg_iter, READ, &iov, nr_segments, count);
</code>```

Body:
I am trying to send a UDP packet from a driver using sock_sendmsg().

There are several guides on how to use sock_sendmsg() and msghdr to fill out at a UDP packet and transmit it, but they are all for older kernel versions. Sometime between 3.13 and 4.8, the struct msghdr changed from:

struct msghdr {
    void    *   msg_name;   /* Socket name          */
    int     msg_namelen;    /* Length of name       */
    struct iovec *  msg_iov;    /* Data blocks          */
    __kernel_size_t msg_iovlen; /* Number of blocks     */
    void    *   msg_control;    /* Per protocol magic (eg BSD file descriptor passing) */
    __kernel_size_t msg_controllen; /* Length of cmsg list */
    unsigned int    msg_flags;
};

To:

struct msghdr {
    void        *msg_name;  /* ptr to socket address structure */
    int     msg_namelen;    /* size of socket address structure */
    struct iov_iter msg_iter;   /* data */
    void        *msg_control;   /* ancillary data */
    __kernel_size_t msg_controllen; /* ancillary data buffer length */
    unsigned int    msg_flags;  /* flags on received message */
    struct kiocb    *msg_iocb;  /* ptr to iocb for async requests */
};

Instead of setting  msg_iov to point to an iovec with the data:

struct msghdr msg = {};
struct iovec iov = {};

iov.iov_base = data;
iov.iov_len = dataLen;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;

There is now an iov_iter structure:

struct iov_iter {
    int type;
    size_t iov_offset;
    size_t count;
    union {
        const struct iovec *iov;
        const struct kvec *kvec;
        const struct bio_vec *bvec;
        struct pipe_inode_info *pipe;
    };
    union {
        unsigned long nr_segs;
        struct {
            int idx;
            int start_idx;
        };
    };
};

How do I fill out the iov_iter structure inside of msghdr with data so that I can pass it to sock_sendmsg?

Body:
After some playing around and reading the guide posted by Ctx (lwn.net/Articles/625077), I figured it out.

unsigned long nr_segments = 1;
size_t count = 1;
struct msghdr msg = {};
struct iovec iov = {};

iov.iov_base = data;
iov.iov_len = dataLen;

iov_iter_init(&msg.msg_iter, READ, &iov, nr_segments, count);


问:
Cannot Build Visual Studio Installer Project when main project has any .winmd references
I'm following the steps in this article.

My solution has a console app project and a visual studio installer project.

In the console app project, if I add any of the following references, I can no longer build my installer project.

For example, in the add references dialog, I go to browse, and select

```<code>C:\Program Files (x86)\Windows Kits\10\References\10.0.15063.0\Windows.Foundation.UniversalApiContract\4.0.0.0\Windows.Foundation.UniversalApiContract.winmd
</code>```

This reference will prevent my deployment project from building. The error message is:

```<code>ERROR: An error occurred while validating.  HRESULT = '80070057'
</code>```

Similarly, all of these references will break the deployment project build.

```<code>Windows.Foundation.FoundationContract.winmd
Windows.winmd
Windows.Foundation.UniversalApiContract.winmd
Windows.Foundation.FoundationContract.winmd
</code>```

My question is, how do I reference these UWP APIs without breaking my installer project?

答: The solution was to copy/paste the build files (.exe and .dll) into the deployment project's file system, instead of having the deployment project build the project output.</p>

Body:
I'm following the steps in this article.

My solution has a console app project and a visual studio installer project.

In the console app project, if I add any of the following references, I can no longer build my installer project.

For example, in the add references dialog, I go to browse, and select

C:\Program Files (x86)\Windows Kits\10\References\10.0.15063.0\Windows.Foundation.UniversalApiContract\4.0.0.0\Windows.Foundation.UniversalApiContract.winmd

This reference will prevent my deployment project from building. The error message is:

ERROR: An error occurred while validating.  HRESULT = '80070057'

Similarly, all of these references will break the deployment project build.

Windows.Foundation.FoundationContract.winmd
Windows.winmd
Windows.Foundation.UniversalApiContract.winmd
Windows.Foundation.FoundationContract.winmd

My question is, how do I reference these UWP APIs without breaking my installer project?


问:
Pickle database independent query in Django
First of all, I know that my question duplicate this question. But I supose it's not the same.

I need to save user "search filter". As I understand Django ORM create specific SQL query for different DB. So if I save SQL query I can't migrate on other database with different SQL syntax.
Am I wrong? If no, how can I save Django side of query, without accsesing to DB?

答:
The short answer is that you're correct -- mostly. If the SQL dialect that Django compiled the query for isn't compatible with a different backend, it wouldn't work or might work unpredictably.

To save the Django side of the query, why not just save the actual filter() statement that you're using or a representation of it that you can convert back on the fly?

Edit: Okay in that case I think you're on the right track based on comments and above answer. If you're parsing a query string already save that in the database as a CharField and then just use it to build a Django QuerySet when you retrieve it. If I'm understanding.


问:
How to find a complement to the following language?
How to find complement of L,

```<code>L = {<M>: M is a TM, which accepts some palindrome}
</code>```

What is the general rule to finding a complement?
I am thinking in this particular case it would be

```<code>L_bar = {<M_bar> : M_bar is a TM, which rejects any palindrome .???
</code>```

答:
The general rule for finding the complement (with respect to some understood universe U) of a language:

```<code>S = {x: P(x)}
</code>```

, where x is an element of universe U and P(x) is true iff x has the property required for membership in S, is

```<code>S' = {x': ~P(x')}
</code>```

, where x' is an element of universe U and ~P(x) is the negation of P(x) and is true iff x' does not have the property required for membership in S.

In your example:

```<code>L = {<M>: M is a TM, which accepts some palindrome}
</code>```

We must first determine what the universe is. If we take the universe to be all strings which represent encodings of TMs, your answer is close but possibly not correct, depending on your definitions. It would be more unambiguously correct if you said "does not accept" instead of "rejects" since a TM could loop forever on a palindrome, never accepting or rejecting it.

If, on the other hand, the universe were TMs that halt on all inputs, your answer is correct. On the other other hand, if the universe were all binary strings, your answer would be wrong unless every possible binary string were a valid encoding of some TM in your encoding. If there were some encodings that weren't valid TMs, they would need to belong to the complement of L as well.

Body:
How to find complement of L,

L = {<M>: M is a TM, which accepts some palindrome}

What is the general rule to finding a complement?
I am thinking in this particular case it would be

L_bar = {<M_bar> : M_bar is a TM, which rejects any palindrome .???

Body:
The general rule for finding the complement (with respect to some understood universe U) of a language:

S = {x: P(x)}

, where x is an element of universe U and P(x) is true iff x has the property required for membership in S, is

S' = {x': ~P(x')}

, where x' is an element of universe U and ~P(x) is the negation of P(x) and is true iff x' does not have the property required for membership in S.

In your example:

L = {<M>: M is a TM, which accepts some palindrome}

We must first determine what the universe is. If we take the universe to be all strings which represent encodings of TMs, your answer is close but possibly not correct, depending on your definitions. It would be more unambiguously correct if you said "does not accept" instead of "rejects" since a TM could loop forever on a palindrome, never accepting or rejecting it.

If, on the other hand, the universe were TMs that halt on all inputs, your answer is correct. On the other other hand, if the universe were all binary strings, your answer would be wrong unless every possible binary string were a valid encoding of some TM in your encoding. If there were some encodings that weren't valid TMs, they would need to belong to the complement of L as well.


问:
"ModuleNotFoundError: No module named <package>" in my Docker container
I'm trying to run a python script in a Docker container, and i don't know why, python can't find any of the python's module. I thaught it has something to do with the PYTHONPATH env variable, so i tried to add it in the Dockerfile like this : ENV PYTHONPATH $PYTHONPATH

But it didn't work.
this is what my Dockerfile looks like:

```<code>FROM ubuntu:16.04
MAINTAINER SaveMe SaveMe@Desperate.com

ADD . /app
WORKDIR /app

RUN apt-get update

RUN DEBIAN_FRONTEND=noninteractive apt-get install -y locales

# Set the locale
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/'
/etc/locale.gen && \
    locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
ENV PYTHONPATH ./app

#Install dependencies
RUN echo "===> Installing sudo to emulate normal OS behavior..."
RUN apt-get install -y software-properties-common
RUN apt-add-repository universe
RUN add-apt-repository ppa:jonathonf/python-3.6
RUN (apt-get update && apt-get upgrade -y -q && apt-get dist-upgrade -
y -q && apt-get -y -q autoclean && apt-get -y -q autoremove)
RUN apt-get install -y libxml2-dev libxslt-dev
RUN apt-get install -y python3.6 python3.6-dev python3.6-venv openssl
ca-certificates python3-pip
RUN apt-get install -y  python3-dev python-dev libffi-dev gfortran
RUN apt-get install -y swig
RUN apt-get install -y sshpass openssh-client rsync python-pip python-
dev libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev
zlib1g-dev libpulse-dev
RUN pip install --upgrade pip
RUN pip install bugsnag

#Install python package + requirements.txt
RUN  pip3 install  -r requirements.txt

CMD ["python3.6", "import_emails.py"]
</code>```

when i'm trying to run: sudo docker run <my_container> i got this Traceback:

```<code>Traceback (most recent call last):
  File "import_emails.py", line 9, in <module>
    import bugsnag
ModuleNotFoundError: No module named 'bugsnag'
</code>```

As you can see i'm using python3.6 for this project. Any lead on how to solve this ?

答:
Inside the container, when I pip install bugsnag, I get the following:

```<code>root@af08af24a458:/app# pip install bugsnag
Requirement already satisfied: bugsnag in /usr/local/lib/python2.7/dist-packages
Requirement already satisfied: webob in /usr/local/lib/python2.7/dist-packages (from bugsnag)
Requirement already satisfied: six<2,>=1.9 in /usr/local/lib/python2.7/dist-packages (from bugsnag)
</code>```

You probably see the problem here. You're installing the package for python2.7, which is the OS default, instead of python3.6, which is what you're trying to use.

Check out this answer for help resolving this issue: "ModuleNotFoundError: No module named <package>" in my Docker container

Alternatively, this is a problem virtualenv and similar tools are meant to solve, you could look into that as well.

Body:
I'm trying to run a python script in a Docker container, and i don't know why, python can't find any of the python's module. I thaught it has something to do with the PYTHONPATH env variable, so i tried to add it in the Dockerfile like this : ENV PYTHONPATH $PYTHONPATH

But it didn't work.
this is what my Dockerfile looks like:

FROM ubuntu:16.04
MAINTAINER SaveMe SaveMe@Desperate.com

ADD . /app
WORKDIR /app

RUN apt-get update

RUN DEBIAN_FRONTEND=noninteractive apt-get install -y locales

# Set the locale
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/'
/etc/locale.gen && \
    locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
ENV PYTHONPATH ./app

#Install dependencies
RUN echo "===> Installing sudo to emulate normal OS behavior..."
RUN apt-get install -y software-properties-common
RUN apt-add-repository universe
RUN add-apt-repository ppa:jonathonf/python-3.6
RUN (apt-get update && apt-get upgrade -y -q && apt-get dist-upgrade -
y -q && apt-get -y -q autoclean && apt-get -y -q autoremove)
RUN apt-get install -y libxml2-dev libxslt-dev
RUN apt-get install -y python3.6 python3.6-dev python3.6-venv openssl
ca-certificates python3-pip
RUN apt-get install -y  python3-dev python-dev libffi-dev gfortran
RUN apt-get install -y swig
RUN apt-get install -y sshpass openssh-client rsync python-pip python-
dev libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev
zlib1g-dev libpulse-dev
RUN pip install --upgrade pip
RUN pip install bugsnag

#Install python package + requirements.txt
RUN  pip3 install  -r requirements.txt

CMD ["python3.6", "import_emails.py"]

when i'm trying to run: sudo docker run <my_container> i got this Traceback:

Traceback (most recent call last):
  File "import_emails.py", line 9, in <module>
    import bugsnag
ModuleNotFoundError: No module named 'bugsnag'

As you can see i'm using python3.6 for this project. Any lead on how to solve this ?

Body:
Inside the container, when I pip install bugsnag, I get the following:

root@af08af24a458:/app# pip install bugsnag
Requirement already satisfied: bugsnag in /usr/local/lib/python2.7/dist-packages
Requirement already satisfied: webob in /usr/local/lib/python2.7/dist-packages (from bugsnag)
Requirement already satisfied: six<2,>=1.9 in /usr/local/lib/python2.7/dist-packages (from bugsnag)

You probably see the problem here. You're installing the package for python2.7, which is the OS default, instead of python3.6, which is what you're trying to use.

Check out this answer for help resolving this issue: "ModuleNotFoundError: No module named <package>" in my Docker container

Alternatively, this is a problem virtualenv and similar tools are meant to solve, you could look into that as well.


问:
Are argument types optional for methods?
I came across this unusual bit of Objective-C today which, to my suprise, compiles without fail and outputs "hi":

```<code>#include <Foundation/Foundation.h>

@interface MyObject : NSObject

- (NSString *)method:param;

@end

@implementation MyObject

- (NSString *)method:param
{
    return param;
}

@end

int main() {
    MyObject * m = [MyObject new];
    NSLog(@"%@", [m method:@"hi"]);
    return 0;
}
</code>```

Compile command:

```<code># clang version: clang-900.0.37
clang test.m -fobjc-arc -o test
</code>```

method has a single argument, param, but I did not explicitly give a type. I can't seem to find any documentation on this? What's going on?

答: I've been unable to find any official docs on this, but in my testing this is indistinguishable from the param being a generic id type.

Body:
I came across this unusual bit of Objective-C today which, to my suprise, compiles without fail and outputs "hi":

#include <Foundation/Foundation.h>

@interface MyObject : NSObject

- (NSString *)method:param;

@end

@implementation MyObject

- (NSString *)method:param
{
    return param;
}

@end

int main() {
    MyObject * m = [MyObject new];
    NSLog(@"%@", [m method:@"hi"]);
    return 0;
}

Compile command:

# clang version: clang-900.0.37
clang test.m -fobjc-arc -o test

method has a single argument, param, but I did not explicitly give a type. I can't seem to find any documentation on this? What's going on?


问:
iOS 11, Xcode 9 Error: NSURLConnection finished with error - code -1009
I am getting  Error: NSURLConnection finished with error - code -1009
 in iOS 11, Xcode 9 when i am going to background and wifi off.. its getting continuously up to wifi on and any one have a solution. </p>

答: Maybe it's one of those crazy iOS 11 bugs, because I got the exact same problem after upgrading to 11.2. The reason was that the cellular data for the app had been set to false on the device for some reason. To fix it, just goto the settings app, and cellular. Find your app in the list and enable it.


问:
How does this particular StrPos work in PHP?
I have the following code. I'm wondering if it's working like I think it is:

```<code>//Gift Card Redemption
        if(strpos($_order->getDiscountDescription(), 'Gift Card') !== false){
                $order .= 'RGC1*1*'.$_order->getDiscountDescription().'*****';
                $order .= "\r\n";
        }
</code>```

How I think it works: look for 'Gift Card' in $_order->getDiscountDescription(), and if it's not false, do something. I don't follow what that something is, though. Any ideas on that?

答:
This basically checks to see if the string literal 'Gift Card' is contained in the string returned by $_order->getDiscountDescription() (i.e. presuming it returns a string...). The use of the operator !== and operand false is used because the position might be 0, meaning the start of the string. Refer to the warning on the documentation for strpos():

Warning
  This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

When that condition is true (i.e. the order description contains 'Gift Card') then the variable $order gets appended with the string literal RGC1*1* followed by the return value from the call to $_order->getDiscountDescription(), 5 asterisk characters, a carriage return character (i.e. \r) and a new line character (i.e. \n).

Body:
I have the following code. I'm wondering if it's working like I think it is:

//Gift Card Redemption
        if(strpos($_order->getDiscountDescription(), 'Gift Card') !== false){
                $order .= 'RGC1*1*'.$_order->getDiscountDescription().'*****';
                $order .= "\r\n";
        }

How I think it works: look for 'Gift Card' in $_order->getDiscountDescription(), and if it's not false, do something. I don't follow what that something is, though. Any ideas on that?


问:
SQL Server Triggers, Stored Procedures
I dont ever used triggers or stored procedures. Now i want to study how and when i use that.
I have table named Products, when products table filling with row i want to copy ProductID and UnitsInStock and paset into Inventory table. There is one problem in inventory table is column which must fill buy user when row is filling. Would triggers or stored procedures will be useful for this situation?</p>

答:
If you just need to copy stuff from one table to another after inserting or updating, a trigger is the right way to do this.

But if in your case a column must be filled with user-applied data, you probably will have to do this from your code.

About the use of stored procedures: take a look at this. But there are many discussions on the web about this theme. Just google a bit around.

Title: SQL Server Triggers, Stored Procedures


问:
Rails Filterrific - sorting always reverts to created_at desc
I'm trying to implement Filterrific into my Rails app and I diligently followed the instructions on their website, but my default_filter_params always reverts to model's default of created_at desc.

Here is what I have:

```<code>#suggestion.rb

scope :sorted_by, lambda { |sort_option|
  # extract the sort direction from the param value.\
  direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'
  case sort_option.to_s
  when /^created_at_/
    order("suggestions.created_at #{ direction }")
  else
    raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")
  end
}

filterrific(
    default_filter_params: { sorted_by: "created_at_asc" }, #I changed this to ascending order, but it always sorts in descending order
    available_filters: [
        :sorted_by
    ]
)

#suggestions_controller.rb

def index

@filterrific = initialize_filterrific(
    Suggestion,
    params[:filterrific]
) or return
@suggestions = @filterrific.find.page(params[:page])
respond_to do |format|
    format.html
    format.js
end

... #other code
</code>```

Thanks for any help.

答: I just figured out that the code above is correct; it was just a cookie issue. When I cleared my cookies and modified my code, it switches between ascending and descending just fine (I was using Opera as my browser).

Body:
I'm trying to implement Filterrific into my Rails app and I diligently followed the instructions on their website, but my default_filter_params always reverts to model's default of created_at desc.

Here is what I have:

#suggestion.rb

scope :sorted_by, lambda { |sort_option|
  # extract the sort direction from the param value.\
  direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'
  case sort_option.to_s
  when /^created_at_/
    order("suggestions.created_at #{ direction }")
  else
    raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")
  end
}

filterrific(
    default_filter_params: { sorted_by: "created_at_asc" }, #I changed this to ascending order, but it always sorts in descending order
    available_filters: [
        :sorted_by
    ]
)

#suggestions_controller.rb

def index

@filterrific = initialize_filterrific(
    Suggestion,
    params[:filterrific]
) or return
@suggestions = @filterrific.find.page(params[:page])
respond_to do |format|
    format.html
    format.js
end

... #other code

Thanks for any help.


问:
How to do a line selection in fiji (imagej) using specified coords
How to select a line in an image using ImageJ/Fiji by setting its start and end points? As in not drawing it over the image, but inputting the coordinates directly somewhere.</p>

答:
open script editor, select IJ1 macro and then type the code below and then run.

```<code>makeLine(1, 1, 100, 100);
</code>```

This will create a line ROI between (1,1) and (100, 100).

See
https://imagej.nih.gov/ij/developer/macro/functions.html#makeLine

Body:
open script editor, select IJ1 macro and then type the code below and then run.

makeLine(1, 1, 100, 100);

This will create a line ROI between (1,1) and (100, 100).

See
https://imagej.nih.gov/ij/developer/macro/functions.html#makeLine


问:
Jquery validator error mvc 5
I have a view /Consolas/ that when I try to put a new record in my view /Consolas/Agregar/.

When I try to save and validate it with jquery send me to the page /Consolas/Agregar/ and I lose the view of /Console/.

In the Add post I have the following:

```<code>  [HttpPost]
        public ActionResult Agregar(ConsolasDTO consolasDTO)
        {

            if(ModelState.IsValid)
            {
                _consolas.AgregarConsola(consolasDTO);
                return RedirectToAction("Index");
            }
            return View();
        }
</code>```

What could be this error?

答:
Check whether in you page those javascripts exists or not

```<code><script src='@Url.Content("~/Scripts/jquery.validate.min.js")'></script>
<script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")'></script>
<script src='@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")'></script>
</code>```

If not existing and install it from nuget/bower package and check it, then also you have same problem make sure that on submit not closing the pop-model if it is closing,then change the submit type to button and onclick on this submit the form submit through javascript close model after success message

Title: Jquery validator error mvc 5

Body:
I have a view /Consolas/ that when I try to put a new record in my view /Consolas/Agregar/.

When I try to save and validate it with jquery send me to the page /Consolas/Agregar/ and I lose the view of /Console/.

In the Add post I have the following:

  [HttpPost]
        public ActionResult Agregar(ConsolasDTO consolasDTO)
        {

            if(ModelState.IsValid)
            {
                _consolas.AgregarConsola(consolasDTO);
                return RedirectToAction("Index");
            }
            return View();
        }

What could be this error?

Body:
Check whether in you page those javascripts exists or not

<script src='@Url.Content("~/Scripts/jquery.validate.min.js")'></script>
<script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")'></script>
<script src='@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")'></script>

If not existing and install it from nuget/bower package and check it, then also you have same problem make sure that on submit not closing the pop-model if it is closing,then change the submit type to button and onclick on this submit the form submit through javascript close model after success message


问:
Hadoop installation on windows
After extracting hadoop in my C drive I tried to execute the hadoop version command and getting below error. JAVA_HOME is set correctly in my environment variable. Can anybody help on that error ?

```<code>C:\>hadoop version

The system cannot find the path specified.
Error: JAVA_HOME is incorrectly set.
Please update C:\hadoop-2.5.1\conf\hadoop-env.cmd '-Xmx512m' is not recognized as an internal or external command, ooperable program or batch file.
</code>```

答: "@echo on" will help us to trace the error. The message is appearing from hadoop-config.cmd file. Pls copy the C:\Program Files\Java to C:\Java and change the path and try. This will work.</p>

Title: Hadoop installation on windows

Body:
After extracting hadoop in my C drive I tried to execute the hadoop version command and getting below error. JAVA_HOME is set correctly in my environment variable. Can anybody help on that error ?

C:\>hadoop version

The system cannot find the path specified.
Error: JAVA_HOME is incorrectly set.
Please update C:\hadoop-2.5.1\conf\hadoop-env.cmd '-Xmx512m' is not recognized as an internal or external command, ooperable program or batch file.


问:
How to implement regex in if statement in dictionaries
I have the following code snippet:
I want to find the row, with the value is digit (they are integers all the time) on the column/key "Something" and delete the matched row. I have tried it with re.compile()

```<code>for row in list:
    if re.compile("\d") in row["Something"]:
        print(row)
        del (row)
</code>```

How is the right implementation in this case?

答:
don't try remove items from lists while iterating, it doesn't work that well: Remove items from a list while iterating. Anyway, del row has no effect since you're just deleting the name, not the item of the list.

I'm assuming that you want to remove rows if row["Something"] is an integer value.

I would rebuild the list using a list comprehension filtering out when the data is digits only (regex can be avoided here by using isdigit()):

```<code>[row for row in lst if not row["Something"].isdigit()]
</code>```

That doesn't take care of negative numbers, mind. For that you would need a regex-type check like re.match("-?\d+",row["Something"])

Body:
I have the following code snippet:
I want to find the row, with the value is digit (they are integers all the time) on the column/key "Something" and delete the matched row. I have tried it with re.compile()

for row in list:
    if re.compile("\d") in row["Something"]:
        print(row)
        del (row)

How is the right implementation in this case?

Body:
don't try remove items from lists while iterating, it doesn't work that well: Remove items from a list while iterating. Anyway, del row has no effect since you're just deleting the name, not the item of the list.

I'm assuming that you want to remove rows if row["Something"] is an integer value.

I would rebuild the list using a list comprehension filtering out when the data is digits only (regex can be avoided here by using isdigit()):

[row for row in lst if not row["Something"].isdigit()]

That doesn't take care of negative numbers, mind. For that you would need a regex-type check like re.match("-?\d+",row["Something"])