问:
SwiftUI inverse animation delay on removal
I am trying to choreograph animations in SwiftUI.  I want two colored bars to move in to the view with a delay between them and then move out of the view with the delays switched so that the removal is the reverse of the insertion.

I think I understand why the below code doesn't work, but I can't figure out how to make it do what I need:

```<code>import SwiftUI

struct TestAnimControl: View {
    @State var show: Bool = false
    @State var reverseDelay: Bool = false

    var body: some View {
        VStack {
            Button(action:{
                self.show.toggle()
            }) {
                Text("Animate")
                    .font(.largeTitle)
            }
            if show {
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(show ? 0.3 : 0.5))
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(show ? 0.5 : 0.3))
            }
        }
    }
}
</code>```

When you run this and hit the button, the blue bar moves in and then the red bar moves in.  Hit the button again and the blue bar moves out and then the red bar moves out.  What I want is when you hit the button for removal, the red bar moves out and then the blue bar moves out, reverse of the way the bars came in.  In this code I believe the ternary doesn't work because the animation is set when the Rectangle is created and the delay can't change after that.  I may be wrong, but either way is there a way to do what I am trying to do?

答:
You cannot change delay value according to state value because Animation struct is marked as @frozen that has no effect on property observers - state properties (check it out https://docs.swift.org/swift-book/ReferenceManual/Attributes.html). The proper way to do is using DispatchQueue.main.asyncAfter(deadline:_:) to specify each delay. Here is my sample code...

```<code>struct ContentView: View {
    @State var blue = false
    @State var red = false

    var body: some View {
        VStack {
            Button(action:{
                let redDelay = self.red ? 0.3 : 0.5
                DispatchQueue.main.asyncAfter(deadline: .now() + redDelay) {
                    self.red.toggle()
                }
                let blueDelay = self.blue ? 0.5 : 0.3
                DispatchQueue.main.asyncAfter(deadline: .now() + blueDelay) {
                    self.blue.toggle()
                }
            }) {
                Text("Animate")
                    .font(.largeTitle)
            }
            if blue {
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(height: 100)
                    .transition(AnyTransition.move(edge: .trailing))
                    .animation(Animation.spring())
            }
            if red {
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                    .transition(AnyTransition.move(edge: .trailing))
                    .animation(Animation.spring())
            }
        }
        .animation(.spring())
    }
}
</code>```

Thanks. X_X

Body:
I am trying to choreograph animations in SwiftUI.  I want two colored bars to move in to the view with a delay between them and then move out of the view with the delays switched so that the removal is the reverse of the insertion.

I think I understand why the below code doesn't work, but I can't figure out how to make it do what I need:

import SwiftUI

struct TestAnimControl: View {
    @State var show: Bool = false
    @State var reverseDelay: Bool = false

    var body: some View {
        VStack {
            Button(action:{
                self.show.toggle()
            }) {
                Text("Animate")
                    .font(.largeTitle)
            }
            if show {
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(show ? 0.3 : 0.5))
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(show ? 0.5 : 0.3))
            }
        }
    }
}

When you run this and hit the button, the blue bar moves in and then the red bar moves in.  Hit the button again and the blue bar moves out and then the red bar moves out.  What I want is when you hit the button for removal, the red bar moves out and then the blue bar moves out, reverse of the way the bars came in.  In this code I believe the ternary doesn't work because the animation is set when the Rectangle is created and the delay can't change after that.  I may be wrong, but either way is there a way to do what I am trying to do?

