问:
How to render images from an array using the map() method?
I'm trying to render my images that I stored in my array by using the map() method. Unfortunately I'm getting error when I'm trying to render the image from array but without using mapping I could render the images but I need to write the codes line by line. Could anyone help me with the solution?

```<code>const CardList = ({robots}) => {
const cardComponent = robots.map((user, i) => {
    return <Card src={robots[i].src} id={robots[i].id} name={robots[i].name} email={robots[i].email}/>
})
return(
    <div>
    {cardComponent}
    </div>
);
</code>```

My CardList Component

```<code>const Card = ({name, email, id, src}) => {

return(
   <div className='bg-light-green dib br3 pa3 ma2 grow bw db w-20'>
         <img className='personal ' alt='robots' src={require(`${src}`)}/>
        <div>
             <h1>{name}</h1>
            <p>{email}</p>
        </div>
    </div>
)
</code>```

My Card Component
i feel there is something wrong with src={require(${src})}

and this is the error that i'm getting from react DOM:

答:
```<code>yourArray.map((key, data) => {
  <ComponentToDisplay id={key} {...this.props} />
});
</code>```

Body:
I'm trying to render my images that I stored in my array by using the map() method. Unfortunately I'm getting error when I'm trying to render the image from array but without using mapping I could render the images but I need to write the codes line by line. Could anyone help me with the solution?

