问:
Speed limit for multiple locations using HERE API
I need to know the speed limit for some coordinates from the vehicle's trip.
If I do POST request like:

```<code>https://fleet.cit.api.here.com/2/calculateroute.json?routeMatch=1&mode=car&attributes=SPEED_LIMITS_FCn(*)&&app_id=APP_ID&app_code=APP_CODE

with body:
LATITUDE,LONGITUDE
37.401996,-122.041338
37.416438,-122.086022
</code>```

I'm receiving back built route with very many coordinates.
But I'm interested in only two coordinates...
Is there a better way to get speed-limit for a few (~10-100) coordinates?

答:
This will get an array of link and if speed limit is available in map data, it would be returned for the link. linkAttributes and routeAttributes will limit the response of parameters. the default response however can't be limited.

https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey=xxx&waypoint0=42.4065,-113.3798&waypoint1=42.2821,-83.74847&mode=fastest;car&inkAttributes=speedLimit,dynamicSpeedInfo&legAttributes=links

speedinfo can come via geocoder API in the form of speed category like below that will be based on the address location.

https://geocoder.ls.hereapi.com/6.2/geocode.json?searchtext=Castro%20St%20Mountain%20View%20Santa%20Clara%20US&gen=9&apiKey=xxxxx&locationattributes=li

Body:
I need to know the speed limit for some coordinates from the vehicle's trip.
If I do POST request like:

https://fleet.cit.api.here.com/2/calculateroute.json?routeMatch=1&mode=car&attributes=SPEED_LIMITS_FCn(*)&&app_id=APP_ID&app_code=APP_CODE

with body:
LATITUDE,LONGITUDE
37.401996,-122.041338
37.416438,-122.086022

I'm receiving back built route with very many coordinates.
But I'm interested in only two coordinates...
Is there a better way to get speed-limit for a few (~10-100) coordinates?


来源: stackexchange

问:
jquery selector problem
I'm using this code:

```<code>$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})
</code>```

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

```<code><fieldset>
        <input checked="checked" />
        <label></label>
        <div class="toggle_box">
            <div class="switch" state="on"></div>
        </div>
    </fieldset>
    <fieldset>
        <input/>
        <label></label>
        <div class="toggle_box">
            <div class="switch"></div>
        </div>
    </fieldset>
</code>```

答:
At first glance I see you're using .is('checked') when I beleive you want .is(':checked') The preceding colon being the difference.

UPDATE:  I see you updated the code.  The line

```<code>if ($(this).attr('checked', 'checked'))
</code>```

is actually setting all 'input:checkbox' elements to checked.  It should be:

```<code>if ($(this).is(':checked'))
</code>```

ContentLicense: CC BY-SA 3.0

Title: jquery selector problem

Body:
I'm using this code:

$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
    var switches = $(this).parent().find('.switch');
    $(switches).attr('state','on')
    $(switches).css({'left':"52px"});
    $(switches).parent().css({'background-position': "147px -37px"});
}})

But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?

Thanks for your help :)

EDIT:
here is the HTML

<fieldset>
        <input checked="checked" />

    </fieldset>
    <fieldset>
        <input/>

    </fieldset>

Body:
At first glance I see you're using .is('checked') when I beleive you want .is(':checked') The preceding colon being the difference.

UPDATE:  I see you updated the code.  The line

if ($(this).attr('checked', 'checked'))

is actually setting all 'input:checkbox' elements to checked.  It should be:

if ($(this).is(':checked'))


问:
Must class constructor variables be assigned to private class variables or is there a less code intensive way?
When creating a class you have to assign its parameters to private class variables in order to use those private variables in other procedures and functions in the class. This is code intensive since you have to define the same variable twice.

I have tried using a constructor parameter in a procedure of the same class but it did not work without having to

```<code>type
    WorldObject=class

    private
        privX, privY, privStartSpriteNum, privEndSpriteNum:word;
        privDirection, privTurn:byte;

    public
        constructor create(x, y, startSpriteNum, endSpriteNum:word; direction, turn:byte);
        procedure draw;

constructor WorldObject.create(x, y, startSpriteNum, endSpriteNum:word; direction, turn:byte);
begin
    privX:=x;
    privY:=y;
    privStartSpriteNum:=startSpriteNum;
    privEndSpriteNum:=endSpriteNum;
    privDirection:=direction;
    privTurn:=turn;
end;

procedure WorldObject.draw;
begin
    writeLn(privX);
    writeLn(WorldObject.x);
end;
</code>```

Was expecting writeLn(WorldObject.x) to print the value of x.
But got the error: Identifier idents no member "x".

Is there not a way to use the parameter variables from the constructor without having to pass them to private variables?

Thanks!

答:
You can write properties instead of copying private variables, you just need to specify where to read and where to write, since then you can use properties in nested classes or even outside the class.
If you need to use them in the nested classes, declare as protected, if not - as public.</p>

```<code>property MyProp: TYPE read WriteMyProp read GetMyProp; // for procedure to write and function to read;
property MyPropV: TYPE read MyPropValue write MyPropValue; // for deriving from variable;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When creating a class you have to assign its parameters to private class variables in order to use those private variables in other procedures and functions in the class. This is code intensive since you have to define the same variable twice.

I have tried using a constructor parameter in a procedure of the same class but it did not work without having to

type
    WorldObject=class

    private
        privX, privY, privStartSpriteNum, privEndSpriteNum:word;
        privDirection, privTurn:byte;

    public
        constructor create(x, y, startSpriteNum, endSpriteNum:word; direction, turn:byte);
        procedure draw;

constructor WorldObject.create(x, y, startSpriteNum, endSpriteNum:word; direction, turn:byte);
begin
    privX:=x;
    privY:=y;
    privStartSpriteNum:=startSpriteNum;
    privEndSpriteNum:=endSpriteNum;
    privDirection:=direction;
    privTurn:=turn;
end;

procedure WorldObject.draw;
begin
    writeLn(privX);
    writeLn(WorldObject.x);
end;

Was expecting writeLn(WorldObject.x) to print the value of x.
But got the error: Identifier idents no member "x".

Is there not a way to use the parameter variables from the constructor without having to pass them to private variables?

Thanks!

Body:
You can write properties instead of copying private variables, you just need to specify where to read and where to write, since then you can use properties in nested classes or even outside the class.
If you need to use them in the nested classes, declare as protected, if not - as public.

property MyProp: TYPE read WriteMyProp read GetMyProp; // for procedure to write and function to read;
property MyPropV: TYPE read MyPropValue write MyPropValue; // for deriving from variable;


问:
How can I easily crop a PDF page?
How can I easily crop a PDF page in a given PDF file? I prefer using as little coding as possible, and guess border geometries as little as possible...</p>

答: You could try using the pdfCropMargins Python program (https://pypi.org/project/pdfCropMargins/) with the -pg option to select the particular page.  The command-line program offers many options, and also has an optional GUI.

Title: How can I easily crop a PDF page?


问:
Vue.js Compile Error: no-unused-vars & no-undef
I'm currently trying to create a Vue.js component. When I start the app there's an error.
The error message as shown below:

```<code><template>
    <div class="hello" id="app">
         <span style="font-size:30px;cursor:pointer;" onclick="openNav()">☰</span>

        <div id="mySidenav" class="sidenav">
            <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
            <a href="#">{{name1}}</a>
            <a href="#">{{name2}}</a>
            <a href="#">{{name3}}</a>
            <a href="#">{{name4}}</a>

            <div id="bottom">
                <input v-model="name1" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name2" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name3" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name4" style="margin-left: 25px;max-width: 50%;">
            </div>

        </div>
        <h2>Lorem ipsum dolor sit amet</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque elit velit, dictum in urna et,
            vulputate ornare sapien. Phasellus sed metus sed dolor hendrerit iaculis.
            Cras eget libero sit amet massa aliquet dignissim. Vivamus faucibus lorem sit amet semper luctus.
            Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In at placerat
            felis,
            id finibus mauris. Proin maximus orci quis lacus pellentesque, ac dignissim sapien vestibulum. Maecenas
            pharetra
            vulputate semper.
            Suspendisse potenti. Donec nisi nisi, aliquam eget felis euismod, semper dictum ligula.
            Aenean mauris enim, iaculis vel malesuada vel, pulvinar et risus. Fusce sit amet orci eget diam commodo
            ultricies sed vel elit.
            Curabitur quis scelerisque est.</p>
    </div>
</template>

<script>
    //Vue App
    var app = new Vue({
        el: '#app',
        data: {
            /*
            navlink: [
                {id: 1, link: "https://www.tfbern.ch"},
                {id: 2, link: "https://www.tfbern.ch"},
                {id: 3, link: "https://www.tfbern.ch"},
                {id: 4, link: "https://www.tfbern.ch"}
                ]
            */

            name1: 'name 1',
            name2: 'name 2',
            name3: 'name 3',
            name4: 'name 4'
        }
    })
    export default {
        name: 'NavigationDrawer',
        props: {
            msg: String
        }
    }

    //Navbar Animation
   /*
   function openNav() {
        document.getElementById("mySidenav").style.width = "250px";
    }

    function closeNav() {
        document.getElementById("mySidenav").style.width = "0"; -->
    }
     */
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
</code>```

Navigation-Drawer.vue

```<code><template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <App msg="test">
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import App from './components/Navigation-Drawer.vue'
export default {
  name: 'App',
  components: {
    HelloWorld,
    App
  }
}

