问:
Angular ControlValueAccessor onChanges not updating form control value
Here is the stackblitz of the component/problem reproduced.

I've built a custom input component that:

takes an array of user objects for typeahead filtering

displays your selections as tags

form control value is an array of the selected users users[]

The issue is that adding a result (input-tags.component) does not update the form (app.component) and I can't understand why.

input-tags.component.ts

```<code>addTag(contact: any) {
   ...
   this.onChange(this.tags); // update controller value
}
</code>```

app.component.ts

```<code>this.form.controls['users'].valueChanges.subscribe(data => {
  this.control = data; // always null
});
</code>```

onChanges is called as expected and everything works fine except the form control is always null. Why?

答: The error seems to be in your addTag() function. You're trying to access a parameter that doesn't exist in your typeaheadSource. Change the contact.userId to contact.id and you should be good to go.

Body:
Here is the stackblitz of the component/problem reproduced.

I've built a custom input component that:

takes an array of user objects for typeahead filtering

displays your selections as tags

form control value is an array of the selected users users[]

The issue is that adding a result (input-tags.component) does not update the form (app.component) and I can't understand why.

input-tags.component.ts

addTag(contact: any) {
   ...
   this.onChange(this.tags); // update controller value
}

app.component.ts

this.form.controls['users'].valueChanges.subscribe(data => {
  this.control = data; // always null
});

onChanges is called as expected and everything works fine except the form control is always null. Why?


来源: stackexchange

问:
Loader icon in Bot Framework Webchat
I am using Bot Framework Webchat. There are few user related data which I am posting using back channel post activity through the store option to greet the user.

```<code><ReactWebChat
  activityMiddleware={ activityMiddleware }
  directLine={ window.WebChat.createDirectLine( this.state.token ) }
  store = {this.handleGetStore()}
  styleOptions={styleOptions}
/>
</code>```

handleGetStore returns the store data:

```<code>handleGetStore(){
    const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
        if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
            dispatch({
                type: 'WEB_CHAT/SEND_EVENT',
                payload: {
                    name: 'userDetail',
                    value: this.state.userDetail
                }
            });
        }
        return next(action);
    });
    return store;
}
</code>```

When the connection initiates the loader appears.

After that there is delay of about 3-5 seconds before the welcome message appears and in the meantime the Webchat seems ready for the user.

A slight delay of 3 seconds is acceptable but quite often the delay is upto 10 seconds or more. I understand that this can be slightly improved by using the Always On feature of the App Service and scaling up the plan. Is there a way I can wait for the back channel welcome message to appear and show the loader until then?

Reference: https://github.com/microsoft/BotFramework-WebChat/pull/1866

答:
Unfortunately, the connection status display relies on events received from DirectLineJs and Web Chat does not support customizing its behavior at the moment. That being said, there is a hacky way to accomplish what you're trying to do by dispatching pseudo DirectLine events.

Here are the steps below:

Create a flag that will indicate whether or not the bot has sent a welcome message - received_welcome_message.

When Web Chat dispatches a connection fulfilled event, check the flag
to ensure a welcome message has been received. If the bot has not
sent a welcome message, dispatch the welcome event to the bot and reset the
connection status to fulfilling.

When Web Chat receives an activity
from the bot, check if it is a welcome message. I would recommend
adding a name attribute to message on the bot side to check - await
context.sendActivity({ text: 'Welcome', name: 'welcome'}). If the
activity is a welcome message, dispatch a connection fulfilled event and set the flag to true.

For more details take a look at the code snippets below.

```<code>let received_welcome_message = false;
const store = createStore(
  {},
  ({ dispatch}) => next => action => {

    if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {

      if (!received_welcome_message) {
        dispatch({
          type: 'DIRECT_LINE/CONNECT_FULFILLING'
        });
        dispatch({
          type: 'WEB_CHAT/SEND_EVENT',
          payload: { name: 'webchat/join' }
        });

        return
      }

    } else if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY' && action.payload.activity.name === 'welcome') {
      received_welcome_message = true;
      dispatch({
        type: 'DIRECT_LINE/CONNECT_FULFILLED',
      });
    }
    return next(action);
  }
);
</code>```

Edit

A less hacky approach is to dispatch a post activity pending event when the connection to the bot is fulfilled to mimic the bot sending a welcome message. Note, that the bot is unaware of the mimicked activity. See the code snippet below.

```<code>const store = createStore(
  {},
  ({ dispatch}) => next => action => {
    console.log(action)
    if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
      dispatch({
        type: 'DIRECT_LINE/POST_ACTIVITY_PENDING',
        meta: { method: 'keyboard' },
        payload: {
          activity: {
            from: { role: "bot" },
            text: "Welcome Message",
            textFormat: "plain",
            timestamp: new Date().toString(),
            type: "message"
          }
        }
      })
    }
    return next(action);
  }
</code>```

Hope this helps!

ContentLicense: CC BY-SA 4.0

Title: Loader icon in Bot Framework Webchat

Body:
I am using Bot Framework Webchat. There are few user related data which I am posting using back channel post activity through the store option to greet the user.

<ReactWebChat
  activityMiddleware={ activityMiddleware }
  directLine={ window.WebChat.createDirectLine( this.state.token ) }
  store = {this.handleGetStore()}
  styleOptions={styleOptions}
/>

handleGetStore returns the store data:

handleGetStore(){
    const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
        if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
            dispatch({
                type: 'WEB_CHAT/SEND_EVENT',
                payload: {
                    name: 'userDetail',
                    value: this.state.userDetail
                }
            });
        }
        return next(action);
    });
    return store;
}

When the connection initiates the loader appears.

After that there is delay of about 3-5 seconds before the welcome message appears and in the meantime the Webchat seems ready for the user.

A slight delay of 3 seconds is acceptable but quite often the delay is upto 10 seconds or more. I understand that this can be slightly improved by using the Always On feature of the App Service and scaling up the plan. Is there a way I can wait for the back channel welcome message to appear and show the loader until then?

Reference: https://github.com/microsoft/BotFramework-WebChat/pull/1866

Body:
Unfortunately, the connection status display relies on events received from DirectLineJs and Web Chat does not support customizing its behavior at the moment. That being said, there is a hacky way to accomplish what you're trying to do by dispatching pseudo DirectLine events.

Here are the steps below:

Create a flag that will indicate whether or not the bot has sent a welcome message - received_welcome_message.

When Web Chat dispatches a connection fulfilled event, check the flag
to ensure a welcome message has been received. If the bot has not
sent a welcome message, dispatch the welcome event to the bot and reset the
connection status to fulfilling.

When Web Chat receives an activity
from the bot, check if it is a welcome message. I would recommend
adding a name attribute to message on the bot side to check - await
context.sendActivity({ text: 'Welcome', name: 'welcome'}). If the
activity is a welcome message, dispatch a connection fulfilled event and set the flag to true.

For more details take a look at the code snippets below.

let received_welcome_message = false;
const store = createStore(
  {},
  ({ dispatch}) => next => action => {

    if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {

      if (!received_welcome_message) {
        dispatch({
          type: 'DIRECT_LINE/CONNECT_FULFILLING'
        });
        dispatch({
          type: 'WEB_CHAT/SEND_EVENT',
          payload: { name: 'webchat/join' }
        });

        return
      }

    } else if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY' && action.payload.activity.name === 'welcome') {
      received_welcome_message = true;
      dispatch({
        type: 'DIRECT_LINE/CONNECT_FULFILLED',
      });
    }
    return next(action);
  }
);

Edit

A less hacky approach is to dispatch a post activity pending event when the connection to the bot is fulfilled to mimic the bot sending a welcome message. Note, that the bot is unaware of the mimicked activity. See the code snippet below.

const store = createStore(
  {},
  ({ dispatch}) => next => action => {
    console.log(action)
    if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
      dispatch({
        type: 'DIRECT_LINE/POST_ACTIVITY_PENDING',
        meta: { method: 'keyboard' },
        payload: {
          activity: {
            from: { role: "bot" },
            text: "Welcome Message",
            textFormat: "plain",
            timestamp: new Date().toString(),
            type: "message"
          }
        }
      })
    }
    return next(action);
  }

Hope this helps!


问:
SharePoint Calculated column based on other List data
Possible to set the value of a calcualted column to data from another list? Say I have a lookup column, and based on my selection, another column from that lookup list?

Also, Does the calculated column offer String Contains or begins with operators?

And, side question, Can either of the above be done inside workflow Alert email conditons?

Thanks.

答:
Are you familiar with looking up ID's in a workflow based on values entered in the list?  If not, let me know and we'll break that out a little further.

Assuming you are, you could create a variable named LookupID and put the Row ID of the lookup value from the Lookup list.  Then analyze the variable value and see if it matches one of the IDs that meet your criteria.

If it does, then build the URL using the Dynamic String builder to include the ID.  So the URL would look something like:

http://server/site/Lists/myList/DispForm.aspx?ID=[ListID]

[ListID] is a parameter that you add to the string using the Lookup Field button in the dynamic string builder.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Android Layout Inspector fails with timeout error
When I try to inspect my application's layout in a simulator, by going Tools => Layout Inspector, it always fails with one of the errors:

1.

Error obtaining view hierarchy: There was a timeout error capturing the layout data from the device.
      The device may be too slow, the captured view may be too complex, or the view may contain animations.

Please retry with a simplified view and ensure the device is responsive.

2.

No active windows displayed by com.instabridge.android.dev

The layout is not particularly complex, and it does not contain animations, just map with some views. Android Studio is 3.4.1. How do I fix it? Or how to find the cause of the errors?

答:
Found a really strange solution.

Open your app, go to android home screen, open another app, now use Layout inspector in Android Studio.

It worked and I see my app's view hierarchy.

UPDATE

P.Melch claims that you don't even need to open another app, try just sending your app to background.


问:
How can I serialize DateTime with miliseconds in CsvHelper
I wat to serialize object with DateTime field to csv with milliseconds. How can I do this?

I'm writing csv by this code:

```<code>using (var writer = new StreamWriter(_checksumsFilePath))
using (var csv = new CsvWriter(writer))
{
   csv.WriteRecords(_checksums.Values.ToList());
}
</code>```

And _checksums is Dictionary of this class:

```<code>public class SomeClass
{
    public string Name { get; set; }

    public string val{ get; set; }

    public DateTime lastTime{ get; set; }
}
</code>```

When I write, I see from debugger - in DateTime are some miliseconds but to csv file write only:

```<code>Name;val;lastTime
someName;49BC20DF15E412A64472421E13FE86FF1C5165E18B2AFCCF160D4DC19FE68A14;29.05.2019 16:13:08
</code>```

答:
Thank but I make my own converter from this topic CsvHelper set default custom TypeConverter

I make some little changes

```<code>    public class DateConverter : ITypeConverter
    {
        private readonly string _dateFormat;

        public DateConverter(string dateFormat)
        {
            _dateFormat = dateFormat;
        }

        public object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
        {
            if (!string.IsNullOrEmpty(text))
            {
                DateTime dt;
                DateTime.TryParseExact(text, _dateFormat,
                                       CultureInfo.InvariantCulture,
                                       DateTimeStyles.None,
                                       out dt);
                if (IsValidSqlDateTime(dt))
                {
                    return dt;
                }

            }

            return null;
        }
        public string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
        {
            return ObjectToDateString(value, _dateFormat);
        }

        public string ObjectToDateString(object o, string dateFormat)
        {
            if (o == null) return string.Empty;

            DateTime dt;
            if (o is DateTime)
            {
                dt = (DateTime)o;
                return dt.ToString(dateFormat);
            }
            else
                return string.Empty;
        }
        public bool IsValidSqlDateTime(DateTime? dateTime)
        {
            if (dateTime == null) return true;

            DateTime minValue = DateTime.Parse(System.Data.SqlTypes.SqlDateTime.MinValue.ToString());
            DateTime maxValue = DateTime.Parse(System.Data.SqlTypes.SqlDateTime.MaxValue.ToString());

            if (minValue > dateTime.Value || maxValue < dateTime.Value)
                return false;

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

and use :

```<code>using (var writer = new StreamWriter(_checksumsFilePath))
            using (var csv = new CsvWriter(writer))
            {
                csv.Configuration.TypeConverterCache.RemoveConverter<DateTime>();
                csv.Configuration.TypeConverterCache.RemoveConverter<DateTime?>();
                csv.Configuration.TypeConverterCache.AddConverter<DateTime?>(new DateConverter("MM/dd/yyyy hh:mm:ss.fff"));
                csv.Configuration.TypeConverterCache.AddConverter<DateTime>(new DateConverter("MM/dd/yyyy hh:mm:ss.fff"));
                csv.WriteRecords(_checksums.Values.ToList());
            }
</code>```

Body:
I wat to serialize object with DateTime field to csv with milliseconds. How can I do this?

I'm writing csv by this code:

using (var writer = new StreamWriter(_checksumsFilePath))
using (var csv = new CsvWriter(writer))
{
   csv.WriteRecords(_checksums.Values.ToList());
}

And _checksums is Dictionary of this class:

public class SomeClass
{
    public string Name { get; set; }

    public string val{ get; set; }

    public DateTime lastTime{ get; set; }
}

When I write, I see from debugger - in DateTime are some miliseconds but to csv file write only:

Name;val;lastTime
someName;49BC20DF15E412A64472421E13FE86FF1C5165E18B2AFCCF160D4DC19FE68A14;29.05.2019 16:13:08

Body:
Thank but I make my own converter from this topic CsvHelper set default custom TypeConverter

I make some little changes

    public class DateConverter : ITypeConverter
    {
        private readonly string _dateFormat;

        public DateConverter(string dateFormat)
        {
            _dateFormat = dateFormat;
        }

        public object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
        {
            if (!string.IsNullOrEmpty(text))
            {
                DateTime dt;
                DateTime.TryParseExact(text, _dateFormat,
                                       CultureInfo.InvariantCulture,
                                       DateTimeStyles.None,
                                       out dt);
                if (IsValidSqlDateTime(dt))
                {
                    return dt;
                }

            }

            return null;
        }
        public string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
        {
            return ObjectToDateString(value, _dateFormat);
        }

        public string ObjectToDateString(object o, string dateFormat)
        {
            if (o == null) return string.Empty;

            DateTime dt;
            if (o is DateTime)
            {
                dt = (DateTime)o;
                return dt.ToString(dateFormat);
            }
            else
                return string.Empty;
        }
        public bool IsValidSqlDateTime(DateTime? dateTime)
        {
            if (dateTime == null) return true;

            DateTime minValue = DateTime.Parse(System.Data.SqlTypes.SqlDateTime.MinValue.ToString());
            DateTime maxValue = DateTime.Parse(System.Data.SqlTypes.SqlDateTime.MaxValue.ToString());

            if (minValue > dateTime.Value || maxValue < dateTime.Value)
                return false;

            return true;
        }
    }

and use :

using (var writer = new StreamWriter(_checksumsFilePath))
            using (var csv = new CsvWriter(writer))
            {
                csv.Configuration.TypeConverterCache.RemoveConverter<DateTime>();
                csv.Configuration.TypeConverterCache.RemoveConverter<DateTime?>();
                csv.Configuration.TypeConverterCache.AddConverter<DateTime?>(new DateConverter("MM/dd/yyyy hh:mm:ss.fff"));
                csv.Configuration.TypeConverterCache.AddConverter<DateTime>(new DateConverter("MM/dd/yyyy hh:mm:ss.fff"));
                csv.WriteRecords(_checksums.Values.ToList());
            }


问:
What is a 'Closure'?
I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?</p>

答:
Closure is very easy. We can consider it as follows :
Closure = function + its lexical environment

Consider the following function:

```<code>function init() {
    var name = “Mozilla”;
}
</code>```

What will be the closure in the above case ?
Function init() and variables in its lexical environment ie name.
Closure = init() + name

Consider another function :

```<code>function init() {
    var name = “Mozilla”;
    function displayName(){
        alert(name);
}
displayName();
}
</code>```

What will be the closures here ?
Inner function can access variables of outer function. displayName() can access the variable name declared in the parent function, init(). However, the same local variables in displayName() will be used if they exists.

Closure 1 : init function +  ( name variable + displayName() function) --> lexical scope

Closure 2 : displayName function +  ( name variable ) --> lexical scope

OwnerDisplayName: Ben

Title: What is a 'Closure'?

LastEditorDisplayName: Ben

Body:
Closure is very easy. We can consider it as follows :
Closure = function + its lexical environment

Consider the following function:

function init() {
    var name = “Mozilla”;
}

What will be the closure in the above case ?
Function init() and variables in its lexical environment ie name.
Closure = init() + name

Consider another function :

function init() {
    var name = “Mozilla”;
    function displayName(){
        alert(name);
}
displayName();
}

What will be the closures here ?
Inner function can access variables of outer function. displayName() can access the variable name declared in the parent function, init(). However, the same local variables in displayName() will be used if they exists.

Closure 1 : init function +  ( name variable + displayName() function) --> lexical scope

Closure 2 : displayName function +  ( name variable ) --> lexical scope


问:
Install Wordpress in subdirectory as addon domain and remove install folder in url
I have installed an addon domain and created a subdirectory in the public_html folder where I installed wordpress for the new site. Everything works fine except the I cannot remove the subfolder from the url. I presume chhanging the htaccess file in the addondomain is the problem.

wordpress address url http://addondomain.com/addondomain
site url http://addondomain.com

in index.php in the addondomain folder I changed

```<code>require( dirname( __FILE__ ) . '/wp-blog-header.php' );
</code>```

to

```<code>require( dirname( __FILE__ ) . '/addondomain/wp-blog-header.php' );
</code>```

my htaccess file in the addon directory

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /addondomain/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /addondomain/index.php [L]
</IfModule>
</code>```

The htaccess file in the main public_html directory (contains files of another domain)

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

All I want is to remove the wordpress installation folder from the url, but I have a domain and subdomain and two wp installations.

答:
Remove /addondomain from the last rule in .htaccess file in the addon directory (RewriteBase stays as before).</p>

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /addondomain/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

Body:
I have installed an addon domain and created a subdirectory in the public_html folder where I installed wordpress for the new site. Everything works fine except the I cannot remove the subfolder from the url. I presume chhanging the htaccess file in the addondomain is the problem.

wordpress address url http://addondomain.com/addondomain
site url http://addondomain.com

in index.php in the addondomain folder I changed

require( dirname( __FILE__ ) . '/wp-blog-header.php' );

to

require( dirname( __FILE__ ) . '/addondomain/wp-blog-header.php' );

my htaccess file in the addon directory

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /addondomain/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /addondomain/index.php [L]
</IfModule>

The htaccess file in the main public_html directory (contains files of another domain)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

All I want is to remove the wordpress installation folder from the url, but I have a domain and subdomain and two wp installations.

Body:
Remove /addondomain from the last rule in .htaccess file in the addon directory (RewriteBase stays as before).

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /addondomain/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


问:
Angular HTTP Res JSON Data print in html
Below is the HTTP get request response. how can i print same in view using *ngFor . iam trying to print single object print like data[0].value1 in console. it returns undefined. inside data array 3 JSON Objects. and some arrays also

Any help much appreciated...

```<code>getEmp(){
    this.EmpService.getAccounts().subscribe((res : any[])=>{
      this.products = JSON.stringify(res);
  });
</code>```

.

```<code>{
        "data": [
            {
                "value1": "3546786908765432",
                "category": "Clothing (Brand)",
                "category_list": [
                    {
                        "id": "001",
                        "name": "Clothing (Brand)"
                    },
                    {
                        "id": "39324324230",
                        "name": "Boutique Store"
                    },
                    {
                        "id": "12342324324",
                        "name": "Website"
                    }
                ],
                "name": "wqeqws",
                "id": "qwsqwsq  w",
                "tasks": [
                    "ANALYZE",
                    "ADVERTISE",
                    "MODERATE",
                    "CREATE_CONTENT",
                    "MANAGE"
                ]
            },
            {
                "value1": "111-9=-09876543",
                "category": "Education",
                "category_list": [
                    {
                        "id": "23456",
                        "name": "Education"
                    }
                ],
                "name": "sdcsfcsdfvsd",
                "id": "111111111111",
                "tasks": [
                    "ANALYZE",
                    "ADVERTISE",
                    "MODERATE",
                    "CREATE_CONTENT",
                    "MANAGE"
                ]
            }
    ],
        "paging": {
            "cursors": {
                "before": "dsfsds",
                "after": "sdfsfs"
            }
        }
    }
</code>```

