问:
Unable to Run any Gulp commands
I am relatively new to NodeJS and am learning to develop using Sharepoint Framework. It was working fine and all of a sudden started to throw errors.

My NodeJS version is:  V10.13.0.

My gulp version is:    CLI - 2.0.1 Local - 3.9.1

I get the following error when I try to use gulp serve or gulp bundle:

Error: Your dev environment is running NodeJS version v10.13.0 which
  does not meet the requirements for running this tool. This tool
  requires a version of NodeJS that matches >=8.9.4 <9.0.0.......

Could someone help me fix this issue please?

Many Thanks,

答: The current supported LTS version of NodeJS for the SharePoint Framework is Node.js v8.x and Node.js v10.x. Notice that 9.x, 11.x or 12.x versions are currently not supported with SharePoint Framework development.</p>

Title: Unable to Run any Gulp commands


来源: stackexchange

问:
Facebook error when pulling og:image
For whatever reason, the image that I'm trying to use when sharing a link on FB doesn't load. The exact error that's being given is this:

Provided og:image,  could not be downloaded. This can happen due to several different reasons such as your server using unsupported content-encoding. The crawler accepts deflate and gzip content encodings.

I'm using an s3 bucket to hold my images, and as far as I'm concerned the bucket is public and I can load these images on any browser. I'm also adding the og:image, og:image:url, og:image:secure_url, og:image:height, og:image:width, and og:image:type to the meta tags, so as far as meta tags are concerned I think I've covered all grounds. Is there a particular setting that I should be adding? Thanks of any help

答:
At first I convert HTML to canvas, then canvas to image and afterwards this image is drawn with canvas for cropping the initial image to get rid of extra space. After this is done, the image is sent to the server for storage and passed to FB in og:image meta tag.</p>

```<code>$scope.facebookShared = () ->

      $window.open "//www.facebook.com/sharer/sharer.php?u=" + encodeURI($location.absUrl()), "sharer", "toolbar=0,status=0,width=" + 500 + ",height=" + 500 /// this is window for share fb

      height=$('.sharing').height()
      html2canvas document.body,
        onrendered: (canvas) ->

          context = canvas.getContext('2d')
          image = new Image()
          image.src = canvas.toDataURL("image/png")
          image.onload = ->
            sharing=$('.sharing')
            canvas.height = Math.round(sharing.width()/1.91)
            canvas.width = sharing.width()

            context=canvas.getContext('2d')

            pos =  sharing.parent(0).parent(0).position()
            context.drawImage(this, pos.left, pos.top, sharing.width() + 20, sharing.height(),0,0,sharing.width()+20,sharing.height())

            $.ajax
              url: '../../save_img'
              type: 'post'
              beforeSend: (xhr) ->
                xhr.setRequestHeader "X-CSRF-Token", $("meta[name=\"csrf-token\"]").attr("content")
                return
              data:
                base64_image: canvas.toDataURL("image/png").replace(/^data:image\/(png|jpg);base64,/, "")
                claim_slug: $scope.claim.slug

            return false

        width: $('.claim-page ').width()
        height: height+115

      return
</code>```

ContentLicense: CC BY-SA 4.0

Title: Facebook error when pulling og:image

Body:
At first I convert HTML to canvas, then canvas to image and afterwards this image is drawn with canvas for cropping the initial image to get rid of extra space. After this is done, the image is sent to the server for storage and passed to FB in og:image meta tag.

$scope.facebookShared = () ->

      $window.open "//www.facebook.com/sharer/sharer.php?u=" + encodeURI($location.absUrl()), "sharer", "toolbar=0,status=0,width=" + 500 + ",height=" + 500 /// this is window for share fb

      height=$('.sharing').height()
      html2canvas document.body,
        onrendered: (canvas) ->

          context = canvas.getContext('2d')
          image = new Image()
          image.src = canvas.toDataURL("image/png")
          image.onload = ->
            sharing=$('.sharing')
            canvas.height = Math.round(sharing.width()/1.91)
            canvas.width = sharing.width()

            context=canvas.getContext('2d')

            pos =  sharing.parent(0).parent(0).position()
            context.drawImage(this, pos.left, pos.top, sharing.width() + 20, sharing.height(),0,0,sharing.width()+20,sharing.height())

            $.ajax
              url: '../../save_img'
              type: 'post'
              beforeSend: (xhr) ->
                xhr.setRequestHeader "X-CSRF-Token", $("meta[name=\"csrf-token\"]").attr("content")
                return
              data:
                base64_image: canvas.toDataURL("image/png").replace(/^data:image\/(png|jpg);base64,/, "")
                claim_slug: $scope.claim.slug

            return false

        width: $('.claim-page ').width()
        height: height+115

      return


问:
last insert data not showing in node js when i redirect from add to show listing
in my code when I redirect from add data, in this case, it will not fetch the latest data but when I refresh it will fetch  me that data </p>

```<code>var CountryResponseData = [];
router.get('/', ensureAuthenticated, (req, res) => {
    Country.find({}).then(countrylist =>{
        console.log(countrylist);
        if(countrylist){
            CountryResponseData = countrylist;
        }else{
            CountryResponseData = "empty";
        }
    });

    res.render('countrymgmt/list', { layout: "layoutinternal", title: "List Of Countries","countries":CountryResponseData });
});
</code>```

答:
it will problem because of it taking time to fetching data from database till it renders the view page do u need to do inside promise means do like as follow

```<code>var CountryResponseData = [];router.get('/', ensureAuthenticated, (req, res) => {
Country.find({}).then(countrylist =>{
    console.log(countrylist);
    if(countrylist){
        res.render('countrymgmt/list', { layout: "layoutinternal", title: "List Of Countries","countries":countrylist });

    }else{
        res.render('countrymgmt/list', { layout: "layoutinternal", title: "List Of Countries","countries":[] });
    }
});
</code>```

});

Body:
in my code when I redirect from add data, in this case, it will not fetch the latest data but when I refresh it will fetch  me that data

var CountryResponseData = [];
router.get('/', ensureAuthenticated, (req, res) => {
    Country.find({}).then(countrylist =>{
        console.log(countrylist);
        if(countrylist){
            CountryResponseData = countrylist;
        }else{
            CountryResponseData = "empty";
        }
    });

    res.render('countrymgmt/list', { layout: "layoutinternal", title: "List Of Countries","countries":CountryResponseData });
});

Body:
it will problem because of it taking time to fetching data from database till it renders the view page do u need to do inside promise means do like as follow

var CountryResponseData = [];router.get('/', ensureAuthenticated, (req, res) => {
Country.find({}).then(countrylist =>{
    console.log(countrylist);
    if(countrylist){
        res.render('countrymgmt/list', { layout: "layoutinternal", title: "List Of Countries","countries":countrylist });

    }else{
        res.render('countrymgmt/list', { layout: "layoutinternal", title: "List Of Countries","countries":[] });
    }
});

});


问:
Getting the Version of my C# app?
I am working on desktop application. I have create a setup.

Ex. My Application. Version is 1.0.0.

I want to get the current version of my desktop application which is 1.0.0. I have tried by using Application.ProductVersion but it provides the version of my controls. (I am using DevExpress Control15.2.7, so it provides the current version as 15.2.7).

How can I get the current version of the installed application? I want to compare it to the installed version to provide a "New Version Available" functionality for my product.

答:
Get the version of a specific assembly:</p>

```<code>private const string AssemblyName = "MyAssembly"; // Name of your assembly

public Version GetVersion()
{
    // Get all the assemblies currently loaded in the application domain.
    Assembly[] assemblies = Thread.GetDomain().GetAssemblies();

    for (int i = 0; i < assemblies.Length; i++)
    {
        if (string.Compare(assemblies[i].GetName().Name, AssemblyName) == 0)
        {
            return assemblies[i].GetName().Version;
        }
    }

    return Assembly.GetExecutingAssembly().GetName().Version; // return current version assembly or return null;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Getting the Version of my C# app?

Body:
Get the version of a specific assembly:

private const string AssemblyName = "MyAssembly"; // Name of your assembly

public Version GetVersion()
{
    // Get all the assemblies currently loaded in the application domain.
    Assembly[] assemblies = Thread.GetDomain().GetAssemblies();

    for (int i = 0; i < assemblies.Length; i++)
    {
        if (string.Compare(assemblies[i].GetName().Name, AssemblyName) == 0)
        {
            return assemblies[i].GetName().Version;
        }
    }

    return Assembly.GetExecutingAssembly().GetName().Version; // return current version assembly or return null;
}


问:
I can try create login page but getting error on state email
```<code>  import React, { Component } from 'react';
import {
    SafeAreaView,
    Text,
    View,
    Image,
    ScrollView,
    StyleSheet,
    StatusBar,
    TextInput,
    TouchableOpacity

} from 'react-native';

export default class LoginFrom extends React. Component {
    state = {
        isLoading: false,
        strEmail: "test@example.com", isEmailValid: true, errMsgEmail: "",
        strPassword: "test@123", isPasswordValid: true, errMsgPassword: "",
        strErrMsg: ""
    }

    login() {
        setTimeout(() => {

            fetch("url", {
                method: 'POST',
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify({
                    'email': this.state.strEmail,
                    'password': this.state.strPassword
                })
            }).then((response) => {
                if (response.status == 200) {
                    return response.json()
                } else {
                    return null
                }
            }).then((responseJson) => {
                console.log(responseJson);

                if (responseJson != null) {
                    this.setState({
                        strErrMsg: ""
                    })

                } else {
                    this.setState({
                        strErrMsg: "Email and password does not match."
                    })
                }
            })

        }, 100);

    }
    txtEmailChangeHangler = (val) => {
        this.setState({
            strEmail: val.trim()
        })
    }

