问:
PARTITION BY row value
I need to partition my output table when a certain row is of a certain value. I have:

```<code>ID|Value|User
-------------
1 |A    |Rick
2 |A    |Rick
3 |B    |Rick
7 |A    |Rick
8 |C    |Rick
4 |A    |Joe
5 |B    |Joe
6 |B    |Joe
</code>```

I need to partition my table for each individual user, and when the value = A, so what I need is:

```<code>Row|ID|Value|User
------------------
1  |1 |A    |Rick
1  |2 |A    |Rick
2  |3 |B    |Rick
1  |7 |A    |Rick
2  |8 |C    |Rick
1  |4 |A    |Joe
2  |5 |B    |Joe
3  |6 |B    |Joe
</code>```

Every value has its own ID.

I've tried things like:

```<code>SELECT ROW_NUMBER() OVER(PARTITION BY User, Value = A ORDER BY ID ASC) AS Row, Value, User FROM...
SELECT ROW_NUMBER() OVER(PARTITION BY User, WHERE Value = A ORDER BY ID ASC) AS Row, Value, User FROM...
etc
</code>```

But I can't seem to figure out how to write it correctly, if it even is possible.

答:
Seems like what you're after is simply a DENSE_RANK:

```<code>DENSE_RANK() OVER (PARTITION BY [User] ORDER BY [Value] ASC) AS [Row]
</code>```

Note USER is a reserved keyword in T-SQL. I strongly recommend you chose a different name for your column, as you must otherwise delimit identify it. ROW and VALUE are not currently reserved, but they are listed as a Future Keyword and their use is also recommended to be avoided.

Edit: Seems, actually that it's 'A' is 1, and then also increment afterwards. This is messy, but you could therefore you could do:

```<code>SELECT CASE [Value]
            WHEN 'A' THEN 1
            ELSE ROW_NUMBER() OVER (PARTITION BY [User] ORDER BY [Value]) -
                 COUNT(CASE [Value] WHEN 'A' THEN 1 END) OVER (PARTITION BY [User]) + 1
       END AS [Row],
       V.[Value],
       V.[User]
FROM (VALUES ('A', 'Rick'),
             ('A', 'Rick'),
             ('B', 'Rick'),
             ('C', 'Rick'),
             ('A', 'Joe '),
             ('B', 'Joe '),
             ('B', 'Joe ')) V ([Value], [User]);
</code>```

This assumes that there will always be at least one row with 'A'.

Edit 2: Ok, goal posts were moved again, this now does what you are after. If they move again, you will need to amend the solution though:

```<code>WITH YourTable AS(
    SELECT V.ID,
           V.Value,
           V.[User]
    FROM (VALUES(1,'A','Rick'),
                (2,'A','Rick'),
                (3,'B','Rick'),
                (7,'A','Rick'),
                (8,'C','Rick'),
                (4,'A','Joe '),
                (5,'B','Joe '),
                (6,'B','Joe '))V(ID,[Value],[User])),
Grps AS(
    SELECT YT.ID,
           YT.Value,
           YT.[User],
           COUNT(CASE YT.[Value] WHEN 'A' THEN 1 END) OVER(PARTITION BY YT.[User] ORDER BY YT.ID) AS Grp
    FROM YourTable YT)
SELECT ID,
       CASE G.[Value]
            WHEN 'A' THEN 1
            ELSE ROW_NUMBER() OVER (PARTITION BY G.[User], G.Grp ORDER BY G.[Value]) -
                 COUNT(CASE G.[Value] WHEN 'A' THEN 1 END) OVER (PARTITION BY G.[User], G.Grp) + 1
       END AS [Row],
       G.[Value],
       G.[User]
FROM Grps G
ORDER BY G.[User], G.ID;
</code>```

Title: PARTITION BY row value

Body:
I need to partition my output table when a certain row is of a certain value. I have:

ID|Value|User
-------------
1 |A    |Rick
2 |A    |Rick
3 |B    |Rick
7 |A    |Rick
8 |C    |Rick
4 |A    |Joe
5 |B    |Joe
6 |B    |Joe

I need to partition my table for each individual user, and when the value = A, so what I need is:

Row|ID|Value|User
------------------
1  |1 |A    |Rick
1  |2 |A    |Rick
2  |3 |B    |Rick
1  |7 |A    |Rick
2  |8 |C    |Rick
1  |4 |A    |Joe
2  |5 |B    |Joe
3  |6 |B    |Joe

Every value has its own ID.

I've tried things like:

SELECT ROW_NUMBER() OVER(PARTITION BY User, Value = A ORDER BY ID ASC) AS Row, Value, User FROM...
SELECT ROW_NUMBER() OVER(PARTITION BY User, WHERE Value = A ORDER BY ID ASC) AS Row, Value, User FROM...
etc

But I can't seem to figure out how to write it correctly, if it even is possible.

Body:
Seems like what you're after is simply a DENSE_RANK:

DENSE_RANK() OVER (PARTITION BY [User] ORDER BY [Value] ASC) AS [Row]

Note USER is a reserved keyword in T-SQL. I strongly recommend you chose a different name for your column, as you must otherwise delimit identify it. ROW and VALUE are not currently reserved, but they are listed as a Future Keyword and their use is also recommended to be avoided.

Edit: Seems, actually that it's 'A' is 1, and then also increment afterwards. This is messy, but you could therefore you could do:

SELECT CASE [Value]
            WHEN 'A' THEN 1
            ELSE ROW_NUMBER() OVER (PARTITION BY [User] ORDER BY [Value]) -
                 COUNT(CASE [Value] WHEN 'A' THEN 1 END) OVER (PARTITION BY [User]) + 1
       END AS [Row],
       V.[Value],
       V.[User]
FROM (VALUES ('A', 'Rick'),
             ('A', 'Rick'),
             ('B', 'Rick'),
             ('C', 'Rick'),
             ('A', 'Joe '),
             ('B', 'Joe '),
             ('B', 'Joe ')) V ([Value], [User]);

This assumes that there will always be at least one row with 'A'.

Edit 2: Ok, goal posts were moved again, this now does what you are after. If they move again, you will need to amend the solution though:

WITH YourTable AS(
    SELECT V.ID,
           V.Value,
           V.[User]
    FROM (VALUES(1,'A','Rick'),
                (2,'A','Rick'),
                (3,'B','Rick'),
                (7,'A','Rick'),
                (8,'C','Rick'),
                (4,'A','Joe '),
                (5,'B','Joe '),
                (6,'B','Joe '))V(ID,[Value],[User])),
Grps AS(
    SELECT YT.ID,
           YT.Value,
           YT.[User],
           COUNT(CASE YT.[Value] WHEN 'A' THEN 1 END) OVER(PARTITION BY YT.[User] ORDER BY YT.ID) AS Grp
    FROM YourTable YT)
SELECT ID,
       CASE G.[Value]
            WHEN 'A' THEN 1
            ELSE ROW_NUMBER() OVER (PARTITION BY G.[User], G.Grp ORDER BY G.[Value]) -
                 COUNT(CASE G.[Value] WHEN 'A' THEN 1 END) OVER (PARTITION BY G.[User], G.Grp) + 1
       END AS [Row],
       G.[Value],
       G.[User]
FROM Grps G
ORDER BY G.[User], G.ID;


来源: stackexchange

问:
find, save and remove duplicate values from more then one array
first array

```<code>[0]=> Brian
[1]=> A
[2]=> Leo
[3]=> A
[4]=> Mike
</code>```

second array

```<code>[0]=> 1
[1]=> 2
[2]=> 3
[3]=> 4
[4]=> 5
</code>```

I want to check if in first array there are duplicates, if yes, save only the first occurrence of that value, the other removes, remember those keys, and delete them from the second array too. In the end i want to have

first array

```<code>[0]=> Brian
[1]=> A
[2]=> Leo
[3]=> Mike
</code>```

second array

```<code>[0]=> 1
[1]=> 2
[2]=> 3
[3]=> 5
</code>```

I tried with this but second array does not have duplicates so it won't work for both array:

```<code>array_values(array_unique($array));
</code>```

答:
You did

```<code>array_values(array_unique($array));
</code>```

This will give unique values of $array, but you won't find which index of second array needs to be unset.

Approach #1:

Your best shot is a simple for loop with an isset check. If we find the value already present in our $set(a new temp array), we unset that index from both original arrays, else we preserve it.

Snippet:

```<code><?php

$arr1 = [
    'Brian',
    'A',
    'Leo',
    'A',
    'Mike'
];

$arr2 = [
        1,2,3,4,5
];

$set = [];

foreach($arr1 as $key => $value){
    if(!isset($set[$value])) $set[$value] = true;
    else{
        unset($arr1[$key]); // foreach creates a copy of $arr1, so safe to unset
        unset($arr2[$key]);
    }
}

print_r($arr1);
print_r($arr2);
</code>```

Demo: https://3v4l.org/BQ9mA

Approach #2:

If you don't like for loops, you can use array wrappers to do this. You can use array_combine to make first array values as keys and second array values as arrays. Note that this would only preserve the latest key value pairs, so we do a array_reverse to only maintain first occurrence pairs.

Snippet:

```<code><?php

$arr1 = [
    'Brian',
    'A',
    'Leo',
    'A',
    'Mike'
];

$arr2 = [
        1,2,3,4,5
    ];

$filtered_data = array_combine(array_reverse($arr1),array_reverse($arr2));
print_r(array_keys($filtered_data));
print_r(array_values($filtered_data));
</code>```

Demo: https://3v4l.org/mlstg

ContentLicense: CC BY-SA 4.0

Body:
first array

[0]=> Brian
[1]=> A
[2]=> Leo
[3]=> A
[4]=> Mike

second array

[0]=> 1
[1]=> 2
[2]=> 3
[3]=> 4
[4]=> 5

I want to check if in first array there are duplicates, if yes, save only the first occurrence of that value, the other removes, remember those keys, and delete them from the second array too. In the end i want to have

first array

[0]=> Brian
[1]=> A
[2]=> Leo
[3]=> Mike

second array