Body:
You cannot change delay value according to state value because Animation struct is marked as @frozen that has no effect on property observers - state properties (check it out https://docs.swift.org/swift-book/ReferenceManual/Attributes.html). The proper way to do is using DispatchQueue.main.asyncAfter(deadline:_:) to specify each delay. Here is my sample code...

struct ContentView: View {
    @State var blue = false
    @State var red = false

    var body: some View {
        VStack {
            Button(action:{
                let redDelay = self.red ? 0.3 : 0.5
                DispatchQueue.main.asyncAfter(deadline: .now() + redDelay) {
                    self.red.toggle()
                }
                let blueDelay = self.blue ? 0.5 : 0.3
                DispatchQueue.main.asyncAfter(deadline: .now() + blueDelay) {
                    self.blue.toggle()
                }
            }) {
                Text("Animate")
                    .font(.largeTitle)
            }
            if blue {
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(height: 100)
                    .transition(AnyTransition.move(edge: .trailing))
                    .animation(Animation.spring())
            }
            if red {
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                    .transition(AnyTransition.move(edge: .trailing))
                    .animation(Animation.spring())
            }
        }
        .animation(.spring())
    }
}

Thanks. X_X


来源: stackexchange

问:
CoreLocation singleton delegate methods used by multiple views
I've implemented a singleton CoreLocation class (courtesy of this link:  http://jinru.wordpress.com/2010/08/15/singletons-in-objective-c-an-example-of-cllocationmanager/)

However, I need two different ViewControllers to access the delegate method "newLocation".  One viewController manages identification of locations.  Another manages a mapView.

Ideally, I want both viewControllers to be delegates of my singleton - so they can both handle the "newLocation" method. But is this advisable (and if so, how would I do it)?

Or should I be using notifications to achieve this?  With the singleton posting a notification, and the ViewControllers listening to them?

Any advice, much appreciated.

dunc

答: I would go with posting notifications with NSNotificationCenter.

ContentLicense: CC BY-SA 3.0


问:
Linux: batch filename change adding creation date
i have a directory with a lot of sub-directories including files.
For each WAV file i would like to rename WAV file by adding creation date (date when file WAV has been firstly created) at the beginning of the file (without changing timestamps of file itself).

Next step would be to convert the WAV file to MP3 file, so i will save hard drive space.

for that purpose, i'm trying to create a bash script but i'm having some issues.

I want to keep the same structure as original directory and therefore i was thinking of something like:

```<code>for file in `ls -1 *.wav`
  do name=`stat -c %y $file | awk -F"." '{ print $1 }' | sed -e "s/\-//g" -e "s/\://g" -e "s/[ ]/_/g"`.wav
  cp -r --preserve=timestampcp $dir_original/$file $dir_converted/$name
done
</code>```

答:
I wanted to append all file names in that folder with the date they were created , and below works perfectly.</p>

```<code>#############################
#!/bin/sh
for file in `ls *.JPG`;
do
mv -f "$file" "$(date -r "$file" +"%Y%m%d_%H_%M_%S")_"$file".jpg"
done
##############################
</code>```

Body:
i have a directory with a lot of sub-directories including files.
For each WAV file i would like to rename WAV file by adding creation date (date when file WAV has been firstly created) at the beginning of the file (without changing timestamps of file itself).

Next step would be to convert the WAV file to MP3 file, so i will save hard drive space.

for that purpose, i'm trying to create a bash script but i'm having some issues.

I want to keep the same structure as original directory and therefore i was thinking of something like:

for file in `ls -1 *.wav`
  do name=`stat -c %y $file | awk -F"." '{ print $1 }' | sed -e "s/\-//g" -e "s/\://g" -e "s/[ ]/_/g"`.wav
  cp -r --preserve=timestampcp $dir_original/$file $dir_converted/$name
done

Body:
I wanted to append all file names in that folder with the date they were created , and below works perfectly.

#############################
#!/bin/sh
for file in `ls *.JPG`;
do
mv -f "$file" "$(date -r "$file" +"%Y%m%d_%H_%M_%S")_"$file".jpg"
done
##############################

ContentLicense: CC BY-SA 4.0


问:
Laravel one to many relation Property [jadwal_poliklinik] does not exist on this collection instance
Can Anybody help me with Laravel Relationship ?
i have data base structure

```<code>   poliklinik Table
   ===========
   id
   nama_poliklinik
   ****************

   jadwal_poliklinik Table
   =======================
   id
   poliklinik_id
   hari
   ***********************
</code>```

the relationship is "One" polikinik "have many" jadwal_poliklinik

my model poliklinik is

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;
use App\jadwal_poliklinik;

class poliklinik extends Model
{
    protected $table = 'poliklinik';

    public function jadwal_poliklinik()
    {
        return $this->hasMany(jadwal_poliklinik::class);
    }
}
</code>```

my jadwal_poliklinik model

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;
use App\poliklinik;

class jadwal_poliklinik extends Model
{
    protected $table = 'jadwal_poliklinik';

    public function poliklinik()
    {
        return $this->belongsTo(poliklinik::class);
    }

}
</code>```

my controller is

```<code>public function jadwal()
    {
        $poliklinik = poliklinik::all();

        return view('jadwal', compact('poliklinik'));
    }
</code>```

and the view

```<code>            <div class="row">
                @foreach($poliklinik as $p)
                <div class="col-md-4 animate-box">
                    <div class="blog-entry">
                        <a href="blog.html" class="blog-img" style="background-image: url(images/blog-1.jpg);"></a>
                        <div class="desc">
                            <h3>{{$p->nama_poliklinik}}</h3>
                            <hr/>
                            @foreach($poliklinik->jadwal_poliklinik as $jp)
                            {{$jp->hari}}<br/>
                            @endforeach
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
</code>```

but result is

Exception Property [jadwal_poliklinik] does not exist on this
  collection instance.

can someone help me with this??

答:
It must be $p->jadwal_poliklinik

```<code>@foreach($p->jadwal_poliklinik as $jp)
      {{$jp->hari}}<br/>
 @endforeach
</code>```

But also, Its better if you can use CamelCase for class names. That is the standard. You can simply use artisan command to create classes. See the bellow link for more details.

https://laravel.com/docs/7.x/eloquent#defining-models

Body:
Can Anybody help me with Laravel Relationship ?
i have data base structure

   poliklinik Table
   ===========
   id
   nama_poliklinik
   ****************

   jadwal_poliklinik Table
   =======================
   id
   poliklinik_id
   hari
   ***********************

the relationship is "One" polikinik "have many" jadwal_poliklinik

my model poliklinik is

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\jadwal_poliklinik;

class poliklinik extends Model
{
    protected $table = 'poliklinik';

    public function jadwal_poliklinik()
    {
        return $this->hasMany(jadwal_poliklinik::class);
    }
}

my jadwal_poliklinik model

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\poliklinik;

class jadwal_poliklinik extends Model
{
    protected $table = 'jadwal_poliklinik';

    public function poliklinik()
    {
        return $this->belongsTo(poliklinik::class);
    }

}

my controller is

public function jadwal()
    {
        $poliklinik = poliklinik::all();

        return view('jadwal', compact('poliklinik'));
    }

and the view

                @foreach($poliklinik as $p)

{{$p->nama_poliklinik}}

                            @foreach($poliklinik->jadwal_poliklinik as $jp)
                            {{$jp->hari}}

                            @endforeach

                @endforeach

but result is

Exception Property [jadwal_poliklinik] does not exist on this
  collection instance.

can someone help me with this??

Body:
It must be $p->jadwal_poliklinik

@foreach($p->jadwal_poliklinik as $jp)
      {{$jp->hari}}<br/>
 @endforeach

But also, Its better if you can use CamelCase for class names. That is the standard. You can simply use artisan command to create classes. See the bellow link for more details.

https://laravel.com/docs/7.x/eloquent#defining-models


问:
Converting EditText to int? (Android)
I am wondering how to convert an EditText input to an int, I have the user input a number, which then divides it by 8.

MainActivity.java:

```<code>@SuppressWarnings("unused")
public void calcSpeed(View view)
{
    setContentView(R.layout.activity_speed);

    final TextView mTextView = (TextView) findViewById(R.id.textView3);
    mTextView.setText("You should be getting: " +netSpedCalcd);
}
</code>```

activity_main.xml:

```<code>    <EditText
    android:id="@+id/editText1"
    android:inputType="number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="62dp"
    android:ems="10" >
</code>```

答:
In Kotlin, you can do this.</p>

```<code>val editText1 = findViewById(R.id.editText)
val intNum = editText1.text.toString().toInt()
</code>```

Title: Converting EditText to int? (Android)

Body:
I am wondering how to convert an EditText input to an int, I have the user input a number, which then divides it by 8.

MainActivity.java:

@SuppressWarnings("unused")
public void calcSpeed(View view)
{
    setContentView(R.layout.activity_speed);

    final TextView mTextView = (TextView) findViewById(R.id.textView3);
    mTextView.setText("You should be getting: " +netSpedCalcd);
}

activity_main.xml:

    <EditText
    android:id="@+id/editText1"
    android:inputType="number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="62dp"
    android:ems="10" >

Body:
In Kotlin, you can do this.

val editText1 = findViewById(R.id.editText)
val intNum = editText1.text.toString().toInt()


问:
Convert String value into a list of custom objects
I have a String  [{max=0.0, min=0.0, co=3.0},{max=0.0, min=0.0, co=3.0}]
  I want to convert it to List<CustomObject> where Custom Object is a Java class as

```<code>CustomObject{
   Integer max;
   Integer min;
   Integer co;
  //getter setter
}
</code>```

Is there any optimal way to cast or convert?

答:
I don't think there is a short way to do it using only the Java standard library. But if you use an external library like GSON, it's quite easy:</p>

```<code>String str = "[{max=0.0, min=0.0, co=3.0},{max=0.0, min=0.0, co=3.0}]";

// Parse str to list of maps
List<Map<String, Double>> list = new Gson().fromJson(str, List.class);

// Convert list of maps to list of CustomObject
List<CustomObject> objects = list.stream().map(map -> {
    CustomObject obj = new CustomObject();
    obj.min = map.get("min").intValue();
    obj.max = map.get("max").intValue();
    obj.co = map.get("co").intValue();
    return obj;
}).collect(Collectors.toList());
</code>```

Body:
I have a String  [{max=0.0, min=0.0, co=3.0},{max=0.0, min=0.0, co=3.0}]
  I want to convert it to List<CustomObject> where Custom Object is a Java class as

CustomObject{
   Integer max;
   Integer min;
   Integer co;
  //getter setter
}

Is there any optimal way to cast or convert?

Body:
I don't think there is a short way to do it using only the Java standard library. But if you use an external library like GSON, it's quite easy:

String str = "[{max=0.0, min=0.0, co=3.0},{max=0.0, min=0.0, co=3.0}]";

// Parse str to list of maps
List<Map<String, Double>> list = new Gson().fromJson(str, List.class);

// Convert list of maps to list of CustomObject
List<CustomObject> objects = list.stream().map(map -> {
    CustomObject obj = new CustomObject();
    obj.min = map.get("min").intValue();
    obj.max = map.get("max").intValue();
    obj.co = map.get("co").intValue();
    return obj;
}).collect(Collectors.toList());


问:
Add string to h5 file
I have the following code:

```<code>import tables
import numpy as np

filename = "file.h5"

x = np.random.random(150)
z = np.random.random(150)
mystr = " " * 160

f = tables.open_file(filename, mode="w")
hds = f.create_carray(f.root, "x", obj=x,
                      filters=tables.Filters(complevel=5, complib='zlib'))
hds = f.create_carray(f.root, "z", obj=z,
                      filters=tables.Filters(complevel=5, complib='zlib'))
f.close()
</code>```

I would like to add a string to my file with the length of 160. Is there an elegant way to do this?

Thank you in advance.

答:
Storing string type data in H5 is somewhat tricky. It is a common problem for the first time H5 user in Python. The data type must be presented clearly before putting into an H5 dataset (i.e., whether if it is a string, integer, or float). As for string data type, you need to specify it as a variable. For example, dt = h5py.string_dtype().

Below is an example to put a string in a H5 file.

```<code>import h5py
data = 'value in string'
f= h5py.File('./fname.h5','w')
try:
    dt = h5py.string_dtype()
    f.create_dataset('str_data', data=data, dtype=dt)
except Exception as ex:
    print(ex)
finally:
    f.close()
</code>```

Also, for your reference, to check if the data is stored correctly, just use the following code.

```<code>f= h5py.File('./fname.h5','r')
try:
    print(f.keys())
    print(f['str_data'][()])
except Exception as ex:
    print(ex)
finally:
    f.close()
</code>```

For further reference, please read the H5 documentation about String in HDF5.
http://docs.h5py.org/en/stable/strings.html

Title: Add string to h5 file

Body:
I have the following code:

import tables
import numpy as np

filename = "file.h5"

x = np.random.random(150)
z = np.random.random(150)
mystr = " " * 160

f = tables.open_file(filename, mode="w")
hds = f.create_carray(f.root, "x", obj=x,
                      filters=tables.Filters(complevel=5, complib='zlib'))
hds = f.create_carray(f.root, "z", obj=z,
                      filters=tables.Filters(complevel=5, complib='zlib'))
f.close()

I would like to add a string to my file with the length of 160. Is there an elegant way to do this?

Thank you in advance.

Body:
Storing string type data in H5 is somewhat tricky. It is a common problem for the first time H5 user in Python. The data type must be presented clearly before putting into an H5 dataset (i.e., whether if it is a string, integer, or float). As for string data type, you need to specify it as a variable. For example, dt = h5py.string_dtype().

Below is an example to put a string in a H5 file.

import h5py
data = 'value in string'
f= h5py.File('./fname.h5','w')
try:
    dt = h5py.string_dtype()
    f.create_dataset('str_data', data=data, dtype=dt)
except Exception as ex:
    print(ex)
finally:
    f.close()

Also, for your reference, to check if the data is stored correctly, just use the following code.

f= h5py.File('./fname.h5','r')
try:
    print(f.keys())
    print(f['str_data'][()])
except Exception as ex:
    print(ex)
finally:
    f.close()

For further reference, please read the H5 documentation about String in HDF5.
http://docs.h5py.org/en/stable/strings.html


问:
Using pandas dataframes, how to read through a column to find "True" statement and then proceed to create a new dataframe
Below I have 4 columns in my dataframe. I am interested in going through the entire "Greater_than_50" column. Upon reaching a "True" flag, I then want to take the associated  "Discharge" and "Resistance" values to make a new dataframe which contains only those values found to be "True".

```<code>time           Discharge          Resistance  Greater_than_50
-------------------------------------------------------------
0                  0.000                 NaN              NaN
1                  0.005              76.373             True
2                  0.010             -48.174            False
3                  0.016             -37.012            False
4                  0.021             -27.808            False
5                  0.026             -24.674            False
6                  0.031             -20.464            False
7                  0.037             100.114            True
...                  ...                 ...              ...
</code>```

I would like the new dataframe to look something like this:

```<code>Discharge          Resistance
------------------------------
0.005              76.373
0.037             100.114
...                   ...

</code>```

答:
Assuming the positions of columns "Discharge" and "Resistance" are 1 and 2, df2 is what you need

```<code>df1 = df[df.Greater_than_50 == True]
df2 = df1.iloc[:, 1:3]
</code>```

You can do a one liner like so

```<code>df2 = df[df.Greater_than_50 == True].iloc[:, 1:3]
</code>```

Body:
Below I have 4 columns in my dataframe. I am interested in going through the entire "Greater_than_50" column. Upon reaching a "True" flag, I then want to take the associated  "Discharge" and "Resistance" values to make a new dataframe which contains only those values found to be "True".

time           Discharge          Resistance  Greater_than_50
-------------------------------------------------------------
0                  0.000                 NaN              NaN
1                  0.005              76.373             True
2                  0.010             -48.174            False
3                  0.016             -37.012            False
4                  0.021             -27.808            False
5                  0.026             -24.674            False
6                  0.031             -20.464            False
7                  0.037             100.114            True
...                  ...                 ...              ...

I would like the new dataframe to look something like this:

Discharge          Resistance
------------------------------
0.005              76.373
0.037             100.114
...                   ...

Body:
Assuming the positions of columns "Discharge" and "Resistance" are 1 and 2, df2 is what you need

df1 = df[df.Greater_than_50 == True]
df2 = df1.iloc[:, 1:3]

You can do a one liner like so

df2 = df[df.Greater_than_50 == True].iloc[:, 1:3]


问:
How to write unit test case for JWT strategy
I am new to passport.js and trying to cover the unit test case for my JWT strategy. Can anyone suggest how to do that?</p>

```<code>// Setup JWT strategy for all requests
passport.use(
  new JWTStrategy(
    {
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: JWT_PRIVATE_KEY,
    },
    async (jwtPayload: any, done: any) => {
      const isUser = jwtPayload.type === EntityType.User;
      const model = isUser ? userModel : vendorModel;
      try {
        const document = await model.findOne({ _id: jwtPayload.id });
        if (document) {
          return done(null, jwtPayload);
        } else {
          return done(null, false);
        }
      } catch (err) {
        return done(err, false);
      }
    },
  ),
);
</code>```

答:
Unit test solution:

index.ts:

import passport from 'passport';
import { Strategy as JWTStrategy, ExtractJwt } from 'passport-jwt';
import { userModel, vendorModel, EntityType } from './models';

const JWT_PRIVATE_KEY = 'secret 123';

passport.use(
  new JWTStrategy(
    {
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: JWT_PRIVATE_KEY,
    },
    async (jwtPayload: any, done: any) => {
      console.log('123123');
      const isUser = jwtPayload.type === EntityType.User;
      const model = isUser ? userModel : vendorModel;
      try {
        const document = await model.findOne({ _id: jwtPayload.id });
        if (document) {
          return done(null, jwtPayload);
        } else {
          return done(null, false);
        }
      } catch (err) {
        return done(err, false);
      }
    },
  ),
);
```

<p><code>models.ts</code>:</p>

<pre class="lang-js prettyprint-override"><code>export enum EntityType {
  User = 'User',
}
export const userModel = {
  async findOne(opts) {
    return 'real user document';
  },
};
export const vendorModel = {
  async findOne(opts) {
    return 'real vendor document';
  },
};
</code>```

index.test.ts:

import { Strategy as JWTStrategy, ExtractJwt, VerifyCallback, StrategyOptions } from 'passport-jwt';
import passport from 'passport';
import { userModel, vendorModel } from './models';

jest.mock('passport-jwt', () => {
  const mJWTStrategy = jest.fn();
  const mExtractJwt = {
    fromAuthHeaderAsBearerToken: jest.fn(),
  };
  return { Strategy: mJWTStrategy, ExtractJwt: mExtractJwt };
});
jest.mock('passport', () => {
  return { use: jest.fn() };
});

describe('62125872', () => {
  let verifyRef;
  beforeEach(() => {
    const mJwtFromRequestFunction = jest.fn();
    (ExtractJwt.fromAuthHeaderAsBearerToken as jest.MockedFunction<
      typeof ExtractJwt.fromAuthHeaderAsBearerToken
    >).mockReturnValueOnce(mJwtFromRequestFunction);

    (JWTStrategy as jest.MockedClass<any>).mockImplementation((opt: StrategyOptions, verify: VerifyCallback) => {
      verifyRef = verify;
    });
  });

  it('should verify using user model and call done with jwtpayload if user document exists', async () => {
    const payload = { type: 'User', id: 1 };
    const mDone = jest.fn();

    jest.spyOn(userModel, 'findOne').mockResolvedValueOnce('mocked user document');
    await import('./');
    await verifyRef(payload, mDone);
    expect(passport.use).toBeCalledWith(expect.any(Object));
    expect(JWTStrategy).toBeCalledWith(
      { jwtFromRequest: expect.any(Function), secretOrKey: 'secret 123' },
      expect.any(Function),
    );
    expect(ExtractJwt.fromAuthHeaderAsBearerToken).toBeCalledTimes(1);
    expect(userModel.findOne).toBeCalledWith({ _id: 1 });
    expect(mDone).toBeCalledWith(null, { type: 'User', id: 1 });
  });

  it("should verify using user model and call done with false if user document doesn't exist", async () => {
    const payload = { type: 'User', id: 1 };
    const mDone = jest.fn();

    jest.spyOn(userModel, 'findOne').mockResolvedValueOnce('');
    await import('./');
    await verifyRef(payload, mDone);
    expect(passport.use).toBeCalledWith(expect.any(Object));
    expect(JWTStrategy).toBeCalledWith(
      { jwtFromRequest: expect.any(Function), secretOrKey: 'secret 123' },
      expect.any(Function),
    );
    expect(ExtractJwt.fromAuthHeaderAsBearerToken).toBeCalledTimes(1);
    expect(userModel.findOne).toBeCalledWith({ _id: 1 });
    expect(mDone).toBeCalledWith(null, false);
  });

  // you can do the rest parts
});
```

<p>Unit test results:</p>

<pre class="lang-sh prettyprint-override"><code> PASS  stackoverflow/62125872/index.test.ts
  62125872
    ✓ should verify using user model and call done with jwtpayload if user document exists (11ms)
    ✓ should verify using user model and call done with false if user document doesn't exist (2ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |      85 |    83.33 |      60 |   84.21 |
 index.ts  |   92.86 |       75 |     100 |   92.31 | 24
 models.ts |   66.67 |      100 |   33.33 |   66.67 | 6,11
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.716s, estimated 10s
</code>```

Body:
I am new to passport.js and trying to cover the unit test case for my JWT strategy. Can anyone suggest how to do that?

// Setup JWT strategy for all requests
passport.use(
  new JWTStrategy(
    {
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: JWT_PRIVATE_KEY,
    },
    async (jwtPayload: any, done: any) => {
      const isUser = jwtPayload.type === EntityType.User;
      const model = isUser ? userModel : vendorModel;
      try {
        const document = await model.findOne({ _id: jwtPayload.id });
        if (document) {
          return done(null, jwtPayload);
        } else {
          return done(null, false);
        }
      } catch (err) {
        return done(err, false);
      }
    },
  ),
);

Body:
Unit test solution:

index.ts:

import passport from 'passport';
import { Strategy as JWTStrategy, ExtractJwt } from 'passport-jwt';
import { userModel, vendorModel, EntityType } from './models';

const JWT_PRIVATE_KEY = 'secret 123';

passport.use(
  new JWTStrategy(
    {
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: JWT_PRIVATE_KEY,
    },
    async (jwtPayload: any, done: any) => {
      console.log('123123');
      const isUser = jwtPayload.type === EntityType.User;
      const model = isUser ? userModel : vendorModel;
      try {
        const document = await model.findOne({ _id: jwtPayload.id });
        if (document) {
          return done(null, jwtPayload);
        } else {
          return done(null, false);
        }
      } catch (err) {
        return done(err, false);
      }
    },
  ),
);

models.ts:

export enum EntityType {
  User = 'User',
}
export const userModel = {
  async findOne(opts) {
    return 'real user document';
  },
};
export const vendorModel = {
  async findOne(opts) {
    return 'real vendor document';
  },
};

index.test.ts:

import { Strategy as JWTStrategy, ExtractJwt, VerifyCallback, StrategyOptions } from 'passport-jwt';
import passport from 'passport';
import { userModel, vendorModel } from './models';

jest.mock('passport-jwt', () => {
  const mJWTStrategy = jest.fn();
  const mExtractJwt = {
    fromAuthHeaderAsBearerToken: jest.fn(),
  };
  return { Strategy: mJWTStrategy, ExtractJwt: mExtractJwt };
});
jest.mock('passport', () => {
  return { use: jest.fn() };
});

describe('62125872', () => {
  let verifyRef;
  beforeEach(() => {
    const mJwtFromRequestFunction = jest.fn();
    (ExtractJwt.fromAuthHeaderAsBearerToken as jest.MockedFunction<
      typeof ExtractJwt.fromAuthHeaderAsBearerToken
    >).mockReturnValueOnce(mJwtFromRequestFunction);

    (JWTStrategy as jest.MockedClass<any>).mockImplementation((opt: StrategyOptions, verify: VerifyCallback) => {
      verifyRef = verify;
    });
  });

  it('should verify using user model and call done with jwtpayload if user document exists', async () => {
    const payload = { type: 'User', id: 1 };
    const mDone = jest.fn();

    jest.spyOn(userModel, 'findOne').mockResolvedValueOnce('mocked user document');
    await import('./');
    await verifyRef(payload, mDone);
    expect(passport.use).toBeCalledWith(expect.any(Object));
    expect(JWTStrategy).toBeCalledWith(
      { jwtFromRequest: expect.any(Function), secretOrKey: 'secret 123' },
      expect.any(Function),
    );
    expect(ExtractJwt.fromAuthHeaderAsBearerToken).toBeCalledTimes(1);
    expect(userModel.findOne).toBeCalledWith({ _id: 1 });
    expect(mDone).toBeCalledWith(null, { type: 'User', id: 1 });
  });

  it("should verify using user model and call done with false if user document doesn't exist", async () => {
    const payload = { type: 'User', id: 1 };
    const mDone = jest.fn();

    jest.spyOn(userModel, 'findOne').mockResolvedValueOnce('');
    await import('./');
    await verifyRef(payload, mDone);
    expect(passport.use).toBeCalledWith(expect.any(Object));
    expect(JWTStrategy).toBeCalledWith(
      { jwtFromRequest: expect.any(Function), secretOrKey: 'secret 123' },
      expect.any(Function),
    );
    expect(ExtractJwt.fromAuthHeaderAsBearerToken).toBeCalledTimes(1);
    expect(userModel.findOne).toBeCalledWith({ _id: 1 });
    expect(mDone).toBeCalledWith(null, false);
  });

  // you can do the rest parts
});

Unit test results:

 PASS  stackoverflow/62125872/index.test.ts
  62125872
    ✓ should verify using user model and call done with jwtpayload if user document exists (11ms)
    ✓ should verify using user model and call done with false if user document doesn't exist (2ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |      85 |    83.33 |      60 |   84.21 |
 index.ts  |   92.86 |       75 |     100 |   92.31 | 24
 models.ts |   66.67 |      100 |   33.33 |   66.67 | 6,11
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.716s, estimated 10s


问:
Split a python string by particular identifications
I am trying to split a python string when a particular character appears.

For example:

```<code>mystring="I want to eat an apple. \n 12345 \n 12 34 56"
</code>```

The output I want is a string with

```<code>[["I want to eat an apple"], [12345], [12, 34, 56]]
</code>```

答:
Use split(),strip() and re for this question

First split the strings by nextline and then strip each of them and then extract numbers from string by re, if length is more than one then replace the item

```<code>import re
mystring="I want to eat an apple. \n 12345 \n 12 34 56"
l = [i.strip() for i in mystring.split("\n")]
for idx,i in enumerate(l):
  if len(re.findall(r'\d+',i))>1:
    l[idx] = re.findall(r'\d+',i)

print(l)
#['I want to eat an apple.', '12345', ['12', '34', '56']]
</code>```

Body:
I am trying to split a python string when a particular character appears.

For example:

mystring="I want to eat an apple. \n 12345 \n 12 34 56"

The output I want is a string with

[["I want to eat an apple"], [12345], [12, 34, 56]]

Body:
Use split(),strip() and re for this question

First split the strings by nextline and then strip each of them and then extract numbers from string by re, if length is more than one then replace the item

import re
mystring="I want to eat an apple. \n 12345 \n 12 34 56"
l = [i.strip() for i in mystring.split("\n")]
for idx,i in enumerate(l):
  if len(re.findall(r'\d+',i))>1:
    l[idx] = re.findall(r'\d+',i)

print(l)
#['I want to eat an apple.', '12345', ['12', '34', '56']]


问:
How do I insert a linebreak where the cursor is without entering into insert mode in Vim?
Is possible to insert a line break where the cursor is in Vim without entering into insert mode? Here's an example ([x] means cursor is on x):

```<code>if (some_condition) {[ ]return; }
</code>```

Occasionally, I might want to enter some more code. So I'd press i to get into insert mode, press Enter to insert the line break and then delete the extra space. Next, I'd enter normal mode and position the cursor before the closing brace and then do the same thing to get it on its own line.

I've been doing this a while, but there's surely a better way to do it?

答: o ESC command will do it for you.

OwnerDisplayName: Mark A. Nicolosi

Body:
Is possible to insert a line break where the cursor is in Vim without entering into insert mode? Here's an example ([x] means cursor is on x):

if (some_condition) {[ ]return; }

Occasionally, I might want to enter some more code. So I'd press i to get into insert mode, press Enter to insert the line break and then delete the extra space. Next, I'd enter normal mode and position the cursor before the closing brace and then do the same thing to get it on its own line.

I've been doing this a while, but there's surely a better way to do it?

LastEditorDisplayName: Greg Hewgill

Body: o ESC command will do it for you.


问:
Tear Down Resource Groups on PR Completion
I am using Pull Request Builds as outlined below to create a resource group with contained resources

https://learn.microsoft.com/en-us/azure/devops/pipelines/release/deploy-pull-request-builds?view=azure-devops

This all works as expected and I am using the SourceBranch of the Pull Request to name by new Resource Group.

My intention is to then delete the Resource Group automatically on completion of the PR. I believed this could be achieved by using another Release pipeline triggered on the build triggered by the PR merge to Master. The issue is that I have no reference to the Branch name in this new Release, the SourceBranch is 'master'

Can anyone come up with a solution? Essentially I need to delete a Resource Group named after a Branch on completion of a PR which merges said branch to master.

There may be multiple PRs in review at any one time so I would prefer that the solution does not queue any stages.

答:
The issue is that I have no reference to the Branch name in this new Release, the SourceBranch is 'master'

The Pull Request triggered release pipeline is triggered by refs/pull/x/merge. This is related with the Pull Request. Then the Pull Request information can be obtained through environment variables.

When the Pull Request Completes, the reason for running the release pipeline is that the master branch has changed. The trigger branch is master.

In this case, the variable BUILD_SOURCEBRANCHNAME is master.

Based on my test, I couldn't find the environment variables related to Pull Request Source Branch.

So I am afraid that there is no such variable could meet your requirements.

For a workaround:

If you want to get the expected source branch name , you may need to use the target branch to run the release pipeline again(Manual or Continuous deployment trigger).You need to make sure that the trigger branch is pull request source branch. Then the BUILD_SOURCEBRANCHNAME variable could be the expected one.

not queue any stages.

You could try to set the Artifacts filters (include and exclude) in Release Pipeline stages.

For example:

Result:

Hope this helps.


问:
what happen with my componentDidUpdate in reactjs?

this is file app.js

```<code>...
constructor(props) {
    super(props);
    this.state = {
      todoLists: [],
      inputValue: "",
      currentName: "",
      todoSearch: "",
      idUpdate: "",
      loader: true
    };
  }
 componentDidUpdate(){
    this.setState({
      loader: true
    })
  }
  componentDidMount() {
    axios
      .get("https://5ec912d99ccbaf0016aa8b6f.mockapi.io/todoLists")
      .then((res) => {
        this.setState({
          loader: false,
          todoLists: res.data
        });
      });
  }
...
</code>```

i added componentDidUpdate in my App but it message :  Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

答:
Hi try this way to avoid maximum loop executions.</p>

```<code>import React from "react";
import axios from "axios";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todoLists: [],
      loader: true
    };
  }
  componentDidMount() {
    this.setState({ loader: true });
    axios
      .get("https://5ec912d99ccbaf0016aa8b6f.mockapi.io/todoLists")
      .then(res => {
        console.log(res.data);
        this.setState({
          loader: false,
          todoLists: res.data
        });
      });
  }
  render() {
    const { loader } = this.state;
    return (
      <div>
        {loader
          ? "Loading"
          : this.state.todoLists.map(res => {
              return (
                <ul key={res.id}>
                  <li>{res.id}</li>
                  <li>{res.name}</li>
                </ul>
              );
            })}
      </div>
    );
  }
}

export default App;
</code>```

Body:
this is file app.js

...
constructor(props) {
    super(props);
    this.state = {
      todoLists: [],
      inputValue: "",
      currentName: "",
      todoSearch: "",
      idUpdate: "",
      loader: true
    };
  }
 componentDidUpdate(){
    this.setState({
      loader: true
    })
  }
  componentDidMount() {
    axios
      .get("https://5ec912d99ccbaf0016aa8b6f.mockapi.io/todoLists")
      .then((res) => {
        this.setState({
          loader: false,
          todoLists: res.data
        });
      });
  }
...

i added componentDidUpdate in my App but it message :  Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

Body:
Hi try this way to avoid maximum loop executions.

import React from "react";
import axios from "axios";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todoLists: [],
      loader: true
    };
  }
  componentDidMount() {
    this.setState({ loader: true });
    axios
      .get("https://5ec912d99ccbaf0016aa8b6f.mockapi.io/todoLists")
      .then(res => {
        console.log(res.data);
        this.setState({
          loader: false,
          todoLists: res.data
        });
      });
  }
  render() {
    const { loader } = this.state;
    return (
      <div>
        {loader
          ? "Loading"
          : this.state.todoLists.map(res => {
              return (
                <ul key={res.id}>
                  <li>{res.id}</li>
                  <li>{res.name}</li>
                </ul>
              );
            })}
      </div>
    );
  }
}