答:
```<code>this.products = res.data;
</code>```

In your page

```<code>< *ngFor="let item of products >
</code>```

Body:
Below is the HTTP get request response. how can i print same in view using *ngFor . iam trying to print single object print like data[0].value1 in console. it returns undefined. inside data array 3 JSON Objects. and some arrays also

Any help much appreciated...

getEmp(){
    this.EmpService.getAccounts().subscribe((res : any[])=>{
      this.products = JSON.stringify(res);
  });

.

{
        "data": [
            {
                "value1": "3546786908765432",
                "category": "Clothing (Brand)",
                "category_list": [
                    {
                        "id": "001",
                        "name": "Clothing (Brand)"
                    },
                    {
                        "id": "39324324230",
                        "name": "Boutique Store"
                    },
                    {
                        "id": "12342324324",
                        "name": "Website"
                    }
                ],
                "name": "wqeqws",
                "id": "qwsqwsq  w",
                "tasks": [
                    "ANALYZE",
                    "ADVERTISE",
                    "MODERATE",
                    "CREATE_CONTENT",
                    "MANAGE"
                ]
            },
            {
                "value1": "111-9=-09876543",
                "category": "Education",
                "category_list": [
                    {
                        "id": "23456",
                        "name": "Education"
                    }
                ],
                "name": "sdcsfcsdfvsd",
                "id": "111111111111",
                "tasks": [
                    "ANALYZE",
                    "ADVERTISE",
                    "MODERATE",
                    "CREATE_CONTENT",
                    "MANAGE"
                ]
            }
    ],
        "paging": {
            "cursors": {
                "before": "dsfsds",
                "after": "sdfsfs"
            }
        }
    }

Body:
this.products = res.data;

In your page

< *ngFor="let item of products >


问:
datepicker doesn't save selected date
When you select the day, month and year, always save today's time. this is what i tried

```<code>private DatePicker.OnDateChangedListener dateSetListener = new DatePicker.OnDateChangedListener() {
       public void onDateChanged(DatePicker view, int año, int mes,
                                 int dia) {
           isDateChanged = true;
       }
   };
private void AgregarCumpleaños() {
       if (isDateChanged = false)
       {
           Toast.makeText(this, "Elija su cumpleaños", Toast.LENGTH_SHORT).show();
       }
       else
       {
           datePicker = findViewById(R.id.cumpleano);
           final Calendar ca = Calendar.getInstance();
           int dia =  ca.get(Calendar.DAY_OF_MONTH);
           int mes = ca.get(Calendar.MONTH);
           int año = ca.get(Calendar.YEAR);

           final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM");
           saveCurrentDate = dateFormatter.format(ca.getTime());
</code>```

I need to save the selected month and day or save it in its variables

答:
I don't see any implement for OnDateChangedListener

```<code>DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {

                @Override
                public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
                    Log.d("Date", "Year=" + year + " Month=" + (month + 1) + " day=" + dayOfMonth);

                }
            });
</code>```

Title: datepicker doesn't save selected date

Body:
When you select the day, month and year, always save today's time. this is what i tried

private DatePicker.OnDateChangedListener dateSetListener = new DatePicker.OnDateChangedListener() {
       public void onDateChanged(DatePicker view, int año, int mes,
                                 int dia) {
           isDateChanged = true;
       }
   };
private void AgregarCumpleaños() {
       if (isDateChanged = false)
       {
           Toast.makeText(this, "Elija su cumpleaños", Toast.LENGTH_SHORT).show();
       }
       else
       {
           datePicker = findViewById(R.id.cumpleano);
           final Calendar ca = Calendar.getInstance();
           int dia =  ca.get(Calendar.DAY_OF_MONTH);
           int mes = ca.get(Calendar.MONTH);
           int año = ca.get(Calendar.YEAR);

           final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM");
           saveCurrentDate = dateFormatter.format(ca.getTime());

I need to save the selected month and day or save it in its variables

Body:
I don't see any implement for OnDateChangedListener

DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {

                @Override
                public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
                    Log.d("Date", "Year=" + year + " Month=" + (month + 1) + " day=" + dayOfMonth);

                }
            });


问:
JSF 2 OpenJPA 2 Glassfish 3.1 WEB9031 Error
I got this error which according to Apache Support is an issue relating with Glassfish rather than OpenJPA:

```<code>java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource [org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped
</code>```

The stacktrace is:

```<code>Caused by: java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource [org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1410)
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1368)
    at com.ckd.model.BookModel.pcNewObjectIdInstance(BookModel.java)
    at org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:138)
    at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1693)
    at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1643)
    ... 112 more
</code>```

Has anyone come across this before and how to resolve it? I have been stuck on this issue for the last several days.

Another of my post related to this issue can be found here: JSF 2: h:link and getrowdata.

答:
The above error relates to a problem with the OpenJPA enhancer. When you execute Sun's JDK the OpenJPA's dynamic enhancer starts by default. This action, in turn, stuffs up Glassfish's classloader class - hence, the WEB9031 error.

For those who experience this same issue, a simple workaround is to do the enhancement at build time - which I did in ANT with org.apache.openjpa.ant.PCEnhancerTask - and add this property to your persistence.xml to shut off the dynamic enhancer: <property name="openjpa.DynamicEnhancementAgent" value="false"/>.

Also, it wouldn't hurt to throw this in your persistence.xml as well <property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />.

Body:
I got this error which according to Apache Support is an issue relating with Glassfish rather than OpenJPA:

java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource [org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped

The stacktrace is:

Caused by: java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource [org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1410)
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1368)
    at com.ckd.model.BookModel.pcNewObjectIdInstance(BookModel.java)
    at org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:138)
    at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1693)
    at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1643)
    ... 112 more

Has anyone come across this before and how to resolve it? I have been stuck on this issue for the last several days.

Another of my post related to this issue can be found here: JSF 2: h:link and getrowdata.


问:
passing image from collectionViewCell which is located tableviewCell
I ask for help with determining the right approach

when I click on the picture I need to pass text and her to new VC, but the problem is that the project has a great depth struct

the cell lies in the collectionView, which is in the tableViewCell

How do I properly implement the transfer?
(the number of cells is generated automatically)

Another complication is that the code of the cell with which I work lies in another cell.

those. the transfer of information must also be written in it.

```<code>import UIKit
import moa

class RealPhotoInfoTableViewCell: UITableViewCell {

    @IBOutlet private weak var MyCollection: UICollectionView!

    var model: RealPhoto!

    func setCollectionViewDataSourceDelegate(dataSourceDelegate: UICollectionViewDataSource & UICollectionViewDelegate, forRow row: Int) {
        MyCollection.delegate = self
        MyCollection.dataSource = self
        MyCollection.reloadData()
    }
}

extension RealPhotoInfoTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(model?.data.count as Any)
        return model?.data.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RPhotoCell", for: indexPath) as! RealPhotoCollectionViewCell

        cell.realPhotoImage.moa.url = model?.data[indexPath.row].photo

        return cell
    }
}
</code>```

答:
You can use delegate protocol in that case. You can implement that protocol. Please find following sample code for that.</p>

```<code>protocol ImageSelectionDelegate {
    func imageClicked(imageURL: String)
}

//Class A
class A : ImageSelectionDelegate{
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //your existing code
        cell.delegate = self
    }
    //Implement that protocol
    func imageClicked(imageURL: String){
        //You will get url for tapped image
    }
}

class RealPhotoInfoTableViewCell{
    weak var delegate : ImageSelectionDelegate? = nil
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        delegate.imageClicked(model?.data[indexPath.item].photo)
    }
}
</code>```

Body:
I ask for help with determining the right approach

when I click on the picture I need to pass text and her to new VC, but the problem is that the project has a great depth struct

the cell lies in the collectionView, which is in the tableViewCell

How do I properly implement the transfer?
(the number of cells is generated automatically)

Another complication is that the code of the cell with which I work lies in another cell.

those. the transfer of information must also be written in it.

import UIKit
import moa

class RealPhotoInfoTableViewCell: UITableViewCell {

    @IBOutlet private weak var MyCollection: UICollectionView!

    var model: RealPhoto!

    func setCollectionViewDataSourceDelegate(dataSourceDelegate: UICollectionViewDataSource & UICollectionViewDelegate, forRow row: Int) {
        MyCollection.delegate = self
        MyCollection.dataSource = self
        MyCollection.reloadData()
    }
}

extension RealPhotoInfoTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(model?.data.count as Any)
        return model?.data.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RPhotoCell", for: indexPath) as! RealPhotoCollectionViewCell

        cell.realPhotoImage.moa.url = model?.data[indexPath.row].photo

        return cell
    }
}

Body:
You can use delegate protocol in that case. You can implement that protocol. Please find following sample code for that.

protocol ImageSelectionDelegate {
    func imageClicked(imageURL: String)
}

//Class A
class A : ImageSelectionDelegate{
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //your existing code
        cell.delegate = self
    }
    //Implement that protocol
    func imageClicked(imageURL: String){
        //You will get url for tapped image
    }
}

class RealPhotoInfoTableViewCell{
    weak var delegate : ImageSelectionDelegate? = nil
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        delegate.imageClicked(model?.data[indexPath.item].photo)
    }
}


问:
Type error when using Array.find with a custom type
I have an object containing a list of supported languages. I'd like to find the user's browser contains one of the languages:

const userLanguage = browserLanguages.find(language => !!supported[language]);
```

<p>However, I'm getting the following error: <code>Element implicitly has an 'any' type because type 'LanguageName' has no index signature.</code></p>

<p><code>LanguageName</code> is a type I've created for my <code>supported</code> object:</p>

<pre class="lang-js prettyprint-override"><code>type LanguageName = {
  [language in SupportedLanguages]: string;
};
</code>```

And supportedLanguages is a type containing all languages supported by our app:

type SupportedLanguages = 'en' | 'es';
```

DEMO

答:
I think you'll get the best results by explicitly invoking the overload of Array.find() which treats the callback as a user-defined type guard.  Note that you have to do this via manual annotation; the compiler does not currently infer type guards from function return values.

There are multiple ways to do this; here's one:

```<code>// make an explicit type guard for SupportedLanguages
function supportedLanguageGuard<T extends keyof any>(
  x: T
): x is T & SupportedLanguages {
  return !!(supported as any)[x];
}