</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
</code>```

App.vue

答:
These are the errors from eslint. See https://eslint.org/docs/rules/no-unused-vars and https://eslint.org/docs/rules/no-undef for details.

In order to remove these errors, add this line just before the line where you are initializing the app

```<code>    // eslint-disable-next-line
    var app = new Vue({
    // rest of the code
</code>```

Make sure that the line with eslint-disable-next-line is commented. This will tell eslint to ignore that line and not lint it.

Body:
I'm currently trying to create a Vue.js component. When I start the app there's an error.
The error message as shown below:

<template>

         ☰

            ×
            {{name1}}
            {{name2}}
            {{name3}}
            {{name4}}

                <input v-model="name1" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name2" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name3" style="margin-left: 25px;max-width: 50%;">
                <input v-model="name4" style="margin-left: 25px;max-width: 50%;">

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque elit velit, dictum in urna et,
            vulputate ornare sapien. Phasellus sed metus sed dolor hendrerit iaculis.
            Cras eget libero sit amet massa aliquet dignissim. Vivamus faucibus lorem sit amet semper luctus.
            Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In at placerat
            felis,
            id finibus mauris. Proin maximus orci quis lacus pellentesque, ac dignissim sapien vestibulum. Maecenas
            pharetra
            vulputate semper.
            Suspendisse potenti. Donec nisi nisi, aliquam eget felis euismod, semper dictum ligula.
            Aenean mauris enim, iaculis vel malesuada vel, pulvinar et risus. Fusce sit amet orci eget diam commodo
            ultricies sed vel elit.
            Curabitur quis scelerisque est.

</template>

Navigation-Drawer.vue

<template>

    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <App msg="test">

</template>

App.vue

Body:
These are the errors from eslint. See https://eslint.org/docs/rules/no-unused-vars and https://eslint.org/docs/rules/no-undef for details.

In order to remove these errors, add this line just before the line where you are initializing the app

    // eslint-disable-next-line
    var app = new Vue({
    // rest of the code

Make sure that the line with eslint-disable-next-line is commented. This will tell eslint to ignore that line and not lint it.


问:
Xml Parsing using SAX parser in Android application.
Can anybody please solve my Issue regarding XML SAX Parsing:

I have a small issue that in my Android application when parsing is done, it goes through the whole response and parse the data.

My issue is that I just want to parse the data from the particular place. So that when I parse the XML Response, parsing should be done from the desired place and then it should not check further even if the "same tag" used to appear elsewhere in the response.

Is there any way to do this? I am stranded in this situation badly and have no clue for what to do.

答: Try using xmlpullparser instead of SAX parser, Android supports xmlpullparser too</p>


问:
Spark: create a csv file(must use scala and dataframe)
I'm learning scala and dataframe recently and I came up a problem. It is about dataframe things. It must be solved using Scala and Dataframe, but NOT SparkSQL.

Problem:

Create a csv file with 4 columns (person, class, subject, score)for a school and put some random data into the csv, each person must have "Maths", "English", "Art" and plus some other subjects, and at least there are 3 classes.

Write a Spark program to:

read a csv file

show the full data table

show how many persons per class

show the person and his score with the highest score in "Maths"

I have tried to solve it and googled it, but what I came up is about using SQL to resolve it and also SQL is the first solution given by google.

I really don't know how to do it via Spark and Dataframe but NOT SparkSQL, though the tutorial said it was a very easy question:(

Could anyone help me with it, like write an example for me or give me an example?
thank you so much. I will very appreciate it.

Body:
Sample csv file :

+-------+-------+---------+-------+
| name  | class | subject | marks |
+-------+-------+---------+-------+
| ab    | 12    | Maths   | 72    |
+-------+-------+---------+-------+
| abc   | 12    | Maths   | 88    |
+-------+-------+---------+-------+
| abcd  | 11    | Arts    | 92    |
+-------+-------+---------+-------+
| abcde | 12    | English | 88    |
+-------+-------+---------+-------+
| bc    | 11    | Maths   | 99    |
+-------+-------+---------+-------+
| bcd   | 12    | English | 55    |
+-------+-------+---------+-------+
| bcde  | 11    | English | 77    |
+-------+-------+---------+-------+
| axax  | 10    | Maths   | 83    |
+-------+-------+---------+-------+
| amam  | 10    | English | 65    |
+-------+-------+---------+-------+
| arar  | 10    | Arts    | 66    |
+-------+-------+---------+-------+

Read csv file:

val df = spark.read.option("inferSchema","true").option("header","true").csv(filePath)

Show dataframe :

df.show()

Show how many persons per class :

df.groupBy("class").count.show

Show the person and his score with the highest score in "Maths":
df.filter(col("subject")==="Maths").orderBy(desc("marks")).limit(1).show

Moreover for the last question we can also filter out the class also.


问:
How To get values of textfields from a UITableViewCell dynamic in swift?
How to submit all cell values dynamic

Here is code . I just hit the api and after that I append the values then I show all the data. Right now the issue is how to text field all vaues get.

```<code>func submitApi(){

    SVProgressHUD.show(withStatus: "Loading please wait........")
    let url = constatUrl + "url"
    print("catagory",url)

    Alamofire.request(url, method: .get, parameters:nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
        switch(response.result) {
        case .success(_):
            SVProgressHUD.dismiss()
            if let data = response.result.value{

                let json = response.result.value as? [String: Any]
                print("theloginAuthValue is ",json!)
                let responseStatus = json!["responseStatus"] as! Bool
                let responseText  = json!["responseText"] as! String

                if (responseStatus == true){

                    self.user_GLosary.removeAll()

                    self.productLabel.isHidden = false
                    self.quantyLabel.isHidden = false
                     self.quntySubmitButton.isHidden = false

                    let responseData = json!["responseData"] as! [Any]
                    var index = 0
                    while index < responseData.count{

                        let responseArray = responseData[index] as! [String: Any]
                        let chainId = responseArray["id"] as? String
                        let chainValue = responseArray["value"] as? String

                        let folderAppend = FolderGlosaryDetails()
                       folderAppend.glosaryId = chainId
                       folderAppend.glosaryName = chainValue
                       self.user_GLosary.append(folderAppend)

                        index += 1
                    }

                    DispatchQueue.main.async {
                        self.openingStockTableView.reloadData()
                    }
                }
                else if (responseStatus == false){

                    self.displayAlertMessage(messageToDisplay: responseText)
                }
            }
            break

        case .failure(_):
            SVProgressHUD.dismiss()
            print("faliure",response.result.error!)
            self.displayAlertMessage(messageToDisplay: "Something Wrong Please try again")
            break

        }
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return user_GLosary.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier:"OpeningStockCell",for: indexPath) as! OpeningStockCell

    cell.stockLabel.text = user_GLosary[indexPath.row].glosaryName
    return cell
}
</code>```

答:
Your Question is not so clear but i think you want to store your textfield value into some array from tableviewCell, so bellow code may help you.

First, define array for store value into. i,m taking string array here you can take as per your need.

```<code>var arrayValue:Array<String>!
</code>```

Then store your textfield value from cell into array.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier:"OpeningStockCell",for: indexPath) as! OpeningStockCell

    cell.stockLabel.text = user_GLosary[indexPath.row].glosaryName

    // here you can see how you can get value from textfield
    arrayValue.append(cell.yourTextField.text!)
    return cell

}
</code>```

Body:
How to submit all cell values dynamic

Here is code . I just hit the api and after that I append the values then I show all the data. Right now the issue is how to text field all vaues get.

func submitApi(){

    SVProgressHUD.show(withStatus: "Loading please wait........")
    let url = constatUrl + "url"
    print("catagory",url)

    Alamofire.request(url, method: .get, parameters:nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
        switch(response.result) {
        case .success(_):
            SVProgressHUD.dismiss()
            if let data = response.result.value{

                let json = response.result.value as? [String: Any]
                print("theloginAuthValue is ",json!)
                let responseStatus = json!["responseStatus"] as! Bool
                let responseText  = json!["responseText"] as! String

                if (responseStatus == true){

                    self.user_GLosary.removeAll()

                    self.productLabel.isHidden = false
                    self.quantyLabel.isHidden = false
                     self.quntySubmitButton.isHidden = false

                    let responseData = json!["responseData"] as! [Any]
                    var index = 0
                    while index < responseData.count{

                        let responseArray = responseData[index] as! [String: Any]
                        let chainId = responseArray["id"] as? String
                        let chainValue = responseArray["value"] as? String

                        let folderAppend = FolderGlosaryDetails()
                       folderAppend.glosaryId = chainId
                       folderAppend.glosaryName = chainValue
                       self.user_GLosary.append(folderAppend)

                        index += 1
                    }

                    DispatchQueue.main.async {
                        self.openingStockTableView.reloadData()
                    }
                }
                else if (responseStatus == false){

                    self.displayAlertMessage(messageToDisplay: responseText)
                }
            }
            break

        case .failure(_):
            SVProgressHUD.dismiss()
            print("faliure",response.result.error!)
            self.displayAlertMessage(messageToDisplay: "Something Wrong Please try again")
            break

        }
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return user_GLosary.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier:"OpeningStockCell",for: indexPath) as! OpeningStockCell

    cell.stockLabel.text = user_GLosary[indexPath.row].glosaryName
    return cell
}

Body:
Your Question is not so clear but i think you want to store your textfield value into some array from tableviewCell, so bellow code may help you.

First, define array for store value into. i,m taking string array here you can take as per your need.

var arrayValue:Array<String>!

Then store your textfield value from cell into array.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier:"OpeningStockCell",for: indexPath) as! OpeningStockCell

    cell.stockLabel.text = user_GLosary[indexPath.row].glosaryName

    // here you can see how you can get value from textfield
    arrayValue.append(cell.yourTextField.text!)
    return cell

}


问:
SSL client authentication in Android
I need to write Android app that will be communicate with .Net service. I have to make server/client authentication. I found some useful topics (this blog and this blog) , but they both show how to made server authentication. How can I made client authentication? I found a useful discussion, but there author uses Sockets, but i need to make it via HttpClient.</p>

答:
the following allows me to use my own rootca and client+server certificates. ie, security without paying anyone money :-)

create your rootca, and client and server keys and certs using openssl (many tutorials for this on the web)

create rootcacert.bks using keytool with bouncycastle as provider and -importcert

create clientcertandkey.p12 using openssl pkcs12 -export ...

