问:
Any caveats using isPrototypeOf in JavaScript to check if a variable is of a specific type?

What I want to do

I'd like to write a function that is able to deal with two different argument types as its first parameter.

To be more specific, the function shall be able to deal with the first argument either being NodeList or Element.

My research

I was researching a bit on how to detect the type of a variable, since I'm not using libraries like jQuery or underscore and came across a variety of resources. Those were the best:

http://tobyho.com/2011/01/28/checking-types-in-javascript/

How do I get the name of an object's type in JavaScript?

I didn't expect that this particular corner of JavaScript is this flawed. The resources above list ways of doing this with typeof, instanceof etc.

But none of the resources I've found included isPrototypeOf as a viable option.

The question

I found NodeList.prototype.isPrototypeOf(myParam) and Element.prototype.isPrototypeOf(myParam) to work quite well. Since none of the resources I've found discusses the usage of isPrototypeOf, I'm wondering:

Are there any caveats using isPrototypeOf to check a variable for a specific type?

答:
A caveat is you can't use isPrototypeOf on primitive values (numbers, strings, booleans) because they aren't objects. Primitives MDN

console.log(String.prototype.isPrototypeOf('I am string')); // false
console.log(Number.prototype.isPrototypeOf(1)); // false
console.log(Boolean.prototype.isPrototypeOf(true)); // false
```

<p>Another caveat is many things are prototypes of an <code>Object</code>, like Arrays, Functions, Regular Expressions, Dates, even Elements</p>

<pre class="lang-js prettyprint-override"><code>console.log(Object.prototype.isPrototypeOf([])); // true
console.log(Object.prototype.isPrototypeOf(function(){})); // true
console.log(Object.prototype.isPrototypeOf(/test/i)); // true
console.log(Object.prototype.isPrototypeOf(new Date())); // true
console.log(Object.prototype.isPrototypeOf(document.querySelector('body'))); // true
</code>```

Todd Motto has a nice solution for reliable type checking Primitives and Global Objects.

function type(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1);
}
```

However, this doesn't work if checking that a value is an Element or NodeList. For that isPrototypeOf works well.

Body:
A caveat is you can't use isPrototypeOf on primitive values (numbers, strings, booleans) because they aren't objects. Primitives MDN

console.log(String.prototype.isPrototypeOf('I am string')); // false
console.log(Number.prototype.isPrototypeOf(1)); // false
console.log(Boolean.prototype.isPrototypeOf(true)); // false

Another caveat is many things are prototypes of an Object, like Arrays, Functions, Regular Expressions, Dates, even Elements

console.log(Object.prototype.isPrototypeOf([])); // true
console.log(Object.prototype.isPrototypeOf(function(){})); // true
console.log(Object.prototype.isPrototypeOf(/test/i)); // true
console.log(Object.prototype.isPrototypeOf(new Date())); // true
console.log(Object.prototype.isPrototypeOf(document.querySelector('body'))); // true

Todd Motto has a nice solution for reliable type checking Primitives and Global Objects.

function type(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1);
}

However, this doesn't work if checking that a value is an Element or NodeList. For that isPrototypeOf works well.


来源: stackexchange

问:
Issue selecting button by xpath, Python, tinder
I struggle to select the Tinder like button. I just copied the Xpath from the web version of tinder. It works for the Dislike button not for the like button. I've also tried to add a sleep button in case the like button didnt render quickly enough.

```<code>def dislike(self):
    dislike_btn = self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/main/div[1]/div/div/div[1]/div/div[2]/button[1]')
    dislike_btn.click()

def like(self):
    like_btn = self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/div/main/div/div[1]/div/div[2]/button[3]')
    like_btn.click()
</code>```

I've tried to select by CSS Selector but that didnt work either.

I am an absolute noob, so have mercy if I missed out on some relevant infos :D

答:
try clicking the element directly without assigning it. This is working for me and also check if there are any overlapping elements on the like button.</p>

```<code>driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/main/div[1]/div/div/div[1]/div/div[2]/button[3]').click()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I struggle to select the Tinder like button. I just copied the Xpath from the web version of tinder. It works for the Dislike button not for the like button. I've also tried to add a sleep button in case the like button didnt render quickly enough.

def dislike(self):
    dislike_btn = self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/main/div[1]/div/div/div[1]/div/div[2]/button[1]')
    dislike_btn.click()

def like(self):
    like_btn = self.driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/div/main/div/div[1]/div/div[2]/button[3]')
    like_btn.click()

I've tried to select by CSS Selector but that didnt work either.

I am an absolute noob, so have mercy if I missed out on some relevant infos :D

Body:
try clicking the element directly without assigning it. This is working for me and also check if there are any overlapping elements on the like button.

driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/main/div[1]/div/div/div[1]/div/div[2]/button[3]').click()


问:
Clone an Eloquent object including all relationships?
Is there any way to easily clone an Eloquent object, including all of its relationships?

For example, if I had these tables:

```<code>users ( id, name, email )
roles ( id, name )
user_roles ( user_id, role_id )
</code>```

In addition to creating a new row in the users table, with all columns being the same except  id, it should also create a new row in the user_roles table, assigning the same role to the new user.

Something like this:

```<code>$user = User::find(1);
$new_user = $user->clone();
</code>```

Where the User model has

```<code>class User extends Eloquent {
    public function roles() {
        return $this->hasMany('Role', 'user_roles');
    }
}
</code>```

答:
Here is a trait that will recursively duplicate all the loaded relationships on an object. You could easily expand this for other relationship types like Sabrina's example for belongsToMany.

```<code>trait DuplicateRelations
{
    public static function duplicateRelations($from, $to)
    {
        foreach ($from->relations as $relationName => $object){
            if($object !== null) {
                if ($object instanceof Collection) {
                    foreach ($object as $relation) {
                        self::replication($relationName, $relation, $to);
                    }
                } else {
                    self::replication($relationName, $object, $to);
                }
            }
        }
    }

    private static function replication($name, $relation, $to)
    {
        $newRelation = $relation->replicate();
        $to->{$name}()->create($newRelation->toArray());
        if($relation->relations !== null) {
            self::duplicateRelations($relation, $to->{$name});
        }
    }
}
</code>```

Usage:

```<code>//copy attributes
$new = $this->replicate();

//save model before you recreate relations (so it has an id)
$new->push();

//reset relations on EXISTING MODEL (this way you can control which ones will be loaded
$this->relations = [];

//load relations on EXISTING MODEL
$this->load('relation1','relation2.nested_relation');

// duplication all LOADED relations including nested.
self::duplicateRelations($this, $new);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there any way to easily clone an Eloquent object, including all of its relationships?

For example, if I had these tables:

users ( id, name, email )
roles ( id, name )
user_roles ( user_id, role_id )

In addition to creating a new row in the users table, with all columns being the same except  id, it should also create a new row in the user_roles table, assigning the same role to the new user.

Something like this:

$user = User::find(1);
$new_user = $user->clone();

Where the User model has

class User extends Eloquent {
    public function roles() {
        return $this->hasMany('Role', 'user_roles');
    }
}

Body:
Here is a trait that will recursively duplicate all the loaded relationships on an object. You could easily expand this for other relationship types like Sabrina's example for belongsToMany.

trait DuplicateRelations
{
    public static function duplicateRelations($from, $to)
    {
        foreach ($from->relations as $relationName => $object){
            if($object !== null) {
                if ($object instanceof Collection) {
                    foreach ($object as $relation) {
                        self::replication($relationName, $relation, $to);
                    }
                } else {
                    self::replication($relationName, $object, $to);
                }
            }
        }
    }

    private static function replication($name, $relation, $to)
    {
        $newRelation = $relation->replicate();
        $to->{$name}()->create($newRelation->toArray());
        if($relation->relations !== null) {
            self::duplicateRelations($relation, $to->{$name});
        }
    }
}

Usage:

//copy attributes
$new = $this->replicate();

//save model before you recreate relations (so it has an id)
$new->push();

//reset relations on EXISTING MODEL (this way you can control which ones will be loaded
$this->relations = [];

//load relations on EXISTING MODEL
$this->load('relation1','relation2.nested_relation');

// duplication all LOADED relations including nested.
self::duplicateRelations($this, $new);


问:
Identical bases conflict in multiple empty member optimization
I want to use an empty member optimization with a class having two members of user-defined types. As far as I know, the only way to achieve this is two make them my class' parents.

template<class Callback1, class Callback2>
struct S: Callback1, Callback2
{
    S(Callback1 c1, Callback2 c2): Callback1(c1), Callback2(c2) {}
    void Method()
    {
        Callback1::operator()();
        Callback2::operator()();
    }
    int field;
};
struct Functor {};
struct Functor2 {};
static_assert(sizeof(S<Functor, Functor2>) == sizeof(int));
```

The problem of this solution is that I cannot instantiate something like S<Functor, Functor>. When these two arguments are of the same type, I get a compiler error about two identical parents.
What is the best way to work around this problem?

Edit: There must always be two instances of callbacks even if they are of the same type. Any of these callbacks may be empty or not empty (stateful), but the cases when any of them or both are empty should be optimized.

答:
The only way I can think of involving multiple inheritance from the same base would go something like;</p>

