问:
Is it necessary to secure the secret (e.g., key) in the .so file?
A private key has been #define in the C code of .so file. This key is used for the customized authentication process between client-server.

In some video and blog, people show how to disassemble .so file using IDA as well as extract function information. The output should be assembly language. How difficult to extract the key value from such output?

If the answer is the key defined in .so also needs protection, do I need to apply obfuscation on the C code before converting it to .so? Whether the normal algorithm will be affected for C?

答: It is possible and for skilled reverse engineer it is more or less easy. Obfuscating the secret key only slows down the hacker, but don't give you 100% protection. Consider using certificates signed by some authority.</p>


来源: stackexchange

问:
laravel route name parameter
Use a pageNation to request the value of the page to the controller. But why can't any parameters reach the controller?

```<code> Route::get('/index', 'Penpal\ViewController@index')->name('penpal.index');

 <form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="get">
            <select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
                    <option value="3">@lang('penpal/component/indexMenu.twelve')</option>
                    <option value="4">@lang('penpal/component/indexMenu.twenty_four')</option>
                    <option value="5">@lang('penpal/component/indexMenu.thirty_six')</option>
                </select>
        </form>

 public function index (Request $request){
    return $request;\
 }
</code>```

A parameter named "menu" cannot be received from the controller.

答:
You haven't set any route parameters for your route and neither passing any to your controller method. And it would be a better idea to use POST then GET.

Change this to

```<code>Route::get('/index', 'Penpal\ViewController@index')->name('penpal.index');
</code>```

this

```<code>Route::post('/index/{menu?}', 'Penpal\ViewController@index')->name('penpal.index');
</code>```

and your form

```<code><form action="{{ route('penpal.index', ['menu' => 'p11-c3']) }}" method="POST">
@csrf
</code>```

And in your controller method you can fetch the passed parameter

```<code> public function index (Request $request, $menu){
    print_r($menu);
 }
</code>```

ContentLicense: CC BY-SA 4.0

Title: laravel route name parameter

Body:
Use a pageNation to request the value of the page to the controller. But why can't any parameters reach the controller?

 Route::get('/index', 'Penpal\ViewController@index')->name('penpal.index');

 <form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="get">
            <select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
                    <option value="3">@lang('penpal/component/indexMenu.twelve')</option>
                    <option value="4">@lang('penpal/component/indexMenu.twenty_four')</option>
                    <option value="5">@lang('penpal/component/indexMenu.thirty_six')</option>
                </select>
        </form>

 public function index (Request $request){
    return $request;\
 }

A parameter named "menu" cannot be received from the controller.

Body:
You haven't set any route parameters for your route and neither passing any to your controller method. And it would be a better idea to use POST then GET.

Change this to

Route::get('/index', 'Penpal\ViewController@index')->name('penpal.index');

this

Route::post('/index/{menu?}', 'Penpal\ViewController@index')->name('penpal.index');

and your form

<form action="{{ route('penpal.index', ['menu' => 'p11-c3']) }}" method="POST">
@csrf

And in your controller method you can fetch the passed parameter

 public function index (Request $request, $menu){
    print_r($menu);
 }


问:
How to redirect textfields enter command of going to form submit instead of button midway form?
I'm using material UI as my component library. I have a small dialog that has a "recover password" button placed somewhere inside the form.  - I notice that after adding this button the "enter" command in the textfields becomes the onClick command of the buttons.

The form is simply like:

```<code>type PropTy = {
    classes: any,
    submit: (Event) => mixed;
    handleClose: (Event) => mixed;
    handleRequestPasswordRecover: (Event) => mixed;
};

function SigninForm(props:PropTy) {
    const {classes, submit, handleClose, handleRequestPasswordRecover} = props;
    const signinRef = React.createRef();

    const actions = [
        <Button
            type="reset"
            label="Reset"
            color="secondary"
            style={{ float: 'left' }}
            key='reset'
        >Reset</Button>,
        <Button
            label="Cancel"
            color="primary"
            onClick={handleClose}
            key='cancel'
        >Cancel</Button>,
        <Button
            type="submit"
            label="Submit"
            variant="contained"
            color="primary"
            key='submit'
            autoFocus
        >Login</Button>,
    ];

    return (
        <form className={classes.form}
              onSubmit={submit}
              ref={signinRef}
        >
            <FormControl margin="normal" required fullWidth>
                <TextField id="username" name="username" autoComplete="username" autoFocus label={'Username'}/>
            </FormControl>
            <FormControl margin="normal" required fullWidth>
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'baseline'}}>
                    <FormLabel htmlFor="password">Password</FormLabel>
                    <button className={classes.linkButton} onClick={(e) => {
                        handleRequestPasswordRecover(e)
                    }}>{'Lost password?'}</button>
                </div>
                <Input
                    name="password"
                    type="password"
                    id="password"
                    autoComplete="current-password"
                />
            </FormControl>
            <FormControlLabel
                control={<Checkbox value="remember" color="primary" />}
                label="Remember me"
            />
            <div style={{ textAlign: 'right'}}>
                {actions}
            </div>
        </form>);
}
</code>```

The action that happens on "enter" is not "submit" as I expect - but rather the button's onClick event (handleRequestPasswordRecover). How do I redirect this?