const CardList = ({robots}) => {
const cardComponent = robots.map((user, i) => {
    return <Card src={robots[i].src} id={robots[i].id} name={robots[i].name} email={robots[i].email}/>
})
return(

    {cardComponent}

);

My CardList Component

const Card = ({name, email, id, src}) => {

return(

         <img className='personal ' alt='robots' src={require(`${src}`)}/>

{name}

{email}

)

My Card Component
i feel there is something wrong with src={require(${src})}

and this is the error that i'm getting from react DOM:


来源: stackexchange

问:
Is there a way to wait for batch process to complete in Mule 4?
I have a mule flow that runs a batch job. What I have found is that the batch job will branch and my flow will continue on. I would like to wait till the On Complete gets hit and return those results. I found that in older version there was a scope of run-and-wait. I don't see an equivalent in Mule 4. Any suggestion would be much appreciated.</p>

答:
Batch runs asynchronously with respect to the flow. That was the same in Mule 3.
I guess you could send a message to a VM queue in the onComplete stage and wait for it to be received on the flow.</p>

ContentLicense: CC BY-SA 4.0


问:
Shuffling an array or arrays in Objective-C
I have an array of integers, I want split this array into smaller arrays of integers, then put these smaller arrays into a new array, shuffle this new array, and repopulate the original array with the shuffled integers. The result will be a shuffled version of the original array, but each individual item will not be shuffled, instead chunks of the original will be shuffled.

I can do this in Java, C# so on, but new to Objective-C, so any examples would be helpful.

Here's what I have thus far:

```<code>NSMutableArray *chunks = [[NSMutableArray alloc] init];
for(int x = 0; x < [rawData count]; x += 400){
    NSMutableArray *chunk = [[NSMutableArray alloc] init];
    for(int y = 0; y < 400; y++){ //chunks of 400 items
        [chunk addObject:[NSNumber numberWithInt:rawData[x + y]]];
    }
    count ++;
}
//shuffle chunks
int index = 0;
for(int i = 0; i < [chunks count]; i ++ ){
    for (int y = 0; y < 400; y++) {
        //how do I put the chunks chunk back into the rawData[index]??
    }
}
</code>```

答:
This is what you're looking for (note that you count iterate to 400 in your second loop... you have to stop at 'chunk.count'):</p>

```<code>for(int i = 0; i < [chunks count]; i ++ ){
  NSMutableArray *chunk = [chunks objectAtIndex:i];
  for (int y = 0; y < [chunk count]; y++) {
    [rawData replaceObjectAtIndex:i*400+y withObject:[chunk objectAtIndex:y]];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array of integers, I want split this array into smaller arrays of integers, then put these smaller arrays into a new array, shuffle this new array, and repopulate the original array with the shuffled integers. The result will be a shuffled version of the original array, but each individual item will not be shuffled, instead chunks of the original will be shuffled.

I can do this in Java, C# so on, but new to Objective-C, so any examples would be helpful.

Here's what I have thus far:

NSMutableArray *chunks = [[NSMutableArray alloc] init];
for(int x = 0; x < [rawData count]; x += 400){
    NSMutableArray *chunk = [[NSMutableArray alloc] init];
    for(int y = 0; y < 400; y++){ //chunks of 400 items
        [chunk addObject:[NSNumber numberWithInt:rawData[x + y]]];
    }
    count ++;
}
//shuffle chunks
int index = 0;
for(int i = 0; i < [chunks count]; i ++ ){
    for (int y = 0; y < 400; y++) {
        //how do I put the chunks chunk back into the rawData[index]??
    }
}

Body:
This is what you're looking for (note that you count iterate to 400 in your second loop... you have to stop at 'chunk.count'):

for(int i = 0; i < [chunks count]; i ++ ){
  NSMutableArray *chunk = [chunks objectAtIndex:i];
  for (int y = 0; y < [chunk count]; y++) {
    [rawData replaceObjectAtIndex:i*400+y withObject:[chunk objectAtIndex:y]];


问:
Angular and Http Calls How to make an http call to keep trying until a success response is received?
We are migrating data from a system into another. These data are composed of two excel files.

The first one contains the basic/general information about a family, and the other is information about each member of each family.

The script is composed of two nested loops. The first loop will take a row from the excel, add it into the database then the second loop, will search for related members (using a unique ID for each family) and add them as well.

I wrapped the HTTP calls, inside promise. When a promise is resolved, we will move to the next step, if not, an array will be added to a log file saying that this row had an issue while uploading and we will check it later.

Sometimes, when handling HTTP calls from an observable, some of the calls will be ahead of others that should not be. Let us say, that family X is being added, and there is 5 HTTP calls are running, if one of them, had a late response and the initial loop is started with uploading info of family Y, the code will break, because of the structure of the new system we are migrating to.

Long story short, while uploading data, we receive an error 500: Internal Server Error without knowing the reason. But we expected that this is going to happen, so we did the following at our api.services.ts service:

```<code>postData(data) {
    const url = 'apiUrlForDataUpload';
    return this.http.post(url, data, this.httpOptions).pipe(retry(3), timeout(15000));
}
</code>```

I am specifying that in case the server returned an error, to repeat the call at least 3 times, and in case there was a network interruption, to wait for 15 seconds before skipping into next part.

The problem is that whenever the server returns an error, the loop will be broke and the call would not retry the process for 1 time at least not 3.

How to make an HTTP call to keep trying until a success response is received?

答:
You can use catchError and retry() (without the number).

        this.httpClient.get('http://doesnot.exist').pipe(
            tap(
                () => console.log('emit'),
                () => console.log('error'),
                () => console.log('complete'),
            ),
            // a short delay in a retry.
            catchError(error => timer(1500).pipe(switchMapTo(throwError(error)))),
            retry(),
        ).subscribe();
```

Body:
We are migrating data from a system into another. These data are composed of two excel files.

The first one contains the basic/general information about a family, and the other is information about each member of each family.

The script is composed of two nested loops. The first loop will take a row from the excel, add it into the database then the second loop, will search for related members (using a unique ID for each family) and add them as well.

I wrapped the HTTP calls, inside promise. When a promise is resolved, we will move to the next step, if not, an array will be added to a log file saying that this row had an issue while uploading and we will check it later.

Sometimes, when handling HTTP calls from an observable, some of the calls will be ahead of others that should not be. Let us say, that family X is being added, and there is 5 HTTP calls are running, if one of them, had a late response and the initial loop is started with uploading info of family Y, the code will break, because of the structure of the new system we are migrating to.

Long story short, while uploading data, we receive an error 500: Internal Server Error without knowing the reason. But we expected that this is going to happen, so we did the following at our api.services.ts service:

postData(data) {
    const url = 'apiUrlForDataUpload';
    return this.http.post(url, data, this.httpOptions).pipe(retry(3), timeout(15000));
}

I am specifying that in case the server returned an error, to repeat the call at least 3 times, and in case there was a network interruption, to wait for 15 seconds before skipping into next part.

The problem is that whenever the server returns an error, the loop will be broke and the call would not retry the process for 1 time at least not 3.

How to make an HTTP call to keep trying until a success response is received?


问:
How to read binary QR Code with AVFoundation?
Is it possible to read a binary encoded QR Code with AVFoundation?

I can get a AVMetadataMachineReadableCodeObject object of .type AVMetadataObjectTypeQRCode, however this only has a stringValue property, which won't work, because the data contained in the QR Code can't be converted to a string friendly representation.

Should I use ZXing instead?

Thanks.

答:
You can use a CIDetector to get to a CIQRCodeFeature which has a symbolDescriptor which has a errorCorrectedPayload which contains the data.

Only problem is that this data still includes QR code headers, like ECI etc... so you still need to interpret the bits.

I summed it up in a post here.


问:
App catalog is not showing in site collection of SharePoint Admin Center
I am working on SharePoint add-ins to create a remote event receiver. I have generated .app file and need to deploy on my SharePoint site. I followed the following reference to create app catalog for my site.

Reference: Create App Catalog In SharePoint Online

After following all the above steps, I visited to site collections of the SharePoint Admin Center to get app catalog home lisk but app catalog is not showing there.
What did I do wrong while following the reference steps?

答:
Creating app catalog site collection in admin center does not always mean app catalog will be enabled for all sites (maybe it has been disabled).

Kindly use the below PowerShell script to enable app catalog for a particular site:

$site = Get-SPOSite <Site collection url>
Add-SPOSiteCollectionAppCatalog -Site $site
```


问:
cannot read csv file in python
I have a python script that has a line with open('gg.csv') as csv_file:, and I have a csv file called gg.csv in the exact same directory as the python file, but when I run the script I am getting FileNotFoundError: [Errno 2] No such file or directory: 'gg.csv' - does anyone know of the solution?

答:
tl;dr: You are running your script in another directory.

You are running it in another directory other than the main one. Basically, "gg.csv" in python has a relative path. For example, if I am in my home directory, (in Linux) this should correspond to the path of:

```<code>/home/<whatever username>/gg.csv
</code>```

But say you are in your Desktop directory, in Linux, python interprets that as:

```<code>/home/<whatever username>/Desktop/gg.csv
</code>```

Because you are running it in a different directory, Python thinks you are corresponding to the gg.csv there, not the gg.csv with the directory that has the script.

Thus, run it in the correct directory or set a absolute path that always links to the correct directory and path.

Title: cannot read csv file in python

Body:
tl;dr: You are running your script in another directory.

You are running it in another directory other than the main one. Basically, "gg.csv" in python has a relative path. For example, if I am in my home directory, (in Linux) this should correspond to the path of:

/home/<whatever username>/gg.csv

But say you are in your Desktop directory, in Linux, python interprets that as:

/home/<whatever username>/Desktop/gg.csv

Because you are running it in a different directory, Python thinks you are corresponding to the gg.csv there, not the gg.csv with the directory that has the script.

Thus, run it in the correct directory or set a absolute path that always links to the correct directory and path.


问:
ASP.NET MVC3: Debug and Release app settings not working
My debug and release web.config app settings are not being read correctly.

Web.config:

```<code><appSettings>
 <add key="webpages:Version" value="1.0.0.0"/>
 <add key="ClientValidationEnabled" value="true"/>
 <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</code>```

Web.Debug.config

```<code><appSettings>
    <add key="ErrorEmailAddress" value="developerEmail@email.com" />
    <add key="TestModeEmailAddress" value="developerEmail@email.com" />
</appSettings>
</code>```

Web.Release.config

```<code><appSettings>
    <add key="ErrorEmailAddress" value="prodErrorEmail@email.com" />
</appSettings>
</code>```

However, calling:

```<code>WebConfigurationManager.AppSettings["ErrorEmailAddress"]
</code>```

is returning null (when debugging).

I have tried adding xdt:Transform="Insert" e.g.

```<code><add key="ErrorEmailAddress" value="prodErroEmail@email.com" xdt:Transform="Insert" />
</code>```

Any ideas?

答: are you debugging in release mode? in the toolbar next to the green arrow used to start debugging you can set a mode, make sure it isn't on release. </p>

Body:
My debug and release web.config app settings are not being read correctly.

Web.config:

<appSettings>
 <add key="webpages:Version" value="1.0.0.0"/>
 <add key="ClientValidationEnabled" value="true"/>
 <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

Web.Debug.config

<appSettings>
    <add key="ErrorEmailAddress" value="developerEmail@email.com" />
    <add key="TestModeEmailAddress" value="developerEmail@email.com" />
</appSettings>

Web.Release.config

<appSettings>
    <add key="ErrorEmailAddress" value="prodErrorEmail@email.com" />
</appSettings>

However, calling:

WebConfigurationManager.AppSettings["ErrorEmailAddress"]

is returning null (when debugging).

I have tried adding xdt:Transform="Insert" e.g.

<add key="ErrorEmailAddress" value="prodErroEmail@email.com" xdt:Transform="Insert" />

Any ideas?


问:
Cannot access memory error for character array in struct - C
I am attempting to create a queue using a linked list in C. I am using two structs to represent the queue and each node which are as follows.

```<code>#define DATA_MAX 100

struct QueueNode_ch
{
    struct QueueNode_ch* next;
    char data[(DATA_MAX + 1)];
};
typedef struct QueueNode_ch QueueNode_ch;

struct Queue_ch
{
    struct QueueNode_ch* front;
    struct QueueNode_ch* rear;
    int count;
};
typedef struct Queue_ch Queue_ch;
</code>```

I then use these the following functions to initialize the queue and the nodes.

```<code>int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}

int initQueueNode_ch(QueueNode_ch* node)
{
    node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    node->next = NULL;
    node->data[0] = '\0';
    return 0;
}
</code>```

Upon running my enqueue function I get a seg fault due to a strcpy function and when debugging gdb says it cannot access the memory of the node I am attempting to add. The enqueue code is as follows:

```<code>int enqueue_ch(Queue_ch* q, char* data)
{
    if(strlen(data) > (DATA_MAX + 1))
        return 1;
    QueueNode_ch* tmp;
    initQueueNode_ch(tmp);
    strncpy(tmp->data, data, DATA_MAX);
    if(isEmpty_queue_ch(q))
        q->rear = q->front = tmp;
    else
    {
        q->rear->next = tmp;
        q->rear = tmp;
    }
    q->count++;
    return 0;
}
</code>```

I will also include my main function as additional information.

```<code>#include <stdio.h>
#include "Queue.h"

int main()
{
    Queue_ch* queue;
    initQueue_ch(queue);
    enqueue_ch(queue, "hello");
    return 0;
}
</code>```

As far as I can tell there should be plenty of space to copy the given string to the node. Would anyone have any idea what is failing and possible fixes?

答:
As others have mentioned, you're passing your structs by value. In C, the proper way to do this is with a pointer to a pointer. Note that I haven't tried compiling this, but hopefully the idea is clear. </p>

```<code>int initQueue_ch(Queue_ch** q)
{
    *q = (Queue_ch*)malloc(sizeof(Queue_ch));
    (*q)->count = 0;
    (*q)->front = NULL;
    (*q)->rear = NULL;
    return 0;
}

int initQueueNode_ch(QueueNode_ch** node)
{
    *node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    (*node)->next = NULL;
    (*node)->data[0] = '\0';
    return 0;
}
</code>```

Body:
I am attempting to create a queue using a linked list in C. I am using two structs to represent the queue and each node which are as follows.

#define DATA_MAX 100

struct QueueNode_ch
{
    struct QueueNode_ch* next;
    char data[(DATA_MAX + 1)];
};
typedef struct QueueNode_ch QueueNode_ch;

struct Queue_ch
{
    struct QueueNode_ch* front;
    struct QueueNode_ch* rear;
    int count;
};
typedef struct Queue_ch Queue_ch;

I then use these the following functions to initialize the queue and the nodes.

int initQueue_ch(Queue_ch* q)
{
    q = (Queue_ch*)malloc(sizeof(Queue_ch));
    q->count = 0;
    q->front = NULL;
    q->rear = NULL;
    return 0;
}

int initQueueNode_ch(QueueNode_ch* node)
{
    node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    node->next = NULL;
    node->data[0] = '\0';
    return 0;
}

Upon running my enqueue function I get a seg fault due to a strcpy function and when debugging gdb says it cannot access the memory of the node I am attempting to add. The enqueue code is as follows:

int enqueue_ch(Queue_ch* q, char* data)
{
    if(strlen(data) > (DATA_MAX + 1))
        return 1;
    QueueNode_ch* tmp;
    initQueueNode_ch(tmp);
    strncpy(tmp->data, data, DATA_MAX);
    if(isEmpty_queue_ch(q))
        q->rear = q->front = tmp;
    else
    {
        q->rear->next = tmp;
        q->rear = tmp;
    }
    q->count++;
    return 0;
}

I will also include my main function as additional information.

#include <stdio.h>
#include "Queue.h"

int main()
{
    Queue_ch* queue;
    initQueue_ch(queue);
    enqueue_ch(queue, "hello");
    return 0;
}

As far as I can tell there should be plenty of space to copy the given string to the node. Would anyone have any idea what is failing and possible fixes?

Body:
As others have mentioned, you're passing your structs by value. In C, the proper way to do this is with a pointer to a pointer. Note that I haven't tried compiling this, but hopefully the idea is clear.

int initQueue_ch(Queue_ch** q)
{
    *q = (Queue_ch*)malloc(sizeof(Queue_ch));
    (*q)->count = 0;
    (*q)->front = NULL;
    (*q)->rear = NULL;
    return 0;
}

int initQueueNode_ch(QueueNode_ch** node)
{
    *node = (QueueNode_ch*)malloc(sizeof(QueueNode_ch));
    (*node)->next = NULL;
    (*node)->data[0] = '\0';
    return 0;
}


问:
Put many pictures into one div with specific size
I have created an app which creates lots of pictures with new Image() according to the context.

I want to put all my photos into one specific div, this div will always have the same size: 90% of the screen.

When I hover over a picture, the real picture will appear.

The photos width have to be resized according to the number of photos.

This is an example of what I want to do:

Every color represents a different picture.

This is when I hover a picture (here: the red one):

I have absolutely no idea of how to make this. If you have an idea or a clue for one of these things you're welcome to help me! Thanks.

答:
You can use onmouseover and onmouseout event to grab the image element you want to select.
Adding event listeners to all images would be potentially bad idea with memory leak if you don't handle them carefully and there are a lot of images. I think you can add event listener to window or document and find out the source element(target) of mouseover and mouseout event when hovering.

```<code>window.onmouseover = function(event) {
       event = event || window.event;
       const srcEl = event.srcElement || event.target;
       // use srcEl for further actions (get image src url or whatever)
}
</code>```

After that, you get the image url by 'src' attribute of image tag to update the main hero image.

Also as for performance when there lots of images, I advise you to use images as background of divs with css instead of img tag. They are faster than tag img. (why? images can be scale if img tag, although backgrounds can't be).

Body:
You can use onmouseover and onmouseout event to grab the image element you want to select.
Adding event listeners to all images would be potentially bad idea with memory leak if you don't handle them carefully and there are a lot of images. I think you can add event listener to window or document and find out the source element(target) of mouseover and mouseout event when hovering.

window.onmouseover = function(event) {
       event = event || window.event;
       const srcEl = event.srcElement || event.target;
       // use srcEl for further actions (get image src url or whatever)
}

After that, you get the image url by 'src' attribute of image tag to update the main hero image.

Also as for performance when there lots of images, I advise you to use images as background of divs with css instead of img tag. They are faster than tag img. (why? images can be scale if img tag, although backgrounds can't be).


问:
Getting error in web3.js regarding write tx
Hi I am getting error

```<code>Error: [ethjs-query] while formatting inputs '[{"0":false}]' for method 'getTransactionReceipt' error: Error: [ethjs-format] hex string '[object Object]' must be an alphanumeric 66 utf8 byte hex (chars: a-fA-F) string, is 0 bytes
    at ethjs.min.js:11
    at new Promise (<anonymous>)
    at i.getTransactionReceipt (ethjs.min.js:11)
    at i.e.<computed> [as getTransactionReceipt] (ethjs.min.js:11)
    at ethjs.min.js:11
</code>```

Im calling the smartcontract invest function :

```<code>function invest()public payable onlyAmount() firstExist  returns(bool){

//  balances[msg.sender]=msg.value;
 invested[msg.sender]+= msg.value;
 isInvested[msg.sender]=true;
 users[msg.sender].creationTime=now;
  commission=(msg.value.mul(10)).div(100);
 forCreators(commission);
emit Invest(msg.sender,msg.value);
 return true;
}
</code>```

Where As Im calling the function from web3.js like

```<code>tokenContract.invest({
    from: user_address,
    gasLimit: web3.toHex(8000000),
    gasPrice: web3.toHex(web3.toWei('10', 'gwei')),
    value : web3.toHex( web3.toWei(0.25, 'ether'))

  })
  .then(txHash =>  eth.getTransactionSuccess(txHash)
      .then(receipt => {
        alert("Sigup Has been successful",receipt);
      })
  )
  .catch((err) => {
    alert("Error couldnot signUp");
    console.log(err);
  })
</code>```

this error is showing on all write functions .. Read is working just fine. I have never encountered this error before. I tried deploying contract on Ropsten and Rinkeby same error.
And these contract functions are working just fine on etherscan and remix.
In web3js Even Metamask doesnt appears for transactions. What might be the issue?

答:
so as I mentioned above I was using eth.js . So somehow that was the issue. I did a worked around by not using ethjs and just by using web3js. As I already implemented all the read functions and all the functionality of my node app so It was a waste of time to change everything . made 2 diff variables 1 from ethjs (for read ) and 1 from pure web3js

```<code>const NameContract = web3.eth.contract(tokenABI);
window.tokenContract2 = NameContract.at(tokenAddress); //web3js

 window.tokenContract = eth.contract(tokenABI).at(tokenAddress); ethjs
</code>```

then I used the function like

```<code>tokenContract2.regUser({ from: user_address, gas: 400000 },
(err, res) => { /** callback **/ }
)
</code>```

call backs are necessary because metamask gives out an error.

I would still like to know the root of the issue. But since I was low on time I had to move forward with the project

Body:
Hi I am getting error

Error: [ethjs-query] while formatting inputs '[{"0":false}]' for method 'getTransactionReceipt' error: Error: [ethjs-format] hex string '[object Object]' must be an alphanumeric 66 utf8 byte hex (chars: a-fA-F) string, is 0 bytes
    at ethjs.min.js:11
    at new Promise (<anonymous>)
    at i.getTransactionReceipt (ethjs.min.js:11)
    at i.e.<computed> [as getTransactionReceipt] (ethjs.min.js:11)
    at ethjs.min.js:11

Im calling the smartcontract invest function :

function invest()public payable onlyAmount() firstExist  returns(bool){

//  balances[msg.sender]=msg.value;
 invested[msg.sender]+= msg.value;
 isInvested[msg.sender]=true;
 users[msg.sender].creationTime=now;
  commission=(msg.value.mul(10)).div(100);
 forCreators(commission);
emit Invest(msg.sender,msg.value);
 return true;
}

Where As Im calling the function from web3.js like

tokenContract.invest({
    from: user_address,
    gasLimit: web3.toHex(8000000),
    gasPrice: web3.toHex(web3.toWei('10', 'gwei')),
    value : web3.toHex( web3.toWei(0.25, 'ether'))

  })
  .then(txHash =>  eth.getTransactionSuccess(txHash)
      .then(receipt => {
        alert("Sigup Has been successful",receipt);
      })
  )
  .catch((err) => {
    alert("Error couldnot signUp");
    console.log(err);
  })

this error is showing on all write functions .. Read is working just fine. I have never encountered this error before. I tried deploying contract on Ropsten and Rinkeby same error.
And these contract functions are working just fine on etherscan and remix.
In web3js Even Metamask doesnt appears for transactions. What might be the issue?

Body:
so as I mentioned above I was using eth.js . So somehow that was the issue. I did a worked around by not using ethjs and just by using web3js. As I already implemented all the read functions and all the functionality of my node app so It was a waste of time to change everything . made 2 diff variables 1 from ethjs (for read ) and 1 from pure web3js

const NameContract = web3.eth.contract(tokenABI);
window.tokenContract2 = NameContract.at(tokenAddress); //web3js

 window.tokenContract = eth.contract(tokenABI).at(tokenAddress); ethjs

then I used the function like

tokenContract2.regUser({ from: user_address, gas: 400000 },
(err, res) => { /** callback **/ }
)

call backs are necessary because metamask gives out an error.

I would still like to know the root of the issue. But since I was low on time I had to move forward with the project


问:
Share Type Alias among different files in one namespace
I have defined a type alias, and I can use it in my class that I've declared in this file.

using TemplateStructure = System.Collections.Generic.List<System.Collections.Generic.List<DataManagement.TemplateImageLocation>>;

namespace Gui.ViewModels
{
    public class AddRemoveCellsViewModel : TemplateWorkflowStepViewModel
    {
        public TemplateViewModel TemplateVM
        {
            get;
        }

        public AddRemoveCellsViewModel(TemplateStructure locations) : base(locations)
        {
            base.DisplayName = "Add and Remove Rows/Columns";
            TemplateVM = new TemplateViewModel();
        }
    }
}

```

<p>But another class in another file, in the same namespace, it doesn't work.</p>

<pre class="lang-cs prettyprint-override"><code>namespace Gui.ViewModels
{
    public class ActivateDeactivateCellsViewModel : TemplateWorkflowStepViewModel
    {
        // FAILS
        public ActivateDeactivateCellsViewModel(TemplateStructure locations) : base(locations)
        {
            base.DisplayName = "Click to deactivate image locations";
        }
    }
}
</code>```

And, of course, usings must be placed outside of a namespace declaration.

Is it possible to use this Type Alias in multiple files?

答:
You have to write

```<code>using TemplateStructure = System.Collections.Generic.List<System.Collections.Generic.List<DataManagement.TemplateImageLocation>>;
</code>```

In every file where you want to use this alias, because

A using_alias_directive introduces an identifier that serves as an alias for a namespace or type within the immediately enclosing compilation unit or namespace body.

(from C# Language Specification - Using alias directives)

Using-aliases do not work across compilation-units, which are:

A C# program consists of one or more compilation units, each contained in a separate source file.

(from C# Language Specification - Compilation units)

Body:
I have defined a type alias, and I can use it in my class that I've declared in this file.

using TemplateStructure = System.Collections.Generic.List<System.Collections.Generic.List<DataManagement.TemplateImageLocation>>;

namespace Gui.ViewModels
{
    public class AddRemoveCellsViewModel : TemplateWorkflowStepViewModel
    {
        public TemplateViewModel TemplateVM
        {
            get;
        }

        public AddRemoveCellsViewModel(TemplateStructure locations) : base(locations)
        {
            base.DisplayName = "Add and Remove Rows/Columns";
            TemplateVM = new TemplateViewModel();
        }
    }
}

But another class in another file, in the same namespace, it doesn't work.

namespace Gui.ViewModels
{
    public class ActivateDeactivateCellsViewModel : TemplateWorkflowStepViewModel
    {
        // FAILS
        public ActivateDeactivateCellsViewModel(TemplateStructure locations) : base(locations)
        {
            base.DisplayName = "Click to deactivate image locations";
        }
    }
}

And, of course, usings must be placed outside of a namespace declaration.

Is it possible to use this Type Alias in multiple files?

Body:
You have to write

using TemplateStructure = System.Collections.Generic.List<System.Collections.Generic.List<DataManagement.TemplateImageLocation>>;

In every file where you want to use this alias, because

A using_alias_directive introduces an identifier that serves as an alias for a namespace or type within the immediately enclosing compilation unit or namespace body.

(from C# Language Specification - Using alias directives)

Using-aliases do not work across compilation-units, which are:

A C# program consists of one or more compilation units, each contained in a separate source file.

(from C# Language Specification - Compilation units)


问:
Custom Form Builder to Export XML into ODK Aggregate Server
I have a web application that have pre-defined set of questions as shown in the image below. A user is supposed to select a subset of the questions that he wants then click "Export Assessment". An XML should be created which will be imported into ODK Aggregate server which then becomes a Form which users in the field can get using ODK collect.

So far when a user clicks the Export I can only manage to create a json like below. Could someone point me to an easier way to end up with an ODK XForm.

```<code>[
{refField: null, label: "How many minutes does it take you to reach the nearest hospital from home?", hint: null, labelField: null, hintField: null,labelField: null, ref: "/data/group_ca7gs53/minutes_walk_hosp"}
{refField: null, label: "What mode of transport is your previous answer based on?", hint: null, labelField: null, hintField: null,labelField: null, ref: "/data/group_ca7gs53/mode_of_transport_prev_answe_0"}
{refField: null, label: "Specify other", hint: null, labelField: null, hintField: null,ref: "/data/group_ca7gs53/Specify_other_011"}
{refField: null, label: "How far is the river/dam from your house?", hint: null, labelField: null, hintField: null,ref: "/data/group_ca7gs53/minutes_walk_hosp"}
]
</code>```

答:
An easier way would be to use https://github.com/xlsform/pyxform, I think. If your UI can produce either a JSON format pyxform understands (or an xlsform), you can get a valid XForm from pyxform.

Note, KoBoToolbox has built a UI in front of pyxform as well.

Good luck!

Body:
I have a web application that have pre-defined set of questions as shown in the image below. A user is supposed to select a subset of the questions that he wants then click "Export Assessment". An XML should be created which will be imported into ODK Aggregate server which then becomes a Form which users in the field can get using ODK collect.

So far when a user clicks the Export I can only manage to create a json like below. Could someone point me to an easier way to end up with an ODK XForm.

[
{refField: null, label: "How many minutes does it take you to reach the nearest hospital from home?", hint: null, labelField: null, hintField: null,labelField: null, ref: "/data/group_ca7gs53/minutes_walk_hosp"}
{refField: null, label: "What mode of transport is your previous answer based on?", hint: null, labelField: null, hintField: null,labelField: null, ref: "/data/group_ca7gs53/mode_of_transport_prev_answe_0"}
{refField: null, label: "Specify other", hint: null, labelField: null, hintField: null,ref: "/data/group_ca7gs53/Specify_other_011"}
{refField: null, label: "How far is the river/dam from your house?", hint: null, labelField: null, hintField: null,ref: "/data/group_ca7gs53/minutes_walk_hosp"}
]


问:
Create a file in docker container (alpine images)
How can I create a file while building docker image?

Below is the docker file used and I want to create a file say config.txt in /usr/bin location

```<code>FROM gitlab/gitlab-runner:alpine
WORKDIR /app
COPY . /app
RUN apk add yarn && yarn install
RUN ng build --prod
ENTRYPOINT ["yarn"]
EXPOSE 3000
CMD ["run", "start"]
</code>```

I am specifically working on gitlab-runner image

Edit:
I know it's a stupid question because I didn't know anything about bash scripting :), earlier.

答:
We use the touch command.
When you perform RUN touch /usr/bin/config.txt you get the file with default permissions (644). Further, you can modify permissions using the chmod command.

Body:
How can I create a file while building docker image?

Below is the docker file used and I want to create a file say config.txt in /usr/bin location

FROM gitlab/gitlab-runner:alpine
WORKDIR /app
COPY . /app
RUN apk add yarn && yarn install
RUN ng build --prod
ENTRYPOINT ["yarn"]
EXPOSE 3000
CMD ["run", "start"]

I am specifically working on gitlab-runner image

Edit:
I know it's a stupid question because I didn't know anything about bash scripting :), earlier.


问:
Changing the colour of a face of a cube
I am trying to change the colour of the face of a cube, when the mouse hovers over:

This is what i came up with so far:

```<code>function onDocumentMouseMove(event)
  {
       event.preventDefault();

       // update the mouse variable
       mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
       mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

       var intersects = raycaster.intersectObjects( scene.children );

       if ( intersects.length > 0 )
       {
           var index = Math.floor( intersects[0].faceIndex / 2 );
           switch (index)
           {
                 case 0:
                 case 1:
                 case 2:
                 case 3:
                 case 4:
                 case 5:
            }
       }
   }
</code>```

The problem is i dno't know what method to use to paint the faces a different colour inside the switch-case

Take a look at this jsfiddle with code i used from Georges:

https://jsfiddle.net/rand0mus3r/5qe4gyj3/4/

Look only for the onDocumentMouseMouve() function.

I tried your code but it didn't work.

The reason i put your code under the  if (cube.material.color == 0xff0000),
was because i still wanted the cube to be painted grey when a hover over.

But when it it selected, thus the colour is red, i wanted on hover over, that side to change.

So when you change the y dimension on the gui and create a cube, and it IS selected (thus the colour is red), when you hover over its sides, it doesn't change colour.

I am stuck as to what to do next, as it is unclear how to paint the sides of the cube.

Here is the code for this function:

```<code> function onDocumentMouseMove(event)
    {

      event.preventDefault();

      // update the mouse variable
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            cube.material.color.set( 0xF7F7F7 );
        }
        else if (isClicked === false)
        {
            cube.material.color.set( cube.userData.originalColor );
        }

        if (cube.material.color == 0xff0000)
        {
           if ( intersects.length > 0 )
            {
               // pick the first object. It's the closest one
      this.pickedObject = intersectedObjects[0].object;
      // save its color
      this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
      // set its emissive color to flashing red/yellow
      this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
            }
        }

    }