    txtPasswordChangeHangler = (val) => {
        this.setState({
            strPassword: val.trim()
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <TextInput style={styles.inputbox}
                    onSubmitEditing={() => { this.secondTextInput.focus(); }}
                    underlineColorAndroid='rgba(0,0,0,0)'
                    placeholder='Email'
                    selectionColor='#fff'
                    value={this.state.strEmail}
                    onChangeText={this.txtEmailChangeHangler}
                    keyboardType='email-address' />
                <TextInput
                    secureTextEntry={true}
                    style={styles.inputbox}
                    underlineColorAndroid='rgba(0,0,0,0)'
                    placeholder='password'
                    onChangeText={this.txtPasswordChangeHangler}
                    value={this.state.strPassword}
                    ref={(input) => { this.secondTextInput = input; }} />

                <TouchableOpacity onPress={this.login} style={styles.button}>
                    <Text style={styles.buttontext}>{this.props.type}</Text>
                </TouchableOpacity>
            </View>
        );

    }

}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#D3EDFA',
        flexGrow: 1,
        alignItems: 'center',
        justifyContent: 'center'

    },
    inputbox: {
        width: 300,
        backgroundColor: 'rgba(255,255,255,1)',
        borderRadius: 25,
        paddingHorizontal: 16,
        marginVertical: 10

    },
    button: {
        width: 300,
        backgroundColor: '#ED6825',
        borderRadius: 25,
        paddingVertical: 16,
        marginVertical: 10

    },
    buttontext:
    {
        fontSize: 16,
        color: '#ffffff',
        fontWeight: '100',
        textAlign: 'center',
        paddingHorizontal: 16,

    }

})
</code>```

答:
Just try replacing login function with fat arrow function

```<code>login() {
       // your code here
    }
</code>```

to

```<code>login = () => {
    // your code here
    }
</code>```

hope it helps, this is done because fat arrow functions implicty binds this keyword

Body:
Just try replacing login function with fat arrow function

login() {
       // your code here
    }

to

login = () => {
    // your code here
    }

hope it helps, this is done because fat arrow functions implicty binds this keyword


问:
Can't do anything with helm
I have all sorts of problems with Kubernetes/helm, but I'm really new to it and so I'm not sure what I'm doing at all, despite spending a day trying to work it out.

I have a pod that's in a CrashLoopBackOff situation as I entered an incorrect port number in the Dockerfile. When I do a kubectl -n dev get pods, I can see it in the crash loop. I tried to kill it with helm delete --purge emails but I get the error Error: unknown flag: --purge. I tried to edit the chart with kubectl edit pod emails -n dev, but I get an error saying that the field cannot be changed.

But I can't delete the pod, so I'm not quite sure where to go from here. I've tried without the --purge flag and I get the error Error: uninstall: Release not loaded: emails: release: not found. I get the same if I try helm uninstall emails or pretty much anything.

To get to the crux of the matter, I believe it's because there's been an upgrade to the helm client to version v3.1.0 but the pods were created with v2.11.0. But I don't know how to roll back the client to this version. I've downloaded it via curl -L https://git.io/get_helm.sh | bash -s -- --version v2.11.0 but I can't run helm init and so I'm still on v3.1.0

If I run helm list, I get an empty list. I have 16 running pods I can see through kubectl -n dev get pods but I don't seem to be able to do anything to any of them.

Is this likely to be because my helm client is the wrong version and, if so, how do I roll it back?

Thanks for any suggestions.

答:
EricZ's answer hit the main points, but just to provide some context and recommend a couple of resources — first off, you can find the binaries for the current v2 release here. Just drop that in your path and everything should be as you left it with all your releases.

As mentioned, the problem is you're trying to query Helm v2 releases with a v3 client1. However, Helm v3 was designed to have a separate release "store", allowing a rolling migration of your workloads; this is why the v3 client doesn't "see" v2 releases, and vice versa (i.e. you could, for example, "convert" a v2 release to v3 in a test environment while the deployed one keeps running, verify that everything looks good, and then rollover traffic to the new release and remove the old one). While you're migrating, you'll probably want both versions in your PATH — I just aliased the v2 client to helm2, so e.g., helm2 list would show me all my v2 releases, and helm list the new migrated releases.

That being said — there's nothing preventing you from continuing to use Helm v2 as you have been. If you've already got a working cluster running with v2, it may be worth just sticking to that while you get more familiar with the Kubernetes fundamentals. I was at a meetup with one of the core maintainers of Helm last week, and it sounds like Helm v2 will still be supported for the next year or so; so you've got time. (In fact, they recommend taking the time to test your migrations on a development cluster for production-critical applications.)

When you're ready to migrate... I'd highly recommend checking out the Helm 2to3 plugin (an official plugin maintained by the core Helm team), which was designed to automate migrating v2 releases to v3 in an easy CLI interface. YMMV, but it's worked great for me. In short:

$ helm plugin install https://github.com/helm/helm-2to3
# Note: the following commands can be also be run with the `--dry-run`
# flag to preview their effects.
$ helm 2to3 move config
[...]
[Move Config/confirm] Are you sure you want to move the v2 configuration? [y/N]: y
2020/02/18 23:02:08
Helm v2 configuration will be moved to Helm v3 configuration.
[...]
$ helm 2to3 convert some-helm2-release
2020/02/19 00:30:35 Release "some-helm2-release" will be converted from Helm v2 to Helm v3.
2020/02/19 00:30:35 [Helm 3] Release "some-helm2-release" will be created.
[...]
```

Hope this helps!

1 Check out the documentation here on "changes since Helm 2" for the details. Worth noting in your case:

Releases are now scoped to the namespace they're deployed in; to see all releases, use helm list -A.

No need to helm init in Helm v3 — since the v3 client doesn't rely on tiller anymore.

As you noticed — helm delete --purge is now helm uninstall in v3; if you want the v2 functionality of persisting a "deleted" release, use the --keep-history flag.

Title: Can't do anything with helm

Body:
EricZ's answer hit the main points, but just to provide some context and recommend a couple of resources — first off, you can find the binaries for the current v2 release here. Just drop that in your path and everything should be as you left it with all your releases.

As mentioned, the problem is you're trying to query Helm v2 releases with a v3 client1. However, Helm v3 was designed to have a separate release "store", allowing a rolling migration of your workloads; this is why the v3 client doesn't "see" v2 releases, and vice versa (i.e. you could, for example, "convert" a v2 release to v3 in a test environment while the deployed one keeps running, verify that everything looks good, and then rollover traffic to the new release and remove the old one). While you're migrating, you'll probably want both versions in your PATH — I just aliased the v2 client to helm2, so e.g., helm2 list would show me all my v2 releases, and helm list the new migrated releases.

That being said — there's nothing preventing you from continuing to use Helm v2 as you have been. If you've already got a working cluster running with v2, it may be worth just sticking to that while you get more familiar with the Kubernetes fundamentals. I was at a meetup with one of the core maintainers of Helm last week, and it sounds like Helm v2 will still be supported for the next year or so; so you've got time. (In fact, they recommend taking the time to test your migrations on a development cluster for production-critical applications.)

When you're ready to migrate... I'd highly recommend checking out the Helm 2to3 plugin (an official plugin maintained by the core Helm team), which was designed to automate migrating v2 releases to v3 in an easy CLI interface. YMMV, but it's worked great for me. In short:

$ helm plugin install https://github.com/helm/helm-2to3
# Note: the following commands can be also be run with the `--dry-run`
# flag to preview their effects.
$ helm 2to3 move config
[...]
[Move Config/confirm] Are you sure you want to move the v2 configuration? [y/N]: y
2020/02/18 23:02:08
Helm v2 configuration will be moved to Helm v3 configuration.
[...]
$ helm 2to3 convert some-helm2-release
2020/02/19 00:30:35 Release "some-helm2-release" will be converted from Helm v2 to Helm v3.
2020/02/19 00:30:35 [Helm 3] Release "some-helm2-release" will be created.
[...]

Hope this helps!

1 Check out the documentation here on "changes since Helm 2" for the details. Worth noting in your case:

Releases are now scoped to the namespace they're deployed in; to see all releases, use helm list -A.

No need to helm init in Helm v3 — since the v3 client doesn't rely on tiller anymore.

As you noticed — helm delete --purge is now helm uninstall in v3; if you want the v2 functionality of persisting a "deleted" release, use the --keep-history flag.


问:
Checking if date is overdue from text file
I have a text file that has users and then due dates. I would like to be able to read the due date which was initially input by the user and see if the date is overdue compared with the current date. Any help would be appreciated.

Text file:

User: Tommy

Gender: Male

Date due: 2020-02-18

The code I have so far is:

```<code>import datetime
data = open("duedate.txt", "r")
    d = datetime.datetime.today()
    line = data.readlines(3)
    if line > d
        print("This date is overdue ")
</code>```

答:
Try this:</p>

```<code>import datetime
today = datetime.datetime.today()
with open("duedate.txt", "r") as f:
    for line in f:
        if not line.startswith('Date due'): continue
        field, value = line.split(':')
        if field == 'Date due':
            if datetime.datetime.strptime(value.strip(), '%Y-%m-%d') < today:
                print("Overdue")
</code>```

Body:
I have a text file that has users and then due dates. I would like to be able to read the due date which was initially input by the user and see if the date is overdue compared with the current date. Any help would be appreciated.

Text file:

User: Tommy

Gender: Male

Date due: 2020-02-18

The code I have so far is:

import datetime
data = open("duedate.txt", "r")
    d = datetime.datetime.today()
    line = data.readlines(3)
    if line > d
        print("This date is overdue ")

Body:
Try this:

import datetime
today = datetime.datetime.today()
with open("duedate.txt", "r") as f:
    for line in f:
        if not line.startswith('Date due'): continue
        field, value = line.split(':')
        if field == 'Date due':
            if datetime.datetime.strptime(value.strip(), '%Y-%m-%d') < today:
                print("Overdue")