[0]=> 1
[1]=> 2
[2]=> 3
[3]=> 5

I tried with this but second array does not have duplicates so it won't work for both array:

array_values(array_unique($array));

Body:
You did

array_values(array_unique($array));

This will give unique values of $array, but you won't find which index of second array needs to be unset.

Approach #1:

Your best shot is a simple for loop with an isset check. If we find the value already present in our $set(a new temp array), we unset that index from both original arrays, else we preserve it.

Snippet:

<?php

$arr1 = [
    'Brian',
    'A',
    'Leo',
    'A',
    'Mike'
];

$arr2 = [
        1,2,3,4,5
];

$set = [];

foreach($arr1 as $key => $value){
    if(!isset($set[$value])) $set[$value] = true;
    else{
        unset($arr1[$key]); // foreach creates a copy of $arr1, so safe to unset
        unset($arr2[$key]);
    }
}

print_r($arr1);
print_r($arr2);

Demo: https://3v4l.org/BQ9mA

Approach #2:

If you don't like for loops, you can use array wrappers to do this. You can use array_combine to make first array values as keys and second array values as arrays. Note that this would only preserve the latest key value pairs, so we do a array_reverse to only maintain first occurrence pairs.

Snippet:

<?php

$arr1 = [
    'Brian',
    'A',
    'Leo',
    'A',
    'Mike'
];

$arr2 = [
        1,2,3,4,5
    ];

$filtered_data = array_combine(array_reverse($arr1),array_reverse($arr2));
print_r(array_keys($filtered_data));
print_r(array_values($filtered_data));

Demo: https://3v4l.org/mlstg


问:
Create space at the beginning of a UITextField
I want to leave a bit of space at the beginning of a UITextField, just like here:
Add lefthand margin to UITextField

But I don't know how to do that with Swift.

答:
Use my extension Swift 5 tested:

```<code>extension UITextField {

enum PaddingSpace {
    case left(CGFloat)
    case right(CGFloat)
    case equalSpacing(CGFloat)
}

func addPadding(padding: PaddingSpace) {

    self.leftViewMode = .always
    self.layer.masksToBounds = true

    switch padding {

    case .left(let spacing):
        let leftPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
        self.leftView = leftPaddingView
        self.leftViewMode = .always

    case .right(let spacing):
        let rightPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
        self.rightView = rightPaddingView
        self.rightViewMode = .always

    case .equalSpacing(let spacing):
        let equalPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
        // left
        self.leftView = equalPaddingView
        self.leftViewMode = .always
        // right
        self.rightView = equalPaddingView
        self.rightViewMode = .always
    }
}
}
</code>```

How to use

```<code>// equal padding
yourTextField.addPadding(padding: .equalSpacing(10))

// padding right
yourTextField.addPadding(padding: .right(10))

// padding left
yourTextField.addPadding(padding: .left(10))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use my extension Swift 5 tested:

extension UITextField {

enum PaddingSpace {
    case left(CGFloat)
    case right(CGFloat)
    case equalSpacing(CGFloat)
}

func addPadding(padding: PaddingSpace) {

    self.leftViewMode = .always
    self.layer.masksToBounds = true

    switch padding {

    case .left(let spacing):
        let leftPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
        self.leftView = leftPaddingView
        self.leftViewMode = .always

    case .right(let spacing):
        let rightPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
        self.rightView = rightPaddingView
        self.rightViewMode = .always

    case .equalSpacing(let spacing):
        let equalPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
        // left
        self.leftView = equalPaddingView
        self.leftViewMode = .always
        // right
        self.rightView = equalPaddingView
        self.rightViewMode = .always
    }
}
}

How to use

// equal padding
yourTextField.addPadding(padding: .equalSpacing(10))

// padding right
yourTextField.addPadding(padding: .right(10))

// padding left
yourTextField.addPadding(padding: .left(10))


问:
How to tell Octopus Deploy to wait until another deployment finishes on the same machine?
Sometimes it is preferred and/or required to host dozens of applications on a single server.  Not saying this is "right" or "wrong," I'm only saying that it happens.

A downside to this configuration is the error message Waiting for the script in task [TASK ID] to finish as this script requires that no other Octopus scripts are executing on this target at the same time appears whenever more than one deployment to the same machine is running.  It seems like Octopus Deploy is fighting itself.

How can I configure Octopus Deploy to wait for one deployment to completely finish before the next one is started?

答:
Before diving into the answer, it is important to understand why that message is appearing in the first place.  Each time a step is run on a deployment target, the tentacle will create a "Mutex" to prevent others projects from interfering with it.  An early use case for this was updating the IIS metabase during a deployment.  In certain cases, concurrent updates would cause random errors.

Option 1: Disable the Mutex

We've seen cases where the mutex is the cause of the delay.  The mutex is applied per step, not per deployment.  It is common to see a situation where it looks like Octopus is "jumping" between deployments.  Depending on the number of concurrent deployments, that can slow down the deployment.  The natural thought is to disable the mutex altogether.

It is possible to disable the mutex by adding the variable OctopusBypassDeploymentMutex and setting it to True. That variable can exist in either a specific project or in a variable set.

More details on what that variable does can be found in this document.   If you do disable the mutex please test it and monitor for any failures.  For the most part, we don't see issues disabling the mutex, but it has happened from time to time.  It depends on a host of other factors such as application type and Windows version.

Option 2: Leverage Deploy a Release Step

Another option is to coordinate the projects using the deploy a release step.  Typically this works best when the projects being deployed are part of the same application suite.  In the example screenshot below I have five "deployment" projects:

Azure Worker IaC

Database Worker IaC

Kubernetes Worker IaC

Script Worker IaC

OctoStudy

The project Unleash the Kraken coordinates deployments for those projects.

It does this by using the Deploy a Release step.  First it spins up all the infrastructure, then it deploys the application.

This won't work as well if the server is hosting 50 disparate applications.

Option 3: Leverage the API to check for running deployments

The final option is to include a step at the start of each project which hits the API to check for active releases to the deployment targets for the deployment target.  If an active deployment is found then wait until it is done.

You can do this by hitting the endpoint https://[YOUR URL]/api/[SPACE ID]/machines/[Machine Id]/tasks?skip=0&name=Deploy&states=Executing%2CCancelling&spaces=[SPACE ID]&includeSystem=false.  That will tell you all the active tasks being run for a specific machine.

You can get Machine Id by pulling the value from Octopus.Deployment.Machines.  You can get Space Id by pulling the value from Octopus.Space.Id.

The pseudo code for this approach could look like this (I'm not including the actual code as your requirements could be very different).

```<code>activeDeployments = true

while (activeDeployments)
{
      activeDeployments = false
      foreach(machineId in Octopus.Deployment.Machines)
      {
             activeTasks = https://[YOUR URL]/api/[Octopus.Space.Id]/machines/[Machine Id]/tasks?skip=0&name=Deploy&states=Executing%2CCancelling&spaces=[Octopus.Space.Id]&includeSystem=false

             if (activeTasks.Count > 0)
             {
                      activeDeployments = true
             }
      }

      if (activeDeployments = true)
      {
            Sleep for 5 seconds
      }
}
</code>```

Body:
Before diving into the answer, it is important to understand why that message is appearing in the first place.  Each time a step is run on a deployment target, the tentacle will create a "Mutex" to prevent others projects from interfering with it.  An early use case for this was updating the IIS metabase during a deployment.  In certain cases, concurrent updates would cause random errors.

Option 1: Disable the Mutex

We've seen cases where the mutex is the cause of the delay.  The mutex is applied per step, not per deployment.  It is common to see a situation where it looks like Octopus is "jumping" between deployments.  Depending on the number of concurrent deployments, that can slow down the deployment.  The natural thought is to disable the mutex altogether.

It is possible to disable the mutex by adding the variable OctopusBypassDeploymentMutex and setting it to True. That variable can exist in either a specific project or in a variable set.

More details on what that variable does can be found in this document.   If you do disable the mutex please test it and monitor for any failures.  For the most part, we don't see issues disabling the mutex, but it has happened from time to time.  It depends on a host of other factors such as application type and Windows version.

Option 2: Leverage Deploy a Release Step

Another option is to coordinate the projects using the deploy a release step.  Typically this works best when the projects being deployed are part of the same application suite.  In the example screenshot below I have five "deployment" projects:

Azure Worker IaC

Database Worker IaC

Kubernetes Worker IaC

Script Worker IaC

OctoStudy

The project Unleash the Kraken coordinates deployments for those projects.

It does this by using the Deploy a Release step.  First it spins up all the infrastructure, then it deploys the application.

This won't work as well if the server is hosting 50 disparate applications.

Option 3: Leverage the API to check for running deployments

The final option is to include a step at the start of each project which hits the API to check for active releases to the deployment targets for the deployment target.  If an active deployment is found then wait until it is done.

You can do this by hitting the endpoint https://[YOUR URL]/api/[SPACE ID]/machines/[Machine Id]/tasks?skip=0&name=Deploy&states=Executing%2CCancelling&spaces=[SPACE ID]&includeSystem=false.  That will tell you all the active tasks being run for a specific machine.

You can get Machine Id by pulling the value from Octopus.Deployment.Machines.  You can get Space Id by pulling the value from Octopus.Space.Id.

The pseudo code for this approach could look like this (I'm not including the actual code as your requirements could be very different).

activeDeployments = true

while (activeDeployments)
{
      activeDeployments = false
      foreach(machineId in Octopus.Deployment.Machines)
      {
             activeTasks = https://[YOUR URL]/api/[Octopus.Space.Id]/machines/[Machine Id]/tasks?skip=0&name=Deploy&states=Executing%2CCancelling&spaces=[Octopus.Space.Id]&includeSystem=false

             if (activeTasks.Count > 0)
             {
                      activeDeployments = true
             }
      }

      if (activeDeployments = true)
      {
            Sleep for 5 seconds
      }
}


问:
Flutter socket io doesn't connect to node js socket io server
I'm trying to build a simple flutter chat application using a node.js matchmaking server. I've worked with this for a few hours already but I simple cannot get the app to connect with the server.

Here's the node js server:

```<code>var express=require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