```<code>HttpClient httpClient = null;
try {
    HttpParams httpParameters = new BasicHttpParams();
    KeyStore rootca = KeyStore.getInstance("BKS");
    rootca.load(getResources().openRawResource(R.raw.rootcacert),"bkskeystorepass".toCharArray());
    KeyStore mycert = KeyStore.getInstance("pkcs12");
    mycert.load(getResources().openRawResource(R.raw.clientcertandkey),"pkcs12storepass".toCharArray());
    SSLSocketFactory sockfact = new SSLSocketFactory(mycert,null,rootca);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https",sockfact , 443));
    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParameters, registry), httpParameters);
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Title: SSL client authentication in Android

Body:
the following allows me to use my own rootca and client+server certificates. ie, security without paying anyone money :-)

create your rootca, and client and server keys and certs using openssl (many tutorials for this on the web)

create rootcacert.bks using keytool with bouncycastle as provider and -importcert

create clientcertandkey.p12 using openssl pkcs12 -export ...

HttpClient httpClient = null;
try {
    HttpParams httpParameters = new BasicHttpParams();
    KeyStore rootca = KeyStore.getInstance("BKS");
    rootca.load(getResources().openRawResource(R.raw.rootcacert),"bkskeystorepass".toCharArray());
    KeyStore mycert = KeyStore.getInstance("pkcs12");
    mycert.load(getResources().openRawResource(R.raw.clientcertandkey),"pkcs12storepass".toCharArray());
    SSLSocketFactory sockfact = new SSLSocketFactory(mycert,null,rootca);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https",sockfact , 443));
    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParameters, registry), httpParameters);
} catch (Exception e) {
    e.printStackTrace();
}


问:
Not able to load image when captured from Camera second time
I have been using Camera Intent to capture images. For the first time it works perfectly and I am able to capture image and show that in ImageView. But when I try second time to capture a different image it still shows the same old image.

Here is my code for Camera Intent and onActivityResult()

```<code>       Uri selectedImage;
        private Uri imageUri;

         private void activeTakePhoto() {

                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                            File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photo));
                            imageUri = Uri.fromFile(photo);
                            startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
                        }

      @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case RESULT_LOAD_IMAGE:
                    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
                        selectedImage = data.getData();
                        imageView.setImageURI(selectedImage);
                    }

                    break;

                case REQUEST_IMAGE_CAPTURE:
                    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                        try {
                            selectedImage = imageUri;
                            getContentResolver().notifyChange(selectedImage, null);
                            imageView.setImageURI(imageUri);
                        } catch (Exception e) {
                            Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                                    .show();
                            Log.e("Camera", e.toString());
                        }
                        Log.e("A", "AAA");
                    }
            }
        }

   submit.setOnClickListener(new View.OnClickListener() { // back to Activity A listView
            @Override
            public void onClick(View v) {
                Intent returnIntent = new Intent();
                amount = Amount.getText().toString();
                description = Description.getText().toString();
                type = spinnerType.getSelectedItem().toString();
                returnIntent.putExtra("type", type);
                returnIntent.putExtra("description", description);
                returnIntent.putExtra("amount", amount);
                if(selectedImage!=null) {
                    returnIntent.putExtra("img_uri", selectedImage.toString());
                }
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });
</code>```

Activity A

```<code> listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) { // if list is clicked
                mClickedPosition = position;
                Object o = listview.getItemAtPosition(position);
                ImageAndText image = (ImageAndText) o;
                String type = image.getType();
                String amount = image.getAmount();
                String description = image.getDescription();
                Uri photo = image.getImage();
                String[] type1 = type.split(":");
                String[] amount1 = amount.split(":");
                String[] description1 = description.split(":");
                Intent i = new Intent(getApplication(), AddMoreClaims.class);
                i.putExtra("type", type1[1].toString().trim());
                i.putExtra("amount", amount1[1].toString().trim());
                i.putExtra("description", description1[1].toString().trim());
                i.putExtra("photo", photo);
                startActivityForResult(i, PROJECT_REQUEST_CODE);
            }
        });
</code>```

Edited(add TimeStamp)

```<code> private void activeTakePhoto() {
        String filename = "Pic_" + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(photo,filename));
        imageUri = Uri.fromFile(photo,filename);
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }
</code>```

答:
```<code>>To display image which is captured by camera on second time, Simply **update** the first element from database after completing the operation .
</code>```

public class MainActivity extends AppCompatActivity {

```<code>private static final int CAMERA_REQUEST = 1;
private static final int GALLERY_IMAGE = 2;
private static final String TAG = "";
Button captureImage;
ImageView imageView;
ImageDatabase database;
Bitmap b,theImage;
MainActivity CameraActivity = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    CameraActivity = this;

    imageView = (ImageView) findViewById(R.id.image_view);
    database = new ImageDatabase(this);

    //Set OnClick Listener to button view
    captureImage = (Button) findViewById(R.id.capture_image);
    captureImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            isStoragePermissionGranted();
        }
    });

    //long press on image
    imageView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            isStoragePermissionGranted();
            return true;
        }
    });
}

private void startDialog() {
    AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
            CameraActivity);
    myAlertDialog.setTitle("Upload Pictures Option");
    myAlertDialog.setMessage("How do you want to set your picture?");

    myAlertDialog.setPositiveButton("Gallery",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    Intent i = new Intent();
                    i.setType("image/*");
                    i.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(i.createChooser(i, "Result load Image")
                            , GALLERY_IMAGE);
                }
            });

    myAlertDialog.setNegativeButton("Camera",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {

                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            });
    myAlertDialog.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {

        theImage = (Bitmap) data.getExtras().get("data");

    }

    if (requestCode == GALLERY_IMAGE && resultCode == RESULT_OK) {
        try {
            Uri imageUri = data.getData();
            InputStream imageStream = getContentResolver().openInputStream(imageUri);
            theImage = BitmapFactory.decodeStream(imageStream);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        theImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        SQLiteDatabase db = database.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ImageDatabase.KEY_IMG_URL, byteArray);
        db.insert(ImageDatabase.TABLE_NAME, null, values);
        db.update(ImageDatabase.TABLE_NAME, values, null, null);
        db.close();

}

public void getTheImage() {

    SQLiteDatabase db = database.getReadableDatabase();

    Cursor cursor = (Cursor) db.rawQuery(" SELECT * FROM " + ImageDatabase.TABLE_NAME,
            null, null);
    if (cursor.moveToFirst()) {
        byte[] imgByte = cursor.getBlob(cursor.getColumnIndex(ImageDatabase.KEY_IMG_URL));
        cursor.close();
        b = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);

    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    imageView.setImageBitmap(b);

}

//Storage permission
public boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG, "Permission is granted");
            startDialog();
            return true;
        } else {

            Log.v(TAG, "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG, "Permission is granted");
        startDialog();
        return true;
    }
}

@Override
protected void onStart() {
    super.onStart();
    getTheImage();
}
</code>```

}

Body:
I have been using Camera Intent to capture images. For the first time it works perfectly and I am able to capture image and show that in ImageView. But when I try second time to capture a different image it still shows the same old image.

Here is my code for Camera Intent and onActivityResult()

       Uri selectedImage;
        private Uri imageUri;

         private void activeTakePhoto() {

                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                            File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photo));
                            imageUri = Uri.fromFile(photo);
                            startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
                        }

      @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case RESULT_LOAD_IMAGE:
                    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
                        selectedImage = data.getData();
                        imageView.setImageURI(selectedImage);
                    }

                    break;

                case REQUEST_IMAGE_CAPTURE:
                    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                        try {
                            selectedImage = imageUri;
                            getContentResolver().notifyChange(selectedImage, null);
                            imageView.setImageURI(imageUri);
                        } catch (Exception e) {
                            Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                                    .show();
                            Log.e("Camera", e.toString());
                        }
                        Log.e("A", "AAA");
                    }
            }
        }

   submit.setOnClickListener(new View.OnClickListener() { // back to Activity A listView
            @Override
            public void onClick(View v) {
                Intent returnIntent = new Intent();
                amount = Amount.getText().toString();
                description = Description.getText().toString();
                type = spinnerType.getSelectedItem().toString();
                returnIntent.putExtra("type", type);
                returnIntent.putExtra("description", description);
                returnIntent.putExtra("amount", amount);
                if(selectedImage!=null) {
                    returnIntent.putExtra("img_uri", selectedImage.toString());
                }
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });

Activity A

 listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) { // if list is clicked
                mClickedPosition = position;
                Object o = listview.getItemAtPosition(position);
                ImageAndText image = (ImageAndText) o;
                String type = image.getType();
                String amount = image.getAmount();
                String description = image.getDescription();
                Uri photo = image.getImage();
                String[] type1 = type.split(":");
                String[] amount1 = amount.split(":");
                String[] description1 = description.split(":");
                Intent i = new Intent(getApplication(), AddMoreClaims.class);
                i.putExtra("type", type1[1].toString().trim());
                i.putExtra("amount", amount1[1].toString().trim());
                i.putExtra("description", description1[1].toString().trim());
                i.putExtra("photo", photo);
                startActivityForResult(i, PROJECT_REQUEST_CODE);
            }
        });

Edited(add TimeStamp)

 private void activeTakePhoto() {
        String filename = "Pic_" + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(photo,filename));
        imageUri = Uri.fromFile(photo,filename);
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }

Body:
>To display image which is captured by camera on second time, Simply **update** the first element from database after completing the operation .

public class MainActivity extends AppCompatActivity {

private static final int CAMERA_REQUEST = 1;
private static final int GALLERY_IMAGE = 2;
private static final String TAG = "";
Button captureImage;
ImageView imageView;
ImageDatabase database;
Bitmap b,theImage;
MainActivity CameraActivity = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    CameraActivity = this;

    imageView = (ImageView) findViewById(R.id.image_view);
    database = new ImageDatabase(this);

    //Set OnClick Listener to button view
    captureImage = (Button) findViewById(R.id.capture_image);
    captureImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            isStoragePermissionGranted();
        }
    });

    //long press on image
    imageView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            isStoragePermissionGranted();
            return true;
        }
    });
}

private void startDialog() {
    AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
            CameraActivity);
    myAlertDialog.setTitle("Upload Pictures Option");
    myAlertDialog.setMessage("How do you want to set your picture?");

    myAlertDialog.setPositiveButton("Gallery",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    Intent i = new Intent();
                    i.setType("image/*");
                    i.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(i.createChooser(i, "Result load Image")
                            , GALLERY_IMAGE);
                }
            });

    myAlertDialog.setNegativeButton("Camera",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {

                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            });
    myAlertDialog.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {

        theImage = (Bitmap) data.getExtras().get("data");

    }

    if (requestCode == GALLERY_IMAGE && resultCode == RESULT_OK) {
        try {
            Uri imageUri = data.getData();
            InputStream imageStream = getContentResolver().openInputStream(imageUri);
            theImage = BitmapFactory.decodeStream(imageStream);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        theImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        SQLiteDatabase db = database.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ImageDatabase.KEY_IMG_URL, byteArray);
        db.insert(ImageDatabase.TABLE_NAME, null, values);
        db.update(ImageDatabase.TABLE_NAME, values, null, null);
        db.close();

}

public void getTheImage() {

    SQLiteDatabase db = database.getReadableDatabase();

    Cursor cursor = (Cursor) db.rawQuery(" SELECT * FROM " + ImageDatabase.TABLE_NAME,
            null, null);
    if (cursor.moveToFirst()) {
        byte[] imgByte = cursor.getBlob(cursor.getColumnIndex(ImageDatabase.KEY_IMG_URL));
        cursor.close();
        b = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);

    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    imageView.setImageBitmap(b);

}

//Storage permission
public boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG, "Permission is granted");
            startDialog();
            return true;
        } else {

            Log.v(TAG, "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG, "Permission is granted");
        startDialog();
        return true;
    }
}

@Override
protected void onStart() {
    super.onStart();
    getTheImage();
}

}


问:
Error creating bean with name 'dataSource' [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]
i'm getting the following error when i try to debug a Spring boot with Gradle project in Eclipse

```<code>Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested exception
is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in class path resource
[org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]

Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver

</code>```

i've searched a lot, and most of the solutions came from something that is wrong in the application.properties file, but i can not figure what is wrong in mine

```<code>server.port=8080
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/dices?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
</code>```

Any suggestion?

thanks

答: The problem was with eclipse which was not downloading the dependencies. Gradle configuration files were ok</p>

Body:
i'm getting the following error when i try to debug a Spring boot with Gradle project in Eclipse

Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested exception
is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in class path resource
[org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]

Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver

i've searched a lot, and most of the solutions came from something that is wrong in the application.properties file, but i can not figure what is wrong in mine

server.port=8080
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/dices?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

Any suggestion?

thanks


答:
```<code>library(dplyr)

df %>%
    left_join(df1, by=c('ID','DAY','MONTH','YEAR','HOUR')) %>%
    left_join(df2, by=c('ID','DAY','MONTH','YEAR')) %>%
    left_join(df3, by=c('ID','MONTH','YEAR'))
</code>```

Output:

```<code>  ID YEAR MONTH DAY HOUR VALUE1 VALUE2 VALUE3 VALUE4
1  A 2020     1  16   15      1      3      6      9
2  B 2020     1  16   15      2      4      7     10
3  C 2020     1  16   15      3      5      8     11
</code>```

So, this is a little more efficient, because it doesn't use memory for the intermediate results.

Title: How to merge(efficient way) multiple data frame in one go?

Body:
I would like to merge multiple dataframe in one shot. Below the method, I am currently using for merging.
My data:

df <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'DAY'=c('16','16','16'),'HOUR'=c('15','15','15'),'VALUE1'=c(1,2,3))

df1 <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'DAY'=c('16','16','16'),'HOUR'=c('15','15','15'),'VALUE2'=c(3,4,5))

df2 <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'DAY'=c('16','16','16'),'VALUE3'=c(6,7,8))

df3 <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'VALUE4'=c(9,10,11))

My method of merging:

df4 <- merge(df,df1,by=c('ID','DAY','MONTH','YEAR','HOUR'),all.x=T)
df5 <- merge(df4,df2,by=c('ID','DAY','MONTH','YEAR'),all.x=T)
df6 <- merge(df5,df3,by=c('ID','MONTH','YEAR'),all.x=T)

My output:

ID MONTH YEAR DAY HOUR VALUE1 VALUE2 VALUE3 VALUE4
1  A     1 2020  16   15      1      3      6      9
2  B     1 2020  16   15      2      4      7     10
3  C     1 2020  16   15      3      5      8     11

Is there any good method of merging which can make code more efficient. I appreciate any help.

Body:
library(dplyr)

df %>%
    left_join(df1, by=c('ID','DAY','MONTH','YEAR','HOUR')) %>%
    left_join(df2, by=c('ID','DAY','MONTH','YEAR')) %>%
    left_join(df3, by=c('ID','MONTH','YEAR'))

Output:

  ID YEAR MONTH DAY HOUR VALUE1 VALUE2 VALUE3 VALUE4
1  A 2020     1  16   15      1      3      6      9
2  B 2020     1  16   15      2      4      7     10
3  C 2020     1  16   15      3      5      8     11

So, this is a little more efficient, because it doesn't use memory for the intermediate results.


问:
C# Sending UrlEndcoded Form Data
Trying to send UrlEncoded form data in Post request :

```<code>        client.BaseAddress = new Uri("myURI");

        var formContent = new MultipartFormDataContent();
        formContent.Headers.ContentType.MediaType = "application/x-www-form-urlencoded";

        formContent.Add(new StringContent("password"), "grant_type");
        formContent.Add(new StringContent("someUser"), "username");
        formContent.Add(new StringContent("somePassword"), "password");
        HttpResponseMessage response = client.PostAsync("token", formContent).Result;
</code>```

For some reason the request headers contain the following :

```<code> somePassword
 --7e556624-1d60-4321-a4ee-a85f6ab601c6
 Content-Type: text/plain; charset=utf-8
 Content-Disposition: form-data; name=username

 someUser
 --7e556624-1d60-4321-a4ee-a85f6ab601c6
 Content-Type: text/plain; charset=utf-8
 Content-Disposition: form-data; name=password
</code>```

etc...

The Guid I guess is a boundary. However since I used urlencode it should be a '?' boundary.

In fact, if I call my service with Postman, using the same parameters and application/x-www-form-urlencoded then the request headers contain :

app_profile=freelancer&username=someUser&password=SomePassword&grant_type=password

So how do I achieve this with C# ?

[EDIT]

I managed to make it work like this. However I'd like to understand what was wrong in the original code ?

```<code> var values = new Dictionary<string, string>
        {
            {"username", "someUser"},
            {"password", "somePassword"},
            {"grant_type", "password"},
        };

        var formContent = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "application/json");
        HttpResponseMessage response = client.PostAsync("token", new FormUrlEncodedContent(values)).Result;
</code>```

答:
Initially, you used MultipartFormDataContent.

This means that Request content type will be replaced with
multipart/form-data; boundary={some randomly generated key}

and the request body will be split in chunks using this {some randomly generated key}
each chunk will have its own content type.

multipart/form-data content type especially useful when sending files together with other form data.

In the edited example, you are using StringContent

Title: C# Sending UrlEndcoded Form Data

Body:
Trying to send UrlEncoded form data in Post request :

        client.BaseAddress = new Uri("myURI");

        var formContent = new MultipartFormDataContent();
        formContent.Headers.ContentType.MediaType = "application/x-www-form-urlencoded";

        formContent.Add(new StringContent("password"), "grant_type");
        formContent.Add(new StringContent("someUser"), "username");
        formContent.Add(new StringContent("somePassword"), "password");
        HttpResponseMessage response = client.PostAsync("token", formContent).Result;

For some reason the request headers contain the following :

 somePassword
 --7e556624-1d60-4321-a4ee-a85f6ab601c6
 Content-Type: text/plain; charset=utf-8
 Content-Disposition: form-data; name=username

 someUser
 --7e556624-1d60-4321-a4ee-a85f6ab601c6
 Content-Type: text/plain; charset=utf-8
 Content-Disposition: form-data; name=password

etc...

The Guid I guess is a boundary. However since I used urlencode it should be a '?' boundary.

In fact, if I call my service with Postman, using the same parameters and application/x-www-form-urlencoded then the request headers contain :

app_profile=freelancer&username=someUser&password=SomePassword&grant_type=password

So how do I achieve this with C# ?

[EDIT]

I managed to make it work like this. However I'd like to understand what was wrong in the original code ?

 var values = new Dictionary<string, string>
        {
            {"username", "someUser"},
            {"password", "somePassword"},
            {"grant_type", "password"},
        };

        var formContent = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "application/json");
        HttpResponseMessage response = client.PostAsync("token", new FormUrlEncodedContent(values)).Result;


问:
Any DrRacket keybinding that uses the shift key to modify a letter key doesn't work
I have Enable keybindings in menus unchecked.

As a modifier, the shift key only seems to work for the arrow keys.

For example, in the default active keybindings, "backward-select" is mapped to (c:s:b), but when I hold down ctrl and shift and press "b", it just inserts "B". The same command is also mapped to (s:left), and that works fine. Keybindings without shift also seem to work.

For non-letter keys, I can get around it by making a custom keybind with the up-shifted symbol; (c:colon) works, while (c:s:semicolon) does not.

Thanks for your help.

Things I have tried:

Making my own keybindings as shown in 3.3.9
https://docs.racket-lang.org/drracket/Keyboard_Shortcuts.html

using the Capitalized letter E.g. (c:s:J), changing the order, E.g. (s:c:j)

pressing the keys in a different order

Both Ubuntu and Windows

Upgrading to DrRacket 7.6

Reinstalling DrRacket

begging

pleading

Edits:

https://imgur.com/a/cggI9ei Here's a screenshot of my active keybindings.

Checking Enable keybindings in menus has the expected behaviour, but the shift shortcuts still don't work.

I did have a custom Windows keymapping on with a program called Sharpkeys, but it didn't change shift and I've since disabled it. Now I'm using a Canadian Multilingual Standard keyboard layout, but the US layout doesn't work either.

答:
Can you post a similar screenshot, showing what appears on your system?

In DrRacket in the menu "Edit" choose the menu item "Keybindings"
then choose "Show Active ...".


问:
How would you structure mutual rating social network model on Firestore?
I think it would be easier to display my model with an example. The functionality of the app would be the following: It would be social network schema. A mutual friend model. When a user logins in the app, a list will be displayed. Each list item consist of a friend name - photos(photo1, photo2) - rating for each photo(calculated based on both ratings).

Example:

Logged in as UserA:

```<code>list item1:
[
 name: UserBName,
 photo1: 5 (UserA rated it 2, UserB rated it 8),
 photo2: 4 (UserA rated it 3, UserB rated it 5)
],
list item2:
[
 name: UserCName,
 photo1: 2 (UserA rated it 1, UserC rated it 4)
]
</code>```

I was thinking of creating a friend subcollection for each user document and inside having a structure like that:

```<code>UserB: {
     name: UserBName,
     photo1:{
      rating from UserA: 4
      rating from UserB: 2
     },
     photo2:{
      rating from UserA: 3
      rating from UserB: 5
     }
    }