```<code>template <class Callback> struct FirstBase : Callback {};
template <class Callback> struct SecondBase : Callback {};

struct Functor1 {};
struct Functor2 {};

template<class Callback1, class Callback2> struct S: FirstBase<Callback1>, SecondBase<Callback2> {int field;};
</code>```

Body:
I want to use an empty member optimization with a class having two members of user-defined types. As far as I know, the only way to achieve this is two make them my class' parents.

template<class Callback1, class Callback2>
struct S: Callback1, Callback2
{
    S(Callback1 c1, Callback2 c2): Callback1(c1), Callback2(c2) {}
    void Method()
    {
        Callback1::operator()();
        Callback2::operator()();
    }
    int field;
};
struct Functor {};
struct Functor2 {};
static_assert(sizeof(S<Functor, Functor2>) == sizeof(int));

The problem of this solution is that I cannot instantiate something like S<Functor, Functor>. When these two arguments are of the same type, I get a compiler error about two identical parents.
What is the best way to work around this problem?

Edit: There must always be two instances of callbacks even if they are of the same type. Any of these callbacks may be empty or not empty (stateful), but the cases when any of them or both are empty should be optimized.

Body:
The only way I can think of involving multiple inheritance from the same base would go something like;

template <class Callback> struct FirstBase : Callback {};
template <class Callback> struct SecondBase : Callback {};

struct Functor1 {};
struct Functor2 {};

template<class Callback1, class Callback2> struct S: FirstBase<Callback1>, SecondBase<Callback2> {int field;};


问:
Cannot Create Instance Of Class ViewModel
I'm currently working on a countdown app, and whenever I open it, it fails with a message saying Cannot create instance of class com.nailuj29gaming.CountdownViewModel

The stack trace is

```<code>    Process: com.nailuj29gaming.countdown.debug, PID: 17800
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nailuj29gaming.countdown.debug/com.nailuj29gaming.countdown.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.nailuj29gaming.countdown.CountdownViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2750)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.nailuj29gaming.countdown.CountdownViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.nailuj29gaming.countdown.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:6757)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2703)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
     Caused by: java.lang.InstantiationException: java.lang.Class<com.nailuj29gaming.countdown.CountdownViewModel> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.nailuj29gaming.countdown.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:6757)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2703)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
</code>```

I know there is a very similar question, this one, but that is target at Java, and my code is written in Kotlin. My ViewModel class's text is

```<code>package com.nailuj29gaming.countdown

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class CountdownViewModel(application: Application) : AndroidViewModel(application) {
    private val repo: CountdownRepo
    val countdowns: LiveData<List<Countdown>>

    init {
        val countdownDao = AppDatabase.getDatabase(application).countdownDao()
        repo = CountdownRepo(countdownDao)
        countdowns = repo.countdowns

    }

    fun insert(countdown: Countdown) = viewModelScope.launch {
        repo.insert(countdown)
    }

    fun delete(countdown: Countdown) = viewModelScope.launch {
        repo.delete(countdown)
    }
}
</code>```

I create the ViewModel in the first line of my MainActivity.onCreate() method. The code I used to create it is viewModel = ViewModelProvider(this).get(CountdownViewModel::class.java)

My build.gradle file (at least what matters in this question) is

```<code>apply plugin: 'kotlin-kapt'

dependencies {
    def room_version = "2.2.3"
    def lifecycle_version = "2.2.0"
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'androidx.preference:preference:1.1.0'
    implementation 'net.steamcrafted:materialiconlib:1.1.5'
    implementation 'com.google.android.material:material:1.0.0'
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.room:room-ktx:$room_version"
}
</code>```

I tried using a factory, but the ViewModelProviders class is deprecated

When I used a delegate, the IDE did not give me an error, but the compiler said

```<code>Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option
</code>```

My code is compiled into bytecode built with JVM target 1.8, so this error shouldn't show, right?

答:
You need to upgrade to Fragment 1.2.0 or higher, which is what adds a support for the ViewModelProvider constructor as per the Lifecycle 2.2.0 release notes:

You can pass a Fragment or FragmentActivity to the new ViewModelProvider(ViewModelStoreOwner) constructor to achieve the same functionality when using Fragment 1.2.0.

When using an older version of Fragments (i.e., the Fragment 1.1.0 that AppCompat 1.1.0 pulls in), you'll only get the ViewModelProvider$NewInstanceFactory you see in your exception trace, rather than a ViewModel.Factory that supports AndroidViewModel.

Therefore you should add an explicit dependency on Fragment 1.3.5 (the current latest):

```<code>implementation 'androidx.fragment:fragment:1.3.5'
</code>```

Body:
I'm currently working on a countdown app, and whenever I open it, it fails with a message saying Cannot create instance of class com.nailuj29gaming.CountdownViewModel

The stack trace is

    Process: com.nailuj29gaming.countdown.debug, PID: 17800
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nailuj29gaming.countdown.debug/com.nailuj29gaming.countdown.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.nailuj29gaming.countdown.CountdownViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2750)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.nailuj29gaming.countdown.CountdownViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.nailuj29gaming.countdown.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:6757)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2703)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
     Caused by: java.lang.InstantiationException: java.lang.Class<com.nailuj29gaming.countdown.CountdownViewModel> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.nailuj29gaming.countdown.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:6757)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2703)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2811)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6316)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

I know there is a very similar question, this one, but that is target at Java, and my code is written in Kotlin. My ViewModel class's text is

package com.nailuj29gaming.countdown

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class CountdownViewModel(application: Application) : AndroidViewModel(application) {
    private val repo: CountdownRepo
    val countdowns: LiveData<List<Countdown>>

    init {
        val countdownDao = AppDatabase.getDatabase(application).countdownDao()
        repo = CountdownRepo(countdownDao)
        countdowns = repo.countdowns

    }

    fun insert(countdown: Countdown) = viewModelScope.launch {
        repo.insert(countdown)
    }

    fun delete(countdown: Countdown) = viewModelScope.launch {
        repo.delete(countdown)
    }
}

I create the ViewModel in the first line of my MainActivity.onCreate() method. The code I used to create it is viewModel = ViewModelProvider(this).get(CountdownViewModel::class.java)

My build.gradle file (at least what matters in this question) is

apply plugin: 'kotlin-kapt'

dependencies {
    def room_version = "2.2.3"
    def lifecycle_version = "2.2.0"
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'androidx.preference:preference:1.1.0'
    implementation 'net.steamcrafted:materialiconlib:1.1.5'
    implementation 'com.google.android.material:material:1.0.0'
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.room:room-ktx:$room_version"
}

I tried using a factory, but the ViewModelProviders class is deprecated

When I used a delegate, the IDE did not give me an error, but the compiler said

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option

My code is compiled into bytecode built with JVM target 1.8, so this error shouldn't show, right?

Body:
You need to upgrade to Fragment 1.2.0 or higher, which is what adds a support for the ViewModelProvider constructor as per the Lifecycle 2.2.0 release notes:

You can pass a Fragment or FragmentActivity to the new ViewModelProvider(ViewModelStoreOwner) constructor to achieve the same functionality when using Fragment 1.2.0.

When using an older version of Fragments (i.e., the Fragment 1.1.0 that AppCompat 1.1.0 pulls in), you'll only get the ViewModelProvider$NewInstanceFactory you see in your exception trace, rather than a ViewModel.Factory that supports AndroidViewModel.

Therefore you should add an explicit dependency on Fragment 1.3.5 (the current latest):

implementation 'androidx.fragment:fragment:1.3.5'


问:
Where's definitive reference on string formatting
does anyone know of a good online resource that simply and definitevly explains how to use the string formatter method...?

I need to write a series of "records" into a set ascii text files. I need to "delimit" each "record" with a cr-lf sequence in a windows 2008 server environment.
Therefore I'm trying to figure out how to add a \r\n character string at the end of each "record". I tried a "record_string.append(CR) and LF" ; but it didn't work.

Thanks much

Guy

答:
If you specifically need to add CR LF to the end of each record (carriage return, linefeed), then you can just use exactly \r\n. The \r translates to a carriage return, and \n to linefeed. For example:

```<code>StringBuilder sb = new StringBuilder();
sb.append("some data");
// ...
sb.append("\r\n");  // add CR LF record separator
</code>```

You can find the exact list of escape sequences that exist in Java in section 3.10.6 of the Java Language Specification.

Body:
If you specifically need to add CR LF to the end of each record (carriage return, linefeed), then you can just use exactly \r\n. The \r translates to a carriage return, and \n to linefeed. For example:

StringBuilder sb = new StringBuilder();
sb.append("some data");
// ...
sb.append("\r\n");  // add CR LF record separator

You can find the exact list of escape sequences that exist in Java in section 3.10.6 of the Java Language Specification.


问:
Reducing the height so that the section does not take up so much of the screen
I am trying to make this section not so big when scrolling I feel it takes too much of the screen. Does anyone have any ideas to make it not so long? Thanks in advance to any one who helps.

.content-sm {
    padding-top: 60px;
    padding-bottom: 60px;
}
@media (min-width: 1200px)
.container {
    width: 1170px;
}
@media (min-width: 992px)
.container {
    width: 970px;
}
@media (min-width: 768px)
.container {
    width: 750px;
}
.container {
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}
* {
    border-radius: 0;
}

/*Business Posts Section
------------------------------------*/
.business-post-section {
  position: relative;
  background: #f7f7f7;
}