var allClients = {};

io.on('connection', function (socket) {
    io.to(socket.id).emit('userCount', Object.keys(allClients).length);
    console.log(socket.id,'joined');
    //match making logic
});

var port = 8080;
console.log(port);
server.listen(port);
</code>```

Flutter connecting code:

```<code>//Find a match for the user
void findMatch() async {
    SocketIO socketIO = SocketIOManager().createSocketIO("http://192.168.0.32:8080", "/");
    print('Created');
    await socketIO.init(); //code execution pauses indefinitely at this line
    print('Initialized');
    await socketIO.connect();
    print('Connected');

    socketIO.sendMessage('new user', data);

    socketIO.subscribe('match found', (data) async {
      UserData peerData = await getUserData(data.peerId);
      redirectToPage(context, Chat(peerId: data.peerId, peerData: peerData));
    });
}
</code>```

When the function is run, the code execution pauses at the line shown above, and the node js server doesn't react at all. However this shows up on the debug console.

```<code>D/FlutterSocketIoPlugin: FlutterSocketIoPlugin( 4490): onMethodCall: socketInit - domain: http://192.168.0.32:8080 - with namespace: /
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: added SocketIO( 4490): http://192.168.0.32:8080/
D/FlutterSocketIoPlugin: SocketIO( 4490): connecting...null
</code>```

Any help is appreciated. Thank you!

I wrote a simple node js client as suggested in the comments, and it connects to the server successfully.

```<code>//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});