</code>```

答:
You're on the right track with normalizing your mouse position to pass into the raycaster. This page on ThreeJSFundamentals has a solution that should be similar to you're after, with the exclusion of coloring a specific face. I believe you need to set up your raycaster as

```<code>var raycaster = new THREE.Raycaster();
// cast a ray from the camera's location to where the mouse click was registered
raycaster.setFromCamera(mouse, yourCameraName);
</code>```

Once you've got this, then you can call something similar to the following (taken from the link above)

```<code>var intersectedObjects =  raycaster.intersectObjects(scene.children);

 if (intersectedObjects.length) {
      // pick the first object. It's the closest one
      this.pickedObject = intersectedObjects[0].object;
      // save its color
      this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
      // set its emissive color to flashing red/yellow
      this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
    }
</code>```

You may also find it's easier to break your cube into an Object3D() of planes, and color the intersected plane

Title: Changing the colour of a face of a cube

Body:
I am trying to change the colour of the face of a cube, when the mouse hovers over:

This is what i came up with so far:

function onDocumentMouseMove(event)
  {
       event.preventDefault();

       // update the mouse variable
       mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
       mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

       var intersects = raycaster.intersectObjects( scene.children );

       if ( intersects.length > 0 )
       {
           var index = Math.floor( intersects[0].faceIndex / 2 );
           switch (index)
           {
                 case 0:
                 case 1:
                 case 2:
                 case 3:
                 case 4:
                 case 5:
            }
       }
   }

The problem is i dno't know what method to use to paint the faces a different colour inside the switch-case

Take a look at this jsfiddle with code i used from Georges:

https://jsfiddle.net/rand0mus3r/5qe4gyj3/4/

Look only for the onDocumentMouseMouve() function.

I tried your code but it didn't work.

The reason i put your code under the  if (cube.material.color == 0xff0000),
was because i still wanted the cube to be painted grey when a hover over.

But when it it selected, thus the colour is red, i wanted on hover over, that side to change.

So when you change the y dimension on the gui and create a cube, and it IS selected (thus the colour is red), when you hover over its sides, it doesn't change colour.

I am stuck as to what to do next, as it is unclear how to paint the sides of the cube.

Here is the code for this function:

 function onDocumentMouseMove(event)
    {

      event.preventDefault();

      // update the mouse variable
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            cube.material.color.set( 0xF7F7F7 );
        }
        else if (isClicked === false)
        {
            cube.material.color.set( cube.userData.originalColor );
        }

        if (cube.material.color == 0xff0000)
        {
           if ( intersects.length > 0 )
            {
               // pick the first object. It's the closest one
      this.pickedObject = intersectedObjects[0].object;
      // save its color
      this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
      // set its emissive color to flashing red/yellow
      this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
            }
        }

    }

Body:
You're on the right track with normalizing your mouse position to pass into the raycaster. This page on ThreeJSFundamentals has a solution that should be similar to you're after, with the exclusion of coloring a specific face. I believe you need to set up your raycaster as

var raycaster = new THREE.Raycaster();
// cast a ray from the camera's location to where the mouse click was registered
raycaster.setFromCamera(mouse, yourCameraName);

Once you've got this, then you can call something similar to the following (taken from the link above)

var intersectedObjects =  raycaster.intersectObjects(scene.children);

 if (intersectedObjects.length) {
      // pick the first object. It's the closest one
      this.pickedObject = intersectedObjects[0].object;
      // save its color
      this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
      // set its emissive color to flashing red/yellow
      this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
    }

You may also find it's easier to break your cube into an Object3D() of planes, and color the intersected plane


问:
How to Block Duplicate Transactions on CyberSource REST API
The CyberSource payments system seems to have a method of preventing duplicate transactions, as covered here:

This functionality looks at the Merchant Reference Number (MRN) of successful orders submitted within the last 15 minutes of a previous order, and blocks any duplicate transactions submitted with the same MRN.

and here:

Reason Code 104: The access_key and transaction_uuid fields for this authorization request match the access_key and transaction_uuid fields of another authorization request that you sent within the past 15 minutes.

Although it's obvious you need to use transaction_uuid for earlier APIs such as KVP, it's not clear which field to use for the REST API.

答:
Use the clientReferenceInformation > transactionId field.  You can see this in the playground with a request body like:

```<code>{
  "clientReferenceInformation": {
    "code": "TC50171_3",
    "transactionId": "465465411adfasdfsdf"
  },
  "processingInformation": {
    "reconciliationId": "1234"
  },
  "paymentInformation": {
    "card": {
      "number": "4111111111111111",
      "expirationMonth": "12",
      "expirationYear": "2031"
    }
  },
  "orderInformation": {
    "amountDetails": {
      "totalAmount": "102.21",
      "currency": "USD"
    },
    "billTo": {
      "firstName": "John",
      "lastName": "Doe",
      "address1": "1 Market St",
      "locality": "san francisco",
      "administrativeArea": "CA",
      "postalCode": "94105",
      "country": "US",
      "email": "test@cybs.com",
      "phoneNumber": "4158880000"
    }
  }
}
</code>```

If you include the same transactionId twice, the backend will tell you to get bent INVALID_DATA.  I would actually expect it to return DUPLICATE_REQUEST as a reason, (it's in their list of possible responses) but this is better than a poke in the eye with a sharp stick.

Body:
Use the clientReferenceInformation > transactionId field.  You can see this in the playground with a request body like:

{
  "clientReferenceInformation": {
    "code": "TC50171_3",
    "transactionId": "465465411adfasdfsdf"
  },
  "processingInformation": {
    "reconciliationId": "1234"
  },
  "paymentInformation": {
    "card": {
      "number": "4111111111111111",
      "expirationMonth": "12",
      "expirationYear": "2031"
    }
  },
  "orderInformation": {
    "amountDetails": {
      "totalAmount": "102.21",
      "currency": "USD"
    },
    "billTo": {
      "firstName": "John",
      "lastName": "Doe",
      "address1": "1 Market St",
      "locality": "san francisco",
      "administrativeArea": "CA",
      "postalCode": "94105",
      "country": "US",
      "email": "test@cybs.com",
      "phoneNumber": "4158880000"
    }
  }
}

If you include the same transactionId twice, the backend will tell you to get bent INVALID_DATA.  I would actually expect it to return DUPLICATE_REQUEST as a reason, (it's in their list of possible responses) but this is better than a poke in the eye with a sharp stick.


问:
C how to get input correctly
I'm trying to get a sentence and a letter from the user and for some reason it's not getting the letter
it's not doing the scanf the same with getcahr();

```<code>void main(){

    char str[100];
    char letter;
    printf("Enter a line: \n");
    scanf("%s", str);
    printf("Enter a letter: ");
    scanf("%c", &letter);
    printf("%c", letter);
}
</code>```

tried putting NULL in the letter no difference

答:
scanf("%s" reads a whitespace delimited word, NOT a line.  So it skips any initial whitespace on the input, then reads non-whitespace characters up until (and not including) the next whitespace character.  Since a newline is whitespace, it will end this process, but any other space will also end it.

scanf("%c" reads a single character without skipping any whitespace (same as getchar).  The fact that it does not skip whitespace means that if you use it directly after a scanf("%s", you'll get whatever whitespace character ended the first scanf.

If you want to read a line, use fgets or getline

Title: C how to get input correctly

Body:
I'm trying to get a sentence and a letter from the user and for some reason it's not getting the letter
it's not doing the scanf the same with getcahr();

void main(){

    char str[100];
    char letter;
    printf("Enter a line: \n");
    scanf("%s", str);
    printf("Enter a letter: ");
    scanf("%c", &letter);
    printf("%c", letter);
}

tried putting NULL in the letter no difference


问:
I need to highlight a text input when entry is correct
I would like to verify that what the user enters is exactly the same as the name value of the input. I have this working but I need for the input box to appear in green when it is. This is the code I have...

function onKeyUp(el) {
    var update_value = el.value;
  var  inputValue = el.getAttribute('name');
  if(update_value == inputValue){
    document.getElementById("myDiv").style.borderColor = "green";
  }
    if (update_value != inputValue) { // el.value is current value, inputValue is the default value
        $('[name="actionSave"]').removeClass('disabled');
    } else {
        $('[name="actionSave"]').addClass('disabled');

    }
}```