// use it
const userLanguage: SupportedLanguages | undefined = browserLanguages.find(
  supportedLanguageGuard
); // okay
</code>```

I went this way because it should work whether or not you narrow browserLanguages to keep track of the literals inside it

```<code>const browserLanguages = ["fr", "es"] as const; // TS3.4+
</code>```

Okay, hope that helps.  Good luck!

Link to code

Body:
I have an object containing a list of supported languages. I'd like to find the user's browser contains one of the languages:

const userLanguage = browserLanguages.find(language => !!supported[language]);

However, I'm getting the following error: Element implicitly has an 'any' type because type 'LanguageName' has no index signature.

LanguageName is a type I've created for my supported object:

type LanguageName = {
  [language in SupportedLanguages]: string;
};

And supportedLanguages is a type containing all languages supported by our app:

type SupportedLanguages = 'en' | 'es';

DEMO

Body:
I think you'll get the best results by explicitly invoking the overload of Array.find() which treats the callback as a user-defined type guard.  Note that you have to do this via manual annotation; the compiler does not currently infer type guards from function return values.

There are multiple ways to do this; here's one:

// make an explicit type guard for SupportedLanguages
function supportedLanguageGuard<T extends keyof any>(
  x: T
): x is T & SupportedLanguages {
  return !!(supported as any)[x];
}

// use it
const userLanguage: SupportedLanguages | undefined = browserLanguages.find(
  supportedLanguageGuard
); // okay

I went this way because it should work whether or not you narrow browserLanguages to keep track of the literals inside it

const browserLanguages = ["fr", "es"] as const; // TS3.4+

Okay, hope that helps.  Good luck!

<a href="https://typescript-play.js.org/#code/C4TwDgpgBAygrmMB7ATsCATAMgQwHYDmcOBEAzlALxQBEEeNUAPreTQNwBQnokUuhYqQByOALbRqAbygBtADb4iJaAEs8sBMjSYBy0mQC6ALihlgKdQSgBfLpwDGSPObNbU6DKb1CIoiVRQUpxQUPSmNACihPKqZAAWNAA0IWFkEZFkYDgAj0jyNJx23E4uwFAARihIAO5kECg+KhTUsjQAZijJrGQ0hvbtcHgOwKrObogeukq+AOLEKBgAPAAqYQAe6HgYFADWECBI7VD4IAB8ABSp66YrnACUputQcVBrAGSakzrYM81BqRQEGAcBQGgAhOCLmR3D8ThRTvdZOt+kUSs5XHB6o0-qRTPBvp4mgZmFAhhgIO11JhAlVatjieQAHRU7ZXUIwwnTQQqeY4RYPeylMj5CBM+RIAgXLENRn3LhAA" rel="nofollow noreferrer">Link to code


问:
File storage issue
I have recently started to work with laravel voyager admin package, and I have an issue about file upload mechanism.

Firstly, I have create a folder on media menu "contacts":
https://i.imgur.com/fkaVqBz.png

After that, I have made a controller to deal with the contact form and which they can upload their curriculum vitae:
https://i.imgur.com/ckCCSOH.png

In my ContactController, I have made some validations regarding the uploaded file, and some modifications on the name of the uploaded file if the user send the post request:

```<code><?php

namespace App\Http\Controllers;

use App\Contact;
use Illuminate\Http\Request;
use App\Rules\Captcha;

class ContactController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function PostContact(Request $request) {
        //
        $this->validate($request, [
            'nom' => 'required|min:2|max:50',
            'prenom' => 'required|min:2|max:50',
            'email' => 'required|email',
            'organisme' => 'required',
            'fonction' => 'required',
            'pays' => 'required',
            'ville' => 'required',
            'telephone' => 'required|numeric|',
            'objet' => 'required',
            'fichier' => 'sometimes|nullable|mimes:doc,docx,pdf',
            'g-recaptcha-response' => new Captcha(),
            'message' => 'required|min:10']);

        $contact = new Contact;

        $contact->nom = $request->input('nom');
        $contact->prenom = $request->input('prenom');
        $contact->organisme = $request->input('organisme');
        $contact->fonction = $request->input('fonction');
        $contact->pays = $request->input('pays');
        $contact->ville = $request->input('ville');
        $contact->email = $request->input('email');
        $contact->telephone = $request->input('telephone');
        $contact->objet = $request->objet;

        if ($request->hasFile('fichier')) {

            $filenameWithExt = $request->file('fichier')->getClientOriginalName();

            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);

            $extension = $request->file('fichier')->getClientOriginalExtension();

            $fileNameToStore = $filename.'_'.time().'.'.$extension;

            $path = $request->file('fichier')->storeAs('contacts', $fileNameToStore);

            $contact->fichier = $path;
        }

        $contact->message = $request->input('message');

        $contact->save();

        return redirect('contact')->with('status', 'Votre message a été envoyé avec succès !!');
    }
}
</code>```

The CV file is successfully uploaded but not in the right destination, and contacts folder is creation in storage\app:
https://i.imgur.com/YPpzfCD.png
https://i.imgur.com/KV2CNXo.png

When I create a new contact via voyager admin panel (contact bread)
https://i.imgur.com/Q3GBom8.png, the file uploaded goes into public\contacts\month-year-folder (May2019)\
and this is what I hope to do also using my contact form.
https://i.imgur.com/bFKSKzq.png

Can someone help me solving this issue?

PS: the command php artisan storage:link
indicate that the "public/storage" directory already exists.

Also, I will show any file content if needed

Thanks.

答:
Regarding @Leonardo Rossi's comment, I have resolved this issue by adding this into my config/filesystem.php:

```<code>        'contacts' => [
        'driver' => 'local',
        'root' => storage_path('app/public/contacts'),
        'url' => '/contacts',
        'visibility' => 'public',
    ],
</code>```

and in the controller, because the file was stored in the correct folder, I have tried to get the path and then store it in database field (fichier) like that:

```<code>        if ($request->hasFile('fichier')) {

        $filenameWithExt = $request->file('fichier')->getClientOriginalName();

        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);

        $extension = $request->file('fichier')->getClientOriginalExtension();

        $fileNameToStore = $filename.'_'.time().'.'.$extension;

        /* $path = $request->file('fichier')->storeAs(public_path('contacts'), $fileNameToStore); */
        $now = new \DateTime('now'); //Datetime
        $monthNum = $now->format('m');
        $dateObj   = DateTime::createFromFormat('!m', $monthNum);
        $monthName = $dateObj->format('F'); // Month
        $year = $now->format('Y'); // Year

        $monthYear = $monthName.$year;

        Storage::disk('contacts')->putFileAs($monthYear, $request->file('fichier'), $fileNameToStore);

        $path = Storage::disk('contacts')->url($monthYear.'/'.$fileNameToStore);

        $contact->fichier = $path;
    }
</code>```

You can also have an idea of how can you create a folder using datetime elements (Month+Year) for my case.

Thanks.

Title: File storage issue

Body:
I have recently started to work with laravel voyager admin package, and I have an issue about file upload mechanism.

Firstly, I have create a folder on media menu "contacts":
https://i.imgur.com/fkaVqBz.png

After that, I have made a controller to deal with the contact form and which they can upload their curriculum vitae:
https://i.imgur.com/ckCCSOH.png

In my ContactController, I have made some validations regarding the uploaded file, and some modifications on the name of the uploaded file if the user send the post request:

<?php

namespace App\Http\Controllers;

use App\Contact;
use Illuminate\Http\Request;
use App\Rules\Captcha;

class ContactController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function PostContact(Request $request) {
        //
        $this->validate($request, [
            'nom' => 'required|min:2|max:50',
            'prenom' => 'required|min:2|max:50',
            'email' => 'required|email',
            'organisme' => 'required',
            'fonction' => 'required',
            'pays' => 'required',
            'ville' => 'required',
            'telephone' => 'required|numeric|',
            'objet' => 'required',
            'fichier' => 'sometimes|nullable|mimes:doc,docx,pdf',
            'g-recaptcha-response' => new Captcha(),
            'message' => 'required|min:10']);

        $contact = new Contact;

        $contact->nom = $request->input('nom');
        $contact->prenom = $request->input('prenom');
        $contact->organisme = $request->input('organisme');
        $contact->fonction = $request->input('fonction');
        $contact->pays = $request->input('pays');
        $contact->ville = $request->input('ville');
        $contact->email = $request->input('email');
        $contact->telephone = $request->input('telephone');
        $contact->objet = $request->objet;

        if ($request->hasFile('fichier')) {

            $filenameWithExt = $request->file('fichier')->getClientOriginalName();

            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);

            $extension = $request->file('fichier')->getClientOriginalExtension();

            $fileNameToStore = $filename.'_'.time().'.'.$extension;

            $path = $request->file('fichier')->storeAs('contacts', $fileNameToStore);

            $contact->fichier = $path;
        }

        $contact->message = $request->input('message');

        $contact->save();

        return redirect('contact')->with('status', 'Votre message a été envoyé avec succès !!');
    }
}

The CV file is successfully uploaded but not in the right destination, and contacts folder is creation in storage\app:
https://i.imgur.com/YPpzfCD.png
https://i.imgur.com/KV2CNXo.png

When I create a new contact via voyager admin panel (contact bread)
https://i.imgur.com/Q3GBom8.png, the file uploaded goes into public\contacts\month-year-folder (May2019)\
and this is what I hope to do also using my contact form.
https://i.imgur.com/bFKSKzq.png

Can someone help me solving this issue?

PS: the command php artisan storage:link
indicate that the "public/storage" directory already exists.

Also, I will show any file content if needed

Thanks.

Body:
Regarding @Leonardo Rossi's comment, I have resolved this issue by adding this into my config/filesystem.php:

        'contacts' => [
        'driver' => 'local',
        'root' => storage_path('app/public/contacts'),
        'url' => '/contacts',
        'visibility' => 'public',
    ],

and in the controller, because the file was stored in the correct folder, I have tried to get the path and then store it in database field (fichier) like that:

        if ($request->hasFile('fichier')) {

        $filenameWithExt = $request->file('fichier')->getClientOriginalName();

        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);

        $extension = $request->file('fichier')->getClientOriginalExtension();

        $fileNameToStore = $filename.'_'.time().'.'.$extension;

        /* $path = $request->file('fichier')->storeAs(public_path('contacts'), $fileNameToStore); */
        $now = new \DateTime('now'); //Datetime
        $monthNum = $now->format('m');
        $dateObj   = DateTime::createFromFormat('!m', $monthNum);
        $monthName = $dateObj->format('F'); // Month
        $year = $now->format('Y'); // Year

        $monthYear = $monthName.$year;

        Storage::disk('contacts')->putFileAs($monthYear, $request->file('fichier'), $fileNameToStore);

        $path = Storage::disk('contacts')->url($monthYear.'/'.$fileNameToStore);

        $contact->fichier = $path;
    }

You can also have an idea of how can you create a folder using datetime elements (Month+Year) for my case.

Thanks.


问:
Error when loading a custom model with spacy
I'm trying to load a custom model called 'ru2' into spacy (for npl processing).

it can be found there: https://github.com/buriy/spacy-ru

The problem is when I call the function

nlp = spacy.load('ru2')
doc = nlp(text)
```