// Add a connect listener
socket.on('connect', function (socket) {
    console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');
</code>```

Edit:

Removing the 'await's before the socket functions in findMatch() gets me this.

```<code>D/FlutterSocketIoPlugin: SocketIO(21368): reconnect_error: [{"cause":{"cause":{"detailMessage":"CLEARTEXT communication to 192.168.0.32 not permitted by network security policy","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"websocket error","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"Connection error","stackTrace":[],"suppressedExceptions":[]}]
</code>```

I tried android:usesCleartextTraffic="true" in AndroidManifest.xml but it doesn't seem to work.  Changing http to https gives SSL handshake aborted. Maybe deploying the socket server on a remote machine with an SSL certificate will work? Will continue digging.

答:
I tried above code with this flutter plugin here as I think you are also using the same, but I also got the same problem. I tried to see any error log generated by Logcat and I found an entry connecting...null and it was stuck there but don't know how to fix or what is the problem. I tried it with another flutter plugin here and tested it in emulator, it worked fine for below sample code. If you can use a different flutter plugin then this might be useful.

```<code>var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

io.on('connection', function (socket) {
    console.log(socket.id, 'joined');
    socket.on('/test', function (msg) {
        console.log(msg);
    });
});

var port = 8080;
console.log(port);
server.listen(port);
</code>```

Flutter client code -

```<code>IO.Socket socket = IO.io('http://10.0.2.2:8080', <String, dynamic>{
   'transports': ['websocket'],
   'autoConnect': false,
});
socket.connect();
socket.emit('/test', 'test');
</code>```

Body:
I'm trying to build a simple flutter chat application using a node.js matchmaking server. I've worked with this for a few hours already but I simple cannot get the app to connect with the server.

Here's the node js server:

var express=require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

var allClients = {};

io.on('connection', function (socket) {
    io.to(socket.id).emit('userCount', Object.keys(allClients).length);
    console.log(socket.id,'joined');
    //match making logic
});

var port = 8080;
console.log(port);
server.listen(port);

Flutter connecting code:

//Find a match for the user
void findMatch() async {
    SocketIO socketIO = SocketIOManager().createSocketIO("http://192.168.0.32:8080", "/");
    print('Created');
    await socketIO.init(); //code execution pauses indefinitely at this line
    print('Initialized');
    await socketIO.connect();
    print('Connected');

    socketIO.sendMessage('new user', data);

    socketIO.subscribe('match found', (data) async {
      UserData peerData = await getUserData(data.peerId);
      redirectToPage(context, Chat(peerId: data.peerId, peerData: peerData));
    });
}

When the function is run, the code execution pauses at the line shown above, and the node js server doesn't react at all. However this shows up on the debug console.

D/FlutterSocketIoPlugin: FlutterSocketIoPlugin( 4490): onMethodCall: socketInit - domain: http://192.168.0.32:8080 - with namespace: /
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: added SocketIO( 4490): http://192.168.0.32:8080/
D/FlutterSocketIoPlugin: SocketIO( 4490): connecting...null

Any help is appreciated. Thank you!

I wrote a simple node js client as suggested in the comments, and it connects to the server successfully.

//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});

// Add a connect listener
socket.on('connect', function (socket) {
    console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');

Edit:

Removing the 'await's before the socket functions in findMatch() gets me this.

D/FlutterSocketIoPlugin: SocketIO(21368): reconnect_error: [{"cause":{"cause":{"detailMessage":"CLEARTEXT communication to 192.168.0.32 not permitted by network security policy","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"websocket error","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"Connection error","stackTrace":[],"suppressedExceptions":[]}]

I tried android:usesCleartextTraffic="true" in AndroidManifest.xml but it doesn't seem to work.  Changing http to https gives SSL handshake aborted. Maybe deploying the socket server on a remote machine with an SSL certificate will work? Will continue digging.

Body:
I tried above code with this flutter plugin here as I think you are also using the same, but I also got the same problem. I tried to see any error log generated by Logcat and I found an entry connecting...null and it was stuck there but don't know how to fix or what is the problem. I tried it with another flutter plugin here and tested it in emulator, it worked fine for below sample code. If you can use a different flutter plugin then this might be useful.

var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

io.on('connection', function (socket) {
    console.log(socket.id, 'joined');
    socket.on('/test', function (msg) {
        console.log(msg);
    });
});

var port = 8080;
console.log(port);
server.listen(port);

Flutter client code -

IO.Socket socket = IO.io('http://10.0.2.2:8080', <String, dynamic>{
   'transports': ['websocket'],
   'autoConnect': false,
});
socket.connect();
socket.emit('/test', 'test');


问:
BL001 Component Parameter should have publi setter
Solution Upgraded to Dotnet Core 3.1
I have found in this warnings, but my code Build & Run without problems.

I can't diagnose the problems.

I try to consolidate all packages.

How can I get details on the mistakes I make?

Solution Explorer

答:
This is a "false positive". It is a known issue with the user interface of the Solution Explorer.

It has nothing to do with the upgrade and it is just a bug.

Here is the Developer Community issue.

Here is the GitHub issue as well.

It seems to be happening to a lot of people.

For me sometimes it goes away... but then after a while it comes back.


问:
disassembly of C array gives weird results

int square() {
    char test[50];
}
```

<p>The above code produces</p>

```square():
        push    rbp
        mov     rbp, rsp
```

<p>When i change the code a little to</p>

<pre class="lang-c prettyprint-override"><code>int square() {
    char test[150];
}
</code>```

The assembly generated is

```<code>square():
        push    rbp
        mov     rbp, rsp
        sub     rsp, 40
</code>```

Which is still weird because I cannot understand why it does not allocate for previous creations. I'm running at -O0 so gcc doesn't optimize it out. Why is gcc creating code for wrong sized arrays?

```<code>int square() {
    char a[50];
    char b[50];
}
</code>```

```<code>square():
        push    rbp
        mov     rbp, rsp
        sub     rsp, 8
</code>```

Similarly for x86

```<code>int square() {
    char a[500];
}
</code>```

compiled with -m32 gives me:

```<code>square():
        push    ebp
        mov     ebp, esp
        sub     esp, 512
</code>```

Where is this extra 12 bytes from? And why does -m32 have an sub instruction for char test[50] but x86_64 doesn't?

答:
GCC is using the x86-64 System V ABI's 128-byte Red Zone below the stack pointer for the variables, only reserving some extra stack space when that's not sufficient

For the last example, GCC subs 512 to keep the stack (and the array) aligned.

The i386 System V ABI does not have a red zone so it has to reserve space for the whole array (neither does Windows x64, for that matter).

Body:
int square() {
    char test[50];
}

The above code produces

square():
        push    rbp
        mov     rbp, rsp

When i change the code a little to

int square() {
    char test[150];
}

The assembly generated is

square():
        push    rbp
        mov     rbp, rsp
        sub     rsp, 40

Which is still weird because I cannot understand why it does not allocate for previous creations. I'm running at -O0 so gcc doesn't optimize it out. Why is gcc creating code for wrong sized arrays?

int square() {
    char a[50];
    char b[50];
}

square():
        push    rbp
        mov     rbp, rsp
        sub     rsp, 8

Similarly for x86

int square() {
    char a[500];
}

compiled with -m32 gives me:

square():
        push    ebp
        mov     ebp, esp
        sub     esp, 512

Where is this extra 12 bytes from? And why does -m32 have an sub instruction for char test[50] but x86_64 doesn't?


问:
How can I catch programmer error with malloc?
I'm trying to find a way to catch a programmer error in the argument for malloc in an automated code tester.

For example:

```<code>struct Pepe* p = malloc(sizeof(struct Pepe*));
</code>```

This, of course, compiles without any problems. The thing is that struct Pepe has another struct of the same size inside it, therefore no problem appears during execution (nor with free).

The correct code should be:

```<code>struct Pepe* p = malloc(sizeof(struct Pepe));
</code>```

Can we get a warning or something to catch this problem?

I tried -Wall and -Wextra but there was no warning.

答:
The issue is that both statements are very much correct with 'c' and there is no way of catching it in the language. The malloc is just a function which the program calls in order to allocate some amount of memory. Compiler does not know anything about it, does not check and does not care. The only way around it is to use a good programming style, as mentioned in other replies of use a different programming language with build in memory management, e.g. java, c#, ...

However, there is a bunch of free and commercial static and dynamic linting tools (e.g., purify, cppcheck, clang static analyzer, ...) available for 'c' and 'c++'. Maybe you need to investigate them and use as a part of the build methodology. They should be able to catch those issues. And, as it was mentioned, valgrind is a free dynamic checker.

Body:
I'm trying to find a way to catch a programmer error in the argument for malloc in an automated code tester.

For example:

struct Pepe* p = malloc(sizeof(struct Pepe*));

This, of course, compiles without any problems. The thing is that struct Pepe has another struct of the same size inside it, therefore no problem appears during execution (nor with free).

The correct code should be:

struct Pepe* p = malloc(sizeof(struct Pepe));

Can we get a warning or something to catch this problem?

I tried -Wall and -Wextra but there was no warning.


问:
Split x axis for every value in graph, in Power BI
I have the following graph in Power BI:

and I'm trying to recreate the below graph from Excel (note the X axis with the months February and January, with the Operation Text:

As you can see, my attempt only displays the Operation Text rather than the month and Operation Text).

Here is what my current axis looks like:

Changing the axis to have Actual Start Date on top, rather than the Operation Text:

Makes my graph look like this:

Is it possible to achieve the same outcome as in Excel, with the values in my graph showing the two months side by side, for each operation text? If so, how can I do this?

I've tried looking into the X axis 'format' settings and wasn't able to see anything obvious to help achieve this. In addition, unfortunately the graph I'm looking to recreate is only a screenshot so I am unable to see how it achieves that outcome.

EDIT:

As suggested, I attempted to place Operation Text into the Legend field in my Visualisations section but I am unable to, due to the fact that I have two Value fields (the two columns Actual Hours and Estimated Hours).

答: You would have to drill down one level, using the arrows seen at the top right of your first screenshot. For your specific purposes, the split arrow should do the trick. Hope this helps.</p>


问:
Spring SAML extension and spring security 5
Can someone tell me what is the difference between spring saml extension and spring security 5 saml. I found like configs are less in spring security 5. </p>

答:
Spring Security SAML extension is not actively developed.

The Spring Security team opted to provide framework support for SAML 2 authentication as part of core Spring Security, which is available since version 5.2.0.

As you stated, not all feature functionality exists in Spring Security core yet.

From the Spring Security documentation

SAML 2 Service Provider, SP a.k.a. a relying party, support existed as an independent project since 2009. The 1.0.x branch is still in use, including in the Cloud Foundry User Account and Authentication Server that also created a SAML 2.0 Identity Provider implementation based on the SP implementation.

In 2018 we experimented with creating an updated implementation of both a Service Provider and Identity Provider as a standalone library. After careful, and lengthy, deliberation we, the Spring Security team, decided to discontinue that effort. While this effort created a replacement for that standalone 1.0.x library we didn’t feel that we should build a library on top of another library.

Instead we opted to provide framework support for SAML 2 authentication as part of core Spring Security instead.

From the Spring Security SAML GitHub

This project is being rewritten.

...

we will not be publishing any official releases of the 2.0.0 milestones, but will maintain it until all feature functionality that exists in the milestones are part of Spring Security.

We continue to accept pull request for the 1.0.x branch, but are not actively developing it.


问:
In dolphindb， I have two independent clusters. How to transfer distributed databases between these two clusters
In dolphindb， I have two independent clusters, which are installed on a different physical server. I want to transfer the historical data from one cluster to another. and is there any convenient way to do this work.</p>

答: One approach is backup and restore. You can backup a database in cluster A to a shared media and then restore it in cluster B</p>


问:
How to calculate the 99th percentile of a dataset
I have a dataset of the mean of weights of two sample sizes, I have 100,000 tests and I am trying to find out the 99th percentile but I do not understand how to do so, I have found out the median quartile by doing the following;

```<code>summary(Lifts)
 Large           Small
 Min.   : 62.5   Min.   : 54.2
 1st Qu.: 99.1   1st Qu.: 96.0
 Median :106.0   Median :106.0
 Mean   :106.0   Mean   :106.0
 3rd Qu.:112.9   3rd Qu.:116.0
 Max.   :147.5   Max.   :156.8
</code>```

I need to find the 99th percentile of both the large and the small, I have tried using the quartile command;

```<code>quantile(Lifts, probs = c(0, 0.25, 0.50, 0.99))
Error in `[.data.frame`(x, order(x, na.last = na.last, decreasing = decreasing)) :
  undefined columns selected
</code>```

But I receive that error

any help would be appreciated

答:
If we specify the column (for example using $ notation) we get rid of the error:

```<code>quantile(Lifts$Large, probs = c(0, 0.25, 0.50, 0.99))
</code>```

Or

```<code>quantile(Lifts$Small, probs = c(0, 0.25, 0.50, 0.99))
</code>```

Body:
I have a dataset of the mean of weights of two sample sizes, I have 100,000 tests and I am trying to find out the 99th percentile but I do not understand how to do so, I have found out the median quartile by doing the following;

summary(Lifts)
 Large           Small
 Min.   : 62.5   Min.   : 54.2
 1st Qu.: 99.1   1st Qu.: 96.0
 Median :106.0   Median :106.0
 Mean   :106.0   Mean   :106.0
 3rd Qu.:112.9   3rd Qu.:116.0
 Max.   :147.5   Max.   :156.8

I need to find the 99th percentile of both the large and the small, I have tried using the quartile command;

quantile(Lifts, probs = c(0, 0.25, 0.50, 0.99))
Error in `[.data.frame`(x, order(x, na.last = na.last, decreasing = decreasing)) :
  undefined columns selected

But I receive that error

any help would be appreciated

Body:
If we specify the column (for example using $ notation) we get rid of the error:

quantile(Lifts$Large, probs = c(0, 0.25, 0.50, 0.99))

Or

quantile(Lifts$Small, probs = c(0, 0.25, 0.50, 0.99))


问:
How to make specific bit manipulation?
I'm doing practice of bit manipulation in arduino with a 74HC595 shift register.

I would like to create an algorithm that allows the binary digit to perform this way:

1 0 0 0 0 0 0 1

0 1 0 0 0 0 1 0

0 0 1 0 0 1 0 0

.

.

.

1 0 0 0 0 0 0 1

In this type of function the decimal values are: (129,66,36,24,24,36,66,129) and so on in a loop.

How can I perform this type of shifting? I don't have any fluency thinking this type of operation, I have only performed a circular shift with "an algorithm" like:

```<code>//my circular shift

myByte = myByte*128 + myByte/2
</code>```

But I don't know how to perform the output that I showed.

How can I do this? Thanks

答:
Noticing that:

129,66,36,24,24,36,66,129 = 128+1; 64+2 ; 32+4; 16+8; 16+8; 32+4; 64+2; 128+1;

I ended up with this code:

```<code>int latchPin = 11;
int clockPin = 9;
int dataPin = 12;
int dt = 2000;
uint8_t n1 = 128, n2 = 1;
byte myByte = 0b10000001; //in BIN

void setup() {
Serial.begin(9600);
pinMode(latchPin,OUTPUT);
pinMode(dataPin,OUTPUT);
pinMode(clockPin,OUTPUT);
}

//circular shift to the left
void loop() {
digitalWrite(latchPin,LOW);
shiftOut(dataPin,clockPin,LSBFIRST,myByte);
digitalWrite(latchPin,HIGH);
int i;

myByte = 0b10000001; //restarting the value of 129
        Serial.print("BIN: ");
        Serial.print(myByte,BIN);
        Serial.print(" --> ");
        Serial.print("HEX: ");
        Serial.print(myByte,HEX);
        Serial.print(" --> ");
        Serial.print("DEC: ");
        Serial.println(myByte,DEC);
        delay(200);

    for (int i = 0; i < 7; i++) {
        Serial.print("i:  ");
        Serial.println(i);
        //int i1 = i+1;
        //int myGap = myByte - (pow(2,i));      //no need to round when it's raised to 0;
        //int firstpart = (myGap/2);
        //int secondpart = 0.5 + pow(2,i1);     //because it rounds the number. (i.e --> 1.9999 = 1)
        //myByte = firstpart+ secondpart;

          myByte = (myByte - (pow(2,i)))/2 + (0.5 + pow(2,i+1));

        //Serial.print("firstpart: ");
        //Serial.println(firstpart);
        //Serial.print("secondpart: ");
        //Serial.println(secondpart);
        //delay(3000);
        Serial.print("BIN: ");
        Serial.print(myByte,BIN);
        Serial.print(" --> ");
        Serial.print("HEX: ");
        Serial.print(myByte,HEX);
        Serial.print(" --> ");
        Serial.print("DEC: ");
        Serial.println(myByte,DEC);
        digitalWrite(latchPin,LOW);
        shiftOut(dataPin,clockPin,LSBFIRST,myByte);
        digitalWrite(latchPin,HIGH);
        delay(100);
    }
//myByte = myByte*2;    //shift by right //using MSBFIRTS
//delay(dt);
}
</code>```

And it works.

Title: How to make specific bit manipulation?

Body:
I'm doing practice of bit manipulation in arduino with a 74HC595 shift register.

I would like to create an algorithm that allows the binary digit to perform this way:

1 0 0 0 0 0 0 1

0 1 0 0 0 0 1 0

0 0 1 0 0 1 0 0

.

.

.

1 0 0 0 0 0 0 1

In this type of function the decimal values are: (129,66,36,24,24,36,66,129) and so on in a loop.

How can I perform this type of shifting? I don't have any fluency thinking this type of operation, I have only performed a circular shift with "an algorithm" like:

//my circular shift

myByte = myByte*128 + myByte/2

But I don't know how to perform the output that I showed.

How can I do this? Thanks

Body:
Noticing that:

129,66,36,24,24,36,66,129 = 128+1; 64+2 ; 32+4; 16+8; 16+8; 32+4; 64+2; 128+1;

I ended up with this code:

int latchPin = 11;
int clockPin = 9;
int dataPin = 12;
int dt = 2000;
uint8_t n1 = 128, n2 = 1;
byte myByte = 0b10000001; //in BIN

void setup() {
Serial.begin(9600);
pinMode(latchPin,OUTPUT);
pinMode(dataPin,OUTPUT);
pinMode(clockPin,OUTPUT);
}

//circular shift to the left
void loop() {
digitalWrite(latchPin,LOW);
shiftOut(dataPin,clockPin,LSBFIRST,myByte);
digitalWrite(latchPin,HIGH);
int i;

myByte = 0b10000001; //restarting the value of 129
        Serial.print("BIN: ");
        Serial.print(myByte,BIN);
        Serial.print(" --> ");
        Serial.print("HEX: ");
        Serial.print(myByte,HEX);
        Serial.print(" --> ");
        Serial.print("DEC: ");
        Serial.println(myByte,DEC);
        delay(200);

    for (int i = 0; i < 7; i++) {
        Serial.print("i:  ");
        Serial.println(i);
        //int i1 = i+1;
        //int myGap = myByte - (pow(2,i));      //no need to round when it's raised to 0;
        //int firstpart = (myGap/2);
        //int secondpart = 0.5 + pow(2,i1);     //because it rounds the number. (i.e --> 1.9999 = 1)
        //myByte = firstpart+ secondpart;

          myByte = (myByte - (pow(2,i)))/2 + (0.5 + pow(2,i+1));

        //Serial.print("firstpart: ");
        //Serial.println(firstpart);
        //Serial.print("secondpart: ");
        //Serial.println(secondpart);
        //delay(3000);
        Serial.print("BIN: ");
        Serial.print(myByte,BIN);
        Serial.print(" --> ");
        Serial.print("HEX: ");
        Serial.print(myByte,HEX);
        Serial.print(" --> ");
        Serial.print("DEC: ");
        Serial.println(myByte,DEC);
        digitalWrite(latchPin,LOW);
        shiftOut(dataPin,clockPin,LSBFIRST,myByte);
        digitalWrite(latchPin,HIGH);
        delay(100);
    }
//myByte = myByte*2;    //shift by right //using MSBFIRTS
//delay(dt);
}

And it works.


问:
Failed to parse column picker rules - azure ML designer
I am trying to use the azure ML designer (preview).

referencing this - https://learn.microsoft.com/en-in/azure/machine-learning/tutorial-designer-automobile-price-train-score

using my own input sheet which has four columns and some decimal values. nothing fancy and identical to the sample datasets provided.

I do this step (from the linked document above)

Select the Train Model module.
In the module details pane to the right of the canvas, select Edit column selector.
In the Label column dialog box, expand the drop-down menu and select Column names.
In the text box, enter price to specify the value that your model is going to predict.

and I get this (but there are no errors in the actual designer window.

"Failed to parse column picker rules"

答:
Okay, I found an answer myself. Hope that is okay.

In my input sheet, the title was something like this "Interest Rate %". Looks like azure was trying to say that it does not like special characters it the column names.

I edited my original csv file in excel, and removed the % in all the titles.

Then, created a new data store. problem solved.


问:
Alternative to the HTML Bold tag
Okay, so I know that in HTML you can use the  tag, but isn't there a "weight=bold" attribute that I can use in the
 tag?

Or is that in CSS, or Javascript?

答:
You can use following :

```<code><p id="p1">Some Text here </p>
#p1{
   font-weight: bold;
}
</code>```

OR

```<code><Strong><p>Some text here </p></strong>
</code>```

OR

You can use
 tag which is somewhat similar to bold

OwnerDisplayName: Learner

LastEditorDisplayName: Cerebrus

Title: Alternative to the HTML Bold tag

Body:
You can use following :

<p id="p1">Some Text here </p>
#p1{
   font-weight: bold;
}

OR

<Strong><p>Some text here </p></strong>

OR

You can use <h1> tag which is somewhat similar to bold


问:
Using replace and pathArray[0], I seem to be adding rather than replacing with my JavaScript
I have made a simple browser extension and have a manifest.json file that runs through a background.js file into my JavaScript file, which has this code

var l=location;
var str2='/edit';

var pathArray = l.pathname.split('/');
var secondLevelLocation = pathArray[1];

pathArray[1] = 'node';

l.href=l.origin.replace(l.origin, pathArray[1])+l.pathname.concat(str2);```

But rather than replacing pathArray[1], it's adding to the url.

For example, the script is taking: https://mywebiste.com/items/1234;
and replacing with: https://mywebiste.com/items/node/items/1234/edit

However, the intended output is: https://mywebiste.com/node/1234/edit

Updated

Following comments on incorrect array number, I've updated my script but naturally it doesn't fix the issue.

答:
The simplest approach:

// emulating window.location
var l = {
  "href": "https://mywebiste.com/items/1234"
};

console.log("Input:", l.href);
console.log("Output:", l.href.replace(/items/i, "node") + "/edit");```

Body:
I have made a simple browser extension and have a manifest.json file that runs through a background.js file into my JavaScript file, which has this code

var l=location;
var str2='/edit';

var pathArray = l.pathname.split('/');
var secondLevelLocation = pathArray[1];

pathArray[1] = 'node';

l.href=l.origin.replace(l.origin, pathArray[1])+l.pathname.concat(str2);

But rather than replacing pathArray[1], it's adding to the url.

For example, the script is taking: https://mywebiste.com/items/1234;
and replacing with: https://mywebiste.com/items/node/items/1234/edit

However, the intended output is: https://mywebiste.com/node/1234/edit

Updated

Following comments on incorrect array number, I've updated my script but naturally it doesn't fix the issue.


问:
How to access the values inside resolved promises?
I'm having difficulty accessing the values from getPeople(0,4).

```<code>function getPeople(start, end) {
    const peopleArray = [];
    for (let i = start; i <= end; i++) {
      peopleArray.push(
        axios.get(`https://www.testsite.net/api/test/workers/${i}`)
      );
    }
    return peopleArray;
  }

  useEffect(() => {
    Promise.all([getData(), getPeople(0, 4)]).then(item => {
      //console.log(item[0].data.orders); //
      setData(item);
      setPersonData(item);
    });
  }, []);
</code>```

item[0] works fine.
Here's the result I'm getting when I console.log(item[1]) How can I access the data?

item[1] is an array of promises.

答:
You simply need to spread the array returned from getPeople() like so:

Promise.all([getData(), ...getPeople(0, 4)]).then(item => {
    console.log(item);
});
```

Promise.all() expects an array of Promise, you were passing an array containing another array.

Body:
I'm having difficulty accessing the values from getPeople(0,4).

function getPeople(start, end) {
    const peopleArray = [];
    for (let i = start; i <= end; i++) {
      peopleArray.push(
        axios.get(`https://www.testsite.net/api/test/workers/${i}`)
      );
    }
    return peopleArray;
  }

  useEffect(() => {
    Promise.all([getData(), getPeople(0, 4)]).then(item => {
      //console.log(item[0].data.orders); //
      setData(item);
      setPersonData(item);
    });
  }, []);

item[0] works fine.
Here's the result I'm getting when I console.log(item[1]) How can I access the data?

item[1] is an array of promises.

Body:
You simply need to spread the array returned from getPeople() like so:

Promise.all([getData(), ...getPeople(0, 4)]).then(item => {
    console.log(item);
});

Promise.all() expects an array of Promise, you were passing an array containing another array.


答:
This simply builds a temp array using the values from your 2 arrays.

Because we use values of $a1 as the key, dups get overwritten and therefore lost. The array_keys_exists() check makes sure the first Dup is used and not subsequent dups. Then we just split the array into the two input arrays.

```<code>$a1 = ['Brian', 'A', 'Leo', 'A', 'Mike'];
$a2 = [1,2,3,4,5];

#temp array created using values of $a1 as key so dups get dropped because they are reused

foreach ($a1 as $i=>$a) {
    if ( ! array_key_exists($a, $new)){
        $new[$a] = $a2[$i];
    }
}
$a1 = array_keys($new);
$a2 = array_values($new);

print_r($a1);
print_r($a2);
</code>```

RESULT:

```<code>Array
(
    [0] => Brian
    [1] => A
    [2] => Leo
    [3] => Mike
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
)
</code>```

Title: find, save and remove duplicate values from more then one array

Body:
This simply builds a temp array using the values from your 2 arrays.

Because we use values of $a1 as the key, dups get overwritten and therefore lost. The array_keys_exists() check makes sure the first Dup is used and not subsequent dups. Then we just split the array into the two input arrays.

$a1 = ['Brian', 'A', 'Leo', 'A', 'Mike'];
$a2 = [1,2,3,4,5];

#temp array created using values of $a1 as key so dups get dropped because they are reused

foreach ($a1 as $i=>$a) {
    if ( ! array_key_exists($a, $new)){
        $new[$a] = $a2[$i];
    }
}
$a1 = array_keys($new);
$a2 = array_values($new);

print_r($a1);
print_r($a2);

RESULT:

Array
(
    [0] => Brian
    [1] => A
    [2] => Leo
    [3] => Mike
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
)


问:
to display student details from and list of array,by validating or using a 6 digit string of code in php?
`

<!DOCTYPE html>

 <title>string checker</title>

 <?php

 $student_1 =array("name"=>"deepak","bc"=>"bca","year"=>2,"e_roll"=>001);
 $student_2 = array("name"=>"aditya","bs"=>"bs-it","year"=>2,"e_roll"=>002);
 $student_3 = array("name"=>"kissan","mc"=>"mca","year"=>3,"e_roll"=>003);
 $student_4 = array("name"=>"Shubham","bc"=>"bca","year"=>1,"e_roll"=>004);
 $student_5 = array("name"=>"vivek","bc"=>"bca","year"=>3,"e_roll"=>005);
 $student_6 = array("name"=>"rohit","mc"=>"mca","year"=>2,"e_roll"=>0003);

 $test_1="bc1001";
 $test_2="mc2003";
 $test_3="bs2002";

 $test_1 = str_replace(array_keys($student_1),$student_1,$test_1);

 ?>

```

using test_1 i want to  display student_1 details

`we have a 6 character alpha-numerical string.
1st two-character represents a program or course he/she pursuing**(eg; bs-BSC(it),bc-BCA,mc-MCA)**.
next char represents in which year he/she studying.
and remaining char represents roll no.

sample of the string is bc1001 should display student name course as BCA, year first and roll no 001

答:
You can use substr() to get the portions of the string that you want to compare, then do what you want with them from there. The manual can provide more specific usage of substr: https://www.php.net/manual/en/function.substr.php

Ex:

```<code>$course = substr('bc1001', 0, 2); // will output "bc"
</code>```

Body:
`

<!DOCTYPE html>

 <title>string checker</title>

 <?php

 $student_1 =array("name"=>"deepak","bc"=>"bca","year"=>2,"e_roll"=>001);
 $student_2 = array("name"=>"aditya","bs"=>"bs-it","year"=>2,"e_roll"=>002);
 $student_3 = array("name"=>"kissan","mc"=>"mca","year"=>3,"e_roll"=>003);
 $student_4 = array("name"=>"Shubham","bc"=>"bca","year"=>1,"e_roll"=>004);
 $student_5 = array("name"=>"vivek","bc"=>"bca","year"=>3,"e_roll"=>005);
 $student_6 = array("name"=>"rohit","mc"=>"mca","year"=>2,"e_roll"=>0003);

 $test_1="bc1001";
 $test_2="mc2003";
 $test_3="bs2002";

 $test_1 = str_replace(array_keys($student_1),$student_1,$test_1);

 ?>

using test_1 i want to  display student_1 details

`we have a 6 character alpha-numerical string.
1st two-character represents a program or course he/she pursuing**(eg; bs-BSC(it),bc-BCA,mc-MCA)**.
next char represents in which year he/she studying.
and remaining char represents roll no.

sample of the string is bc1001 should display student name course as BCA, year first and roll no 001

Body:
You can use substr() to get the portions of the string that you want to compare, then do what you want with them from there. The manual can provide more specific usage of substr: https://www.php.net/manual/en/function.substr.php

Ex:

$course = substr('bc1001', 0, 2); // will output "bc"


问:
Why is my javascript function not found by the page it is embedded in?
I have a page that has a simple javascript in the header portion of the page:

```<code><script type="text/javascript">
    function doLogout() {
        var conf = confirm("Really log out?");
        if (conf === true) {      //changed == to === for boolean comparison
            $.post("logout.aspx");
        }
    }
</script>
</code>```

It uses jQuery to do an AJAX post to my logout page.  The only issue right now is that when I click on the link (logout) to fire this function, nothing happens.  I checked FireBug's console, and it told me that the function is not defined.  This has happened to me before, but I think I botched a bunch of code to fix it sometimes.

Does anyone know the proper way to fix this issue?

Edit

After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise!  Hopefully this information will be useful for more people.

答: The issue might occur if you have NoScript. You should check and make sure it's not blocking said script. </p>

OwnerDisplayName: Anders

ContentLicense: CC BY-SA 2.5

Body:
I have a page that has a simple javascript in the header portion of the page:

It uses jQuery to do an AJAX post to my logout page.  The only issue right now is that when I click on the link (logout) to fire this function, nothing happens.  I checked FireBug's console, and it told me that the function is not defined.  This has happened to me before, but I think I botched a bunch of code to fix it sometimes.

Does anyone know the proper way to fix this issue?

Edit

After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise!  Hopefully this information will be useful for more people.

LastEditorDisplayName: Anders

OwnerDisplayName: R. Bemrose


问:
Large Binary (byte[]) File transfer through WCF
I am trying to build a WCF service that allows me to send large binary files from clients to the service.

However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond)

The Error I get if I try to send the 4.91MB file is:

Exception Message: An error occurred while receiving the HTTP response to http://localhost:56198/Service.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Inner Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.

Inner Exception Message: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Inner Exception Message: An existing connection was forcibly closed by the remote host

This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method.

I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error.

I am going to paste my  sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well.

Service Web.Config

```<code><system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00"
      openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
      messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
        maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
    <services>
        <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService">
                <identity>
                    <dns value="localhost"/>
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="DragDrop.Service.ServiceBehavior">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>
</code>```

Client (Asp.net page) Web.Config

```<code><system.serviceModel>
<bindings>
   <basicHttpBinding>
      <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
         openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
         allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
         maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
         messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse"
         useDefaultWebProxy="true">
         <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
            maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
         <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
               realm="">
               <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
            <message clientCredentialType="UserName" algorithmSuite="Default" />
         </security>
      </binding>
   </basicHttpBinding>
</bindings>

<behaviors>
  <endpointBehaviors>
    <behavior name="debuggingBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483646" />
    </behavior>
  </endpointBehaviors>
</behaviors>

<client>
   <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding"
      bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService"
      name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" />
</client>
</system.serviceModel>
</code>```

答:
As pointed out, try using Streaming Transfer, here's some example code showing both sending and receiving (possibly) large amounts of data using streamed transfer.

Use a binding like this, notice the MaxReceivedMessageSize and TranferMode settings.

```<code><binding name="Streaming_Binding" maxReceivedMessageSize="67108864"
    messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed">
</binding>
</code>```

Add some service code:

```<code>[OperationContract]
public Stream GetLargeFile()
{
    return new FileStream(path, FileMode.Open, FileAccess.Read);
}

[OperationContract]
public void SendLargeFile(Stream stream)
{
    // Handle stream here - e.g. save to disk
    ProcessTheStream(stream);

    // Close the stream when done processing it
    stream.Close();
}
</code>```

And some client code:

```<code>public Stream GetLargeFile()
{
    var client = /* create proxy here */;
    try
    {
        var response = client.GetLargeFile();

        // All communication is now handled by the stream,
        // thus we can close the proxy at this point
        client.Close();

        return response;
    }
    catch (Exception)
    {
        client.Abort();
        throw;
    }
}

public void SendLargeFile(string path)
{
    var client = /* create proxy here */;
    client.SendLargeFile(new FileStream(path, FileMode.Open, FileAccess.Read));
}
</code>```

Also, make sure you are not getting a timeout, a large file might take a while to transfer (the default receiveTimeout is 10 minutes though).

You can download Microsoft WCF/WF sample code here (top C# link is broken at the time of writing but other samples code seems ok).

Body:
I am trying to build a WCF service that allows me to send large binary files from clients to the service.

However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond)

The Error I get if I try to send the 4.91MB file is:

Exception Message: An error occurred while receiving the HTTP response to http://localhost:56198/Service.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Inner Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.

Inner Exception Message: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Inner Exception Message: An existing connection was forcibly closed by the remote host

This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method.

I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error.

I am going to paste my  sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well.

Service Web.Config

<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00"
      openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
      messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
        maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
    <services>
        <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService">
                <identity>
                    <dns value="localhost"/>
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="DragDrop.Service.ServiceBehavior">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

Client (Asp.net page) Web.Config

<system.serviceModel>
<bindings>
   <basicHttpBinding>
      <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
         openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
         allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
         maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
         messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse"
         useDefaultWebProxy="true">
         <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
            maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
         <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
               realm="">
               <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
            <message clientCredentialType="UserName" algorithmSuite="Default" />
         </security>
      </binding>
   </basicHttpBinding>
</bindings>

<behaviors>
  <endpointBehaviors>
    <behavior name="debuggingBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483646" />
    </behavior>
  </endpointBehaviors>
</behaviors>

<client>
   <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding"
      bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService"
      name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" />
</client>
</system.serviceModel>

Body:
As pointed out, try using Streaming Transfer, here's some example code showing both sending and receiving (possibly) large amounts of data using streamed transfer.

Use a binding like this, notice the MaxReceivedMessageSize and TranferMode settings.

<binding name="Streaming_Binding" maxReceivedMessageSize="67108864"
    messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed">
</binding>

Add some service code:

[OperationContract]
public Stream GetLargeFile()
{
    return new FileStream(path, FileMode.Open, FileAccess.Read);
}

[OperationContract]
public void SendLargeFile(Stream stream)
{
    // Handle stream here - e.g. save to disk
    ProcessTheStream(stream);

    // Close the stream when done processing it
    stream.Close();
}

And some client code:

public Stream GetLargeFile()
{
    var client = /* create proxy here */;
    try
    {
        var response = client.GetLargeFile();

        // All communication is now handled by the stream,
        // thus we can close the proxy at this point
        client.Close();

        return response;
    }
    catch (Exception)
    {
        client.Abort();
        throw;
    }
}

public void SendLargeFile(string path)
{
    var client = /* create proxy here */;
    client.SendLargeFile(new FileStream(path, FileMode.Open, FileAccess.Read));
}

Also, make sure you are not getting a timeout, a large file might take a while to transfer (the default receiveTimeout is 10 minutes though).

You can download Microsoft WCF/WF sample code here (top C# link is broken at the time of writing but other samples code seems ok).


问:
Displaying results for items that have value in one of the field in the table
Is there a way to display content based on th value in the table field? Lets say that I have a field in my table called label, which isnt obligatory to fill in, can I filter the content based on if that field is populated for specific item? Item that has that field populated would be displayed and item with that field left blank wouldnt.

model.py:

```<code>class Item(models.Model):
  title = models.CharField(max_length=100)
  price = models.FloatField()
  discount_price = models.FloatField(blank=True, null=True)
  category = models.ManyToManyField(Category, blank=True)
  label = models.ManyToManyField(Label, blank=True)
  slug = models.SlugField(unique=True)
  description = models.TextField()
  image = models.ImageField()
</code>```

views.py:

```<code>def HomeView(request):
  item_list = Item.objects.all()
  context = {
    'item_list': item_list,
  }
  return render(request, "home.html", context)
</code>```

答:
If I understand correctly, you want to have the Items where label is not None? Then you could try this:

item_list = Item.objects.exclude(label=None)
```

Body:
Is there a way to display content based on th value in the table field? Lets say that I have a field in my table called label, which isnt obligatory to fill in, can I filter the content based on if that field is populated for specific item? Item that has that field populated would be displayed and item with that field left blank wouldnt.

model.py:

class Item(models.Model):
  title = models.CharField(max_length=100)
  price = models.FloatField()
  discount_price = models.FloatField(blank=True, null=True)
  category = models.ManyToManyField(Category, blank=True)
  label = models.ManyToManyField(Label, blank=True)
  slug = models.SlugField(unique=True)
  description = models.TextField()
  image = models.ImageField()

views.py:

def HomeView(request):
  item_list = Item.objects.all()
  context = {
    'item_list': item_list,
  }
  return render(request, "home.html", context)


问:
Value return null when search a value using query firebase android studio
I want to ask, so I want to search a value which are an ID barcode on firebase. I try search on stackoverflow which using this line code.

```<code> tindakan = FirebaseDatabase.getInstance().getReference("tindakan");
 bedahMulut = tindakan.child("Bedah Mulut");

 Query searchByID = tindakan.orderByChild("ID").equalTo(idBarcode);

 searchByID.addValueEventListener(new ValueEventListener() {
     @Override
     public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
         for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
             Log.v("hasil", "Found! -> " + idSnapshot.child("ID").getValue(String.class));
         }
     }

     @Override
     public void onCancelled(@NonNull DatabaseError databaseError) {
         Log.v("hasil", databaseError.toException().toString());
     }
 });
</code>```

but this code are return null value, I already post structure firebase and debug session in below. Please help me in advance, thank you :)

答:
It looks like you're trying to query a deeply nested data structure, which is not possible. Firebase Realtime Database queries operate on a flat list, where the property/value you order/filter on is at a fixed path under each direct child node.

The solution is typically to create an additional data structure, where you keep a simple list of IDs and then the value is the path of the node that has that ID.

```<code>"IDs": {
  "INLAY": "/tindakan/Konservasi/Inlay/Kelas -"
}
</code>```

See

Firebase Query Double Nested

Correct JSON structure to filter through data

Firebase Query all users with nested childs , with conditions (Nodejs)

Firebase query orderByChild

How does .indexOn works with users and unique keys?

Body:
I want to ask, so I want to search a value which are an ID barcode on firebase. I try search on stackoverflow which using this line code.

 tindakan = FirebaseDatabase.getInstance().getReference("tindakan");
 bedahMulut = tindakan.child("Bedah Mulut");

 Query searchByID = tindakan.orderByChild("ID").equalTo(idBarcode);

 searchByID.addValueEventListener(new ValueEventListener() {
     @Override
     public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
         for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
             Log.v("hasil", "Found! -> " + idSnapshot.child("ID").getValue(String.class));
         }
     }

     @Override
     public void onCancelled(@NonNull DatabaseError databaseError) {
         Log.v("hasil", databaseError.toException().toString());
     }
 });

but this code are return null value, I already post structure firebase and debug session in below. Please help me in advance, thank you :)