</code>```

My issue is that UserB(document)->friends(subcollection)->UserA(document) would have the same data and i am not so sure if its a viable solution.

答:
why not just :

list item :[

userB :{...}

userC : {...}

]

userB (and userC) will use the structure you post below, photo1 and photo2 for each item seems redundant

Body:
I think it would be easier to display my model with an example. The functionality of the app would be the following: It would be social network schema. A mutual friend model. When a user logins in the app, a list will be displayed. Each list item consist of a friend name - photos(photo1, photo2) - rating for each photo(calculated based on both ratings).

Example:

Logged in as UserA:

list item1:
[
 name: UserBName,
 photo1: 5 (UserA rated it 2, UserB rated it 8),
 photo2: 4 (UserA rated it 3, UserB rated it 5)
],
list item2:
[
 name: UserCName,
 photo1: 2 (UserA rated it 1, UserC rated it 4)
]

I was thinking of creating a friend subcollection for each user document and inside having a structure like that:

UserB: {
     name: UserBName,
     photo1:{
      rating from UserA: 4
      rating from UserB: 2
     },
     photo2:{
      rating from UserA: 3
      rating from UserB: 5
     }
    }

My issue is that UserB(document)->friends(subcollection)->UserA(document) would have the same data and i am not so sure if its a viable solution.


问:
Angular Protractor e2e mat-radio-group innerText iteration function error
```<code>clickOnQuestionsRadioButton(buttonName) {
    const matRadioButtonList = $$('mat-radio-group > mat-radio-button');
    const question_btn = matRadioButtonList.filter(elem => {
      return elem.getInnerText().then(text => {
        console.log(text);
        return text.toLowerCase().includes(buttonName.toLowerCase());
      });
    }).first().all(by.cssContainingText('innerText', buttonName));
    question_btn.click();
  }

clickOnQuestionsRadioButton('AEP');
</code>```

ERROR:
TypeError: elem.getInnerText is not a function

答:
Instead of getInnerText() use getText().

getInnerText() function does not exist in Protractor API.

Body:
clickOnQuestionsRadioButton(buttonName) {
    const matRadioButtonList = $$('mat-radio-group > mat-radio-button');
    const question_btn = matRadioButtonList.filter(elem => {
      return elem.getInnerText().then(text => {
        console.log(text);
        return text.toLowerCase().includes(buttonName.toLowerCase());
      });
    }).first().all(by.cssContainingText('innerText', buttonName));
    question_btn.click();
  }

clickOnQuestionsRadioButton('AEP');

ERROR:
TypeError: elem.getInnerText is not a function


问:
create a new variable in the data frame based on multiple criteria in r
I have a data set which has

```<code>COl1 COl2 Col3
1     0     0
0     1     0
0     0     1
1     0     0
</code>```

Based on these three column i need to add new variable in the same table

Expected Output

```<code>COl1 COl2 Col3  New_variable
1     0     0     c1
0     1     0     c2
0     0     1     c3
1     0     0     c1
</code>```

答:
Another base option:

```<code>df$New_variable <- paste0('c', apply(df, 1, function(x) which(x != 0)))
</code>```

Output:

```<code>  COl1 COl2 Col3 New_variable
1    1    0    0           c1
2    0    1    0           c2
3    0    0    1           c3
4    1    0    0           c1
</code>```

Since there is a vague reference to dplyr in tags, you could also use this in combination with purrr - though it is clearly an overkill compared to variety of base solutions available (as evident from all the answers):

```<code>library(dplyr)

df %>%
  mutate(
    New_variable = purrr::pmap(select(., 1:3), ~ paste0('c', which(c(...) != 0)))
    )
</code>```

Whereby in the select(., 1:3) statement you can choose which columns to use (here we use all 3 columns, so you could just use . instead of the whole select and it would have the same effect).

Body:
I have a data set which has

COl1 COl2 Col3
1     0     0
0     1     0
0     0     1
1     0     0

Based on these three column i need to add new variable in the same table

Expected Output

COl1 COl2 Col3  New_variable
1     0     0     c1
0     1     0     c2
0     0     1     c3
1     0     0     c1

Body:
Another base option:

df$New_variable <- paste0('c', apply(df, 1, function(x) which(x != 0)))

Output:

  COl1 COl2 Col3 New_variable
1    1    0    0           c1
2    0    1    0           c2
3    0    0    1           c3
4    1    0    0           c1

Since there is a vague reference to dplyr in tags, you could also use this in combination with purrr - though it is clearly an overkill compared to variety of base solutions available (as evident from all the answers):

library(dplyr)

df %>%
  mutate(
    New_variable = purrr::pmap(select(., 1:3), ~ paste0('c', which(c(...) != 0)))
    )

Whereby in the select(., 1:3) statement you can choose which columns to use (here we use all 3 columns, so you could just use . instead of the whole select and it would have the same effect).


问:
How could i send notfication app to web in node js i am new to nodejs please if you can
i have to send a notification on  web when a event occurs on app  </p>

答: If the event dispatches from server, you can use Socket.IO, but if there is no hurry in getting notifications you can request in AJAX form every (for example) 5 minutes from client side code, to check if there are any notifs or not.</p>


问:
docker compose up generate (2005, "Unknown MySQL server host 'db' (-2)") error
Hi all i'm trying to dockerize a django application with a connexion to the database. when i run docker compose up i get this error when the dockerfile is making migrations django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)")
ERROR: Service 'web' failed to build: The command '/bin/sh -c python manage.py makemigrations' returned a non-zero code: 1

here is my Dockerfile

```<code>FROM python:3.6
ENV PYTHONUNBUFFERED 1
RUN mkdir /SFP_ingestion
WORKDIR /SFP_ingestion
COPY . /SFP_ingestion
RUN pip install -r requirements.txt
RUN python generatemodel.py
RUN python generateapp.py
RUN python manage.py makemigrations
RUN python manage.py migrate
RUN python manage.py migrate easyaudit
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
</code>```

and here is my docker-compose.yml

```<code>
services:
  db:
    image: mysql
    restart: always
    command: --default-authentication-plugin=mysql_native_password --mysqlx=0
    environment:
      - MYSQL_HOST=localhost
      - MYSQL_PORT=3306  # cannot change this port to other number
      - MYSQL_DATABASE=sfp # name you want for the database
      - MYSQL_USER=root # change to whatever username you want
      - MYSQL_PASSWORD=password #change to the password you want for user
      - MYSQL_ROOT_PASSWORD=password #change to good root password
    ports:
      - "3306:3306"
    expose:
      - "3306"
    volumes:
      - "./db:/var/lib/mysql"

  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/SFP_ingestion
    restart: always
    ports:
      - "8000:8000"
    depends_on:
      - db
</code>```

答:
You have to specify network for your containers.
https://docs.docker.com/compose/networking/</p>

Body:
Hi all i'm trying to dockerize a django application with a connexion to the database. when i run docker compose up i get this error when the dockerfile is making migrations django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)")
ERROR: Service 'web' failed to build: The command '/bin/sh -c python manage.py makemigrations' returned a non-zero code: 1

here is my Dockerfile

FROM python:3.6
ENV PYTHONUNBUFFERED 1
RUN mkdir /SFP_ingestion
WORKDIR /SFP_ingestion
COPY . /SFP_ingestion
RUN pip install -r requirements.txt
RUN python generatemodel.py
RUN python generateapp.py
RUN python manage.py makemigrations
RUN python manage.py migrate
RUN python manage.py migrate easyaudit
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

and here is my docker-compose.yml

services:
  db:
    image: mysql
    restart: always
    command: --default-authentication-plugin=mysql_native_password --mysqlx=0
    environment:
      - MYSQL_HOST=localhost
      - MYSQL_PORT=3306  # cannot change this port to other number
      - MYSQL_DATABASE=sfp # name you want for the database
      - MYSQL_USER=root # change to whatever username you want
      - MYSQL_PASSWORD=password #change to the password you want for user
      - MYSQL_ROOT_PASSWORD=password #change to good root password
    ports:
      - "3306:3306"
    expose:
      - "3306"
    volumes:
      - "./db:/var/lib/mysql"

  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/SFP_ingestion
    restart: always
    ports:
      - "8000:8000"
    depends_on:
      - db


问:
How to choose the location for the local repository for Mylyn tasks?
I am using a local repository for Mylyn. I would like to save the repository as file in the version controlled path for my project. This way I can have backup and versioning for my tasks. How can I set the repository path?</p>

答:
Windows / Prferences / Tasks

Open up hidden fieldgroup under "Advanced"

PROFIT


问:
How to prevent internal field shift in views when base table gets additional fields?
Today there was an interesting issue in our MS SQL Server database view.

There are several base tables. One is sys_user an the others join in some additional data.

The (beginning of) SQL view definition looks like this:

```<code>ALTER VIEW [dbo].[V_Usage] AS
SELECT u.*,
    case when assexcl.sys_id IS NULL THEN asslookup.home_office ELSE assexcl.home_office END [Home Office],
    case when assexcl.sys_id IS NULL THEN asslookup.assigned_group ELSE assexcl.assigned_group END [Assigned Group],
    case when assexcl.sys_id IS NULL THEN asslookup.drs_hub ELSE assexcl.drs_hub END [DRS Hub],
  x.request_sys_id, x.request_pa_name, x.u_allocation request_allocation, x.u_negotiated_deadline, x.u_research_time, x.u_qa_time_drs, x.u_assignment_group, x.u_utilization_category