/*Business Posts Links/Buttons
------------------------------------*/
.business-post-link {
 padding-top: 25px;
 text-align: center;
}

.business-post-link i {
 color: #fff;
 width: 90px;
 height: 90px;
 padding: 30px;
 font-size: 30px;
 line-height: 30px;
 position: relative;
 text-align: center;
 background: #00539c;
 margin-bottom: 25px;
 display: inline-block;
}

.business-post-link i:after {
 top: -8px;
 left: -8px;
 right: -8px;
 bottom: -8px;
 content: " ";
 position: absolute;
 border: 1px solid #dedede;
 border-radius: 50% !important;
}

.business-post-link:hover i,
.business-post-link:hover i:after {
 transition: all 0.3s ease-in-out;
}

.business-post-link:hover i {
 background: #db9e33;
}

.business-post-link:hover i:after {
 border-color: #db9e33;
}

.rounded-x {
    border-radius: 50% !important;
}

.business-post-title {
 font-size: 20px;
 line-height: 24px;
 color: #555;
}

@media (min-width: 768px)
.col-sm-4 {
    width: 33.33333333%;
}
@media (min-width: 768px)
.col-sm-6 {
    width: 50%;
}
@media (min-width: 768px)
.col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9 {
    float: left;
}
.col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 {
    position: relative;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" rel="stylesheet"/>
<div class="wrapper">
  <!--=== Business Block ===-->
  <div class="business-post-section">
  <div class="container content-sm">
   <div class="row ">

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-drawer"></i>
     <h2 class="business-post-title">Tax Collection Solutions</h2>
    </div>

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-flag"></i>
     <h2 class="business-post-title">Auction Solutions</h2>
    </div>

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-wallet"></i>
     <h2 class="business-post-title">Payment Solutions</h2>
    </div>

   </div><!--/row-->
  </div><!--/container-->
  </div>

  <!--=== Contact Us Block ===-->
  <div class="business-post-section">
  <div class="container content-sm">
   <div class="row ">
    <div class="col-sm-2"></div>

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-screen-desktop"></i>
     <h2 class="business-post-title">Request a Demo</h2>
    </div>

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-call-in"></i>
     <h2 class="business-post-title">Contact Us</h2>
    </div>

    <div class="col-sm-2"></div>
   </div><!--/row-->
  </div><!--/container-->
  </div>

    </div></code>```

答:
I would probably cut the padding top/bottom in half on content-sm and then get rid of the margin between the icon and the h2 below:

```<code>.content-sm { padding: 30px 0; }
.business-post-link i { margin-bottom: 0; }
</code>```

Not sure if you wanted me to re-post your whole CSS but that's where I would start, then incrementally reduce the size of the icons themselves until it fit better with the other content.

Body:
I am trying to make this section not so big when scrolling I feel it takes too much of the screen. Does anyone have any ideas to make it not so long? Thanks in advance to any one who helps.

.content-sm {
    padding-top: 60px;
    padding-bottom: 60px;
}
@media (min-width: 1200px)
.container {
    width: 1170px;
}
@media (min-width: 992px)
.container {
    width: 970px;
}
@media (min-width: 768px)
.container {
    width: 750px;
}
.container {
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}
* {
    border-radius: 0;
}

/*Business Posts Section
------------------------------------*/
.business-post-section {
  position: relative;
  background: #f7f7f7;
}

/*Business Posts Links/Buttons
------------------------------------*/
.business-post-link {
 padding-top: 25px;
 text-align: center;
}

.business-post-link i {
 color: #fff;
 width: 90px;
 height: 90px;
 padding: 30px;
 font-size: 30px;
 line-height: 30px;
 position: relative;
 text-align: center;
 background: #00539c;
 margin-bottom: 25px;
 display: inline-block;
}

.business-post-link i:after {
 top: -8px;
 left: -8px;
 right: -8px;
 bottom: -8px;
 content: " ";
 position: absolute;
 border: 1px solid #dedede;
 border-radius: 50% !important;
}

.business-post-link:hover i,
.business-post-link:hover i:after {
 transition: all 0.3s ease-in-out;
}

.business-post-link:hover i {
 background: #db9e33;
}

.business-post-link:hover i:after {
 border-color: #db9e33;
}

.rounded-x {
    border-radius: 50% !important;
}

.business-post-title {
 font-size: 20px;
 line-height: 24px;
 color: #555;
}

@media (min-width: 768px)
.col-sm-4 {
    width: 33.33333333%;
}
@media (min-width: 768px)
.col-sm-6 {
    width: 50%;
}
@media (min-width: 768px)
.col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9 {
    float: left;
}
.col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 {
    position: relative;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" rel="stylesheet"/>

Tax Collection Solutions

Auction Solutions

Payment Solutions

Request a Demo

Contact Us

Body:
I would probably cut the padding top/bottom in half on content-sm and then get rid of the margin between the icon and the h2 below:

.content-sm { padding: 30px 0; }
.business-post-link i { margin-bottom: 0; }

Not sure if you wanted me to re-post your whole CSS but that's where I would start, then incrementally reduce the size of the icons themselves until it fit better with the other content.


问:
Error in downloading NLTK data: [Errno 11004] getaddrinfo failed
I have installed NLTK module but when I try to install the data I am getting the error below.

```<code>>>>import nltk
>>> nltk.download('punkt')
[nltk_data] Error loading punkt: <urlopen error [Errno 11004]
[nltk_data]     getaddrinfo failed>
False
</code>```

How should I install the data?

答:
I understand this is a very old question but wanted to share my experience for anyone who may experience this situation in future.
What i did was (in windows 10) -

open command prompt.

set proxies using command -

set HTTP_PROXY=http://userid:password@proxyurl:port

set HTTPS_PROXY=http://userid:password@proxyurl:port

set FTP_PROXY=http://userid:password@proxyurl:port

run command -

python -m nltk.downloader

Body:
I have installed NLTK module but when I try to install the data I am getting the error below.

>>>import nltk
>>> nltk.download('punkt')
[nltk_data] Error loading punkt: <urlopen error [Errno 11004]
[nltk_data]     getaddrinfo failed>
False

How should I install the data?


问:
Do NOT remove spaces in a variable
I'm creating a variable in a bash script, to pull a field from an sql database. There might be spaces in there, and I want to see that.

```<code>SIDE_NBR=$($CMD_CONNX "select side_nbr from setup" | awk 'NR==6{print$1}'|tr -d '\r'
</code>```

I need the tr -d '\r' as it comes in with a carriage return. However, this field might be

```<code>"    4"
</code>```

or

```<code>"4"
</code>```

I want to see those spaces so when i call my variable later, i can

```<code>log "Side_nbr=\"$SIDE_NBR\""
</code>```

And in my log would display "    4" or "4"

答:
To have an official answer posted. </p>

<p>{print$1} in awk will remove leading spaces. </p>

<p>Just using 'NR==6' works for what i'm doing. Thanks every one! </p>

Title: Do NOT remove spaces in a variable

Body:
I'm creating a variable in a bash script, to pull a field from an sql database. There might be spaces in there, and I want to see that.

SIDE_NBR=$($CMD_CONNX "select side_nbr from setup" | awk 'NR==6{print$1}'|tr -d '\r'

I need the tr -d '\r' as it comes in with a carriage return. However, this field might be

"    4"

or

"4"

I want to see those spaces so when i call my variable later, i can

log "Side_nbr=\"$SIDE_NBR\""

And in my log would display "    4" or "4"

Body:
To have an official answer posted.

{print$1} in awk will remove leading spaces.

Just using 'NR==6' works for what i'm doing. Thanks every one!


问:
tf.data + generator + keras => repeat() does not work, why?
When I train my dataset (tf.data.dataset.from_generator(x), with x an iterator created by

```<code>df.rdd.flatMap(func).toLocalIterator()
</code>```

where func is applied over my dataset. The repeat() function does not work over the dataset. I am using tensorflow version 1.14.0. The error is:

Your dataset iterator ran out of data; interrupting training. Make
  sure that your iterator can generate at least validation_steps * epochs batches (in this case, 3 batches). You may need to use the
  repeat() function when building your dataset.

What are possible workarounds to make the repeat function work? I can give more details, but I think that was is happening is just that the function by itself does not work under my conditions.

EDIT:

in my script 'pipeline.py' I have:

```<code>import numpy as np
from src.spark_utils.spark_session.sparkSession import arranca_spark
import tensorflow as tf

def f_input(
        row: np.array,
        future_steps=10,
        input_steps=10,
        slice=1,
        start=0,
        end=0
):
    input_array = np.array(
        [
            np.array(row['customer_id_list']),
            np.array(row['year_list']),
            np.array(row['month_list']),
            np.array(row['day_list']),
            np.array(row['importe_list']),
            np.array(row['cif_id_list']),
            np.array(row['cat_id_list'])
        ]
    )
    _, n = input_array.shape
    if start < 0:
        for i in range(n - input_steps + 1 - future_steps + start,
                       n - input_steps + 1 - future_steps - end):
            input_indices = range(i * slice, i * slice + input_steps, 1)
            input = input_array[:, input_indices]
            yield input[0], input[1], input[2], input[3], input[4], input[5], input[6]
    else:
        for i in range(start, n - input_steps + 1 - future_steps - end):
            input_indices = range(i * slice, i * slice + input_steps, 1)
            input = input_array[:, input_indices]
            yield input[0], input[1], input[2], input[3], input[4], input[5], input[6]

class Input():
    def __init__(self, data, input_steps, future_steps, start, end):
        self.data =data
        self.input_steps =input_steps
        self.future_steps =future_steps
        self.start =start
        self.end =end
        self.slice=1

    def __call__(self, *args, **kwargs):
        func =lambda x: f_input(x)
        result = self.data.rdd.flatMap(func)
        return result.toLocalIterator()

def f_output(
        row: np.array,
        future_steps=10,
        input_steps=10,
        slice=1,
        start=0,
        end=0
):
    output_array = np.array(
        [
            np.array(row['year_list']),
            np.array(row['month_list']),
            np.array(row['day_list']),
            np.array(row['cif_id_list'])
        ]
    )
    _, n = output_array.shape
    if start < 0:
        for i in range(n - input_steps + 1 - future_steps + start,
                       n - input_steps + 1 - future_steps - end):
            output_indices = range(i * slice + future_steps, i * slice + input_steps + future_steps, 1)
            output = np.reshape(output_array[:, output_indices], (4, 10, 1))
            yield output[0], output[1], output[2], output[3]
    else:
        for i in range(start, n - input_steps + 1 - future_steps - end):
            output_indices = range(i * slice + future_steps, i * slice + input_steps + future_steps, 1)
            output = np.reshape(output_array[:, output_indices], (4, 10, 1))
            yield output[0], output[1], output[2], output[3]

class Output():
    def __init__(self, data, input_steps, future_steps, start, end):
        self.data = data
        self.input_steps = input_steps
        self.future_steps = future_steps
        self.start = start
        self.end = end

    def __call__(self, *args, **kwargs):
        func = lambda x: f_output(x)
        result = self.data.rdd.flatMap(func)
        return result.toLocalIterator()

class Pipeline(object):
    def __init__(self, df, batch_size, input_steps,future_steps):
        self.df =df
        self.batch_size=batch_size
        self.input_steps=input_steps
        self.future_steps=future_steps

    @property
    def train_dataset(self):
        features= tf.data.Dataset.from_generator(
            generator=lambda: Input(data=self.df, input_steps=self.input_steps, future_steps=self.future_steps, start=0, end=self.input_steps+1)(),
            output_types=(tf.float32, tf.float32, tf.int32, tf.int32, tf.float32, tf.int32, tf.int32),
            output_shapes=(
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,))
            )
        )
        labels = tf.data.Dataset.from_generator(
            generator=lambda: Output(data=self.df, input_steps=self.input_steps, future_steps=self.future_steps,
                                         start=0, end=self.input_steps+1)(),
            output_types=(tf.float32, tf.int32, tf.int32, tf.int32),
            output_shapes=(
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1))
            )
        )
        return tf.data.Dataset.zip((features, labels)).repeat().batch(self.batch_size)

    @property
    def test_dataset(self):
        features= tf.data.Dataset.from_generator(
            generator=lambda: Input(data=self.df, input_steps=self.input_steps, future_steps=self.future_steps, start=-1, end=0)(),
            output_types=(tf.float32, tf.float32, tf.int32, tf.int32, tf.float32, tf.int32, tf.int32),
            output_shapes=(
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,))
            )
        )
        labels = tf.data.Dataset.from_generator(
            generator=lambda: Output(data=self.df, input_steps=self.input_steps, future_steps=self.future_steps,
                                         start=-1, end=0)(),
            output_types=(tf.float32, tf.int32, tf.int32, tf.int32),
            output_shapes=(
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1))
            )
        )
        return tf.data.Dataset.zip((features, labels)).repeat().batch(self.batch_size)