答:
You should set the type attribute of the button with the onClick={(e) => { handleRequestPasswordRecover(e)... to "button" (i.e. <button type="button"...).

The default type of buttons is submit.

Body:
I'm using material UI as my component library. I have a small dialog that has a "recover password" button placed somewhere inside the form.  - I notice that after adding this button the "enter" command in the textfields becomes the onClick command of the buttons.

The form is simply like:

type PropTy = {
    classes: any,
    submit: (Event) => mixed;
    handleClose: (Event) => mixed;
    handleRequestPasswordRecover: (Event) => mixed;
};

function SigninForm(props:PropTy) {
    const {classes, submit, handleClose, handleRequestPasswordRecover} = props;
    const signinRef = React.createRef();

    const actions = [
        <Button
            type="reset"
            label="Reset"
            color="secondary"
            style={{ float: 'left' }}
            key='reset'
        >Reset</Button>,
        <Button
            label="Cancel"
            color="primary"
            onClick={handleClose}
            key='cancel'
        >Cancel</Button>,
        <Button
            type="submit"
            label="Submit"
            variant="contained"
            color="primary"
            key='submit'
            autoFocus
        >Login</Button>,
    ];

    return (
        <form className={classes.form}
              onSubmit={submit}
              ref={signinRef}
        >
            <FormControl margin="normal" required fullWidth>
                <TextField id="username" name="username" autoComplete="username" autoFocus label={'Username'}/>
            </FormControl>
            <FormControl margin="normal" required fullWidth>

                    <FormLabel htmlFor="password">Password</FormLabel>
                    <button className={classes.linkButton} onClick={(e) => {
                        handleRequestPasswordRecover(e)
                    }}>{'Lost password?'}</button>

                <Input
                    name="password"
                    type="password"
                    id="password"
                    autoComplete="current-password"
                />
            </FormControl>
            <FormControlLabel
                control={<Checkbox value="remember" color="primary" />}
                label="Remember me"
            />

                {actions}

        </form>);
}

The action that happens on "enter" is not "submit" as I expect - but rather the button's onClick event (handleRequestPasswordRecover). How do I redirect this?


问:
What could be happened if at a dismissModalViewController call doesn't follow up a dealloc call?
I have a strange problem.
I set up a simple system that present modally a view. When i call dismiss for this modal view, the view disappear correctly but neither dealloc or viewDidUnload calls are done.

Here the code to make the view appear:

```<code>-(IBAction) spendBtnTap{
    SpendVC *spendVC = [[SpendVC alloc] initSpendWithContext:self.context];
    spendVC.delegate = self;
    [self presentModalViewController:spendVC animated:YES];
    [spendVC release];
}
</code>```

And the code to make the view disappear (from SpendVC.m):

```<code>-(void) pressBackBtn{
    [self.delegate dismissModalViewControllerAnimated:YES];
}
</code>```

And for dealloc in SpendVC ... i just added this output (But nothing happen in my console log...):

```<code>- (void)dealloc {
    NSLog(@"spend dealloc");
}
</code>```

In my application i have other button set this way... and they work correctly ... what can i missed?

答:
From the UIViewController docs:

viewDidUnload is called during low-memory conditions
  when the view controller needs to
  release its view and any objects
  associated with that view to free up
  memory

So it's not likely to be called.

As for dealloc, is something else retaining SpendVC?

ContentLicense: CC BY-SA 3.0

Body:
I have a strange problem.
I set up a simple system that present modally a view. When i call dismiss for this modal view, the view disappear correctly but neither dealloc or viewDidUnload calls are done.

Here the code to make the view appear:

-(IBAction) spendBtnTap{
    SpendVC *spendVC = [[SpendVC alloc] initSpendWithContext:self.context];
    spendVC.delegate = self;
    [self presentModalViewController:spendVC animated:YES];
    [spendVC release];
}

And the code to make the view disappear (from SpendVC.m):

-(void) pressBackBtn{
    [self.delegate dismissModalViewControllerAnimated:YES];
}

And for dealloc in SpendVC ... i just added this output (But nothing happen in my console log...):

- (void)dealloc {
    NSLog(@"spend dealloc");
}

In my application i have other button set this way... and they work correctly ... what can i missed?


问:
State managment for too large angular application
Recently I came across a situation In our application, I searched for the solution but nowhere found a proper answer, As you know we have more than 600+ modules in our application. As the user navigates to new pages the browser may fill up with new states and it's data. So we are planning to clear all other feature states as entering a new module. And only keeping the root state alive throughout the application. I would like to know whether my approach is right or not? if it is fine then what is the best way to do that?</p>

答:
I don't see why having a huge state would be an issue at all.

It would be an issue if you where writing a lot to it because as it's immutable you'd need to update all the references higher up in the chain. But if you touch another part of the state only when you're on a different module, then when the store is updated, the part that you didn't modify will be reused (by reference) which is really cheap.

One thing you could do on the other hand, is to watch from an effect when you leave the current module and trigger a cleanup (reset to default state?) for the current reducer.

About all the selectors, if you use createSelector it's using memoization and so as the reference will not change for "unused" part of the store, it'll return the previous value directly.

Why do you feel that need of cleaning up your state? I'm curious. If it's because of a perf issue I'd say that it's probably unrelated to that exactly.


问:
Whitelisting IP addresses for network traffic through Istio gateways
I tried whitelisting IP address/es in my kubernetes cluster's incoming traffic using this example :

Although this works as expected, wanted to go a step further and try if I can use istio gateways or virtual service when I set up Istio rule, instead of Loadbalancer(ingressgateway).

```<code>apiVersion: config.istio.io/v1alpha2
kind: rule
metadata:
  name: checkip
  namespace: my-namespace
spec:
  match: source.labels["app"] == "my-app"
  actions:
  - handler: whitelistip.listchecker
    instances:
    - sourceip.listentry
---
</code>```

Where my-app is of kind: Gateway with a certain host and port, and labelled app=my-app.

Am using istio version 1.1.1
Also my cluster has all the istio-system running with envoy sidecars on almost all service pods.

答:
You confuse one thing that, in above rule, match: source.labels["app"] == "my-app" is not referring to any resource's label, but to pod's label.

From OutputTemplate Documentation:

sourceLabels  | Refers to source pod labels.
  attributebindings can refer to this field using $out.sourcelabels

And you can verify by looking for resources with "app=istio-ingressgateway" label via:

```<code>kubectl get pods,svc -n istio-system -l "app=istio-ingressgateway" --show-labels
</code>```

You can check this blog from istio about Mixer Adapter Model, to understand complete mixer model, its handlers,instances and rules.

Hope it helps!

Body:
I tried whitelisting IP address/es in my kubernetes cluster's incoming traffic using this example :

Although this works as expected, wanted to go a step further and try if I can use istio gateways or virtual service when I set up Istio rule, instead of Loadbalancer(ingressgateway).

apiVersion: config.istio.io/v1alpha2
kind: rule
metadata:
  name: checkip
  namespace: my-namespace
spec:
  match: source.labels["app"] == "my-app"
  actions:
  - handler: whitelistip.listchecker
    instances:
    - sourceip.listentry
---

Where my-app is of kind: Gateway with a certain host and port, and labelled app=my-app.

Am using istio version 1.1.1
Also my cluster has all the istio-system running with envoy sidecars on almost all service pods.

Body:
You confuse one thing that, in above rule, match: source.labels["app"] == "my-app" is not referring to any resource's label, but to pod's label.

From OutputTemplate Documentation:

sourceLabels  | Refers to source pod labels.
  attributebindings can refer to this field using $out.sourcelabels

And you can verify by looking for resources with "app=istio-ingressgateway" label via:

kubectl get pods,svc -n istio-system -l "app=istio-ingressgateway" --show-labels

You can check this blog from istio about Mixer Adapter Model, to understand complete mixer model, its handlers,instances and rules.

Hope it helps!


问:
Django (PostgreSQL) query filter to exclude given letters
The user sends one of the letters from the following alphabet and I want to sent appropriate response.

As you can notice there is some mixture of Cyrillic and Latin. I have the following get_queryset method:

```<code>def get_queryset(self):
        SPECIAL_CHARACTERS = [
            'Аь', 'Гl', 'Кх', 'Къ', 'Кl', 'Оь', 'Хь', 'Хl', 'Цl', 'Чl', 'Юь', 'Яь'
        ]
        queryset = WordChechenModel.objects.all().order_by('word_chechen')
        first_letter = self.request.query_params.get('letter', None)
        if first_letter is not None:
            if len(first_letter) == 2:
                queryset = queryset.filter(
                    word_chechen__iregex=r"^w+%s" % first_letter)
            else:
                queryset = queryset.filter(Q(word_chechen__startswith=first_letter) | Q(
                    word_chechen__startswith=first_letter.upper())).exclude(
                    word_chechen__startswith__in=SPECIAL_CHARACTERS)
        return queryset
</code>```

In case that user sends a request for double(mixture) letter I can filter that using regex, but if a user sends request lets to say with Аь or some of the SPECIAL_CHARACTERS characters than I have problems.

Currently, I tried to exclude all words that start with one of the letters defined in SPECIAL_CHARACTERS using the following query:

```<code>queryset = queryset.filter(Q(word_chechen__startswith=first_letter) | Q(
                        word_chechen__startswith=first_letter.upper())).exclude(
                        word_chechen__startswith__in=SPECIAL_CHARACTERS)
            return queryset
</code>```

But this gives me the following error:

```<code>django.core.exceptions.FieldError: Unsupported lookup 'startswith' for CharField or join on the field not permitted, perhaps you meant s
tartswith or istartswith?
</code>```

I would be very grateful for the ideas. The speed of processing the request is important. Therefore, it would nice to get a review of my code at the same time.

答:
I've resolved this problem using regex, thx nigel222 for pointing on that. I found solution in this post https://stackoverflow.com/a/2667582/7986808

My working code:

```<code>def get_queryset(self):
        SPECIAL_CHARACTERS = [
            'Аь', 'Гl', 'Кх', 'Къ', 'Кl', 'Оь', 'Хь', 'Хl', 'Цl', 'Чl', 'Юь', 'Яь'
        ]
        queryset = WordChechenModel.objects.all().order_by('word_chechen')
        first_letter = self.request.query_params.get('letter', None)
        if first_letter is not None:
            if len(first_letter) == 2:
                queryset = queryset.filter(
                    word_chechen__regex=r"^%s" % first_letter)
            else:
                queryset = queryset.filter(
                    word_chechen__regex=r"^%s" % first_letter).exclude(
                        word_chechen__regex=r'(^' + '|^'.join(SPECIAL_CHARACTERS) + ')')
        return queryset
</code>```

Body:
The user sends one of the letters from the following alphabet and I want to sent appropriate response.

As you can notice there is some mixture of Cyrillic and Latin. I have the following get_queryset method:

def get_queryset(self):
        SPECIAL_CHARACTERS = [
            'Аь', 'Гl', 'Кх', 'Къ', 'Кl', 'Оь', 'Хь', 'Хl', 'Цl', 'Чl', 'Юь', 'Яь'
        ]
        queryset = WordChechenModel.objects.all().order_by('word_chechen')
        first_letter = self.request.query_params.get('letter', None)
        if first_letter is not None:
            if len(first_letter) == 2:
                queryset = queryset.filter(
                    word_chechen__iregex=r"^w+%s" % first_letter)
            else:
                queryset = queryset.filter(Q(word_chechen__startswith=first_letter) | Q(
                    word_chechen__startswith=first_letter.upper())).exclude(
                    word_chechen__startswith__in=SPECIAL_CHARACTERS)
        return queryset

In case that user sends a request for double(mixture) letter I can filter that using regex, but if a user sends request lets to say with Аь or some of the SPECIAL_CHARACTERS characters than I have problems.

Currently, I tried to exclude all words that start with one of the letters defined in SPECIAL_CHARACTERS using the following query:

queryset = queryset.filter(Q(word_chechen__startswith=first_letter) | Q(
                        word_chechen__startswith=first_letter.upper())).exclude(
                        word_chechen__startswith__in=SPECIAL_CHARACTERS)
            return queryset

But this gives me the following error:

django.core.exceptions.FieldError: Unsupported lookup 'startswith' for CharField or join on the field not permitted, perhaps you meant s
tartswith or istartswith?

I would be very grateful for the ideas. The speed of processing the request is important. Therefore, it would nice to get a review of my code at the same time.

Body:
I've resolved this problem using regex, thx nigel222 for pointing on that. I found solution in this post https://stackoverflow.com/a/2667582/7986808

My working code:

def get_queryset(self):
        SPECIAL_CHARACTERS = [
            'Аь', 'Гl', 'Кх', 'Къ', 'Кl', 'Оь', 'Хь', 'Хl', 'Цl', 'Чl', 'Юь', 'Яь'
        ]
        queryset = WordChechenModel.objects.all().order_by('word_chechen')
        first_letter = self.request.query_params.get('letter', None)
        if first_letter is not None:
            if len(first_letter) == 2:
                queryset = queryset.filter(
                    word_chechen__regex=r"^%s" % first_letter)
            else:
                queryset = queryset.filter(
                    word_chechen__regex=r"^%s" % first_letter).exclude(
                        word_chechen__regex=r'(^' + '|^'.join(SPECIAL_CHARACTERS) + ')')
        return queryset


问:
Where does Lynx broswer download files?
I am using Lynx command line browser on Ubuntu. I have a Generate Report button on my web page which when clicked, would download an Excel report from my Rails application.

I am not able to find where the downloaded files go.

Please help! Where do the downloaded files go in Lynx browser?

答:
Usually Lynx will save downloaded files in the same directory where you started Lynx.

For example, if you are at your home directory /path/to/myhomedir and start lynx there, then the downloaded file should be at /path/to/myhomedir/[downloaded-file]

Title: Where does Lynx broswer download files?


问:
OpenCV Calibration
I am little confused about world coordinates. How can we find the origin of world coordinate system.
Origin of camera coordinate system is behind the image plan on the optical axis at a distance of focal length. but how can we find the origin of world coordinate system.</p>

答:
Unlike the origin of the camera coordinate system which is at the centre of projection, the world coordinate system is not fixed and should be defined by you depending on the use case. The origin of the world coordinate system can be anywhere, independent of the origin of the camera coordinate system.

The transformation between world and camera coordinates is defined by the pinhole camera model. See this for a brief overview of the pinhole camera model.

Title: OpenCV Calibration


问:
Directory layout for pure Ruby project
I'm starting to learn ruby. I'm also a day-to-day C++ dev.
For C++ projects I usually go with following dir structure

```<code>/
 -/bin <- built binaries
 -/build <- build time temporary object (eg. .obj, cmake intermediates)
 -/doc <- manuals and/or Doxygen docs
 -/src
 --/module-1
 --/module-2
 -- non module specific sources, like main.cpp
 - IDE project files (.sln), etc.
</code>```

What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable?

答:
Why not use just the same layout? Normally you won't need build because there's no compilation step, but the rest seems OK to me.

I'm not sure what you mean by a module but if it's just a single class a separate folder wouldn't be necessary and if there's more than one file you normally write a module-1.rb file (at the name level as the module-1 folder) that does nothing more than require everything in module-1/.

Oh, and I would suggest using Rake for the management tasks (instead of make).

OwnerDisplayName: Dentharg

ContentLicense: CC BY-SA 2.5

Title: Directory layout for pure Ruby project

Body:
I'm starting to learn ruby. I'm also a day-to-day C++ dev.
For C++ projects I usually go with following dir structure

/
 -/bin <- built binaries
 -/build <- build time temporary object (eg. .obj, cmake intermediates)
 -/doc <- manuals and/or Doxygen docs
 -/src
 --/module-1
 --/module-2
 -- non module specific sources, like main.cpp
 - IDE project files (.sln), etc.

What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable?

LastEditorDisplayName: Dave L.

OwnerDisplayName: ujh


问:
Need help understanding how to version an iOS app
In Xcode I have Bundle Version and Bundle Version string, short.  There is also a version in iTunes Connect.  Just trying to see what I should use for each one and which one iOS uses to determine the version of the app so that a newer version properly replaces and older version.

答: Long story short: you can just set both Bundle Version and Bundle Version string short to to the same value. You will need to increase them between submissions. The version in iTunes Connect is the version displayed to the user in the App Store and does not have to match the version strings in your Info.plist</p>


问:
How to substitute $_POST inputs with fgets(STDIN) in PHP
I want to create PHP CLI CRUD Application. I started by simply creating MySQL connection and writing basic CRUD functions. Now I want to be able to accept data using PHP CLI, so I need to substitute $_POST with fgets(atleast, I think so). Never dealed with that before, so would appreciate any help.

```<code><?php

echo "Welcome to Company Register App" . "\n\n";

//establish database connection
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "root");
define ("DB_NAME", "mydatabase");

$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if($mysqli === false) {
    echo "Sorry, there seems to be a connection issue.";
} else {
    echo "We are connected". "\n\n";
}

//register function
function addCompany() {

    $name = "";
    $code = "";
    $phone = "";
    $comment = "";
    $id = 0;
    $update = false;

    if (isset($_POST['save'])) {
        $name = $_POST['name'];
        $code = $_POST['code'];
        $phone = $_POST['phone'];
        $comment = $_POST['comment'];

        mysqli_query($mysqli, "INSERT INTO mydatabase (name, code, email, phone, comment) VALUES ('$name', '$code', '$phone', '$comment')");

    }
}

?>
</code>```

I expect to be able to run this file and be prompted to enter info.

Thank you!

答:
Check for $argc and $argv variables. $argc should contain number of passed parameters and $argv is the array that contains passed parameters:

https://www.igorkromin.net/index.php/2017/12/07/how-to-pass-parameters-to-your-php-script-via-the-command-line/

Check it on php.net:

https://www.php.net/manual/en/reserved.variables.argv.php

https://www.php.net/manual/en/reserved.variables.argc.php

But also check ont getopt() function:

https://www.php.net/manual/en/function.getopt.php

Body:
I want to create PHP CLI CRUD Application. I started by simply creating MySQL connection and writing basic CRUD functions. Now I want to be able to accept data using PHP CLI, so I need to substitute $_POST with fgets(atleast, I think so). Never dealed with that before, so would appreciate any help.

<?php

echo "Welcome to Company Register App" . "\n\n";

//establish database connection
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "root");
define ("DB_NAME", "mydatabase");

$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if($mysqli === false) {
    echo "Sorry, there seems to be a connection issue.";
} else {
    echo "We are connected". "\n\n";
}

//register function
function addCompany() {

    $name = "";
    $code = "";
    $phone = "";
    $comment = "";
    $id = 0;
    $update = false;

    if (isset($_POST['save'])) {
        $name = $_POST['name'];
        $code = $_POST['code'];
        $phone = $_POST['phone'];
        $comment = $_POST['comment'];

        mysqli_query($mysqli, "INSERT INTO mydatabase (name, code, email, phone, comment) VALUES ('$name', '$code', '$phone', '$comment')");

    }
}

?>

I expect to be able to run this file and be prompted to enter info.

Thank you!


问:
Cannot deploy Node.js app inside AWS Lambda using Serverless Framework
I am new to serverless framework.
I was trying to deploy my code to lambda using serverless.

```<code>service:
  name: store-consumer

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: ap-XXXXXX-1

functions:
  lambda:
    handler: index.handler
</code>```

The content of the serverless.yml file is as given above.
But when I hit 'sls deploy' in terminal my code is zipped and uploaded to an s3 bucket. How do I deploy my code to the corresponding lambda using serverless?

I assume I 'll have to give some credentials for the lambda, but how do I do that in the .yml file?! What am I not getting correctly?

答:
You can specify the Lambda function name explicitly using the name field. Example:

```<code>service:
  name: store-consumer

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: ap-XXXXXX-1

functions:
  lambda:
    handler: index.handler
    name: myfunc
</code>```

With this config file your deployed Lambda function will have the name myfunc.

See line 129 in https://serverless.com/framework/docs/providers/aws/guide/serverless.yml/.

Using the name of an already existing Lambda function will not work, you still have to delete old the Lambda function beforehand.

Body:
I am new to serverless framework.
I was trying to deploy my code to lambda using serverless.

service:
  name: store-consumer

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: ap-XXXXXX-1

functions:
  lambda:
    handler: index.handler

The content of the serverless.yml file is as given above.
But when I hit 'sls deploy' in terminal my code is zipped and uploaded to an s3 bucket. How do I deploy my code to the corresponding lambda using serverless?

I assume I 'll have to give some credentials for the lambda, but how do I do that in the .yml file?! What am I not getting correctly?

Body:
You can specify the Lambda function name explicitly using the name field. Example:

service:
  name: store-consumer

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: ap-XXXXXX-1

functions:
  lambda:
    handler: index.handler
    name: myfunc

With this config file your deployed Lambda function will have the name myfunc.

See line 129 in https://serverless.com/framework/docs/providers/aws/guide/serverless.yml/.

Using the name of an already existing Lambda function will not work, you still have to delete old the Lambda function beforehand.


问:
How to replace a substring in a line that contains another substring
I have this lines.

I want for each line that contains "Id" of any case to replace "string" with int.

Not sure how to do grouping for this.

This is my list

I've tried something like this ^(.*(string).*(Id).*)$ and replace with \1 or \2

```<code>public string ID {get; set}
public string IdSite {get; set}
public string IdParent {get; set}
public string IdPageType {get; set}
public string PageType {get; set}
public string IdTemplate {get; set}
public string TemplateName {get; set}
public string IdTemplateParent {get; set}
</code>```

答:
You don't need to match entire line or capture anything. Instead try:

```<code>string(?=.*?id)
</code>```

The positive lookahead asserts that id comes somewhere after string. Also to match id in any form you should enable case-insensitive match or use [iI][dD] in favor of id.

Body:
I have this lines.

I want for each line that contains "Id" of any case to replace "string" with int.

Not sure how to do grouping for this.

This is my list

I've tried something like this ^(.*(string).*(Id).*)$ and replace with \1 or \2

public string ID {get; set}
public string IdSite {get; set}
public string IdParent {get; set}
public string IdPageType {get; set}
public string PageType {get; set}
public string IdTemplate {get; set}
public string TemplateName {get; set}
public string IdTemplateParent {get; set}

Body:
You don't need to match entire line or capture anything. Instead try:

string(?=.*?id)

The positive lookahead asserts that id comes somewhere after string. Also to match id in any form you should enable case-insensitive match or use [iI][dD] in favor of id.


问:
How to get the xPath of an element
I'm trying to get the value of the data-content_published_date attribute which is published date of an article with xPath but for some reason I cant!

Here is how I tried:

```<code>//div[@id='page-segment-values']/@data-content_published_date
</code>```

And here is the div tag:

```<code><div id="page-segment-values" class="">
  <div class="keyvals" data-content_author_name="Eli Meixler" data-content_cms_id="5461956" data-content_headline="British Academic" data-content_modified_date="" data-content_published_date="2018-11-22T08:15:43.000Z" data-content_shown_on_platform="own" data-content_type="article" data-path="/5461956/british-academic-sentenced-spying-united-arab-emirates/" data-referrer="" data-search="" data-content_is_post="post" data-title="A British Academic Has Been Sentenced to Life in Prison on Espionage Charges in the United Arab Emirates" data-affiliate_link_count="0" data-content_cms_category="World" data-content_cms_tags="onetime|overnight|United Arab Emirates" data-content_cms_terms="World,onetime,overnight,United Arab Emirates" data-time_inc_brand="time.com" data-time_inc_application="front end" data-content_syndicated="false" data-content_syndicated_brand="" data-content_syndicated_url="" data-content_nlp_sentiment_label="negative" data-content_nlp_sentiment_score="-0.2" data-content_nlp_sentiment_magnitude="5.9" data-content_nlp_entities="Matthew Hedges" data-content_nlp_payload="{"entities":[{"type":"PERSON","text":"Matthew Hedges","relevance":0.57477295,"disambiguation":{}},{"type":"WORK_OF_ART","text":"British Academic Sentenced to Life on Spying Charges","relevance":0.02937225,"disambiguation":{}},{"type":"LOCATION","text":"British","relevance":0.029201617,"disambiguation":{"mid":"\/m\/07ssc","wikipedia_url":"https:\/\/en.wikipedia.org\/wiki\/United_Kingdom"}},{"type":"PERSON","text":"academic","relevance":0.020707963,"disambiguation":{}},{"type":"OTHER","text":"life","relevance":0.018888554,"disambiguation":{}},{"type":"OTHER","text":"spying charges","relevance":0.013851213,"disambiguation":{}},{"type":"LOCATION","text":"prison","relevance":0.0133453375,"disambiguation":{}},{"type":"LOCATION","text":"United Arab Emirates","relevance":0.011457251,"disambiguation":{"wikipedia_url":"https:\/\/en.wikipedia.org\/wiki\/United_Arab_Emirates","mid":"\/m\/0j1z8"}},{"type":"OTHER","text":"threats","relevance":0.009783207,"disambiguation":{}},{"type":"EVENT","text":"blowback","relevance":0.009783207,"disambiguation":{}}],"categories":[{"label":"\/Law & Government\/Public Safety\/Crime & Justice","score":0.64}],"docSentiment":{"magnitude":5.9,"score":-0.2,"label":"negative"},"language":"en"}" data-content_nlp_categories="/Law & Government/Public Safety/Crime & Justice"></div>
</div>
</code>```

Anyone has any idea why can't I access the value of it? And how to get it?

答:
Use the inner
 element and the attribute you are looking after.

```<code>//div[@class='keyvals']/@data-content_published_date
</code>```

Title: How to get the xPath of an element

Body:
I'm trying to get the value of the data-content_published_date attribute which is published date of an article with xPath but for some reason I cant!

Here is how I tried:

//div[@id='page-segment-values']/@data-content_published_date

And here is the div tag:

  <div class="keyvals" data-content_author_name="Eli Meixler" data-content_cms_id="5461956" data-content_headline="British Academic" data-content_modified_date="" data-content_published_date="2018-11-22T08:15:43.000Z" data-content_shown_on_platform="own" data-content_type="article" data-path="/5461956/british-academic-sentenced-spying-united-arab-emirates/" data-referrer="" data-search="" data-content_is_post="post" data-title="A British Academic Has Been Sentenced to Life in Prison on Espionage Charges in the United Arab Emirates" data-affiliate_link_count="0" data-content_cms_category="World" data-content_cms_tags="onetime|overnight|United Arab Emirates" data-content_cms_terms="World,onetime,overnight,United Arab Emirates" data-time_inc_brand="time.com" data-time_inc_application="front end" data-content_syndicated="false" data-content_syndicated_brand="" data-content_syndicated_url="" data-content_nlp_sentiment_label="negative" data-content_nlp_sentiment_score="-0.2" data-content_nlp_sentiment_magnitude="5.9" data-content_nlp_entities="Matthew Hedges" data-content_nlp_payload="{"entities":[{"type":"PERSON","text":"Matthew Hedges","relevance":0.57477295,"disambiguation":{}},{"type":"WORK_OF_ART","text":"British Academic Sentenced to Life on Spying Charges","relevance":0.02937225,"disambiguation":{}},{"type":"LOCATION","text":"British","relevance":0.029201617,"disambiguation":{"mid":"\/m\/07ssc","wikipedia_url":"https:\/\/en.wikipedia.org\/wiki\/United_Kingdom"}},{"type":"PERSON","text":"academic","relevance":0.020707963,"disambiguation":{}},{"type":"OTHER","text":"life","relevance":0.018888554,"disambiguation":{}},{"type":"OTHER","text":"spying charges","relevance":0.013851213,"disambiguation":{}},{"type":"LOCATION","text":"prison","relevance":0.0133453375,"disambiguation":{}},{"type":"LOCATION","text":"United Arab Emirates","relevance":0.011457251,"disambiguation":{"wikipedia_url":"https:\/\/en.wikipedia.org\/wiki\/United_Arab_Emirates","mid":"\/m\/0j1z8"}},{"type":"OTHER","text":"threats","relevance":0.009783207,"disambiguation":{}},{"type":"EVENT","text":"blowback","relevance":0.009783207,"disambiguation":{}}],"categories":[{"label":"\/Law & Government\/Public Safety\/Crime & Justice","score":0.64}],"docSentiment":{"magnitude":5.9,"score":-0.2,"label":"negative"},"language":"en"}" data-content_nlp_categories="/Law & Government/Public Safety/Crime & Justice">

Anyone has any idea why can't I access the value of it? And how to get it?

Body:
Use the inner <div> element and the attribute you are looking after.

//div[@class='keyvals']/@data-content_published_date


问:
dictionary update sequence element #0 has length 3; 2 is required
I want to add lines to the object account.bank.statement.line through other object But I get following error:

"dictionary update sequence element #0 has length 3; 2 is required"

Here is my code:

```<code>def action_account_line_create(self, cr, uid, ids):
    res = False
    cash_id = self.pool.get('account.bank.statement.line')
    for exp in self.browse(cr, uid, ids):
        company_id = exp.company_id.id
        #statement_id = exp.statement_id.id
        lines = []
        for l in exp.line_ids:
            lines.append((0, 0, {
                'name': l.name,
                'date': l.date,
                'amount': l.amount,
                'type': l.type,
                'statement_id': exp.statement_id.id,
                'account_id': l.account_id.id,
                'account_analytic_id': l.analytic_account_id.id,
                'ref': l.ref,
                'note': l.note,
                'company_id': l.company_id.id
            }))

        inv_id = cash_id.create(cr, uid, lines,context=None)
        res = inv_id
    return res
</code>```

I changed it on that but then I ran into this error:

```<code>  File "C:\Program Files (x86)\OpenERP 6.1-20121029-003136\Server\server\.\openerp\workflow\wkf_expr.py", line 68, in execute
  File "C:\Program Files (x86)\OpenERP 6.1-20121029-003136\Server\server\.\openerp\workflow\wkf_expr.py", line 58, in _eval_expr
  File "C:\Program Files (x86)\OpenERP 6.1-20121029-003136\Server\server\.\openerp\tools\safe_eval.py", line 241, in safe_eval
  File "C:\Program Files (x86)\OpenERP 6.1-20121029-003136\Server\server\.\openerp\tools\safe_eval.py", line 108, in test_expr
  File "<string>", line 0
   ^
SyntaxError: unexpected EOF while parsing
</code>```

Code:

```<code>def action_account_line_create(self, cr, uid, ids, context=None):
    res = False
    cash_id = self.pool.get('account.bank.statement.line')
    for exp in self.browse(cr, uid, ids):
        company_id = exp.company_id.id
        lines = []
        for l in exp.line_ids:
            res = cash_id.create ( cr, uid, {
                'name': l.name,
                'date': l.date,
                'amount': l.amount,
                'type': l.type,
                'statement_id': exp.statement_id.id,
                'account_id': l.account_id.id,
                'account_analytic_id': l.analytic_account_id.id,
                'ref': l.ref,
                'note': l.note,
                'company_id': l.company_id.id
            }, context=None)
    return res
</code>```

答:
One of the fast ways to create a dict from equal-length tuples:</p>

```<code>>>> t1 = (a,b,c,d)
>>> t2 = (1,2,3,4)
>>> dict(zip(t1, t2))
{'a':1, 'b':2, 'c':3, 'd':4, }
</code>```

Body:
I want to add lines to the object account.bank.statement.line through other object But I get following error:

"dictionary update sequence element #0 has length 3; 2 is required"

Here is my code:

def action_account_line_create(self, cr, uid, ids):
    res = False
    cash_id = self.pool.get('account.bank.statement.line')
    for exp in self.browse(cr, uid, ids):
        company_id = exp.company_id.id
        #statement_id = exp.statement_id.id
        lines = []
        for l in exp.line_ids:
            lines.append((0, 0, {
                'name': l.name,
                'date': l.date,
                'amount': l.amount,
                'type': l.type,
                'statement_id': exp.statement_id.id,
                'account_id': l.account_id.id,
                'account_analytic_id': l.analytic_account_id.id,
                'ref': l.ref,
                'note': l.note,
                'company_id': l.company_id.id
            }))

        inv_id = cash_id.create(cr, uid, lines,context=None)
        res = inv_id
    return res

I changed it on that but then I ran into this error:

  File "C:\Program Files (x86)\OpenERP 6.1-20121029-003136\Server\server\.\openerp\workflow\wkf_expr.py", line 68, in execute
  File "C:\Program Files (x86)\OpenERP 6.1-20121029-003136\Server\server\.\openerp\workflow\wkf_expr.py", line 58, in _eval_expr
  File "C:\Program Files (x86)\OpenERP 6.1-20121029-003136\Server\server\.\openerp\tools\safe_eval.py", line 241, in safe_eval
  File "C:\Program Files (x86)\OpenERP 6.1-20121029-003136\Server\server\.\openerp\tools\safe_eval.py", line 108, in test_expr
  File "<string>", line 0
   ^
SyntaxError: unexpected EOF while parsing

Code:

def action_account_line_create(self, cr, uid, ids, context=None):
    res = False
    cash_id = self.pool.get('account.bank.statement.line')
    for exp in self.browse(cr, uid, ids):
        company_id = exp.company_id.id
        lines = []
        for l in exp.line_ids:
            res = cash_id.create ( cr, uid, {
                'name': l.name,
                'date': l.date,
                'amount': l.amount,
                'type': l.type,
                'statement_id': exp.statement_id.id,
                'account_id': l.account_id.id,
                'account_analytic_id': l.analytic_account_id.id,
                'ref': l.ref,
                'note': l.note,
                'company_id': l.company_id.id
            }, context=None)
    return res

Body:
One of the fast ways to create a dict from equal-length tuples:

>>> t1 = (a,b,c,d)
>>> t2 = (1,2,3,4)
>>> dict(zip(t1, t2))
{'a':1, 'b':2, 'c':3, 'd':4, }


问:
Why there is Pig and Hive
I understood what are the components of Hadoop, but my question is:
As an end user, how can I access a file in Hadoop without worrying about the data storage?

So when using Pig/Hive commands, should I worry if the data storage is HDFS or HBase?

Thank you

答:
Pig is used when the data is unstructured and has no schema.
Database recommended - HDFS.

Hive is used when the data is structured and has a schema available.
Database recommended - Hbase.

Title: Why there is Pig and Hive


问:
Use serial UART output as input in other serial terminal on Windows 10
I would like to use UART communication to synchronize the clocks of two microcontrollers of different manufacturers. How can I relay outputs from one microcontroller to the other, as input? (Windows 10)

Are there specific programs I should use? Currently both microcontrollers can communicate with their own Putty terminals, but I would like to let them communicate with each other as well.

答:
Your goal here is, once you have both microcontrollers connected to your Windows 10 PC and communicating correctly, forward data from one of them to the other through your computer (in a kind of man-in-the-middle or sniffer arrangement).

You can accomplish that easily with Termite, following these steps:

-Download and install Termite from here: https://www.compuphase.com/software/termite-3.4.exe

-Open <s>two</s> instances of the software and go to "Settings" and make sure the parameters of your serial port<s>s</s> are correct (baud rate, data bits, stop bits)

-On one of the ports, in the same settings dialog box choose the other port under the option "Forwarding"

-Click on the bottom with the port parameters on each instance of Termite to open the port and establish the forwarding link

Quoting from Termite's manual:

With forwarding set up, all data received on the primary port is transmitted through the forward port. All data received on the forward port is transmitted through the primary port. The "sent/received colouring" of Termite is also still in effect: data received on the primary port is in green and data received on the secondary port is in blue.

In this configuration, Termite would typically only be used to monitor the communication between two devices. If you type in text on the edit line and transmit it, this text is only sent through the primary port.

EDIT: I made a quick test of the setup above and I realized there is actually no need to open two instances of Termite. You just have to setup one of the ports and select the other as the forwarding output.

I tested sending text from a serial port on a SBC (minicom Linux window in the screenshot), receiving on COM4 and forwarding to COM5 on a Windows 7 VM. The characters are indeed forwarded to COM5 (scope picture). So the chain is as follows:

```<code>SBC Serial (minicom)--->Termite COM4--->Termite COM5--->Oscilloscope
</code>```

This can be indeed used a very simple serial port sniffer.

Body:
Your goal here is, once you have both microcontrollers connected to your Windows 10 PC and communicating correctly, forward data from one of them to the other through your computer (in a kind of man-in-the-middle or sniffer arrangement).

You can accomplish that easily with Termite, following these steps:

-Download and install Termite from here: https://www.compuphase.com/software/termite-3.4.exe

-Open <s>two</s> instances of the software and go to "Settings" and make sure the parameters of your serial port<s>s</s> are correct (baud rate, data bits, stop bits)

-On one of the ports, in the same settings dialog box choose the other port under the option "Forwarding"

-Click on the bottom with the port parameters on each instance of Termite to open the port and establish the forwarding link

Quoting from Termite's manual:

With forwarding set up, all data received on the primary port is transmitted through the forward port. All data received on the forward port is transmitted through the primary port. The "sent/received colouring" of Termite is also still in effect: data received on the primary port is in green and data received on the secondary port is in blue.

In this configuration, Termite would typically only be used to monitor the communication between two devices. If you type in text on the edit line and transmit it, this text is only sent through the primary port.

EDIT: I made a quick test of the setup above and I realized there is actually no need to open two instances of Termite. You just have to setup one of the ports and select the other as the forwarding output.

I tested sending text from a serial port on a SBC (minicom Linux window in the screenshot), receiving on COM4 and forwarding to COM5 on a Windows 7 VM. The characters are indeed forwarded to COM5 (scope picture). So the chain is as follows:

SBC Serial (minicom)--->Termite COM4--->Termite COM5--->Oscilloscope

This can be indeed used a very simple serial port sniffer.


问:
Extracing elements from a nested list based on elements of another nested list
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

```<code>users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

</code>```

答:
Using list comprehension and map.

list(map(lambda x: (x[0], set([ul[1] for u in x[1] for ul in users if ul[0]==u])), prod))
```

<p>Output</p>

```[(1005, {'US'}),
 (1004, {'EN', 'FR', 'MX'}),
 (1003, {'US'}),
 (1002, {'EN', 'MX', 'US'}),
 (1001, {'EN', 'MX', 'US'})]
```

<p>To get a dictionary simply pass the output of <code>map</code> to <code>dict</code>.</p>

<pre class="lang-py prettyprint-override"><code>dict(map(lambda x: (x[0], set([ul[1] for u in x[1] for ul in users if ul[0]==u])), prod))
</code>```

Output

```<code>{1005: {'US'},
 1004: {'EN', 'FR', 'MX'},
 1003: {'US'},
 1002: {'EN', 'MX', 'US'},
 1001: {'EN', 'MX', 'US'}}
</code>```

Body:
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

Body:
Using list comprehension and map.

list(map(lambda x: (x[0], set([ul[1] for u in x[1] for ul in users if ul[0]==u])), prod))

Output

[(1005, {'US'}),
 (1004, {'EN', 'FR', 'MX'}),
 (1003, {'US'}),
 (1002, {'EN', 'MX', 'US'}),
 (1001, {'EN', 'MX', 'US'})]

To get a dictionary simply pass the output of map to dict.

dict(map(lambda x: (x[0], set([ul[1] for u in x[1] for ul in users if ul[0]==u])), prod))

Output

{1005: {'US'},
 1004: {'EN', 'FR', 'MX'},
 1003: {'US'},
 1002: {'EN', 'MX', 'US'},
 1001: {'EN', 'MX', 'US'}}


问:
Access React types in props interface
I have a functional component like so:

```<code>import React, { memo } from 'react';

import {
  ButtonStyled,
  LinkStyled,
  Text,
} from './index.style';

export interface Props {
  buttonType?: string;
  handleClick?: () => void;
  href?: string;
  invertColors?: boolean;
  isDisabled?: boolean;
  isLoading?: boolean;
  text: string;
  variant?: 'dark' | 'light';
}

const defaultProps = {
  buttonType: 'button',
  handleClick: null,
  href: null,
  invertColors: false,
  isDisabled: false,
  isLoading: false,
  variant: 'dark',
};

const Button = ({
  buttonType,
  handleClick,
  href,
  isDisabled,
  isLoading,
  text,
  variant,
}: Props) => {
  if (href) {
    return (
      <LinkStyled
        href={href}
        isDisabled={isDisabled}
        isLoading={isLoading}
        variant={variant}
      >
        <Text isLoading={isLoading}>
          {text}
        </Text>
      </LinkStyled>
    );
  }

  return (
    <ButtonStyled
      disabled={isDisabled}
      isDisabled={isDisabled}
      isLoading={isLoading}
      onClick={handleClick}
      type={buttonType}
      variant={variant}
    >
      <Text isLoading={isLoading}>
        {text}
      </Text>
    </ButtonStyled>
  );
};

Button.defaultProps = defaultProps;

export default memo(Button);
</code>```

There is a single Typescript error in this file and it's to do with the line type={buttonType}. The error is:

```<code>Type 'string | undefined' is not assignable to type '"button" | "reset" | "submit" | undefined'.
</code>```

I understand this error. React types have declared the 'type' attribute must be either 'button', 'reset', 'submit' or 'undefined' but I have set my props to be either string or undefined.

My question is, how do I assign the options from React to my props to avoid duplication by typing out all the options manually?

EDIT: The full error here:

```<code>Type 'string | undefined' is not assignable to type '"button" | "reset" | "submit" | undefined'.
  Type 'string' is not assignable to type '"button" | "reset" | "submit" | undefined'.ts(2322)
index.d.ts(1849, 9): The expected type comes from property 'type' which is declared here on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | "style" | "title" | "className" | "color" | ... 259 more ... | "value"> & { ...; } & ButtonStyledProps, "isDisabled" | ... 267 more ... | "value"> & Partial<...>, "isDisabled" | ... 267 more ....'
</code>```

The type in question from @types/react looks like this:

```<code>interface ButtonHTMLAttributes<T> extends HTMLAttributes<T> {
  autoFocus?: boolean;
  disabled?: boolean;
  form?: string;
  formAction?: string;
  formEncType?: string;
  formMethod?: string;
  formNoValidate?: boolean;
  formTarget?: string;
  name?: string;
  type?: 'submit' | 'reset' | 'button';
  value?: string | string[] | number;
}
</code>```

答:
You can use a type query to get access to the type of type:

```<code>type ButtonType = JSX.IntrinsicElements['button']['type']
</code>```

Using this type (or directly the type query) as the type for buttonType should solve your issue:

```<code>export interface Props {
  buttonType?: ButtonType; // or directly JSX.IntrinsicElements['button']['type']
  handleClick?: () => void;
  href?: string;
  invertColors?: boolean;
  isDisabled?: boolean;
  isLoading?: boolean;
  text: string;
  variant?: 'dark' | 'light';
}
</code>```

Title: Access React types in props interface

Body:
I have a functional component like so:

import React, { memo } from 'react';

import {
  ButtonStyled,
  LinkStyled,
  Text,
} from './index.style';

export interface Props {
  buttonType?: string;
  handleClick?: () => void;
  href?: string;
  invertColors?: boolean;
  isDisabled?: boolean;
  isLoading?: boolean;
  text: string;
  variant?: 'dark' | 'light';
}

const defaultProps = {
  buttonType: 'button',
  handleClick: null,
  href: null,
  invertColors: false,
  isDisabled: false,
  isLoading: false,
  variant: 'dark',
};

const Button = ({
  buttonType,
  handleClick,
  href,
  isDisabled,
  isLoading,
  text,
  variant,
}: Props) => {
  if (href) {
    return (
      <LinkStyled
        href={href}
        isDisabled={isDisabled}
        isLoading={isLoading}
        variant={variant}
      >
        <Text isLoading={isLoading}>
          {text}
        </Text>
      </LinkStyled>
    );
  }

  return (
    <ButtonStyled
      disabled={isDisabled}
      isDisabled={isDisabled}
      isLoading={isLoading}
      onClick={handleClick}
      type={buttonType}
      variant={variant}
    >
      <Text isLoading={isLoading}>
        {text}
      </Text>
    </ButtonStyled>
  );
};

Button.defaultProps = defaultProps;

export default memo(Button);

There is a single Typescript error in this file and it's to do with the line type={buttonType}. The error is:

Type 'string | undefined' is not assignable to type '"button" | "reset" | "submit" | undefined'.

I understand this error. React types have declared the 'type' attribute must be either 'button', 'reset', 'submit' or 'undefined' but I have set my props to be either string or undefined.

My question is, how do I assign the options from React to my props to avoid duplication by typing out all the options manually?

EDIT: The full error here:

Type 'string | undefined' is not assignable to type '"button" | "reset" | "submit" | undefined'.
  Type 'string' is not assignable to type '"button" | "reset" | "submit" | undefined'.ts(2322)
index.d.ts(1849, 9): The expected type comes from property 'type' which is declared here on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | "style" | "title" | "className" | "color" | ... 259 more ... | "value"> & { ...; } & ButtonStyledProps, "isDisabled" | ... 267 more ... | "value"> & Partial<...>, "isDisabled" | ... 267 more ....'

The type in question from @types/react looks like this:

interface ButtonHTMLAttributes<T> extends HTMLAttributes<T> {
  autoFocus?: boolean;
  disabled?: boolean;
  form?: string;
  formAction?: string;
  formEncType?: string;
  formMethod?: string;
  formNoValidate?: boolean;
  formTarget?: string;
  name?: string;
  type?: 'submit' | 'reset' | 'button';
  value?: string | string[] | number;
}

Body:
You can use a type query to get access to the type of type:

type ButtonType = JSX.IntrinsicElements['button']['type']

Using this type (or directly the type query) as the type for buttonType should solve your issue:

export interface Props {
  buttonType?: ButtonType; // or directly JSX.IntrinsicElements['button']['type']
  handleClick?: () => void;
  href?: string;
  invertColors?: boolean;
  isDisabled?: boolean;
  isLoading?: boolean;
  text: string;
  variant?: 'dark' | 'light';
}


问:
How to redirect textfields enter command of going to form submit instead of button midway form?
I'm using material UI as my component library. I have a small dialog that has a "recover password" button placed somewhere inside the form.  - I notice that after adding this button the "enter" command in the textfields becomes the onClick command of the buttons.

The form is simply like:

```<code>type PropTy = {
    classes: any,
    submit: (Event) => mixed;
    handleClose: (Event) => mixed;
    handleRequestPasswordRecover: (Event) => mixed;
};

function SigninForm(props:PropTy) {
    const {classes, submit, handleClose, handleRequestPasswordRecover} = props;
    const signinRef = React.createRef();

    const actions = [
        <Button
            type="reset"
            label="Reset"
            color="secondary"
            style={{ float: 'left' }}
            key='reset'
        >Reset</Button>,
        <Button
            label="Cancel"
            color="primary"
            onClick={handleClose}
            key='cancel'
        >Cancel</Button>,
        <Button
            type="submit"
            label="Submit"
            variant="contained"
            color="primary"
            key='submit'
            autoFocus
        >Login</Button>,
    ];

    return (
        <form className={classes.form}
              onSubmit={submit}
              ref={signinRef}
        >
            <FormControl margin="normal" required fullWidth>
                <TextField id="username" name="username" autoComplete="username" autoFocus label={'Username'}/>
            </FormControl>
            <FormControl margin="normal" required fullWidth>
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'baseline'}}>
                    <FormLabel htmlFor="password">Password</FormLabel>
                    <button className={classes.linkButton} onClick={(e) => {
                        handleRequestPasswordRecover(e)
                    }}>{'Lost password?'}</button>
                </div>
                <Input
                    name="password"
                    type="password"
                    id="password"
                    autoComplete="current-password"
                />
            </FormControl>
            <FormControlLabel
                control={<Checkbox value="remember" color="primary" />}
                label="Remember me"
            />
            <div style={{ textAlign: 'right'}}>
                {actions}
            </div>
        </form>);
}
</code>```

The action that happens on "enter" is not "submit" as I expect - but rather the button's onClick event (handleRequestPasswordRecover). How do I redirect this?

答:
Inside submit function you can call preventDefault();

const submit = (event)=>{    event.preventDefault(); }

Body:
I'm using material UI as my component library. I have a small dialog that has a "recover password" button placed somewhere inside the form.  - I notice that after adding this button the "enter" command in the textfields becomes the onClick command of the buttons.

The form is simply like:

type PropTy = {
    classes: any,
    submit: (Event) => mixed;
    handleClose: (Event) => mixed;
    handleRequestPasswordRecover: (Event) => mixed;
};

function SigninForm(props:PropTy) {
    const {classes, submit, handleClose, handleRequestPasswordRecover} = props;
    const signinRef = React.createRef();

    const actions = [
        <Button
            type="reset"
            label="Reset"
            color="secondary"
            style={{ float: 'left' }}
            key='reset'
        >Reset</Button>,
        <Button
            label="Cancel"
            color="primary"
            onClick={handleClose}
            key='cancel'
        >Cancel</Button>,
        <Button
            type="submit"
            label="Submit"
            variant="contained"
            color="primary"
            key='submit'
            autoFocus
        >Login</Button>,
    ];

    return (
        <form className={classes.form}
              onSubmit={submit}
              ref={signinRef}
        >
            <FormControl margin="normal" required fullWidth>
                <TextField id="username" name="username" autoComplete="username" autoFocus label={'Username'}/>
            </FormControl>
            <FormControl margin="normal" required fullWidth>

                    <FormLabel htmlFor="password">Password</FormLabel>
                    <button className={classes.linkButton} onClick={(e) => {
                        handleRequestPasswordRecover(e)
                    }}>{'Lost password?'}</button>

                <Input
                    name="password"
                    type="password"
                    id="password"
                    autoComplete="current-password"
                />
            </FormControl>
            <FormControlLabel
                control={<Checkbox value="remember" color="primary" />}
                label="Remember me"
            />

                {actions}

        </form>);
}

The action that happens on "enter" is not "submit" as I expect - but rather the button's onClick event (handleRequestPasswordRecover). How do I redirect this?


问:
How to extract data from nested JSON with Swift 4 with dynamic keys
I have a JSON data structure using unique keys that are created on upload. I can read all of it if I read each dictionary item line by line. However, I'm trying to modify my code to use the Swift 4 codable properties.

Doing the Ray Wenderlich tutorial and reading the Ultimate Guide to JSON Parsing with Swift unfortunately did not propel me to genius status.

The JSON looks like this simple example:
NOTE that keys, like "123", "456", "case1", "case2", "u1", "u2" are not known at run time.

```<code>   let json = """
    {
    "things" : {
        "123" : {
        "name" : "Party",
        "owner" : "Bob",
        "isActive" : true,
        "cases" : {
            "case1" : {
                "no" : 1
            },
            "case2" : {
                "no" : 2
            }
        }
        },
        "456" : {
        "name" : "Bus",
        "owner" : "Joe",
        "isActive" : true
        }
    },
    "users" : {
        "u1" : {
        "name" : "Summer"
        },
        "u2" : {
        "name" : "Daffy"
        }
    }
    }
    """
</code>```

Following this SO question on flattening JSON, I was able to create a decoder for most of my data, but not for the nested dictionaries (in the example, cases is acting like a nested dictionary). I am sure that I am missing something simple.

If I attempt to include the commented out portion, the playground will not run, no error is given.

```<code>    struct Thing: Decodable {
    let id: String
    let isActive: Bool
    let name: String
    let owner: String
    //var cases = [Case]()

    init(id: String, isActive: Bool, name: String, owner: String){//}, cases: [Case]?) {
        self.id = id
        self.isActive = isActive
        self.name = name
        self.owner = owner
        //self.cases = cases ?? [Case(id: "none", caseNumber: 0)]
    }
}
struct User: Decodable {
    let id: String
    let name: String
}
struct Case: Decodable {
    let id: String
    let caseNumber: Int
}
struct ResponseData: Decodable {
    var things = [Thing]()
    var users = [User]()

    enum CodingKeys: String, CodingKey {
        case trips
        case users
    }

    private struct PhantomKeys: CodingKey {
        var intValue: Int?
        var stringValue: String
        init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
        init?(stringValue: String) { self.stringValue = stringValue }
    }

    private enum ThingKeys: String, CodingKey {
        case isActive, name, owner, cases
    }
    private enum UserKeys: String, CodingKey {
        case name
    }
    private enum CaseKeys: String, CodingKey {
        case id
        case caseNumber = "no"
    }

    init(from decoder: Decoder) throws {

        let outer = try decoder.container(keyedBy: CodingKeys.self)
        let thingcontainer = try outer.nestedContainer(keyedBy: PhantomKeys.self, forKey: .things)

        for key in thingcontainer.allKeys {
            let aux = try thingcontainer.nestedContainer(keyedBy: ThingKeys.self, forKey: key)

            let name = try aux.decode(String.self, forKey: .name)
            let owner = try aux.decode(String.self, forKey: .owner)
            let isActive = try aux.decode(Bool.self, forKey: .isActive)
//            let c = try aux.nestedContainer(keyedBy: CaseKeys.self, forKey: .cases)
//            var cases = [Case]()
//            for ckey in c.allKeys {
//                let caseNumber = try c.decode(Int.self, forKey: .caseNumber)
//                let thiscase = Case(id: ckey.stringValue, caseNumber: caseNumber)
//                cases.append(thiscase)
//            }

            let thing = Thing(id: key.stringValue, isActive: isActive, name: name, owner: owner)//, cases: cases)
            things.append(thing)
        }
        let usercontainer = try outer.nestedContainer(keyedBy: PhantomKeys.self, forKey: .users)

        for key in usercontainer.allKeys {
            let aux = try usercontainer.nestedContainer(keyedBy: UserKeys.self, forKey: key)
            let name = try aux.decode(String.self, forKey: .name)
            let user = User(id: key.stringValue,name: name)
            users.append(user)
        }
    }
}
</code>```

It works for the things and users, but I have to ignore the cases. See the output of print in comments//.

```<code>let data = json.data(using: .utf8)!
let things = try JSONDecoder().decode(ResponseData.self, from: data).things
print(things[0])
//Thing(id: "456", isActive: true, name: "Bus", owner: "Joe")

let users = try JSONDecoder().decode(ResponseData.self, from: data).users
print(users[0])
//User(id: "u1", name: "Summer")
</code>```

I have tried to use the guidance from this SO question on decoding that seems much cleaner to me, but I have not successfully implemented it.

This code is also a GIST

My question is twofold:

How can I get the Case data as a nested array in my Thing?

Can you
suggest a cleaner/shorter way to code this? It feels like I'm
repeating things, but I have seen this kind of wrapper structure in
several examples for JSON encoding/decoding.

答:
You can get keys from your current json as

```<code> jq -r 'keys[]'
</code>```

After that query in the loop by each key retrieved

Body:
I have a JSON data structure using unique keys that are created on upload. I can read all of it if I read each dictionary item line by line. However, I'm trying to modify my code to use the Swift 4 codable properties.

Doing the Ray Wenderlich tutorial and reading the Ultimate Guide to JSON Parsing with Swift unfortunately did not propel me to genius status.

The JSON looks like this simple example:
NOTE that keys, like "123", "456", "case1", "case2", "u1", "u2" are not known at run time.

   let json = """
    {
    "things" : {
        "123" : {
        "name" : "Party",
        "owner" : "Bob",
        "isActive" : true,
        "cases" : {
            "case1" : {
                "no" : 1
            },
            "case2" : {
                "no" : 2
            }
        }
        },
        "456" : {
        "name" : "Bus",
        "owner" : "Joe",
        "isActive" : true
        }
    },
    "users" : {
        "u1" : {
        "name" : "Summer"
        },
        "u2" : {
        "name" : "Daffy"
        }
    }
    }
    """

Following this SO question on flattening JSON, I was able to create a decoder for most of my data, but not for the nested dictionaries (in the example, cases is acting like a nested dictionary). I am sure that I am missing something simple.

If I attempt to include the commented out portion, the playground will not run, no error is given.

    struct Thing: Decodable {
    let id: String
    let isActive: Bool
    let name: String
    let owner: String
    //var cases = [Case]()

    init(id: String, isActive: Bool, name: String, owner: String){//}, cases: [Case]?) {
        self.id = id
        self.isActive = isActive
        self.name = name
        self.owner = owner
        //self.cases = cases ?? [Case(id: "none", caseNumber: 0)]
    }
}
struct User: Decodable {
    let id: String
    let name: String
}
struct Case: Decodable {
    let id: String
    let caseNumber: Int
}
struct ResponseData: Decodable {
    var things = [Thing]()
    var users = [User]()

    enum CodingKeys: String, CodingKey {
        case trips
        case users
    }

    private struct PhantomKeys: CodingKey {
        var intValue: Int?
        var stringValue: String
        init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
        init?(stringValue: String) { self.stringValue = stringValue }
    }

    private enum ThingKeys: String, CodingKey {
        case isActive, name, owner, cases
    }
    private enum UserKeys: String, CodingKey {
        case name
    }
    private enum CaseKeys: String, CodingKey {
        case id
        case caseNumber = "no"
    }

    init(from decoder: Decoder) throws {

        let outer = try decoder.container(keyedBy: CodingKeys.self)
        let thingcontainer = try outer.nestedContainer(keyedBy: PhantomKeys.self, forKey: .things)

        for key in thingcontainer.allKeys {
            let aux = try thingcontainer.nestedContainer(keyedBy: ThingKeys.self, forKey: key)

            let name = try aux.decode(String.self, forKey: .name)
            let owner = try aux.decode(String.self, forKey: .owner)
            let isActive = try aux.decode(Bool.self, forKey: .isActive)
//            let c = try aux.nestedContainer(keyedBy: CaseKeys.self, forKey: .cases)
//            var cases = [Case]()
//            for ckey in c.allKeys {
//                let caseNumber = try c.decode(Int.self, forKey: .caseNumber)
//                let thiscase = Case(id: ckey.stringValue, caseNumber: caseNumber)
//                cases.append(thiscase)
//            }

            let thing = Thing(id: key.stringValue, isActive: isActive, name: name, owner: owner)//, cases: cases)
            things.append(thing)
        }
        let usercontainer = try outer.nestedContainer(keyedBy: PhantomKeys.self, forKey: .users)

        for key in usercontainer.allKeys {
            let aux = try usercontainer.nestedContainer(keyedBy: UserKeys.self, forKey: key)
            let name = try aux.decode(String.self, forKey: .name)
            let user = User(id: key.stringValue,name: name)
            users.append(user)
        }
    }
}

It works for the things and users, but I have to ignore the cases. See the output of print in comments//.

let data = json.data(using: .utf8)!
let things = try JSONDecoder().decode(ResponseData.self, from: data).things
print(things[0])
//Thing(id: "456", isActive: true, name: "Bus", owner: "Joe")

let users = try JSONDecoder().decode(ResponseData.self, from: data).users
print(users[0])
//User(id: "u1", name: "Summer")

I have tried to use the guidance from this SO question on decoding that seems much cleaner to me, but I have not successfully implemented it.

This code is also a GIST

My question is twofold:

How can I get the Case data as a nested array in my Thing?

Can you
suggest a cleaner/shorter way to code this? It feels like I'm
repeating things, but I have seen this kind of wrapper structure in
several examples for JSON encoding/decoding.

Body:
You can get keys from your current json as

 jq -r 'keys[]'

After that query in the loop by each key retrieved


问:
How to replace one value calculated by COUNT with another value in SELECT result?
Suppose there are two tables

```<code>shop        seller
------      -------
id          id
seller_id   seller_name
goods       sallary
</code>```

seller_id may be repeated, parts from seller.id may not be there at all. So, I need to get the result of the request consisting of saller_name and counting the number of stores on each seller. I did it like this

```<code>SELECT seller_name, COUNT(seller_id) AS shops FROM seller
LEFT JOIN shop ON seller.id = shop.seller_id GROUP BY seller_name.
</code>```

And it works. But the problem is that I need to replace all 0 in shops with the text 'none'.
I tried to do it through

```<code>REPLACE(COUNT(seller_id),0,"none")
</code>```

and with

```<code>CASE
WHEN COUNT(seller_id)=0 THEN "none"
ELSE COUNT(seller_id)
END
</code>```

But instead of the expected numbers and none, I get a random set of numbers and letters. How to do it?

答:
You need to change yor query to something like this:</p>

```<code>SELECT seller_name,
CASE
WHEN COUNT(shop.Id)=0 THEN 'none'
ELSE CAST(COUNT(shop.Id) as NVARCHAR(10))
END AS shops FROM seller
LEFT JOIN shop ON seller.id = shop.seller_id GROUP BY seller_name
</code>```

Body:
Suppose there are two tables

shop        seller
------      -------
id          id
seller_id   seller_name
goods       sallary

seller_id may be repeated, parts from seller.id may not be there at all. So, I need to get the result of the request consisting of saller_name and counting the number of stores on each seller. I did it like this

SELECT seller_name, COUNT(seller_id) AS shops FROM seller
LEFT JOIN shop ON seller.id = shop.seller_id GROUP BY seller_name.

And it works. But the problem is that I need to replace all 0 in shops with the text 'none'.
I tried to do it through

REPLACE(COUNT(seller_id),0,"none")

and with

CASE
WHEN COUNT(seller_id)=0 THEN "none"
ELSE COUNT(seller_id)
END

But instead of the expected numbers and none, I get a random set of numbers and letters. How to do it?

Body:
You need to change yor query to something like this:

SELECT seller_name,
CASE
WHEN COUNT(shop.Id)=0 THEN 'none'
ELSE CAST(COUNT(shop.Id) as NVARCHAR(10))
END AS shops FROM seller
LEFT JOIN shop ON seller.id = shop.seller_id GROUP BY seller_name


问:
Can't take full page screenshot using applitools in selenium with java
I tried java with selenium to take full page screenshot in applitools and I used below code for full page screenshot but am not able to take full page screenshot , it takes only the current page and stitches.I have just initiated to learn automation testing,so please help me out in detail.</p>

```<code>public void checklogin()
{
    Eyes eyes=new Eyes();
    eyes.setApiKey("MY API KEY");
    eyes.setBatch(new BatchInfo("My Batch"));
    eyes.setMatchLevel(MatchLevel.LAYOUT);
    eyes.setForceFullPageScreenshot(true);
    eyes.setStitchMode(StitchMode.CSS);
    eyes.open(driver, "BasicInfo", "BasicInformation");
    eyes.checkWindow("BasicPage");
    eyes.check("basic",Target.window().fully());
    eyes.close();
}
</code>```

答:
Just replace

```<code>eyes.setStitchMode(StitchMode.CSS);
</code>```

to:

```<code> eyes.setStitchMode(StitchMode.SCROLL);
</code>```

For details, please visit:
StitchMode

Body:
I tried java with selenium to take full page screenshot in applitools and I used below code for full page screenshot but am not able to take full page screenshot , it takes only the current page and stitches.I have just initiated to learn automation testing,so please help me out in detail.

public void checklogin()
{
    Eyes eyes=new Eyes();
    eyes.setApiKey("MY API KEY");
    eyes.setBatch(new BatchInfo("My Batch"));
    eyes.setMatchLevel(MatchLevel.LAYOUT);
    eyes.setForceFullPageScreenshot(true);
    eyes.setStitchMode(StitchMode.CSS);
    eyes.open(driver, "BasicInfo", "BasicInformation");
    eyes.checkWindow("BasicPage");
    eyes.check("basic",Target.window().fully());
    eyes.close();
}

Body:
Just replace

eyes.setStitchMode(StitchMode.CSS);

to:

 eyes.setStitchMode(StitchMode.SCROLL);

For details, please visit:
StitchMode


问:
Android - Make an envelope shape background in xml/vector
I'm trying to do a shape as this one in xml:

It is a simple rectangle, with a solid color and a little transparent triangle in the top-center, from the inner side.

Can this be achieved using vectors?

答:
You can draw it with using shapeShifter even you can give some animations to your vector.

Try with this :

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
  <path
      android:pathData="M0.871,16L0.871,6L9.065,6L11.968,8.977L15.194,6L23.194,6L23.194,16Z"
      android:strokeWidth="1"
      android:fillColor="#6fb054"
      android:strokeColor="#6fb054"/>
</vector>
</code>```

Body:
You can draw it with using shapeShifter even you can give some animations to your vector.

Try with this :

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
  <path
      android:pathData="M0.871,16L0.871,6L9.065,6L11.968,8.977L15.194,6L23.194,6L23.194,16Z"
      android:strokeWidth="1"
      android:fillColor="#6fb054"
      android:strokeColor="#6fb054"/>
</vector>


问:
iphone multiple image url loading in tableview
I want to display or load multiple images from a server and load it in tableview or image view  ...if a single url with image is coming then imageview or tableview loads the image, but more that one image is coming then it did not load the multiple images,

my code is

```<code>NSString *urlVal = @"http://at.azinova.info/green4care/iphone/viewImage.php?id=";

NSString *urlVal1 = [urlVal stringByAppendingString:selectedCountryw];

NSURL *url1 = [NSURL URLWithString:urlVal1];

NSString *resultString = [NSString stringWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:nil];

resultString=[resultString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

NSArray *profileedit = [resultString componentsSeparatedByString:@"#***#"];
lbl.text = resultString;
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:lbl.text]]];
 timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:@selector(tick) userInfo:nil repeats:YES];
UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"ALERT" message:resultString delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];

[alert1 show];

[alert1 release];
</code>```

selectedCountryw is just an id

resultstring is the url from the server ,it may be one image or more than one image

答:
You need to create a function that takes a parameter for selectedCountryw

The function returns a UIImage

Call the function every time you need an image, the function makes the request and creates the image

Set the image in the UITableView

Once you've gotten this far, let us know where you are and we'll jump right in and help.

```<code>-(UIImage*)getImage:(NSString*)country
{

    NSString *urlString = [NSString stringWithFormat: @"http://at.azinova.info/green4care/iphone/viewImage.php?id=%@", country];
    NSURL *url = [NSURL URLWithString: urlString];
    NSString *strImage = [NSString stringWithContentsOfURL:url];
    UIImage *image = [[UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:strImage]]] retain];
    return image;
}
</code>```

Better yet..Do a search on SO or Google for Lazy TableView Loading. That'll get you started.

Edited to provide additional information:

I'll leave it up to you to optimize.

Body:
I want to display or load multiple images from a server and load it in tableview or image view  ...if a single url with image is coming then imageview or tableview loads the image, but more that one image is coming then it did not load the multiple images,

my code is

NSString *urlVal = @"http://at.azinova.info/green4care/iphone/viewImage.php?id=";

NSString *urlVal1 = [urlVal stringByAppendingString:selectedCountryw];

NSURL *url1 = [NSURL URLWithString:urlVal1];

NSString *resultString = [NSString stringWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:nil];

resultString=[resultString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

NSArray *profileedit = [resultString componentsSeparatedByString:@"#***#"];
lbl.text = resultString;
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:lbl.text]]];
 timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:@selector(tick) userInfo:nil repeats:YES];
UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"ALERT" message:resultString delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];

[alert1 show];

[alert1 release];

selectedCountryw is just an id

resultstring is the url from the server ,it may be one image or more than one image

Body:
You need to create a function that takes a parameter for selectedCountryw

The function returns a UIImage

Call the function every time you need an image, the function makes the request and creates the image

Set the image in the UITableView

Once you've gotten this far, let us know where you are and we'll jump right in and help.

-(UIImage*)getImage:(NSString*)country
{

    NSString *urlString = [NSString stringWithFormat: @"http://at.azinova.info/green4care/iphone/viewImage.php?id=%@", country];
    NSURL *url = [NSURL URLWithString: urlString];
    NSString *strImage = [NSString stringWithContentsOfURL:url];
    UIImage *image = [[UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:strImage]]] retain];
    return image;
}

Better yet..Do a search on SO or Google for Lazy TableView Loading. That'll get you started.

Edited to provide additional information:

I'll leave it up to you to optimize.


问:
JavaFx: How to properly fire updateItem in a TableCell
I have to implement a lot of custom TableCell which behavior relies on the model's change. I could manage to get somehow the expected result, but I think in many cases it was a workaround rather a really good solution.
I have used bindings/listeners to achieve the expected result, but the problem I face is that I may add the listeners/bind the properties multiple times and it can create memory leaks.

Here is an example what I mean.

Controller:

```<code>public class Controller implements Initializable {

    @FXML private TableView<Model> table;
    @FXML private TableColumn<Model, String> column;
    @FXML private Button change;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        column.setCellValueFactory(data -> data.getValue().text);
        column.setCellFactory(cell -> new ColoredTextCell());

        Model apple = new Model("Apple", "#8db600");

        table.getItems().add(apple);
        table.getItems().add(new Model("Banana", "#ffe135"));

        change.setOnAction(event -> apple.color.setValue("#ff0800"));

    }

    @Getter
    private class Model {
        StringProperty text;
        StringProperty color;

        private Model(String text, String color) {
            this.text = new SimpleStringProperty(text);
            this.color = new SimpleStringProperty(color);
        }
    }

    private class ColoredTextCell extends TableCell<Model, String> {

        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (empty || getTableRow() == null || getTableRow().getItem() == null) {
                setGraphic(null);
                return;
            }
            Model model = (Model) getTableRow().getItem();
            Text text = new Text(item);
            text.setFill(Color.web(model.getColor().getValue()));

            // This way I add the listener evey item updateItem is called.
            model.getColor().addListener((observable, oldValue, newValue) -> {
                if (newValue != null) {
                    text.setFill(Color.web(newValue));
                } else {
                    text.setFill(Color.BLACK);
                }
            });
            setGraphic(text);
        }
    }

}
</code>```

FXML:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Button?>
<AnchorPane xmlns="http://javafx.com/javafx"
            xmlns:fx="http://javafx.com/fxml"
            fx:controller="stackoverflow.tabpane.Controller">
    <VBox>
        <Button fx:id="change" text="Change color"/>
        <TableView fx:id="table">
            <columns>
                <TableColumn fx:id="column" prefWidth="200"/>
            </columns>
        </TableView>
    </VBox>
</AnchorPane>
</code>```