FROM sys_user u
    LEFT outer join (...
</code>```

The select u.* brings in all fields of the sys_user table and some other fields are also shown per user which is queried in the lower part.

After adding a field in the sys_user table we had the issues that all content in the last fields was shiftet one column to the right.

[Home Office] did contain the last field of the sys_user table,
[Assigned Group] did contain the content of [Home Office]
etc.

First I would like to understand the issue. I think it is due to internal compilation and referencing.

And second I would like to have a solution to make that not happen again. I would prefer not reference all fields directly in the view since it was intentional that all sys_user fields should be in the view.

Is there a kind of flag or db hint to keep those view correct even when base tables get fields added?

Any information appreciated.

答:
Just dont' use u.*. This is generally not a good practice, and the issue that you are having now is one of the reason why.

While selecting *, there is no "automagical" solution that would allow you to keep those view correct even when base tables get fields added.

Instead, you should enumerate all the columns that you want to pick from sys_user in the select clause. This way, you do control which columns are being displayed in the view, and in which order the appear.

When new columns are added, you can modifiy the definition of the view to add them in the position that you like.

Body:
Today there was an interesting issue in our MS SQL Server database view.

There are several base tables. One is sys_user an the others join in some additional data.

The (beginning of) SQL view definition looks like this:

ALTER VIEW [dbo].[V_Usage] AS
SELECT u.*,
    case when assexcl.sys_id IS NULL THEN asslookup.home_office ELSE assexcl.home_office END [Home Office],
    case when assexcl.sys_id IS NULL THEN asslookup.assigned_group ELSE assexcl.assigned_group END [Assigned Group],
    case when assexcl.sys_id IS NULL THEN asslookup.drs_hub ELSE assexcl.drs_hub END [DRS Hub],
  x.request_sys_id, x.request_pa_name, x.u_allocation request_allocation, x.u_negotiated_deadline, x.u_research_time, x.u_qa_time_drs, x.u_assignment_group, x.u_utilization_category
FROM sys_user u
    LEFT outer join (...

The select u.* brings in all fields of the sys_user table and some other fields are also shown per user which is queried in the lower part.

After adding a field in the sys_user table we had the issues that all content in the last fields was shiftet one column to the right.

[Home Office] did contain the last field of the sys_user table,
[Assigned Group] did contain the content of [Home Office]
etc.

First I would like to understand the issue. I think it is due to internal compilation and referencing.

And second I would like to have a solution to make that not happen again. I would prefer not reference all fields directly in the view since it was intentional that all sys_user fields should be in the view.

Is there a kind of flag or db hint to keep those view correct even when base tables get fields added?

Any information appreciated.


问:
How to set tags while using reflect.New
When creating a new struct from existing struct, tags are not set on the new struct.

For example:

package main

import (
    "fmt"
    "reflect"
)

type Foo struct {
  Bar string `custom:"tag"`
}

func readTag(e interface{}) {
  t := reflect.TypeOf(e).Elem()
  f, _ := t.FieldByName("Bar")
  fmt.Println(f.Tag)
}

func main() {
  foo := &Foo{"baz"}

  fmt.Println(foo)
  readTag(foo)

  fooType := reflect.TypeOf(foo).Elem()
  newFoo := reflect.New(fooType).Elem()
  newFoo.FieldByName("Bar").SetString("baz2")
  fmt.Println(newFoo)
  readTag(&newFoo)// empty
}

```

Playground link: https://play.golang.org/p/7-zMPnwQ8Vo

How to set tags while using reflect.New? Is it even possible?

答:
Tags do not belong to instances, tags belong to types.

So when you create new instances of your type, their type will be the same "wearing" the same tags. It doesn't matter if you create new instances with literals or via the reflect package.

The problem in your case is that newFoo is of type reflect.Value, and &newFoo is of type *reflect.Value, it's not a pointer to your struct (not of type *Foo).

If you unwrap the struct value:

```<code>newFoo.Interface()
</code>```

And you pass this, and you make the Elem() call optional (only do it if it's a pointer):

```<code>func readTag(e interface{}) {
    t := reflect.TypeOf(e)
    if t.Kind() == reflect.Ptr {
        t = t.Elem()
    }
    f, _ := t.FieldByName("Bar")
    fmt.Println(f.Tag)
}
</code>```

Then you'll get the same tag (try it on the Go Playground):

```<code>&{baz}
custom:"tag"
{baz2}
custom:"tag"
</code>```

You get the same result if you keep the reflect.Value wrapping the struct pointer, and unwrap from it:

```<code>newFooPtr := reflect.New(fooType)
newFoo := newFooPtr.Elem()
newFoo.FieldByName("Bar").SetString("baz2")
fmt.Println(newFoo)
readTag(newFooPtr.Interface()) // empty
</code>```

Then readTag() doesn't need to be modified. Try this version on the Go Playground.

Title: How to set tags while using reflect.New

Body:
When creating a new struct from existing struct, tags are not set on the new struct.

For example:

package main

import (
    "fmt"
    "reflect"
)

type Foo struct {
  Bar string `custom:"tag"`
}

func readTag(e interface{}) {
  t := reflect.TypeOf(e).Elem()
  f, _ := t.FieldByName("Bar")
  fmt.Println(f.Tag)
}

func main() {
  foo := &Foo{"baz"}

  fmt.Println(foo)
  readTag(foo)

  fooType := reflect.TypeOf(foo).Elem()
  newFoo := reflect.New(fooType).Elem()
  newFoo.FieldByName("Bar").SetString("baz2")
  fmt.Println(newFoo)
  readTag(&newFoo)// empty
}

Playground link: https://play.golang.org/p/7-zMPnwQ8Vo

How to set tags while using reflect.New? Is it even possible?

Body:
Tags do not belong to instances, tags belong to types.

So when you create new instances of your type, their type will be the same "wearing" the same tags. It doesn't matter if you create new instances with literals or via the reflect package.

The problem in your case is that newFoo is of type reflect.Value, and &newFoo is of type *reflect.Value, it's not a pointer to your struct (not of type *Foo).

If you unwrap the struct value:

newFoo.Interface()

And you pass this, and you make the Elem() call optional (only do it if it's a pointer):

func readTag(e interface{}) {
    t := reflect.TypeOf(e)
    if t.Kind() == reflect.Ptr {
        t = t.Elem()
    }
    f, _ := t.FieldByName("Bar")
    fmt.Println(f.Tag)
}

Then you'll get the same tag (try it on the Go Playground):

&{baz}
custom:"tag"
{baz2}
custom:"tag"

You get the same result if you keep the reflect.Value wrapping the struct pointer, and unwrap from it:

newFooPtr := reflect.New(fooType)
newFoo := newFooPtr.Elem()
newFoo.FieldByName("Bar").SetString("baz2")
fmt.Println(newFoo)
readTag(newFooPtr.Interface()) // empty

Then readTag() doesn't need to be modified. Try this version on the Go Playground.


问:
Speech recognition, batch processing, speech analytics, 404 [No such child resource]
I use the following url to access IBM's speech recognition batch processing via curl:

"https://api.us-east.speech-to-text.watson.cloud.ibm.com/v1/batches?function=recognize&timestamps=true&audio_metrics=true&model=en-US_NarrowbandModel&speech_analytics=true"

The files are in a COS bucket at us-geo.  I get the following response:

{
      "error": "No such child resource.",
      "code": 404,
      "code_description": "No Such Resource"
}

Any suggestions as to what resource is being referred to?

Thanks in advance for any guidance.

Cheers, Scott

答:
The API signature that you are attempting to use matches the speech to text : customer care API, that according to the documentation at

https://cloud.ibm.com/apidocs/speech-to-text/speech-to-text-icp

The Speech to Text: Customer Care service is an on-premise solution
  that is available only on IBM Cloud Private.

If that doesn't match your usage then the API you are attempting will not work.

If on the other hand it does match your usage then you need to submit a multi-part form with information locating the COS bucket holding your audio files.

EG.

```<code>curl -X POST -u "apikey:{apikey}" --header "Content-Type: multipart/form-data" --form input_credentials_file=@my_cos_credentials.json --form input_bucket_location=us-geo --form input_bucket_name=my_cos_input_bucket --form output_credentials_file=@my_cos_credentials.json --form output_bucket_location=us-geo --form output_bucket_name=my_cos_output_bucket "https://{icp_cluster_host}{:port}/speech-to-text/api/v1/batches?function=recognize&speech_analytics=true"
</code>```

Body:
The API signature that you are attempting to use matches the speech to text : customer care API, that according to the documentation at

https://cloud.ibm.com/apidocs/speech-to-text/speech-to-text-icp

The Speech to Text: Customer Care service is an on-premise solution
  that is available only on IBM Cloud Private.

If that doesn't match your usage then the API you are attempting will not work.

If on the other hand it does match your usage then you need to submit a multi-part form with information locating the COS bucket holding your audio files.

EG.

curl -X POST -u "apikey:{apikey}" --header "Content-Type: multipart/form-data" --form input_credentials_file=@my_cos_credentials.json --form input_bucket_location=us-geo --form input_bucket_name=my_cos_input_bucket --form output_credentials_file=@my_cos_credentials.json --form output_bucket_location=us-geo --form output_bucket_name=my_cos_output_bucket "https://{icp_cluster_host}{:port}/speech-to-text/api/v1/batches?function=recognize&speech_analytics=true"


问:
Renders LaTeX code in UILabel/UITextfield natively on iOS
I want to render LaTeX in my application. I have tried iOSMath and iOSLatex.

The problem is iOS Math does not support latex with text while iOS Latex renders latex on a WkWebview and the takes screenshot of it and return an image.

Do we have a native renderer for LaTeX (on iOS)?

I am trying to render

Solve this equation (\left{\begin{matrix} 3x + 2y - 11 = 0 \ 2x + 3y - 9 = 0 \end{matrix}\right.)

答:
You can use KatexMathe View

you can download this library

```<code>//MARK:- IBOutlet

@IBOutlet weak var webViewQuestion: KatexMathView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.webViewQuestion.loadLatex("your string")
}

extension ReadQuestionVC : WKNavigationDelegate {

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
       self.webViewQuestionHC.constant = 10 //Default constant height
       self.setContaintSizeWebView(webView: webViewQuestion, constantSize: self.webViewQuestionHC)

}

func setContaintSizeWebView(webView:WKWebView,constantSize:NSLayoutConstraint){
    webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
        if complete != nil {
            webView.evaluateJavaScript("Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight)", completionHandler: { (height, error) in
                constantSize.constant = height as! CGFloat
                webView.sizeToFit()
                self.view.layoutIfNeeded()
            })
        }

    })
}
}
</code>```

Body:
You can use KatexMathe View

you can download this library

//MARK:- IBOutlet

@IBOutlet weak var webViewQuestion: KatexMathView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.webViewQuestion.loadLatex("your string")
}

extension ReadQuestionVC : WKNavigationDelegate {

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
       self.webViewQuestionHC.constant = 10 //Default constant height
       self.setContaintSizeWebView(webView: webViewQuestion, constantSize: self.webViewQuestionHC)

}

func setContaintSizeWebView(webView:WKWebView,constantSize:NSLayoutConstraint){
    webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
        if complete != nil {
            webView.evaluateJavaScript("Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight)", completionHandler: { (height, error) in
                constantSize.constant = height as! CGFloat
                webView.sizeToFit()
                self.view.layoutIfNeeded()
            })
        }

    })
}
}