</code>```

From another file, I call this classes by writing:

```<code>from pyspark.sql import Row
names=("customer_id_list", "year_list", "month_list", "day_list", "importe_list", 'cif_id_list', 'cat_id_list')
customer=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
year=[0.5, 0.5, 0.5, 0.5, 0.5,0.5, 0.5, 0.5, 0.5, 0.5,0.5 ,0.5, 0.5, 0.5, 0.5, 0.5, 0.5,0.5, 0.5, 0.5, 0.5, 0.5,0.5 ,0.5 ]
month=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
day=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
importe=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
cif_id=[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
cat_id=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

row_dict={'customer_id_list': customer, 'year_list':year, 'month_list':month, 'day_list':day, 'importe_list':importe, 'cif_id_list':cif_id, 'cat_id_list':cat_id}
df = spark.createDataFrame([Row(**row_dict)])
input=Input(df,input_steps=10, future_steps=10, start=0, end=0)
print(list(input()))
</code>```

And then I get the error:

Exception in thread "serve toLocalIterator" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent ...

Any idea why this could be?

答:
Make sure your generator function can be called multiple times, or use .cache() so that the generator only needs to be run once.

```<code>import tensorflow as tf

# Created only once outside of gen()
it = iter([1, 2, 3])

def gen():
  for element in it:
    yield element

dataset = tf.data.Dataset.from_generator(gen, tf.int32)
print(list(dataset.repeat(2).as_numpy_iterator()))  # Prints just [1, 2, 3]
</code>```

If you move the iterator creation inside of the generator function, repeat will work how you expect:

```<code>import tensorflow as tf

def gen():
  # Create iterator every time gen() is called
  it = iter([1, 2, 3])
  for element in it:
    yield element

dataset = tf.data.Dataset.from_generator(gen, tf.int32)
print(list(dataset.repeat(2).as_numpy_iterator()))  # Prints [1, 2, 3, 1, 2, 3]
</code>```

Another option is to use cache so that gen only gets called once:

```<code>import tensorflow as tf

# Created only once outside of gen()
it = iter([1, 2, 3])

def gen():
  for element in it:
    yield element

dataset = tf.data.Dataset.from_generator(gen, tf.int32)
# Add a `.cache()` here
print(list(dataset.cache().repeat(2).as_numpy_iterator()))  # Prints [1, 2, 3, 1, 2, 3]
</code>```

Body:
When I train my dataset (tf.data.dataset.from_generator(x), with x an iterator created by

df.rdd.flatMap(func).toLocalIterator()

where func is applied over my dataset. The repeat() function does not work over the dataset. I am using tensorflow version 1.14.0. The error is:

Your dataset iterator ran out of data; interrupting training. Make
  sure that your iterator can generate at least validation_steps * epochs batches (in this case, 3 batches). You may need to use the
  repeat() function when building your dataset.

What are possible workarounds to make the repeat function work? I can give more details, but I think that was is happening is just that the function by itself does not work under my conditions.

EDIT:

in my script 'pipeline.py' I have:

import numpy as np
from src.spark_utils.spark_session.sparkSession import arranca_spark
import tensorflow as tf

def f_input(
        row: np.array,
        future_steps=10,
        input_steps=10,
        slice=1,
        start=0,
        end=0
):
    input_array = np.array(
        [
            np.array(row['customer_id_list']),
            np.array(row['year_list']),
            np.array(row['month_list']),
            np.array(row['day_list']),
            np.array(row['importe_list']),
            np.array(row['cif_id_list']),
            np.array(row['cat_id_list'])
        ]
    )
    _, n = input_array.shape
    if start < 0:
        for i in range(n - input_steps + 1 - future_steps + start,
                       n - input_steps + 1 - future_steps - end):
            input_indices = range(i * slice, i * slice + input_steps, 1)
            input = input_array[:, input_indices]
            yield input[0], input[1], input[2], input[3], input[4], input[5], input[6]
    else:
        for i in range(start, n - input_steps + 1 - future_steps - end):
            input_indices = range(i * slice, i * slice + input_steps, 1)
            input = input_array[:, input_indices]
            yield input[0], input[1], input[2], input[3], input[4], input[5], input[6]

class Input():
    def __init__(self, data, input_steps, future_steps, start, end):
        self.data =data
        self.input_steps =input_steps
        self.future_steps =future_steps
        self.start =start
        self.end =end
        self.slice=1

    def __call__(self, *args, **kwargs):
        func =lambda x: f_input(x)
        result = self.data.rdd.flatMap(func)
        return result.toLocalIterator()

def f_output(
        row: np.array,
        future_steps=10,
        input_steps=10,
        slice=1,
        start=0,
        end=0
):
    output_array = np.array(
        [
            np.array(row['year_list']),
            np.array(row['month_list']),
            np.array(row['day_list']),
            np.array(row['cif_id_list'])
        ]
    )
    _, n = output_array.shape
    if start < 0:
        for i in range(n - input_steps + 1 - future_steps + start,
                       n - input_steps + 1 - future_steps - end):
            output_indices = range(i * slice + future_steps, i * slice + input_steps + future_steps, 1)
            output = np.reshape(output_array[:, output_indices], (4, 10, 1))
            yield output[0], output[1], output[2], output[3]
    else:
        for i in range(start, n - input_steps + 1 - future_steps - end):
            output_indices = range(i * slice + future_steps, i * slice + input_steps + future_steps, 1)
            output = np.reshape(output_array[:, output_indices], (4, 10, 1))
            yield output[0], output[1], output[2], output[3]

class Output():
    def __init__(self, data, input_steps, future_steps, start, end):
        self.data = data
        self.input_steps = input_steps
        self.future_steps = future_steps
        self.start = start
        self.end = end

    def __call__(self, *args, **kwargs):
        func = lambda x: f_output(x)
        result = self.data.rdd.flatMap(func)
        return result.toLocalIterator()

class Pipeline(object):
    def __init__(self, df, batch_size, input_steps,future_steps):
        self.df =df
        self.batch_size=batch_size
        self.input_steps=input_steps
        self.future_steps=future_steps

    @property
    def train_dataset(self):
        features= tf.data.Dataset.from_generator(
            generator=lambda: Input(data=self.df, input_steps=self.input_steps, future_steps=self.future_steps, start=0, end=self.input_steps+1)(),
            output_types=(tf.float32, tf.float32, tf.int32, tf.int32, tf.float32, tf.int32, tf.int32),
            output_shapes=(
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,))
            )
        )
        labels = tf.data.Dataset.from_generator(
            generator=lambda: Output(data=self.df, input_steps=self.input_steps, future_steps=self.future_steps,
                                         start=0, end=self.input_steps+1)(),
            output_types=(tf.float32, tf.int32, tf.int32, tf.int32),
            output_shapes=(
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1))
            )
        )
        return tf.data.Dataset.zip((features, labels)).repeat().batch(self.batch_size)

    @property
    def test_dataset(self):
        features= tf.data.Dataset.from_generator(
            generator=lambda: Input(data=self.df, input_steps=self.input_steps, future_steps=self.future_steps, start=-1, end=0)(),
            output_types=(tf.float32, tf.float32, tf.int32, tf.int32, tf.float32, tf.int32, tf.int32),
            output_shapes=(
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,)),
                tf.TensorShape((self.input_steps,))
            )
        )
        labels = tf.data.Dataset.from_generator(
            generator=lambda: Output(data=self.df, input_steps=self.input_steps, future_steps=self.future_steps,
                                         start=-1, end=0)(),
            output_types=(tf.float32, tf.int32, tf.int32, tf.int32),
            output_shapes=(
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1)),
                tf.TensorShape((self.input_steps, 1))
            )
        )
        return tf.data.Dataset.zip((features, labels)).repeat().batch(self.batch_size)

From another file, I call this classes by writing:

from pyspark.sql import Row
names=("customer_id_list", "year_list", "month_list", "day_list", "importe_list", 'cif_id_list', 'cat_id_list')
customer=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
year=[0.5, 0.5, 0.5, 0.5, 0.5,0.5, 0.5, 0.5, 0.5, 0.5,0.5 ,0.5, 0.5, 0.5, 0.5, 0.5, 0.5,0.5, 0.5, 0.5, 0.5, 0.5,0.5 ,0.5 ]
month=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
day=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
importe=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
cif_id=[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
cat_id=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

row_dict={'customer_id_list': customer, 'year_list':year, 'month_list':month, 'day_list':day, 'importe_list':importe, 'cif_id_list':cif_id, 'cat_id_list':cat_id}
df = spark.createDataFrame([Row(**row_dict)])
input=Input(df,input_steps=10, future_steps=10, start=0, end=0)
print(list(input()))

And then I get the error:

Exception in thread "serve toLocalIterator" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent ...

Any idea why this could be?

Body:
Make sure your generator function can be called multiple times, or use .cache() so that the generator only needs to be run once.

import tensorflow as tf

# Created only once outside of gen()
it = iter([1, 2, 3])

def gen():
  for element in it:
    yield element

dataset = tf.data.Dataset.from_generator(gen, tf.int32)
print(list(dataset.repeat(2).as_numpy_iterator()))  # Prints just [1, 2, 3]

If you move the iterator creation inside of the generator function, repeat will work how you expect:

import tensorflow as tf

def gen():
  # Create iterator every time gen() is called
  it = iter([1, 2, 3])
  for element in it:
    yield element

dataset = tf.data.Dataset.from_generator(gen, tf.int32)
print(list(dataset.repeat(2).as_numpy_iterator()))  # Prints [1, 2, 3, 1, 2, 3]

Another option is to use cache so that gen only gets called once:

import tensorflow as tf

# Created only once outside of gen()
it = iter([1, 2, 3])

def gen():
  for element in it:
    yield element

dataset = tf.data.Dataset.from_generator(gen, tf.int32)
# Add a `.cache()` here
print(list(dataset.cache().repeat(2).as_numpy_iterator()))  # Prints [1, 2, 3, 1, 2, 3]


问:
Doctrine & Symfony - Get data from database with parameter on array column
Good afternoon,

I try to find, from my database specific users with a role which is passed in parameter to the query. However, I have "null" result currently.

The users class is like this example from Symfony Documentation.

This is my CustomerRepository:

```<code>class CustomerRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Customer::class);
    }

    public function findByRole(string $role)
    {
        return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Customer c
              WHERE c.roles IN (:role)'
        )
            ->setParameter(':role', $role)
            ->getResult()
        ;
    }
}
</code>```

I expect to return an array which contains one or several users who have the role.

答:
First of all in the class from the example you have given does not have declared variable called roles, therefore you cannot write this

```<code> ... WHERE c.roles IN (:role)'
</code>```

So in your User class you should have something like this

```<code>private $roles;
</code>```

Also as it said here you can have "multiple tables and JOIN them
  in your queries."

So you would have 1 table for all your roles, one for the users and one called user_roles where you will store the roles for each user.
The next step I would approach is to search this new table for the user I want and then retrieve all rows containing the different roles in an array.

Also there are other ways - stated here. The method I recommend when storing arrays is to have a VARCHAR field (or TEXT) and then use (in your case) the Symfony serializer component to serialize() the array when saving in the DB and to  deserialize()it when needed.

Body:
Good afternoon,

I try to find, from my database specific users with a role which is passed in parameter to the query. However, I have "null" result currently.

The users class is like this example from Symfony Documentation.

This is my CustomerRepository:

class CustomerRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Customer::class);
    }

    public function findByRole(string $role)
    {
        return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Customer c
              WHERE c.roles IN (:role)'
        )
            ->setParameter(':role', $role)
            ->getResult()
        ;
    }
}

I expect to return an array which contains one or several users who have the role.

Body:
First of all in the class from the example you have given does not have declared variable called roles, therefore you cannot write this

 ... WHERE c.roles IN (:role)'

So in your User class you should have something like this

private $roles;

Also as it said here you can have "multiple tables and JOIN them
  in your queries."

So you would have 1 table for all your roles, one for the users and one called user_roles where you will store the roles for each user.
The next step I would approach is to search this new table for the user I want and then retrieve all rows containing the different roles in an array.

Also there are other ways - stated here. The method I recommend when storing arrays is to have a VARCHAR field (or TEXT) and then use (in your case) the Symfony serializer component to serialize() the array when saving in the DB and to  deserialize()it when needed.


问:
How can I check which file is a function in?
I'm working with PHP and sometimes, I want to find where the function being used is located. How can I do this easily without tracing through everything?</p>

答:
Cannot redeclare the function error

Check out the answer from dev-null-dweller here.  VERY handy extension.


问:
How can you connect Snowflake to an IDE using Okta with MFA?
We currently use Okta (which requires MFA) to manage our Snowflake users, so most of our Snowflake users do not have a password. We have developers who want to use an IDE like DataGrip or DBeaver but we are unable to connect using the Okta method.

When we try to connect with the connection parameter of authenticator='https://<your_okta_account_name>.okta.com' we get the error message of [08001][390400] Bad request; operation not supported.

When we try to connect with the connection parameter of authenticator= externalbrowser we get the error message of [08001][390400] !390400!

We can't find better error messages than those. We get those error messages with both DBeaver and DataGrip.

Is there any advice in getting this to work? We can't figure out if this a Snowflake or Okta issue.

We were referencing these pieces of documentation:
https://docs.snowflake.net/manuals/user-guide/jdbc-configure.html#connection-parameters
https://support.snowflake.net/s/article/How-to-Configure-Snowflake-connections-for-Datagrip

答:
Our issue was actually different and didn't have anything to do with our Okta/Snowflake integration. We could have followed the Snowflake documentation on how to connect to Tableau or DataGrip.

There is an issue when using Okta with MFA for Snowflake using the externalbrowser authenticator method. We have an alias on our host name that we were trying to use for authentication.

For example, our real host name might be aaa111.snowflakecomputing.com and we have an alias of companyname.snowflakecomputing.com, you need to use the aaa111.snowflakecomputing.com host name when setting up the connection.

If you are on Okta with MFA, you do need to specify the externalbrowser authenticator method though.


问:
Getting attributes of Enum's value
I would like to know if it is possible to get attributes of the enum values and not of the enum itself? For example, suppose I have the following enum:

```<code>using System.ComponentModel; // for DescriptionAttribute