Body:
It looks like you're trying to query a deeply nested data structure, which is not possible. Firebase Realtime Database queries operate on a flat list, where the property/value you order/filter on is at a fixed path under each direct child node.

The solution is typically to create an additional data structure, where you keep a simple list of IDs and then the value is the path of the node that has that ID.

"IDs": {
  "INLAY": "/tindakan/Konservasi/Inlay/Kelas -"
}

See

Firebase Query Double Nested

Correct JSON structure to filter through data

Firebase Query all users with nested childs , with conditions (Nodejs)

Firebase query orderByChild

How does .indexOn works with users and unique keys?


问:
Proper way to create a singleton service in ASP.NET Core - does it have to use the static keyword, or not?
This is really confusing for me. Nothing is stopping us from creating a class with instance fields and
instance methods, versus creating a class with static fields and static methods. Both can be registered as a singleton.

Is there a preferred approach to this problem, and why?

EDIT: I'm not asking about creating a class using the singleton pattern. I'm asking about singleton dependency injecting a class versus injecting the same class but with static defined members/fields/methods/properties.

答:
You need to understand the different lifetimes for DI and your needs, in order to choose the proper life span.

Transient services are created each time the service is requested (So if in 1 request, a service is used 2 times, it will be created 2 times).

Scoped services are created per web request (So if in 1 request, a service is used 2 times, it will be created only once).

