问:
Append an the entire array as one element to another array that has arrays of different sizes inside with Python
Let's say I have array 'a' like this

```<code>>>> a = np.array([[1,2], [3,4,5]])

>>> a.shape

(2,)
>>>
</code>```

Now I'd like to append the entire of an array like [6,7,8,9] to it as just one element and not four:

```<code>>>> b = np.append(a,[6,7,8,9])

>>> b.shape

(6,)
>>>
</code>```

But this is not what I want. What I do want is to have b having 3 elements and not 6 by stacking every element of the new array to a. I found a workaround  this as below but what is the proper way to get this done?

```<code>>>> b = np.append(a,[0])

>>> b[2] = [6,7,8,9]

>>> b.shape

(3,)
>>>
</code>```

答:
You shouldn't create numpy array with arrays of different sizes, because it's not how it works.

Result of first line, will be numpy array of 2 python lists.
If you want to have arrays of different sizes then you should use python list(), not ndarray.

And then you will be able to use append method.

```<code>a = [[1, 2], [3, 4, 5]]
a.append([6, 7, 8, 9])
</code>```

Body:
Let's say I have array 'a' like this

>>> a = np.array([[1,2], [3,4,5]])

>>> a.shape

(2,)
>>>

Now I'd like to append the entire of an array like [6,7,8,9] to it as just one element and not four:

>>> b = np.append(a,[6,7,8,9])

>>> b.shape

(6,)
>>>

But this is not what I want. What I do want is to have b having 3 elements and not 6 by stacking every element of the new array to a. I found a workaround  this as below but what is the proper way to get this done?

>>> b = np.append(a,[0])

>>> b[2] = [6,7,8,9]

>>> b.shape

(3,)
>>>

Body:
You shouldn't create numpy array with arrays of different sizes, because it's not how it works.

Result of first line, will be numpy array of 2 python lists.
If you want to have arrays of different sizes then you should use python list(), not ndarray.

And then you will be able to use append method.

a = [[1, 2], [3, 4, 5]]
a.append([6, 7, 8, 9])


来源: stackexchange

问:
sql query - how to apply limit within group by
I have a table named t1 with following fields: ROWID, CID, PID, Score, SortKey

it has the following data:

```<code>1, C1, P1, 10, 1
2, C1, P2, 20, 2
3, C1, P3, 30, 3

4, C2, P4, 20, 3
5, C2, P5, 30, 2

6, C3, P6, 10, 1
7, C3, P7, 20, 2
</code>```

what query do I write so that it applies group by on CID, but instead of returning me 1 single result per group, it returns me a max of 2 results per group. also where condition is score >= 20 and I want the results ordered by CID and SortKey.

If I had to run my query on above data, I would expect the following result:

RESULTS FOR C1 - note: ROWID 1 is not considered as its score < 20

```<code>C1, P2, 20, 2
C1, P3, 30, 3
</code>```

RESULTS FOR C2 - note: ROWID 5 appears before ROWID 4 as ROWID 5 has lesser value
SortKey

```<code>C2, P5, 30, 2
C2, P4, 20, 3
</code>```

RESULTS FOR C3 - note: ROWID 6 does not appear as its score is less than 20 so only 1 record returned here

```<code>C3, P7, 20, 2
</code>```

IN SHORT, I WANT A LIMIT WITHIN A GROUP BY. I want the simplest solution and want to avoid temp tables. sub queries are fine. Also note I am using SQLite for this.

答:
We can use LIMIT clause in SQLite. For example :

```<code>select * from tableName where field1='something' limit 10;
</code>```

this gives the 10 first rows.

ContentLicense: CC BY-SA 3.0

Body:
I have a table named t1 with following fields: ROWID, CID, PID, Score, SortKey

it has the following data:

1, C1, P1, 10, 1
2, C1, P2, 20, 2
3, C1, P3, 30, 3

4, C2, P4, 20, 3
5, C2, P5, 30, 2

6, C3, P6, 10, 1
7, C3, P7, 20, 2

what query do I write so that it applies group by on CID, but instead of returning me 1 single result per group, it returns me a max of 2 results per group. also where condition is score >= 20 and I want the results ordered by CID and SortKey.

If I had to run my query on above data, I would expect the following result:

RESULTS FOR C1 - note: ROWID 1 is not considered as its score < 20

C1, P2, 20, 2
C1, P3, 30, 3

RESULTS FOR C2 - note: ROWID 5 appears before ROWID 4 as ROWID 5 has lesser value
SortKey

C2, P5, 30, 2
C2, P4, 20, 3

RESULTS FOR C3 - note: ROWID 6 does not appear as its score is less than 20 so only 1 record returned here

C3, P7, 20, 2

IN SHORT, I WANT A LIMIT WITHIN A GROUP BY. I want the simplest solution and want to avoid temp tables. sub queries are fine. Also note I am using SQLite for this.

Body:
We can use LIMIT clause in SQLite. For example :

select * from tableName where field1='something' limit 10;

this gives the 10 first rows.