enum FunkyAttributesEnum
{
    [Description("Name With Spaces1")]
    NameWithoutSpaces1,
    [Description("Name With Spaces2")]
    NameWithoutSpaces2
}
</code>```

What I want is given the enum type, produce 2-tuples of enum string value and its description.

Value was easy:

```<code>Array values = System.Enum.GetValues(typeof(FunkyAttributesEnum));
foreach (int value in values)
    Tuple.Value = Enum.GetName(typeof(FunkyAttributesEnum), value);
</code>```

But how do I get description attribute's value, to populate Tuple.Desc? I can think of how to do it if the Attribute belongs to the enum itself, but I am at a loss as to how to get it from the value of the enum.

答:
This is how I solved it without using custom helpers or extensions with .NET core 3.1.

Class

```<code>public enum YourEnum
{
    [Display(Name = "Suryoye means Arameans")]
    SURYOYE = 0,
    [Display(Name = "Oromoye means Syriacs")]
    OROMOYE = 1,
}
</code>```

Razor

```<code>@using Enumerations

foreach (var name in Html.GetEnumSelectList(typeof(YourEnum)))
{
    <h1>@name.Text</h1>
}
</code>```

Title: Getting attributes of Enum's value

Body:
I would like to know if it is possible to get attributes of the enum values and not of the enum itself? For example, suppose I have the following enum:

using System.ComponentModel; // for DescriptionAttribute

enum FunkyAttributesEnum
{
    [Description("Name With Spaces1")]
    NameWithoutSpaces1,
    [Description("Name With Spaces2")]
    NameWithoutSpaces2
}

What I want is given the enum type, produce 2-tuples of enum string value and its description.

Value was easy:

Array values = System.Enum.GetValues(typeof(FunkyAttributesEnum));
foreach (int value in values)
    Tuple.Value = Enum.GetName(typeof(FunkyAttributesEnum), value);

But how do I get description attribute's value, to populate Tuple.Desc? I can think of how to do it if the Attribute belongs to the enum itself, but I am at a loss as to how to get it from the value of the enum.

Body:
This is how I solved it without using custom helpers or extensions with .NET core 3.1.

Class

public enum YourEnum
{
    [Display(Name = "Suryoye means Arameans")]
    SURYOYE = 0,
    [Display(Name = "Oromoye means Syriacs")]
    OROMOYE = 1,
}

Razor

@using Enumerations

foreach (var name in Html.GetEnumSelectList(typeof(YourEnum)))
{
    <h1>@name.Text</h1>
}


问:
Stream lots of screenshots from server
Let's say I have this tool that takes a screenshot of the user's desktop every 10 seconds and uploads the images to a server.  Images are deleted from the server after 24 hours.  I want to allow the user to view these screenshots in their browser.  So let's say each image is 300K and there are 5000 of them uploaded in a 24 hour period -- that's 1.5 GB of data.  These are png images, and often one screenshot isn't that different from the previous one, so I imagine I could compress them pretty well -- but I'm not sure how that would work.  I want to allow the user to view these images in their browser.  I want a slider under the images so the user can jump to any point in the 24 hour period.  I guess something like the YouTube player would be ideal.  Where the user could jump around and data is streamed, etc.  Image quality is important because the user needs to be able to read text in the screenshots.  I'd prefer a Python solution.

I've never done anything like this before, and am not sure how to approach the problem.  What would you do?

答:
If the user is currently at image K and want to load image H, assuming the screenshots will be mostly the same, you can just send the delta diff between H and K.

You can calculate the diffs ahead of time and store them into a cache or database for faster access (but there will be a lot of data) or you can calculate it on the fly.

Title: Stream lots of screenshots from server


问:
How do I get language specif commands to work in VSCode?
I am new to Visual Studio Code and I am trying to run commands in terminal to work with my project. I changed the default terminal to Git Bash but that didn't work. When I run a specific command I get errors. Here is an example for Ruby:

```<code>$ bundle install
bash: bundle: command not found
</code>```

This occurs whenever I try running a ruby/rails command. I am using Windows, is there a specific setting I need to edit in order to get this fixed?

答:
Add this to your VSCode settings.json file

```<code>"terminal.integrated.shell.windows": "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
"terminal.integrated.shellArgs.windows": ["--login", "-i"]
</code>```

Source

Body:
I am new to Visual Studio Code and I am trying to run commands in terminal to work with my project. I changed the default terminal to Git Bash but that didn't work. When I run a specific command I get errors. Here is an example for Ruby:

$ bundle install
bash: bundle: command not found

This occurs whenever I try running a ruby/rails command. I am using Windows, is there a specific setting I need to edit in order to get this fixed?

Body:
Add this to your VSCode settings.json file

"terminal.integrated.shell.windows": "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
"terminal.integrated.shellArgs.windows": ["--login", "-i"]

Source


问:
comparing two strings and their index seeing if all of string 2 is in string 1 with same order but different letter in between
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

```<code>>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False
</code>```

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

答:
Let's "rubber duck":

```<code># if word 1 is longer than word two
if len(word1) > len(word2):
   # lets `enumerate()` or look at each index of word 1 ,
   # and see if it is in word 2
    for i in range(0,len(word1)):
        # if the letter of word2 at index "i" is less than
        # the letter of word2 at "i + 1" then return true
        #############
        # notice you're trying to compare using a relational operator "<"
        # which would be
        # "a" < "a" == False
        # "b" < "a" == False
        # "a" < "b" == True
        # for example:
        #     'oboe', 'bob'
        #     (w1 letter, index, w2 letter)
        #     o, 0, b < o == True
        #     b, 1, o < b == False
        #     o, 2, b < None
        #     e, 3, None < None
        # this doesn't work because word2 isn't alphabetical.
        # and the len() of word2 in these examples are not longer than
        # word1. For example ["t", "a", "c"][2] and ["c", "a", "t"][2+1]
        if word2[i] < word2[i+1]:
            # end the function by returning true
            # the loop will not continue to check the rest of the word
            return True
        else:
            return False