问:
How to efficiently sum over levels defined in another variable?
I am new to R. Now I have a function as follow:

```<code>funItemAverRating = function()
{
    itemRatingNum = array(0, itemNum);
    print("begin");
    apply(input, 1, function(x)
        {
            itemId = x[2]+1;
            itemAverRating[itemId] <<- itemAverRating[itemId] + x[3];
            itemRatingNum[itemId] <<- itemRatingNum[itemId] + 1;
        }
    );
}
</code>```

In this function input is a n*3 data frame, n is ~6*(10e+7), itemRatingNum is a vector of size ~3*(10e+5).

My question is why the apply function is so slow (it would take nearly an hour to finish)? Also, as the function runs, it uses more and more memory. But as you can see, the variables are all defined outside the apply function. Can anybody help me?

cheng

答:
It's slow because you call high-level R functions many times.

You have to vectorize your function, meaning that most operations (like <- or +1) should be computed over all data vectors.

For example it looks to me that itemRatingNum holds frequencies of input[[2]] (second column of input data.frame) which could be replaced by:

```<code>tb <- table(input[[2]]+1)
itemRatingNum[as.integer(names(tb))] <- tb
</code>```

Body:
I am new to R. Now I have a function as follow:

funItemAverRating = function()
{
    itemRatingNum = array(0, itemNum);
    print("begin");
    apply(input, 1, function(x)
        {
            itemId = x[2]+1;
            itemAverRating[itemId] <<- itemAverRating[itemId] + x[3];
            itemRatingNum[itemId] <<- itemRatingNum[itemId] + 1;
        }
    );
}

In this function input is a n*3 data frame, n is ~6*(10e+7), itemRatingNum is a vector of size ~3*(10e+5).

My question is why the apply function is so slow (it would take nearly an hour to finish)? Also, as the function runs, it uses more and more memory. But as you can see, the variables are all defined outside the apply function. Can anybody help me?

cheng

Body:
It's slow because you call high-level R functions many times.

You have to vectorize your function, meaning that most operations (like <- or +1) should be computed over all data vectors.

For example it looks to me that itemRatingNum holds frequencies of input[[2]] (second column of input data.frame) which could be replaced by:

tb <- table(input[[2]]+1)
itemRatingNum[as.integer(names(tb))] <- tb


问:
Snowflake & SQLAlchemy "unexpected 'UNIQUE'
I'm running a python db migration script (Flask-Migrate) and have added the alembic.ddl.imp import DefaultImpl to get around the first set of errors but now I'm getting the following. I'm trying to use this script to set up my tables and database in snowflake. What am I missing? Everything seems to be working and I can't seem to find any help on this particular error in the snowflake documentation. I would assume that the snowflake sqlalchemy connector would address the creation of a unique index.

The script so far does create several of the tables, but when it gets to this part it throws the error.

```<code>> sqlalchemy.exc.ProgrammingError:
> (snowflake.connector.errors.ProgrammingError) 001003 (42000): SQL
> compilation error: syntax error line 1 at position 7 unexpected
> 'UNIQUE'. [SQL: CREATE UNIQUE INDEX ix_flicket_users_token ON
> flicket_users (token)] (Background on this error at:
> http://sqlalche.me/e/f405)
</code>```

答:
Snowflake does not have INDEX objects, so any CREATE ... INDEX statement will fail.

With Snowflake, you have to trust the database to organize your data with micro partitions and build a good access plan for your queries.

You will feel uneasy at first, but eventually stop worrying.

Bleeding edge solutions will require monitoring/tuning performance using the query log, however.

Nothing new here.

Body:
I'm running a python db migration script (Flask-Migrate) and have added the alembic.ddl.imp import DefaultImpl to get around the first set of errors but now I'm getting the following. I'm trying to use this script to set up my tables and database in snowflake. What am I missing? Everything seems to be working and I can't seem to find any help on this particular error in the snowflake documentation. I would assume that the snowflake sqlalchemy connector would address the creation of a unique index.

The script so far does create several of the tables, but when it gets to this part it throws the error.

> sqlalchemy.exc.ProgrammingError:
> (snowflake.connector.errors.ProgrammingError) 001003 (42000): SQL
> compilation error: syntax error line 1 at position 7 unexpected
> 'UNIQUE'. [SQL: CREATE UNIQUE INDEX ix_flicket_users_token ON
> flicket_users (token)] (Background on this error at:
> http://sqlalche.me/e/f405)


问:
How to select all checkboxes, while clicking the main checkbox in android?
I need selecting the main checkbox, the all other partial checkboxes also selected

My Requirement is ,I have a checkbox selectAll and some other checkboxes,by clicking this selectAll checkbox ,all other checkboxes must selected.And while clicking the partial checkbox the selectAll checkbox selection must gone.

```<code> selectAllCheckbox.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                CheckBox cb = (CheckBox) view;
                isPartial = true;
                splitItemAdapter.selectAllItem(cb.isChecked());
                if (isFromCashPayment) {
                    if (cb.isChecked()) {
                      selectAllCheckbox.setChecked(true);
                      isitemChecked = true;

                    } else {

                        selectAllCheckbox.setChecked(false);

                        isitemChecked = false;

                    }
                }
            }
        });
</code>```

答:
You can use this way. Firstly, all checkbox to be in one layout. And then you use this code block.

layout.xml

```<code>...
 <CheckBox android:id="@+id/allCheckbox" />
 <LinearLayout android:id="@+id/checkboxLayouts"...>

               <CheckBox  android:layout_width="wrap_content"
                         android:layout_height="wrap_content"/>

               <CheckBox  android:layout_width="wrap_content"
                         android:layout_height="wrap_content"/>

               <CheckBox android:layout_width="wrap_content"
                         android:layout_height="wrap_content"/>

               <CheckBox  android:layout_width="wrap_content"
                         android:layout_height="wrap_content"/>
</LinearLayout>
...
</code>```

Code

```<code>LinearLayout checkboxLayout = findViewById(R.id.checkboxLayouts);

checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
   @Override
   public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
       for(int i=0 ; i < checkboxLayout.getChildCount(); i++) {
          if(checkboxLayout.getChildAt(i) instanceof CheckBox) {
             ((CheckBox) checkboxLayout.getChildAt(i)).setChecked(isChecked);
          }
       }
 }
});
</code>```

Note: I can't check code. Sorry for syntax error.

Body:
I need selecting the main checkbox, the all other partial checkboxes also selected

My Requirement is ,I have a checkbox selectAll and some other checkboxes,by clicking this selectAll checkbox ,all other checkboxes must selected.And while clicking the partial checkbox the selectAll checkbox selection must gone.

 selectAllCheckbox.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                CheckBox cb = (CheckBox) view;
                isPartial = true;
                splitItemAdapter.selectAllItem(cb.isChecked());
                if (isFromCashPayment) {
                    if (cb.isChecked()) {
                      selectAllCheckbox.setChecked(true);
                      isitemChecked = true;

                    } else {

                        selectAllCheckbox.setChecked(false);

                        isitemChecked = false;

                    }
                }
            }
        });

Body:
You can use this way. Firstly, all checkbox to be in one layout. And then you use this code block.

layout.xml

...
 <CheckBox android:id="@+id/allCheckbox" />
 <LinearLayout android:id="@+id/checkboxLayouts"...>

               <CheckBox  android:layout_width="wrap_content"
                         android:layout_height="wrap_content"/>

               <CheckBox  android:layout_width="wrap_content"
                         android:layout_height="wrap_content"/>

               <CheckBox android:layout_width="wrap_content"
                         android:layout_height="wrap_content"/>

               <CheckBox  android:layout_width="wrap_content"
                         android:layout_height="wrap_content"/>
</LinearLayout>
...

Code

LinearLayout checkboxLayout = findViewById(R.id.checkboxLayouts);

checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
   @Override
   public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
       for(int i=0 ; i < checkboxLayout.getChildCount(); i++) {
          if(checkboxLayout.getChildAt(i) instanceof CheckBox) {
             ((CheckBox) checkboxLayout.getChildAt(i)).setChecked(isChecked);
          }
       }
 }
});

Note: I can't check code. Sorry for syntax error.


问:
Get value from JSON in Python
I want to assign get the value of "feels_like" and assign it to a new variable. How can I do it?</p>

```<code>test({"coord":{"lon":-71.06,"lat":42.36},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"stations","main":{"temp":1.69,"feels_like":-1.22,"temp_min":0,"temp_max":3.33,"pressure":1013,"humidity":94},"visibility":16093,"wind":{"speed":1.5,"deg":230},"rain":{"1h":0.25},"clouds":{"all":90},"dt":1582094044,"sys":{"type":1,"id":3413,"country":"US","sunrise":1582112159,"sunset":1582150834},"timezone":-18000,"id":4930956,"name":"Boston","cod":200})
</code>```

答:
If you are loading this from a file, you can use the json package to load the file into a python dictionary. You can then manipulate the dictionary the way you normally do.

See https://docs.python.org/3/library/json.html

Title: Get value from JSON in Python

Body:
I want to assign get the value of "feels_like" and assign it to a new variable. How can I do it?

test({"coord":{"lon":-71.06,"lat":42.36},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"stations","main":{"temp":1.69,"feels_like":-1.22,"temp_min":0,"temp_max":3.33,"pressure":1013,"humidity":94},"visibility":16093,"wind":{"speed":1.5,"deg":230},"rain":{"1h":0.25},"clouds":{"all":90},"dt":1582094044,"sys":{"type":1,"id":3413,"country":"US","sunrise":1582112159,"sunset":1582150834},"timezone":-18000,"id":4930956,"name":"Boston","cod":200})


问:
How to format numbers floats with comma and dot
I have the following data that I need to format:

```<code>  Ativo        high       close
 HTMX11       169.8       169.8
 KNHY11       116.0       116.0
 FAED11       272.3       272.3
 FLRP11     1579.92     1579.92
 FVPQ11       215.5       215.5
</code>```

Need to convert 1579.92 to 1.579,92

not a problem, since I can do with:

```<code>import pandas as pd
import locale
locale.setlocale (locale.LC_ALL, 'pt_br.utf-8')
pd.set_option ('display.float_format', lambda x: locale.format ('%. 2f', x, grouping = True))
</code>```

but when I need to convert the column to a string and add some letters, numbers are kept only with commas:

I need complete formatting.

```<code>df['close'] = '$' + df['close'].astype()
df['close']
</code>```

Results in:

```<code>Fechamento
  R$ 169,8
  R$ 116,0
  R$ 272,3
R$ 1579,92
  R$ 215,5
</code>```

desired output:

```<code>R$ 1.579,92
</code>```

答:
```<code>import pandas as pd
from babel.numbers import format_currency
df = pd.DataFrame({"close":[169.8,116.0,272.3,1579.92,215.5]})
df['close'].apply(lambda x :format_currency(x,'BRL', locale='pt_BR'))
</code>```

output:

```<code>0      R$ 169,80
1      R$ 116,00
2      R$ 272,30
3    R$ 1.579,92
4      R$ 215,50
</code>```

Body:
I have the following data that I need to format:

  Ativo        high       close
 HTMX11       169.8       169.8
 KNHY11       116.0       116.0
 FAED11       272.3       272.3
 FLRP11     1579.92     1579.92
 FVPQ11       215.5       215.5

Need to convert 1579.92 to 1.579,92

not a problem, since I can do with:

import pandas as pd
import locale
locale.setlocale (locale.LC_ALL, 'pt_br.utf-8')
pd.set_option ('display.float_format', lambda x: locale.format ('%. 2f', x, grouping = True))

but when I need to convert the column to a string and add some letters, numbers are kept only with commas:

I need complete formatting.

df['close'] = '$' + df['close'].astype()
df['close']

Results in:

Fechamento
  R$ 169,8
  R$ 116,0
  R$ 272,3
R$ 1579,92
  R$ 215,5

desired output:

R$ 1.579,92

Body:
import pandas as pd
from babel.numbers import format_currency
df = pd.DataFrame({"close":[169.8,116.0,272.3,1579.92,215.5]})
df['close'].apply(lambda x :format_currency(x,'BRL', locale='pt_BR'))

output:

0      R$ 169,80
1      R$ 116,00
2      R$ 272,30
3    R$ 1.579,92
4      R$ 215,50


问:
Range function is not working properly in jupyter notebook

for i in range():
    for j in range(i):
        print("*",end = " ")
    print()
```
<p>Error:</p>
<pre class="lang-none prettyprint-override"><code>TypeError
Traceback (most recent call last) <ipython-input-81-6bc40b03c32e> in <module>
----> 1 for i in range():
      2     for j in range(i):
      3         print("*",end = " ")
      4     print()
      5

TypeError: 'int' object is not callable
</code>```

答:
In Python, range() is not valid, you need to provide an argument to allow it to create a range.

For example:

range(3) will give you a generator for the integers { 0, 1, 2 };

range(3, 20, 7) will generate { 3, 10, 17 };

range() will just generate an error :-)

Body:
for i in range():
    for j in range(i):
        print("*",end = " ")
    print()

Error:

TypeError
Traceback (most recent call last) <ipython-input-81-6bc40b03c32e> in <module>
----> 1 for i in range():
      2     for j in range(i):
      3         print("*",end = " ")
      4     print()
      5

TypeError: 'int' object is not callable


Title: Get value from JSON in Python

Body:
you can do that as follows:

d = {"coord": {"lon": -71.06, "lat": 42.36}, "weather": [{"id": 500, "main": "Rain", "description": "light rain", "icon": "10n"}], "base": "stations", "main": {"temp": 1.69, "feels_like": -1.22, "temp_min": 0, "temp_max": 3.33, "pressure": 1013, "humidity": 94}, "visibility": 16093, "wind": {
    "speed": 1.5, "deg": 230}, "rain": {"1h": 0.25}, "clouds": {"all": 90}, "dt": 1582094044, "sys": {"type": 1, "id": 3413, "country": "US", "sunrise": 1582112159, "sunset": 1582150834}, "timezone": -18000, "id": 4930956, "name": "Boston", "cod": 200}
feels = d["main"]["feels_like"]

Hope it helps you!


问:
Trying to hide elements and call them back when a button is clicked
I'm still new to coding so maybe I'm making some rookie mistakes but here I go. In my HTML page, I have a container that is caring the only two elements I need for my javascript,  I have also added a class called "hide" in that div. I used the class "hide" to hide the contents in my CSS using display: none, so when you first open my HTML page all you see is a start button and a timer. In my javascript, I have written my code so that when they start button is clicked, the timer will go start counting down and my quiz will appear on the page. However at the moment, only my timer is working, my quiz won't appear regardless of everything I have tried. Any help will be much appreciated. Not sure if I provided everything needed but I can provide more of my code if need.

const startButton = document.getElementById('Start-btn')
var funcEl = document.getElementById("func container")
startButton.addEventListener('click', function(){
    clock();
    renderQuestion()
});
// pos is position of where the user in the test or which question they're up to
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
  ["Which language is used for styling web pages?", "HTML", "JQuery", "CSS", "C"],
  ["Which is not a JavaScript Framework?", "Python Script", "JQuery","Django",  "C"],
  ["Hyper Text Markup Language Stand For?", "XHTML","CSS", "HTML", "C"],
  ["Which languages hasn't been covered in class yet?", "JavaScript", "HTML", "React", "C"]
  ];