export default App;


问:
Python one liner with function
I am strengthening my understanding of one liner in Python and have some difficulties for the following one. I would like to use list comprehension to make it shorter. Any contribution would be great please.</p>

```<code>daily_prices_l = []
daily_prices_h = []
for b in bitwise_exchanges:
  try:
    high = daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').high
    low = daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').low
    daily_prices_l.append(high.rename(b))
    daily_prices_h.append(low.rename(b))
  except:
    pass
daily_prices_l = pd.concat(daily_prices_l, axis=1)
daily_prices_h = pd.concat(daily_prices_h, axis=1)
</code>```

答:
This is pretty unnecessary, taking that it is hard to read, but here is a way:</p>

```<code>try: daily_prices_l,daily_prices_h = pd.concat([daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').high.rename(b) for b in bitwise_exchanges],axis=1),pd.concat([daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').low.rename(b) for b in bitwise_exchanges],axis=1)
except: pass
</code>```

Title: Python one liner with function

Body:
I am strengthening my understanding of one liner in Python and have some difficulties for the following one. I would like to use list comprehension to make it shorter. Any contribution would be great please.

daily_prices_l = []
daily_prices_h = []
for b in bitwise_exchanges:
  try:
    high = daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').high
    low = daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').low
    daily_prices_l.append(high.rename(b))
    daily_prices_h.append(low.rename(b))
  except:
    pass