# word 1 is not longer than word 2
else:
    return False
</code>```

see:

https://docs.python.org/3/library/stdtypes.html#str.find

https://en.wikipedia.org/wiki/Rubber_duck_debugging

What does enumerate() mean?

Body:
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

Body:
Let's "rubber duck":

# if word 1 is longer than word two
if len(word1) > len(word2):
   # lets `enumerate()` or look at each index of word 1 ,
   # and see if it is in word 2
    for i in range(0,len(word1)):
        # if the letter of word2 at index "i" is less than
        # the letter of word2 at "i + 1" then return true
        #############
        # notice you're trying to compare using a relational operator "<"
        # which would be
        # "a" < "a" == False
        # "b" < "a" == False
        # "a" < "b" == True
        # for example:
        #     'oboe', 'bob'
        #     (w1 letter, index, w2 letter)
        #     o, 0, b < o == True
        #     b, 1, o < b == False
        #     o, 2, b < None
        #     e, 3, None < None
        # this doesn't work because word2 isn't alphabetical.
        # and the len() of word2 in these examples are not longer than
        # word1. For example ["t", "a", "c"][2] and ["c", "a", "t"][2+1]
        if word2[i] < word2[i+1]:
            # end the function by returning true
            # the loop will not continue to check the rest of the word
            return True
        else:
            return False
# word 1 is not longer than word 2
else:
    return False

see:

https://docs.python.org/3/library/stdtypes.html#str.find

https://en.wikipedia.org/wiki/Rubber_duck_debugging

What does enumerate() mean?


问:
ifdown: interface eth0 not configured Error: ??? prefix is expectd rather than
on Ubuntu 16.04, I tried to set static IP in order to communicate with a local device.
I changed /etc/network/interfaces

```<code>auto eno1
iface eno1 inet static
    address 192.168.100.102
    netmask 255.2555.255.0
    gatway 192.168.100.1
    dns-nameservers 8.8.8.8 192.168.100.1

</code>```

After, I run the following command:

```<code>sudo ifdown eno1 && sudo ifup eno1
</code>```

I got error:

```<code>ifdown: interface eth0 not configured Error: ??? prefix is expectd rather than ...
</code>```

答:
The error caused by two typos:
1. "2555" should be "255"
2. "getway" should be "gateway"

After I fixed these two errors, my static IP address changed to 192.168.100.102

Body:
on Ubuntu 16.04, I tried to set static IP in order to communicate with a local device.
I changed /etc/network/interfaces

auto eno1
iface eno1 inet static
    address 192.168.100.102
    netmask 255.2555.255.0
    gatway 192.168.100.1
    dns-nameservers 8.8.8.8 192.168.100.1

After, I run the following command:

sudo ifdown eno1 && sudo ifup eno1

I got error:

ifdown: interface eth0 not configured Error: ??? prefix is expectd rather than ...


问:
Parsing the DOM to extract data using Python
I have the following code that outputs data extracted from
 tag.

s = BeautifulSoup(driver.page_source, "lxml")

best_price_tags = s.findAll('div', "flt-subhead1 gws-flights-results__price gws-flights-results__cheapest-price")
best_prices = []
for tag in best_price_tags:
    best_prices.append(tag.text.replace('€', '').strip())
```

<p>The first element of the variable <code>best_price_tags</code> contains the following:</p>

```
      1 820 €

```

<p>I am expecting from the above code to output only the value 1821.</p>

<p>The above code chunk has a problem where it outputs the following, consider the case of <code>best_price_tags[0]</code>, <code>'1\u202f821'</code>. </p>

<p>I tried the following but unfortunately did not work for me.</p>

```for tag in best_price_tags:
    best_prices.append(int(tag.text.replace('€', '').strip()))
```

Looking for an automated solution without using NLP modules.

NOTE: I have edited the exact value
 tag has. It was
1 820 €
 and now it is
      1 820 €
.

答: the space in 1 821 seems to be a no-break space (causing the \u202f in the output), try doing a replace on this too. By the way, I don't know where this character is on a keyboard, but copy/paste should be enough</p>