Since the color property isn't directly observed by the cell the updateItem is not called if it changes, so I have to listen to somehow.
I would need that the updateItem to be triggered after the color is changed. This would result a single call to the content of the listener.

Is there any way to listen to another change of the model in the same cell, or call the update item somehow, so the change gets rendered.

答:
I guess you could do it the other way around.

I would create a color property like this:

```<code>    ObjectBinding<Paint> colorProperty = Bindings.createObjectBinding(()->{
        String color = model.getColor().get();
        return Paint.valueOf(color==null?"BLACK":color);
    } , model.getColor());
</code>```

Then I would bind the property like that:

```<code>text.fillProperty().bind(model.colorProperty);
</code>```

It would be even simpler if you just had:

```<code>    SimpleObjectProperty<Paint> textColor = new SimpleObjectProperty<Paint>(Paint.valueOf("BLACK"));
</code>```

and then in getter and setter of your model update such property.

Body:
I have to implement a lot of custom TableCell which behavior relies on the model's change. I could manage to get somehow the expected result, but I think in many cases it was a workaround rather a really good solution.
I have used bindings/listeners to achieve the expected result, but the problem I face is that I may add the listeners/bind the properties multiple times and it can create memory leaks.

Here is an example what I mean.

Controller:

public class Controller implements Initializable {