daily_prices_l = pd.concat(daily_prices_l, axis=1)
daily_prices_h = pd.concat(daily_prices_h, axis=1)

Body:
This is pretty unnecessary, taking that it is hard to read, but here is a way:

try: daily_prices_l,daily_prices_h = pd.concat([daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').high.rename(b) for b in bitwise_exchanges],axis=1),pd.concat([daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').low.rename(b) for b in bitwise_exchanges],axis=1)
except: pass


问:
Running protractor test in chrome driver doest not opens up any website
```<code>System Details
Mac OS, Chromedriver v=83.0.4103.39 , Protractor=7.0
</code>```

My test is failing all the time when chromedriver opens any website it says your connection is not private please let me know how to fix this issue
chromedriver page

My spec.js looks like below

```<code>describe('angularjs homepage todo list', function() {
  it('should add a todo', function() {
      browser.get('https://angularjs.org');
  });
});
</code>```

config.js looks like below

```<code>exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['spec.js'],
};
</code>```

答:
this is how my proxies look like
proxy settings in mac

Changes my config.js to
exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['spec1.js'],
  //acceptInsecureCerts : true
  'args': ['--disable-web-security', '--user-data-dir=~/.e2e-chrome-profile', '--ignore-certificate-errors']
};

Still any URL like facebook.com or google.com I am getting err_invalid_cert err