Body:
I have the following code that outputs data extracted from
 tag.

s = BeautifulSoup(driver.page_source, "lxml")

best_price_tags = s.findAll('div', "flt-subhead1 gws-flights-results__price gws-flights-results__cheapest-price")
best_prices = []
for tag in best_price_tags:
    best_prices.append(tag.text.replace('€', '').strip())

The first element of the variable best_price_tags contains the following:

      1 820 €

I am expecting from the above code to output only the value 1821.

The above code chunk has a problem where it outputs the following, consider the case of best_price_tags[0], '1\u202f821'.

I tried the following but unfortunately did not work for me.

for tag in best_price_tags:
    best_prices.append(int(tag.text.replace('€', '').strip()))

Looking for an automated solution without using NLP modules.

NOTE: I have edited the exact value
 tag has. It was
1 820 €
 and now it is
      1 820 €
.


问:
Asynchronous server messages with python flask
I'm trying to get server messages pushed out to the end user that's logged into our flask website.

I've done some research and it seems that the best solution is to use socket-io.

My attempts at this don't seem to be working, I must also indicate that my knowledge of javascript is very basic.

Any assistance / guidance will be highly appreciated.

See my code below:

python - app.py

```<code>from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, request
from time import sleep

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True

# turn the flask app into a socketio app
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if request.form['submit_button'] == 'Do Stuff':
            # server doing things....
            # the below method will make calls to emit socket messages
            # based on actions / outcome of actions.
            serverActions()
    return render_template('index.html')

@socketio.on('connect')
def connect():
    print('Client connected')

@socketio.on('display_message')
def displayMessage(message):
    socketio.emit('newmessage', {'message': message})
    socketio.sleep(2)

def serverActions():
    # get connection to DB
    message = "connecting to DB"
    # show message to user on flask page
    displayMessage(message)

    # test successful connection to DB
    message = "successfully connected to DB"
    displayMessage(message)

    # query the DB
    message = "querying the DB"
    displayMessage(message)

    # update DB
    message = "updating the DB"
    displayMessage(message)

    # etc......

if __name__ == '__main__':
    socketio.run(app)
</code>```

HTML - templates/index.html

```<code><!DOCTYPE html>
<html>
<head>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
    <script src="static/js/application.js"></script>
</head>
<body>
  <form method="POST">
  <div>
    <div>
      <h1>Asynchronous Flask Communication</h1>
      <p>Messages generated by the Flask server should appear below, asynchronously.</p>
    </div>
  </div>

  <div>
      <p>Asynchronous page updates will appear here:</p>
      <div>
        <input type="submit" value="Do Stuff" name="submit_button">
      </div>
      <div>
        <h3>Server Messages:</h3>
        <div id="message">
        </div>
      </div>
  </div>

  </form>
</body>
</html>
</code>```

javascript - static/js/application.js

```<code>$(document).ready(function(){
    //connect to the socket server.
    var socket = io.connect('http://' + document.domain + ':' + location.port);

    //receive message details from server
    socket.on('display_message', function(msg) {
        console.log("Received message" + msg.message);
        message_string = '<p>' + msg.message + '</p>';
        $('#message').html(message_string);
    });

});
</code>```

答:
Heres the trick to it: emit messages to a group. So, could invoke join group and add everyone to a group on log in that way you can send messages to everyone connected.

```<code>from flask import Flask
from flask_socketio import SocketIO, send, emit, join_room, leave_room

app = Flask('__name__')
socket = SocketIO(app, cors_allowed_origins="*", SameSite=None)

@socket.on('connect', namespace='/optional')
def connect():
    join_room('connected')

@app.route('/message')
def some_name():
    emit('message', 'your actual message', room='connected', namespace='/optional')
</code>```

Now when you hit the url it should send a message to everyone connected.
Remember the namespace is optional, but i recommend you use one.

Body:
I'm trying to get server messages pushed out to the end user that's logged into our flask website.

I've done some research and it seems that the best solution is to use socket-io.

My attempts at this don't seem to be working, I must also indicate that my knowledge of javascript is very basic.

Any assistance / guidance will be highly appreciated.

See my code below:

python - app.py

from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, request
from time import sleep

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True

# turn the flask app into a socketio app
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if request.form['submit_button'] == 'Do Stuff':
            # server doing things....
            # the below method will make calls to emit socket messages
            # based on actions / outcome of actions.
            serverActions()
    return render_template('index.html')

@socketio.on('connect')
def connect():
    print('Client connected')

@socketio.on('display_message')
def displayMessage(message):
    socketio.emit('newmessage', {'message': message})
    socketio.sleep(2)

def serverActions():
    # get connection to DB
    message = "connecting to DB"
    # show message to user on flask page
    displayMessage(message)

    # test successful connection to DB
    message = "successfully connected to DB"
    displayMessage(message)

    # query the DB
    message = "querying the DB"
    displayMessage(message)

    # update DB
    message = "updating the DB"
    displayMessage(message)

    # etc......

if __name__ == '__main__':
    socketio.run(app)

HTML - templates/index.html

<!DOCTYPE html>

  <form method="POST">

Asynchronous Flask Communication

Messages generated by the Flask server should appear below, asynchronously.

Asynchronous page updates will appear here:

        <input type="submit" value="Do Stuff" name="submit_button">

Server Messages:

  </form>

javascript - static/js/application.js

$(document).ready(function(){
    //connect to the socket server.
    var socket = io.connect('http://' + document.domain + ':' + location.port);

    //receive message details from server
    socket.on('display_message', function(msg) {
        console.log("Received message" + msg.message);
        message_string = '
' + msg.message + '
';
        $('#message').html(message_string);
    });

});

Body:
Heres the trick to it: emit messages to a group. So, could invoke join group and add everyone to a group on log in that way you can send messages to everyone connected.

from flask import Flask
from flask_socketio import SocketIO, send, emit, join_room, leave_room

app = Flask('__name__')
socket = SocketIO(app, cors_allowed_origins="*", SameSite=None)

@socket.on('connect', namespace='/optional')
def connect():
    join_room('connected')

@app.route('/message')
def some_name():
    emit('message', 'your actual message', room='connected', namespace='/optional')

Now when you hit the url it should send a message to everyone connected.
Remember the namespace is optional, but i recommend you use one.


问:
Define default values for function arguments
In the Lua wiki I found a way to define default values for missing arguments:

```<code>function myfunction(a,b,c)
    b = b or 7
    c = c or 5
    print (a,b,c)
end
</code>```

Is that the only way? The PHP style myfunction (a,b=7,c=5) does not seem to work. Not that the Lua way doesn't work, I am just wondering if this is the only way to do it.

答:
If you want named arguments and default values like PHP or Python, you can call your function with a table constructor:

```<code>myfunction{a,b=3,c=2}
</code>```