答:
I've got this partly working now...

  function onKeyUp(el) {
    var update_value = el.value;
    var  inputValue = el.getAttribute('name');
  if(update_value == inputValue){
    // alert(update_value+"=="+inputValue);
    el.style.borderColor = "#66ff00";
  }
    if (update_value != inputValue) { // el.value is current value, inputValue is the default value
        jQuery('[name="actionSave"]').removeClass('disabled');

    } else {
        jQuery('[name="actionSave"]').addClass('disabled');

    }
}```

When I type in the correct response, the text box turns green, however if I change it afterwards it does not change, it remains green. Is there a way to make it go back to the original color?

Body:
I've got this partly working now...

  function onKeyUp(el) {
    var update_value = el.value;
    var  inputValue = el.getAttribute('name');
  if(update_value == inputValue){
    // alert(update_value+"=="+inputValue);
    el.style.borderColor = "#66ff00";
  }
    if (update_value != inputValue) { // el.value is current value, inputValue is the default value
        jQuery('[name="actionSave"]').removeClass('disabled');

    } else {
        jQuery('[name="actionSave"]').addClass('disabled');

    }
}

When I type in the correct response, the text box turns green, however if I change it afterwards it does not change, it remains green. Is there a way to make it go back to the original color?


问:
python parameter validation -pyspark dataframe filter string
I have requirement to pass the where clause string directly to the input dataframe to filter the input records.
The filter_string with column name and the value to filter will be in the below format:

```<code>Ex 1: "(col('clm1') == '201')"
Ex 2: "(col('clm1') == '101') & (col('dim2') == '201')"