<p>I see the error </p>

```C:\ProgramData\Anaconda3\lib\importlib\_bootstrap.py:205: RuntimeWarning: spacy.tokens.span.Span size changed, may indicate binary incompatibility. Expected 72 from C header, got 80 from PyObject
  return f(*args, **kwds)
Traceback (most recent call last):
  File "C://.../nlp/src/ie/main.py", line 125, in <module>
    main(examp_dict['Poroshenko'])
  File "C://.../nlp/src/ie/main.py", line 92, in main
    nlp = spacy.load('ru2')
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\__init__.py", line 27, in load
    return util.load_model(name, **overrides)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 133, in load_model
    return load_model_from_path(Path(name), **overrides)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 173, in load_model_from_path
    return nlp.from_disk(model_path)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\language.py", line 791, in from_disk
    util.from_disk(path, deserializers, exclude)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 630, in from_disk
    reader(path / key)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\language.py", line 781, in <lambda>
    deserializers["tokenizer"] = lambda p: self.tokenizer.from_disk(p, exclude=["vocab"])
  File "tokenizer.pyx", line 391, in spacy.tokenizer.Tokenizer.from_disk
  File "tokenizer.pyx", line 432, in spacy.tokenizer.Tokenizer.from_bytes
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 606, in from_bytes
    msg = srsly.msgpack_loads(bytes_data)
  File "C:\ProgramData\Anaconda3\lib\site-packages\srsly\_msgpack_api.py", line 29, in msgpack_loads
    msg = msgpack.loads(data, raw=False, use_list=use_list)
  File "C:\ProgramData\Anaconda3\lib\site-packages\srsly\msgpack\__init__.py", line 60, in unpackb
    return _unpackb(packed, **kwargs)
  File "_unpacker.pyx", line 191, in srsly.msgpack._unpacker.unpackb
TypeError: unhashable type: 'list'
```

I was searching for similar questions in the Internet:

https://github.com/explosion/spaCy/issues/2715

https://spacy.io/usage#unhashable-list

But non of those solutions work for me.

I use

msgpack==0.5.6 (even downgraded as suggested in the link above)

spacy==2.1.4