    @FXML private TableView<Model> table;
    @FXML private TableColumn<Model, String> column;
    @FXML private Button change;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        column.setCellValueFactory(data -> data.getValue().text);
        column.setCellFactory(cell -> new ColoredTextCell());

        Model apple = new Model("Apple", "#8db600");

        table.getItems().add(apple);
        table.getItems().add(new Model("Banana", "#ffe135"));

        change.setOnAction(event -> apple.color.setValue("#ff0800"));

    }

    @Getter
    private class Model {
        StringProperty text;
        StringProperty color;

        private Model(String text, String color) {
            this.text = new SimpleStringProperty(text);
            this.color = new SimpleStringProperty(color);
        }
    }

    private class ColoredTextCell extends TableCell<Model, String> {

        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (empty || getTableRow() == null || getTableRow().getItem() == null) {
                setGraphic(null);
                return;
            }
            Model model = (Model) getTableRow().getItem();
            Text text = new Text(item);
            text.setFill(Color.web(model.getColor().getValue()));

            // This way I add the listener evey item updateItem is called.
            model.getColor().addListener((observable, oldValue, newValue) -> {
                if (newValue != null) {
                    text.setFill(Color.web(newValue));
                } else {
                    text.setFill(Color.BLACK);
                }
            });
            setGraphic(text);
        }
    }

}

FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Button?>
<AnchorPane xmlns="http://javafx.com/javafx"
            xmlns:fx="http://javafx.com/fxml"
            fx:controller="stackoverflow.tabpane.Controller">
    <VBox>
        <Button fx:id="change" text="Change color"/>
        <TableView fx:id="table">
            <columns>
                <TableColumn fx:id="column" prefWidth="200"/>
            </columns>
        </TableView>
    </VBox>
</AnchorPane>

Since the color property isn't directly observed by the cell the updateItem is not called if it changes, so I have to listen to somehow.
I would need that the updateItem to be triggered after the color is changed. This would result a single call to the content of the listener.

Is there any way to listen to another change of the model in the same cell, or call the update item somehow, so the change gets rendered.

Body:
I guess you could do it the other way around.

I would create a color property like this:

    ObjectBinding<Paint> colorProperty = Bindings.createObjectBinding(()->{
        String color = model.getColor().get();
        return Paint.valueOf(color==null?"BLACK":color);
    } , model.getColor());

Then I would bind the property like that:

text.fillProperty().bind(model.colorProperty);

It would be even simpler if you just had:

    SimpleObjectProperty<Paint> textColor = new SimpleObjectProperty<Paint>(Paint.valueOf("BLACK"));

and then in getter and setter of your model update such property.