Scenario: If filter_string = "(col('clm1') == '201')"   # In the correct format
   df_output = df_input.filter(eval(filter_str)
</code>```

Now, i want to write the python syntax to raise an exception of the filter string if itis not in the above format. How can i do that?

答:
I am trying to understand what you have written, but am having trouble. In general, you should not mix "text" and "code" together. It confuses people that are trying to read your work. The words "Scenario:" and "Ex 1:" are not code and shouldn't be in your code block. </p>

<p>It sounds like you want to raise an exception, based on a matching string. Here is how to do that: </p>

```<code>filter_string = "(col('clm1') == '201')" # Could be something else too.
check_string  = "(col('clm1') == '201')"

if not other_string == check_string:
    raise TypeError(f"The string you provided, {filter_string}, is not valid.")

df_output = df_input.filter(eval(filter_string))
</code>```

Body:
I have requirement to pass the where clause string directly to the input dataframe to filter the input records.
The filter_string with column name and the value to filter will be in the below format:

Ex 1: "(col('clm1') == '201')"
Ex 2: "(col('clm1') == '101') & (col('dim2') == '201')"

Scenario: If filter_string = "(col('clm1') == '201')"   # In the correct format
   df_output = df_input.filter(eval(filter_str)

Now, i want to write the python syntax to raise an exception of the filter string if itis not in the above format. How can i do that?

Body:
I am trying to understand what you have written, but am having trouble. In general, you should not mix "text" and "code" together. It confuses people that are trying to read your work. The words "Scenario:" and "Ex 1:" are not code and shouldn't be in your code block.

It sounds like you want to raise an exception, based on a matching string. Here is how to do that:

filter_string = "(col('clm1') == '201')" # Could be something else too.
check_string  = "(col('clm1') == '201')"

if not other_string == check_string:
    raise TypeError(f"The string you provided, {filter_string}, is not valid.")

df_output = df_input.filter(eval(filter_string))


问:
Pandas Create multiindex pivot table with year month and day from single time column
I have a single column with time (time since epoch if it matters) from an sql query.

```<code>time     value
1000000  10
1000001  15
1000002  20
...
</code>```

I want to create a multiindex pivot table in Pandas automatically like so based on those values.

```<code>                  Value
2018    Jan       10
        Feb       15
        March     20
2019    Jan       25
        Feb       30
        March     35
</code>```

Is there an easy way to do this automatically for a variety of incoming time columns? And in some cases if the user specifies I would like to add day as the third multiindex level

答: If the column is a pandas.DateTime column, you can use the .dt datetime accessor to access attributes such as df[col].dt.year, df[col].dt.month, etc. You could assign these to new columns, then use pivot or set the index as you describe.

Body:
I have a single column with time (time since epoch if it matters) from an sql query.

time     value
1000000  10
1000001  15
1000002  20
...

I want to create a multiindex pivot table in Pandas automatically like so based on those values.

                  Value
2018    Jan       10
        Feb       15
        March     20
2019    Jan       25
        Feb       30
        March     35

Is there an easy way to do this automatically for a variety of incoming time columns? And in some cases if the user specifies I would like to add day as the third multiindex level


问:
How to convert array to a json object?
I am trying to push values in an array and it comes like

```<code>[{"Monday":"11:30"},{"Monday":"12:00"},{"Monday":"23:00"},{"Tuesday":"11:30"},{"Tuesday":"12:00"},{"Tuesday":"23:00"}]
</code>```

But I want it to be an object like

```<code>
{

"Monday" : [ "11:30", "12:00", "23:00"]

"Tuesday" : ["11:30","12:00","23:00"]

}
</code>```

Here is my code snippet

$timings = DoctorTimings::where('doctor_id', '=', $input['doctor_id'])->get();
$doctor_timings = [];

foreach($timings as $timing) {
    $day_id = $timing->day_id;
    $time_slot_id = $timing->time_slot_id;
    $day_id =  Days::where('id', '=', $day_id)->first()->day;
    $time_id = DB::table('time_slot')->where('id', '=', $time_slot_id)->select('time')->first()->time;
    array_push($doctor_timings, array($day_id => $time_id));
}

$doctorTimings = json_encode($doctor_timings);

echo $doctorTimings;
```

答:
You may use mapToGroups to get in the requested format. But i don't know your table structure so i got these;

```<code>[{"Monday":"11:30"},{"Monday":"12:00"},{"Monday":"23:00"},{"Tuesday":"11:30"},{"Tuesday":"12:00"},{"Tuesday":"23:00"}]
</code>```

put into the collection (assuming your eloquent collection returns like that)

```<code>$timings = collect([
        ["Monday" => "11:30"],
        ["Monday" => "12:00"],
        ["Monday" => "23:00"],
        ["Tuesday" => "11:30"],
        ["Tuesday" => "12:00"],
        ["Tuesday" => "23:00"]
    ]);

    return $timings->mapToGroups(function ($item) {
        $day = array_key_first($item);

        return [$day => $item[$day]];
    });
</code>```

which prints these;

```<code>{
  "Monday": [
    "11:30",
    "12:00",
    "23:00"
  ],
  "Tuesday": [
    "11:30",
    "12:00",
    "23:00"
  ]
}
</code>```

Edit: (the same array you posted in online used here + same function i used for solution)

```<code>$days = ["Monday", "Monday"];
$time = ["11:30", "12:30"];
$doctor_timings = [];
for ($i = 0; $i < sizeof($days); $i++) {
    $day_id = $days[$i];
    $time_id = $time[$i];
    array_push($doctor_timings, [$day_id => $time_id]);
}

return collect($doctor_timings)->mapToGroups(function ($item) {
    $day = array_key_first($item);

    return [$day => $item[$day]];
});
</code>```

which prints

```<code>{"Monday":["11:30","12:30"]}
</code>```

Title: How to convert array to a json object?

Body:
I am trying to push values in an array and it comes like

[{"Monday":"11:30"},{"Monday":"12:00"},{"Monday":"23:00"},{"Tuesday":"11:30"},{"Tuesday":"12:00"},{"Tuesday":"23:00"}]

But I want it to be an object like

{

"Monday" : [ "11:30", "12:00", "23:00"]

"Tuesday" : ["11:30","12:00","23:00"]

}

Here is my code snippet

$timings = DoctorTimings::where('doctor_id', '=', $input['doctor_id'])->get();
$doctor_timings = [];

foreach($timings as $timing) {
    $day_id = $timing->day_id;
    $time_slot_id = $timing->time_slot_id;
    $day_id =  Days::where('id', '=', $day_id)->first()->day;
    $time_id = DB::table('time_slot')->where('id', '=', $time_slot_id)->select('time')->first()->time;
    array_push($doctor_timings, array($day_id => $time_id));
}

$doctorTimings = json_encode($doctor_timings);

echo $doctorTimings;

Body:
You may use mapToGroups to get in the requested format. But i don't know your table structure so i got these;

[{"Monday":"11:30"},{"Monday":"12:00"},{"Monday":"23:00"},{"Tuesday":"11:30"},{"Tuesday":"12:00"},{"Tuesday":"23:00"}]

put into the collection (assuming your eloquent collection returns like that)

$timings = collect([
        ["Monday" => "11:30"],
        ["Monday" => "12:00"],
        ["Monday" => "23:00"],
        ["Tuesday" => "11:30"],
        ["Tuesday" => "12:00"],
        ["Tuesday" => "23:00"]
    ]);

    return $timings->mapToGroups(function ($item) {
        $day = array_key_first($item);

        return [$day => $item[$day]];
    });

which prints these;

{
  "Monday": [
    "11:30",
    "12:00",
    "23:00"
  ],
  "Tuesday": [
    "11:30",
    "12:00",
    "23:00"
  ]
}

Edit: (the same array you posted in online used here + same function i used for solution)

$days = ["Monday", "Monday"];
$time = ["11:30", "12:30"];
$doctor_timings = [];
for ($i = 0; $i < sizeof($days); $i++) {
    $day_id = $days[$i];
    $time_id = $time[$i];
    array_push($doctor_timings, [$day_id => $time_id]);
}

return collect($doctor_timings)->mapToGroups(function ($item) {
    $day = array_key_first($item);

    return [$day => $item[$day]];
});

which prints

{"Monday":["11:30","12:30"]}


问:
error: result of comparison against a string literal is unspecified for C
So I am trying to create a little joke with C and I don´t know what I am doing wrong. I see the Error "error: result of comparison against a string literal is unspecified" and do not know how to fix it, can someone help.

```<code>#include<stdio.h>
#include<cs50.h>
int main(void){
    string a = get_string("ENTER YOUR NAME FOR READING\n");
    if (a == "david")
    ;
    {
        printf("...");
    }
}
</code>```

答:
Comparing two char pointers like this char *a, *b; a == b; is accepted by the compiler, but if you are using such a syntax to compare the string values, then you may not get the results you are expecting. Some times it may evaluate to true or sometimes to false. The reason is, the program checks whether a and b are pointing to the same address, and not for if they have the same string value. Consider the program below.

```<code>#include <stdio.h>
int main()
{
        char* a = "test";

        char* b;

        if ((b="test") == a)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        printf("%p %p\n", a, b);

        return 0;
}
</code>```

OUTPUT

```<code>Impossible
0x55b6bd52d004 0x55b6bd52d004
</code>```

As you see from the output, the if block is evaluated to true. The reason is also in the output; a and b are pointing to a similar address. Why?

It comes from the string-pooling, one of the compiler optimization. Even though a and b are initialized at different points in the program, as they are referring to the same string constant, the string constant is initialized only once by the compiler.

Here is the objdump of the executable.

```<code>$ objdump -s -j .rodata

a.out:     file format elf64-x86-64

Contents of section .rodata:
 2000 01000200 74657374 00496d70 6f737369  ....test.Impossi
 2010 626c6500 54686f75 67687420 736f0025  ble.Thought so.%
 2020 70202570 0a00                        p %p..
</code>```

test is initialized only once. For a quick check, consider this program's output and its objdump .

```<code>#include <stdio.h>
int main()
{
        char* a = "test";

        char* b;

        if ((b="test1") == a)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        printf("%p %p\n", a, b);

        return 0;
}
</code>```

OUTPUT

```<code>Thought so
0x557a96aa9004 0x557a96aa9009
</code>```

objdump

```<code>$ objdump  -s -j .rodata a.out

a.out:     file format elf64-x86-64

Contents of section .rodata:
 2000 01000200 74657374 00746573 74310049  ....test.test1.I
 2010 6d706f73 7369626c 65005468 6f756768  mpossible.Though
 2020 7420736f 00257020 25700a00           t so.%p %p..
</code>```

It is evident from the output that a and bare pointing to different locations, and both are having different string values that are initialized by the compiler separately. So, if a and b are having similar string values, does a==b always evaluate to true? Consider the below program.

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

int main()
{
        char* a = malloc(sizeof(char) * 5);
        strcpy(a, "test");

        char* b;

        if ((b="test") == a)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        printf("%p %p\n", a, b);

        return 0;
}
</code>```

OUTPUT

```<code>Thought so
0x5607d9938260 0x5607d91fb004
</code>```

Even though the a and b are having the same string values, if evaluate to false. Why?  The address a is pointing, which is created by malloc() belongs to the heap section of the executable, whereas the address b is pointing belongs to the data section of the executable, and they are indeed different.

So what should we do to compare the string values?

Well, it is straight forward, there are already library functions which can perform this task. You can use them withstring.h. Consider the below code.

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

int main()
{
        char* a = malloc(sizeof(char) * 5);
        strcpy(a, "test");

        char* b = "test";

        char* c;

        if (strcmp((c="test"), a) == 0)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        if (strcmp(b, a) == 0)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        if (strcmp(b, c) == 0)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        printf("%p %p %p\n", a, b, c);

        return 0;
}
</code>```

OUTPUT

```<code>Impossible
Impossible
Impossible
0x556debf41260 0x556deac28004 0x556deac28004
</code>```

Irrespective of where a, b and c are pointing if they all are having the same string values, then strcmp() returns 0.

Body:
So I am trying to create a little joke with C and I don´t know what I am doing wrong. I see the Error "error: result of comparison against a string literal is unspecified" and do not know how to fix it, can someone help.

#include<stdio.h>
#include<cs50.h>
int main(void){
    string a = get_string("ENTER YOUR NAME FOR READING\n");
    if (a == "david")
    ;
    {
        printf("...");
    }
}

Body:
Comparing two char pointers like this char *a, *b; a == b; is accepted by the compiler, but if you are using such a syntax to compare the string values, then you may not get the results you are expecting. Some times it may evaluate to true or sometimes to false. The reason is, the program checks whether a and b are pointing to the same address, and not for if they have the same string value. Consider the program below.

#include <stdio.h>
int main()
{
        char* a = "test";

        char* b;

        if ((b="test") == a)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        printf("%p %p\n", a, b);

        return 0;
}

OUTPUT

Impossible
0x55b6bd52d004 0x55b6bd52d004

As you see from the output, the if block is evaluated to true. The reason is also in the output; a and b are pointing to a similar address. Why?

It comes from the string-pooling, one of the compiler optimization. Even though a and b are initialized at different points in the program, as they are referring to the same string constant, the string constant is initialized only once by the compiler.

Here is the objdump of the executable.

$ objdump -s -j .rodata

a.out:     file format elf64-x86-64

Contents of section .rodata:
 2000 01000200 74657374 00496d70 6f737369  ....test.Impossi
 2010 626c6500 54686f75 67687420 736f0025  ble.Thought so.%
 2020 70202570 0a00                        p %p..

test is initialized only once. For a quick check, consider this program's output and its objdump .

#include <stdio.h>
int main()
{
        char* a = "test";

        char* b;

        if ((b="test1") == a)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        printf("%p %p\n", a, b);

        return 0;
}

OUTPUT

Thought so
0x557a96aa9004 0x557a96aa9009

objdump

$ objdump  -s -j .rodata a.out

a.out:     file format elf64-x86-64

Contents of section .rodata:
 2000 01000200 74657374 00746573 74310049  ....test.test1.I
 2010 6d706f73 7369626c 65005468 6f756768  mpossible.Though
 2020 7420736f 00257020 25700a00           t so.%p %p..

It is evident from the output that a and bare pointing to different locations, and both are having different string values that are initialized by the compiler separately. So, if a and b are having similar string values, does a==b always evaluate to true? Consider the below program.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        char* a = malloc(sizeof(char) * 5);
        strcpy(a, "test");

        char* b;

        if ((b="test") == a)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        printf("%p %p\n", a, b);

        return 0;
}