//   We use this functions in order to use get instead of getElement
function get(x){
  return document.getElementById(x);
}
function renderQuestion(){
    startButton.classList.add('hide')
    funcEl.classList.remove('hide')
  test = get("test");
  if(pos >= questions.length){
    test.innerHTML = "
You got "+correct+" of "+questions.length+" questions correct
";
    get("test_status").innerHTML = "Test completed";
    // resets the variable to allow users to restart the test
    pos = 0;
    correct = 0;
    // stops rest of renderQuestion function running when test is completed
    return false;

//Stopwatch
var c = 60;
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
function myClock() {
document.getElementById("timer").innerHTML = c--;
if (c == 0) {
clearInterval(myTimer);
}
}
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
  <div class="container">
      <div id="func container" class='hide'>
          <h1 id="test_status"></h1>
          <div id="test"></div>
      </div>
      <div class="controls">
          <button id="Start-btn" class="start-btn btn" onclick="() => clock()">Start</button>
      </div>
  </div>
</body>
</html></code>```

答:
It seem you define duplicate onclick event.

```<code><button id="Start-btn" class="start-btn btn" onclick="() => clock()">Start</button>

startButton.addEventListener('click', function(){
    clock();
    renderQuestion()
});
</code>```

Please try remove onclick="() => clock()".Futhermore can you share clock() fuction code ?

Body:
I'm still new to coding so maybe I'm making some rookie mistakes but here I go. In my HTML page, I have a container that is caring the only two elements I need for my javascript,  I have also added a class called "hide" in that div. I used the class "hide" to hide the contents in my CSS using display: none, so when you first open my HTML page all you see is a start button and a timer. In my javascript, I have written my code so that when they start button is clicked, the timer will go start counting down and my quiz will appear on the page. However at the moment, only my timer is working, my quiz won't appear regardless of everything I have tried. Any help will be much appreciated. Not sure if I provided everything needed but I can provide more of my code if need.

const startButton = document.getElementById('Start-btn')
var funcEl = document.getElementById("func container")
startButton.addEventListener('click', function(){
    clock();
    renderQuestion()
});
// pos is position of where the user in the test or which question they're up to
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
  ["Which language is used for styling web pages?", "HTML", "JQuery", "CSS", "C"],
  ["Which is not a JavaScript Framework?", "Python Script", "JQuery","Django",  "C"],
  ["Hyper Text Markup Language Stand For?", "XHTML","CSS", "HTML", "C"],
  ["Which languages hasn't been covered in class yet?", "JavaScript", "HTML", "React", "C"]
  ];

//   We use this functions in order to use get instead of getElement
function get(x){
  return document.getElementById(x);
}
function renderQuestion(){
    startButton.classList.add('hide')
    funcEl.classList.remove('hide')
  test = get("test");
  if(pos >= questions.length){
    test.innerHTML = "
You got "+correct+" of "+questions.length+" questions correct
";
    get("test_status").innerHTML = "Test completed";
    // resets the variable to allow users to restart the test
    pos = 0;
    correct = 0;
    // stops rest of renderQuestion function running when test is completed
    return false;

//Stopwatch
var c = 60;
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
function myClock() {
document.getElementById("timer").innerHTML = c--;
if (c == 0) {
clearInterval(myTimer);
}
}
}
}

          <button id="Start-btn" class="start-btn btn" onclick="() => clock()">Start</button>

Body:
It seem you define duplicate onclick event.

<button id="Start-btn" class="start-btn btn" onclick="() => clock()">Start</button>

startButton.addEventListener('click', function(){
    clock();
    renderQuestion()
});

Please try remove onclick="() => clock()".Futhermore can you share clock() fuction code ?


问:
Update Question: How to Mock MapToJson Class
this is an update to my previous question.  I have a Utility class which I already manage to cover with my unit test except when the condition returns false.

Here is my class:

@Component
public class Utils {

    @Autowired
    private ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private LoggingService loggingService;

    public <E> String mapToJsonString(E object) {
        try {
            if (object == null) {
                throw new IOException(ErrorMessage.ERROR_PROCESSING_JSON_NULL);
            }else {
                return mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object); //NullPointer Here
            }

        } catch (IOException e) {
            loggingService.logError(this.getClass().getName(), "1", ErrorMessage.ERROR_MAPPING_TO_JSONSTRING, e);
            return "";
        }
    }
}
```

<p>and here is my unit test</p>

<pre class="lang-java prettyprint-override"><code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ATMMonitoringApplication.class, initializers = ConfigFileApplicationContextInitializer.class)
public class ObjectToJsonStringTest {

    @SpyBean
    private ATM atm;

    @Autowired
    private Utils utils;

    @MockBean
    private ObjectMapper mapper;

    @MockBean
    private LoggingService loggingService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        myModelClass = new MyModelclass();
            myModelClass.setStatus("U");
            myModelClass.setTermCode("001");
            myModelClass.setLocation("BGC");
    }

    @Test
    public void testObjectToJson() throws JsonProcessingException {
        String output = utils.mapToJsonStringmyModelClass
        assertNotNull(output);
    }

    @Test
    public void testObjectToJsonNull() throws JsonProcessingException {
        String output = utils.mapToJsonString(null);
        assertNull(output);
    }

    @Test
    public void testJsonParsingException() {
        myModelClass = new MyModelclass();
            myModelClass = null;
        String output = utils.mapToJsonString(myModelClass);
        Mockito.when(loggingService.logError(this.getClass().getName(), "1", ErrorMessage.ERROR_MAPPING_TO_JSONSTRING, new Exception()))
        .thenReturn("");
        assertThat(output).isEmpty();
    }

}
</code>```

Stack trace says that i have a null pointer on this line of code:

```<code>return mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object);
</code>```

Please help me on this.  Thanks

答:
Solved it.  I just change this

```<code>@Mock
private ObjectMapper mapper;
</code>```

From @MockBean and it covered the whole class.

Body:
this is an update to my previous question.  I have a Utility class which I already manage to cover with my unit test except when the condition returns false.

Here is my class:

@Component
public class Utils {

    @Autowired
    private ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private LoggingService loggingService;

    public <E> String mapToJsonString(E object) {
        try {
            if (object == null) {
                throw new IOException(ErrorMessage.ERROR_PROCESSING_JSON_NULL);
            }else {
                return mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object); //NullPointer Here
            }

        } catch (IOException e) {
            loggingService.logError(this.getClass().getName(), "1", ErrorMessage.ERROR_MAPPING_TO_JSONSTRING, e);
            return "";
        }
    }
}

and here is my unit test

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ATMMonitoringApplication.class, initializers = ConfigFileApplicationContextInitializer.class)
public class ObjectToJsonStringTest {

    @SpyBean
    private ATM atm;

    @Autowired
    private Utils utils;

    @MockBean
    private ObjectMapper mapper;

    @MockBean
    private LoggingService loggingService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        myModelClass = new MyModelclass();
            myModelClass.setStatus("U");
            myModelClass.setTermCode("001");
            myModelClass.setLocation("BGC");
    }

    @Test
    public void testObjectToJson() throws JsonProcessingException {
        String output = utils.mapToJsonStringmyModelClass
        assertNotNull(output);
    }

    @Test
    public void testObjectToJsonNull() throws JsonProcessingException {
        String output = utils.mapToJsonString(null);
        assertNull(output);
    }

    @Test
    public void testJsonParsingException() {
        myModelClass = new MyModelclass();
            myModelClass = null;
        String output = utils.mapToJsonString(myModelClass);
        Mockito.when(loggingService.logError(this.getClass().getName(), "1", ErrorMessage.ERROR_MAPPING_TO_JSONSTRING, new Exception()))
        .thenReturn("");
        assertThat(output).isEmpty();
    }

}

Stack trace says that i have a null pointer on this line of code:

return mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object);

Please help me on this.  Thanks

Body:
Solved it.  I just change this

@Mock
private ObjectMapper mapper;

From @MockBean and it covered the whole class.


问:
What package contains the CAA_File library?
And where do I obtain the package from? I would imagine it comes from some package on the CoDeSys store but I can't seem to find which one.

Thanks,

答:
Check this out:

Open library manager

Click add library,

Click advanced

Browse to Intern -> CAA -> System -> CAA File

Select the CAA file and hit OK

Then you can find the library under FILE namespace.


问:
tunnel-ssh throws an error after getting connected
I'm trying to connect to mongodb(mongodb package) using the tunnel-ssh package. It gets connected and I can log the db but it immediately throws an error and disconnects.

```<code>buffer.js:705
    throw new ERR_INVALID_ARG_TYPE(
    ^

    TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type undefined
        at Function.byteLength (buffer.js:705:11)
        at SSH2Stream.directTcpip (D:\WORK\node_modules\ssh2-streams\lib\ssh.js:1128:23)
        at openChannel (D:\WORK\node_modules\ssh2\lib\client.js:1142:21)
        at Client.forwardOut (D:\WORK\node_modules\ssh2\lib\client.js:994:10)
        at Client.<anonymous> (D:\WORK\node_modules\tunnel-ssh\index.js:16:23)
        at Client.emit (events.js:223:5)
        at SSH2Stream.<anonymous> (D:\WORK\node_modules\ssh2\lib\client.js:601:10)
        at Object.onceWrapper (events.js:312:28)
        at SSH2Stream.emit (events.js:223:5)
        at parsePacket (D:\WORK\node_modules\ssh2-streams\lib\ssh.js:3911:10) {
      code: 'ERR_INVALID_ARG_TYPE'
    }
</code>```

This is my code.

```<code>const tunnel = require("tunnel-ssh");
const config = require("config");
const MongoClient = require("mongodb").MongoClient;

const connection = new Promise((resolve, _) => {
    // eslint-disable-next-line
    tunnel(config.get("server"), async (err, server) => {
        server.on("connection", console.log.bind(console, "server error"));
        const client = await MongoClient.connect(config.get("mongodb").url, {
            useUnifiedTopology: true,
            useNewUrlParser: true
        });
        client.on("error", console.error.bind(console, "mongodb error"));
        resolve({ client });
    });
});

async function runQuery() {
    const { client} = await connection;
    console.log(client);
}

runQuery();
</code>```

There is no problem with config. In fact, the logging in runQuery function works but throws that error immediately.

答:
I have not used the tunnel-ssh package you have mentioned, but I went through the docs and I see that you are using it wrong. I simply copied the configuration given in the docs of tunnel-ssh and it started working for me. pasting the entire code below

const tunnel = require("tunnel-ssh");
const MongoClient = require("mongodb").MongoClient;

const connection = new Promise((resolve, _) => {
    // eslint-disable-next-line
    tunnel(
        {
            username: "root",
            Password: "secret",
            host: "127.0.0.1",
            port: 22,
            dstHost: "127.0.0.1",
            dstPort: 27017,
            localHost: "127.0.0.1",
            localPort: 27000
        },
        async (err, server) => {
            server.on("connection", console.log.bind(console, "server error"));
            const client = await MongoClient.connect(
                "mongodb://localhost:27017/user",
                {
                    useUnifiedTopology: true,
                    useNewUrlParser: true
                }
            );
            client.on("error", console.error.bind(console, "mongodb error"));
            resolve({ client });
            server.close();
        }
    );
});

async function runQuery() {
    const { client } = await connection;
    console.log("Connection Successful");
}

runQuery();
```

The part where you went wrong is passing string to tunnel package. it expects configuration object not string.

Body:
I'm trying to connect to mongodb(mongodb package) using the tunnel-ssh package. It gets connected and I can log the db but it immediately throws an error and disconnects.

buffer.js:705
    throw new ERR_INVALID_ARG_TYPE(
    ^

    TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type undefined
        at Function.byteLength (buffer.js:705:11)
        at SSH2Stream.directTcpip (D:\WORK\node_modules\ssh2-streams\lib\ssh.js:1128:23)
        at openChannel (D:\WORK\node_modules\ssh2\lib\client.js:1142:21)
        at Client.forwardOut (D:\WORK\node_modules\ssh2\lib\client.js:994:10)
        at Client.<anonymous> (D:\WORK\node_modules\tunnel-ssh\index.js:16:23)
        at Client.emit (events.js:223:5)
        at SSH2Stream.<anonymous> (D:\WORK\node_modules\ssh2\lib\client.js:601:10)
        at Object.onceWrapper (events.js:312:28)
        at SSH2Stream.emit (events.js:223:5)
        at parsePacket (D:\WORK\node_modules\ssh2-streams\lib\ssh.js:3911:10) {
      code: 'ERR_INVALID_ARG_TYPE'
    }

This is my code.

const tunnel = require("tunnel-ssh");
const config = require("config");
const MongoClient = require("mongodb").MongoClient;

const connection = new Promise((resolve, _) => {
    // eslint-disable-next-line
    tunnel(config.get("server"), async (err, server) => {
        server.on("connection", console.log.bind(console, "server error"));
        const client = await MongoClient.connect(config.get("mongodb").url, {
            useUnifiedTopology: true,
            useNewUrlParser: true
        });
        client.on("error", console.error.bind(console, "mongodb error"));
        resolve({ client });
    });
});

async function runQuery() {
    const { client} = await connection;
    console.log(client);
}

runQuery();

There is no problem with config. In fact, the logging in runQuery function works but throws that error immediately.

Body:
I have not used the tunnel-ssh package you have mentioned, but I went through the docs and I see that you are using it wrong. I simply copied the configuration given in the docs of tunnel-ssh and it started working for me. pasting the entire code below

const tunnel = require("tunnel-ssh");
const MongoClient = require("mongodb").MongoClient;

const connection = new Promise((resolve, _) => {
    // eslint-disable-next-line
    tunnel(
        {
            username: "root",
            Password: "secret",
            host: "127.0.0.1",
            port: 22,
            dstHost: "127.0.0.1",
            dstPort: 27017,
            localHost: "127.0.0.1",
            localPort: 27000
        },
        async (err, server) => {
            server.on("connection", console.log.bind(console, "server error"));
            const client = await MongoClient.connect(
                "mongodb://localhost:27017/user",
                {
                    useUnifiedTopology: true,
                    useNewUrlParser: true
                }
            );
            client.on("error", console.error.bind(console, "mongodb error"));
            resolve({ client });
            server.close();
        }
    );
});

async function runQuery() {
    const { client } = await connection;
    console.log("Connection Successful");
}

runQuery();

The part where you went wrong is passing string to tunnel package. it expects configuration object not string.


问:
How to extract all string that match a certain pattern and explode as rows in SQL
I have a table like

```<code>memberid  content
1         hello @abc
2         I'm happy @sunny @rainy
</code>```

My expected output

```<code>memberid  text_after_@
1         abc
2         sunny
2         rainy
</code>```

SQLFidle

答:
```<code>        SELECT memberid,
          Min(Substr(content,
         INSTR(CONTENT,
          '@')
        , Length(content))) over
         (Partition by Substr(content,
         INSTR(CONTENT,
          '@'), Length(content)) order by
           memberid)

        from
        table
</code>```

Body:
I have a table like

memberid  content
1         hello @abc
2         I'm happy @sunny @rainy

My expected output

memberid  text_after_@
1         abc
2         sunny
2         rainy

SQLFidle


问:
Elasticsearch Updating field value issue
I am trying to work with update_by_query but cannot make it work.

Following is a simple query,

```<code>curl -X GET "172.17.0.3:9200/useripvsuserid/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "_source":"userid","query": {
    "term": {
      "userip": "10.0.30.181"
    }
  }
}
'
{
  "took" : 3,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 10.803431,
    "hits" : [
      {
        "_index" : "useripvsuserid",
        "_type" : "_doc",
        "_id" : "PhfBW3AB8mhGfmGvIs-j",
        "_score" : 10.803431,
        "_source" : {
          "userid" : "hasan1855"
        }
      }
    ]
  }
}
</code>```

Following is the update_by_query that is not working. I am trying to replace userid value hasan1855 to arif. Where is the problem?

```<code>curl -X POST "172.17.0.3:9200/useripvsuserid/_update_by_query?pretty" -H 'Content-Type: application/json' -d'
{
  "script": {
    "source": "ctx._source.userid='arif';",
    "lang": "painless"
  },
  "query": {
    "term": {
      "userip": "10.0.30.181"
    }
  }
}
'
{
  "error" : {
    "root_cause" : [
      {
        "type" : "script_exception",
        "reason" : "compile error",
        "script_stack" : [
          "ctx._source.userid=arif;",
          "                   ^---- HERE"
        ],
        "script" : "ctx._source.userid=arif;",
        "lang" : "painless"
      }
    ],
    "type" : "script_exception",
    "reason" : "compile error",
    "script_stack" : [
      "ctx._source.userid=arif;",
      "                   ^---- HERE"
    ],
    "script" : "ctx._source.userid=arif;",
    "lang" : "painless",
    "caused_by" : {
      "type" : "illegal_argument_exception",
      "reason" : "Variable [arif] is not defined."
    }
  },
  "status" : 400
}
</code>```

答:
It's the same issue as described here, i.e. the single quotes around arif conflict with the single quotes around the JSON query.

So you can either send your query in binary mode as explained in the link above, or escape the quotes, like this:

```<code>curl -X POST "172.17.0.3:9200/useripvsuserid/_update_by_query?pretty" -H 'Content-Type: application/json' -d'
{
  "script": {
    "source": "ctx._source.userid = \"arif\";",         <---- escape quotes
    "lang": "painless"
  },
  "query": {
    "term": {
      "userip": "10.0.30.181"
    }
  }
}
'
</code>```

Body:
I am trying to work with update_by_query but cannot make it work.

Following is a simple query,

curl -X GET "172.17.0.3:9200/useripvsuserid/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "_source":"userid","query": {
    "term": {
      "userip": "10.0.30.181"
    }
  }
}
'
{
  "took" : 3,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 10.803431,
    "hits" : [
      {
        "_index" : "useripvsuserid",
        "_type" : "_doc",
        "_id" : "PhfBW3AB8mhGfmGvIs-j",
        "_score" : 10.803431,
        "_source" : {
          "userid" : "hasan1855"
        }
      }
    ]
  }
}