问:
How to sort javascript array where first record should be specific and then follow by descending order
input array as list object like,  [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

Expected sorted descending order output as, "active" object should be first and all other descending sorted by numbers after "active" record.
Tried with below approach but it does not give me active as first entry. this sort the descending by number but active not coming first.

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

const customSortActiveShouldBeFirst = function(array) {
  let key = 'number';
  if (array && array.length > 0) {
    return array.sort(function(a, b) {
      var x = a[key];
      var y = b[key];
      return (x['Active'] === true ? 1 : (y - x));
    });
  }
  return array;
};
console.log(customSortActiveShouldBeFirst(arr))```

Expected output:
Active object to be first in result array and then all entries descending by numbers. like, [{ number: 2.3 , Active: true },{ number: 13.23 , Active: false },{ number: 2.21 , Active: false }]

答:
You can filter by the items of the array which Active is true and false.

Then sort the items of the array which Active is false

const arr =
  [
    { number: 13.23 , Active: false },
    { number: 2.21 , Active: false },
    { number: 2.3 , Active: true }
  ];

const activeTrueArr = arr.filter(({ Active }) => Active);
const activeFalseArr = arr.filter(({ Active }) => !Active);

activeFalseArr.sort((a, b) => {
  return a.number < b.number ? 1 : -1;
})

console.log([...activeTrueArr, ...activeFalseArr])```

ContentLicense: CC BY-SA 4.0

Body:
input array as list object like,  [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

Expected sorted descending order output as, "active" object should be first and all other descending sorted by numbers after "active" record.
Tried with below approach but it does not give me active as first entry. this sort the descending by number but active not coming first.

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

const customSortActiveShouldBeFirst = function(array) {
  let key = 'number';
  if (array && array.length > 0) {
    return array.sort(function(a, b) {
      var x = a[key];
      var y = b[key];
      return (x['Active'] === true ? 1 : (y - x));
    });
  }
  return array;
};
console.log(customSortActiveShouldBeFirst(arr))

Expected output:
Active object to be first in result array and then all entries descending by numbers. like, [{ number: 2.3 , Active: true },{ number: 13.23 , Active: false },{ number: 2.21 , Active: false }]


问:
How can I make my model conform to codable and save it locally on every change?
I have a parent class, that has children (Child Class), that have Puppets (Puppet Class).
The data is displayed in a list of parents that navigates to a list of children, that navigates to a list of puppets.

Within the views, the user is able to add parents, children and puppets or remove them.

I want to store the data locally so that every change is save. I think storing the Parent class is enough, because of parents.children.puppets.
Thus I need to conform to Codable anyhow and decode and encode my data anyhow.

The AppState should load local data or [] instead of the current dummy data. On every parent (or child or puppet) change, I want to store the parents locally in the most efficient way.
Same for receiving the data.

```<code>class Parent: ObservableObject, Hashable {

    static func == (lhs: Parent, rhs: Parent) -> Bool {
        lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    let id = UUID()
    let name: String
    @Published var children: [Child]

    init(name: String, children: [Child]? = nil) {
        self.name = name
        self.children = children ?? []
    }

    func remove(child: Child) {
        self.children.remove(child)
    }

    func add(child: Child) {
        self.children.append(child)
    }
}

class Child: ObservableObject, Identifiable, Hashable {
    static func == (lhs: Child, rhs: Child) -> Bool {
        return lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    let id = UUID()
    let name: String
    @Published var puppets: [Puppet]

    init(name: String, puppets:[Puppet]? = nil) {
        self.name = name
        self.puppets = puppets ?? []
    }

    func remove(puppet: Puppet) {
        self.puppets.remove(puppet)
    }

    func add(puppet: Puppet) {
        self.puppets.append(puppet)
    }
}

struct Puppet: Identifiable, Hashable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar", puppets: [Puppet(name: "Tom")])]),
            Parent(name: "FooBar", children: [Child(name: "foo", puppets: nil)])
        ]
    }
}

extension Array where Element: Identifiable {
    mutating func remove(_ object: Element) {
        if let index = self.firstIndex(where: { $0.id == object.id}) {
            self.remove(at: index)
        }
    }
}
</code>```

答:
If you're not bound to any database or format, I'd recommend using CoreData (as suggested in the comments).

From Apple documentation:

Use Core Data to save your application’s permanent data for offline
  use, to cache temporary data, and to add undo functionality to your
  app on a single device.

This way your model doesn't have to conform to Codable.

You can find more information in these links:

Core Data for beginners

Getting started with Core Data Tutorial

Getting started with Core Data

Body:
I have a parent class, that has children (Child Class), that have Puppets (Puppet Class).
The data is displayed in a list of parents that navigates to a list of children, that navigates to a list of puppets.

Within the views, the user is able to add parents, children and puppets or remove them.

I want to store the data locally so that every change is save. I think storing the Parent class is enough, because of parents.children.puppets.
Thus I need to conform to Codable anyhow and decode and encode my data anyhow.

The AppState should load local data or [] instead of the current dummy data. On every parent (or child or puppet) change, I want to store the parents locally in the most efficient way.
Same for receiving the data.

class Parent: ObservableObject, Hashable {

    static func == (lhs: Parent, rhs: Parent) -> Bool {
        lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    let id = UUID()
    let name: String
    @Published var children: [Child]

    init(name: String, children: [Child]? = nil) {
        self.name = name
        self.children = children ?? []
    }

    func remove(child: Child) {
        self.children.remove(child)
    }

    func add(child: Child) {
        self.children.append(child)
    }
}

class Child: ObservableObject, Identifiable, Hashable {
    static func == (lhs: Child, rhs: Child) -> Bool {
        return lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    let id = UUID()
    let name: String
    @Published var puppets: [Puppet]

    init(name: String, puppets:[Puppet]? = nil) {
        self.name = name
        self.puppets = puppets ?? []
    }

    func remove(puppet: Puppet) {
        self.puppets.remove(puppet)
    }

    func add(puppet: Puppet) {
        self.puppets.append(puppet)
    }
}

struct Puppet: Identifiable, Hashable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar", puppets: [Puppet(name: "Tom")])]),
            Parent(name: "FooBar", children: [Child(name: "foo", puppets: nil)])
        ]
    }
}

extension Array where Element: Identifiable {
    mutating func remove(_ object: Element) {
        if let index = self.firstIndex(where: { $0.id == object.id}) {
            self.remove(at: index)
        }
    }
}


问:
How To: Deploy SQL Database Project using Team System Build 2010 (beta 2)
Can anyone shed some light on how to get Team Build 2010 beta 2 to push a SQL database project to the SQL server?

In VSTS 2008 you'd just add MSBuild commands with the targets attribute set to "deploy" in the TFSBuild.proj file, but I'm having a little trouble translating that to the new workflow based xaml thing that 2010 uses.

What I'm looking for is how to trigger the actual deployment of the databases themselves. It is already generating the deployment scripts just fine.

答:
There is another solution to this problem if you don't need incremental database upgrade. So if recreating the database for each build is ok with you the following would also work.

Add a deploy target to Database Project file

Configure the deployment settings for ‘My project settings’.  Those settings will then be used by the build server when building the solution. When building locally, the settings used will be the ones from ‘My isolated development environment’.

In the database project properties

Deploy Action needs to be ‘Create a deployment script (.sql) and deploy the database’; this will prevent the execution of the script, it will only create it.

Database project file

Modify the database project file (right-click database project, select Unload, right-click again, select Edit [ProjectName].dbproj)
from

```<code><Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
</code>```

To

```<code><Project DefaultTargets="Build;Deploy" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
</code>```

When the Build server builds the solution containing the database project, adding the default targets will also deploy the database. This build will use the Deploy settings selected for ‘My project settings’.

Pros

Easy to set up

Cons

Because the default target is changed to Build and Deploy, when a developer do a local Rebuild of the solution, it will also deploy the database (building only won't trigger the deployment)

ContentLicense: CC BY-SA 2.5

Body:
There is another solution to this problem if you don't need incremental database upgrade. So if recreating the database for each build is ok with you the following would also work.

Add a deploy target to Database Project file

Configure the deployment settings for ‘My project settings’.  Those settings will then be used by the build server when building the solution. When building locally, the settings used will be the ones from ‘My isolated development environment’.

In the database project properties

Deploy Action needs to be ‘Create a deployment script (.sql) and deploy the database’; this will prevent the execution of the script, it will only create it.

Database project file

Modify the database project file (right-click database project, select Unload, right-click again, select Edit [ProjectName].dbproj)
from

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">

To

<Project DefaultTargets="Build;Deploy" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">

When the Build server builds the solution containing the database project, adding the default targets will also deploy the database. This build will use the Deploy settings selected for ‘My project settings’.

Pros

Easy to set up

Cons

Because the default target is changed to Build and Deploy, when a developer do a local Rebuild of the solution, it will also deploy the database (building only won't trigger the deployment)


问:
Laravel Spatie Roles and permissions - error on Update
I need help for my Laravel application.

I use spatie roles and permissions.

When i create the user, assign roles is no problem. When i will update the same user, there is the following error:

[2019-12-06 08:44:36] local.ERROR: The given role or permission should use guard instead of `web`. {"userId":1,"exception":"[object] (Spatie\\Permission\\Exceptions\\GuardDoesNotMatch(code: 0): The given role or permission should use guard instead of web. at /home/vagrant/code/test/vendor/spatie/laravel-permission/src/Exceptions/GuardDoesNotMatch.php:12)

```<code>public function store(StoreUserRequest $request)
{
    $user = $this->repo->create( $request->all());

    $user->assignRole($request->roles);

    return $user;
}

public function update(UpdateUserRequest $request, User $user)
{
    $user = $this->repo->update($user, $request->all());

    $user->assignRole($request->roles);

    return $user;
}
</code>```

I added protected $guard_name = 'web'; to the User Model but still the same problem.

What is wrong? Is there a problme with the userId?

答:
When you assign role for a user the model path App\User insert into table model_has_roles if you change the model folders spatie give you an error. I think this code may help you more.

don't missing add HasRoles

```<code>class User extends Authenticatable
{

    use Notifiable, HasRoles;
    ...
}
</code>```

make sure you import use App\User;

UserController

```<code>public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users,email,'.$id,
            'password' => 'same:confirm-password',
            'roles' => 'required'
        ]);

        $input = $request->all();
        if(!empty($input['password'])){
            $input['password'] = Hash::make($input['password']);
        }else{
            $input = array_except($input,array('password'));
        }

        $user = User::find($id);
        $user->update($input);
        DB::table('model_has_roles')->where('model_id',$id)->delete();

        $user->assignRole($request->input('roles'));

        return redirect()->route('users.index')
                        ->with('success','User updated successfully');
    }
</code>```

Body:
I need help for my Laravel application.

I use spatie roles and permissions.

When i create the user, assign roles is no problem. When i will update the same user, there is the following error:

[2019-12-06 08:44:36] local.ERROR: The given role or permission should use guard instead of `web`. {"userId":1,"exception":"[object] (Spatie\\Permission\\Exceptions\\GuardDoesNotMatch(code: 0): The given role or permission should use guard instead of web. at /home/vagrant/code/test/vendor/spatie/laravel-permission/src/Exceptions/GuardDoesNotMatch.php:12)

public function store(StoreUserRequest $request)
{
    $user = $this->repo->create( $request->all());

    $user->assignRole($request->roles);

    return $user;
}

public function update(UpdateUserRequest $request, User $user)
{
    $user = $this->repo->update($user, $request->all());

    $user->assignRole($request->roles);

    return $user;
}

I added protected $guard_name = 'web'; to the User Model but still the same problem.

What is wrong? Is there a problme with the userId?

Body:
When you assign role for a user the model path App\User insert into table model_has_roles if you change the model folders spatie give you an error. I think this code may help you more.

don't missing add HasRoles

class User extends Authenticatable
{

    use Notifiable, HasRoles;
    ...
}

make sure you import use App\User;

UserController

public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users,email,'.$id,
            'password' => 'same:confirm-password',
            'roles' => 'required'
        ]);

        $input = $request->all();
        if(!empty($input['password'])){
            $input['password'] = Hash::make($input['password']);
        }else{
            $input = array_except($input,array('password'));
        }

        $user = User::find($id);
        $user->update($input);
        DB::table('model_has_roles')->where('model_id',$id)->delete();

        $user->assignRole($request->input('roles'));

        return redirect()->route('users.index')
                        ->with('success','User updated successfully');
    }


问:
Room's `onDelete = CASCADE` not working during a migration
I have the following tables:

```<code>@Entity(
    tableName = "users"
)
class Users {
    @PrimaryKey(autoGenerate = true)
    var id: Long? = null

    @NonNull
    var name: String? = null
}

@Entity(
    tableName = "pets",
    foreignKeys = [
        ForeignKey(
            entity = Users::class,
            parentColumns = ["id"],
            childColumns = ["owner_id"],
            onDelete = ForeignKey.CASCADE
        )
    ]
)
class Pets {
    @PrimaryKey(autoGenerate = true)
    var id: Long? = null

    @NonNull
    var name: String? = null

    @ColumnInfo(name = "owner_id")
    var ownerId: Long? = null
}
</code>```

When I run a migration that deletes all users table rows, the pets table is not affected. The rows are not automatically deleted.

```<code>object Migration_1_2 : Migration(1, 2) {

    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("""
            DELETE FROM users
        """)
    }
}
</code>```

Even when I execute the following snippet of code before the migration it does not work.

```<code>database.execSQL("PRAGMA foreign_keys=ON;");
</code>```

What should I do to make the onDelete = ForeignKey.CASCADE work?

答:
As @sergiytikhonov indicates in his comment, enabling the foreign_keys constraint in a migration function has no effect. This is because migrations are executed as part of a transaction and the pragma is a no-op inside a transaction.

I don't see any way to get control and enable foreign_keys before the migration is executed.  I think your only option is to delete the pets explicitly as part of the migration:

```<code>override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL("""
        DELETE FROM pets WHERE owner_id IN (SELECT id FROM users)
    """)

    database.execSQL("""
        DELETE FROM users
    """)
}
</code>```

Body:
I have the following tables:

@Entity(
    tableName = "users"
)
class Users {
    @PrimaryKey(autoGenerate = true)
    var id: Long? = null

    @NonNull
    var name: String? = null
}

@Entity(
    tableName = "pets",
    foreignKeys = [
        ForeignKey(
            entity = Users::class,
            parentColumns = ["id"],
            childColumns = ["owner_id"],
            onDelete = ForeignKey.CASCADE
        )
    ]
)
class Pets {
    @PrimaryKey(autoGenerate = true)
    var id: Long? = null

    @NonNull
    var name: String? = null

    @ColumnInfo(name = "owner_id")
    var ownerId: Long? = null
}

When I run a migration that deletes all users table rows, the pets table is not affected. The rows are not automatically deleted.

object Migration_1_2 : Migration(1, 2) {

    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("""
            DELETE FROM users
        """)
    }
}

Even when I execute the following snippet of code before the migration it does not work.

database.execSQL("PRAGMA foreign_keys=ON;");

What should I do to make the onDelete = ForeignKey.CASCADE work?

Body:
As @sergiytikhonov indicates in his comment, enabling the foreign_keys constraint in a migration function has no effect. This is because migrations are executed as part of a transaction and the pragma is a no-op inside a transaction.

I don't see any way to get control and enable foreign_keys before the migration is executed.  I think your only option is to delete the pets explicitly as part of the migration:

override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL("""
        DELETE FROM pets WHERE owner_id IN (SELECT id FROM users)
    """)

    database.execSQL("""
        DELETE FROM users
    """)
}