问:
Power Bi DAX: Divide Value and set it for each week
I have a target value of 20 for January but it is 20 for the month, i need to show this over each week. I have to divide the target by 4 if there are 4 weeks in a month and by 5 if there are 5 weeks in a month. It is as simple as that, i am using a line and clustered column chart to display my data, i need the target spread out into each week of the month. I also need another field to do this but im sure i can replicate your formula and make it applicable.

I have added a WeeksinMonth column that counts how many weeks are in a particular month e.g January has 5 weeks and February has 4 weeks. I need an IF statement that will divide the target and value by how many weeks in a month. e.g if month has 5 weeks then divide target and value by 5, if month has 4 weeks divide target and value by 4.

I have a calendar table with week values which i can used to put the divided target into and also the desired output i made in excel (See attached).

How will i go about this?

Desired Output

Calendar Table

答:
enter code hereYou can create an extra column in your calendar table:

```<code>WeekMax =
var stOfMonth = Weeks[Start of Week].[Month]
var stOfYear = Weeks[Start of Week].[year]
return CALCULATE(max(Weeks[Weekinmonth]);FILTER(Weeks;Weeks[Start of Week].[Month] = stOfMonth && Weeks[Start of Week].[Year] = stOfYear))
</code>```

Make sure you have a relation in your model between calendar and target date. Now you can use this number for that week/date to divide by.

You can now add an extra column in your target table:

```<code>WeeklyTarget = Targets[Target]/Related(Calendar[WeekMax])
</code>```

Body:
enter code hereYou can create an extra column in your calendar table:

WeekMax =
var stOfMonth = Weeks[Start of Week].[Month]
var stOfYear = Weeks[Start of Week].[year]
return CALCULATE(max(Weeks[Weekinmonth]);FILTER(Weeks;Weeks[Start of Week].[Month] = stOfMonth && Weeks[Start of Week].[Year] = stOfYear))

Make sure you have a relation in your model between calendar and target date. Now you can use this number for that week/date to divide by.

You can now add an extra column in your target table:

WeeklyTarget = Targets[Target]/Related(Calendar[WeekMax])


问:
Highmaps caribbean map
I am trying to display points(lat/long) with highmaps. I have successfully done that for US because there is a finished map for that.
Now I am trying to display points in the caribbean. I found the following link to create a map for the caribbean: Demo

The problem is with this option I can only set values for the whole country. But I need to set specific points in the different countries with values. Example is California Map.

I tried to update the sample code to:

```<code>import mapDataUSWithoutCentral from "@highcharts/map-collection/custom/north-america-no-central.geo.json"

    var dataCaribbean = [{
    'hc-key': 'cu', //Cuba
    value: 0
},{
    'hc-key': 'bs', //Bahamas
    value: 0
},{
  'hc-key': 'tc', //Turks and Caicos Islands
  value: 0
},{
  'hc-key': 'ky', //Cayman Islands
  value: 0
},{
  'hc-key': 'ht', //Haiti
  value: 0
},{
  'hc-key': 'do', //Dominican Republic
  value: 0
},{
  'hc-key': 'jm', //Jamaica
  value: 0
},{
  'hc-key': 'pr', //Puerto Rico
  value: 0
},
{ z: 10, keyword: "demo", lat: 23.113592, lon: -82.366592, color: '#ff0000' }
];

  const mapOptionsCaribbean = {
    chart: {
      map: mapDataUSWithoutCentral
    },
    title: {
      text: 'Caribbean'
    },
    mapNavigation: {
      enabled: true,
  },
    series: [{
      data: dataCaribbean,
      mapData: mapDataUSWithoutCentral,
      joinBy: 'hc-key',
      allAreas: false,
      name: 'Random data',
      states: {
          hover: {
              color: '#a4edba'
          }
      },
      dataLabels: {
          enabled: true,
          format: '{point.name}'
      }
  }]
  }
</code>```

But the result is only this:

The last point in the data array is not displayed.

答:
You need to create another series with mapbubble type and add proj4 library:

```<code>series: [...,
  {
    type: "mapbubble",
    data: [...]
  }
]
</code>```

Live demo: https://codesandbox.io/s/highcharts-react-demo-o5roi

API Reference: https://api.highcharts.com/highmaps/series.mapbubble.data

Title: Highmaps caribbean map

Body:
I am trying to display points(lat/long) with highmaps. I have successfully done that for US because there is a finished map for that.
Now I am trying to display points in the caribbean. I found the following link to create a map for the caribbean: Demo

The problem is with this option I can only set values for the whole country. But I need to set specific points in the different countries with values. Example is California Map.

I tried to update the sample code to:

import mapDataUSWithoutCentral from "@highcharts/map-collection/custom/north-america-no-central.geo.json"

    var dataCaribbean = [{
    'hc-key': 'cu', //Cuba
    value: 0
},{
    'hc-key': 'bs', //Bahamas
    value: 0
},{
  'hc-key': 'tc', //Turks and Caicos Islands
  value: 0
},{
  'hc-key': 'ky', //Cayman Islands
  value: 0
},{
  'hc-key': 'ht', //Haiti
  value: 0
},{
  'hc-key': 'do', //Dominican Republic
  value: 0
},{
  'hc-key': 'jm', //Jamaica
  value: 0
},{
  'hc-key': 'pr', //Puerto Rico
  value: 0
},
{ z: 10, keyword: "demo", lat: 23.113592, lon: -82.366592, color: '#ff0000' }
];

  const mapOptionsCaribbean = {
    chart: {
      map: mapDataUSWithoutCentral
    },
    title: {
      text: 'Caribbean'
    },
    mapNavigation: {
      enabled: true,
  },
    series: [{
      data: dataCaribbean,
      mapData: mapDataUSWithoutCentral,
      joinBy: 'hc-key',
      allAreas: false,
      name: 'Random data',
      states: {
          hover: {
              color: '#a4edba'
          }
      },
      dataLabels: {
          enabled: true,
          format: '{point.name}'
      }
  }]
  }

But the result is only this:

The last point in the data array is not displayed.

Body:
You need to create another series with mapbubble type and add proj4 library:

series: [...,
  {
    type: "mapbubble",
    data: [...]
  }
]

Live demo: https://codesandbox.io/s/highcharts-react-demo-o5roi

API Reference: https://api.highcharts.com/highmaps/series.mapbubble.data


问:
Google Sheets - Highlight cell if value exists in other sheet
I would like to highlight a cell if a value matches a cell in another sheet.

Proposed Solution

```<code>FOR EACH row in 'sheet1'

IF column C == TRUE
&& column D (value split by comma, only search values with 'tf' in) does not match any cell in 'sheet2'

Highlight the cell Red
</code>```

Example Value

CELL D9

"Platform,TF Platform,TF User"

Do not search "Platform" in sheet2

Search "TF Platform" in sheet2

Search "TF User" in sheet2

Example Sheet

https://docs.google.com/spreadsheets/d/1eI9FTVNuyMEzQTJnHzufz_gElE53AMmk-mxVEWKPdRk/edit?usp=sharing

答:
You can use MATCH function to search other sheets.

for example: =NOT(ISERROR(MATCH(D1,'SheetName'!C:C,0))) Search for D1 cell value in [SheetName] column C

Body:
I would like to highlight a cell if a value matches a cell in another sheet.

Proposed Solution

FOR EACH row in 'sheet1'

IF column C == TRUE
&& column D (value split by comma, only search values with 'tf' in) does not match any cell in 'sheet2'

Highlight the cell Red

Example Value

CELL D9