OUTPUT

Thought so
0x5607d9938260 0x5607d91fb004

Even though the a and b are having the same string values, if evaluate to false. Why?  The address a is pointing, which is created by malloc() belongs to the heap section of the executable, whereas the address b is pointing belongs to the data section of the executable, and they are indeed different.

So what should we do to compare the string values?

Well, it is straight forward, there are already library functions which can perform this task. You can use them withstring.h. Consider the below code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        char* a = malloc(sizeof(char) * 5);
        strcpy(a, "test");

        char* b = "test";

        char* c;

        if (strcmp((c="test"), a) == 0)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        if (strcmp(b, a) == 0)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        if (strcmp(b, c) == 0)
                printf("Impossible\n");
        else
                printf("Thought so\n");

        printf("%p %p %p\n", a, b, c);

        return 0;
}

OUTPUT

Impossible
Impossible
Impossible
0x556debf41260 0x556deac28004 0x556deac28004

Irrespective of where a, b and c are pointing if they all are having the same string values, then strcmp() returns 0.


问:
How to visually consume/create .diff .patch files in OS X?
Sorry, I'm just not finding anything that can do this!  For example I get a big fat .diff of 30 files.. sure, I can use patch and apply that to my source baseline.  But, I'd hope to be able to take that .diff and my source tree and interactively view those changes to review the diff and optionally merge in or ignore sections.

答:
I use "p4merge" from Perforce.  It's commercial software, but this particular piece of the tool suite is free and available here on multiple platforms:

http://www.perforce.com/perforce/downloads/

I think you have to download the whole visual client and then pull the pieces you want from the DMG.


问:
Sort in access database
Im trying to sort a database in access and I can't get it done. I need to use only the records with the latest day. First the city with the lowest price and all the prices of that city, then the city with the second lowest price, etc. Thank you!!

This is the example database:

```<code>Date           Country    City     Price    Departure_date     Return_date
05-06-2019     Peru       Lima     360$     xxxx               xxxxx
05-06-2019     Peru       Lima     420$     xxxx               xxxxx
05-06-2019     Mexico     CMX      300$     xxxx               xxxxx
05-06-2019     Mexico     CMX      400$     xxxx               xxxxx
05-06-2019     Mexico     Cancun   350$     xxxx               xxxxx
05-06-2019     Mexico     Cancun   500$     xxxx               xxxxx
05-06-2019     Peru       Cusco    50$      xxxx               xxxxx
05-06-2019     Peru       Cusco    60$      xxxx               xxxxx
04-06-2017     Mexico     Cancun   300$     xxxx               xxxxx
04-06-2017     Peru       Cusco    70$      xxxx               xxxxx
04-06-2017     Peru       Cusco    30$      xxxx               xxxxx
</code>```

It has to be sorted this way:

```<code>Date         Country    City     Price    Departure_date     Return_date
05-06-2019   Peru       Cusco    50$      xxxx               xxxxx
05-06-2019   Peru       Cusco    60$      xxxx               xxxxx
05-06-2019   Mexico     CMX      300$     xxxx               xxxxx
05-06-2019   Mexico     CMX      400$     xxxx               xxxxx
05-06-2019   Mexico     Cancun   350$     xxxx               xxxxx
05-06-2019   Mexico     Cancun   500$     xxxx               xxxxx
05-06-2019   Peru       Lima     360$     xxxx               xxxxx
05-06-2019   Peru       Lima     420$     xxxx               xxxxx
</code>```

答:
There is likely to be a way to condense this, but the following should perform as required:

```<code>select t0.*
from
    YourTable t0 inner join
    (
        select t1.city, t1.date, min(t1.price) as mprice
        from
            YourTable t1 inner join
            (
                select t2.city, max(t2.date) as mdate
                from YourTable t2
                group by t2.city
            ) t3
            on t1.date = t3.mdate and t1.city = t3.city
        group by
            t1.city, t1.date
    ) t4
    on t0.city = t4.city and t0.date = t4.date
order by
    t4.mprice, t0.city, t0.price
</code>```

Essentially:

The innermost subquery (t3) obtains the records for each city with the latest date (mdate).

The outer subquery (t4) obtains the minimum price (mprice) within the set of latest records for each city.

Finally the main query outputs the relevant records, sorting by minimum price (to sort the city groups), then by the city (to sort cities with the same minimum), and then by the price to sort records within each city group.

You will need to change all occurrences of YourTable to the name of your table.

Title: Sort in access database

Body:
Im trying to sort a database in access and I can't get it done. I need to use only the records with the latest day. First the city with the lowest price and all the prices of that city, then the city with the second lowest price, etc. Thank you!!

This is the example database:

Date           Country    City     Price    Departure_date     Return_date
05-06-2019     Peru       Lima     360$     xxxx               xxxxx
05-06-2019     Peru       Lima     420$     xxxx               xxxxx
05-06-2019     Mexico     CMX      300$     xxxx               xxxxx
05-06-2019     Mexico     CMX      400$     xxxx               xxxxx
05-06-2019     Mexico     Cancun   350$     xxxx               xxxxx
05-06-2019     Mexico     Cancun   500$     xxxx               xxxxx
05-06-2019     Peru       Cusco    50$      xxxx               xxxxx
05-06-2019     Peru       Cusco    60$      xxxx               xxxxx
04-06-2017     Mexico     Cancun   300$     xxxx               xxxxx
04-06-2017     Peru       Cusco    70$      xxxx               xxxxx
04-06-2017     Peru       Cusco    30$      xxxx               xxxxx

It has to be sorted this way:

Date         Country    City     Price    Departure_date     Return_date
05-06-2019   Peru       Cusco    50$      xxxx               xxxxx
05-06-2019   Peru       Cusco    60$      xxxx               xxxxx
05-06-2019   Mexico     CMX      300$     xxxx               xxxxx
05-06-2019   Mexico     CMX      400$     xxxx               xxxxx
05-06-2019   Mexico     Cancun   350$     xxxx               xxxxx
05-06-2019   Mexico     Cancun   500$     xxxx               xxxxx
05-06-2019   Peru       Lima     360$     xxxx               xxxxx
05-06-2019   Peru       Lima     420$     xxxx               xxxxx

Body:
There is likely to be a way to condense this, but the following should perform as required:

select t0.*
from
    YourTable t0 inner join
    (
        select t1.city, t1.date, min(t1.price) as mprice
        from
            YourTable t1 inner join
            (
                select t2.city, max(t2.date) as mdate
                from YourTable t2
                group by t2.city
            ) t3
            on t1.date = t3.mdate and t1.city = t3.city
        group by
            t1.city, t1.date
    ) t4
    on t0.city = t4.city and t0.date = t4.date
order by
    t4.mprice, t0.city, t0.price

Essentially:

The innermost subquery (t3) obtains the records for each city with the latest date (mdate).

The outer subquery (t4) obtains the minimum price (mprice) within the set of latest records for each city.

Finally the main query outputs the relevant records, sorting by minimum price (to sort the city groups), then by the city (to sort cities with the same minimum), and then by the price to sort records within each city group.

You will need to change all occurrences of YourTable to the name of your table.