答: It might be because the version number of SpaCy used to generate your model is not the same as the version of SpaCy you have installed. (I don't know of course, just mentioning it in case it helps.)</p>

Body:
I'm trying to load a custom model called 'ru2' into spacy (for npl processing).

it can be found there: https://github.com/buriy/spacy-ru

The problem is when I call the function

nlp = spacy.load('ru2')
doc = nlp(text)

I see the error

C:\ProgramData\Anaconda3\lib\importlib\_bootstrap.py:205: RuntimeWarning: spacy.tokens.span.Span size changed, may indicate binary incompatibility. Expected 72 from C header, got 80 from PyObject
  return f(*args, **kwds)
Traceback (most recent call last):
  File "C://.../nlp/src/ie/main.py", line 125, in <module>
    main(examp_dict['Poroshenko'])
  File "C://.../nlp/src/ie/main.py", line 92, in main
    nlp = spacy.load('ru2')
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\__init__.py", line 27, in load
    return util.load_model(name, **overrides)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 133, in load_model
    return load_model_from_path(Path(name), **overrides)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 173, in load_model_from_path
    return nlp.from_disk(model_path)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\language.py", line 791, in from_disk
    util.from_disk(path, deserializers, exclude)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 630, in from_disk
    reader(path / key)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\language.py", line 781, in <lambda>
    deserializers["tokenizer"] = lambda p: self.tokenizer.from_disk(p, exclude=["vocab"])
  File "tokenizer.pyx", line 391, in spacy.tokenizer.Tokenizer.from_disk
  File "tokenizer.pyx", line 432, in spacy.tokenizer.Tokenizer.from_bytes
  File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 606, in from_bytes
    msg = srsly.msgpack_loads(bytes_data)
  File "C:\ProgramData\Anaconda3\lib\site-packages\srsly\_msgpack_api.py", line 29, in msgpack_loads
    msg = msgpack.loads(data, raw=False, use_list=use_list)
  File "C:\ProgramData\Anaconda3\lib\site-packages\srsly\msgpack\__init__.py", line 60, in unpackb
    return _unpackb(packed, **kwargs)
  File "_unpacker.pyx", line 191, in srsly.msgpack._unpacker.unpackb
TypeError: unhashable type: 'list'

I was searching for similar questions in the Internet:

https://github.com/explosion/spaCy/issues/2715

https://spacy.io/usage#unhashable-list

But non of those solutions work for me.

I use

msgpack==0.5.6 (even downgraded as suggested in the link above)

spacy==2.1.4


问:
Object value not changing in a for loop
I have this code :

```<code> for (var item in oldMenu) {
   var newid = newID();
   oldMenu[item].nodeId = newid;
   db.selectDatas('pages','',{'datas.menu': item.nodeId},null,null,null,null, function(err1, page) {
     if(page.length > 0) {
       var oldPage = page[0].datas;
         oldPage.menu = newid;
       }
   });
</code>```

Sample data of the oldMenu variable :

```<code>[
  {
    "nodeId": "e9c2b2a4-4583-eff9-d0de-bc4d7d2bf50f",
    "nodeText": "Présentation",
    "hasChildren": true,
    "count": 0,
    "expanded": true
  },
  {
    "nodeId": "be225e39-9848-913a-1b18-0f3995e2199a",
    "nodeText": "Installation",
    "hasChildren": true,
    "expanded": true
  },
  {
    "nodeId": "aa41e413-be60-460f-dbbe-84284245414b",
    "nodeText": "Premier lancement"
  }
]
</code>```

The problem is that the items not changing nodeId field is not changing with the new value as expected, I'm missing something?

Thanks for helping

答:
You're using item.nodeId in the selectDatas query when it should be oldMenu[item].nodeId. However you overwrite that value in the line above, so it will probably return 0 results.

Here's what I believe the code should be:

```<code>for (var item of oldMenu) {
   var oldId = item.nodeId;

   var newid = newID();
   item.nodeId = newid;

   db.selectDatas('pages','',{'datas.menu': oldId},null,null,null,null, function(err1, page) {
     if(page.length > 0) {
       var oldPage = page[0].datas;
         oldPage.menu = newid;
       }
   });
}
</code>```

Title: Object value not changing in a for loop

Body:
I have this code :

 for (var item in oldMenu) {
   var newid = newID();
   oldMenu[item].nodeId = newid;
   db.selectDatas('pages','',{'datas.menu': item.nodeId},null,null,null,null, function(err1, page) {
     if(page.length > 0) {
       var oldPage = page[0].datas;
         oldPage.menu = newid;
       }
   });

Sample data of the oldMenu variable :

[
  {
    "nodeId": "e9c2b2a4-4583-eff9-d0de-bc4d7d2bf50f",
    "nodeText": "Présentation",
    "hasChildren": true,
    "count": 0,
    "expanded": true
  },
  {
    "nodeId": "be225e39-9848-913a-1b18-0f3995e2199a",
    "nodeText": "Installation",
    "hasChildren": true,
    "expanded": true
  },
  {
    "nodeId": "aa41e413-be60-460f-dbbe-84284245414b",
    "nodeText": "Premier lancement"
  }
]

The problem is that the items not changing nodeId field is not changing with the new value as expected, I'm missing something?

Thanks for helping

Body:
You're using item.nodeId in the selectDatas query when it should be oldMenu[item].nodeId. However you overwrite that value in the line above, so it will probably return 0 results.

Here's what I believe the code should be:

for (var item of oldMenu) {
   var oldId = item.nodeId;

   var newid = newID();
   item.nodeId = newid;

   db.selectDatas('pages','',{'datas.menu': oldId},null,null,null,null, function(err1, page) {
     if(page.length > 0) {
       var oldPage = page[0].datas;
         oldPage.menu = newid;
       }
   });
}


问:
Parsing and updating markdown file with Python
I'm creating a script that will traverse a markdown file and update the any image tags from

```<code>![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif)
</code>```

to

```<code>![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif?alt-text="Daffy Duck")
</code>```

I'm new to Python, so I'm unsure about syntax and my approach, but my current thinking is to create an new empty string, traverse the original markdown line by line, if an image tag is detected splice the alt text to the correct location and add the lines to the new markdown string. The code I have so far looks like:

```<code>import markdown
from markdown.treeprocessors import Treeprocessor
from markdown.extensions import Extension

originalMarkdown = '''
## New Article
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pretium nunc ligula. Quisque bibendum vel lectus sed pulvinar. Phasellus id magna ac arcu iaculis facilisis. Curabitur tincidunt sed ipsum vel lacinia. Nulla et semper urna. Quisque ultrices hendrerit magna nec tempor.

![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif)
Quisque accumsan sem mi. Nunc orci justo, laoreet vel metus nec, interdum euismod ipsum.
![Bugs Bunny](http://www.nationalnannies.com/wp-content/uploads/2012/03/bugsbunny.png)
 Suspendisse augue odio, pharetra ac erat eget, volutpat ornare velit. Sed ac luctus quam. Sed id mauris erat. Duis lacinia faucibus metus, nec vehicula metus consectetur eu.
'''

updatedMarkdown = ""

# First create the treeprocessor
class AltTextExtractor(Treeprocessor):
    def run(self, doc):
        "Find all alt_text and append to markdown.alt_text. "
        self.markdown.alt_text = []
        for image in doc.findall('.//img'):
         self.markdown.alt_text.append(image.get('alt'))

# Then traverse the markdown file and concatenate the alt text to the end of any image tags
class ImageTagUpdater(Treeprocessor):
    def run(self, doc):
      # Set a counter
      count = 0
      # Go through markdown file line by line
        for line in doc:
          # if line is an image tag
          if line > ('.//img'):
            # grab the array of the alt text
            img_ext = ImgExtractor(md)
            # find the second to last character of the line
            location = len(line) - 1
            # insert the alt text
            line += line[location] + '?' +  '"' + img_ext[count] +  '"'
            # add line to new markdown file
        updatedMarkdownadd.add(line)
</code>```

The above code is pseudo code. I'm able to successfully extract the strings I need from the original file but I'm unable to concatenate those strings to their respective image tags and update the original file.

答:
Provided your files aren't huge, it might be easier to overwrite the file, rather than try to wedge little bits in here or there.

```<code>orig = '![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif)'
new = '![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif?alt-text="Daffy Duck")'

with open(filename, 'r') as f:
    text = f.readlines()
    new_text = "\n".join([line if line != orig else new for line in text])

with open(filename, 'w') as f:
    f.write(new_text)
</code>```

You could also use regex re.sub, but I suppose its a matter of preference.

Body:
I'm creating a script that will traverse a markdown file and update the any image tags from

![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif)

to

![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif?alt-text="Daffy Duck")

I'm new to Python, so I'm unsure about syntax and my approach, but my current thinking is to create an new empty string, traverse the original markdown line by line, if an image tag is detected splice the alt text to the correct location and add the lines to the new markdown string. The code I have so far looks like:

import markdown
from markdown.treeprocessors import Treeprocessor
from markdown.extensions import Extension

originalMarkdown = '''
## New Article
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pretium nunc ligula. Quisque bibendum vel lectus sed pulvinar. Phasellus id magna ac arcu iaculis facilisis. Curabitur tincidunt sed ipsum vel lacinia. Nulla et semper urna. Quisque ultrices hendrerit magna nec tempor.

![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif)
Quisque accumsan sem mi. Nunc orci justo, laoreet vel metus nec, interdum euismod ipsum.
![Bugs Bunny](http://www.nationalnannies.com/wp-content/uploads/2012/03/bugsbunny.png)
 Suspendisse augue odio, pharetra ac erat eget, volutpat ornare velit. Sed ac luctus quam. Sed id mauris erat. Duis lacinia faucibus metus, nec vehicula metus consectetur eu.
'''

updatedMarkdown = ""

# First create the treeprocessor
class AltTextExtractor(Treeprocessor):
    def run(self, doc):
        "Find all alt_text and append to markdown.alt_text. "
        self.markdown.alt_text = []
        for image in doc.findall('.//img'):
         self.markdown.alt_text.append(image.get('alt'))

# Then traverse the markdown file and concatenate the alt text to the end of any image tags
class ImageTagUpdater(Treeprocessor):
    def run(self, doc):
      # Set a counter
      count = 0
      # Go through markdown file line by line
        for line in doc:
          # if line is an image tag
          if line > ('.//img'):
            # grab the array of the alt text
            img_ext = ImgExtractor(md)
            # find the second to last character of the line
            location = len(line) - 1
            # insert the alt text
            line += line[location] + '?' +  '"' + img_ext[count] +  '"'
            # add line to new markdown file
        updatedMarkdownadd.add(line)

The above code is pseudo code. I'm able to successfully extract the strings I need from the original file but I'm unable to concatenate those strings to their respective image tags and update the original file.

Body:
Provided your files aren't huge, it might be easier to overwrite the file, rather than try to wedge little bits in here or there.

orig = '![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif)'
new = '![Daffy Duck](http://www.nonstick.com/wp-content/uploads/2015/10/Daffy.gif?alt-text="Daffy Duck")'

with open(filename, 'r') as f:
    text = f.readlines()
    new_text = "\n".join([line if line != orig else new for line in text])

with open(filename, 'w') as f:
    f.write(new_text)

You could also use regex re.sub, but I suppose its a matter of preference.


问:
RxJava - Observable - multiple filter calls vs one filter call
I want to filter items emitted by an Observable, but I have many filter criterias and I'm wondering what is the better way to do that - performance wise.

One way would be to call one "filter" method which has all of the criterias in multiple "if" statements and returns the final filtering result, and to call:

```<code>observable
    .filter(this::filter)
</code>```

Another way would be to have multiple "filterX" methods, each filters by a specific criteria, and call them in a chain:

```<code>observable
    .filter(this::filterX)
    .filter(this::filterY)
    .filter(this::filterZ)
</code>```

My question is - is there any performance difference and which of the two is 'better practice'?
I find the second one nicer and more readable, but currently I encountered a "filter" method with ~30 'if' statements and I'm wondering if I should bother and refactor it to the second approach.

答:
RxJava library tries to optimize the scenario described by you with the concept of Operator Fusion:

Operator fusion has the premise that certain operators can be combined into one single operator (macro-fusion) or their internal data structures shared between each other (micro-fusion) that allows fewer allocations, lower overhead and better performance.

It gives a specific example about the filter operator in the design document:

a is b and the two operator's parameter set can be combined into a single application. Example: filter(p1).filter(p2) combined into filter(p1 && p2).

So, in your case, the library will try its best to combine all the filters in order to not have much performance difference.

Body:
I want to filter items emitted by an Observable, but I have many filter criterias and I'm wondering what is the better way to do that - performance wise.

One way would be to call one "filter" method which has all of the criterias in multiple "if" statements and returns the final filtering result, and to call:

observable
    .filter(this::filter)

Another way would be to have multiple "filterX" methods, each filters by a specific criteria, and call them in a chain:

observable
    .filter(this::filterX)
    .filter(this::filterY)
    .filter(this::filterZ)

My question is - is there any performance difference and which of the two is 'better practice'?
I find the second one nicer and more readable, but currently I encountered a "filter" method with ~30 'if' statements and I'm wondering if I should bother and refactor it to the second approach.


问:
How do I keep my splash screen over React components
I am trying to put a splash screen on my app. However, React is rendering its components above the splash screen.

My HTML looks like this:

```<code><div id='overlay'>
   <img/>
</div>
<div id='root'></div>

#overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(36,79,53, 1);
  z-index: 99;
}

#root{
  height: 100vh;
  z-index: 1;
}
</code>```

What else can I do?

答: I would encourage you to create a react component that would render as part of the react application. That way you can programmatically control when the overlap appears relative to the rest of your application logic.  Since you already have the CSS, and markup, you just need to put it into a component and render it.</p>

Body:
I am trying to put a splash screen on my app. However, React is rendering its components above the splash screen.

My HTML looks like this:

#overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(36,79,53, 1);
  z-index: 99;
}

#root{
  height: 100vh;
  z-index: 1;
}

What else can I do?


问:
how to determine maximum route cost in a n high numeric pyramid
I've got a numeric pyramid like this

```<code>       7
      4 8
     1 8 9
    2 4 6 7
   4 6 7 4 9
  4 9 7 3 8 8

routes: 32
</code>```

every number indexed by how powerful in its line.

```<code> 0 ( 9 => 1 ) 1 ( 8 => 5 ) 2 ( 8 => 4 ) 3 ( 7 => 2 ) 4 ( 4 => 0 ) 5 ( 3 => 3 )
 0 ( 9 => 4 ) 1 ( 7 => 2 ) 2 ( 6 => 1 ) 3 ( 4 => 3 ) 4 ( 4 => 0 )
 0 ( 7 => 3 ) 1 ( 6 => 2 ) 2 ( 4 => 1 ) 3 ( 2 => 0 )
 0 ( 9 => 2 ) 1 ( 8 => 1 ) 2 ( 1 => 0 )
 0 ( 8 => 1 ) 1 ( 4 => 0 )
 0 ( 7 => 0 )
</code>```

in this pyramid there are 2^(n-1) routes (you can go 2 way form each number)
If the pyramid high this low, it's easy you can calculate all the routes, and compare to eachother. But if you have an 50 high pyramid with 562949953421312 routes, the problem little bit more difficult.

I thoght I start from the bottom beginning from the most powerful numbers, but soon i realized, the max route cost ain't necesserly start or end up in big numbers.

Then I thought maybe secoundary indexes (where can you go futher from a number) will help, but I didin't even implement that becouse I assumed its still uses much resources and not optimal.

And now i'm confused how to restart thinking about this problem... any advice appreciated

答: If the numbers represent the cost to travel between 2 nodes of a graph, then Dijkstra's algorithm will find the shortest path.</p>

Body:
I've got a numeric pyramid like this

       7
      4 8
     1 8 9
    2 4 6 7
   4 6 7 4 9
  4 9 7 3 8 8

routes: 32

every number indexed by how powerful in its line.

 0 ( 9 => 1 ) 1 ( 8 => 5 ) 2 ( 8 => 4 ) 3 ( 7 => 2 ) 4 ( 4 => 0 ) 5 ( 3 => 3 )
 0 ( 9 => 4 ) 1 ( 7 => 2 ) 2 ( 6 => 1 ) 3 ( 4 => 3 ) 4 ( 4 => 0 )
 0 ( 7 => 3 ) 1 ( 6 => 2 ) 2 ( 4 => 1 ) 3 ( 2 => 0 )
 0 ( 9 => 2 ) 1 ( 8 => 1 ) 2 ( 1 => 0 )
 0 ( 8 => 1 ) 1 ( 4 => 0 )
 0 ( 7 => 0 )

in this pyramid there are 2^(n-1) routes (you can go 2 way form each number)
If the pyramid high this low, it's easy you can calculate all the routes, and compare to eachother. But if you have an 50 high pyramid with 562949953421312 routes, the problem little bit more difficult.

I thoght I start from the bottom beginning from the most powerful numbers, but soon i realized, the max route cost ain't necesserly start or end up in big numbers.