Singleton is an instance that will last the entire lifetime of the application (All requests will share this one instance).

If in doubt, make it transient.

EDIT

I guess its worth to mention that if you create a services as Transient and they have static properties which you constantly change, then this will affect every other created instance, since static affects the type itself, rather than an instance.


问:
iphone categorization problem
I'll make a simple app with these features;

In main windows there will be a menu.

```<code>Menu Item 1
Menu Item 2
Menu Item 3
</code>```

When user click Menu Item 1

a new menu based view should appear, however when user clicked menu item 2, a text based view should appear.

I made a navigation based app, but i couldn't connect different view file for each cell.

How can i do this ? Have you got any example ?

My app:

```<code>Menu Item 1
- Menu Item 1.1
- Text
- Menu Item 1.2
- Menu Item 1.2.1
- Text
- Menu Item 1.2.2
- Text
Menu Item 2
- Text

...
..
.
</code>```

(probably i will use sqlite for context of menu and texts.)

答:
See

http://developer.apple.com/library/ios/#documentation/uikit/reference/UINavigationController_Class/Reference/Reference.html

and the associated sample code, this is a good one.

http://developer.apple.com/library/ios/#samplecode/WorldCities/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009466

Title: iphone categorization problem

Body:
I'll make a simple app with these features;

In main windows there will be a menu.

