答:
If by adding a second div you mean no write it in the html you can simply use the ::after css property on your div like this:

div {
  width: 100px;
  height: 150px;
  background: black;
  position: relative;
}

div::after {
  content: "";
  position: absolute;
  width: 3px;
  right: -3px;
  height: 60%;
  background: red;
  top: 50%;
  transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Title: border only half the side of a div

Body:
In the  html div shown above I want a border on only some of the right-side of the div, however border-right sets a border for the whole side.

I have seen many other questions on this topic but the only working answers I have found require using a second div, but I want to know if this can be done without a second div, i.e: by editing the css properties of this div only.

Body:
If by adding a second div you mean no write it in the html you can simply use the ::after css property on your div like this:

div {
  width: 100px;
  height: 150px;
  background: black;
  position: relative;
}

div::after {
  content: "";
  position: absolute;
  width: 3px;
  right: -3px;
  height: 60%;
  background: red;
  top: 50%;
  transform: translate(-50%, -50%);
}

<div></div>


来源: stackexchange

问:
How to search for a needle in multi-dimensional array in php?
I have some different type of php arrays which can have sensitive data at any level of nesting. I want to unset this sensitive keys. How should I go about this?

For e.g. sensitive data keys can be account_no, acc_no etc

Sample request array1:

```<code>[
    'ClientCode'   => "abcom",
    'MerchantCode' => "Code1",
    'acc_no'       =>  "12345"
]
</code>```

This array should become

```<code>[
    'ClientCode'   =>  "abcom"
    'MerchantCode' =>  "Code1"

]
</code>```

Sample request array2:

```<code>  [
      'customer_name' => "Umesh",
      'age' => 24,
      'customer_details' => [
          'mob_no' => "989729069",
          'account_no' => '1235'
      ]
  ]
</code>```

This array should become

```<code>[
      'customer_name' => "Umesh",
      'age'           => 24,
      'customer_details' => [
          'mob_no' => "989729069"
      ]
]
</code>```

答:
Solution without loop

In the first array:

```<code>unset($arr['acc_no']);
</code>```

In the second array:

```<code>unset($arr['customer_details']['account_no']);
</code>```

Solution using loops

First array:

```<code>foreach($arr1 as $key => $value) {
   if($key === 'acc_no') {
      unset($arr1['acc_no']);
   }
}
</code>```

Second array:

```<code>foreach($arr2 as $key => $value) {
    if($key === 'customer_details') {
        unset($arr2['customer_details']['account_no']);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some different type of php arrays which can have sensitive data at any level of nesting. I want to unset this sensitive keys. How should I go about this?

For e.g. sensitive data keys can be account_no, acc_no etc

Sample request array1:

[
    'ClientCode'   => "abcom",
    'MerchantCode' => "Code1",
    'acc_no'       =>  "12345"
]

This array should become

[
    'ClientCode'   =>  "abcom"
    'MerchantCode' =>  "Code1"

]

Sample request array2:

  [
      'customer_name' => "Umesh",
      'age' => 24,
      'customer_details' => [
          'mob_no' => "989729069",
          'account_no' => '1235'
      ]
  ]

This array should become

[
      'customer_name' => "Umesh",
      'age'           => 24,
      'customer_details' => [
          'mob_no' => "989729069"
      ]
]

Body:
Solution without loop

In the first array:

unset($arr['acc_no']);

In the second array:

unset($arr['customer_details']['account_no']);

Solution using loops

First array:

foreach($arr1 as $key => $value) {
   if($key === 'acc_no') {
      unset($arr1['acc_no']);
   }
}

Second array:

foreach($arr2 as $key => $value) {
    if($key === 'customer_details') {
        unset($arr2['customer_details']['account_no']);
    }
}


问:
C# : what regular expression can match these text?
what regular expression can match these in C#:

```<code>^TEST(%USER,"ADDRESS","NAME","^\",()")
^TEST(%USER,"ADDRESS","NAME")
^TEST()
^TEST
^TEST("HALLO")
$$TEST^QCC("HALLO")
$$TEST^QCC
</code>```

I hope i can get two groups:

group 1: the text before left round bracket if there is a left round bracket, otherwise the whole text.

group 2: the text between the round bracket.

I tried regular expression "(\S+)((\S+))" at https://regex101.com/r/R5wiOh/12 but it works not good.

答:
Try this one:

```<code>^(\S+?)(?:\((\S*)\))?$
</code>```

It is basically the same regex you used, but makes an optional non capturing group around the second group. This means: If it's available capture its content into group 2.

Body:
what regular expression can match these in C#:

^TEST(%USER,"ADDRESS","NAME","^\",()")
^TEST(%USER,"ADDRESS","NAME")
^TEST()
^TEST
^TEST("HALLO")
$$TEST^QCC("HALLO")
$$TEST^QCC

I hope i can get two groups:

group 1: the text before left round bracket if there is a left round bracket, otherwise the whole text.

group 2: the text between the round bracket.

I tried regular expression "(\S+)((\S+))" at https://regex101.com/r/R5wiOh/12 but it works not good.

Body:
Try this one:

^(\S+?)(?:\((\S*)\))?$

It is basically the same regex you used, but makes an optional non capturing group around the second group. This means: If it's available capture its content into group 2.


问:
Unable to Launch Safaridriver
OS: macOS Sierra

Browser: Safari v11.0.3

Problem: Cannot launch safaridriver even though safaridriver --enable has been run.

Error

'safaridriver could not launch because it is not configured correctly or you need to authenticate. Re-run safaridriver(1) and pass the '--enable' flag to configure and/or authenticate. For more information, consult the safaridriver(1) man page.'

Error Log

```<code>qa01:~ svctest$ safaridriver --enable
Password:
qa01:~ svctest$ safaridriver -p 0
ERROR: safaridriver could not launch because it is not configured
correctly or you need to authenticate. Re-run safaridriver(1) and
pass the '--enable' flag to configure and/or authenticate.
For more information, consult the safaridriver(1) man page.
qa01:~ svctest$
</code>```

答:
This works for me:

```<code>sudo -u <your user> safaridriver --enable
</code>```

After that you can see in Safari menu Develop->Allow Remote Automation is checked

ContentLicense: CC BY-SA 3.0

Title: Unable to Launch Safaridriver

Body:
OS: macOS Sierra

Browser: Safari v11.0.3

Problem: Cannot launch safaridriver even though safaridriver --enable has been run.

Error

'safaridriver could not launch because it is not configured correctly or you need to authenticate. Re-run safaridriver(1) and pass the '--enable' flag to configure and/or authenticate. For more information, consult the safaridriver(1) man page.'

Error Log

qa01:~ svctest$ safaridriver --enable
Password:
qa01:~ svctest$ safaridriver -p 0
ERROR: safaridriver could not launch because it is not configured
correctly or you need to authenticate. Re-run safaridriver(1) and
pass the '--enable' flag to configure and/or authenticate.
For more information, consult the safaridriver(1) man page.
qa01:~ svctest$

Body:
This works for me:

sudo -u <your user> safaridriver --enable

After that you can see in Safari menu Develop->Allow Remote Automation is checked


问:
How to call swiftui struct from function
The HomeView()struct is not able to call in function or in button action. How should i call the  HomeView() struct from another struct. While calling  HomeView() either in button action or function of LoginView() , am getting "Result of 'HomeView' initializer is unused"</p>

```<code>struct LoginView: View
{
    var body: some View
    {
    }
    func login()
    {
        HomeView() //Result of 'HomeView' initializer is unused "WARNING"
    }
}

struct LoginView: View
{
    var body: some View {
        NavigationView {
            VStack
                {
                    Button(action: {
                        HomeView() //Result of 'HomeView' initializer is unused  "WARNING"
                    })
                    {
                        HStack(alignment: .center) {
                            Spacer()
                            Text("Submit")
                        }
                    }
            }
        }
    }
}

struct HomeView: View
{
    var body: some View
    {
    }
    func submit()
    {
    }
}
</code>```

答:
To present another view via button, please check below:</p>

```<code>struct LoginView: View {
    @State var showingHome = false
    var loginButton: some View {
        Button(action: {
            self.showingHome.toggle()
        }) {
            Text("Login")
            .foregroundColor(Color.init(.white))
            .font(.system(size: 14))
            .frame(minWidth: 0, maxWidth: .infinity)
            .padding()
            .background(Color.init(.systemOrange))
            .cornerRadius(4)
        }
    }

    var body: some View {
        NavigationView {
            VStack{
                loginButton.sheet(isPresented: $showingHome) {
                    HomeView()
                }
            }
        }
    }
}
</code>```

Body:
The HomeView()struct is not able to call in function or in button action. How should i call the  HomeView() struct from another struct. While calling  HomeView() either in button action or function of LoginView() , am getting "Result of 'HomeView' initializer is unused"

struct LoginView: View
{
    var body: some View
    {
    }
    func login()
    {
        HomeView() //Result of 'HomeView' initializer is unused "WARNING"
    }
}

struct LoginView: View
{
    var body: some View {
        NavigationView {
            VStack
                {
                    Button(action: {
                        HomeView() //Result of 'HomeView' initializer is unused  "WARNING"
                    })
                    {
                        HStack(alignment: .center) {
                            Spacer()
                            Text("Submit")
                        }
                    }
            }
        }
    }
}

struct HomeView: View
{
    var body: some View
    {
    }
    func submit()
    {
    }
}

Body:
To present another view via button, please check below:

struct LoginView: View {
    @State var showingHome = false
    var loginButton: some View {
        Button(action: {
            self.showingHome.toggle()
        }) {
            Text("Login")
            .foregroundColor(Color.init(.white))
            .font(.system(size: 14))
            .frame(minWidth: 0, maxWidth: .infinity)
            .padding()
            .background(Color.init(.systemOrange))
            .cornerRadius(4)
        }
    }

    var body: some View {
        NavigationView {
            VStack{
                loginButton.sheet(isPresented: $showingHome) {
                    HomeView()
                }
            }
        }
    }
}


问:
CloudFront ForwardedValues ambiguous documentation
I'm configuring my CloudFront using CloudFormation, and on the AWS documentation page for the ForwardedValues property, we can see the following statement:

If you specify true for QueryString and you don't specify any values for QueryStringCacheKeys, CloudFront forwards all query string parameters to the origin and caches based on all query string parameters.

The word in bold (caches) are causing some confusion, as the meaning of this sentence is completely dependent on caches being a verb or caches being a noun:

Verb: CloudFormation will cache the queryparameter

Noun: CloudFormation will forward the queryparameter to the cache, but it will not cache the queryparameters

If I don't specify the QueryStringCacheKeys, what is the behaviour of CloudFront?

答:
If you don't specify the QueryStringCacheKeys, but only this:

```<code>ForwardedValues:
  QueryString: true
</code>```

CloudFront will Forward all, cache based on all, which means that the request will be cached based on url+querystring and that the querystring is forwarded to the underlying system.

You can read more on this in the AWS documentation here.

Body:
If you don't specify the QueryStringCacheKeys, but only this:

ForwardedValues:
  QueryString: true

CloudFront will Forward all, cache based on all, which means that the request will be cached based on url+querystring and that the querystring is forwarded to the underlying system.

You can read more on this in the AWS documentation here.


问:
Why two object are not equals after i save with serializable
```<code>public class ProveSerialization {
    public static void main(String[] args) throws Exception{

        Save obj = new Save();
        obj.a = 4;

        File f = new File("File.txt");
        FileOutputStream fos = new FileOutputStream(f);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);

        FileInputStream fis = new FileInputStream(f);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Save obj1 = (Save) ois.readObject();

        System.out.println(obj1.a);
        System.out.println(obj);
        System.out.println(obj1);
        System.out.println(obj.equals(obj1));
        System.out.println(obj == obj1);
</code>```

Output:

```<code>4
Save@14ae5a5
Save@6d03e736
false
false
</code>```

答:
Check the implementation of equals in the Object class; it compares the identity of two objects, which can only be true if the two objects occupy the very same space in memory. However, by serializing your object, you effectively create a new one (which is fine, as you might even intent to exchange your serialized object between two VMs. As a result, a serialized object can never be the same as it was before.

However, if you intend to loosen the definition of equals for your Save object, keep in mind that you could override the method. But I guess, that is OT, right?

Body:
public class ProveSerialization {
    public static void main(String[] args) throws Exception{

        Save obj = new Save();
        obj.a = 4;

        File f = new File("File.txt");
        FileOutputStream fos = new FileOutputStream(f);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);

        FileInputStream fis = new FileInputStream(f);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Save obj1 = (Save) ois.readObject();

        System.out.println(obj1.a);
        System.out.println(obj);
        System.out.println(obj1);
        System.out.println(obj.equals(obj1));
        System.out.println(obj == obj1);

Output:

4
Save@14ae5a5
Save@6d03e736
false
false


问:
ComponentWillUnmount is not getting called React-Navigation
I know this question already exists on Stack Overflow but most questions and answers are very old. I am working on an app that performs a fetch call to a db inside componentDidMount obviously using react-native.

I have an interval running in componentDidMount that calls a query and it works well. Now I need to call clearInterval(this.interval) inside componentWillUnmount to stop the query and logging in my app.

It should be called when I press a save button and navigate with props.navigation.navigate("new Screen", {params})

I read a solution for this where I should use props.navgiation.replace("Screen") - but it doesn't work for me

The second important part is that componentWillUnmount also needs to be called when I press on another tab (using bottom-tab-navigator)

I understand that the screens in a stack navigator for example never really unmount. So is there a different way to call componentWillUnmount maybe something like when the user left screen( or loses focus on-screen) or user left the specific routeName or something.

My componentWillUnmount - really simple:

```<code>  componentWillUnmount(){
    clearInterval(this.interval)
    console.log("Component did Unmount")
  }
</code>```

it's only called if I go to my LogOut Screen and log-out to be in my LoginScreen again.

(EDIT) My Navigator:

```<code>const EintragenStack = createStackNavigator(
  {
    Eintragen: {
      screen: StundenEintragen2,
      navigationOptions: {
        headerTitle: "Stundenverwaltung",
        headerTitleStyle:{
          color: "white",
          alignSelf: "center"
        },
        headerStyle:{
          backgroundColor: "#a51717"
        },
      }
    }
  }
)

const CheckStack = createStackNavigator(
  {
    Übersicht: StundenChecken,
    Monat: Monatsübersicht2, // Monatsübersicht
    Tag: TagesübersichtDiff, // Tagesübersicht
    Edit: {
      screen: StundenEdit,
      navigationOptions:{
        headerTitle: "Stunden bearbeiten",
        headerTitleStyle: {
          color: "white",
          alignSelf: "center"
        },
        headerStyle: {
          backgroundColor: "#F39237"
        }
      }
    }
  },
  {
    backBehavior: "history"
  }
);
const Tabs = createBottomTabNavigator(
  {
    Eintragen: EintragenStack,     // StundenEintragen
    Checken: CheckStack,
    Logout: Logout
  },
  {
    backBehavior: "history",
    tabBarOptions: {
      labelStyle: {
        fontSize: 12,
        color: "black"
      },
      activeTintColor: "red",
      activeBackgroundColor: "#ccc"
    }
  }
);
const AppNavigator = createSwitchNavigator({
  Login: Auth, //SecondAuth,
  Tabs: Tabs,
});

EintragenStack.navigationOptions = {
  tabBarIcon: () => {
    return <Icon style={{marginTop: 5}} size={34} name="ios-add-circle-outline" color="green" />;
  }

};
CheckStack.navigationOptions = {
  tabBarIcon: () => {
    return <Icon style={{marginTop: 5}} size={34} name="ios-calendar" color="black" />;
  }
};
Logout.navigationOptions = {
  tabBarIcon: () => {
    return <Icon style={{marginTop: 5}} size={34} name="ios-power" color="red" />;
  }
};

const AppContainer = createAppContainer(AppNavigator);

export default AppContainer;
</code>```

I actually kind of fixed it for my needs but the problem still exists overall. I don't know if this is a good approach but for me I did it like this:

I am calling checkUnlockHandler in componentWillMount every 30sec.

When checkUnlockHandler gets to an if that tells it that it doesn't need running anymore I call clearInterval(this.interval("here is my checkUnlockHandler"))

After that my interval in componentDidMount stops running which is good.

Problems: Interval still runs in other screens, It feels weird to call a function inside componentDidMount wrapped in a interval and inside this function to tell when the interval should stop.

答:
I faced the same problem in using bottom tab navigator and I found simple solution, which works for me.

```<code>    componentDidMount()
    {
        this.props.navigation.addListener('focus', async () =>{
             this.interval= setInterval(() => {
                 //---------
             }, 5000);
         });
        this.props.navigation.addListener('blur', () => {
            clearInterval(this.interval);
        });
    }
</code>```

also in functional component we can use useEffect with cleanup.

```<code>React.useEffect(() => {
    navigation.addListener('focus', () => {
        this.interval= setInterval(() => {
                 //---------
        }, 5000);
    });

    return () =>{
        clearInterval(this.interval);
    };
 }, [navigation]);

</code>```

Body:
I know this question already exists on Stack Overflow but most questions and answers are very old. I am working on an app that performs a fetch call to a db inside componentDidMount obviously using react-native.

I have an interval running in componentDidMount that calls a query and it works well. Now I need to call clearInterval(this.interval) inside componentWillUnmount to stop the query and logging in my app.

It should be called when I press a save button and navigate with props.navigation.navigate("new Screen", {params})

I read a solution for this where I should use props.navgiation.replace("Screen") - but it doesn't work for me

The second important part is that componentWillUnmount also needs to be called when I press on another tab (using bottom-tab-navigator)

I understand that the screens in a stack navigator for example never really unmount. So is there a different way to call componentWillUnmount maybe something like when the user left screen( or loses focus on-screen) or user left the specific routeName or something.

My componentWillUnmount - really simple:

  componentWillUnmount(){
    clearInterval(this.interval)
    console.log("Component did Unmount")
  }

it's only called if I go to my LogOut Screen and log-out to be in my LoginScreen again.

(EDIT) My Navigator:

const EintragenStack = createStackNavigator(
  {
    Eintragen: {
      screen: StundenEintragen2,
      navigationOptions: {
        headerTitle: "Stundenverwaltung",
        headerTitleStyle:{
          color: "white",
          alignSelf: "center"
        },
        headerStyle:{
          backgroundColor: "#a51717"
        },
      }
    }
  }
)

const CheckStack = createStackNavigator(
  {
    Übersicht: StundenChecken,
    Monat: Monatsübersicht2, // Monatsübersicht
    Tag: TagesübersichtDiff, // Tagesübersicht
    Edit: {
      screen: StundenEdit,
      navigationOptions:{
        headerTitle: "Stunden bearbeiten",
        headerTitleStyle: {
          color: "white",
          alignSelf: "center"
        },
        headerStyle: {
          backgroundColor: "#F39237"
        }
      }
    }
  },
  {
    backBehavior: "history"
  }
);
const Tabs = createBottomTabNavigator(
  {
    Eintragen: EintragenStack,     // StundenEintragen
    Checken: CheckStack,
    Logout: Logout
  },
  {
    backBehavior: "history",
    tabBarOptions: {
      labelStyle: {
        fontSize: 12,
        color: "black"
      },
      activeTintColor: "red",
      activeBackgroundColor: "#ccc"
    }
  }
);
const AppNavigator = createSwitchNavigator({
  Login: Auth, //SecondAuth,
  Tabs: Tabs,
});

EintragenStack.navigationOptions = {
  tabBarIcon: () => {
    return <Icon style={{marginTop: 5}} size={34} name="ios-add-circle-outline" color="green" />;
  }

};
CheckStack.navigationOptions = {
  tabBarIcon: () => {
    return <Icon style={{marginTop: 5}} size={34} name="ios-calendar" color="black" />;
  }
};
Logout.navigationOptions = {
  tabBarIcon: () => {
    return <Icon style={{marginTop: 5}} size={34} name="ios-power" color="red" />;
  }
};

const AppContainer = createAppContainer(AppNavigator);

export default AppContainer;

I actually kind of fixed it for my needs but the problem still exists overall. I don't know if this is a good approach but for me I did it like this:

I am calling checkUnlockHandler in componentWillMount every 30sec.

When checkUnlockHandler gets to an if that tells it that it doesn't need running anymore I call clearInterval(this.interval("here is my checkUnlockHandler"))

After that my interval in componentDidMount stops running which is good.

Problems: Interval still runs in other screens, It feels weird to call a function inside componentDidMount wrapped in a interval and inside this function to tell when the interval should stop.

Body:
I faced the same problem in using bottom tab navigator and I found simple solution, which works for me.

    componentDidMount()
    {
        this.props.navigation.addListener('focus', async () =>{
             this.interval= setInterval(() => {
                 //---------
             }, 5000);
         });
        this.props.navigation.addListener('blur', () => {
            clearInterval(this.interval);
        });
    }

also in functional component we can use useEffect with cleanup.

React.useEffect(() => {
    navigation.addListener('focus', () => {
        this.interval= setInterval(() => {
                 //---------
        }, 5000);
    });

    return () =>{
        clearInterval(this.interval);
    };
 }, [navigation]);


问:
Unable to generate token using tymon jwt in laravel
I'm stuck with this for about 3 days. Basically, i'm trying to generate a JWT token in laravel using Tymon. This is my controller file.

```<code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use JWTAuth;
use JWT;
use Tymon\JWTAuthExceptions\JWTException;
use Tymon\JWTAuth\Contracts\JWTSubject as JWTSubject;

class AuthenticateController extends Controller
{
 public function index()
{
 //
}
 public function authenticate(Request $request)
{

    $user = User::where('email', $request->only('email'))->first();
    dd($user); //This does show some output
    $token = JWTAuth::fromUser($user); //returns error message

    return ["error" => NULL, "token" => $token];

 }
}
</code>```

I tested this api using Chrome postman, but it is reporting this error:

ErrorException in JWT.php line 73:
Argument 1 passed to Tymon\JWTAuth\JWT::fromUser() must be an instance of Tymon\JWTAuth\Contracts\JWTSubject, instance of App\User given, called in /Users/shankerm/mccadmin/laravel/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 217 and defined

Pls give me some advice. Im new to Laravel and struggling with this for a long time. Thanks.

答:
Two issues that could be happening according to previous experience

Setting the jwt as the default auth driver. You can do it like this

'api' => [
           'driver' => 'jwt',
            'provider' => 'users',
            'hash' => false,
      ],

Not implementing the JWTSubject in your preferred Model i.e for a user model you can do it like this

class User extends Authenticatable implements  JWTSubject{
then implement the functions by the interface as below

/**
     * @inheritDoc
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

```<code>/**
 * @inheritDoc
 */
public function getJWTCustomClaims()
{
    return [];
}
</code>```

it could also be you have not generated a jwt auth key

```<code>php artisan jwt:secret
</code>```

with this you should  have a entry like this in your .env

```<code>JWT_SECRET={value generated}
</code>```

Body:
I'm stuck with this for about 3 days. Basically, i'm trying to generate a JWT token in laravel using Tymon. This is my controller file.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use JWTAuth;
use JWT;
use Tymon\JWTAuthExceptions\JWTException;
use Tymon\JWTAuth\Contracts\JWTSubject as JWTSubject;

class AuthenticateController extends Controller
{
 public function index()
{
 //
}
 public function authenticate(Request $request)
{

    $user = User::where('email', $request->only('email'))->first();
    dd($user); //This does show some output
    $token = JWTAuth::fromUser($user); //returns error message

    return ["error" => NULL, "token" => $token];

 }
}

I tested this api using Chrome postman, but it is reporting this error:

ErrorException in JWT.php line 73:
Argument 1 passed to Tymon\JWTAuth\JWT::fromUser() must be an instance of Tymon\JWTAuth\Contracts\JWTSubject, instance of App\User given, called in /Users/shankerm/mccadmin/laravel/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 217 and defined

Pls give me some advice. Im new to Laravel and struggling with this for a long time. Thanks.

Body:
Two issues that could be happening according to previous experience

Setting the jwt as the default auth driver. You can do it like this

'api' => [
           'driver' => 'jwt',
            'provider' => 'users',
            'hash' => false,
      ],

Not implementing the JWTSubject in your preferred Model i.e for a user model you can do it like this

class User extends Authenticatable implements  JWTSubject{
then implement the functions by the interface as below

/**
     * @inheritDoc
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

/**
 * @inheritDoc
 */
public function getJWTCustomClaims()
{
    return [];
}

it could also be you have not generated a jwt auth key

php artisan jwt:secret

with this you should  have a entry like this in your .env

JWT_SECRET={value generated}


问:
Mocha not exiting
I'm running into an issue where Mocha is not exiting.

I read that it can be because I have dangling resources, but I'm not sure where.

My code is:

import express from 'express';

let app = express();

app.get('/', (req, res) => {
    res.end('Done');
});

app.listen(3000);

export default app;
```

<p>And my test is:</p>

<pre class="lang-js prettyprint-override"><code>import { describe, it } from 'mocha';
import chai, { expect } from 'chai';
import chaiHttp from 'chai-http';
import app from '../app';

chai.use(chaiHttp);

describe('Simple test', () => {
    it('Should', async () => {
        let response = await chai.request(app).get('/');
        expect(response).to.have.status(200);
    });
});
</code>```

答:
Try running your test with the --exit flag. This will "Force Mocha to quit after tests complete" ref

$ mocha --exit ./test.test.js

Title: Mocha not exiting

Body:
I'm running into an issue where Mocha is not exiting.

I read that it can be because I have dangling resources, but I'm not sure where.

My code is:

import express from 'express';

let app = express();

app.get('/', (req, res) => {
    res.end('Done');
});

app.listen(3000);

export default app;

And my test is:

import { describe, it } from 'mocha';
import chai, { expect } from 'chai';
import chaiHttp from 'chai-http';
import app from '../app';

chai.use(chaiHttp);

describe('Simple test', () => {
    it('Should', async () => {
        let response = await chai.request(app).get('/');
        expect(response).to.have.status(200);
    });
});


问:
border only half the side of a div

In the  html div shown above I want a border on only some of the right-side of the div, however border-right sets a border for the whole side.

I have seen many other questions on this topic but the only working answers I have found require using a second div, but I want to know if this can be done without a second div, i.e: by editing the css properties of this div only.

答:
Try this, it's just css:

.addBorder {
  width: 100px;
  height: 100px;
  background-color: grey;
  position: relative;
}

.addBorder:before {
  content: "";
  position: absolute;
  width: 2px;
  height: 100%;
  bottom: 0;
  right: 0;
  background-color: #000;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="addBorder"></div></code>```

Title: border only half the side of a div

Body:
Try this, it's just css:

.addBorder {
  width: 100px;
  height: 100px;
  background-color: grey;
  position: relative;
}

.addBorder:before {
  content: "";
  position: absolute;
  width: 2px;
  height: 100%;
  bottom: 0;
  right: 0;
  background-color: #000;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
}

<div class="addBorder"></div>


问:
Swiftui hide disclosure arrow
I have this View

```<code>NavigationView {
                 GeometryReader { geometry in

                    List {
                        ForEach(self.viewModel.items) { item in
                            HStack(spacing: 0, content:  {
                                ZStack {
                                    RowItemView(data: item.FirstItem)
                                    NavigationLink(destination: CustomView(data: item.FirstItem))
                                    {
                                        EmptyView()
                                    }

                                }
                                .frame(width: geometry.size.width / 2, alignment: .center)

                                if (item.SecondItem != nil)  {
                                    ZStack {
                                            RowItemView(data: item.SecondItem!)
                                    NavigationLink(destination: CustomView(data: item.SecondItem!))
                                    {
                                        EmptyView()
                                    }
                                }
                            })
                        }.listRowInsets(EdgeInsets())
                    }
                }
</code>```

I want to hide the disclouse arrow of the NavigationView.
I try to add .buttonStyle(PlainButtonStyle()) or add a negative trailing to the navigationLink, but it doesn't change.

I have already read this question and this one but they do not work in my case, probably because I'm creating a grid and not a plain list.

答:
Thanks to @Asperi I figured out what is the problem.

With a zero EdgeInsets in listRowInsets the arrow still show.

So I create this trick (Works in Xcode 13.3.1)

```<code>List {
    ForEach(self.viewModel.items) { item in
        //code for creating the row
    }.listRowInsets(EdgeInsets.init(top: 8, leading: 0, bottom: 8, trailing: 0))
</code>```

Put a value for both top and bottom.

I do not know if it is the correct way to get rid of that annoying arrow, but for my app it works :-)

Title: Swiftui hide disclosure arrow

Body:
I have this View

NavigationView {
                 GeometryReader { geometry in

                    List {
                        ForEach(self.viewModel.items) { item in
                            HStack(spacing: 0, content:  {
                                ZStack {
                                    RowItemView(data: item.FirstItem)
                                    NavigationLink(destination: CustomView(data: item.FirstItem))
                                    {
                                        EmptyView()
                                    }

                                }
                                .frame(width: geometry.size.width / 2, alignment: .center)

                                if (item.SecondItem != nil)  {
                                    ZStack {
                                            RowItemView(data: item.SecondItem!)
                                    NavigationLink(destination: CustomView(data: item.SecondItem!))
                                    {
                                        EmptyView()
                                    }
                                }
                            })
                        }.listRowInsets(EdgeInsets())
                    }
                }

I want to hide the disclouse arrow of the NavigationView.
I try to add .buttonStyle(PlainButtonStyle()) or add a negative trailing to the navigationLink, but it doesn't change.

I have already read this question and this one but they do not work in my case, probably because I'm creating a grid and not a plain list.

Body:
Thanks to @Asperi I figured out what is the problem.

With a zero EdgeInsets in listRowInsets the arrow still show.

So I create this trick (Works in Xcode 13.3.1)

List {
    ForEach(self.viewModel.items) { item in
        //code for creating the row
    }.listRowInsets(EdgeInsets.init(top: 8, leading: 0, bottom: 8, trailing: 0))

Put a value for both top and bottom.

I do not know if it is the correct way to get rid of that annoying arrow, but for my app it works :-)


问:
How to change text color of TextFormField according to theme
I want to change inputted text color as per the current theme, as text color is not a part of InputDecorationTheme.

As of now the only possible way to change inputted text color is to give style to TextFormField but that also not work when theme gets changed + in that way I need to repeat the similar code for each of my text field available in the app.

答:
You can do by setting ThemeData as below .</p>

```<code> MaterialApp(
  theme: ThemeData(
    textTheme: TextTheme(
      subtitle1: TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
    ),
  )
 ...
</code>```

Body:
You can do by setting ThemeData as below .

 MaterialApp(
  theme: ThemeData(
    textTheme: TextTheme(
      subtitle1: TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
    ),
  )
 ...


问:
SQL select only last entry of date from a calculated field
Hey I'm trying to visualize a past 30 days trend as a line graph in metabase and therefore have to query the data in a right way.

The table looks like this:

```<code>    DATE                          SCORE
September 7, 2019, 12:00 AM         3
September 7, 2019, 12:00 AM         4
September 8, 2019, 12:00 AM         9
September 9, 2019, 12:00 AM         10
</code>```

I tried this query which calculates the NPS and the rolling sum over the last 30 rows.

```<code>select DATE,
        CASE
            WHEN SCORE <= 6 THEN '-1'
            WHEN SCORE <= 8 THEN '0'
            WHEN SCORE > 8 THEN '1'
        END AS NPS
        ,SUM(NPS) OVER(ORDER BY DATE ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) AS NPSTotal
FROM Table;
</code>```

Which looks like this

```<code>    DATE                          NPS    NPSTotal
September 7, 2019, 12:00 AM         -1    -1
September 7, 2019, 12:00 AM         -1    -2
September 8, 2019, 12:00 AM         1     -1
September 9, 2019, 12:00 AM         1      0
</code>```

However, if I want to plot the results in metabase and put the date on the x-axis it naturally aggregates the NPSTotal, giving me a -3 for the 7 September instead of -2. I think the result of my query should look like this.

```<code>    DATE                        NPSTotal
September 7, 2019, 12:00 AM       -2
September 8, 2019, 12:00 AM       -1
September 9, 2019, 12:00 AM        0
</code>```

So I need two things:
1. Sum the NPS over the date of the column and all votes from the last 30 days instead of rows.
2. The output should give out only one NPSTotal entry per date, which should be the last value.

Would be happy if somebody has a solution for this.

答:
This is how we calculate nps and bucket by date.
I'm assuming NPS is net promoter score. I'd tend to calculate the overall NPS in one go then plot the actual value rather than the relative daily values because it also depends on how many people are responding. If you have one responder on day 1 and 100 responders on day 2, then the single responder on day 1 will skew the NPS.</p>

```<code>select date(scored_at),
       ((sum(if(score>8,1,0))/count(*))-(sum(if(score<7,1,0))/count(*)))*100 as nps
from nps_scores
where score is not null
and [date comparators can go here]
group by date(scored_At)
;
</code>```

Body:
Hey I'm trying to visualize a past 30 days trend as a line graph in metabase and therefore have to query the data in a right way.

The table looks like this:

    DATE                          SCORE
September 7, 2019, 12:00 AM         3
September 7, 2019, 12:00 AM         4
September 8, 2019, 12:00 AM         9
September 9, 2019, 12:00 AM         10

I tried this query which calculates the NPS and the rolling sum over the last 30 rows.

select DATE,
        CASE
            WHEN SCORE <= 6 THEN '-1'
            WHEN SCORE <= 8 THEN '0'
            WHEN SCORE > 8 THEN '1'
        END AS NPS
        ,SUM(NPS) OVER(ORDER BY DATE ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) AS NPSTotal
FROM Table;

Which looks like this

    DATE                          NPS    NPSTotal
September 7, 2019, 12:00 AM         -1    -1
September 7, 2019, 12:00 AM         -1    -2
September 8, 2019, 12:00 AM         1     -1
September 9, 2019, 12:00 AM         1      0

However, if I want to plot the results in metabase and put the date on the x-axis it naturally aggregates the NPSTotal, giving me a -3 for the 7 September instead of -2. I think the result of my query should look like this.

    DATE                        NPSTotal
September 7, 2019, 12:00 AM       -2
September 8, 2019, 12:00 AM       -1
September 9, 2019, 12:00 AM        0

So I need two things:
1. Sum the NPS over the date of the column and all votes from the last 30 days instead of rows.
2. The output should give out only one NPSTotal entry per date, which should be the last value.

Would be happy if somebody has a solution for this.

Body:
This is how we calculate nps and bucket by date.
I'm assuming NPS is net promoter score. I'd tend to calculate the overall NPS in one go then plot the actual value rather than the relative daily values because it also depends on how many people are responding. If you have one responder on day 1 and 100 responders on day 2, then the single responder on day 1 will skew the NPS.

select date(scored_at),
       ((sum(if(score>8,1,0))/count(*))-(sum(if(score<7,1,0))/count(*)))*100 as nps
from nps_scores
where score is not null
and [date comparators can go here]
group by date(scored_At)
;


问:
What is the best way to program against powershell's x64 vs. x86 variability
We have several scripts we use to install and configure the dependencies backing the systems we maintain. We run these anytime we establish a dev, test, demo, train, prod, etc. environment. We often find that we have to deal with x64 vs. x86 architecture, especially where the powershell scripts are concerned.

For example, I have a script that uses the Windows Installer PowerShell Extensions to determine if a program/patch has been installed. The script doesn't work in an x64 environment without explicitly invoking PowerShell (x86), which, isn't in the path by default. As we port these scripts to the x64 platform it would be great to maintain a single set of scripts that work in powershell on both architectures and only invoke x86 code when needed.

Does anyone know of a strategy for doing this?

答:
I run into this issue a lot with my configuration scripts.  The basic approach I take is to

Use several functions to test if I'm in a 64 bit environment  (http://blogs.msdn.com/jaredpar/archive/2008/10/16/powershell-and-64-bit-windows-helper-functions.aspx)

Invoke x86/x64 PowerShell based on the needs of a particular script

Unfortunately a lot of this is done in a brute force manner.  Each particular configuration entry that is x86/x64 dependent essentially has 2 code paths (one for each architecture).

The only real exception I've been able to make is to test for the existince of certain programs on disk.  I have a handy function (Get-ProgramFiles32) which makes it easy to test for programs.

```<code>if ( test-path (join-path Get-ProgramFiles32 "subversion") ) { ...
</code>```

Here are all of the helper functions that I have in my common library that deal with 32/64 bit differences.

```<code># Get the path where powershell resides.  If the caller passes -use32 then
# make sure we are returning back a 32 bit version of powershell regardless
# of the current machine architecture
function Get-PowerShellPath() {
    param ( [switch]$use32=$false,
            [string]$version="1.0" )

    if ( $use32 -and (test-win64machine) ) {
        return (join-path $env:windir "syswow64\WindowsPowerShell\v$version\powershell.exe")
    }

    return (join-path $env:windir "System32\WindowsPowerShell\v$version\powershell.exe")
}

# Is this a Win64 machine regardless of whether or not we are currently
# running in a 64 bit mode
function Test-Win64Machine() {
    return test-path (join-path $env:WinDir "SysWow64")
}

# Is this a Wow64 powershell host
function Test-Wow64() {
    return (Test-Win32) -and (test-path env:\PROCESSOR_ARCHITEW6432)
}

# Is this a 64 bit process
function Test-Win64() {
    return [IntPtr]::size -eq 8
}

# Is this a 32 bit process
function Test-Win32() {
    return [IntPtr]::size -eq 4
}

function Get-ProgramFiles32() {
    if (Test-Win64 ) {
        return ${env:ProgramFiles(x86)}
    }

    return $env:ProgramFiles
}

function Invoke-Admin() {
    param ( [string]$program = $(throw "Please specify a program" ),
            [string]$argumentString = "",
            [switch]$waitForExit )

    $psi = new-object "Diagnostics.ProcessStartInfo"
    $psi.FileName = $program
    $psi.Arguments = $argumentString
    $psi.Verb = "runas"
    $proc = [Diagnostics.Process]::Start($psi)
    if ( $waitForExit ) {
        $proc.WaitForExit();
    }
}

# Run the specified script as an administrator
function Invoke-ScriptAdmin() {
    param ( [string]$scriptPath = $(throw "Please specify a script"),
            [switch]$waitForExit,
            [switch]$use32=$false )

    $argString = ""
    for ( $i = 0; $i -lt $args.Length; $i++ ) {
        $argString += $args[$i]
        if ( ($i + 1) -lt $args.Length ) {
            $argString += " "
        }
    }

    $p = "-Command & "
    $p += resolve-path($scriptPath)
    $p += " $argString"

    $psPath = Get-PowershellPath -use32:$use32
    write-debug ("Running: $psPath $p")
    Invoke-Admin $psPath $p -waitForExit:$waitForExit
}
</code>```

OwnerDisplayName: Rob Murdoch

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rob Murdoch

Body:
I run into this issue a lot with my configuration scripts.  The basic approach I take is to

Use several functions to test if I'm in a 64 bit environment  (http://blogs.msdn.com/jaredpar/archive/2008/10/16/powershell-and-64-bit-windows-helper-functions.aspx)

Invoke x86/x64 PowerShell based on the needs of a particular script

Unfortunately a lot of this is done in a brute force manner.  Each particular configuration entry that is x86/x64 dependent essentially has 2 code paths (one for each architecture).

The only real exception I've been able to make is to test for the existince of certain programs on disk.  I have a handy function (Get-ProgramFiles32) which makes it easy to test for programs.

if ( test-path (join-path Get-ProgramFiles32 "subversion") ) { ...

Here are all of the helper functions that I have in my common library that deal with 32/64 bit differences.

# Get the path where powershell resides.  If the caller passes -use32 then
# make sure we are returning back a 32 bit version of powershell regardless
# of the current machine architecture
function Get-PowerShellPath() {
    param ( [switch]$use32=$false,
            [string]$version="1.0" )

    if ( $use32 -and (test-win64machine) ) {
        return (join-path $env:windir "syswow64\WindowsPowerShell\v$version\powershell.exe")
    }

    return (join-path $env:windir "System32\WindowsPowerShell\v$version\powershell.exe")
}

# Is this a Win64 machine regardless of whether or not we are currently
# running in a 64 bit mode
function Test-Win64Machine() {
    return test-path (join-path $env:WinDir "SysWow64")
}

# Is this a Wow64 powershell host
function Test-Wow64() {
    return (Test-Win32) -and (test-path env:\PROCESSOR_ARCHITEW6432)
}

# Is this a 64 bit process
function Test-Win64() {
    return [IntPtr]::size -eq 8
}

# Is this a 32 bit process
function Test-Win32() {
    return [IntPtr]::size -eq 4
}

function Get-ProgramFiles32() {
    if (Test-Win64 ) {
        return ${env:ProgramFiles(x86)}
    }

    return $env:ProgramFiles
}

function Invoke-Admin() {
    param ( [string]$program = $(throw "Please specify a program" ),
            [string]$argumentString = "",
            [switch]$waitForExit )

    $psi = new-object "Diagnostics.ProcessStartInfo"
    $psi.FileName = $program
    $psi.Arguments = $argumentString
    $psi.Verb = "runas"
    $proc = [Diagnostics.Process]::Start($psi)
    if ( $waitForExit ) {
        $proc.WaitForExit();
    }
}

# Run the specified script as an administrator
function Invoke-ScriptAdmin() {
    param ( [string]$scriptPath = $(throw "Please specify a script"),
            [switch]$waitForExit,
            [switch]$use32=$false )

    $argString = ""
    for ( $i = 0; $i -lt $args.Length; $i++ ) {
        $argString += $args[$i]
        if ( ($i + 1) -lt $args.Length ) {
            $argString += " "
        }
    }

    $p = "-Command & "
    $p += resolve-path($scriptPath)
    $p += " $argString"

    $psPath = Get-PowershellPath -use32:$use32
    write-debug ("Running: $psPath $p")
    Invoke-Admin $psPath $p -waitForExit:$waitForExit
}

OwnerDisplayName: JaredPar


问:
How to cleanly do a git pull-with-rebase after merging branches

Alternative title: How to squash merge commits?

I have the following state in my local repository:

```<code>      C     (origin/feature)
     /
A - B - m   (feature)
       /
  Y - Z     (master)
</code>```

I've just merged changes from one branch to another (e.g. from master into our feature branch, or even vice versa). When I did this, commit B and Z were the most latest commits in their respective branches.

However! Dastardly Dan just pushed his change to the branch I was merging into (C). When I now try and push, I can't. I first have to fetch the changes and merge them somehow. The question is: how?

If I do a pull with rebase, I end up having to resolve all the conflicts in the merge between B & Z. If I try to merge, I end up with two merge commits, which isn't that clean, and also shouldn't be that necessary.

```<code>      C --
     /     \
A - B - m - m2
       /
  Y - Z
</code>```

Is there any way of squashing m and m2 such that it looks like:

```<code>      C --
     /     \
A - B    -- m3
       /
  Y - Z
</code>```

An interactive rebase obviously doesn't show the merge commits, and a cherry-pick requires me to resolve all the merge conflicts again (between B & Z, which weren't affected by C at all).

答:
If you are acting on a feature branch, and only have local changes, I would suggest you to throw away your local merge, and re-merge from C.

```<code># from your local 'feature' branch :
git checkout feature

# set your local branch to Dastardly Dan's version :
#    WARNING: do save (or commit) your local changes before running reset --hard,
#        they will be lost otherwise.
git reset --hard origin/feature

# you are now in 'C' state, merge master
git merge master
</code>```

Another option is to ask Dan to rebase his work (commit C in your diagram) on top of your merge (commit m) in order to reach :

```<code>A - B - m - C' <-feature, origin/feature
       /
  Y - Z <-master
</code>```

Body:
Alternative title: How to squash merge commits?

I have the following state in my local repository:

      C     (origin/feature)
     /
A - B - m   (feature)
       /
  Y - Z     (master)

I've just merged changes from one branch to another (e.g. from master into our feature branch, or even vice versa). When I did this, commit B and Z were the most latest commits in their respective branches.

However! Dastardly Dan just pushed his change to the branch I was merging into (C). When I now try and push, I can't. I first have to fetch the changes and merge them somehow. The question is: how?

If I do a pull with rebase, I end up having to resolve all the conflicts in the merge between B & Z. If I try to merge, I end up with two merge commits, which isn't that clean, and also shouldn't be that necessary.

      C --
     /     \
A - B - m - m2
       /
  Y - Z

Is there any way of squashing m and m2 such that it looks like:

      C --
     /     \
A - B    -- m3
       /
  Y - Z

An interactive rebase obviously doesn't show the merge commits, and a cherry-pick requires me to resolve all the merge conflicts again (between B & Z, which weren't affected by C at all).

Body:
If you are acting on a feature branch, and only have local changes, I would suggest you to throw away your local merge, and re-merge from C.

# from your local 'feature' branch :
git checkout feature

# set your local branch to Dastardly Dan's version :
#    WARNING: do save (or commit) your local changes before running reset --hard,
#        they will be lost otherwise.
git reset --hard origin/feature

# you are now in 'C' state, merge master
git merge master

Another option is to ask Dan to rebase his work (commit C in your diagram) on top of your merge (commit m) in order to reach :

A - B - m - C' <-feature, origin/feature
       /
  Y - Z <-master


问:
Firebase Cloud Messaging : How to send push notification to users on specific day after install?
I want to send push notifications using FCM (Firebase Cloud Messaging) to users on a specific day after install.

For instance, After install, I want to send push notifications on Day 0, 1, 2... etc. to the users.

Please help me how can I achieve this with Firebase?

Thanks in advance.

答:
You will need to create a cloud function in order to deliver to the users the notification.

First, you will need to get the users FirebaseInstanceId , which will be used later to send notifications to these users.

Firebase Instance ID provides a unique identifier for each app
  instance and a mechanism to authenticate and authorize actions
  (example: sending FCM messages).

Then, you will need to push some data to the user who opened your app, you can sign in the user with any authentication method that provides Firebase

See Firebase Auth

After the user has logged in, you can push to the user the times it opened your app, this will be code in your onCreate() which will update a value in that user node incrementing the total count when the user opens the app.

After that you will need to store the first time the user logs in timestamp, and then the logout timestamp.

The logout timestamp can be when the user exits your app and onDestroy() is hit, then you can compare the first time the user signed in and the last time the user has been active.

If this difference is greater than 24 hs and the user has a counter greater than 5 (the times the user visited in onCreate() ) you can run a cloud function with that user token and schedule a notification

see Schedule functions

The functions should be a simple get to the users node, you can get all the users data and then compare the timestamps and the times the user opened the app, if that criteria matchs your case, get the user instance ID and send a notification to that user scheduled


问:
what's the difference between plt.plot(), object.plot()
I made a list

```<code>> Book_of_Death_Count

1.0    49
2.0    73
3.0    97
4.0    27
5.0    61
Name: Book of Death, dtype: int64*
</code>```

When I type

```<code>a = Book_of_Death_Count.plot(),
b = plt.plot(Book_of_Death_Count)
</code>```

The result of the two is the same, but:

a.set_xticks(np.arange(1,6)) works;

b.set_xticks(np.arange(1,6)) doesn't work.

What's the difference of these two code?

答:
your "list" is a pandas DataFrame object. When you call Book_of_Death_Count.plot() you are using the function DataFrame.plot(), which returns (in most cases) an Axes object. Therefore a is of Type Axes and you can use it to access all the methods of that class.

When you use plt.plot(), the return values is a list of Line2D objects. If you need to access the Axes object (for instance to modify the ticks), use a = plt.gca().

Body:
I made a list

> Book_of_Death_Count

1.0    49
2.0    73
3.0    97
4.0    27
5.0    61
Name: Book of Death, dtype: int64*

When I type

a = Book_of_Death_Count.plot(),
b = plt.plot(Book_of_Death_Count)

The result of the two is the same, but:

a.set_xticks(np.arange(1,6)) works;

b.set_xticks(np.arange(1,6)) doesn't work.

What's the difference of these two code?


问:
How to fix error with has_and_belongs_to_many creation in rails
I want to create a record in join table but rails shows me two errors in two situation, and I don't want to generate a third model.

```<code>@channel = Channel.find(params[:channel_id])
 if @channel.users.create!(channel_id: params[:channel_id], user_id: params[:user_id])
     flash[:success] = "U Succeed:)"
     redirect_to request.referrer
 else
     flash[:danger] = "U Nit Succeed:H"
     redirect_to request.referrer
 end
</code>```

second situation

```<code> if Channel.users.create!(channel_id: params[:channel_id], user_id: params[:user_id])
     flash[:success] = "U Succeed:)"
     redirect_to request.referrer
 else
     flash[:danger] = "U'r Not Succeed:H"
     redirect_to request.referrer
 end
</code>```

I want to save attrs in join table. According to rails official site guide, what's wrong?

First error:

unknown attribute 'channel_id' for User.

Second error:

undefined method `users' for Class:0x00007feaa0312058

答:
you can use push or << method instead of create : Channel.users.push(attrs) or Channel.users << (attrs)  and second answer in good too but .ids not very readable
or you can find channel by id and use it : channel.users.create(attrs)

see api.rubyonrails.org and search has_and_belongs_to_many methods in searchbar

Body:
I want to create a record in join table but rails shows me two errors in two situation, and I don't want to generate a third model.

@channel = Channel.find(params[:channel_id])
 if @channel.users.create!(channel_id: params[:channel_id], user_id: params[:user_id])
     flash[:success] = "U Succeed:)"
     redirect_to request.referrer
 else
     flash[:danger] = "U Nit Succeed:H"
     redirect_to request.referrer
 end

second situation

 if Channel.users.create!(channel_id: params[:channel_id], user_id: params[:user_id])
     flash[:success] = "U Succeed:)"
     redirect_to request.referrer
 else
     flash[:danger] = "U'r Not Succeed:H"
     redirect_to request.referrer
 end

I want to save attrs in join table. According to rails official site guide, what's wrong?

First error:

unknown attribute 'channel_id' for User.

Second error:

undefined method `users' for Class:0x00007feaa0312058


问:
Xcode Swift can not receive notification from Object-C
I use NetworkSpeedMonitor to check user networking
this is my code

```<code>networking = NetworkSpeedMonitor()
networking.start()
NotificationCenter.default.addObserver(self, selector: #selector(networkSpeedChanged(_:)), name: NSNotification.Name(rawValue: NetworkDownloadSpeedNotificationKey), object: self)
</code>```

this is my selector function

```<code>@objc func networkSpeedChanged(_ notification:NSNotification) {
    // never run
    if let downloadSpeed = notification.userInfo?[NetworkSpeedNotificationKey] as? String {
        self.networkingLabel.text = downloadSpeed
    }
}
</code>```

but I find that the selector is not run

答:
NotificationCenter.default.addObserver(self, selector: #selector(networkSpeedChanged(_:)), name: NSNotification.Name(rawValue: NetworkDownloadSpeedNotificationKey), object: nil)

instead of

NotificationCenter.default.addObserver(self, selector: #selector(networkSpeedChanged(_:)), name: NSNotification.Name(rawValue: NetworkDownloadSpeedNotificationKey), object: self)

Body:
I use NetworkSpeedMonitor to check user networking
this is my code

networking = NetworkSpeedMonitor()
networking.start()
NotificationCenter.default.addObserver(self, selector: #selector(networkSpeedChanged(_:)), name: NSNotification.Name(rawValue: NetworkDownloadSpeedNotificationKey), object: self)

this is my selector function

@objc func networkSpeedChanged(_ notification:NSNotification) {
    // never run
    if let downloadSpeed = notification.userInfo?[NetworkSpeedNotificationKey] as? String {
        self.networkingLabel.text = downloadSpeed
    }
}

but I find that the selector is not run


问:
External controllers for iPhone
Are there any external buttons/controls that can be plugged into the iPhone that can be used within an app. If so, does anyone have any links to any code to use with these controls.

I was thinking of some kind of iPod controller that I could hack that could be plugged into the slot on the bottom of the phone.

Cheers.

答:
Yes.  Several USB MIDI controllers are supported via the Camera Connection kit on stock OS iOS devices.  An app can use CoreMIDI in/out messages to get input from the buttons on these external MIDI controllers.

But an app can't use a generic hackable USB input device under the stock OS, unless the developer is the manufacturer and also a member of Apple's MFi program.

ADDED:

...or you hack the USB device so that it imitates one of Apple's supported MIDI devices.  Example of doing this with an AVR microcontroller is here.

Apple's CoreMIDI reference is here.

ADDED #2:

If you want even more accuracy for a timer app, consider using the mic audio input jack, and connecting some buttons to audio chirp generators (could be done either with analog circuitry or a tiny cheap micro).  Use different chirp frequencies for different buttons.  Some suitable DSP code on the iPhone could probably determine the relative timings of audio input chirp signals with sub-millisecond accuracy.

Title: External controllers for iPhone


答:
Assuming a is a pandas Series: whenever you call my_pandas_series.plot(), the return value is an Axes instance, an object which represents you plot region as a whole. This object has a set_xticks method for... well, setting the position of the x ticks in the plot.

On the other hand, calling plt.plot() returns a list of Line2D objects. Neither the list nor the Line2D objects inside it contains a set_xticks method.

Title: what's the difference between plt.plot(), object.plot()


问:
Checking the content of an array with comparison operators, concerning a specified order
I need a function which checks an array with integers. The integers have to be either in ascending order or in descending order. That depends from case to case.

I have figured out the following solution:

const areVersionNumbersInExpectedOrder = (aNums, sExpectedOrder = "ascending") => {
            let passed = false;

            if (sExpectedOrder === "ascending") {
                if (aNums[0] < aNums[1] && aNums[1] < aNums[2]) {
                    passed = true;
                }
            } else if (sExpectedOrder === "descending") {
                if (aNums[0] > aNums[1] && aNums[1] > aNums[2]) {
                    passed = true;
                }
            }

            return passed
        };

        const versionNumbersAscending = [1, 2, 3];
        console.log(
            `Result ascending order: ${areVersionNumbersInExpectedOrder(versionNumbersAscending, "ascending")}`);

        const versionNumbersDescending = [3, 2, 1];
        console.log(
            `Result descending order: ${areVersionNumbersInExpectedOrder(versionNumbersDescending, "descending")}`);```

Basically it works for me, but it is ugly. Especially the nested ifs.

Is there are better way to solve the task?

答:
I think this is better:</p>

```<code>const isInOrder = (arr, isAscending = true) => {
    let result = false;
    for (let i = 0; i < arr.length - 1; i++) {
        result = isAscending ? arr[i] <= arr[i + 1] : arr[i] >= arr[i + 1];
        if (!result) {
            return result;
        }
    }
    return result;
};
</code>```

Body:
I need a function which checks an array with integers. The integers have to be either in ascending order or in descending order. That depends from case to case.

I have figured out the following solution:

const areVersionNumbersInExpectedOrder = (aNums, sExpectedOrder = "ascending") => {
            let passed = false;

            if (sExpectedOrder === "ascending") {
                if (aNums[0] < aNums[1] && aNums[1] < aNums[2]) {
                    passed = true;
                }
            } else if (sExpectedOrder === "descending") {
                if (aNums[0] > aNums[1] && aNums[1] > aNums[2]) {
                    passed = true;
                }
            }

            return passed
        };

        const versionNumbersAscending = [1, 2, 3];
        console.log(
            `Result ascending order: ${areVersionNumbersInExpectedOrder(versionNumbersAscending, "ascending")}`);

        const versionNumbersDescending = [3, 2, 1];
        console.log(
            `Result descending order: ${areVersionNumbersInExpectedOrder(versionNumbersDescending, "descending")}`);

Basically it works for me, but it is ugly. Especially the nested ifs.

Is there are better way to solve the task?

Body:
I think this is better:

const isInOrder = (arr, isAscending = true) => {
    let result = false;
    for (let i = 0; i < arr.length - 1; i++) {
        result = isAscending ? arr[i] <= arr[i + 1] : arr[i] >= arr[i + 1];
        if (!result) {
            return result;
        }
    }
    return result;
};


问:
admin.site.register(Question) doesn't work
i am new to Django and python, and i want to start django admin with official exercises

i'm okay with running server. but questions doesn't show up.

my code is :

admin.py

```<code>from django.contrib import admin
from .models import Question

admin.site.register(Question)
</code>```

thank you for reading my question

答:
create a Question model class in models.py with the necessary fields then run makemigrations and migrate commands. Example question model is:</p>

```<code>class Question(models.Model):
      question_id = models.AutoField(auto_created=True,primary_key=True)
      name = models.CharField(max_length=100)

      def __str__(self):
           return self.name

      class Meta:
           verbose_name_plural="question"
</code>```

Body:
i am new to Django and python, and i want to start django admin with official exercises

i'm okay with running server. but questions doesn't show up.

my code is :

admin.py

from django.contrib import admin
from .models import Question

admin.site.register(Question)

thank you for reading my question

Body:
create a Question model class in models.py with the necessary fields then run makemigrations and migrate commands. Example question model is:

class Question(models.Model):
      question_id = models.AutoField(auto_created=True,primary_key=True)
      name = models.CharField(max_length=100)

      def __str__(self):
           return self.name

      class Meta:
           verbose_name_plural="question"


问:
Map() function only return last value?
This is data I wanna get :

```<code>    "buttons":[
           {
              "name":"Screen1",
              "display":"Screen1",
              "command":"Screen1"
           },
           {
              "name":"Screen2",
              "display":"Screen2",
              "command":"Screen2"
           },
           {
              "name":"Screen3",
              "display":"Screen3",
              "command":"Screen3"
           }
        ]
     },
</code>```

My code to get data buttons :

```<code>let btnConmand = '';
  let btnName = '';
  let btntest = data.map(ele => {
    if(ele.id == '0100') {
      ele.component[0].buttons.map(btns => {
        btnName = btns.name;
      });
    }
    return btnName ;

  }).join('');
 console.log(btntest)
</code>```

When I write console.log(btntest), it only return last value? How do I get all the values?

答:
You need to use an array

btntest

as an array. what you currently doing will return the last value as of btntest dataType.

Title: Map() function only return last value?

Body:
This is data I wanna get :

    "buttons":[
           {
              "name":"Screen1",
              "display":"Screen1",
              "command":"Screen1"
           },
           {
              "name":"Screen2",
              "display":"Screen2",
              "command":"Screen2"
           },
           {
              "name":"Screen3",
              "display":"Screen3",
              "command":"Screen3"
           }
        ]
     },

My code to get data buttons :

let btnConmand = '';
  let btnName = '';
  let btntest = data.map(ele => {
    if(ele.id == '0100') {
      ele.component[0].buttons.map(btns => {
        btnName = btns.name;
      });
    }
    return btnName ;

  }).join('');
 console.log(btntest)

When I write console.log(btntest), it only return last value? How do I get all the values?


问:
C# encoding a file in EBCDIC with packed decimals
I have to prepare a file for an outside entity, and this entity uses an IBM mainframe with COBOL and requires the file to be encoded in EBCDIC. I am creating the file in C#. I guess this is a two-part question...firstly, is the code below sufficient to ensure that the file will be generated in a manner that they can read?

```<code>StreamWriter sw = new StreamWriter(@"C:\EBCDICFileEquivalent.txt", false, Encoding.GetEncoding(37));
</code>```

Secondly, several fields in the file require packed decimal, in the format S(9)13 COMP-3. Since I have already specified EBCDIC encoding, can I just write the decimal number (e.g. 1234500000001) to the file using:

```<code>sw.WriteLine("1234500000001C");
</code>```

...and have it turn out correctly in the generated file?

Have never done anything with EBCDIC or COMP-3.

答:
That code should create an EBCDIC file just fine. This usually isn't necessary, since the FTP process will usually convert the file automatically from ASCII to EBCDIC, but if that is not the case, then the file you are creating should be correct and may be transmitted as binary rather than text.

Writing the number out as text with the appropriate substitutions to satisfy the mainframe zoned signed decimal format is the correct procedure. Of course, making these substituions is a pain, but writing them out as a string as you are doing is the right way to get it into the file that the mainframe can read.

Body:
I have to prepare a file for an outside entity, and this entity uses an IBM mainframe with COBOL and requires the file to be encoded in EBCDIC. I am creating the file in C#. I guess this is a two-part question...firstly, is the code below sufficient to ensure that the file will be generated in a manner that they can read?

StreamWriter sw = new StreamWriter(@"C:\EBCDICFileEquivalent.txt", false, Encoding.GetEncoding(37));

Secondly, several fields in the file require packed decimal, in the format S(9)13 COMP-3. Since I have already specified EBCDIC encoding, can I just write the decimal number (e.g. 1234500000001) to the file using:

sw.WriteLine("1234500000001C");

...and have it turn out correctly in the generated file?

Have never done anything with EBCDIC or COMP-3.


问:
Angular 8 component not getting rendered
Current scenario

An angular component (angular 8) with a text box and text area.

The component built using the command ""build": "ng build --prod --output-hashing=none"" (in the package.json)

Then the output min file is copied to another external folder containing an HTML file.

The component is displayed using the generated component tag.

Issue

Angular component not getting rendered in a HTML page when 'formControlName' is used for binding the value of a text box (In angular project).

How to implement the form using "formGroup" and 'formControlName' then sould be able to use the component in an external HTML file.

Any help would be highly appreciated. Thanks in advance.

```<code><--------html code-->

        <div>
        <form [formGroup]="generalRequestForm" (ngSubmit)="onSubmit()">
            <div class="mb-15 form-group">
                <select class="custom-select" formControlName="requests" id="requests" ngDefaultControl>
                    <option value="">Select Request Type</option>
                    <option *ngFor="let request of requests; let i = index" [value]="requests[i].id">
                        {{requests[i].name}}
                    </option>
                </select>
            </div>
            <div class="mb-15 form-group">
                <input type="text" class="form-control" placeholder="Item" formControlName="item" ngDefaultControl
                    autocomplete="off" />
                <div *ngIf="invalidItem" class="error">This field cannot be empty.</div>

            </div>
            <div class="mb-15 form-group">
                <textarea class="form-control comments" placeholder="Comments" formControlName="comments"
                    ngDefaultControl autocomplete="off"></textarea>
                <div *ngIf="invalidComments" class="error">This field cannot be empty.</div>

            </div>
            <div class="row align-items-center remember"></div>
            <div class="form-group">
                <button class="btn float-right submit_btn">Submit</button>
                <div *ngIf="invalidLogin" class="error">Invalid credentials.</div>
            </div>
        </form>
    </div>

**<-------ts code------->**

export class GeneralRequestComponent implements OnInit {
    generalRequestForm: FormGroup;
    invalidLogin: boolean = false;
    invalidItem: boolean = false;
    submitSuccess: boolean = false;
    invalidComments: boolean = false;
    requests;
    constructor(
        private formBuilder: FormBuilder,
        private router: Router,
        private apiService: ApiService
    ) {

        this.generalRequestForm = new FormGroup({
            item: new FormControl('', Validators.required),
            comments: new FormControl('', Validators.required),
            requests: new FormControl('', Validators.required),
        })

        of(this.getRequestType()).subscribe(requests => {
            this.requests = requests;
            this.generalRequestForm.controls.requests.patchValue(this.requests[0].id);
        });
    }

    onSubmit() {

        console.log("item...", this.generalRequestForm)
        if (!this.generalRequestForm.controls.item.value) {
            this.invalidItem = true;
            return;
        }
        else if (!this.generalRequestForm.controls.comments.value) {
            this.invalidComments = true;
            return;
        }
        else {
            alert("Your response has been recorded. Administrator would reach you before the time.")
            return;
        }
        if (this.generalRequestForm.invalid) {
            return;
        }
        const loginPayload = {
            item: this.generalRequestForm.controls.item.value,
            comments: this.generalRequestForm.controls.comments.value

        };
        this.apiService.login(loginPayload).subscribe(data => {
            if (data.status === 200) {
                window.localStorage.setItem('token', data.token);
                this.router.navigate(['home']);
            } else {
                this.invalidLogin = true;
                alert(data.message);
            }
        });
    }

    ngOnInit() {
        // window.localStorage.removeItem('token');
        // this.generalRequestForm = this.formBuilder.group({
        //     item: ['', Validators.compose([Validators.required])],
        //     comments: ['', Validators.required],
        //     requests: ['', Validators.required]
        // });

    }

    getRequestType() {
        return [
            { id: '1', name: 'Parking Slot' },
            { id: '2', name: 'Meal Card' },
            { id: '3', name: 'Infopark Sticker' },
            { id: '4', name: 'Address Proof' },
            { id: '5', name: 'Form 16' },
            { id: '6', name: 'Time Entry' },
            { id: '7', name: 'Other Request' }
        ];
    }
}
</code>```

答:
You may want to define a Form object in the typescript file (.ts), then bind it to the html form. This is called "reactive form", you can check out the documentation from angular on this subject:

https://angular.io/guide/reactive-forms

(it also contains an example to followup and gain more knowledge)

Body:
Current scenario

An angular component (angular 8) with a text box and text area.

The component built using the command ""build": "ng build --prod --output-hashing=none"" (in the package.json)

Then the output min file is copied to another external folder containing an HTML file.

The component is displayed using the generated component tag.

Issue

Angular component not getting rendered in a HTML page when 'formControlName' is used for binding the value of a text box (In angular project).

How to implement the form using "formGroup" and 'formControlName' then sould be able to use the component in an external HTML file.

Any help would be highly appreciated. Thanks in advance.

<--------html code-->

        <form [formGroup]="generalRequestForm" (ngSubmit)="onSubmit()">

                <select class="custom-select" formControlName="requests" id="requests" ngDefaultControl>
                    <option value="">Select Request Type</option>
                    <option *ngFor="let request of requests; let i = index" [value]="requests[i].id">
                        {{requests[i].name}}
                    </option>
                </select>

                <input type="text" class="form-control" placeholder="Item" formControlName="item" ngDefaultControl
                    autocomplete="off" />

This field cannot be empty.

                <textarea class="form-control comments" placeholder="Comments" formControlName="comments"
                    ngDefaultControl autocomplete="off"></textarea>

This field cannot be empty.

                <button class="btn float-right submit_btn">Submit</button>

Invalid credentials.

        </form>

**<-------ts code------->**

export class GeneralRequestComponent implements OnInit {
    generalRequestForm: FormGroup;
    invalidLogin: boolean = false;
    invalidItem: boolean = false;
    submitSuccess: boolean = false;
    invalidComments: boolean = false;
    requests;
    constructor(
        private formBuilder: FormBuilder,
        private router: Router,
        private apiService: ApiService
    ) {

        this.generalRequestForm = new FormGroup({
            item: new FormControl('', Validators.required),
            comments: new FormControl('', Validators.required),
            requests: new FormControl('', Validators.required),
        })

        of(this.getRequestType()).subscribe(requests => {
            this.requests = requests;
            this.generalRequestForm.controls.requests.patchValue(this.requests[0].id);
        });
    }

    onSubmit() {

        console.log("item...", this.generalRequestForm)
        if (!this.generalRequestForm.controls.item.value) {
            this.invalidItem = true;
            return;
        }
        else if (!this.generalRequestForm.controls.comments.value) {
            this.invalidComments = true;
            return;
        }
        else {
            alert("Your response has been recorded. Administrator would reach you before the time.")
            return;
        }
        if (this.generalRequestForm.invalid) {
            return;
        }
        const loginPayload = {
            item: this.generalRequestForm.controls.item.value,
            comments: this.generalRequestForm.controls.comments.value

        };
        this.apiService.login(loginPayload).subscribe(data => {
            if (data.status === 200) {
                window.localStorage.setItem('token', data.token);
                this.router.navigate(['home']);
            } else {
                this.invalidLogin = true;
                alert(data.message);
            }
        });
    }

    ngOnInit() {
        // window.localStorage.removeItem('token');
        // this.generalRequestForm = this.formBuilder.group({
        //     item: ['', Validators.compose([Validators.required])],
        //     comments: ['', Validators.required],
        //     requests: ['', Validators.required]
        // });

    }

    getRequestType() {
        return [
            { id: '1', name: 'Parking Slot' },
            { id: '2', name: 'Meal Card' },
            { id: '3', name: 'Infopark Sticker' },
            { id: '4', name: 'Address Proof' },
            { id: '5', name: 'Form 16' },
            { id: '6', name: 'Time Entry' },
            { id: '7', name: 'Other Request' }
        ];
    }
}


问:
How do I solve the staircase problem on Hacker rank
So, I'm trying to do the staircase problem in hacker rank, I'm trying to achieve it with C

The problem : https://www.hackerrank.com/challenges/staircase/problem

```<code>int i,j,k;
for(i=0;i<n;i++)
{
    for(j=i;j<n;j++)
    {
        printf(" ");
    }
    for(k=0;k<=i;k++)
    {
        printf("#");
    }
    printf("\n");
}
</code>```

}

But all the test cases are failing for the following code, any input would be really helpful :)

答:
From the requirement:

Note: The last line must have 0 spaces in it.

Now change printf(" "); to something like printf("O"); in your code
and you will see what the problem is about

Body:
So, I'm trying to do the staircase problem in hacker rank, I'm trying to achieve it with C

The problem : https://www.hackerrank.com/challenges/staircase/problem

int i,j,k;
for(i=0;i<n;i++)
{
    for(j=i;j<n;j++)
    {
        printf(" ");
    }
    for(k=0;k<=i;k++)
    {
        printf("#");
    }
    printf("\n");
}

}

But all the test cases are failing for the following code, any input would be really helpful :)


问:
How to provide more than one trusted package to deserialization in .yml?
When I am creating consumer and trying to deserialize object I got error

Caused by: IllegalArgumentException: The class 'com.domain.project2.package2.SomeEvent' is not in the trusted packages: [java.util, java.lang, com.domain.project2.package1, com.domain.project2.package2]. If you belive this class is....

My .yml config:

```<code>spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.support.serializer.JsonSerializer
    consumer:
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.support.serializer.JsonDeserializer
    properties:
      spring:
        json:
          trusted:
            packages: 'com.domain.project2.package1, com.domain.project2.package2'
</code>```

答:
I presume you mean

```<code>spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
    consumer:
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
    properties:
      spring:
        json:
          trusted:
            packages: 'com.domain.project2.package1, com.domain.project2.package2'
</code>```

Since you are using the Spring deserializer, not the apache JsonDeserializer.

The problem is the space after the comma.

Use 'com.domain.project2.package1,com.domain.project2.package2'.

We should probably trim the packages to remove extraneous spaces.

Body:
When I am creating consumer and trying to deserialize object I got error

Caused by: IllegalArgumentException: The class 'com.domain.project2.package2.SomeEvent' is not in the trusted packages: [java.util, java.lang, com.domain.project2.package1, com.domain.project2.package2]. If you belive this class is....

My .yml config:

spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.support.serializer.JsonSerializer
    consumer:
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.support.serializer.JsonDeserializer
    properties:
      spring:
        json:
          trusted:
            packages: 'com.domain.project2.package1, com.domain.project2.package2'

Body:
I presume you mean

spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
    consumer:
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
    properties:
      spring:
        json:
          trusted:
            packages: 'com.domain.project2.package1, com.domain.project2.package2'

Since you are using the Spring deserializer, not the apache JsonDeserializer.

The problem is the space after the comma.

Use 'com.domain.project2.package1,com.domain.project2.package2'.

We should probably trim the packages to remove extraneous spaces.


问:
Bootstrap carousel: images out of div when sliding
I have a problem I can't figure out. I'm using bootstrap's carousel and everything works fine except for transitions: next items appear out of myCarousel div when the sliding transition starts and previous active items slide out of myCarousel div as they are being replaced by my next item.

Here's my html code:

```<code><div id="myCarousel" class="carousel slide span6">
     <div id="carousel-inner">
            <div class="active item">
                 <img src="img/abstract-landscape-paintings-bursting-sun.jpg" />
             </div>
             <div class="item">
                  <img src="img/charnwood_forest_landscape.jpg" />
             </div>
      </div>
      <a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
      <a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
</div>
</code>```

I'm only using the carousel script:

```<code>    $(document).ready(function() {
    $(".carousel").carousel({
        interval: 5000,
        pause: "hover",
    });
});
</code>```

Here's a link to an example of my problem so you can check my entire code: http://todoapp.nfshost.com/slide

Anyone who can see what's the problem ?

Thank you!

答:
If overflow:hidden then try fixing the height of carousel-item

```<code>#carousel-item {
    height: 40rem;
}
</code>```

and,

```<code>img {
    width: 100%;
    height: 100%;
    display: block;
    background-size: cover;
  }
</code>```

Body:
I have a problem I can't figure out. I'm using bootstrap's carousel and everything works fine except for transitions: next items appear out of myCarousel div when the sliding transition starts and previous active items slide out of myCarousel div as they are being replaced by my next item.

Here's my html code:

      ‹
      ›

I'm only using the carousel script:

    $(document).ready(function() {
    $(".carousel").carousel({
        interval: 5000,
        pause: "hover",
    });
});

Here's a link to an example of my problem so you can check my entire code: http://todoapp.nfshost.com/slide

Anyone who can see what's the problem ?

Thank you!

Body:
If overflow:hidden then try fixing the height of carousel-item

#carousel-item {
    height: 40rem;
}

and,

img {
    width: 100%;
    height: 100%;
    display: block;
    background-size: cover;
  }


问:
How to convert a nested Python dict to object?
I'm searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).

For example:

```<code>>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
</code>```

Should be accessible in this way:

```<code>>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
</code>```

I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?

答:
I wasn't satisfied with the marked and upvoted answers, so here is a simple and general solution for transforming JSON-style nested datastructures (made of dicts and lists) into hierachies of plain objects:

```<code># tested in: Python 3.8
from collections import abc
from typings import Any, Iterable, Mapping, Union

class DataObject:
    def __repr__(self):
        return str({k: v for k, v in vars(self).items()})

def data_to_object(data: Union[Mapping[str, Any], Iterable]) -> object:
    """
    Example
    -------
    >>> data = {
    ...     "name": "Bob Howard",
    ...     "positions": [{"department": "ER", "manager_id": 13}],
    ... }
    ... data_to_object(data).positions[0].manager_id
    13
    """
    if isinstance(data, abc.Mapping):
        r = DataObject()
        for k, v in data.items():
            if type(v) is dict or type(v) is list:
                setattr(r, k, data_to_object(v))
            else:
                setattr(r, k, v)
        return r
    elif isinstance(data, abc.Iterable):
        return [data_to_object(e) for e in data]
    else:
        return data
</code>```

Body:
I'm searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).

For example:

>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}

Should be accessible in this way:

>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar

I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?

Body:
I wasn't satisfied with the marked and upvoted answers, so here is a simple and general solution for transforming JSON-style nested datastructures (made of dicts and lists) into hierachies of plain objects:

# tested in: Python 3.8
from collections import abc
from typings import Any, Iterable, Mapping, Union

class DataObject:
    def __repr__(self):
        return str({k: v for k, v in vars(self).items()})

def data_to_object(data: Union[Mapping[str, Any], Iterable]) -> object:
    """
    Example
    -------
    >>> data = {
    ...     "name": "Bob Howard",
    ...     "positions": [{"department": "ER", "manager_id": 13}],
    ... }
    ... data_to_object(data).positions[0].manager_id
    13
    """
    if isinstance(data, abc.Mapping):
        r = DataObject()
        for k, v in data.items():
            if type(v) is dict or type(v) is list:
                setattr(r, k, data_to_object(v))
            else:
                setattr(r, k, v)
        return r
    elif isinstance(data, abc.Iterable):
        return [data_to_object(e) for e in data]
    else:
        return data


问:
apply function after calling data response
I want to apply slider function after calling API response,

this this my code

```<code>async getProducts () {

                let response = await axios.get('{{url("/")}}/api/products?new=1&limit=6&order=desc&sort=created_at');
                const products = response.data.data;
                this.products = products;
                let element = document.getElementById("sliderContainer");
                element.classList.add("regular");
                this.applySlider();
}
</code>```

as you see i used async await but applySlider() function work before response?
what is my mistake? please, help me
Thanks in advance
 this is applySlider() function

```<code>applySlider() {
                if (this.products.length >= 1) {
                    $(".regular").slick({
                        //dots: true,
                        infinite: true,
                        slidesToShow: 4,
                        slidesToScroll: 4,
                        responsive: [
                            {
                            breakpoint: 992,
                            settings: {
                                slidesToShow: 3,
                                slidesToScroll: 3,
                                infinite: true,
                                dots: true,
                                arrows:false,
                            }
                            },
                            {
                            breakpoint: 768,
                            settings: {
                                slidesToShow: 2,
                                slidesToScroll: 2,
                                arrows:false,
                            }
                            },
                            {
                            breakpoint: 480,
                            settings: {
                                slidesToShow: 2,
                                slidesToScroll: 2,
                                arrows:false,
                            }
                            }
                        ]
                    });
                }
            }
</code>```

答:
You can use then method.

The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.

Try something like this:

```<code>axios.get('{{url("/")}}/api/products?new=1&limit=6&order=desc&sort=created_at')
  .then(response => {
    // handle success
    const products = response.data.data;
    this.products = products;
    let element = document.getElementById("sliderContainer");
    element.classList.add("regular");
    this.applySlider();
  })
</code>```

Minimal example:

```<code>axios.get('{{url("/")}}/api/products?new=1&limit=6&order=desc&sort=created_at')
  .then(response => {
    this.products = response.data.data;
    document.getElementById("sliderContainer").classList.add("regular");
    this.applySlider();
})
</code>```

Check the full axios documentation rigth here.

Body:
I want to apply slider function after calling API response,

this this my code

async getProducts () {

                let response = await axios.get('{{url("/")}}/api/products?new=1&limit=6&order=desc&sort=created_at');
                const products = response.data.data;
                this.products = products;
                let element = document.getElementById("sliderContainer");
                element.classList.add("regular");
                this.applySlider();
}

as you see i used async await but applySlider() function work before response?
what is my mistake? please, help me
Thanks in advance
 this is applySlider() function

applySlider() {
                if (this.products.length >= 1) {
                    $(".regular").slick({
                        //dots: true,
                        infinite: true,
                        slidesToShow: 4,
                        slidesToScroll: 4,
                        responsive: [
                            {
                            breakpoint: 992,
                            settings: {
                                slidesToShow: 3,
                                slidesToScroll: 3,
                                infinite: true,
                                dots: true,
                                arrows:false,
                            }
                            },
                            {
                            breakpoint: 768,
                            settings: {
                                slidesToShow: 2,
                                slidesToScroll: 2,
                                arrows:false,
                            }
                            },
                            {
                            breakpoint: 480,
                            settings: {
                                slidesToShow: 2,
                                slidesToScroll: 2,
                                arrows:false,
                            }
                            }
                        ]
                    });
                }
            }

Body:
You can use then method.

The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.

Try something like this:

axios.get('{{url("/")}}/api/products?new=1&limit=6&order=desc&sort=created_at')
  .then(response => {
    // handle success
    const products = response.data.data;
    this.products = products;
    let element = document.getElementById("sliderContainer");
    element.classList.add("regular");
    this.applySlider();
  })

Minimal example:

axios.get('{{url("/")}}/api/products?new=1&limit=6&order=desc&sort=created_at')
  .then(response => {
    this.products = response.data.data;
    document.getElementById("sliderContainer").classList.add("regular");
    this.applySlider();
})

Check the full axios documentation rigth here.