Following is the update_by_query that is not working. I am trying to replace userid value hasan1855 to arif. Where is the problem?

curl -X POST "172.17.0.3:9200/useripvsuserid/_update_by_query?pretty" -H 'Content-Type: application/json' -d'
{
  "script": {
    "source": "ctx._source.userid='arif';",
    "lang": "painless"
  },
  "query": {
    "term": {
      "userip": "10.0.30.181"
    }
  }
}
'
{
  "error" : {
    "root_cause" : [
      {
        "type" : "script_exception",
        "reason" : "compile error",
        "script_stack" : [
          "ctx._source.userid=arif;",
          "                   ^---- HERE"
        ],
        "script" : "ctx._source.userid=arif;",
        "lang" : "painless"
      }
    ],
    "type" : "script_exception",
    "reason" : "compile error",
    "script_stack" : [
      "ctx._source.userid=arif;",
      "                   ^---- HERE"
    ],
    "script" : "ctx._source.userid=arif;",
    "lang" : "painless",
    "caused_by" : {
      "type" : "illegal_argument_exception",
      "reason" : "Variable [arif] is not defined."
    }
  },
  "status" : 400
}

Body:
It's the same issue as described here, i.e. the single quotes around arif conflict with the single quotes around the JSON query.

So you can either send your query in binary mode as explained in the link above, or escape the quotes, like this:

curl -X POST "172.17.0.3:9200/useripvsuserid/_update_by_query?pretty" -H 'Content-Type: application/json' -d'
{
  "script": {
    "source": "ctx._source.userid = \"arif\";",         <---- escape quotes
    "lang": "painless"
  },
  "query": {
    "term": {
      "userip": "10.0.30.181"
    }
  }
}
'


问:
Python: How to find max value in list of preceding 10 values?
I have a csv file containing wave data (time, tidal elevation, wave period, wave height and wave direction)
I want to know, at a given time, when the previous high tide was and the corresponding wave period, height and direction.

I have this code now which selects the line of the time that I'm looking for:

```<code>import csv

with open ('Waves_2019.csv') as f:
    reader = csv.reader (f)
    for line_num, content in enumerate(reader):
        if content [0] == '01/03/2019T08:00':
            a = line_num
            print (a)
</code>```

The next step would then take the previous 12 hours of data to select the highest tidal elevation (0.77 at 01/03/2019T01:00 in example) and then return the other data (period, height, direction).

How could I amend the code that it looks for the max tidal elevation in column 2 based on the previous 12 data points of the selected time? And then return the other data during that high tide?

答:
First we select the index of the date we require to examine

```<code>selected_index = df.loc[df["time"].eq("01/03/2019T08:00")].index[0]
</code>```

Then obtain the id value having the maximum tidal_elevation from the previous 12 hours (since there are no missing rows in the dataset, we can safely assume that the previous 12 indices would indicate the 12 hours)

```<code>filt = df.loc[selected_index-12: selected_index, "tidal_elevation"].idxmax()
</code>```

Now, we select other parameters for the index having maximum tidal_elevation

```<code>res = df.loc[filt, ["time", "tidal_elevation", "wave_period", "wave_height", "wave_direction"]]
print(res)
</code>```

P.S. res = df.loc[filt, "time":"wave_direction"]
 would also work if the chronology of the columns is the same i.e. it is in the same order ["time", "tidal_elevation", "wave_period", "wave_height", "wave_direction"]

Edit:
Taking average of values one hour before and after the maximum tidal_elevation

```<code>res_avg = df.loc[filt-1:filt+1, "time":"wave_direction"].mean()
print(res_avg)
</code>```

Body:
I have a csv file containing wave data (time, tidal elevation, wave period, wave height and wave direction)
I want to know, at a given time, when the previous high tide was and the corresponding wave period, height and direction.

I have this code now which selects the line of the time that I'm looking for:

import csv

with open ('Waves_2019.csv') as f:
    reader = csv.reader (f)
    for line_num, content in enumerate(reader):
        if content [0] == '01/03/2019T08:00':
            a = line_num
            print (a)

The next step would then take the previous 12 hours of data to select the highest tidal elevation (0.77 at 01/03/2019T01:00 in example) and then return the other data (period, height, direction).

How could I amend the code that it looks for the max tidal elevation in column 2 based on the previous 12 data points of the selected time? And then return the other data during that high tide?

Body:
First we select the index of the date we require to examine

selected_index = df.loc[df["time"].eq("01/03/2019T08:00")].index[0]

Then obtain the id value having the maximum tidal_elevation from the previous 12 hours (since there are no missing rows in the dataset, we can safely assume that the previous 12 indices would indicate the 12 hours)

filt = df.loc[selected_index-12: selected_index, "tidal_elevation"].idxmax()

Now, we select other parameters for the index having maximum tidal_elevation

res = df.loc[filt, ["time", "tidal_elevation", "wave_period", "wave_height", "wave_direction"]]
print(res)

P.S. res = df.loc[filt, "time":"wave_direction"]
 would also work if the chronology of the columns is the same i.e. it is in the same order ["time", "tidal_elevation", "wave_period", "wave_height", "wave_direction"]

Edit:
Taking average of values one hour before and after the maximum tidal_elevation

res_avg = df.loc[filt-1:filt+1, "time":"wave_direction"].mean()
print(res_avg)


问:
Can't find latitude longitude in LG Optimus S
Hey guys i am building a geolocation application.
The following is the code which i use to get latitude and longitude :-