Body:
System Details
Mac OS, Chromedriver v=83.0.4103.39 , Protractor=7.0

My test is failing all the time when chromedriver opens any website it says your connection is not private please let me know how to fix this issue
chromedriver page

My spec.js looks like below

describe('angularjs homepage todo list', function() {
  it('should add a todo', function() {
      browser.get('https://angularjs.org');
  });
});

config.js looks like below

exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['spec.js'],
};


问:
can't display data in the table (angular 9)
enter image description here`     Hi ! i am using angular 9.1.7 , the code works correctly , and i succeed to get data from base , but i can't display them in the html table , i don't understand the source of this. you find below some source code , and thank you in advance

`

==>Interface package:
     public universites:Universite[];
      public universitesall:Universite[];
      public mot_cle:string="";
      constructor(private universitesService:UniversitesService) { }

      ngOnInit(): void {
        this.Afficheruniversites();
      }
      Afficheruniversites()`enter code here`
      {
        this.universitesService.tous_universites().subscribe(data=>{
          this.universites=data;
          this.universitesall=data;
          console.log(data);
        },err=>{console.log(err);
      })
      }

      ==>> model
      export class Universite {
        code_UNV:number
        nom_UNV:String
        adresse_site_UNV:String

        constructor(Code_uni:number, Nom_uni:String,Adr:String)
        {
            this.code_UNV=Code_uni;
            this.nom_UNV=Nom_uni;
            this.adresse_site_UNV=Adr;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>==>> Html
     <table *ngIf="universites" class="table table-striped">
                    <tr>
                        <th>
                            Code
                        </th>
                        <th>
                            Nom
                        </th>
                        <th>
                            Adresse
                        </th><th></th>
                        <tr *ngFor="let c of universites">
                            <td>
                                {{c.code_UNV}}
                            </td>
                            <td>
                                {{c.nom_UNV}}
                            </td>
                            <td>
                                {{c.adresse_site_UNV}}
                            </td>
                        </tr>
                </table></code>```

答:
You need check your data, in attach image, it console log as codeUNV not code_UNV as your defined.

I tried reproduce your code, it work.

https://stackblitz.com/edit/angular-ivy-1tr7we

Body:
enter image description here`     Hi ! i am using angular 9.1.7 , the code works correctly , and i succeed to get data from base , but i can't display them in the html table , i don't understand the source of this. you find below some source code , and thank you in advance

`

==>Interface package:
     public universites:Universite[];
      public universitesall:Universite[];
      public mot_cle:string="";
      constructor(private universitesService:UniversitesService) { }

      ngOnInit(): void {
        this.Afficheruniversites();
      }
      Afficheruniversites()`enter code here`
      {
        this.universitesService.tous_universites().subscribe(data=>{
          this.universites=data;
          this.universitesall=data;
          console.log(data);
        },err=>{console.log(err);
      })
      }

      ==>> model
      export class Universite {
        code_UNV:number
        nom_UNV:String
        adresse_site_UNV:String

        constructor(Code_uni:number, Nom_uni:String,Adr:String)
        {
            this.code_UNV=Code_uni;
            this.nom_UNV=Nom_uni;
            this.adresse_site_UNV=Adr;
        }
    }

==>> Html

                            Code

                            Nom

                            Adresse

                                {{c.code_UNV}}

                                {{c.nom_UNV}}

                                {{c.adresse_site_UNV}}


问:
Play Video from SMB/CIFS file server
I'm a novice in SMB.

Current, I need to read and play .mp4 video files from an SMB server in flutter app.
But currently, we haven't found any possible library for this task.

Does anyone know how to open and read files in SMB from flutter app.

答:
Have you tried this: libsdms?

To play mp4 files though you need to also embed an http server in your app, since you need an http path (instead of the smb file path you get). So you need to convert your file to bits, then stream via http and play the http file in your app.

Check this for more : http server

Title: Play Video from SMB/CIFS file server


问:
How can I "grep" for a filename instead of the contents of a file?
grep is used to search within a file to see if any line matches a given regular expression. However, I have this situation - I want to write a regular expression that will match the filename itself (and not the contents of the file). I will run this from the system's root directory, to find all those files that match the regular expression.

For example, if I want to find all Visual Basic form files that start with an "f" and end with .frm, I'll use the regular expression -

```<code>   "f[[:alnum:]]*\.frm"
</code>```

Can grep do this? If not, is there a utility that would let me do this?

答:
The easiest way is

```<code>find . | grep test
</code>```

Here find will list all the files in the (.), i.e., the
current directory, recursively.

And then it is just a simple grep. All the files which name has "test" will appear.

You can play with grep as per your requirement.
Note: As the grep is a generic string classification. It can result in giving you not only file names. But if a path has a directory ('/xyz_test_123/other.txt') it would also be part of the result set.

Body:
grep is used to search within a file to see if any line matches a given regular expression. However, I have this situation - I want to write a regular expression that will match the filename itself (and not the contents of the file). I will run this from the system's root directory, to find all those files that match the regular expression.

For example, if I want to find all Visual Basic form files that start with an "f" and end with .frm, I'll use the regular expression -

   "f[[:alnum:]]*\.frm"

Can grep do this? If not, is there a utility that would let me do this?

Body:
The easiest way is

find . | grep test

Here find will list all the files in the (.), i.e., the
current directory, recursively.

And then it is just a simple grep. All the files which name has "test" will appear.

You can play with grep as per your requirement.
Note: As the grep is a generic string classification. It can result in giving you not only file names. But if a path has a directory ('/xyz_test_123/other.txt') it would also be part of the result set.


问:
What is the difference between $lt and $not $gt in MongoDB?
db.restaurants.find( { "grades.score": { $not: { $gt: 10 }}}, { "grades.score": 1})

and

db.restaurants.find( { "grades.score": { $lt: 10 }}, { "grades.score": 1})

What would be the difference between these two queries? (i.e. less than 10, and not greater than 10)

答: Just a wild guess - Not Greater than is the same as Less than or equal to... not Less than. Mathematics is only my minor, but I'm pretty sure!</p>


问:
I can't implement marzipano tour 360 on local
I'm trying to use Laravel and Marzipano to make my own virtual tour but I'm having trouble making the photos look on the page. The page goes blank and when I click, the mouse changes to the typical 360 photo motion cross. I have no idea where the problem is because it's the first time I've used it and I've never used anything like it.
This is my code:

```<code><html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Trial</title>
    <script type="text/javascript" src="{{ url('js/marzipano/marzipano.js') }}"></script>

</head>
<body>
    <div id="domID"></div>
    <script type="text/javascript">
        var panoElement = document.getElementById("domID");
        var opts = {
            controls: {
                mouseViewMode: "drag"
            }
        }

        var viewer = new Marzipano.Viewer(panoElement, opts);

        var levels = [
            { tileSize: 512, size: 512 },
            { tileSize: 512, size: 1024 }
        ];

        var geometry = new Marzipano.CubeGeometry(levels);
        var source = Marzipano.ImageUrlSource.fromString("imgs/R0010598.JPG");
        var view = new Marzipano.RectilinearView();

        var scene = viewer.createScene({
            source: source,
            geometry: geometry,
            view: view
        });

        scene.switchTo();
    </script>
</body>
</html>
</code>```

Thank you.

答: run this on LocalHost . try to have some time saving extensions on VS code like LiveServer . Go to Html page and click on GoLive on Bottom Right corner of your screen .Add marzipano.js in project and require it .  </p>

Body:
I'm trying to use Laravel and Marzipano to make my own virtual tour but I'm having trouble making the photos look on the page. The page goes blank and when I click, the mouse changes to the typical 360 photo motion cross. I have no idea where the problem is because it's the first time I've used it and I've never used anything like it.
This is my code:

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Trial</title>

Thank you.


问:
Download an excel file saved on flask server
I have a flask app that has an existing xlsx file in the downloads folder. I am trying to make the front-end download the excel file on a button click. As of right now, my flask server is accessing the file correctly, but sending it as nonsensical string data in the response. I'm assuming I need to use some library to parse the data into an excel workbook and then download it, but I'm having trouble finding answers.
Here is the flask code:

```<code>
    @app.route('/download')
    @handle_errors
    def downloadFile():
        filename = request.args.get('filename')
        uploadPath = sys.path[0] + '\\workflow\\downloads'
        return send_file(uploadPath + '\\' + filename, as_attachment=True)

</code>```

Here is the front end react code:

```<code>
    getFile = (e) => {
        e.preventDefault();
        e.persist();
        const filename = e.target.getAttribute('name');
        axios
          .get(`http://localhost:5000/download?filename=${filename}`)
          .then((data) => {
            console.log('this is data: ', data);
            console.log('Completed: download');
          })
          .catch(() => {
            console.log('We were not able to complete your request.');
          });
      };

</code>```

答:
Your server already seems to be sending a blob. So in the frontend, do:

use URL.createObjectURL and create url object from response.data

create an anchor tag on the fly and associate the url object to the href

call click() which will download the file on client

remove the anchor tag

Code snippet

getFile = (e) => {
    e.preventDefault();
    e.persist();
    const filename = e.target.getAttribute('name');
    axios
      .get(`http://localhost:5000/download?filename=${filename}`)
      .then((data) => {
        console.log('this is data: ', data.data);
        const link = document.createElement('a');
        const url = URL.createObjectURL(data.data) //<---- this should be data.data
        link.download = true;
        link.href = url;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
      .catch(() => {
        console.log('We were not able to complete your request.');
      });
  };
```

Body:
I have a flask app that has an existing xlsx file in the downloads folder. I am trying to make the front-end download the excel file on a button click. As of right now, my flask server is accessing the file correctly, but sending it as nonsensical string data in the response. I'm assuming I need to use some library to parse the data into an excel workbook and then download it, but I'm having trouble finding answers.
Here is the flask code:

    @app.route('/download')
    @handle_errors
    def downloadFile():
        filename = request.args.get('filename')
        uploadPath = sys.path[0] + '\\workflow\\downloads'
        return send_file(uploadPath + '\\' + filename, as_attachment=True)

Here is the front end react code:

    getFile = (e) => {
        e.preventDefault();
        e.persist();
        const filename = e.target.getAttribute('name');
        axios
          .get(`http://localhost:5000/download?filename=${filename}`)
          .then((data) => {
            console.log('this is data: ', data);
            console.log('Completed: download');
          })
          .catch(() => {
            console.log('We were not able to complete your request.');
          });
      };


问:
checkbox logic not working in open layers js file
In my code i have two grid on for base layer other for utility layer .
Base layer has radio button  and on clicking the logic used is working

```<code>{

    var baseLayerGroup= new ol.layer.Group({
    layers:[
        openstreetmapstandard,openstreetmaphumanitarian
    ]
})
map.addLayer(baseLayerGroup);

//Layer Switcher Logic for Baselayer
var baseLayerElements = document.querySelectorAll('.sidebar1 > input[type=radio]');
for(let baseLayerElement of baseLayerElements){
    baseLayerElement.addEventListener('change',function(){
        let baseLayerElementValue = this.value;
        baseLayerGroup.getLayers().forEach(function(element, index, array){
            let baseLayerTitle = element.get('title');
            element.setVisible(baseLayerTitle === baseLayerElementValue);
        })
    })
}
var dataLayerGroup= new ol.layer.Group({
    layers:[
        Sector_office,Roads
    ]
})
</code>```

and my logic for checkbox is :

```<code>Sector_office.setVisible(true);
Roads.setVisible(false);
var toggleLayer = function(inputEl){
     map.getLayers().forEach(function(layer){
          if (layer.get('name') === inputEl.name)
          layer.setVisible(inputEl.checked);
          });
        };
map.addLayer(dataLayerGroup);
</code>```

but my checkbox logic is not working  and here is my html page for it

```<code>   <input type="checkbox" onClick="toggleLayer(this);" value="Sector_office" checked>Sector office<br>
    <input type="checkbox" onClick="toggleLayer(this);" value="Roads" checked>Roads<br>
  </div>
</code>```

答:
For what I see you have a couple of issues in your code.

In the handler function you are referencing the name attribute of the dom element, but I see not such attribute in the html. That will always result false. So you have to set the name attribute or use the value attribute.

The onclick event handler receive as a parameter a MouseEvent argument. To get a reference of the dom element inside the handler you can use this or you can use the event argument attribute target.

Resuming,

handler

const toggleLayer = function(e){
    const chk = e.target.
    map.getLayers().forEach(function(layer){
        if (layer.get('name') === chk.value)
        layer.setVisible(chk.checked);
    });
};
```

<p><em>html</em></p>

<pre class="lang-html prettyprint-override"><code><input type="checkbox" onclick="toggleLayer(event)"
    value="Sector_office" checked>Sector office<br>
<input type="checkbox" onclick="toggleLayer(event)"
    value="Roads" checked>Roads<br>
</code>```

Body:
In my code i have two grid on for base layer other for utility layer .
Base layer has radio button  and on clicking the logic used is working

{

    var baseLayerGroup= new ol.layer.Group({
    layers:[
        openstreetmapstandard,openstreetmaphumanitarian
    ]
})
map.addLayer(baseLayerGroup);

//Layer Switcher Logic for Baselayer
var baseLayerElements = document.querySelectorAll('.sidebar1 > input[type=radio]');
for(let baseLayerElement of baseLayerElements){
    baseLayerElement.addEventListener('change',function(){
        let baseLayerElementValue = this.value;
        baseLayerGroup.getLayers().forEach(function(element, index, array){
            let baseLayerTitle = element.get('title');
            element.setVisible(baseLayerTitle === baseLayerElementValue);
        })
    })
}
var dataLayerGroup= new ol.layer.Group({
    layers:[
        Sector_office,Roads
    ]
})

and my logic for checkbox is :

Sector_office.setVisible(true);
Roads.setVisible(false);
var toggleLayer = function(inputEl){
     map.getLayers().forEach(function(layer){
          if (layer.get('name') === inputEl.name)
          layer.setVisible(inputEl.checked);
          });
        };
map.addLayer(dataLayerGroup);

but my checkbox logic is not working  and here is my html page for it

   <input type="checkbox" onClick="toggleLayer(this);" value="Sector_office" checked>Sector office

    <input type="checkbox" onClick="toggleLayer(this);" value="Roads" checked>Roads

Body:
For what I see you have a couple of issues in your code.

In the handler function you are referencing the name attribute of the dom element, but I see not such attribute in the html. That will always result false. So you have to set the name attribute or use the value attribute.

The onclick event handler receive as a parameter a MouseEvent argument. To get a reference of the dom element inside the handler you can use this or you can use the event argument attribute target.

Resuming,

handler

const toggleLayer = function(e){
    const chk = e.target.
    map.getLayers().forEach(function(layer){
        if (layer.get('name') === chk.value)
        layer.setVisible(chk.checked);
    });
};

html

<input type="checkbox" onclick="toggleLayer(event)"
    value="Sector_office" checked>Sector office<br>
<input type="checkbox" onclick="toggleLayer(event)"
    value="Roads" checked>Roads<br>


问:
Reset <input> text after @onchange
I'm building a blazor component that will revert back to the original input if the entered text is not valid.
Since ValueText doesn't change the rendering process won't update it/replace user input.

```<code><input type="text"
       value="@ValueText"
       @onchange="TextChanged" />
</code>```

Calling StateHasChanged() won't change the result.

In my case ValueText is always empty.
The workaround has been to alternate between null and "" that will cause the input to be reset.

Is there a method to mark the element attribute as "dirty" so the blazor rendering will refresh the DOM even though the virtual DOM is not changed?

答:
```<code>ValueText  = "";
await Task.Delay(1); //Magic!
StateHasChanged();
ValueText  = value;
StateHasChanged();
</code>```

thanks for
 https://github.com/dotnet/aspnetcore/issues/17281#issuecomment-620541274

Title: Reset <input> text after @onchange

Body:
I'm building a blazor component that will revert back to the original input if the entered text is not valid.
Since ValueText doesn't change the rendering process won't update it/replace user input.

<input type="text"
       value="@ValueText"
       @onchange="TextChanged" />

Calling StateHasChanged() won't change the result.

In my case ValueText is always empty.
The workaround has been to alternate between null and "" that will cause the input to be reset.

Is there a method to mark the element attribute as "dirty" so the blazor rendering will refresh the DOM even though the virtual DOM is not changed?

Body:
ValueText  = "";
await Task.Delay(1); //Magic!
StateHasChanged();
ValueText  = value;
StateHasChanged();

thanks for
 https://github.com/dotnet/aspnetcore/issues/17281#issuecomment-620541274


问:
Sort a Pandas DataFrame using both Date and Time
I'm Trying to sort my dataframe using "sort_value" Im not getting the desired output

```<code>df1 = pd.read_csv('raw data/120_FT DDMG.csv')
df2 = pd.read_csv('raw data/120_FT MG.csv')
df3 = pd.read_csv('raw data/120_FT DD.csv')

dconcat = pd.concat([df1,df2,df3])

dconcat['date'] = pd.to_datetime(dconcat['ActivityDates(Individual)']+' '+dconcat['ScheduledStartTime'])
dconcat.sort_values(by='date')
dconcat = dconcat.set_index('date')
print(dconcat)
</code>```

答:
sort_values returns a data frame which is sorted if inplace=False.

so dconcat=dconcat.sort_values(by='date')

or you can do dconcat.sort_values(by='date', inplace=True)

you can try this;

```<code>dconcat = pd.concat([df1,df2,df3])

dconcat['date'] = pd.to_datetime(dconcat['ActivityDates(Individual)']+' '+dconcat['ScheduledStartTime'])
dconcat.set_index('date', inplace=True)
dconcat.sort_index(inplace=True)
print(dconcat)
</code>```

Body:
I'm Trying to sort my dataframe using "sort_value" Im not getting the desired output

df1 = pd.read_csv('raw data/120_FT DDMG.csv')
df2 = pd.read_csv('raw data/120_FT MG.csv')
df3 = pd.read_csv('raw data/120_FT DD.csv')

dconcat = pd.concat([df1,df2,df3])

dconcat['date'] = pd.to_datetime(dconcat['ActivityDates(Individual)']+' '+dconcat['ScheduledStartTime'])
dconcat.sort_values(by='date')
dconcat = dconcat.set_index('date')
print(dconcat)

Body:
sort_values returns a data frame which is sorted if inplace=False.

so dconcat=dconcat.sort_values(by='date')

or you can do dconcat.sort_values(by='date', inplace=True)

you can try this;

dconcat = pd.concat([df1,df2,df3])

dconcat['date'] = pd.to_datetime(dconcat['ActivityDates(Individual)']+' '+dconcat['ScheduledStartTime'])
dconcat.set_index('date', inplace=True)
dconcat.sort_index(inplace=True)
print(dconcat)


问:
How to make relation between enumtype and itemtype in Hybris
I have an enumtype :

```<code><items>
 <enumtypes>
  <enumtype code="FuelEnumeration" generate="true" autocreate="true" dynamic="true">
   <value code="diesel"></value>
   <value code="gasoline"></value>
   <value code="ethanol"></value>
 </enumtype>
</enumtypes>
</code>```

Here is the itemtype :

```<code><itemtypes>
<itemtype code="Car" extends="Product" autocreate="true" generate="true">
 <attributes> ... <attribute qualifier="fuel" type="FuelEnumeration">
<description>Fuel for this car</description>
<persistence type="property"></persistence>
 </attribute>
</code>```

I want to create a One to Many relation between enumtype and itemtype so that one car can have many FuelEnumeration, How can I do this?

答:
Hi Please create Collection type

```<code><collectiontype code="fuelEnumColl"
        elementtype="FuelEnumeration" autocreate="true" generate="true"
        type="list" />
</code>```

Then refer to your item type.

```<code><attribute qualifier="fuel" type="fuelEnumColl">
</code>```

Body:
I have an enumtype :

<items>
 <enumtypes>
  <enumtype code="FuelEnumeration" generate="true" autocreate="true" dynamic="true">
   <value code="diesel"></value>
   <value code="gasoline"></value>
   <value code="ethanol"></value>
 </enumtype>
</enumtypes>

Here is the itemtype :

<itemtypes>
<itemtype code="Car" extends="Product" autocreate="true" generate="true">
 <attributes> ... <attribute qualifier="fuel" type="FuelEnumeration">
<description>Fuel for this car</description>
<persistence type="property"></persistence>
 </attribute>

I want to create a One to Many relation between enumtype and itemtype so that one car can have many FuelEnumeration, How can I do this?

Body:
Hi Please create Collection type

<collectiontype code="fuelEnumColl"
        elementtype="FuelEnumeration" autocreate="true" generate="true"
        type="list" />

Then refer to your item type.

<attribute qualifier="fuel" type="fuelEnumColl">