Menu Item 1
Menu Item 2
Menu Item 3

When user click Menu Item 1

a new menu based view should appear, however when user clicked menu item 2, a text based view should appear.

I made a navigation based app, but i couldn't connect different view file for each cell.

How can i do this ? Have you got any example ?

My app:

Menu Item 1
- Menu Item 1.1
- Text
- Menu Item 1.2
- Menu Item 1.2.1
- Text
- Menu Item 1.2.2
- Text
Menu Item 2
- Text

...
..
.

(probably i will use sqlite for context of menu and texts.)


问:
How can I catch programmer error with malloc?
I'm trying to find a way to catch a programmer error in the argument for malloc in an automated code tester.

For example:

```<code>struct Pepe* p = malloc(sizeof(struct Pepe*));
</code>```

This, of course, compiles without any problems. The thing is that struct Pepe has another struct of the same size inside it, therefore no problem appears during execution (nor with free).

The correct code should be:

```<code>struct Pepe* p = malloc(sizeof(struct Pepe));
</code>```

Can we get a warning or something to catch this problem?

I tried -Wall and -Wextra but there was no warning.

答:
You can use the clang static analyzer for that. Consider the following (buggy) code:

```<code>#include <stdlib.h>

struct foo {
    int a,b;
};

int main (void) {
    struct foo *bar = malloc(sizeof(struct foo *));

    free(bar);
}
</code>```

Now you can invoke the clang static analyzer:

```<code>$ scan-build clang src.c
</code>```

and get the following warning:

```<code>src.c:10:20: warning: Result of 'malloc' is converted to a pointer of type 'struct foo', which is incompatible with sizeof operand type 'struct foo *'
        struct foo *bar = malloc(sizeof(struct foo *));
        ~~~~~~~~~~~~      ^~~~~~ ~~~~~~~~~~~~~~~~~~~~
1 warning generated.
scan-build: 1 bug found.
</code>```

The clang static analyzer is bundled with many linux distributions in the package clang-tools. The homepage can be found here

Body:
I'm trying to find a way to catch a programmer error in the argument for malloc in an automated code tester.

For example:

struct Pepe* p = malloc(sizeof(struct Pepe*));

This, of course, compiles without any problems. The thing is that struct Pepe has another struct of the same size inside it, therefore no problem appears during execution (nor with free).

The correct code should be:

struct Pepe* p = malloc(sizeof(struct Pepe));

Can we get a warning or something to catch this problem?

I tried -Wall and -Wextra but there was no warning.

Body:
You can use the clang static analyzer for that. Consider the following (buggy) code:

#include <stdlib.h>

struct foo {
    int a,b;
};

int main (void) {
    struct foo *bar = malloc(sizeof(struct foo *));

    free(bar);
}

Now you can invoke the clang static analyzer:

$ scan-build clang src.c

and get the following warning:

src.c:10:20: warning: Result of 'malloc' is converted to a pointer of type 'struct foo', which is incompatible with sizeof operand type 'struct foo *'
        struct foo *bar = malloc(sizeof(struct foo *));
        ~~~~~~~~~~~~      ^~~~~~ ~~~~~~~~~~~~~~~~~~~~
1 warning generated.
scan-build: 1 bug found.

The clang static analyzer is bundled with many linux distributions in the package clang-tools. The homepage can be found here


问:
Jenkins does not wait for docker exec command to complete
Here's the situation:

I have a docker container (jenkins). I've mounted the sockets to my container so that I can perform docker commands inside my jenkins container.

Manually, everything works in the container. However, when Jenkins executes the job, it doesn't "wait" for the docker exec command to run to completion.

Below, is an extract from the Jenkinsfile. The short-lived printenv command runs correctly, and prints the environment variables. The next command (python) just gets run and then Jenkins moves on immediately, not waiting for completion. The Jenkins agent (slave) is running on an Ubuntu image. Running all these commands outside Jenkins work as expected.

```<code>echo "Running the app docker container in detached tty mode to keep it up"
docker run --detach --tty --name "${CONTAINER_NAME}" "${IMAGE_NAME}"

echo "Listing environment variables"
docker exec --interactive "${CONTAINER_NAME}" bash -c "printenv"

echo "Running test coverage"
docker exec --interactive "${CONTAINER_NAME}" bash -c "python -m coverage run --source . --branch -m pytest -vs"
</code>```

It seems maybe related to this question.

Please can anyone explain how to get Jenkins to wait for the docker exec command to complete before proceeding to the next step.

Have considered alternatives, like the Docker Pipeline Plugin, but would much prefer to use something close to what I have above where possible.

Ok, another approach, I've tried using Docker Pipeline plugin here.

答:
Ugh. This was down to the way that I'd set up docker support on the slave container.

I'd used socat to provide a TCP server proxy. Instead, switched that out for a plain old docker.sock volume between host & container.

```<code>volumes:
  - /var/run/docker.sock:/var/run/docker.sock
</code>```

The very first time, I had to also sort out a permissions issue by doing (inside the container):