问:
Two NSArrays combine to a NSDictionary with alternating values
Hi I am very new to Objective-c please excuse my ignorance. So basically this is what I want to happened. I have two arrays of numbers

```<code>Array1: (1,3,5);
Array2: (2,4,6);
</code>```

and I want them to be like this after combining them in a dictionary

```<code>"dictionary":{"1":2,: "3":4, "5":6}
</code>```

Any feedback will be appreciated!

答:
Arrays

I have two arrays of numbers Array1: (1,3,5) & Array2: (2,4,6)

I assume that you have them in NSArray and that you're aware of NSNumber & Objective-C Literals. In other words, you have:

NSArray *keys    = @[@1, @3, @5]; // Array of NSNumber
NSArray *objects = @[@2, @4, @6]; // Array of NSNumber
```

<blockquote>
  <p>"dictionary":{"1":2,: "3":4, "5":6}</p>
</blockquote>

<p>I assume that it means:</p>

<pre class="lang-c prettyprint-override"><code>@{
    @"dictionary": @{
        @"1": @2,
        @"3": @4,
        @"5": @6
    }
}
</code>```

Step 1 - Stringify keys

NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];

NSMutableArray *stringifiedKeys = [NSMutableArray arrayWithCapacity:keys.count];
for (NSNumber *key in keys) {
    [stringifiedKeys addObject:key.stringValue];
}

```

<h2>Step 2 - Create a dictionary</h2>

<p><code>dictionaryWithObjects:forKeys:</code>:</p>

<pre class="lang-c prettyprint-override"><code>+ (instancetype)dictionaryWithObjects:(NSArray<ObjectType> *)objects
                              forKeys:(NSArray<id<NSCopying>> *)keys;
</code>```

You can use it in this way:

NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];

NSMutableArray *stringifiedKeys = [NSMutableArray arrayWithCapacity:keys.count];
for (NSNumber *key in keys) {
    [stringifiedKeys addObject:key.stringValue];
}

NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
                                                       forKeys:stringifiedKeys];
```

<h2>Step 3 - Wrap it in a dictionary</h2>

<pre class="lang-c prettyprint-override"><code>NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];

NSMutableArray *stringifiedKeys = [NSMutableArray arrayWithCapacity:keys.count];
for (NSNumber *key in keys) {
    [stringifiedKeys addObject:key.stringValue];
}

NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
                                                       forKeys:stringifiedKeys];
NSDictionary *result = @{ @"dictionary": dictionary };

NSLog(@"%@", result);
</code>```

Result:

```<code>{
    dictionary = {
        1 = 2;
        3 = 4;
        5 = 6;
    };
}
</code>```

Manually

NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];

// Mimick dictionaryWithObjects:forKeys: behavior
if (objects.count != keys.count) {
    NSString *reason = [NSString stringWithFormat:@"count of objects (%lu) differs from count of keys (%lu)", (unsigned long)objects.count, (unsigned long)keys.count];

    @throw [NSException exceptionWithName:NSInvalidArgumentException
                                   reason:reason
                                 userInfo:nil];
}

NSMutableDictionary *inner = [NSMutableDictionary dictionaryWithCapacity:keys.count];

for (NSUInteger index = 0 ; index < keys.count ; index++) {
    NSString *key = [keys[index] stringValue];
    NSString *object = objects[index];
    inner[key] = object;
}

NSDictionary *result = @{ @"dictionary": inner };
```

Footnotes

Because of I am very new to Objective-C, I did intentionally avoid:

Blocks & safer ways to enumerate

Lightweight generics

Nullability stuff

Body:
Hi I am very new to Objective-c please excuse my ignorance. So basically this is what I want to happened. I have two arrays of numbers

Array1: (1,3,5);
Array2: (2,4,6);

and I want them to be like this after combining them in a dictionary

"dictionary":{"1":2,: "3":4, "5":6}

Any feedback will be appreciated!

Body:
Arrays

I have two arrays of numbers Array1: (1,3,5) & Array2: (2,4,6)

I assume that you have them in NSArray and that you're aware of NSNumber & Objective-C Literals. In other words, you have:

NSArray *keys    = @[@1, @3, @5]; // Array of NSNumber
NSArray *objects = @[@2, @4, @6]; // Array of NSNumber

"dictionary":{"1":2,: "3":4, "5":6}

I assume that it means:

@{
    @"dictionary": @{
        @"1": @2,
        @"3": @4,
        @"5": @6
    }
}

Step 1 - Stringify keys

NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];

NSMutableArray *stringifiedKeys = [NSMutableArray arrayWithCapacity:keys.count];
for (NSNumber *key in keys) {
    [stringifiedKeys addObject:key.stringValue];
}

Step 2 - Create a dictionary

dictionaryWithObjects:forKeys::

+ (instancetype)dictionaryWithObjects:(NSArray<ObjectType> *)objects
                              forKeys:(NSArray<id<NSCopying>> *)keys;

You can use it in this way:

NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];

NSMutableArray *stringifiedKeys = [NSMutableArray arrayWithCapacity:keys.count];
for (NSNumber *key in keys) {
    [stringifiedKeys addObject:key.stringValue];
}

NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
                                                       forKeys:stringifiedKeys];

Step 3 - Wrap it in a dictionary

NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];

NSMutableArray *stringifiedKeys = [NSMutableArray arrayWithCapacity:keys.count];
for (NSNumber *key in keys) {
    [stringifiedKeys addObject:key.stringValue];
}

NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
                                                       forKeys:stringifiedKeys];
NSDictionary *result = @{ @"dictionary": dictionary };

NSLog(@"%@", result);

Result:

{
    dictionary = {
        1 = 2;
        3 = 4;
        5 = 6;
    };
}

Manually

NSArray *keys = @[@1, @3, @5];
NSArray *objects = @[@2, @4, @6];

// Mimick dictionaryWithObjects:forKeys: behavior
if (objects.count != keys.count) {
    NSString *reason = [NSString stringWithFormat:@"count of objects (%lu) differs from count of keys (%lu)", (unsigned long)objects.count, (unsigned long)keys.count];

    @throw [NSException exceptionWithName:NSInvalidArgumentException
                                   reason:reason
                                 userInfo:nil];
}

NSMutableDictionary *inner = [NSMutableDictionary dictionaryWithCapacity:keys.count];

for (NSUInteger index = 0 ; index < keys.count ; index++) {
    NSString *key = [keys[index] stringValue];
    NSString *object = objects[index];
    inner[key] = object;
}

NSDictionary *result = @{ @"dictionary": inner };

Footnotes

Because of I am very new to Objective-C, I did intentionally avoid:

Blocks & safer ways to enumerate

Lightweight generics

Nullability stuff


问:
(Why) can we assign non-static class members to static variables in initialization?
In a larger code base I have encountered code like this (see on godbolt):

```<code>struct Foo {};

struct Base {
    Foo* a;
};

struct Bar : public Base {
    static Foo* Bar::*mybar[];
};

Foo* Bar::Bar::*mybar[] = {
    &Base::a
};
</code>```

To be honest, I'm baffled. This looks like it's initializing a static array of Foo pointers in Bar with a non-static member variable of Base. How is that even possible without an object?

(Disclaimer: This is found in production code that actually works - hopefully not relying on UB?)

Also, is there any problem if I remove the qualified name lookup like here? I'd like to refactor the code and make it more readable. All these Bar::s seem quite superfluous, but since I'm not feeling so comfortable with the code I'd rather understand the implications first.

答:
How is that even possible without an object?

It is possible to create pointer to member variables without an object. The pointers can be used to dereference an actual member only in the presence of an object.

Simpler example:

```<code>struct Foo { int m; int n};

using MemberPtr = int Foo::*;

MemberPtr p1 = &Foo::m;  // Instance of Foo is not needed.
MemberPtr p2 = &Foo::n;  // Instance of Foo is not needed.

*p1 = 10; //  Not allowed.
*p2 = 20; //  Not allowed.

Foo a;
a.*p1 = 10;  // Changes a.m
a.*p2 = 20;  // Changes a.n

Foo b;
b.*p1 = 30;  // Changes b.m
b.*p2 = 40;  // Changes b.n
</code>```

Please note that you are able to change values of members of two instances of the class using the same pointer to member variables.

Body:
In a larger code base I have encountered code like this (see on godbolt):

struct Foo {};

struct Base {
    Foo* a;
};

struct Bar : public Base {
    static Foo* Bar::*mybar[];
};

Foo* Bar::Bar::*mybar[] = {
    &Base::a
};

To be honest, I'm baffled. This looks like it's initializing a static array of Foo pointers in Bar with a non-static member variable of Base. How is that even possible without an object?

(Disclaimer: This is found in production code that actually works - hopefully not relying on UB?)

Also, is there any problem if I remove the qualified name lookup like here? I'd like to refactor the code and make it more readable. All these Bar::s seem quite superfluous, but since I'm not feeling so comfortable with the code I'd rather understand the implications first.

Body:
How is that even possible without an object?

It is possible to create pointer to member variables without an object. The pointers can be used to dereference an actual member only in the presence of an object.

Simpler example:

struct Foo { int m; int n};

using MemberPtr = int Foo::*;

MemberPtr p1 = &Foo::m;  // Instance of Foo is not needed.
MemberPtr p2 = &Foo::n;  // Instance of Foo is not needed.

*p1 = 10; //  Not allowed.
*p2 = 20; //  Not allowed.

Foo a;
a.*p1 = 10;  // Changes a.m
a.*p2 = 20;  // Changes a.n

Foo b;
b.*p1 = 30;  // Changes b.m
b.*p2 = 40;  // Changes b.n

Please note that you are able to change values of members of two instances of the class using the same pointer to member variables.


问:
How to get total number of misfiers by quartz scheduler
Is there any method provided by quartz to get total number of misfiers, I am aware about a way, with the help of listeners we can identify the misfier occured by the job, but it would be helpful if I can get total misfier count by all the jobs.

I gone throgh the quartz documentation, but didn't find any solution for the same.

答:
Quartz scheduler API does not provide any method that returns the total number of misfires since its restart. You will need to implement a TriggerListener and implement its triggerMisfired method and do the counting.

Alternatively, you can use QuartzDesk (I am biased here) or some other Quartz GUI manager that provides this information for you in the GUI, through an API or via a simple SQL query.


问:
map and filter function in selector
My selector checks all actions from array and then deletes empty elements. Can it be written better?

const makeSelectError2 = (actions) =>
  createSelector(selectError, (errorState) =>
    actions
      .map((action) =>
        errorState[action] !== undefined ? errorState[action] : null,
      )
      .filter((action) => action)
      .find((action) => true),
  );
```