(This is seen in many places in Lua, such as the advanced forms of LuaSocket's protocol modules and constructors in IUPLua.)

The function itself could have a signature like this:

```<code>function myfunction(t)
    setmetatable(t,{__index={b=7, c=5}})
    local a, b, c =
      t[1] or t.a,
      t[2] or t.b,
      t[3] or t.c
    -- function continues down here...
end
</code>```

Any values missing from the table of parameters will be taken from the __index table in its metatable (see the documentation on metatables).

Of course, more advanced parameter styles are possible using table constructors and functions- you can write whatever you need. For example, here is a function that constructs a function that takes named-or-positional argument tables from a table defining the parameter names and default values and a function taking a regular argument list.

As a non-language-level feature, such calls can be changed to provide new behaviors and semantics:

Variables could be made to accept more than one name

Positional variables and keyword variables can be interspersed - and defining both can give precedence to either (or cause an error)

Keyword-only positionless variables can be made, as well as nameless position-only ones

The fairly-verbose table construction could be done by parsing a string

The argument list could be used verbatim if the function is called with something other than 1 table

Some useful functions for writing argument translators are unpack (moving to table.unpack in 5.2), setfenv (deprecated in 5.2 with the new _ENV construction), and select (which returns a single value from a given argument list, or the length of the list with '#').

Body:
In the Lua wiki I found a way to define default values for missing arguments:

function myfunction(a,b,c)
    b = b or 7
    c = c or 5
    print (a,b,c)
end

Is that the only way? The PHP style myfunction (a,b=7,c=5) does not seem to work. Not that the Lua way doesn't work, I am just wondering if this is the only way to do it.

Body:
If you want named arguments and default values like PHP or Python, you can call your function with a table constructor:

myfunction{a,b=3,c=2}

(This is seen in many places in Lua, such as the advanced forms of LuaSocket's protocol modules and constructors in IUPLua.)

The function itself could have a signature like this:

function myfunction(t)
    setmetatable(t,{__index={b=7, c=5}})
    local a, b, c =
      t[1] or t.a,
      t[2] or t.b,
      t[3] or t.c
    -- function continues down here...
end

Any values missing from the table of parameters will be taken from the __index table in its metatable (see the documentation on metatables).

Of course, more advanced parameter styles are possible using table constructors and functions- you can write whatever you need. For example, here is a function that constructs a function that takes named-or-positional argument tables from a table defining the parameter names and default values and a function taking a regular argument list.

As a non-language-level feature, such calls can be changed to provide new behaviors and semantics:

Variables could be made to accept more than one name

Positional variables and keyword variables can be interspersed - and defining both can give precedence to either (or cause an error)

Keyword-only positionless variables can be made, as well as nameless position-only ones

The fairly-verbose table construction could be done by parsing a string

The argument list could be used verbatim if the function is called with something other than 1 table

Some useful functions for writing argument translators are unpack (moving to table.unpack in 5.2), setfenv (deprecated in 5.2 with the new _ENV construction), and select (which returns a single value from a given argument list, or the length of the list with '#').


问:
How can I check if the time is more than an hour later?
So I have a database entry that update the date/time in yyyy-mm-dd hh:mm:ss.

Now I want to check, if there is a space inbetween the the database and the actual time from 60 minutes. How can I do that?

Example:

```<code>DB: 2020-02-14 10:00:00
Time now: 2020-02-14 11:01:00
Do something

DB: 2020-02-14 10:00:00
Time now: 2020-02-14 10:59:00
Do nothing
</code>```

答:
In MySQL, you can do date arithmetics:

```<code>update mytable
set mydatetime = now()
where mydatetime <= now() - interval 1 hour and id = ?
</code>```

The where clause filters on record whose column mydatetimeis more than one hour old. You did not tell what you want to do , so I assumed an update query, that resets the date/time to the current date/time.

This assumes that you want to update the timestamp of a given record, not accross the whole table, hence condition id = ?, which you can adapt - or remove - for your use case.

Body:
So I have a database entry that update the date/time in yyyy-mm-dd hh:mm:ss.

Now I want to check, if there is a space inbetween the the database and the actual time from 60 minutes. How can I do that?

Example:

DB: 2020-02-14 10:00:00
Time now: 2020-02-14 11:01:00
Do something

DB: 2020-02-14 10:00:00
Time now: 2020-02-14 10:59:00
Do nothing

Body:
In MySQL, you can do date arithmetics:

update mytable
set mydatetime = now()
where mydatetime <= now() - interval 1 hour and id = ?

The where clause filters on record whose column mydatetimeis more than one hour old. You did not tell what you want to do , so I assumed an update query, that resets the date/time to the current date/time.

This assumes that you want to update the timestamp of a given record, not accross the whole table, hence condition id = ?, which you can adapt - or remove - for your use case.


问:
Install specific python library version based on another library version
In setup.py I have

```<code>    install_requires=[
           "python-consul",
           "library_a",
           "library_b"
    ]
</code>```

library_b is also imported by library_a but it is pinned in library_a.

Is it possible to pin library_b to what it is pinned in library_a. I know I can just pin the same version but then everytime library_b pin is updated in library_a I need to repin in my service.

答:
Probably you can just omit one of the libraries, but not sure without concrete examples.

Anyhow, you can use requirement specifiers for versions that will define rules for versions and pin this rule for libraries you need. Example:

```<code>install_requires = [
   "python-consul",
   "library_a >=1.2, <2.0",
   "library_b >=1.2, <2.0",
]
</code>```

It can be exact version, greater/less than some version (by major, minor or even build version). Full list of version specifiers (rules) and examples can be found here.

Body:
In setup.py I have

    install_requires=[
           "python-consul",
           "library_a",
           "library_b"
    ]

library_b is also imported by library_a but it is pinned in library_a.

Is it possible to pin library_b to what it is pinned in library_a. I know I can just pin the same version but then everytime library_b pin is updated in library_a I need to repin in my service.

Body:
Probably you can just omit one of the libraries, but not sure without concrete examples.

Anyhow, you can use requirement specifiers for versions that will define rules for versions and pin this rule for libraries you need. Example:

install_requires = [
   "python-consul",
   "library_a >=1.2, <2.0",
   "library_b >=1.2, <2.0",
]

It can be exact version, greater/less than some version (by major, minor or even build version). Full list of version specifiers (rules) and examples can be found here.


Title: How can I check if the time is more than an hour later?

Body:
You can use something like this:

$t1 = strtotime( '2006-04-14 11:30:00' );
$t2 = strtotime( '2006-04-12 12:30:00' );
$diff = round(($t1 - $t2) / 3600);


答:
Walrus practice :-)</p>

```<code>def occurs_within(s, t):
    i = 0
    return all((i := s.find(c, i) + 1) for c in t)
</code>```

Title: comparing two strings and their index seeing if all of string 2 is in string 1 with same order but different letter in between

Body:
Walrus practice :-)

def occurs_within(s, t):
    i = 0
    return all((i := s.find(c, i) + 1) for c in t)


问:
What do Prolog implementations mean by "float"?
I was looking through the SICStus manual's syntax description and there is a definition of "float". However, there is no indication of what the implementation of "float" actually is. IEEE single or double precision? Maybe even a BigDecimal?

In SWI Prolog (or at least SWISH), the "float" seems to be IEEE double precision, as can be determined via:

```<code>planck_float(P) :-
   planck_float_descent(1.0,P).

planck_float_descent(X,P) :-
   Xhalf is X / 2.0, Xtest is 1.0 + Xhalf, Xtest =\= 1.0, !,
   write(Xhalf),writeln(Xtest),
   planck_float_descent(Xhalf,P).
planck_float_descent(P,P) :-
   Xhalf is P / 2.0, Xtest is 1.0 + Xhalf, Xtest == 1.0,
   writeln(P).

?- planck_float(P).
P = 2.220446049250313e-16
</code>```

2.22e-16 being the last value that, added to 1.0 still yields something larger than 1.0 sounds about right for IEEE 64-bit floating point arithmetic.

What implementation do other Prologs have?

Update many years later

Better code:

```<code>efloat(C,E) :-
   Cf is 1.0 * C, float(Cf),
   erecur(Cf,1.0,E).
erecur(C,X,E) :-
   Xhalf is X / 2.0,
   Xtest is C + Xhalf, Xtest \= C, !,
   format("~e/2.0 = ~20f\n",[Xhalf,Xtest]),
   erecur(C,Xhalf,E).
erecur(C,X,X) :-
   Xhalf is X / 2.0,
   Xtest is C + Xhalf,
   Xtest = C,
   format("~e",[X]).
</code>```

Then:

```<code>?- efloat(1,X).
X = 2.220446049250313e-16.
</code>```

答:
Actually there is more to say about floats in Prolog.
According to ISO core standard, section 7.1.3 Floating Point,
different radix are allowed for internal representation.

So a Prolog system could use radix=2 or radix=10. There
is only one constraint, the Prolog system should allow
at least 6 digits of precision. In secton 7.1.3 Floating Point we find:

```<code>r^p-1 >= 10^6
</code>```

r is the radix and p is the width of the mantissa. There
are other constraints in the same section. The notions integer part and float part of a number (not to be confused with the functions)

do not refer to this section. They refer to the external decimal representation in 6.1.2 Abstract term Syntax of the ISO core standard which fixes the radix to 10.

Body:
I was looking through the SICStus manual's syntax description and there is a definition of "float". However, there is no indication of what the implementation of "float" actually is. IEEE single or double precision? Maybe even a BigDecimal?

In SWI Prolog (or at least SWISH), the "float" seems to be IEEE double precision, as can be determined via:

planck_float(P) :-
   planck_float_descent(1.0,P).

planck_float_descent(X,P) :-
   Xhalf is X / 2.0, Xtest is 1.0 + Xhalf, Xtest =\= 1.0, !,
   write(Xhalf),writeln(Xtest),
   planck_float_descent(Xhalf,P).
planck_float_descent(P,P) :-
   Xhalf is P / 2.0, Xtest is 1.0 + Xhalf, Xtest == 1.0,
   writeln(P).

?- planck_float(P).
P = 2.220446049250313e-16

2.22e-16 being the last value that, added to 1.0 still yields something larger than 1.0 sounds about right for IEEE 64-bit floating point arithmetic.

What implementation do other Prologs have?

Update many years later

Better code:

efloat(C,E) :-
   Cf is 1.0 * C, float(Cf),
   erecur(Cf,1.0,E).
erecur(C,X,E) :-
   Xhalf is X / 2.0,
   Xtest is C + Xhalf, Xtest \= C, !,
   format("~e/2.0 = ~20f\n",[Xhalf,Xtest]),
   erecur(C,Xhalf,E).
erecur(C,X,X) :-
   Xhalf is X / 2.0,
   Xtest is C + Xhalf,
   Xtest = C,
   format("~e",[X]).

Then:

?- efloat(1,X).
X = 2.220446049250313e-16.

Body:
Actually there is more to say about floats in Prolog.
According to ISO core standard, section 7.1.3 Floating Point,
different radix are allowed for internal representation.

So a Prolog system could use radix=2 or radix=10. There
is only one constraint, the Prolog system should allow
at least 6 digits of precision. In secton 7.1.3 Floating Point we find:

r^p-1 >= 10^6

r is the radix and p is the width of the mantissa. There
are other constraints in the same section. The notions integer part and float part of a number (not to be confused with the functions)

do not refer to this section. They refer to the external decimal representation in 6.1.2 Abstract term Syntax of the ISO core standard which fixes the radix to 10.


答:
$currentDate = new DateTime();
$databaseDate = new DateTime($dateFromDatabase);
$interval = $datetime1->diff($datetime2);
```

Then you can check using the $interval variable

Body:
$currentDate = new DateTime();
$databaseDate = new DateTime($dateFromDatabase);
$interval = $datetime1->diff($datetime2);

Then you can check using the $interval variable