```<code>rm -Rf ~/.docker
chmod 666 /var/run/docker.sock
</code>```

After that, everything "just worked". Very painful experience.

Body:
Here's the situation:

I have a docker container (jenkins). I've mounted the sockets to my container so that I can perform docker commands inside my jenkins container.

Manually, everything works in the container. However, when Jenkins executes the job, it doesn't "wait" for the docker exec command to run to completion.

Below, is an extract from the Jenkinsfile. The short-lived printenv command runs correctly, and prints the environment variables. The next command (python) just gets run and then Jenkins moves on immediately, not waiting for completion. The Jenkins agent (slave) is running on an Ubuntu image. Running all these commands outside Jenkins work as expected.

echo "Running the app docker container in detached tty mode to keep it up"
docker run --detach --tty --name "${CONTAINER_NAME}" "${IMAGE_NAME}"

echo "Listing environment variables"
docker exec --interactive "${CONTAINER_NAME}" bash -c "printenv"

echo "Running test coverage"
docker exec --interactive "${CONTAINER_NAME}" bash -c "python -m coverage run --source . --branch -m pytest -vs"

It seems maybe related to this question.

Please can anyone explain how to get Jenkins to wait for the docker exec command to complete before proceeding to the next step.

Have considered alternatives, like the Docker Pipeline Plugin, but would much prefer to use something close to what I have above where possible.

Ok, another approach, I've tried using Docker Pipeline plugin here.

Body:
Ugh. This was down to the way that I'd set up docker support on the slave container.

I'd used socat to provide a TCP server proxy. Instead, switched that out for a plain old docker.sock volume between host & container.

volumes:
  - /var/run/docker.sock:/var/run/docker.sock

The very first time, I had to also sort out a permissions issue by doing (inside the container):

rm -Rf ~/.docker
chmod 666 /var/run/docker.sock

After that, everything "just worked". Very painful experience.


问:
Django test runner not finding tests
I am new to both Python and Django and I'm learning by creating a diet management site but I've been completely defeated by getting my unit tests to run.  All the docs and blogs I've found say that as long as it's discoverable from tests.py, tests.py is in the same folder as models.py and your test class subclasses TestCase, it should all get picked up automatically.  This isn't working for me, when I run manage.py test <myapp> it doesn't find any tests.

I started with all my tests in their own package but have simplified it down to all tests just being in my tests.py file.  The current tests.py looks like:

```<code>import unittest
from pyDietTracker.models import Weight
from pyDietTracker.weight.DisplayDataAdapters import DisplayWeight

class TestDisplayWeight(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testGetWeightInStone_KG_Correctly_Converted(self):
        weight = Weight()
        weight.weight = 99.8

        testAdapter = DisplayWeight(weight)
        self.assertEquals(testAdapter.GetWeightInStone(), '15 st 10 lb')
</code>```

I have tried it by subclassing the Django TestCase class as well but this didn't work either.  I'm using Django 1.1.1, Python 2.6 and I'm running Snow Leopard.

I'm sure I am missing something very basic and obvious but I just can't work out what. Any ideas?

Edit:  Just a quick update after a comment

```<code>INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'pyDietTracker',
 )
</code>```

To get the tests to run I am running manage.py test pyDietTracker

答:
If you encounter this error after upgrading to Django 3, it might be because the -k parameter changed meaning from:

```<code>-k, --keepdb          Preserves the test DB between runs.
</code>```

to

```<code>-k TEST_NAME_PATTERNS   Only run test methods and classes that match the pattern or substring. Can be used multiple times. Same as unittest -k option.
</code>```

So just replace -k with --keepdb to make it work again.

Title: Django test runner not finding tests

Body:
I am new to both Python and Django and I'm learning by creating a diet management site but I've been completely defeated by getting my unit tests to run.  All the docs and blogs I've found say that as long as it's discoverable from tests.py, tests.py is in the same folder as models.py and your test class subclasses TestCase, it should all get picked up automatically.  This isn't working for me, when I run manage.py test <myapp> it doesn't find any tests.

I started with all my tests in their own package but have simplified it down to all tests just being in my tests.py file.  The current tests.py looks like:

import unittest
from pyDietTracker.models import Weight
from pyDietTracker.weight.DisplayDataAdapters import DisplayWeight

class TestDisplayWeight(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testGetWeightInStone_KG_Correctly_Converted(self):
        weight = Weight()
        weight.weight = 99.8

        testAdapter = DisplayWeight(weight)
        self.assertEquals(testAdapter.GetWeightInStone(), '15 st 10 lb')

I have tried it by subclassing the Django TestCase class as well but this didn't work either.  I'm using Django 1.1.1, Python 2.6 and I'm running Snow Leopard.

I'm sure I am missing something very basic and obvious but I just can't work out what. Any ideas?

Edit:  Just a quick update after a comment

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'pyDietTracker',
 )

To get the tests to run I am running manage.py test pyDietTracker

Body:
If you encounter this error after upgrading to Django 3, it might be because the -k parameter changed meaning from:

-k, --keepdb          Preserves the test DB between runs.

to

-k TEST_NAME_PATTERNS   Only run test methods and classes that match the pattern or substring. Can be used multiple times. Same as unittest -k option.

So just replace -k with --keepdb to make it work again.


问:
Setting unordered_map as value for unordered_map
So I am trying to set an unordered_map as value for another unordered_map.
Now I have the problem that I am not able to put values into the second unordered_map.
My code looks like this.

```<code>  std::string postCode;
  std::string[] postCodeSource = new std::string{1111,2222,3333,4444};
  std::unordered_map<std::string,unordered_map<int,Foo*>*> data;
  int k1=1234;//can be any number
  for(int i = 0; i < 4; i++){
    postCode = postCodeSource[i]
    if(data[postCode]==NULL) {
      data[postCode]=new std::unordered_map<int,Foo*>();
    }
    data[postCode]->at(int(k1)) = new Foo(postCodeSource[i]);
  }
</code>```

classes:

```<code>class Foo{
  public:
  Foo();
  Foo(std::string postCode);
  std::string firstName,Customername,postCode;
}
</code>```

Foo(std::string postCode); is a simple copy constructor.

Now when I reach data[lastPlz.getString()]->at(int(k1.customer)) = new Foo(&k1); I get an out of range exception from unordered_map which makes sense since there is no object at k1.customer yet!
Before I changed the code I created and filled a pointer looking like that.

```<code>std::unordered_map<int,Foo*> kdnrMap
kdnrMap[k1.customer] = new Foo(&k1);
</code>```

and later on, I added kdnrMap to data.
That won't work anymore the way I intended since this method would need a completely filled kdnrMap before I can add it to data which I can't do anymore.

So I am looking for help to get kdnrMap filled I've tried pretty much anything I could think of for now.

答:
You don't really need to store the inner map as a pointer. Just let the outer map own the inner one like this:

```<code>std::unordered_map<std::string,
   std::unordered_map<int, std::unique_ptr<Foo>>> data;
data[postCode][int(k1.Kundennr)] = new Foo(&k1);
</code>```

I advise against using raw pointers here, since there is a high risk of leaking memory if you replace a value in the inner map. Using std::unique_ptr makes it so much simpler to deal with pointers.

Your exception probably happens because unordered_map::at requires the value to contain the key you are asking for, in order to retrieve the reference to the value it is mapping. If you use operator[] instead like in my example, the map will create an entry if the key is not found.

If you still insist on having the outer map's values to be pointers to the inner map, then you can add elements like this:

```<code>std::unordered_map<int, Foo*> &inner = *data[postCode];
inner[int(k1.Kundennr)] = new Foo(&k1);
</code>```

or

```<code>data[postCode]->operator[](int(k1.Kundennr)) = new Foo(&k1);
</code>```

Body:
So I am trying to set an unordered_map as value for another unordered_map.
Now I have the problem that I am not able to put values into the second unordered_map.
My code looks like this.

  std::string postCode;
  std::string[] postCodeSource = new std::string{1111,2222,3333,4444};
  std::unordered_map<std::string,unordered_map<int,Foo*>*> data;
  int k1=1234;//can be any number
  for(int i = 0; i < 4; i++){
    postCode = postCodeSource[i]
    if(data[postCode]==NULL) {
      data[postCode]=new std::unordered_map<int,Foo*>();
    }
    data[postCode]->at(int(k1)) = new Foo(postCodeSource[i]);
  }

classes:

class Foo{
  public:
  Foo();
  Foo(std::string postCode);
  std::string firstName,Customername,postCode;
}

Foo(std::string postCode); is a simple copy constructor.

Now when I reach data[lastPlz.getString()]->at(int(k1.customer)) = new Foo(&k1); I get an out of range exception from unordered_map which makes sense since there is no object at k1.customer yet!
Before I changed the code I created and filled a pointer looking like that.

std::unordered_map<int,Foo*> kdnrMap
kdnrMap[k1.customer] = new Foo(&k1);

and later on, I added kdnrMap to data.
That won't work anymore the way I intended since this method would need a completely filled kdnrMap before I can add it to data which I can't do anymore.

So I am looking for help to get kdnrMap filled I've tried pretty much anything I could think of for now.

Body:
You don't really need to store the inner map as a pointer. Just let the outer map own the inner one like this:

std::unordered_map<std::string,
   std::unordered_map<int, std::unique_ptr<Foo>>> data;
data[postCode][int(k1.Kundennr)] = new Foo(&k1);

I advise against using raw pointers here, since there is a high risk of leaking memory if you replace a value in the inner map. Using std::unique_ptr makes it so much simpler to deal with pointers.

Your exception probably happens because unordered_map::at requires the value to contain the key you are asking for, in order to retrieve the reference to the value it is mapping. If you use operator[] instead like in my example, the map will create an entry if the key is not found.

If you still insist on having the outer map's values to be pointers to the inner map, then you can add elements like this:

std::unordered_map<int, Foo*> &inner = *data[postCode];
inner[int(k1.Kundennr)] = new Foo(&k1);

or

data[postCode]->operator[](int(k1.Kundennr)) = new Foo(&k1);