答:
Using Array.flatMap you can combine map and filter into one by either returning an array with one item or zero items for each item processed.

So

```<code>actions
  .flatMap((action) => !!errorState[action]
                       ? [ errorState[action] ]
                       : []
  )[0]
</code>```

Title: map and filter function in selector

Body:
Using Array.flatMap you can combine map and filter into one by either returning an array with one item or zero items for each item processed.

So

actions
  .flatMap((action) => !!errorState[action]
                       ? [ errorState[action] ]
                       : []
  )[0]


问:
Kafka partition contents redistribute
If you have multiple partitions/consumers, and one falls far behind (e.g. stuck for a while on a poison event) allowing a queue to build up, is there an established pattern for re-distributing the queued events (while respecting ordering of serialisation key)?

The intent is to redistribute work from a partition/consumer with a queue to other potentially drained/idle partitions/consumers.

答:
I think the answer is a simple no. If you have a poison message the best approach is to move it to another topic (a dead letter) and keep consuming. This approach is a lot simpler than redistributing the messages to another partition (if I understood your question correcly).

Kafka guarantees the ordering of events for a given partition. Moving messages to another partition would break this guarantee.

A suggestion: share the problem you are trying to solve rather than a potential solution. The world of Kafka is kafkaesque to say the least and the correct solutions are usually not straightforward.

edit

I just read your comment/update. I have the feeling kafka might not be the right tool. And I would like to understand a bit more as there are two contradicting things you mentioned: (1)Ordering, but (2)happy to move messages to other consumers so they complete as quick as possible (which would break ordering). Usually the need to ordering is not real or it's possible to easily come up with a solution that doesn't require ordering.

It sounds to me that a normal queue will do what you want (pick your poison: SQS, ActiveMQ, RabbitMQ...)

Let me know if this helps!

Title: Kafka partition contents redistribute


问:
Sum of a number's digits with JavaScript
I have:

```<code>var nums = [333, 444, 555];
</code>```

I want to treat each digit in a number as a separate number and add them together. In this case sums should be:

```<code>9 = 3 + 3 + 3
12 = 4 + 4 + 4
15 = 5 + 5 + 5
</code>```

How to achieve this using JavaScript?

答:
Now in our days, with the advantages of ES6, you can simply spread each value of your array inside map, and the with reduce make the operation:

var numbers = [333, 444, 555];

const addDigits = nums => nums.map(
      num => [...num.toString()].reduce((acc, act) => acc + parseInt(act), 0)
);

console.log(addDigits(numbers));```

Body:
I have:

var nums = [333, 444, 555];

I want to treat each digit in a number as a separate number and add them together. In this case sums should be:

9 = 3 + 3 + 3
12 = 4 + 4 + 4
15 = 5 + 5 + 5

How to achieve this using JavaScript?


问:
How to find a US zip code in a string using regular expression?
Fill in the code to check if the text passed includes a possible U.S. zip code, formatted as follows: exactly 5 digits, and sometimes, but not always, followed by a dash with 4 more digits. The zip code needs to be preceded by at least one space, and cannot be at the start of the text.

Couldn't produce the required output.

```<code>import re
def check_zip_code (text):
  result = re.search(r"\w+\d{5}-?(\d{4})?", text)
  return result != None