Then I thought maybe secoundary indexes (where can you go futher from a number) will help, but I didin't even implement that becouse I assumed its still uses much resources and not optimal.

And now i'm confused how to restart thinking about this problem... any advice appreciated


问:
How can I determine if an image has loaded, using Javascript/jQuery?
I'm writing some Javascript to resize the large image to fit into the user's browser window.  (I don't control the size of the source images unfortunately.)

So something like this would be in the HTML:

```<code><img id="photo"
     src="a_really_big_file.jpg"
     alt="this is some alt text"
     title="this is some title text" />
</code>```

Is there a way for me to determine if the src image in an img tag has been downloaded?

I need this because I'm running into a problem if $(document).ready() is executed before the browser has loaded the image.  $("#photo").width() and $("#photo").height() will return the size of the placeholder (the alt text).  In my case this is something like 134 x 20.

Right now I'm just checking if the photo's height is less than 150, and assuming that if so it is just alt text.  But this is quite a hack, and it would break if a photo is less than 150 pixels tall (not likely in my particular case), or if the alt text is more than 150 pixels tall (could possibly happen on a small browser window).

Edit: For anyone wanting to see the code:

```<code>$(function()
{
  var REAL_WIDTH = $("#photo").width();
  var REAL_HEIGHT = $("#photo").height();

  $(window).resize(adjust_photo_size);
  adjust_photo_size();

  function adjust_photo_size()
  {
    if(REAL_HEIGHT < 150)
    {
      REAL_WIDTH = $("#photo").width();
      REAL_HEIGHT = $("#photo").height();
      if(REAL_HEIGHT < 150)
      {
        //image not loaded.. try again in a quarter-second
        setTimeout(adjust_photo_size, 250);
        return;
      }
    }

    var new_width = . . . ;
    var new_height = . . . ;

    $("#photo").width(Math.round(new_width));
    $("#photo").height(Math.round(new_height));
  }

});
</code>```

Update: Thanks for the suggestions.  There is a risk of the event not being fired if I set a callback for the $("#photo").load event, so I have defined an onLoad event directly on the image tag.  For the record, here is the code I ended up going with:

```<code><img id="photo"
     onload="photoLoaded();"
     src="a_really_big_file.jpg"
     alt="this is some alt text"
     title="this is some title text" />
</code>```

Then in Javascript:

```<code>//This must be outside $() because it may get called first
var isPhotoLoaded = false;
function photoLoaded()
{
  isPhotoLoaded = true;
}

$(function()
{
  //Hides scrollbars, so we can resize properly.  Set with JS instead of
  //  CSS so that page doesn't break with JS disabled.
  $("body").css("overflow", "hidden");

  var REAL_WIDTH = -1;
  var REAL_HEIGHT = -1;

  $(window).resize(adjust_photo_size);
  adjust_photo_size();

  function adjust_photo_size()
  {
    if(!isPhotoLoaded)
    {
      //image not loaded.. try again in a quarter-second
      setTimeout(adjust_photo_size, 250);
      return;
    }
    else if(REAL_WIDTH < 0)
    {
      //first time in this function since photo loaded
      REAL_WIDTH = $("#photo").width();
      REAL_HEIGHT = $("#photo").height();
    }

    var new_width = . . . ;
    var new_height = . . . ;

    $("#photo").width(Math.round(new_width));
    $("#photo").height(Math.round(new_height));
  }

});
</code>```

答:
May I suggest a pure CSS solution altogether?

Just have a Div that you want to show the image in. Set the image as background. Then have the property background-size: cover or background-size: contain depending on how you want it.

cover will crop the image until smaller sides cover the box.
contain will keep the entire image inside the div, leaving you with spaces on sides.

Check the snippet below.

div {
  height: 300px;
  width: 300px;
  border: 3px dashed grey;
  background-position: center;
  background-repeat: no-repeat;
}

.cover-image {
  background-size: cover;
}

.contain-image {
  background-size: contain;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cover-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">
</div>
<br/>
<div class="contain-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">
</div></code>```

OwnerDisplayName: Kip

Body:
I'm writing some Javascript to resize the large image to fit into the user's browser window.  (I don't control the size of the source images unfortunately.)

So something like this would be in the HTML:

Is there a way for me to determine if the src image in an img tag has been downloaded?

I need this because I'm running into a problem if $(document).ready() is executed before the browser has loaded the image.  $("#photo").width() and $("#photo").height() will return the size of the placeholder (the alt text).  In my case this is something like 134 x 20.

Right now I'm just checking if the photo's height is less than 150, and assuming that if so it is just alt text.  But this is quite a hack, and it would break if a photo is less than 150 pixels tall (not likely in my particular case), or if the alt text is more than 150 pixels tall (could possibly happen on a small browser window).

Edit: For anyone wanting to see the code:

$(function()
{
  var REAL_WIDTH = $("#photo").width();
  var REAL_HEIGHT = $("#photo").height();

  $(window).resize(adjust_photo_size);
  adjust_photo_size();

  function adjust_photo_size()
  {
    if(REAL_HEIGHT < 150)
    {
      REAL_WIDTH = $("#photo").width();
      REAL_HEIGHT = $("#photo").height();
      if(REAL_HEIGHT < 150)
      {
        //image not loaded.. try again in a quarter-second
        setTimeout(adjust_photo_size, 250);
        return;
      }
    }

    var new_width = . . . ;
    var new_height = . . . ;

    $("#photo").width(Math.round(new_width));
    $("#photo").height(Math.round(new_height));
  }

});

Update: Thanks for the suggestions.  There is a risk of the event not being fired if I set a callback for the $("#photo").load event, so I have defined an onLoad event directly on the image tag.  For the record, here is the code I ended up going with:

Then in Javascript:

//This must be outside $() because it may get called first
var isPhotoLoaded = false;
function photoLoaded()
{
  isPhotoLoaded = true;
}

$(function()
{
  //Hides scrollbars, so we can resize properly.  Set with JS instead of
  //  CSS so that page doesn't break with JS disabled.
  $("body").css("overflow", "hidden");

  var REAL_WIDTH = -1;
  var REAL_HEIGHT = -1;

  $(window).resize(adjust_photo_size);
  adjust_photo_size();

  function adjust_photo_size()
  {
    if(!isPhotoLoaded)
    {
      //image not loaded.. try again in a quarter-second
      setTimeout(adjust_photo_size, 250);
      return;
    }
    else if(REAL_WIDTH < 0)
    {
      //first time in this function since photo loaded
      REAL_WIDTH = $("#photo").width();
      REAL_HEIGHT = $("#photo").height();
    }

    var new_width = . . . ;
    var new_height = . . . ;

    $("#photo").width(Math.round(new_width));
    $("#photo").height(Math.round(new_height));
  }

});

LastEditorDisplayName: Kip

Body:
May I suggest a pure CSS solution altogether?

Just have a Div that you want to show the image in. Set the image as background. Then have the property background-size: cover or background-size: contain depending on how you want it.

cover will crop the image until smaller sides cover the box.
contain will keep the entire image inside the div, leaving you with spaces on sides.

Check the snippet below.

div {
  height: 300px;
  width: 300px;
  border: 3px dashed grey;
  background-position: center;
  background-repeat: no-repeat;
}

.cover-image {
  background-size: cover;
}

.contain-image {
  background-size: contain;
}

<div class="cover-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">
</div>
<br/>
<div class="contain-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">
</div>


问:
Character escaping in keymap file
Here is a keymap to auto-pair asterisks (for Markdown and AsciiDoc) files. It works. Questions:

1) Should or should not I escape asterisks in the 6th line of the 1st block?

2) In my tests the escaping in this line doesn't make any difference. But why? If you try to remove escaping in the 5th and 6th lines of the last block (as well as the line in the 5th block), it will lead to incorrect behavior. So, the escaping is required there. But it seems it isn't required in the 1st block. It leads me to confusion.

```<code>[
    // Auto-pair *
    { "keys": ["*"], "command": "insert_snippet", "args": {"contents": "*$0*"}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
            { "key": "following_text", "operator": "regex_contains", "operand": "^(?:\t| |\\)|]|\\}|>|$)", "match_all": true },
            { "key": "preceding_text", "operator": "not_regex_contains", "operand": "[\\*a-zA-Z0-9_]$", "match_all": true }, // --- THIS line ---
            { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.other - punctuation.definition.string.end", "match_all": true }
        ]
    },
    { "keys": ["*"], "command": "insert_snippet", "args": {"contents": "*${0:$SELECTION}*"}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true }
        ]
    },
    { "keys": ["*"], "command": "move", "args": {"by": "characters", "forward": true}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
            { "key": "following_text", "operator": "regex_contains", "operand": "^\\*", "match_all": true }, // --- THIS line ---
            { "key": "selector", "operator": "not_equal", "operand": "punctuation.definition.string.begin", "match_all": true },
            { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.other - punctuation.definition.string.end", "match_all": true },
        ]
    },
    { "keys": ["backspace"], "command": "run_macro_file", "args": {"file": "res://Packages/Default/Delete Left Right.sublime-macro"}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
            { "key": "preceding_text", "operator": "regex_contains", "operand": "\\*$", "match_all": true }, // --- THIS line ---
            { "key": "following_text", "operator": "regex_contains", "operand": "^\\*", "match_all": true }, // --- THIS line ---
            { "key": "selector", "operator": "not_equal", "operand": "punctuation.definition.string.begin", "match_all": true },
            { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.other - punctuation.definition.string.end", "match_all": true },
        ]
    },
]
</code>```

Update: Actually, it will be better to use another regex:

```<code>- [*a-zA-Z0-9_]$
+ (^[*\\s]*$)|([*a-zA-Z0-9_]$)
</code>```

This way the asterisks will not be duplicated in the beginning of the lines when you will work with bulleted lists.

答:
In regular expressions, the * operator is special and indicates zero or more repetitions of the previous atom. So in order to match a literal * character you need to escape it as \* (or in JSON \\*) to indicate to the regex engine that you mean a literal * and not to apply the special meaning.

The construct [] represents a character set, which matches any of the characters within the set. Inside of a character set the only characters that have special meaning to the regex engine are ] (closes the set), \ (still needs to be able to escape),- (specifies a range of characters) and ^ (negates the set and is only special when it's the first character), so only those characters need to be escaped inside of the set.

Since a character set means match any one of the following characters the special meaning of * does not apply, so inside of a character set it doesn't need to be escaped (although you can still do so if you want to).

Title: Character escaping in keymap file

Body:
Here is a keymap to auto-pair asterisks (for Markdown and AsciiDoc) files. It works. Questions:

1) Should or should not I escape asterisks in the 6th line of the 1st block?

2) In my tests the escaping in this line doesn't make any difference. But why? If you try to remove escaping in the 5th and 6th lines of the last block (as well as the line in the 5th block), it will lead to incorrect behavior. So, the escaping is required there. But it seems it isn't required in the 1st block. It leads me to confusion.

[
    // Auto-pair *
    { "keys": ["*"], "command": "insert_snippet", "args": {"contents": "*$0*"}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
            { "key": "following_text", "operator": "regex_contains", "operand": "^(?:\t| |\\)|]|\\}|>|$)", "match_all": true },
            { "key": "preceding_text", "operator": "not_regex_contains", "operand": "[\\*a-zA-Z0-9_]$", "match_all": true }, // --- THIS line ---
            { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.other - punctuation.definition.string.end", "match_all": true }
        ]
    },
    { "keys": ["*"], "command": "insert_snippet", "args": {"contents": "*${0:$SELECTION}*"}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true }
        ]
    },
    { "keys": ["*"], "command": "move", "args": {"by": "characters", "forward": true}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
            { "key": "following_text", "operator": "regex_contains", "operand": "^\\*", "match_all": true }, // --- THIS line ---
            { "key": "selector", "operator": "not_equal", "operand": "punctuation.definition.string.begin", "match_all": true },
            { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.other - punctuation.definition.string.end", "match_all": true },
        ]
    },
    { "keys": ["backspace"], "command": "run_macro_file", "args": {"file": "res://Packages/Default/Delete Left Right.sublime-macro"}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
            { "key": "preceding_text", "operator": "regex_contains", "operand": "\\*$", "match_all": true }, // --- THIS line ---
            { "key": "following_text", "operator": "regex_contains", "operand": "^\\*", "match_all": true }, // --- THIS line ---
            { "key": "selector", "operator": "not_equal", "operand": "punctuation.definition.string.begin", "match_all": true },
            { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.other - punctuation.definition.string.end", "match_all": true },
        ]
    },
]

Update: Actually, it will be better to use another regex:

- [*a-zA-Z0-9_]$
+ (^[*\\s]*$)|([*a-zA-Z0-9_]$)

This way the asterisks will not be duplicated in the beginning of the lines when you will work with bulleted lists.


问:
How to compare the P values in permutation testing or randomization by shuffling only one variable in dataframe
I am writing loops or functions in R, and I still haven't really understood how to do that. Currently, I need to write a loop/function (not sure which one would be better) to create several results of Mixed models formula in the Permutation testing or randomization

sample dataset looks like:

```<code>dataset <- read.table(text =
"ID A_2 B_2 C_2 A_1 B_1 C_1 chkgp
M1  10  20  60  30  54  33  Treatment
M1  20  50  40  33  31  44  Placebo
M2  40  80  40  23  15  66  Placebo
M2  30  90  40  67  67  66  Treatment
M3  30  10  20  22  89  77  Treatment
M3  40  50  30  44  50  88  Placebo
M4  40  30  40  42  34  99  Treatment
M4  30  40  50  33  60  80  Placebo",header = TRUE, stringsAsFactors = FALSE)
</code>```

I have shuffle chkgp  variable each time the model run and used the following code

```<code>
mod1<-summary(lmerTest::lmer(A_2~B_1+sample(chkgp)+(1|ID),data = dataset))
mod1
P_value= 2 * (1 - pnorm(abs(mod1$coefficients[3, 4])))
P_value
</code>```

result model 1 after shuffule 1 time

```<code>Linear mixed model fit by REML. t-tests use Satterthwaite's method ['lmerModLmerTest']
Formula: A_2 ~ B_1 + sample(chkgp) + (1 | ID)
   Data: dataset

REML criterion at convergence: 44.7

Scaled residuals:
    Min      1Q  Median      3Q     Max
-0.7792 -0.4441  0.1185  0.3893  0.7734

Random effects:
 Groups   Name        Variance Std.Dev.
 ID       (Intercept) 122.52   11.069
 Residual              10.15    3.186
Number of obs: 8, groups:  ID, 4

Fixed effects:
                       Estimate Std. Error       df t value Pr(>|t|)
(Intercept)            42.87450    6.49941  4.06743   6.597  0.00258 **
B_1                    -0.27492    0.09149  7.97033  -3.005  0.01702 *
sample(chkgp)Treatment  1.74313    4.71095  8.33366   0.370  0.72060
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Correlation of Fixed Effects:
            (Intr) B_1
B_1         -0.433
smpl(chkg)T  0.164 -0.748
[1] 0.7113693
</code>```

Question 1: I need to find out the way to  compare and  check the actual P-value is same even after shuffling chkgp variable 1000

question 2: I need to write the loop run models 1000 times in each it need shuffle the chkgp variable.

答:
```<code>dataset <- read.table(text =
                        "ID A_2 B_2 C_2 A_1 B_1 C_1 chkgp
M1  10  20  60  30  54  33  Treatment
M1  20  50  40  33  31  44  Placebo
M2  40  80  40  23  15  66  Placebo
M2  30  90  40  67  67  66  Treatment
M3  30  10  20  22  89  77  Treatment
M3  40  50  30  44  50  88  Placebo
M4  40  30  40  42  34  99  Treatment
M4  30  40  50  33  60  80  Placebo",header = TRUE, stringsAsFactors = FALSE)

storeP <- list(rep(NA, 1000))

for(i in 1:1000) {
  #dataset <- transform(dataset, chkgp = sample(chkgp))
  dataset$chkgp <- ifelse(runif(nrow(dataset)) > 0.5, "Treatment", "Placebo")
  mod1<-summary(lmerTest::lmer(A_2~B_1+sample(chkgp)+(1|ID),data = dataset))
  P_value= 2 * (1 - pnorm(abs(mod1$coefficients[3, 4])))
  storeP[[i]] <- P_value
}

var(unlist(storeP)) == 0
</code>```

I have two options of "shuffling the data":

randomly sorting the column chkgp: transform(dataset, chkgp = sample(chkgp))

randomly assigning "Treatment" and "Placebo" to the Variable at a 0.5 threshold: ifelse(runif(nrow(dataset)) > 0.5, "Treatment", "Placebo"

Body:
I am writing loops or functions in R, and I still haven't really understood how to do that. Currently, I need to write a loop/function (not sure which one would be better) to create several results of Mixed models formula in the Permutation testing or randomization

sample dataset looks like:

dataset <- read.table(text =
"ID A_2 B_2 C_2 A_1 B_1 C_1 chkgp
M1  10  20  60  30  54  33  Treatment
M1  20  50  40  33  31  44  Placebo
M2  40  80  40  23  15  66  Placebo
M2  30  90  40  67  67  66  Treatment
M3  30  10  20  22  89  77  Treatment
M3  40  50  30  44  50  88  Placebo
M4  40  30  40  42  34  99  Treatment
M4  30  40  50  33  60  80  Placebo",header = TRUE, stringsAsFactors = FALSE)

I have shuffle chkgp  variable each time the model run and used the following code

mod1<-summary(lmerTest::lmer(A_2~B_1+sample(chkgp)+(1|ID),data = dataset))
mod1
P_value= 2 * (1 - pnorm(abs(mod1$coefficients[3, 4])))
P_value

result model 1 after shuffule 1 time

Linear mixed model fit by REML. t-tests use Satterthwaite's method ['lmerModLmerTest']
Formula: A_2 ~ B_1 + sample(chkgp) + (1 | ID)
   Data: dataset

REML criterion at convergence: 44.7

Scaled residuals:
    Min      1Q  Median      3Q     Max
-0.7792 -0.4441  0.1185  0.3893  0.7734

Random effects:
 Groups   Name        Variance Std.Dev.
 ID       (Intercept) 122.52   11.069
 Residual              10.15    3.186
Number of obs: 8, groups:  ID, 4

Fixed effects:
                       Estimate Std. Error       df t value Pr(>|t|)
(Intercept)            42.87450    6.49941  4.06743   6.597  0.00258 **
B_1                    -0.27492    0.09149  7.97033  -3.005  0.01702 *
sample(chkgp)Treatment  1.74313    4.71095  8.33366   0.370  0.72060
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Correlation of Fixed Effects:
            (Intr) B_1
B_1         -0.433
smpl(chkg)T  0.164 -0.748
[1] 0.7113693

Question 1: I need to find out the way to  compare and  check the actual P-value is same even after shuffling chkgp variable 1000

question 2: I need to write the loop run models 1000 times in each it need shuffle the chkgp variable.

Body:
dataset <- read.table(text =
                        "ID A_2 B_2 C_2 A_1 B_1 C_1 chkgp
M1  10  20  60  30  54  33  Treatment
M1  20  50  40  33  31  44  Placebo
M2  40  80  40  23  15  66  Placebo
M2  30  90  40  67  67  66  Treatment
M3  30  10  20  22  89  77  Treatment
M3  40  50  30  44  50  88  Placebo
M4  40  30  40  42  34  99  Treatment
M4  30  40  50  33  60  80  Placebo",header = TRUE, stringsAsFactors = FALSE)

storeP <- list(rep(NA, 1000))

for(i in 1:1000) {
  #dataset <- transform(dataset, chkgp = sample(chkgp))
  dataset$chkgp <- ifelse(runif(nrow(dataset)) > 0.5, "Treatment", "Placebo")
  mod1<-summary(lmerTest::lmer(A_2~B_1+sample(chkgp)+(1|ID),data = dataset))
  P_value= 2 * (1 - pnorm(abs(mod1$coefficients[3, 4])))
  storeP[[i]] <- P_value
}

var(unlist(storeP)) == 0

I have two options of "shuffling the data":

randomly sorting the column chkgp: transform(dataset, chkgp = sample(chkgp))

randomly assigning "Treatment" and "Placebo" to the Variable at a 0.5 threshold: ifelse(runif(nrow(dataset)) > 0.5, "Treatment", "Placebo"