问:
insert new field in mongodb database
I'm a beginner in mongodb and pymongo and I'm working on a project where I have a students mongodb collection . What I want is to add a new field and specifically an adrress of a student to each element in my collection (the field is obviously added everywhere as null and will be filled by me later).

However when I try using this specific example to add a new field I get a the following syntax error:

```<code> client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

 db = client['InfoSys']   #choose infosys database
 students = db['Students']

 students.update(  {  $set : {"address":1} }  ) #set address field to every column (error happens here)
</code>```

How can I fix this error?

答:
The previous answer here is spot on, but it looks like your question may relate more to PyMongo and how it manages updates to collections. https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html

According to the docs, it looks like you may want to use the 'update_many()' function. You will still need to make your query (all documents, in this case) as the first argument, and the second argument is the operation to perform on all records.

```<code>client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

db = client['InfoSys']   #choose infosys database
students = db['Students']

sudents.update_many({}, {$set : {"address":1}})
</code>```

Title: insert new field in mongodb database

Body:
I'm a beginner in mongodb and pymongo and I'm working on a project where I have a students mongodb collection . What I want is to add a new field and specifically an adrress of a student to each element in my collection (the field is obviously added everywhere as null and will be filled by me later).

However when I try using this specific example to add a new field I get a the following syntax error:

 client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

 db = client['InfoSys']   #choose infosys database
 students = db['Students']

 students.update(  {  $set : {"address":1} }  ) #set address field to every column (error happens here)

How can I fix this error?

Body:
The previous answer here is spot on, but it looks like your question may relate more to PyMongo and how it manages updates to collections. https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html

According to the docs, it looks like you may want to use the 'update_many()' function. You will still need to make your query (all documents, in this case) as the first argument, and the second argument is the operation to perform on all records.

client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

db = client['InfoSys']   #choose infosys database
students = db['Students']

sudents.update_many({}, {$set : {"address":1}})


问:
Accessing link in email message using gmail api & Cypress
hope u all safe ,
i am doing e2e automated test by Cypress , and i have problem to access link in the received email (Gmail account)from a specific email address. So far using GMAIL api I am able to get the email id using Cy.task

testCase 1. : visit signup page and fill information .// Passed

testCase 2 : ensure that email has received by using gmail-tester library // Passed

testCase 3: the problem is here ===>> click on CTA confirm ur email address and it should direct me to confirmation page Or extract href then cy.visit(href)

```<code>**href**="http://post.spmailtechnol.com/f/a/mD0QS83FHCNqxzGZpDJgfg~~/AALxrAA~/RgRgYvyvP0T3aHR0cHM6Ly9uZXh0LWRldi50YWphd2FsLmNvbS9lbi91c2VyL3ZlcmlmeT90b2tlbj00ZjM5Y2I0ZC0yZjU2LTQxYmItOWFlNC0yMDFjN2Y3ZTAyM2UmcmVxdWVzdElkPWM2ZGNiOTEwLThkZWQtNDFhYy05ODQ0LWJjMTdlZWFmOTEyNyZ1dG1fc291cmNlPXRyYW5zYWN0aW9uYWwmdXRtX21lZGl1bT1lbWFpbCZ1dG1fY2FtcGFpZ249MjAyMDAzMzBfRU5fQ09NX1JFR0lTVFJBVElPTiZ1dG1fY29udGVudD1Cb2R5JnV0bV90ZXJtPUNUQVcDc3BjQgoAAC_JgV6KRz5mUh9lbHNoYWlraHRlc3RlbWFpbHMrMjBAZ21haWwuY29tWAQAAAAB" style="font-size:14px;color:#ffffff;text-decoration:none;border-radius:2px;padding:12px 0 12px 0;display:inline-block;border-top:1px solid #499df3;border:none;font-weight:bold;min-width:190px;text-align:center;background:#1dac08"
↵                                               target="_blank">Confirm email</a>
</code>```

thanks in advance for ur reply & help , Thank you

答:
If you are getting a raw body response (a string) you cannot use the cypress method unless you convert this strings into a DOM object so you have to get the link in this way if you have an email body as string:</p>

```<code>const links = body.split("href=http://my.url.com");
var activation_link = links[0].match(/\bhttp?:\/\/\S+/);
activation_link= activation_link[0].replace('"','')
cy.visit(activation_link)
</code>```

Body:
hope u all safe ,
i am doing e2e automated test by Cypress , and i have problem to access link in the received email (Gmail account)from a specific email address. So far using GMAIL api I am able to get the email id using Cy.task

testCase 1. : visit signup page and fill information .// Passed

testCase 2 : ensure that email has received by using gmail-tester library // Passed

testCase 3: the problem is here ===>> click on CTA confirm ur email address and it should direct me to confirmation page Or extract href then cy.visit(href)

**href**="http://post.spmailtechnol.com/f/a/mD0QS83FHCNqxzGZpDJgfg~~/AALxrAA~/RgRgYvyvP0T3aHR0cHM6Ly9uZXh0LWRldi50YWphd2FsLmNvbS9lbi91c2VyL3ZlcmlmeT90b2tlbj00ZjM5Y2I0ZC0yZjU2LTQxYmItOWFlNC0yMDFjN2Y3ZTAyM2UmcmVxdWVzdElkPWM2ZGNiOTEwLThkZWQtNDFhYy05ODQ0LWJjMTdlZWFmOTEyNyZ1dG1fc291cmNlPXRyYW5zYWN0aW9uYWwmdXRtX21lZGl1bT1lbWFpbCZ1dG1fY2FtcGFpZ249MjAyMDAzMzBfRU5fQ09NX1JFR0lTVFJBVElPTiZ1dG1fY29udGVudD1Cb2R5JnV0bV90ZXJtPUNUQVcDc3BjQgoAAC_JgV6KRz5mUh9lbHNoYWlraHRlc3RlbWFpbHMrMjBAZ21haWwuY29tWAQAAAAB" style="font-size:14px;color:#ffffff;text-decoration:none;border-radius:2px;padding:12px 0 12px 0;display:inline-block;border-top:1px solid #499df3;border:none;font-weight:bold;min-width:190px;text-align:center;background:#1dac08"
↵                                               target="_blank">Confirm email

thanks in advance for ur reply & help , Thank you

Body:
If you are getting a raw body response (a string) you cannot use the cypress method unless you convert this strings into a DOM object so you have to get the link in this way if you have an email body as string:

const links = body.split("href=http://my.url.com");
var activation_link = links[0].match(/\bhttp?:\/\/\S+/);
activation_link= activation_link[0].replace('"','')
cy.visit(activation_link)


问:
Send a user-defined Windows-message through JNA
I want a simple but hard thing: to send a specific user-defined Windows-message from the JNA side in order this message to be catched by a message-loop (GetMessage()/DispatchMessage()) on the C++ side and that message loop will be then interrupted. Actually it should be performed by the button click in Swing GUI. My questions and considerations:

1) Suppose for example I defined on the C++ side my own message as #define WM_CUSTOM_MSG (WM_USER+42) and of course add an appropriate if-statement for interruption inside my message-loop on C++ side. But my purpose is to send this message from java.

2) To do this I wrote the following:

```<code>public class User32Ext {
    interface User32Interface extends User32 {
        User32Interface INSTANCE = Native.load("user32",

                User32Interface.class, W32APIOptions.DEFAULT_OPTIONS);

        @Override
        HWND FindWindowEx(HWND lpParent, HWND lpChild, String lpClassName, String lpWindowName);

        HWND GetTopWindow(HWND hwnd);

        HWND GetParent(HWND hwnd);

        @Override
        HWND GetDesktopWindow();

        int SendMessage(HWND hWnd, int Msg, IntByReference wParam, IntByReference lParam);

        void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

        void SwitchToThisWindow(HWND hWnd, boolean fAltTab);

    }

    private final User32Interface u32 = User32Interface.INSTANCE;

    public User32Ext() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void sendInterruptMessage(final String windowName) {
        try {
            final User32.HWND hwnd = u32.FindWindowEx(null, null, null, windowName);
            final int msg = 0x400 + 42;
            final User32.WPARAM wparam = new User32.WPARAM();
            final User32.LPARAM lparam = new User32.LPARAM();
            final LRESULT res = u32.SendMessage(hwnd, msg, wparam, lparam);
        } catch (final RuntimeException e) {
            e.printStackTrace();
        }
    }
 }
</code>```

and then just create an object of this dummy class and call sendInterruptMessage with my JFrame's title as parameter in the button event.

Sadly, on the both sides absolutely no effect was detected. I'm pretty much sure I did some fatal error, because I'm not expirienced enough with Windows and JNA programming. So, could you tell me, at least am I right conceptually, implementing the desired result like this? Or there are just some programming errors on the Java side. Thanks!

P.S. if it could be implemented without sending a custom message, but with some standard Windows message, that's perfectly fine, I just want to be sure, the only thing this message does is to interrupt my C++ message loop.

答:
When mapping WINAPI functions with JNA, you must take care to exactly match the Windows API definitions with appropriate Java/JNA types.  Some of your mappings are wrong.  The last two arguments to SendMessage are a WPARAM and LPARAM, which you appear to be using in your sendInterruptMessage() mapping.  These are calling the already-mapped SendMessage function in the JNA project.  It doesn't matter what you're putting in your own SendMessage mapping since you're not even calling it, as you're using different types.  Delete that.  Also delete the two methods you have put @Override on from the superclass.  You have no reason to overwrite what they are already doing.

Actually, on further inspection, it appears as if you've copied the code someone else wrote in 2014 from this answer.  However, the mappings you need were added to the JNA project in 2017.  Copying code without knowing what it does is not a recipe for success.  Your entire interface is not needed.  Just call JNA's User32 interface.

In your call to FindWindowEx you're passing null for the first three arguments and only placing a String in the fourth argument. This seems to mismatch the API which does not appear to allow null as the third argument.  Have you checked whether the returned handle is null?  It probably is, and per the API you can use GetLastError to look at that error code, which is likely associated with incorrect arguments.

The docs for that third argument specify,

If lpszClass is a string, it specifies the window class name. The
  class name can be any name registered with RegisterClass or
  RegisterClassEx, or any of the predefined control-class names, or it
  can be MAKEINTATOM(0x8000). In this latter case, 0x8000 is the atom
  for a menu class. For more information, see the Remarks section of
  this topic.

It does not appear as if you are doing this as required.

If that first call is succeeding (which would surprise me), it would be instructive for you to evaluate the LRESULT return from the existing SendMessage call and see if it indicates success or generates an error code.  In fact, you are probably passing it a null handle, in which case it's no surprise that nothing is happening.

Starting out by checking method return values that indicate success/failure and evaluating the error codes should help you debug.

Finally, as ponited out by iinspectable in the comments, the code you're passing isn't a custom message.  According to the documentation,

Message-identifier values are used as follows:

The system reserves message-identifier values in the range 0x0000    through 0x03FF (the value of WM_USER  – 1) for system-defined

  messages. Applications cannot use these values for private messages.