```<code>LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
android.location.Location loc = lm.getLastKnownLocation(lm.NETWORK_PROVIDER);
dataManager.setLatitude(Double.toString(loc.getLatitude()));
Log.d("LATITUDE", dataManager.getLatitude());
</code>```

Well the above code seems to be working on HTC devices and Samsung devices.
But for some strange reason i can not get the latitude and longitude in LG Optimus S.

I am thrown NullPointerException

Any help would be appreciated

Thanks in advance

答: Most probably, this is not related to the device type. If you don't have a cell network (e.g. pull out the SIM card), then loc will be null in your code.</p>

Body:
Hey guys i am building a geolocation application.
The following is the code which i use to get latitude and longitude :-

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
android.location.Location loc = lm.getLastKnownLocation(lm.NETWORK_PROVIDER);
dataManager.setLatitude(Double.toString(loc.getLatitude()));
Log.d("LATITUDE", dataManager.getLatitude());

Well the above code seems to be working on HTC devices and Samsung devices.
But for some strange reason i can not get the latitude and longitude in LG Optimus S.

I am thrown NullPointerException

Any help would be appreciated

Thanks in advance


问:
How do I use adapter position to retrieve data from firebase to a new activity
SearchPage where I search the books from firebase

```<code>public class SearchPage extends AppCompatActivity {
EditText searchbar;

RecyclerView recyclerView;
DatabaseReference reference;

ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
ArrayList<String> Desc;
SearchAdapter searchAdapter;

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

    searchbar = (EditText) findViewById(R.id.searchbar);
    reference = FirebaseDatabase.getInstance().getReference();
    reference.keepSynced(true);
    recyclerView = (RecyclerView) findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    BookNameList = new ArrayList<>();
    PublisherList = new ArrayList<>();
    AuthorNameList = new ArrayList<>();
    Shelfnols = new ArrayList<>();
    PicList = new ArrayList<>();
    Desc=new ArrayList<>();

    searchbar.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().isEmpty()) {
                setAdapter(s.toString());

            }
            else{
                BookNameList.clear();
                AuthorNameList.clear();
                PicList.clear();
                PublisherList.clear();
                Shelfnols.clear();
                Desc.clear();

            }
        }

        private void setAdapter(final String searchedString) {
            reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    BookNameList.clear();
                    AuthorNameList.clear();
                    PicList.clear();
                    PublisherList.clear();
                    Shelfnols.clear();
                    Desc.clear();

                    int counter=0;
                    for(DataSnapshot snapshot:dataSnapshot.getChildren()){
                        String uid = snapshot.getKey();

                       Log.i(uid,"ids");
                        String desc = snapshot.child("Desc").getValue(String.class);
                        String bookname = snapshot.child("bookname").getValue(String.class);
                        String author = snapshot.child("author").getValue(String.class);
                        String image = snapshot.child("image").getValue(String.class);
                        String publisher = snapshot.child("Publisher").getValue(String.class);
                        String shelfno = snapshot.child("Shelf_no").getValue(String.class);
                        try {

                            if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);

                                counter++;
                            } else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);
                                counter++;
                            }
                        }
                        catch (Exception e){
                            Toast.makeText(getApplicationContext(),"not found",Toast.LENGTH_LONG).show();
                        }

                        if(counter==15){
                            break;
                        }
                        SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
                        recyclerView.setAdapter(searchAdapter);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }

            });
        }
    });

}
</code>```

this the adapter class SearchAdapter where I am getting the adapter position on click

```<code>public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
final public String id="bookname";

    Context context;
    ArrayList<String> BookNameList;
    ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;
DatabaseReference reference;

class SearchViewHolder extends RecyclerView.ViewHolder{
    ImageView bookimage;
    TextView bookname, authorname,publisher,shelfno;

    public SearchViewHolder(@NonNull View itemView) {
        super(itemView);
        bookimage =  itemView.findViewById(R.id.Bookimg);
        bookname =  itemView.findViewById(R.id.BookName);
        authorname =  itemView.findViewById(R.id.AuthorName);
        publisher =  itemView.findViewById(R.id.Publications);
        shelfno =  itemView.findViewById(R.id.Shelfno);
        booklayout=itemView.findViewById(R.id.LinLayout);
        reference = FirebaseDatabase.getInstance().getReference();
        reference.keepSynced(true);

    }
}

public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
    this.context = context;
    BookNameList = bookNameList;
    AuthorNameList = authorNameList;
    PicList = picList;
    PublisherList=publisherList;
    Shelfnols=shelfnols;
}

@NonNull
@Override
public SearchAdapter.SearchViewHolder  onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
     return new SearchAdapter.SearchViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull SearchViewHolder holder, final int position) {
    holder.bookname.setText(BookNameList.get(position));
    holder.authorname.setText(AuthorNameList.get(position));
    holder.publisher.setText(PublisherList.get(position));
    holder.shelfno.setText(Shelfnols.get(position));

           holder.itemView.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {

                 Toast.makeText(context,"clicked "+position,Toast.LENGTH_LONG).show();
                   Intent i = new Intent(context,Bookdetailslayout.class);

                 context.startActivity(i);
               }
           });

    Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);

}

@Override
public int getItemCount() {
    return BookNameList.size();
}
</code>```

this is my new activity where i want the book details to be shown

```<code>public class Bookdetailslayout extends SearchPage {

DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bookdetailslayout);
    image=(ImageView)findViewById(R.id.img) ;

    bookname = (TextView)findViewById(R.id.bkname);
    author = (TextView) findViewById(R.id.aname);
    publisher = (TextView) findViewById(R.id.pname);
    desc = (TextView) findViewById(R.id.bkdescription);
    location = (TextView) findViewById(R.id.bklocation);
    String Bname=getIntent().getStringExtra("bookname");
    Log.i(Bname, "onCreate: ");

    DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");

}
</code>```

till now I was able to set onclick to new activity and get the position of the click as item 1,2,etc...how do I use this position to get data from firebase to the new activity

答:
create interface

```<code>public interface SetclickListener {

    public void  getposition(int position);
}
</code>```

inside adapter  create constructor

```<code> SetclickListener setclicklistener;
public SetclickListener getSetclick(Context context) {
        this.context=context;
        return setclicklistener;
    }

public void setclicklistener(SetclickListener setclickListener){
        setclicklistener=setclickListener;
    }
</code>```

get selected position

```<code> setclicklistener.getposition(getAdapterPosition());
</code>```

then you can implement inside SearchPage  activity then you can pass selected position data using Bundle you can send data to other activity

```<code>@Override
    public void getposition(int position) {
                        Intent intent = new Intent(context,DetailsActivity.class);
                        intent.putExtra("name", bookNameList.get(position));
                        startActivity(intent);

                }

        }

}
</code>```

Body:
SearchPage where I search the books from firebase

public class SearchPage extends AppCompatActivity {
EditText searchbar;

RecyclerView recyclerView;
DatabaseReference reference;

ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
ArrayList<String> Desc;
SearchAdapter searchAdapter;

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

    searchbar = (EditText) findViewById(R.id.searchbar);
    reference = FirebaseDatabase.getInstance().getReference();
    reference.keepSynced(true);
    recyclerView = (RecyclerView) findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    BookNameList = new ArrayList<>();
    PublisherList = new ArrayList<>();
    AuthorNameList = new ArrayList<>();
    Shelfnols = new ArrayList<>();
    PicList = new ArrayList<>();
    Desc=new ArrayList<>();

    searchbar.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().isEmpty()) {
                setAdapter(s.toString());

            }
            else{
                BookNameList.clear();
                AuthorNameList.clear();
                PicList.clear();
                PublisherList.clear();
                Shelfnols.clear();
                Desc.clear();

            }
        }

        private void setAdapter(final String searchedString) {
            reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    BookNameList.clear();
                    AuthorNameList.clear();
                    PicList.clear();
                    PublisherList.clear();
                    Shelfnols.clear();
                    Desc.clear();

                    int counter=0;
                    for(DataSnapshot snapshot:dataSnapshot.getChildren()){
                        String uid = snapshot.getKey();

                       Log.i(uid,"ids");
                        String desc = snapshot.child("Desc").getValue(String.class);
                        String bookname = snapshot.child("bookname").getValue(String.class);
                        String author = snapshot.child("author").getValue(String.class);
                        String image = snapshot.child("image").getValue(String.class);
                        String publisher = snapshot.child("Publisher").getValue(String.class);
                        String shelfno = snapshot.child("Shelf_no").getValue(String.class);
                        try {

                            if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);

                                counter++;
                            } else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);
                                counter++;
                            }
                        }
                        catch (Exception e){
                            Toast.makeText(getApplicationContext(),"not found",Toast.LENGTH_LONG).show();
                        }

                        if(counter==15){
                            break;
                        }
                        SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
                        recyclerView.setAdapter(searchAdapter);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }

            });
        }
    });

}

this the adapter class SearchAdapter where I am getting the adapter position on click

public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
final public String id="bookname";

    Context context;
    ArrayList<String> BookNameList;
    ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;
DatabaseReference reference;

class SearchViewHolder extends RecyclerView.ViewHolder{
    ImageView bookimage;
    TextView bookname, authorname,publisher,shelfno;

    public SearchViewHolder(@NonNull View itemView) {
        super(itemView);
        bookimage =  itemView.findViewById(R.id.Bookimg);
        bookname =  itemView.findViewById(R.id.BookName);
        authorname =  itemView.findViewById(R.id.AuthorName);
        publisher =  itemView.findViewById(R.id.Publications);
        shelfno =  itemView.findViewById(R.id.Shelfno);
        booklayout=itemView.findViewById(R.id.LinLayout);
        reference = FirebaseDatabase.getInstance().getReference();
        reference.keepSynced(true);

    }
}