"Platform,TF Platform,TF User"

Do not search "Platform" in sheet2

Search "TF Platform" in sheet2

Search "TF User" in sheet2

Example Sheet

https://docs.google.com/spreadsheets/d/1eI9FTVNuyMEzQTJnHzufz_gElE53AMmk-mxVEWKPdRk/edit?usp=sharing


问:
Multiple IF Statements with Multiple COUNTIFS with Multiple criteria
I'm trying to make a cell display a text value depending on a multiple criteria COUNTIFS statement nested inside multiple IF statements, I have got the first IF(COUNTIFS statement working, but I want to nest another IF statement along with that so the cell can display different text values depending on multiple COUNTIFS, here is what I currently have:

```<code>IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   FORMULA!A10
),
IF(
   COUNTIFS(
      B6:B55, "AERO NOMAD",
      D6:D55, "",
      F6:F55, "O"
   ),
   FORMULA!A11,
   FORMULA!A10)
</code>```

I know this part works on its own:

```<code>IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   FORMULA!A10)
</code>```

But when I try and add another IF statement for the same cell it won't allow me; does anyone know a solution for this please?

答:
How to use if Statements

If statements are written as IF(query, when-true, when-false).

You can also nest if statements by using more if statements in the true or false arguments.

For example if you want an extra check being made if the condition is false, you can write IF(condition, if-true, IF(condition2, when-condition2-true, when-condition2-false)).

Answer

I think you want to nest the if statements.

The formula below might be what you're looking for.

```<code>IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   IF(
      COUNTIFS(
         B6:B55, "AERO NOMAD",
         D6:D55, "",
         F6:F55, "O"
      ),
      FORMULA!A11,
      FORMULA!A10)
   )
</code>```

It checks two conditions (1., 2. below), and the outputs are based on that.

Where Rows contain "AERONOMAD", "", "M" in columns B,D,F, this will show the text in FORMULA!A12.

Where Rows contain "AERO NOMAD", "", "O" in, this will show the text in FORMULA!A11.

If neither of the two conditions above are met then it will show FORMULA!A10.

NOTE:
Please note the spellings of AERONOMAD and AERO NOMAD. The second formula, as per your question, has a space. Is this intended?

Body:
I'm trying to make a cell display a text value depending on a multiple criteria COUNTIFS statement nested inside multiple IF statements, I have got the first IF(COUNTIFS statement working, but I want to nest another IF statement along with that so the cell can display different text values depending on multiple COUNTIFS, here is what I currently have:

IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   FORMULA!A10
),
IF(
   COUNTIFS(
      B6:B55, "AERO NOMAD",
      D6:D55, "",
      F6:F55, "O"
   ),
   FORMULA!A11,
   FORMULA!A10)

I know this part works on its own:

IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   FORMULA!A10)

But when I try and add another IF statement for the same cell it won't allow me; does anyone know a solution for this please?

Body:
How to use if Statements

If statements are written as IF(query, when-true, when-false).

You can also nest if statements by using more if statements in the true or false arguments.

For example if you want an extra check being made if the condition is false, you can write IF(condition, if-true, IF(condition2, when-condition2-true, when-condition2-false)).

Answer

I think you want to nest the if statements.

The formula below might be what you're looking for.

IF(
   COUNTIFS(
      B6:B55, "AERONOMAD",
      D6:D55, "",
      F6:F55, "M"
   ),
   FORMULA!A12,
   IF(
      COUNTIFS(
         B6:B55, "AERO NOMAD",
         D6:D55, "",
         F6:F55, "O"
      ),
      FORMULA!A11,
      FORMULA!A10)
   )

It checks two conditions (1., 2. below), and the outputs are based on that.

Where Rows contain "AERONOMAD", "", "M" in columns B,D,F, this will show the text in FORMULA!A12.

Where Rows contain "AERO NOMAD", "", "O" in, this will show the text in FORMULA!A11.

If neither of the two conditions above are met then it will show FORMULA!A10.

NOTE:
Please note the spellings of AERONOMAD and AERO NOMAD. The second formula, as per your question, has a space. Is this intended?


问:
Slim 4: Use a container to share DB connection with models and controllers without Eloquent
I am starting a PET project with SLIM 4 and I can't find a way to use the connection to the database within a Model. Even the controller works ok.

I have used a container to be able to move the connection between the different layers.

app.php

```<code><?php
use Slim\Factory\AppFactory;

require __DIR__ . '/../../vendor/autoload.php';

//set container
$aux_container = new \DI\Container();
AppFactory::setContainer($aux_container);

$app = AppFactory::create();

//get container to manage dependencies on the rest of app files
$container = $app->getContainer();
require __DIR__ . '/../App/routes.php';
require __DIR__ . '/../App/configs.php';
require __DIR__ . '/../App/dependencies.php';

$app->run();
</code>```

configs.php

```<code><?php

$container->set('db_settings',function(){
    return (object)[
        "DB_NAME" => "prohip_operations",
        "DB_USER" => "root",
        "DB_PASS" => "root",
        "DB_CHAR" => "utf8mb4",
        "DB_HOST" => "localhost",
        "DB_PORT" => "33066",
    ];
});
</code>```

dependencies.php

```<code><?php

use Psr\Container\ContainerInterface;

$container->set('db', function(ContainerInterface $c){

    $config = $c->get('db_settings');

    $host = $config->DB_HOST;
    $pass = $config->DB_PASS;
    $charset = $config->DB_CHAR;
    $user = $config->DB_USER;
    $dbname = $config->DB_NAME;
    $port = $config->DB_PORT;

    $opt = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
    ];

    $dsn = "mysql:host=".$host.";port=".$port.";dbname=".$dbname.";charset=".$charset.";";

    return new PDO($dsn, $user, $pass, $opt);
});
</code>```

/Models/BaseModel.php

```<code><?php

namespace App\Models;

use Psr\Container\ContainerInterface;

class BaseModel{

    protected $container;

    public function __construct(ContainerInterface $c){
        $this->container = $c;
    }
}
</code>```

/Models/ApplicantStatus.php

```<code><?php

namespace App\Models;

use App\Models\BaseModel;

class ApplicantStatus extends BaseModel{

    public function __construct($id)
    {
        if(isset($id)){
            $this->id = $id;
        }

    }

    public function getStatusName(){
        var_dump($this->container);
        //get container db
        $pdo = $this->container->get('db');
        $query = $pdo->query('SELECT description_spanish FROM applicant_status WHERE id='.$this->id);

        if($query->rowCount()>0){
            return $query;
        }
    }
}
</code>```

When make var_dump() of $ this-> container printa NULL, when in theory they threaten to initialize and extend it from BaseModel ...

This method ApplicantStatus-> getStatusName(); it's called inside a controller.

```<code>$status = new ApplicantStatus(11);
$status->getStatusName()
</code>```

Maybe this is where i do it wrong ...

Thank you

答:
SOLVED:

I miss the parent contructor declaration.

```<code>class ApplicantStatus extends BaseModel
{
    private $id;

    public function __construct(ContainerInterface $c, int $id = null)
    {
        parent::__construct($c);

        $this->id = $id
    }
...
}
</code>```

Body:
I am starting a PET project with SLIM 4 and I can't find a way to use the connection to the database within a Model. Even the controller works ok.

I have used a container to be able to move the connection between the different layers.

app.php

<?php
use Slim\Factory\AppFactory;

require __DIR__ . '/../../vendor/autoload.php';

//set container
$aux_container = new \DI\Container();
AppFactory::setContainer($aux_container);

$app = AppFactory::create();

//get container to manage dependencies on the rest of app files
$container = $app->getContainer();
require __DIR__ . '/../App/routes.php';
require __DIR__ . '/../App/configs.php';
require __DIR__ . '/../App/dependencies.php';

$app->run();

configs.php

<?php

$container->set('db_settings',function(){
    return (object)[
        "DB_NAME" => "prohip_operations",
        "DB_USER" => "root",
        "DB_PASS" => "root",
        "DB_CHAR" => "utf8mb4",
        "DB_HOST" => "localhost",
        "DB_PORT" => "33066",
    ];
});

dependencies.php

<?php

use Psr\Container\ContainerInterface;

$container->set('db', function(ContainerInterface $c){

    $config = $c->get('db_settings');

    $host = $config->DB_HOST;
    $pass = $config->DB_PASS;
    $charset = $config->DB_CHAR;
    $user = $config->DB_USER;
    $dbname = $config->DB_NAME;
    $port = $config->DB_PORT;

    $opt = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
    ];

    $dsn = "mysql:host=".$host.";port=".$port.";dbname=".$dbname.";charset=".$charset.";";

    return new PDO($dsn, $user, $pass, $opt);
});

/Models/BaseModel.php

<?php

namespace App\Models;

use Psr\Container\ContainerInterface;

class BaseModel{

    protected $container;

    public function __construct(ContainerInterface $c){
        $this->container = $c;
    }
}

/Models/ApplicantStatus.php

<?php

namespace App\Models;

use App\Models\BaseModel;

class ApplicantStatus extends BaseModel{

    public function __construct($id)
    {
        if(isset($id)){
            $this->id = $id;
        }

    }

    public function getStatusName(){
        var_dump($this->container);
        //get container db
        $pdo = $this->container->get('db');
        $query = $pdo->query('SELECT description_spanish FROM applicant_status WHERE id='.$this->id);

        if($query->rowCount()>0){
            return $query;
        }
    }
}

When make var_dump() of $ this-> container printa NULL, when in theory they threaten to initialize and extend it from BaseModel ...

This method ApplicantStatus-> getStatusName(); it's called inside a controller.

$status = new ApplicantStatus(11);
$status->getStatusName()

Maybe this is where i do it wrong ...

Thank you

Body:
SOLVED:

I miss the parent contructor declaration.

class ApplicantStatus extends BaseModel
{
    private $id;

    public function __construct(ContainerInterface $c, int $id = null)
    {
        parent::__construct($c);

        $this->id = $id
    }
...
}