Values in the range 0x0400 (the value of WM_USER) through 0x7FFF are    available for message identifiers for private window classes.

If your application is marked version 4.0, you can use    message-identifier values in the range 0x8000 (WM_APP) through 0xBFFF
  for private messages.

The system returns a message identifier in the range 0xC000 through    0xFFFF when an application calls the RegisterWindowMessage function

  to register a message. The message identifier returned by this

  function is guaranteed to be unique throughout the system. Use of

  this function prevents conflicts that can arise if other applications
  use the same message identifier for different purposes.

Reading the WINAPI documentation to know what's expected in each parameter will help you find the right values to pass and is critical to getting expected results from your code.

Body:
I want a simple but hard thing: to send a specific user-defined Windows-message from the JNA side in order this message to be catched by a message-loop (GetMessage()/DispatchMessage()) on the C++ side and that message loop will be then interrupted. Actually it should be performed by the button click in Swing GUI. My questions and considerations:

1) Suppose for example I defined on the C++ side my own message as #define WM_CUSTOM_MSG (WM_USER+42) and of course add an appropriate if-statement for interruption inside my message-loop on C++ side. But my purpose is to send this message from java.

2) To do this I wrote the following:

public class User32Ext {
    interface User32Interface extends User32 {
        User32Interface INSTANCE = Native.load("user32",

                User32Interface.class, W32APIOptions.DEFAULT_OPTIONS);

        @Override
        HWND FindWindowEx(HWND lpParent, HWND lpChild, String lpClassName, String lpWindowName);

        HWND GetTopWindow(HWND hwnd);

        HWND GetParent(HWND hwnd);

        @Override
        HWND GetDesktopWindow();

        int SendMessage(HWND hWnd, int Msg, IntByReference wParam, IntByReference lParam);

        void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

        void SwitchToThisWindow(HWND hWnd, boolean fAltTab);

    }

    private final User32Interface u32 = User32Interface.INSTANCE;

    public User32Ext() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void sendInterruptMessage(final String windowName) {
        try {
            final User32.HWND hwnd = u32.FindWindowEx(null, null, null, windowName);
            final int msg = 0x400 + 42;
            final User32.WPARAM wparam = new User32.WPARAM();
            final User32.LPARAM lparam = new User32.LPARAM();
            final LRESULT res = u32.SendMessage(hwnd, msg, wparam, lparam);
        } catch (final RuntimeException e) {
            e.printStackTrace();
        }
    }
 }

and then just create an object of this dummy class and call sendInterruptMessage with my JFrame's title as parameter in the button event.

Sadly, on the both sides absolutely no effect was detected. I'm pretty much sure I did some fatal error, because I'm not expirienced enough with Windows and JNA programming. So, could you tell me, at least am I right conceptually, implementing the desired result like this? Or there are just some programming errors on the Java side. Thanks!

P.S. if it could be implemented without sending a custom message, but with some standard Windows message, that's perfectly fine, I just want to be sure, the only thing this message does is to interrupt my C++ message loop.


问:
R Count and CountDistinct elements of a list
I'm facing a little problem: I've used the Tweeter API and I obtained something like:

```<code>id <- c(1:4)
val <- c(100,150,170,200)
tex <- c("[#price", "#quant]","[#good]","[#good] [#price]")
db <- data.frame(id,val,tex)
</code>```

I would like to count the total number of Hashtags and also the number of the unique hashtags in the simplest way because then I need to put everything inside a reactive database in order to create a dashboard through Shiny.

Thx for your help.

答:
in Base-R this will get all the unique hashtags, you can use length(  ) to get the count

```<code>unique(unlist(regmatches(db$tex, gregexpr("#\\w+", db$tex))))

[1] "#price" "#quant" "#good"
</code>```

Edit:
if you prefer without #

```<code>unique(unlist(regmatches(db$tex, gregexpr("#\\K\\w+", db$tex,perl=T))))
[1] "price" "quant" "good"
</code>```

Body:
I'm facing a little problem: I've used the Tweeter API and I obtained something like:

id <- c(1:4)
val <- c(100,150,170,200)
tex <- c("[#price", "#quant]","[#good]","[#good] [#price]")
db <- data.frame(id,val,tex)

I would like to count the total number of Hashtags and also the number of the unique hashtags in the simplest way because then I need to put everything inside a reactive database in order to create a dashboard through Shiny.

Thx for your help.

Body:
in Base-R this will get all the unique hashtags, you can use length(  ) to get the count

unique(unlist(regmatches(db$tex, gregexpr("#\\w+", db$tex))))

[1] "#price" "#quant" "#good"

Edit:
if you prefer without #

unique(unlist(regmatches(db$tex, gregexpr("#\\K\\w+", db$tex,perl=T))))
[1] "price" "quant" "good"


问:
Algorithm complexity notation
I am learning about algorithm complexity and I got a simple algorithm to be analyzed by me, this is the algorithm:

```<code>function test(int x, int y, int N){
  int i, j, k;
  if (x==y) {
   for (i = 0; i < N; i++) {
      for (j = 0; j < N; j++) {
        commands here
      }
   }
   for (i = 0; i < N; i++) {
     commands here
   }
  }else {
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
           for (k = 0; k < N; k++) {
              commands here
           }
       }
    }
  }
}
</code>```

I analyzed as follows:

f( x, y, n) = n² + n (if x = y)

f( x, y, n) = n³ (if x ≠ y)

That means that in the best-case scenario, f(n) = n² + n or simply O(n²) and in the worst-case scenario, f(n) = n³ or simply O(n³)

My question is: Is my understanding correct? Realizing which function is bigger is something intuitive, but do I need to compare both functions mathematically to prove that? On top of that, is the module right?

Thanks, guys!

答:
Assuming 'commands here' are performed in constant-time, then you are correct.

You're describing a piecewise time complexity for this given algorithm, dependent on the values of x and y. You've correctly broken down the two cases and analyzed their complexity, again assuming the 'commands' are constant-time. Now to compare the two cases more rigorously:

Showing that latter case, (x!=y), is asymptotically larger than the former, (x==y), and thus is the worst-case, is as simple as showing that N^3 is at least as large as N^2 for all values of N greater than a certain value. Since N^3 is greater than N^2 for all values at least 0, we can say that N^2 = O(N^3) and thus O(N^3) is in fact the worse of the two cases and thus the worst-case runtime. A symmetric argument can be applied to show the other case is then the best-case runtime.

You can show the same thing quicker by taking the limit of one runtime divided by the other as N goes to infinity. If that limit goes to 0, then the numerator = O(denominator), and if it goes to infinity then the reverse is true. If it goes to some positive constant then the two have the same asymptotic complexity, expressed by the omega notation.

brief review of asymptotic notation

You could dive into average-case analysis if you knew anything about the distributions of X and Y, since you would be able to determine the probability that the worst/best case occur.

Title: Algorithm complexity notation

Body:
I am learning about algorithm complexity and I got a simple algorithm to be analyzed by me, this is the algorithm:

function test(int x, int y, int N){
  int i, j, k;
  if (x==y) {
   for (i = 0; i < N; i++) {
      for (j = 0; j < N; j++) {
        commands here
      }
   }
   for (i = 0; i < N; i++) {
     commands here
   }
  }else {
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
           for (k = 0; k < N; k++) {
              commands here
           }
       }
    }
  }
}

I analyzed as follows:

f( x, y, n) = n² + n (if x = y)

f( x, y, n) = n³ (if x ≠ y)

That means that in the best-case scenario, f(n) = n² + n or simply O(n²) and in the worst-case scenario, f(n) = n³ or simply O(n³)

My question is: Is my understanding correct? Realizing which function is bigger is something intuitive, but do I need to compare both functions mathematically to prove that? On top of that, is the module right?

Thanks, guys!


问:
Regular expression to handle two different file extensions
I am trying to create a regular expression that takes a file of name
"abcd_04-04-2020.txt" or "abcd_04-04-2020.txt.gz"

How can I handle the "OR" condition for the extension. This is what I have so far

```<code>if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
    Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}
</code>```

This handles only the .txt. How can I handle ".txt.gz"
Thanks

答:
You can use the below regex to achieve your purpose:

```<code>^[\w-]+\d{2}-\d{2}-\d{4}\.txt(?:\.gz)?$
</code>```

Explanation of the above regex:]

^,$ - Matches start and end of the test string resp.

[\w-]+ - Matches word character along with hyphen one or more times.

\d{} - Matches digits as many numbers as mentioned in the curly braces.

(?:\.gz)? - Represents non-capturing group matching .gz zero or one time because of ? quantifier. You could have used | alternation( or as you were expecting OR) but this is legible and more efficient too.

You can find the demo of the above regex here.

IMPLEMENTATION IN JAVA:

```<code>import java.util.regex.*;
public class Main
{
    private static final Pattern pattern = Pattern.compile("^[\\w-]+\\d{2}-\\d{2}-\\d{4}\\.txt(?:\\.gz)?$", Pattern.MULTILINE);
    public static void main(String[] args) {
        String testString = "abcd_04-04-2020.txt\nabcd_04-04-2020.txt.gz\nsomethibsnfkns_05-06-2020.txt\n.txt.gz";
        Matcher matcher = pattern.matcher(testString);
        while(matcher.find()){
            System.out.println(matcher.group(0));
        }
    }
}
</code>```

You can find the implementation of the above regex in java in here.

NOTE: If you want to match for valid dates also; please visit this.

Body:
I am trying to create a regular expression that takes a file of name
"abcd_04-04-2020.txt" or "abcd_04-04-2020.txt.gz"

How can I handle the "OR" condition for the extension. This is what I have so far

if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
    Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}

This handles only the .txt. How can I handle ".txt.gz"
Thanks

Body:
You can use the below regex to achieve your purpose:

^[\w-]+\d{2}-\d{2}-\d{4}\.txt(?:\.gz)?$

Explanation of the above regex:]

^,$ - Matches start and end of the test string resp.

[\w-]+ - Matches word character along with hyphen one or more times.

\d{} - Matches digits as many numbers as mentioned in the curly braces.

(?:\.gz)? - Represents non-capturing group matching .gz zero or one time because of ? quantifier. You could have used | alternation( or as you were expecting OR) but this is legible and more efficient too.

You can find the demo of the above regex here.

IMPLEMENTATION IN JAVA:

import java.util.regex.*;
public class Main
{
    private static final Pattern pattern = Pattern.compile("^[\\w-]+\\d{2}-\\d{2}-\\d{4}\\.txt(?:\\.gz)?$", Pattern.MULTILINE);
    public static void main(String[] args) {
        String testString = "abcd_04-04-2020.txt\nabcd_04-04-2020.txt.gz\nsomethibsnfkns_05-06-2020.txt\n.txt.gz";
        Matcher matcher = pattern.matcher(testString);
        while(matcher.find()){
            System.out.println(matcher.group(0));
        }
    }
}

You can find the implementation of the above regex in java in here.

NOTE: If you want to match for valid dates also; please visit this.