public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
    this.context = context;
    BookNameList = bookNameList;
    AuthorNameList = authorNameList;
    PicList = picList;
    PublisherList=publisherList;
    Shelfnols=shelfnols;
}

@NonNull
@Override
public SearchAdapter.SearchViewHolder  onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
     return new SearchAdapter.SearchViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull SearchViewHolder holder, final int position) {
    holder.bookname.setText(BookNameList.get(position));
    holder.authorname.setText(AuthorNameList.get(position));
    holder.publisher.setText(PublisherList.get(position));
    holder.shelfno.setText(Shelfnols.get(position));

           holder.itemView.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {

                 Toast.makeText(context,"clicked "+position,Toast.LENGTH_LONG).show();
                   Intent i = new Intent(context,Bookdetailslayout.class);

                 context.startActivity(i);
               }
           });

    Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);

}

@Override
public int getItemCount() {
    return BookNameList.size();
}

this is my new activity where i want the book details to be shown

public class Bookdetailslayout extends SearchPage {

DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bookdetailslayout);
    image=(ImageView)findViewById(R.id.img) ;

    bookname = (TextView)findViewById(R.id.bkname);
    author = (TextView) findViewById(R.id.aname);
    publisher = (TextView) findViewById(R.id.pname);
    desc = (TextView) findViewById(R.id.bkdescription);
    location = (TextView) findViewById(R.id.bklocation);
    String Bname=getIntent().getStringExtra("bookname");
    Log.i(Bname, "onCreate: ");

    DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");

}

till now I was able to set onclick to new activity and get the position of the click as item 1,2,etc...how do I use this position to get data from firebase to the new activity

Body:
create interface

public interface SetclickListener {

    public void  getposition(int position);
}

inside adapter  create constructor

 SetclickListener setclicklistener;
public SetclickListener getSetclick(Context context) {
        this.context=context;
        return setclicklistener;
    }

public void setclicklistener(SetclickListener setclickListener){
        setclicklistener=setclickListener;
    }

get selected position

 setclicklistener.getposition(getAdapterPosition());

then you can implement inside SearchPage  activity then you can pass selected position data using Bundle you can send data to other activity

@Override
    public void getposition(int position) {
                        Intent intent = new Intent(context,DetailsActivity.class);
                        intent.putExtra("name", bookNameList.get(position));
                        startActivity(intent);

                }

        }

}


问:
Python for loop for list
I have a list containing some integer values.

My list is l = [5,10,15,25,30,45].

I want to write a program that the values in list is between 5 to 35

```<code>list1 = [15,35]
list2 = ['Height','Weight','5','10','25','30','40']
res = [int(ele) if ele.isdigit() else ele for ele in list2]
print([ x for x in res if type(x)==int ])
</code>```

this is the code that I written,now I want to compare list 1 and list 2 , then print values in list 2 of range in the first list

答:
```<code>for i in l:
    if(i>35):
      break
    print(i)
</code>```

Please try this for the list.

Use break whenever you want to out form the loop.

Title: Python for loop for list

Body:
I have a list containing some integer values.

My list is l = [5,10,15,25,30,45].

I want to write a program that the values in list is between 5 to 35

list1 = [15,35]
list2 = ['Height','Weight','5','10','25','30','40']
res = [int(ele) if ele.isdigit() else ele for ele in list2]
print([ x for x in res if type(x)==int ])

this is the code that I written,now I want to compare list 1 and list 2 , then print values in list 2 of range in the first list

Body:
for i in l:
    if(i>35):
      break
    print(i)

Please try this for the list.

Use break whenever you want to out form the loop.


问:
Enter triggers button click
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

```<code>$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})
</code>```

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.

答:
You can do something like this.

bind your event into a common function and call the event either with keypress or button click.

for example.

```<code>function callME(event){
    alert('Hi');
}

$('button').on("click",callME);
$('input ').keypress(function(event){
  if (event.which == 13) {
    callME(event);
  }
});
</code>```

Title: Enter triggers button click

Body:
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.

Body:
You can do something like this.

bind your event into a common function and call the event either with keypress or button click.

for example.

function callME(event){
    alert('Hi');
}

$('button').on("click",callME);
$('input ').keypress(function(event){
  if (event.which == 13) {
    callME(event);
  }
});


问:
How can I implement a boolean tag search in SQL?
Given a table of items, a table of tags and a join table between them, what is a good and efficient way to implement queries of the form:

p1 AND p2 AND ... AND pn AND NOT n1 AND NOT n2 ... AND NOT nk

I am using SQL. So to find all items that match all tags p1...pn and none of n1...nk?

Is there a good "standard" solution for this?

答:
```<code>SELECT i.title
  FROM items i
 WHERE EXISTS(SELECT * FROM join_table j JOIN tags t ON t.id = j.tag_id WHERE j.item_id = i.id AND t.name = 'tag1')
   AND NOT EXISTS(SELECT * FROM join_table j JOIN tags t ON t.id = j.tag_id WHERE j.item_id = i.id AND t.name = 'tag2')
</code>```

SQL server does a good job about this construct, but Oracle might need some hinting to get it right (at least it did 5 years ago).

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
SELECT i.title
  FROM items i
 WHERE EXISTS(SELECT * FROM join_table j JOIN tags t ON t.id = j.tag_id WHERE j.item_id = i.id AND t.name = 'tag1')
   AND NOT EXISTS(SELECT * FROM join_table j JOIN tags t ON t.id = j.tag_id WHERE j.item_id = i.id AND t.name = 'tag2')

SQL server does a good job about this construct, but Oracle might need some hinting to get it right (at least it did 5 years ago).


问:
Fetch value from Azure Key Vault reference (Managed identity)
I am trying to fetch secret values from azure key vault in Azure App Service.
My App Service has a managed identity
In the Azure Key vault, this managed identity is added under 'Role assignments' as 'Key vault contributor'
Also access policies has been added in azure key vault to give 'Get' permission to the AppServices's managed identity
Now in my c# code, I am trying to get the value of the AppSetting element using the code
ConfigurationManager.AppSettings['something'];

In my azure app service, under app settings, I have added the a key with name 'something' and it has the value pointing to the reference of the Key Vault as below:

```<code>@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)
</code>```

Now I am able to retrieve the value from the appsettings, but instead of the actual value, it is pulling the output as @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/c96f02080254f109c51a1f1cdb1931)

I am expecting the output to be value that I have set, not the keyvault reference string itself.

I am using .Net MVC 4.7 web app

答: Actually i figured out that even using ConfiguraionManager.AppSettings["keyname"] also works fine. In my case, i had done everything as listed above , but had enabled "Slot Deployment" option in Connection string configuration in App Service. Once i enabled, now i am able to access my key vault secrets.</p>

Body:
I am trying to fetch secret values from azure key vault in Azure App Service.
My App Service has a managed identity
In the Azure Key vault, this managed identity is added under 'Role assignments' as 'Key vault contributor'
Also access policies has been added in azure key vault to give 'Get' permission to the AppServices's managed identity
Now in my c# code, I am trying to get the value of the AppSetting element using the code
ConfigurationManager.AppSettings['something'];

In my azure app service, under app settings, I have added the a key with name 'something' and it has the value pointing to the reference of the Key Vault as below:

@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)

Now I am able to retrieve the value from the appsettings, but instead of the actual value, it is pulling the output as @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/c96f02080254f109c51a1f1cdb1931)

I am expecting the output to be value that I have set, not the keyvault reference string itself.

I am using .Net MVC 4.7 web app


问:
Connect Python with SQL Server Database
When I am trying to connect python with SQL Server, following error occurred.

"pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server
  Driver][DBNETLIB]SQL Server does not exist or access denied. (17)
  (SQLDriverConnect)')"

Following is the my code.

```<code>import pyodbc
connection = pyodbc.connect("Driver={SQL Server}; Server=localhost;
Database=emotionDetection; uid=uname ;pwd=pw;Trusted_Connection=yes")
cursor = connection.cursor()
SQLCommand = ("INSERT INTO emotion"  "(happy, sad, angry) "
          "VALUES (?,?,?)")
Values = ['smile','cry','blame']
cursor.execute(SQLCommand,Values)
connection.commit()
connection.close()
</code>```

This is my first attempt to connect Python with sql server. I don't have an idea what would be the driver name, server name, username and password.Do you have any idea of what should be my configuration. Please help me.

答:
```<code>import pyodbc
conn = pyodbc.connect('Driver={SQL Server};' 'Server=**SERVER NAME**;' 'Database=**DATABASE NAME**;' 'Trusted_Connection=yes;')
cursor = conn.cursor()

cursor.execute('SELECT * FROM Output3')
</code>```

This works just check you specify the Respective Driver, Server and the Database names correctively!

Title: Connect Python with SQL Server Database

Body:
When I am trying to connect python with SQL Server, following error occurred.

"pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server
  Driver][DBNETLIB]SQL Server does not exist or access denied. (17)
  (SQLDriverConnect)')"

Following is the my code.

import pyodbc
connection = pyodbc.connect("Driver={SQL Server}; Server=localhost;
Database=emotionDetection; uid=uname ;pwd=pw;Trusted_Connection=yes")
cursor = connection.cursor()
SQLCommand = ("INSERT INTO emotion"  "(happy, sad, angry) "
          "VALUES (?,?,?)")
Values = ['smile','cry','blame']
cursor.execute(SQLCommand,Values)
connection.commit()
connection.close()

This is my first attempt to connect Python with sql server. I don't have an idea what would be the driver name, server name, username and password.Do you have any idea of what should be my configuration. Please help me.

Body:
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};' 'Server=**SERVER NAME**;' 'Database=**DATABASE NAME**;' 'Trusted_Connection=yes;')
cursor = conn.cursor()

cursor.execute('SELECT * FROM Output3')

This works just check you specify the Respective Driver, Server and the Database names correctively!