问:
Repartition with a fixed minimum number of elements in each partition of the RDD using Spark
I have a RDD with the following number of elements in each partition (total number of partitions is val numPart = 32:

1351, 962, 537, 250, 80, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 88, 270, 635, 1028, 1388, 1509

To see the previous output I use this:

```<code>def countByPartition[A](anRdd: RDD[A]): RDD[Int] = anRdd.mapPartitions(iter => Iterator(iter.length))

println(countByPartition(anRdd).collect.mkString(", "))
</code>```

I would like to have on each partition at least a minimum number of elements given by val min = 5.

I've tried to perform anRdd.repartition(numPart) and I get the following:

257, 256, 256, 256, 255, 255, 254, 253, 252, 252, 252, 252, 252, 252,
  252, 252, 251, 250, 249, 248, 248, 248, 248, 248, 261, 261, 260, 260,
  259, 258, 258, 257

In this case, it was perfect because in each partition I have more than min elements. But it doesn't always gets the same and sometimes I get some partitions with values less than min value.

Is there a way to do what I want?

答: It is not possible and in general you need to choose partitioning so that the sizes are roughly even. Partitioners in Spark basically implement two methods numPartitions and getPartition. The latter is a function from a single key to a partition number so other elements and thus the potential size of partitions are not known at this point.

Body:
I have a RDD with the following number of elements in each partition (total number of partitions is val numPart = 32:

1351, 962, 537, 250, 80, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 88, 270, 635, 1028, 1388, 1509

To see the previous output I use this:

def countByPartition[A](anRdd: RDD[A]): RDD[Int] = anRdd.mapPartitions(iter => Iterator(iter.length))

println(countByPartition(anRdd).collect.mkString(", "))

I would like to have on each partition at least a minimum number of elements given by val min = 5.

I've tried to perform anRdd.repartition(numPart) and I get the following:

257, 256, 256, 256, 255, 255, 254, 253, 252, 252, 252, 252, 252, 252,
  252, 252, 251, 250, 249, 248, 248, 248, 248, 248, 261, 261, 260, 260,
  259, 258, 258, 257

In this case, it was perfect because in each partition I have more than min elements. But it doesn't always gets the same and sometimes I get some partitions with values less than min value.

Is there a way to do what I want?


问:
Id_token lifetime with respect to access_token lifetime (OpenID Connect)
Is id_token meant to have a longer lifetime than access token?

Here the idea that the id_token can have a short lifetime is suggested:
What is intent of ID Token expiry time in OpenID Connect?

However, here it is said that id_token lifetime is set to 10 hours by default to optimize performance.

https://auth0.com/docs/tokens/id-token

I have seen Openidc client libraries that do not allow access to resources when either the access or id token is invalid (e.g. it has expired).
https://github.com/damienbod/angular-auth-oidc-client

Is this correct?

What is the relationship between id token and access token regarding their lifetime?

答:
Is id_token meant to have a longer lifetime than access token?

No, usually not.

The common way of dealing with id_token is just to verify that user is authenticated, get info about user from that token, cache that info and never use id_token again (because you just don't need it afterwards). But your client app may have some logic related to id_token so you may want to have it live longer. For example, mentioned angular-auth-oidc-client lib uses id_token expiration date to perform silent renew when token become expired.

Here the idea that the id_token can have a short lifetime is suggested
  However, here it is said that id_token lifetime is set to 10 hours by default

Well, 10 hours still a short time, though IdentityServer4, for example, has 5 minutes by default.

What is the relationship between id token and access token regarding their lifetime?

To sum up: it depends on you client. Usually it's ok to have short-lived id_token, but for example if you using angular-auth-oidc-client library with Implicit low then it doesn't make much sense to have different expire time of access and id tokens and if you don't want to perform silent refresh too often, then lifetime should be sufficient, 1 hour or more I would say.


问:
where is the type in elasticsearch7.1 index
i was using elasticsearch-1.6 here we have an index and a type and inside that type we have the documents
https://www.elastic.co/guide/en/elasticsearch/reference/1.6/docs-index_.html
as we had twitter as an index and tweet as an type and 1 is the document id
now i need to upgrade to elasticsearch current version which is 7.1 but in the docs the type is missing
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html

so how can i define a type in index ?

答:
types are deprecated in ES 7.x version, According to official ES site.

Indices created in Elasticsearch 7.0.0 or later no longer accept a
  default mapping. Indices created in 6.x will continue to function as before in Elasticsearch 6.x. Types are deprecated in APIs in 7.0, with
  breaking changes to the index creation, put mapping, get mapping, put
  template, get template and get field mappings APIs.

read more about this breaking change here .

Why its removed is explained here.

But they provide some alternative to types which is explained here

Let me know if you need any clarification.