print(check_zip_code("The zip codes for New York are 10001 thru 11104.")) # True
print(check_zip_code("90210 is a TV show")) # False
print(check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.")) # True
print(check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.")) # False
</code>```

答:
You could use

```<code>(?!\A)\b\d{5}(?:-\d{4})?\b
</code>```

Full code:

```<code>import re

def check_zip_code (text):
    m = re.search(r'(?!\A)\b\d{5}(?:-\d{4})?\b', text)
    return True if m else False

print(check_zip_code("The zip codes for New York are 10001 thru 11104.")) # True
print(check_zip_code("90210 is a TV show")) # False
print(check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.")) # True
print(check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.")) # False
</code>```

Meanwhile I found that there's a package called zipcodes which might be of additional help.

Body:
Fill in the code to check if the text passed includes a possible U.S. zip code, formatted as follows: exactly 5 digits, and sometimes, but not always, followed by a dash with 4 more digits. The zip code needs to be preceded by at least one space, and cannot be at the start of the text.

Couldn't produce the required output.

import re
def check_zip_code (text):
  result = re.search(r"\w+\d{5}-?(\d{4})?", text)
  return result != None

print(check_zip_code("The zip codes for New York are 10001 thru 11104.")) # True
print(check_zip_code("90210 is a TV show")) # False
print(check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.")) # True
print(check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.")) # False

Body:
You could use

(?!\A)\b\d{5}(?:-\d{4})?\b

Full code:

import re

def check_zip_code (text):
    m = re.search(r'(?!\A)\b\d{5}(?:-\d{4})?\b', text)
    return True if m else False

print(check_zip_code("The zip codes for New York are 10001 thru 11104.")) # True
print(check_zip_code("90210 is a TV show")) # False
print(check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.")) # True
print(check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.")) # False

Meanwhile I found that there's a package called zipcodes which might be of additional help.


问:
multidimensional array merge into one array if key is same without using nested loop
```

    [
      {
        "status": true,
        "data": [
          {
            "id": 2,
            "name": "Algeria",
            "country_code": "DZ",
            "regions": [
              {
                "id": 2,
                "country_id": 2,
                "region_code": "RG01",
                "depots": [
                  {
                    "id": 5,
                    "region_id": 2,
                    "depot_code": "DP04",
                    "depot_name": "North Depot",
                    "area": [
                      {
                        "id": 1,
                        "depot_id": 5,
                        "area_code": "AR1",
                        "area_name": "Area-1"
                      },
                      {
                        "id": 2,
                        "depot_id": 5,
                        "area_code": "AR2",
                        "area_name": "Area-2"
                      }
                    ]
                  },
                  {
                    "id": 6,
                    "region_id": 2,
                    "depot_code": "DP06",
                    "depot_name": "east Depot",
                    "area": [
                      {
                        "id": 3,
                        "depot_id": 6,
                        "area_code": "AR3",
                        "area_name": "Area-3"
                      }
                    ]
                  }
                ]
              },
              {
                "id": 3,
                "country_id": 2,
                "region_code": "RG02",
                "depots": []
              }
            ]
          }
        ]
      }
    ]

 ```

i want to merge area into single array like

```

    "area": [
      {
        "id": 1,
        "depot_id": 5,
        "area_code": "AR1",
        "area_name": "Area-1"
      },
      {
        "id": 2,
        "depot_id": 5,
        "area_code": "AR2",
        "area_name": "Area-2"
      },
      {
        "id": 3,
        "depot_id": 6,
        "area_code": "AR3",
        "area_name": "Area-3"
      }
    ]

 ```

i don't want to use multiple foreach.
thanks in advance.

答:
You can use the following code to recursively iterate of all your structure and extract only data you need (by key). I assume $data has your original data structure and within $result you will get array of area:</p>

```<code>$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data), RecursiveIteratorIterator::SELF_FIRST);

$result = [];
foreach ($it as $k => $v) {
    if ($k === 'area') {
        $result = array_merge($result, $v);
    }
}
</code>```

Body:
    [
      {
        "status": true,
        "data": [
          {
            "id": 2,
            "name": "Algeria",
            "country_code": "DZ",
            "regions": [
              {
                "id": 2,
                "country_id": 2,
                "region_code": "RG01",
                "depots": [
                  {
                    "id": 5,
                    "region_id": 2,
                    "depot_code": "DP04",
                    "depot_name": "North Depot",
                    "area": [
                      {
                        "id": 1,
                        "depot_id": 5,
                        "area_code": "AR1",
                        "area_name": "Area-1"
                      },
                      {
                        "id": 2,
                        "depot_id": 5,
                        "area_code": "AR2",
                        "area_name": "Area-2"
                      }
                    ]
                  },
                  {
                    "id": 6,
                    "region_id": 2,
                    "depot_code": "DP06",
                    "depot_name": "east Depot",
                    "area": [
                      {
                        "id": 3,
                        "depot_id": 6,
                        "area_code": "AR3",
                        "area_name": "Area-3"
                      }
                    ]
                  }
                ]
              },
              {
                "id": 3,
                "country_id": 2,
                "region_code": "RG02",
                "depots": []
              }
            ]
          }
        ]
      }
    ]

i want to merge area into single array like

    "area": [
      {
        "id": 1,
        "depot_id": 5,
        "area_code": "AR1",
        "area_name": "Area-1"
      },
      {
        "id": 2,
        "depot_id": 5,
        "area_code": "AR2",
        "area_name": "Area-2"
      },
      {
        "id": 3,
        "depot_id": 6,
        "area_code": "AR3",
        "area_name": "Area-3"
      }
    ]

i don't want to use multiple foreach.
thanks in advance.

Body:
You can use the following code to recursively iterate of all your structure and extract only data you need (by key). I assume $data has your original data structure and within $result you will get array of area:

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data), RecursiveIteratorIterator::SELF_FIRST);

$result = [];
foreach ($it as $k => $v) {
    if ($k === 'area') {
        $result = array_merge($result, $v);
    }
}


问:
Javascript push and loop
I currently have this array: var arr = []
How do I push multiple "hello" strings into the array using a for loop?
I tried</p>

```<code>var newArray = arr.push("hello")10;
</code>```

答:
try new Array forEach or simple for-loop should work.

var arr = [];

// method 1
new Array(5).fill(0).forEach(() => arr.push("hello"));

// alternate method
for (let i = 0; i < 5; i++) {
  arr.push("world");
}

console.log(arr);

// Updating based on suggesion @mplungjan, quick way without loop.
var arr2 = Array(10).fill("hello");
console.log(arr2)```

Title: Javascript push and loop

Body:
I currently have this array: var arr = []
How do I push multiple "hello" strings into the array using a for loop?
I tried

var newArray = arr.push("hello")10;


问:
Is there a String.Remove() equivalent for Java?
Is there a C#'s String.Remove() equivalent for Java?

I never had any problems with doing string.Remove(text.Length, text.Length) and I would know if there were the same equivalent to this in Java.

Example:

```<code>string text = "abcdef";
text = text.Remove(text.Length / 2, text.Length / 2); // becomes abc
</code>```

答:
Such a function is not part of the String class and I'm not aware of any other utility classes that provide this.

But you can always write your own version of it:

```<code>public static String remove(String str, int startIndex, int count) {
    return str.substring(0, startIndex) + str.substring(startIndex + count);
}
</code>```

Or if you want to use the single parameter overload of the String.Remove (which seems to suffice in your example), it's even easier:

```<code>str.substring(0, startIndex);
</code>```

Body:
Is there a C#'s String.Remove() equivalent for Java?

I never had any problems with doing string.Remove(text.Length, text.Length) and I would know if there were the same equivalent to this in Java.

Example:

string text = "abcdef";
text = text.Remove(text.Length / 2, text.Length / 2); // becomes abc

Body:
Such a function is not part of the String class and I'm not aware of any other utility classes that provide this.

But you can always write your own version of it:

public static String remove(String str, int startIndex, int count) {
    return str.substring(0, startIndex) + str.substring(startIndex + count);
}

Or if you want to use the single parameter overload of the String.Remove (which seems to suffice in your example), it's even easier:

str.substring(0, startIndex);


问:
R: How do I generate a sequence of dates to populate all rows within a column?
I want to generate the following sequence on Lubridate

seq(ymd('2017-03-12'),ymd('2020-02-23'), by = '1 week')

and store the weeks generated as a column in an existing data.frame of 102 rows.

When I try to use dataframe["newcolumnname] <- seq(ymd('2017-03-12'),ymd('2020-02-23'), by = '1 week')

It throws an error: Error in [<-.data.frame(* tmp *, "Year", value = c(17237, 17244, 17251,  :
  replacement has 155 rows, data has 102

What's the most efficient way to generate a sequence of dates in a column in R?

答:
dates <- seq(from=as.Date("2017-03-12"), to=as.Date("2020-02-23"), by = "weeks") works fine. I think your problem is the length of the dataframe you're trying to fit the data in (as stated in the error).

EDIT: knowing that the goal is to have the dataframe fit the new column size, here's my suggestion:
Using the method cbind.fill() from the package rowr

cbind.fill(a,b, fill = NA)
```

Will fill the shortest of the two elements with NA's

BTW, I would definitely recommand checking out the xts package to play around with timeseries in R.

Body:
dates <- seq(from=as.Date("2017-03-12"), to=as.Date("2020-02-23"), by = "weeks") works fine. I think your problem is the length of the dataframe you're trying to fit the data in (as stated in the error).

EDIT: knowing that the goal is to have the dataframe fit the new column size, here's my suggestion:
Using the method cbind.fill() from the package rowr

cbind.fill(a,b, fill = NA)

Will fill the shortest of the two elements with NA's

BTW, I would definitely recommand checking out the xts package to play around with timeseries in R.


答:
Not sure why everyone is suggesting ways to parse tab delimited files. Use unpack(). I used to do this by manually parsing files and writing functions to extract the data-—what a waste of time. I found this article that explained how to do it in a clean self-documenting way.

$records[] = unpack('A40Address 1/A40Address 2/A25City/A2State/A10Zip Code',$row);

Title: PHP - Parse text file with fixed column width

Body:
I'm new to PHP and Laravel and I need to open the file and parse the contents to pass them to the database. The text file has fixed column width. It doesn't have delimiters or headers. I think using substrings and assigning each of them to a variable would be the correct approach, but I'm still in the process of learning the language and I have no idea how to implement this.

Here is an example of the data that is inside the text file:

1618 0002 9                    1261    4141191269    4141191269       4      002     0

1606 0000 9                    1159    4169191388    4169191388       4      012     0

1607 0009 7    9  505   04129284134          1245          1245 56984 4

1619 0000 9    6               1172    2129922686    2129922686       4      013     0

1606 0000 9                    1159    4169191388    4169191388       4      012     0

1607 0009 7    9  505   04129284134          1245          1245 56984 4

1619 0000 7    6  521         1188#          1172          1172       0          001 4

1606 0000 9                    1159    4169191388    4169191388       4      012     0

1607 0009 7    9  505   04129284134          1245          1245 56984 4

1619 0000 9    6               1252    2129922686    2129922686       4      003     0

1606 0000 9                    1159    4169191388    4169191388       4      012     0

1607 0009 7    9  505   04129284134          1245          1245 56984 4

1619 0000 7    6  521         1188#          1252          1252       1          002 4

EDIT:

Column names:

id
time
duration
cond_code
code_dial
code_used
dialed_num
calling_num
clg_num_in_tac
auth_code
frl
ixc_code
in_crt_id
out_crt_id


问:
React to-do list: tag form is updating the wrong to-do (problem with useState scope)
Building a react to-do list and I have a very specific bug I need some help with. I added functionality to add tags to each to-do. It works great on the last to-do in the list, but if I try to type in the input of any to-do higher up the list, it's updating the value in the input field of the last to-do. Here's the sandbox link so you can see what I'm talking about: https://codesandbox.io/s/trusting-architecture-xjkbf?file=/src/App.js

My code is below. I know the problem is with declaring [tag, setTag] = useState outside the scope of where I'm calling setTag. I just can't figure out where I need to put it so it works. (I copied all the code but I'm fairly certain the problem is local to the Task component)

```<code>import React, { useState } from "react";
import "./styles.css";
import todoBlack from "./icons/todoBlack.png";

function TodoForm(props) {
  [val, setVal] = useState("");

  const handleSubmit = e => {
    e.preventDefault();
    if (val) {
      props.addTask(val);
      setVal("");
    }
  };

  return (
    <div className="row">
      <div className="col-2" />
      <div className="col-8">
        <form className="py-1" onSubmit={handleSubmit}>
          <input
            placeholder="New Item"
            className="w-100 p-2 border"
            type="text"
            value={val}
            onChange={e => setVal(e.target.value)}
          />
        </form>
      </div>
    </div>
  );
}

function Task(props) {
  [tag, setTag] = useState("");

  const handleSubmit = e => {
    e.preventDefault();
    if (tag) {
      props.addTag(props.index, tag);
      setTag("");
    }
  };

  return (
    <div
      className={props.task.isComplete ? "complete-task" : "incomplete-task"}
    >
      <li className="row w-100 py-2 mx-0 px-0 border-bottom">
        <div className="text-left col-2 todo-button">
          <button onClick={() => props.completeTask(props.index)}>
            <img src={todoBlack} height="25" alt="todo" />
          </button>
        </div>
        <div className="text-left col-4 my-auto">
          <p className="my-1">{props.task.text}</p>
        </div>
        <div className="text-left col-4 my-auto">
          <div>
            {props.task.tags
              ? props.task.tags.map((tag, index) => (
                  <p
                    className="mx-1"
                    key={index}
                    index={index}
                    style={{ display: "inline" }}
                  >
                    {tag}
                    <button onClick={() => props.removeTag(props.index, index)}>
                      x
                    </button>
                  </p>
                ))
              : ""}
          </div>
          <form onSubmit={handleSubmit}>
            <input
              className="w-50"
              placeholder="Add Tag"
              type="text"
              value={tag}
              onChange={e => setTag(e.target.value)}
            />
          </form>
        </div>
        <div className="text-right col-2">
          <button type="button" onClick={() => props.removeTask(props.index)} />
        </div>
      </li>
    </div>
  );
}

export default function App() {
  [tasks, setTasks] = useState([]);
  [globalTags, setglobalTags] = useState([]);

  const addTask = text => {
    const newTasks = [...tasks, { text }];
    setTasks(newTasks);
  };

  const removeTask = index => {
    const newTasks = [...tasks];
    newTasks.splice(index, 1);
    setTasks(newTasks);
  };

  const completeTask = index => {
    const newTasks = [...tasks];
    if (!newTasks[index].isComplete) {
      newTasks[index].isComplete = true;
    } else {
      newTasks[index].isComplete = false;
    }
    setTasks(newTasks);
  };

  const addTag = (index, text) => {
    const newTasks = [...tasks];
    if (newTasks[index].tags) {
      newTasks[index].tags.push(text);
    } else {
      newTasks[index].tags = [];
      newTasks[index].tags.push(text);
    }
    setTasks(newTasks);
  };

  const removeTag = (index, tagIndex) => {
    const newTasks = [...tasks];
    newTasks[index].tags.splice(tagIndex, 1);
    setTasks(newTasks);
  };

  const taskList = tasks.map((task, index) => (
    <Task
      key={index}
      index={index}
      task={task}
      completeTask={completeTask}
      isComplete={task.isComplete}
      removeTask={removeTask}
      addTag={addTag}
      removeTag={removeTag}
    />
  ));

  return (
    <div className="App">
      <TodoForm addTask={addTask} />
      <ul className="container-fluid">{taskList}</ul>
    </div>
  );
}
</code>```

答:
Its the way you are adding the ref in your example. There is not concept of this in a functional component. You need to use useRef. this was hoisting outside the function so it was always applied to the last one, which is why it worked for the last one, but not the the other ones

https://codesandbox.io/s/strange-kowalevski-qyj4s

Body:
Building a react to-do list and I have a very specific bug I need some help with. I added functionality to add tags to each to-do. It works great on the last to-do in the list, but if I try to type in the input of any to-do higher up the list, it's updating the value in the input field of the last to-do. Here's the sandbox link so you can see what I'm talking about: https://codesandbox.io/s/trusting-architecture-xjkbf?file=/src/App.js

My code is below. I know the problem is with declaring [tag, setTag] = useState outside the scope of where I'm calling setTag. I just can't figure out where I need to put it so it works. (I copied all the code but I'm fairly certain the problem is local to the Task component)

import React, { useState } from "react";
import "./styles.css";
import todoBlack from "./icons/todoBlack.png";

function TodoForm(props) {
  [val, setVal] = useState("");

  const handleSubmit = e => {
    e.preventDefault();
    if (val) {
      props.addTask(val);
      setVal("");
    }
  };

  return (

        <form className="py-1" onSubmit={handleSubmit}>
          <input
            placeholder="New Item"
            className="w-100 p-2 border"
            type="text"
            value={val}
            onChange={e => setVal(e.target.value)}
          />
        </form>

  );
}

function Task(props) {
  [tag, setTag] = useState("");

  const handleSubmit = e => {
    e.preventDefault();
    if (tag) {
      props.addTag(props.index, tag);
      setTag("");
    }
  };

  return (

          <button onClick={() => props.completeTask(props.index)}>

          </button>

{props.task.text}

            {props.task.tags
              ? props.task.tags.map((tag, index) => (

                    {tag}
                    <button onClick={() => props.removeTag(props.index, index)}>
                      x
                    </button>

                ))
              : ""}

          <form onSubmit={handleSubmit}>
            <input
              className="w-50"
              placeholder="Add Tag"
              type="text"
              value={tag}
              onChange={e => setTag(e.target.value)}
            />
          </form>

          <button type="button" onClick={() => props.removeTask(props.index)} />

  );
}

export default function App() {
  [tasks, setTasks] = useState([]);
  [globalTags, setglobalTags] = useState([]);

  const addTask = text => {
    const newTasks = [...tasks, { text }];
    setTasks(newTasks);
  };

  const removeTask = index => {
    const newTasks = [...tasks];
    newTasks.splice(index, 1);
    setTasks(newTasks);
  };

  const completeTask = index => {
    const newTasks = [...tasks];
    if (!newTasks[index].isComplete) {
      newTasks[index].isComplete = true;
    } else {
      newTasks[index].isComplete = false;
    }
    setTasks(newTasks);
  };

  const addTag = (index, text) => {
    const newTasks = [...tasks];
    if (newTasks[index].tags) {
      newTasks[index].tags.push(text);
    } else {
      newTasks[index].tags = [];
      newTasks[index].tags.push(text);
    }
    setTasks(newTasks);
  };

  const removeTag = (index, tagIndex) => {
    const newTasks = [...tasks];
    newTasks[index].tags.splice(tagIndex, 1);
    setTasks(newTasks);
  };

  const taskList = tasks.map((task, index) => (
    <Task
      key={index}
      index={index}
      task={task}
      completeTask={completeTask}
      isComplete={task.isComplete}
      removeTask={removeTask}
      addTag={addTag}
      removeTag={removeTag}
    />
  ));

  return (

      <TodoForm addTask={addTask} />

{taskList}

  );
}


答:
```<code>import re

def check_zip_code (text):
    return bool(re.search(r" (\b\d{5}(?!-)\b)| (\b\d{5}-\d{4}\b)", text))

assert check_zip_code("The zip codes for New York are 10001 thru 11104.") is True
assert check_zip_code("90210 is a TV show") is False
assert check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.") is True
assert check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.") is False

assert check_zip_code("x\n90201") is False
assert check_zip_code("the zip somewhere is 98230-0000") is True
assert check_zip_code("the zip somewhere else is not 98230-00000000") is False

</code>```

Title: How to find a US zip code in a string using regular expression?


问:
Office Add-in how to see console.log
I used Visual Studio to create an office project,

I try to see were is written the console.log text.

Looking around stackoverflow and internet I tried to attach debugger to my project or any other things related in so many posts, but nothing works.

In the code provided by the Office Add in template, there is a banner to show the error directly in the taskpane. But there is also a console.log to show in the console ? Well... I can't see where this texte is written.

In the image below, on "1" they catch the error, on "2" they show the error on the banner in html, and in "3" they show the console.log error ...

As you can see, my taskpane well display the error banner, so logically, the console.log is displayed somewhere.

Below images of the different consoles and terminals that can be the most logical to show error, but still nothing

In all the other tabs there is nothing, and I tried ctrl+Q to activate Javascript console or whatever that could be useful for debugging.

答:
The JavaScript console was removed from Visual Studio 2019. You have basically 2 options:

Install Visual Studio 2017 side-by-side Visual 2019 (or install Visual 2017 on another computer) and use VS 2017 to develop Office Add-ins.

Use the Dev Tools of the browser that the add-in is using to run. For which browser your add-in is using, see Browsers used by Office Web Add-ins.

Title: Office Add-in how to see console.log


问:
Typecast between anonymous structs with field tags
I had an Open API generated schema, and I would like to create the response struct in my handler function. But when I want to create the anonymous struct, I need to write again the field tags, too. Is there any solution for not needing to repeat that? Here is the minimal example

package main

// Response is generated by a tool in a separated file
type Response struct {
    Result *struct {
        Id int `json:"id"`
    } `json:"result,omitempty"`
}

func main() {
    var response Response

    response.Result = &struct {
        Id int `json:"id"`
    }{5}

    // This results in an error
    // cannot use &struct { Id int } literal (type *struct { Id int }) as type *struct { Id int "json:\"id\"" } in assignment
    response.Result = &struct {Id int}{5}
}
```

<p>This anonymous struct is a result of oapi-codegen, when I use a complex type in the <code>components</code> part of the api definition as a response type. I think if I use a <code>CreateBookResponseResult</code> type, the code generator won't generate an anonymous struct, but I would postpone this option until I can.</p>

<pre class="lang-yaml prettyprint-override"><code>components:
  CreateBookResponse:
    type: object
    properties:
      result:
        type: object
        properties:
          id:
            type: integer
</code>```

答:
Use a named type.</p>

```<code>type Response struct {
    Result *ResponseResult `json:"result,omitempty"`
}

type ResponseResult struct {
        Id int `json:"id"`
}

var response Response
response.Result = &ResponseResult{Id: 5}
</code>```

Body:
I had an Open API generated schema, and I would like to create the response struct in my handler function. But when I want to create the anonymous struct, I need to write again the field tags, too. Is there any solution for not needing to repeat that? Here is the minimal example

package main

// Response is generated by a tool in a separated file
type Response struct {
    Result *struct {
        Id int `json:"id"`
    } `json:"result,omitempty"`
}

func main() {
    var response Response

    response.Result = &struct {
        Id int `json:"id"`
    }{5}

    // This results in an error
    // cannot use &struct { Id int } literal (type *struct { Id int }) as type *struct { Id int "json:\"id\"" } in assignment
    response.Result = &struct {Id int}{5}
}

This anonymous struct is a result of oapi-codegen, when I use a complex type in the components part of the api definition as a response type. I think if I use a CreateBookResponseResult type, the code generator won't generate an anonymous struct, but I would postpone this option until I can.

components:
  CreateBookResponse:
    type: object
    properties:
      result:
        type: object
        properties:
          id:
            type: integer

Body:
Use a named type.

type Response struct {
    Result *ResponseResult `json:"result,omitempty"`
}

type ResponseResult struct {
        Id int `json:"id"`
}

var response Response
response.Result = &ResponseResult{Id: 5}


问:
Adjustable row heights with bootstrap 4
I'm using bootstrap columns to display expanding cards.  When one expands though, it pushes the whole row underneath it down.

Unexpanded:

Currently how it behaves expanded:

How I'd like it to behave:

I've been reading about flexbox, but I cant find any good examples of the desired behavior, while maintaining responsive design.

Currently the code is along the lines of

```<code><div class="row">
    <div class="col-xl-4 col-lg-5 col-12">
        expanding content...
    </div>
    .
    .
    .
    <div class="col-xl-4 col-lg-5 col-12">
        expanding content...
    </div>
</div>
</code>```

答: Maybe you could try giving it a css height: property. This can be done through Javascript, so when you're expanding the box, also give it a certain height to limit it. Tell me if you'd like me to do it for you :)

Title: Adjustable row heights with bootstrap 4

Body:
I'm using bootstrap columns to display expanding cards.  When one expands though, it pushes the whole row underneath it down.

Unexpanded:

Currently how it behaves expanded:

How I'd like it to behave:

I've been reading about flexbox, but I cant find any good examples of the desired behavior, while maintaining responsive design.

Currently the code is along the lines of

        expanding content...

    .
    .
    .

        expanding content...


问:
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
I am studying spring boot and spring jpa .
I was able to successfully read and write into the database, but the problem occurs while updating the data.

```<code>There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
</code>```

I am trying to update data of table : Person ( Id, Name , Age) using a html form. It accepts the data, and using spring jpa  I am trying to update it in MySQL database.

I am getting the following at console when trying to update the data, after submitting the form

```<code>> WARN 5176 --- [nio-8080-exec-1]
> .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
> [org.springframework.web.HttpRequestMethodNotSupportedException:
> Request method 'GET' not supported]
</code>```

My code is here :
updateperson form :

```<code> <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h1>Enter new details</h1>
    <form action="updatePerson" method="post">
        Id   : <input type="number" name="id"><br>
        Name :<input type = "text" name = "name"><br>
        Age : <input type = "number" name = "age"><br>
        <input type="submit">
    </form>
    </body>
    </html>
</code>```

PersonRepository.java

```<code>package com.example.demo.repository;

import com.example.demo.model.Person;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PersonRepository extends CrudRepository<Person , Integer> {
    List<Person> findByName(String name);
    List<Person> findByAge(int age);
    List<Person> findAll();
}
</code>```

PersonController.java

```<code>    package com.example.demo.controller;

import com.example.demo.model.Person;
import com.example.demo.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class PersonController {
    @Autowired
    PersonRepository personRepository;

    @GetMapping("update")
    public String updatePerson(){
        System.out.println("update to updateperson html");
        return "updateperson";
    }
    @PutMapping("/updatePerson")
    public String updatePerson(Person person){
        System.out.println("UPDATING TO" + person.getAge()+" : "+person.getName() + " : "+person.getPid());
        personRepository.save(person);
        return "updateperson";
    }

}
</code>```

Person.java

```<code>package com.example.demo.model;

import org.springframework.stereotype.Component;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {
    @Id
    @GeneratedValue
    int pid;

    String name;
    int age;

     public Person() {
    }

    public Person(int pid, String name, int age) {
        this.pid = pid;
        this.name = name;
        this.age = age;
    }

//getter and setters
}
</code>```

The URL to which I'm sending the request:

```<code>localhost:8080/updatePerson?id=4&name=personame&age=34
</code>```

答:
have a better look on your endpoints:

```<code>@GetMapping("update")
public String updatePerson(){
    System.out.println("update to updateperson html");
    return "updateperson";
}
@PutMapping("/updatePerson")
public String updatePerson(Person person){
    System.out.println("UPDATING TO" + person.getAge()+" : "+person.getName() + " : "+person.getPid());
    personRepository.save(person);
    return "updateperson";
}
</code>```

your GET and PUT methods have different paths and you try to access GET method with Put path as you said in the comment.

What you can do to fix it:

change GET path to @GetMapping("updatePerson")

call your GET path by this URL: localhost:8080/update not localhost:8080/updatePerson

Body:
I am studying spring boot and spring jpa .
I was able to successfully read and write into the database, but the problem occurs while updating the data.

There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

I am trying to update data of table : Person ( Id, Name , Age) using a html form. It accepts the data, and using spring jpa  I am trying to update it in MySQL database.

I am getting the following at console when trying to update the data, after submitting the form

> WARN 5176 --- [nio-8080-exec-1]
> .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
> [org.springframework.web.HttpRequestMethodNotSupportedException:
> Request method 'GET' not supported]

My code is here :
updateperson form :

 <!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Title</title>

Enter new details

    <form action="updatePerson" method="post">
        Id   : <input type="number" name="id">

        Name :<input type = "text" name = "name">

        Age : <input type = "number" name = "age">

        <input type="submit">
    </form>

PersonRepository.java

package com.example.demo.repository;

import com.example.demo.model.Person;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PersonRepository extends CrudRepository<Person , Integer> {
    List<Person> findByName(String name);
    List<Person> findByAge(int age);
    List<Person> findAll();
}

PersonController.java

    package com.example.demo.controller;

import com.example.demo.model.Person;
import com.example.demo.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class PersonController {
    @Autowired
    PersonRepository personRepository;

    @GetMapping("update")
    public String updatePerson(){
        System.out.println("update to updateperson html");
        return "updateperson";
    }
    @PutMapping("/updatePerson")
    public String updatePerson(Person person){
        System.out.println("UPDATING TO" + person.getAge()+" : "+person.getName() + " : "+person.getPid());
        personRepository.save(person);
        return "updateperson";
    }

}

Person.java

package com.example.demo.model;

import org.springframework.stereotype.Component;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {
    @Id
    @GeneratedValue
    int pid;

    String name;
    int age;

     public Person() {
    }

    public Person(int pid, String name, int age) {
        this.pid = pid;
        this.name = name;
        this.age = age;
    }

//getter and setters
}

The URL to which I'm sending the request:

localhost:8080/updatePerson?id=4&name=personame&age=34

Body:
have a better look on your endpoints:

@GetMapping("update")
public String updatePerson(){
    System.out.println("update to updateperson html");
    return "updateperson";
}
@PutMapping("/updatePerson")
public String updatePerson(Person person){
    System.out.println("UPDATING TO" + person.getAge()+" : "+person.getName() + " : "+person.getPid());
    personRepository.save(person);
    return "updateperson";
}

your GET and PUT methods have different paths and you try to access GET method with Put path as you said in the comment.

What you can do to fix it:

change GET path to @GetMapping("updatePerson")

call your GET path by this URL: localhost:8080/update not localhost:8080/updatePerson


问:
Why is the branch tip behind its remote?
Despite pulling from the remote master and being told everything is up to date, I can't push to the remote master because the current branch is behind the tip of the remote. What?</p>

```<code>$ git pull origin master
From https://github.com
 * branch            master     -> FETCH_HEAD
Already up-to-date.
$ git push origin master
To https://github.com
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

答:
You ARE probable on a different branch.   You probable should back up your changes.   Since folks are losing their changes,  they need to always save to local repository, then save from the local repo to the remote repository.  Merges are done from inside the target branch, which requires you to have saved your work to your source dev branch before merging with master..   Here are the steps.

is a git command
[ is something you need to change ]

First know what branch you are on..

git branch

will tell you what branch you are on.

Then you need to check your code into your Dev branch so you don't lose it.

git status

list the files that have changed

git add [path filename]

add all the files which have changed just copy the path and file names from the status command you want to add.

git commit -m ["comment"]

inserts your files to your local repository with a comment saying what you changed.  The files inserted will the ones you added.

git push origin [branch]

push your local changes from your local repository to remote repository for your dev branch.

Now your local and remote repositories are all in order....   If you want to update Master branch,  You can safely check out that branch and merge from inside of master.   If you are doing pull requests you'll probable want to create a new branch from master and merge with that.   Then do the pull request on that new branch.

But if you aren't using pull requests and want to update master directly to your dev branch.  First you check out master.

git checkout master

This will delete your local code but you have saved it both locally and to the remote server.. so you're good.

git merge [dev branch]

This will merge your dev code into master.   If there are any conflicts then open the file which conflicted and search for the '>>>' string to see where the conflict is.   resolve the conflict by correcting the code.   Then check your changes in locally and then from the local repository to the remote repository.

git status

See what changed

git add master

Add the modified files into the update

git commit -m "[comment what changed]"

update the local repository

git push origin [branch]

update the remote repository.. branch will be  master here unlesss you are synking to a new branch in order to do pull request on it.

Body:
Despite pulling from the remote master and being told everything is up to date, I can't push to the remote master because the current branch is behind the tip of the remote. What?

$ git pull origin master
From https://github.com
 * branch            master     -> FETCH_HEAD
Already up-to-date.
$ git push origin master
To https://github.com
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.


问:
Type 'HTML Collection' must have a '[Symbol.iterator]()' method that returns an iterator in a directive
I have a map in the directive that shows me the error code TS2488 Type 'HTML Collection' must have a '[Symbol.iterator]()' method that returns an iterator .

My map:

```<code>map(
  ([headRow, bodyRows]: [HTMLTableRowElement, HTMLCollectionOf<HTMLTableRowElement>]) => [
    [...headRow.children].map(headerCell => headerCell.textContent), // First issue
    [...bodyRows].map(row => [...row.children]) // Second issue
  ]
),
</code>```

How do I best deal with this problem? Got any advice for me?

答:
HTMLCollection is not iterable but you can get it to ignore that by using "any" on your HTML Elements.</p>

```<code>          ([headRow, bodyRows]: [
            HTMLTableRowElement,
            HTMLCollectionOf<HTMLTableRowElement>
          ]) => [
            [...(<any>headRow.children)].map(
              (headerCell) => headerCell.textContent
            ),
            [...(<any>bodyRows)].map((row) => [...row.children])```
</code>```

Body:
I have a map in the directive that shows me the error code TS2488 Type 'HTML Collection' must have a '[Symbol.iterator]()' method that returns an iterator .

My map:

map(
  ([headRow, bodyRows]: [HTMLTableRowElement, HTMLCollectionOf<HTMLTableRowElement>]) => [
    [...headRow.children].map(headerCell => headerCell.textContent), // First issue
    [...bodyRows].map(row => [...row.children]) // Second issue
  ]
),

How do I best deal with this problem? Got any advice for me?

Body:
HTMLCollection is not iterable but you can get it to ignore that by using "any" on your HTML Elements.

          ([headRow, bodyRows]: [
            HTMLTableRowElement,
            HTMLCollectionOf<HTMLTableRowElement>
          ]) => [
            [...(<any>headRow.children)].map(
              (headerCell) => headerCell.textContent
            ),
            [...(<any>bodyRows)].map((row) => [...row.children])```


问:
What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?
I was trying to change my default/main/startup (whatever you call it) activity by editing the androidmanifest.xml file. All i did was change the android:name property. however, this completely broke the entire app. when I try to install it fails and reads.

Installation error: INSTALL_PARSE_FAILED_NO_CERTIFICATES

When I tried to change it back to its previous state, it was still giving me the same error... What have I done?

答:
Recently I had this error while upgrading to Android Studio 4.0. The cause was that the project had V2 Signing Disabled in the signing configuration in build.gradle.

The solution was to remove v2SigningEnabled false or explicitly set it to true, which is the default value.

```<code>android {
    signingConfigs {
        dev {
            v2SigningEnabled true
        }
     }
}
</code>```

Body:
Recently I had this error while upgrading to Android Studio 4.0. The cause was that the project had V2 Signing Disabled in the signing configuration in build.gradle.

The solution was to remove v2SigningEnabled false or explicitly set it to true, which is the default value.

android {
    signingConfigs {
        dev {
            v2SigningEnabled true
        }
     }
}


问:
How can I set separate splash screens for landscape and portrait mode in Android?
I'm working on an Android application where I need to set separate splash screens, one for portrait and one for landscape orientation. Both are different images. How can I do it?

activity_splash.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/wwe_logo" />

</RelativeLayout>
</code>```

SplashScreen.java

```<code>public class SplashScreen extends Activity {

    // Splash screen timer
    private static int SPLASH_TIME_OUT = 3000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, SPLASH_TIME_OUT);
    }

}
</code>```

答:
Follow these steps.

Create folder layout-land under res folder the same as the layout folder.

Next copy the activity_splash.xml file and paste in new folder layout-land. (This activity_splash is an XML file of SplashActivity java class)

Then change the portrait splash image to your landscape splash image.
No need to change the java code in SplashActivity java class additionally also Manifest file.

Body:
I'm working on an Android application where I need to set separate splash screens, one for portrait and one for landscape orientation. Both are different images. How can I do it?

activity_splash.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/wwe_logo" />

</RelativeLayout>

SplashScreen.java

public class SplashScreen extends Activity {

    // Splash screen timer
    private static int SPLASH_TIME_OUT = 3000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, SPLASH_TIME_OUT);
    }

}


问:
window.setInterval - is it possible to have more than one? how?
I have created a slideshow widget, using jQuery.UI widgets that works with window.setInterval.
I am trying to have more than one slideshow in the same page and i get the following results:

If I try invoking the same widget for both of my divs with images:

```<code>$('#div1').slideshow();
$('#div2').slideshow();
</code>```

none of them work;

I have cloned the definition of my widget and named it slideshowsmall

```<code>$('#div1').slideshow();
$('#div2').slideshowsmall();
</code>```

and only the second one works.

my widget code is in this pastebin, but i really think the problem, at least in the second try, has to do with setInterval

Thanks

答:
Having multiple setInterval() by itself cannot be causing problems. It is more likely to have something to do with the code it's executing (and your widget code being non-english makes it very hard to analize and comprehend).

setInterval() returns and integer ID of the "interval", so that you can later clearInterval(...) by passing this ID. This scenario was implemented exactly for multi-interval uses. More details on MDC

Body:
I have created a slideshow widget, using jQuery.UI widgets that works with window.setInterval.
I am trying to have more than one slideshow in the same page and i get the following results:

If I try invoking the same widget for both of my divs with images:

$('#div1').slideshow();
$('#div2').slideshow();

none of them work;

I have cloned the definition of my widget and named it slideshowsmall

$('#div1').slideshow();
$('#div2').slideshowsmall();

and only the second one works.

my widget code is in this pastebin, but i really think the problem, at least in the second try, has to do with setInterval

Thanks


问:
Navigation drawer title according to the Drawer item
I have used getSupportActionBar().setTitle("drawer_title"); and the title changes according to drawer item. But when I go back the title does not get updated. for eg: If I'm at dashboard-fragment toolbar-title is dashboard and after that when I go to message-fragment toolbar-title changes to message, but, after when I press back button it goes back to dashboard-fragment but the title does not updated to dashboard it remains message.

How could I update the title again??

答: Use getSupportActionBar().setTitle("drawer_title"); inside onResume() method of your fragment.


问:
How to avoid multiple service's instance in an Angular library? (with lazy loaded modules)
I have a Very Big project in angular and i'm migrating the Core to a library. The problem comes when my services (in the library) was exported with:

```<code>public static forRoot(): ModuleWithProviders {
    return {
      ngModule: NbopflModule,
      providers: [
        ...ALL_PIPES,
        ...ALL_SERVICES
      ]
    };
  }
</code>```

And the services (All of them) has:

```<code>@Injectable({
  providedIn: 'root'
})
</code>```

I load the library (forRoot) in appModule.
And i load the same library in the lacy load modules (some like a library lacy loaded, and some are inside the project)

I add a console.log in the constructor, and in every module loaded apear the message, generating multiple instances. I dont want to refactor all the code making all the variabe statics.

Anyone Knows about any way to force a single instance of a service imported by a library?

Thanks a lot

答:
I get the solution :S:S

Its just removing all the declarations in the providers (not in forRoot, not in the module providers....) just with the provideIn: 'root', and being exported in the public-api file, works :)

Body:
I have a Very Big project in angular and i'm migrating the Core to a library. The problem comes when my services (in the library) was exported with:

public static forRoot(): ModuleWithProviders {
    return {
      ngModule: NbopflModule,
      providers: [
        ...ALL_PIPES,
        ...ALL_SERVICES
      ]
    };
  }

And the services (All of them) has:

@Injectable({
  providedIn: 'root'
})

I load the library (forRoot) in appModule.
And i load the same library in the lacy load modules (some like a library lacy loaded, and some are inside the project)

I add a console.log in the constructor, and in every module loaded apear the message, generating multiple instances. I dont want to refactor all the code making all the variabe statics.

Anyone Knows about any way to force a single instance of a service imported by a library?

Thanks a lot


问:
how do I manage source code using SVN? branching, merging
We are team of 4 developers/friends located in different locations. We all have started working on the a ProjectX and created branches A, B, C and D using Subversion.

we have just basic knowledge of version controlling the source code. Other day one of us just tried to merge Branch A with B,C, and D and B tried to merge with A, C, and D. (and they didnt even know how to merge it :D, just right click > merge > merge a range of revisions) We got some conflicts, solved them. Tried merging again, again right click .....) Conflicts again.

Now that all of the code has been messed up. we are having 4 different code copies (D missing B's functionality but having C's etc etc). So I went through lots of threads here on SO, read the SVN book and especially this article (how to branch properly) helped a lot in understanding how to merge branches and trunk. I think I have got a better understanding for the future. But how do I get out of current situation??

My questions are:

As 4 of us are working on same project but usually work on different bits, should we just have one branch?? and then create 4 working copies and then commit and update only. Once we are ready merge trunk to branch, branch to trunk? as per suggestion in the above article

Can you please suggest any work-flow so that we can get our 4 branches to the trunk and then I can take an export to start the version controlling from scratch again.

Also I think if go again with 4 branches, should each of us daily/regularly update our branch and get changes from trunk (merge) and merge local changes back to trunk?? (instead of trying mergin branch to branch :-D)

Please suggest what work flow we should use? so that its a minimum pain in maintaining code. Thanks.

答:
The safest strategy is to create a branch for each CR (Change Request / Task / Bug / etc).
The flow would be like this:

A CR is given to a developer through a CMT (Change Management Tool, like Bugzilla);

The CR is analyzed. If it makes sence it is accepted and the developer creates a branch for it. The branch name could be something like:

projectName_crNumber_crCreationDate_developerId

After the work is done (tested, commited, etc), the developer should lock the branch, so no one would change it, mark the CR as resolved (inform branch name at CR), and wait to the CM (Configuration Manager) to merge it to a build branch (along with other development branches);

After a certain number of CRs are merged into a build branch (build_xxx), this integrated version should be tested. If everything is OK it should then be merged to the truck.

A label could be applied each time the trunk achieves a certain goal/milestone (set of CRs).

Lots of details have been omitted. This is a workflow adopted by large teams with high quality standards. It may not be flexible enough to small groups. However, most of this tasks can be automated and scheduled with existing tools.


问:
Xampp - mysql - Cannot create file xampp-control.ini, Access Denied
I use xampp for one month. But xampp yesterday  started making trouble like this
https://imgur.com/avRWXdb. That I uninstall and now install xampp and my sql is running. But now if i want to run xampp and click to xampp icon I always have to choose language: english / german. And if I want to end the program and I stop mysql, I see https://imgur.com/plIpPS4 (* Access Denied) and this: https://imgur.com/a/sEzGKW2 Then I must wain for program answer. I can end xampp. How to repair to normal working again? Thank´s</p>

答:
The issue is with the permissions, just give write access to the file, you will not get error while you try to exit xampp ...
It worked for me ...


问:
HTML Text Input Value not changing in Backend JavaScript
I am new to web development . I have a question I am trying to build a website that takes input on the front end from the HTML page and actively changes the value on the backend javascript file . The functions I have on the backend rely on the front end input . The input never changes it just stays the default value "google.com".  For Reference here is some code of what I am trying to accomplish .

HTML WebPage

```<code><input type="text"  id="input" value="google.com" placeholder="somewebsite.com">
</code>```

Backend JavaScript File

```<code>var ajaxWebSiteValue = document.getElementById("input");

function getURL(){
    var URL = "http://" + ajaxWebSiteValue.value ;
    return URL;
}
</code>```

答:
It not clear what exactly you want to achieve here because heading, description and code snippet looks contradictory to each other.

1.If you are changing the input value on UI but not getting updated value in backend then use

```<code>function getURL(){
     var ajaxWebSiteValue = document.getElementById("input");
     var URL = "http://" + ajaxWebSiteValue.value ;
     return URL;
}
</code>```

2.If you want to change the value of input from backend.

```<code>function getURL(){
     var ajaxWebSiteValue = document.getElementById("input");
     ajaxWebSiteValue.value  = "http://" + ajaxWebSiteValue.value ;
}
</code>```

Also make sure that you are calling getURL() function from somewhere.

Body:
I am new to web development . I have a question I am trying to build a website that takes input on the front end from the HTML page and actively changes the value on the backend javascript file . The functions I have on the backend rely on the front end input . The input never changes it just stays the default value "google.com".  For Reference here is some code of what I am trying to accomplish .

HTML WebPage

<input type="text"  id="input" value="google.com" placeholder="somewebsite.com">

Backend JavaScript File

var ajaxWebSiteValue = document.getElementById("input");

function getURL(){
    var URL = "http://" + ajaxWebSiteValue.value ;
    return URL;
}

Body:
It not clear what exactly you want to achieve here because heading, description and code snippet looks contradictory to each other.

1.If you are changing the input value on UI but not getting updated value in backend then use

function getURL(){
     var ajaxWebSiteValue = document.getElementById("input");
     var URL = "http://" + ajaxWebSiteValue.value ;
     return URL;
}

2.If you want to change the value of input from backend.

function getURL(){
     var ajaxWebSiteValue = document.getElementById("input");
     ajaxWebSiteValue.value  = "http://" + ajaxWebSiteValue.value ;
}

Also make sure that you are calling getURL() function from somewhere.


问:
Can't access Mobx object within object properties
How could I access property that is located inside an object and that object stored in object

The following console log console.log(this.props.auth.user) provides the output below, I am trying to access the role property.

答:
You can use mobx.toJS to convert an observable object to a javascript structure:

An Example:

```<code>const obj = mobx.observable({
    foo: 1,
    bar: 'hello',
  })
const clone = mobx.toJS(obj)
const foo = clone.foo
const bar = clone.bar
</code>```

So, you could do:

```<code>const user = mobx.toJS(this.props.auth.user)
const role = user.role
</code>```

Body:
You can use mobx.toJS to convert an observable object to a javascript structure:

An Example:

const obj = mobx.observable({
    foo: 1,
    bar: 'hello',
  })
const clone = mobx.toJS(obj)
const foo = clone.foo
const bar = clone.bar

So, you could do:

const user = mobx.toJS(this.props.auth.user)
const role = user.role