问:
Upload binary file with retrofit 2 in Android
I want to upload a binary file to the server in Android. I test Api method by postman:

And it's OK, as you see there is another option which you can upload files as form data(key, value):

Every tutorials (like this one)describe how to upload files as multipart/form-data:

```<code> // create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
</code>```

I search a lot but couldn't find any way to upload file as binary with retrofit2.

There is just one Issue in retrofit repository which ask How can I POST a image binary in retrofit 2.0 beta?. I use its solution :

API Service:

```<code>@POST("trip/{tripId}/media/photos")
Call<MediaPost> postEventPhoto(
    @Path("eventId") int tripId,
    @Header("Authorization") String accessToken,
    @Query("direction") String direction,
    @Body RequestBody photo);
</code>```

Caller:

```<code>InputStream in = new FileInputStream(new File(media.getPath()));
byte[] buf;
buf = new byte[in.available()];
while (in.read(buf) != -1);
RequestBody requestBody = RequestBody
    .create(MediaType.parse("application/octet-stream"), buf);
Call<MediaPost> mediaPostCall = tripApiService.postTripPhoto(
    tripId,
    ((GlobalInfo) getApplicationContext()).getApiAccessToken(),
    direction,
    requestBody);
</code>```

But I got this error:

```<code>java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding.
</code>```

What's wrong with my code? what should I do?

答:
I had same problem, I wanted to upload binary file(image). The API was of Wordpress

I followed the solution code which is given at the end of this issue

Here is my little modified code

```<code>@POST("wp-json/wp/v2/media/")
Call<ImagePostResult> postEventPhoto(
        @Header("Authorization") String accessToken,
        @Header("Content-Type") String contentType,
        @Header("Content-Disposition") String contentDisposition,
        @Body RequestBody photo);
</code>```

Here is the request

```<code>        // For BasicAuth
        String authHeader = getAuthHeader();

        String contentType = "application/binary";
        String contentDisposition = "attachment; filename =  " + fileName;

        RequestBody requestBodyee = null;
        try {
            InputStream in = new FileInputStream(file);

            byte[] buf;
            buf = new byte[in.available()];
            while (in.read(buf) != -1) ;
            requestBodyee = RequestBody
                    .create(MediaType.parse("application/octet-stream"), buf);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Call<ImagePostResult> imagePostResultCall = apiInterface.postEventPhoto(
                authHeader,
                contentType,
                contentDisposition,
                requestBodyee);
        imagePostResultCall.enqueue(new Callback<ImagePostResult>() {
            @Override
            public void onResponse(Call<ImagePostResult> call, Response<ImagePostResult> response) {
                // Response Success
                if (response.isSuccessful()) {
                  // yaay
                }
            }

            @Override
            public void onFailure(Call<ImagePostResult> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t);
            }
        });
</code>```

Body:
I want to upload a binary file to the server in Android. I test Api method by postman:

And it's OK, as you see there is another option which you can upload files as form data(key, value):

Every tutorials (like this one)describe how to upload files as multipart/form-data:

 // create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

I search a lot but couldn't find any way to upload file as binary with retrofit2.

There is just one Issue in retrofit repository which ask How can I POST a image binary in retrofit 2.0 beta?. I use its solution :

API Service:

@POST("trip/{tripId}/media/photos")
Call<MediaPost> postEventPhoto(
    @Path("eventId") int tripId,
    @Header("Authorization") String accessToken,
    @Query("direction") String direction,
    @Body RequestBody photo);

Caller:

InputStream in = new FileInputStream(new File(media.getPath()));
byte[] buf;
buf = new byte[in.available()];
while (in.read(buf) != -1);
RequestBody requestBody = RequestBody
    .create(MediaType.parse("application/octet-stream"), buf);
Call<MediaPost> mediaPostCall = tripApiService.postTripPhoto(
    tripId,
    ((GlobalInfo) getApplicationContext()).getApiAccessToken(),
    direction,
    requestBody);

But I got this error:

java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding.

What's wrong with my code? what should I do?

Body:
I had same problem, I wanted to upload binary file(image). The API was of Wordpress

I followed the solution code which is given at the end of this issue

Here is my little modified code

@POST("wp-json/wp/v2/media/")
Call<ImagePostResult> postEventPhoto(
        @Header("Authorization") String accessToken,
        @Header("Content-Type") String contentType,
        @Header("Content-Disposition") String contentDisposition,
        @Body RequestBody photo);

Here is the request

        // For BasicAuth
        String authHeader = getAuthHeader();

        String contentType = "application/binary";
        String contentDisposition = "attachment; filename =  " + fileName;

        RequestBody requestBodyee = null;
        try {
            InputStream in = new FileInputStream(file);

            byte[] buf;
            buf = new byte[in.available()];
            while (in.read(buf) != -1) ;
            requestBodyee = RequestBody
                    .create(MediaType.parse("application/octet-stream"), buf);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Call<ImagePostResult> imagePostResultCall = apiInterface.postEventPhoto(
                authHeader,
                contentType,
                contentDisposition,
                requestBodyee);
        imagePostResultCall.enqueue(new Callback<ImagePostResult>() {
            @Override
            public void onResponse(Call<ImagePostResult> call, Response<ImagePostResult> response) {
                // Response Success
                if (response.isSuccessful()) {
                  // yaay
                }
            }

            @Override
            public void onFailure(Call<ImagePostResult> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t);
            }
        });


来源: stackexchange

问:
How to make react-hook-form work with multiple forms in one page?
I am using react-hook-form in my project and I have 2 totally separate forms, but when I submit one of the forms and if some fields in the other form is required I can't submit the current form, check the demo, and try to submit one of the form, the forms should work independently of each other but it looks like they depend on each other.</p>

答:
You are using the same hook instance for both forms. You will have to reuse with different names.

import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

function App() {
  const {
    register,
    formState: { errors },
    handleSubmit,
  } = useForm({
    mode: "onBlur",
  });

  const {
    register: register2,
    formState: { errors: errors2 },
    handleSubmit: handleSubmit2,
  } = useForm({
    mode: "onBlur",
  });

  const onSubmit = (data) => {
    alert(JSON.stringify(data));
  };

  const onSubmitEmail = (data) => {
    alert(JSON.stringify(data));
  };

  return (

      <form key={1} onSubmit={handleSubmit(onSubmit)}>

          First Name
          <input
            name="firstName"
            placeholder="bill"
            ref={register({ required: true })}
          />
          {errors.firstName &&
This is required
}

          Last Name
          <input
            name="lastName"
            placeholder="luo"
            ref={register({ required: true })}
          />
          {errors.lastName &&
This is required
}

        <input type="submit" />
      </form>

      <form key={2} onSubmit={handleSubmit2(onSubmitEmail)}>

            Email

          <input name="email" ref={register2({ required: true })} />
          {errors2.email &&
This is required
}

        <input type="submit" />
      </form>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
```

ContentLicense: CC BY-SA 4.0

Body:
You are using the same hook instance for both forms. You will have to reuse with different names.

import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

function App() {
  const {
    register,
    formState: { errors },
    handleSubmit,
  } = useForm({
    mode: "onBlur",
  });

  const {
    register: register2,
    formState: { errors: errors2 },
    handleSubmit: handleSubmit2,
  } = useForm({
    mode: "onBlur",
  });

  const onSubmit = (data) => {
    alert(JSON.stringify(data));
  };

  const onSubmitEmail = (data) => {
    alert(JSON.stringify(data));
  };

  return (
    <div className="App">
      <form key={1} onSubmit={handleSubmit(onSubmit)}>
        <div>
          <label htmlFor="firstName">First Name</label>
          <input
            name="firstName"
            placeholder="bill"
            ref={register({ required: true })}
          />
          {errors.firstName && <p>This is required</p>}
        </div>

        <div>
          <label htmlFor="lastName">Last Name</label>
          <input
            name="lastName"
            placeholder="luo"
            ref={register({ required: true })}
          />
          {errors.lastName && <p>This is required</p>}
        </div>
        <input type="submit" />
      </form>

      <form key={2} onSubmit={handleSubmit2(onSubmitEmail)}>
        <div>
          <label htmlFor="email" placeholder="bluebill1049@hotmail.com">
            Email
          </label>
          <input name="email" ref={register2({ required: true })} />
          {errors2.email && <p>This is required</p>}
        </div>
        <input type="submit" />
      </form>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


问:
Get Latin Character in C++
I am a rookie with C++. I have a string "tỏa" but I can't get the character 'ỏ' and why the length of that string is 5? How can I get that character as a variable?

```<code>void test() {
    std::string str ("tỏa");
    for(int i=0; i<str.length(); ++i){
        std::cout << str[i] << std::endl;
    }
}
</code>```

And the output of that code is:

```<code>t
�
�
�
a
</code>```

Anyone can help me? Thank in advance.

答:
Use a combination of setlocale() and wstring:

Link to live sample

```<code>#include <clocale>
#include <iostream>

void test() {
    std::wstring str = L"tỏa";
    for(int i=0; i<str.length(); ++i){
        std::wcout << str[i] << std::endl;
    }
    std::wcout << "Size: " << str.size(); //the size of the string is 3 as it should
}

int main()
{
    setlocale(LC_ALL, "");
    test();
    return 0;
}
</code>```

EDIT:

If you want to save the wide char in a variable it's as simple as:

```<code>wchar_t ch = str[1];
</code>```

You can also use the ASCII code:

```<code>wchar_t ch = 7887;
</code>```

Note:
This may not work in all compilers in all SO's, 100% portability is not guaranteed.

Title: Get Latin Character in C++

Body:
I am a rookie with C++. I have a string "tỏa" but I can't get the character 'ỏ' and why the length of that string is 5? How can I get that character as a variable?

void test() {
    std::string str ("tỏa");
    for(int i=0; i<str.length(); ++i){
        std::cout << str[i] << std::endl;
    }
}

And the output of that code is:

t
�
�
�
a

Anyone can help me? Thank in advance.

Body:
Use a combination of setlocale() and wstring:

Link to live sample

#include <clocale>
#include <iostream>

void test() {
    std::wstring str = L"tỏa";
    for(int i=0; i<str.length(); ++i){
        std::wcout << str[i] << std::endl;
    }
    std::wcout << "Size: " << str.size(); //the size of the string is 3 as it should
}

int main()
{
    setlocale(LC_ALL, "");
    test();
    return 0;
}

EDIT:

If you want to save the wide char in a variable it's as simple as:

wchar_t ch = str[1];

You can also use the ASCII code:

wchar_t ch = 7887;

Note:
This may not work in all compilers in all SO's, 100% portability is not guaranteed.


问:
Convert mySQL query to KNEX
I am converting series of queries to Knex syntax.
I am having problem with this query:

```<code>SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
FROM store_failure_log
WHERE reviewed = 0
AND create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW();
</code>```

More precisely this line:

```<code>SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
</code>```

I have this Knex in place:

```<code>knex('store_failure_log')
        .select('id', 'reviewed', 'log_reference', 'CONVERT(notification USING utf8)', 'create_time', 'update_time', 'store', 'user_id').convert('notification USING utf8')
        .where('reviewed', 0)
        .where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))
</code>```

that produces this sql query:

```<code>select `id`, `reviewed`, `log_reference`, `CONVERT(notification USING utf8)`, `create_time`, `update_time`, `store`, `user_id` from `store_failure_log` where `reviewed` = 0 and create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()
</code>```

Problem is in the: Convert(notification USING utf8).

The query is not valid, since the Convert is in parentheses. How can I write it with the knex?

In general how do I include SQL function calls in the KNEX syntax?

答:
You can use raw to include SQL function calls in your Knex query, like you've already done in your where:

```<code>knex('store_failure_log')
        .select(knex.raw('id, reviewed, log_reference, CONVERT(notification USING utf8), create_time, update_time, store, user_id'))
        .where('reviewed', 0)
        .where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))
</code>```

Title: Convert mySQL query to KNEX

Body:
I am converting series of queries to Knex syntax.
I am having problem with this query:

SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
FROM store_failure_log
WHERE reviewed = 0
AND create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW();

More precisely this line:

SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id

I have this Knex in place:

knex('store_failure_log')
        .select('id', 'reviewed', 'log_reference', 'CONVERT(notification USING utf8)', 'create_time', 'update_time', 'store', 'user_id').convert('notification USING utf8')
        .where('reviewed', 0)
        .where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))

that produces this sql query:

select `id`, `reviewed`, `log_reference`, `CONVERT(notification USING utf8)`, `create_time`, `update_time`, `store`, `user_id` from `store_failure_log` where `reviewed` = 0 and create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()

Problem is in the: Convert(notification USING utf8).

The query is not valid, since the Convert is in parentheses. How can I write it with the knex?

In general how do I include SQL function calls in the KNEX syntax?

Body:
You can use raw to include SQL function calls in your Knex query, like you've already done in your where:

knex('store_failure_log')
        .select(knex.raw('id, reviewed, log_reference, CONVERT(notification USING utf8), create_time, update_time, store, user_id'))
        .where('reviewed', 0)
        .where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))


问:
How to login using SSO oauth 2.0 and then storing token to run all other API from postman automation script?
I am not able to automate postman script for this procedure:

Open postman then in authorization tab select type->OAuth 2.0, Add authorization data->Request Headers and Access token->Get Access Token
Filled fields-Token Name, Grant Type->Authorization Code, Callback URL, Auth Url, Acess Token Url, client Id, Scope, State, Client Authentication->Send as basic Auth header
then when request Token a pop up window opens for SSO
enter image description here

Then Manage Acess tokens pop up appears, then select Use Token button at the bottom, then running api url which now contain token in the Header tab->temperory headers.
How to automate this procedure with storing token in environment variables,then running rest of the API's with it.

答:
I tried to access access_token from oauth 2.0 login by using Express and puppeteer.

```<code>var express = require('express');
const puppeteer = require('puppeteer');
var app = express();
app.get('/', function(req, res) {
    run().then(() => console.log('Done')).catch(error => console.log(error));
    async function run(){
        const browser = await puppeteer.launch({headless: false});
        const page = await browser.newPage();
        await page.goto('https://abcd.com/authorize?
audience=https://abcd.com&scope=openid%20email%20profile&client_id=abcd&response_type=token&redirect_uri=https://abcd.com/callback');
await new Promise(resolve => setTimeout(resolve, 5000));
    await page.focus('#email');
    await page.keyboard.type('abcd@gmail.com');
    await page.focus('#password');
    await page.keyboard.type('efghi');
    const waitForLoad = new Promise(resolve => page.on('load', () => resolve()));
    await page.evaluate(() => {
        document.querySelector('span[class="label"]').click();
    });
    await waitForLoad;
    console.log('Waiting to be redirected to the client.');
    const clientUrl = await page.evaluate(() => window.location.href);
        //1st the split is from when it encounters = in the url
    var split1 = clientUrl.split('=');
    //2nd split is when it encounters & in the 2nd object of the array
    var split2 = split1[1].split('&');
    //taking array in an object and conversing it to json
    var obj = {
      access_token: split2[0]
    }
    await browser.close();
    res.send(obj);
  };
});
app.listen(8000, function(){
    console.log('Heard on 8000');
});
</code>```

This can be run on postman to run other api with the received access token.

Body:
I tried to access access_token from oauth 2.0 login by using Express and puppeteer.

var express = require('express');
const puppeteer = require('puppeteer');
var app = express();
app.get('/', function(req, res) {
    run().then(() => console.log('Done')).catch(error => console.log(error));
    async function run(){
        const browser = await puppeteer.launch({headless: false});
        const page = await browser.newPage();
        await page.goto('https://abcd.com/authorize?
audience=https://abcd.com&scope=openid%20email%20profile&client_id=abcd&response_type=token&redirect_uri=https://abcd.com/callback');
await new Promise(resolve => setTimeout(resolve, 5000));
    await page.focus('#email');
    await page.keyboard.type('abcd@gmail.com');
    await page.focus('#password');
    await page.keyboard.type('efghi');
    const waitForLoad = new Promise(resolve => page.on('load', () => resolve()));
    await page.evaluate(() => {
        document.querySelector('span[class="label"]').click();
    });
    await waitForLoad;
    console.log('Waiting to be redirected to the client.');
    const clientUrl = await page.evaluate(() => window.location.href);
        //1st the split is from when it encounters = in the url
    var split1 = clientUrl.split('=');
    //2nd split is when it encounters & in the 2nd object of the array
    var split2 = split1[1].split('&');
    //taking array in an object and conversing it to json
    var obj = {
      access_token: split2[0]
    }
    await browser.close();
    res.send(obj);
  };
});
app.listen(8000, function(){
    console.log('Heard on 8000');
});

This can be run on postman to run other api with the received access token.


问:
How can I set the text layout
I have a project and in this project I can add text, no problem so far. I want to write one under the other(Pic1) but it writes side by side (Pic2). How can I do that?

Maybe pictures can't open, I want to explain what I want with an example:

I want this:

```<code>lorem ipsum test text

lorem2 ipsum2 test2 text2

</code>```

Output this (All text in the same line):

```<code>lorem ipsum test tetx lorem2 ipsum test2 text2
</code>```

This is my input textbox

```<code>    <div class="row">
        <div class="col-md-12">
            <div class="Comment input-group">
                <input type="text" class="form-control" id="new_comment_text" placeholder="Yorum" aria-describedby="basic-addon2"/>
                <div class="input-group-append" >
                    <button class="comment btn btn-success btn-sm" type="button" onclick="doComment(this,'new_comment_clicked',-1,-1);"><span class="fas fa-paper-plane"></span> Ekle </button>
                </div>
            </div>
        </div>
    </div>
</code>```

This is my output area

```<code>@helper collapsePopUp(string id = "",int noteId=0 , string title = "Modal Title", bool showCloseButton = true)
{
    <div class="commentWrap noCommentBox" data-note-id=@noteId id="@id" name="@id" aria-labelledby="@(id+"_labelPopup")">
        <ul id="@(id+"_bodyPopup")">

        </ul>
    </div>
}
</code>```

答:
I solved the problem thank you. I added ;

white-space: pre-line

to the .CSS file. I was able to get the image I wanted.

Title: How can I set the text layout

Body:
I have a project and in this project I can add text, no problem so far. I want to write one under the other(Pic1) but it writes side by side (Pic2). How can I do that?

Maybe pictures can't open, I want to explain what I want with an example:

I want this:

lorem ipsum test text

lorem2 ipsum2 test2 text2

Output this (All text in the same line):

lorem ipsum test tetx lorem2 ipsum test2 text2

This is my input textbox

                <input type="text" class="form-control" id="new_comment_text" placeholder="Yorum" aria-describedby="basic-addon2"/>

                    <button class="comment btn btn-success btn-sm" type="button" onclick="doComment(this,'new_comment_clicked',-1,-1);"> Ekle </button>

This is my output area

@helper collapsePopUp(string id = "",int noteId=0 , string title = "Modal Title", bool showCloseButton = true)
{

}


问:
Theme crocal - link menu problem : still redirect to homepage
I try to search a solution but I have no answer. My links menu don't work at all. When I click on it, they redirect always to the homepage. Only when I'm logged as admin they works.

I tried to deactivate all my plugins, recreate a menu from scratch, another from the administration and change the permalinks but the problem still in. I took a look on .htaccess but it's the basic one, so it's not this.

Here the website : primmoconseil.fr .

Please help me for this :)

答:
I have a feeling you are not pointing menus to the right pages. When creating a menu, it is important you select the page you want it to point to.

Be sure to have added pages first. and when creating menus, be sure they are each pointing to the page you want to load.

this might help

https://www.wpbeginner.com/beginners-guide/how-to-add-navigation-menu-in-wordpress-beginners-guide/

If it does not, let me know so we figure it out!


问:
Django: how to modify form field order of bound form with one unbound field?
I have an update form with 4 fields to display

3 of them are related to a class to which the form is bound
the last field (country) is only for information and I would like that field to be display in first position
currently, it is displayed at the end of my form...

I tryed to use field_order but country field is ignored...

form.py

```<code>class ParametrageForm(forms.ModelForm):

    def __init__(self, request, *args, **kwargs):
        super(ParametrageForm, self).__init__(*args, **kwargs)
        self.request = request
        self.language = request.session.get('language')
        self.user = request.user.id # id de l'utilisateur
        self.user_pays = request.session.get('user_pays') # pays de l'utilisateur
        self.user_site_type = request.session.get('user_site_type')
        self.user_site = request.session.get('user_site')
        instance = Parametrage.objects.get(asp_par_cle = kwargs['instance'].asp_par_cle)

        SITE_CONCERNE = Site.option_list_sites(self.language)
        if self.language == 'en':
            country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng
        elif self.language == 'fr':
            country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_fra
        else:
            country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng

        self.fields["country"] = forms.CharField(label = _("Country"),widget=forms.TextInput,initial=country, disabled=True)
        self.fields["asp_par_loc"] = forms.ChoiceField(label = _("Site concerned by settings"), widget=forms.Select, choices=SITE_CONCERNE,)
        self.fields["asp_par_ale"] = forms.IntegerField(label = _("Stock alert value for this site"), widget=forms.TextInput,)
        self.fields["asp_par_con"] = forms.IntegerField(label = _("Stock confort value for this site"), widget=forms.TextInput,)

    class Meta:
        model = Parametrage
        fields = ('asp_par_loc','asp_par_ale','asp_par_con',)

    field_order = ['country','asp_par_loc','asp_par_ale','asp_par_con',]
</code>```

答:
I found how to solve my issue:

I defined 'country' field outside of the init
and then filed_order works

but doing that, I do not have access to my initial country value, set in init (country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng)

I must improve my Python understanding...

Body:
I have an update form with 4 fields to display

3 of them are related to a class to which the form is bound
the last field (country) is only for information and I would like that field to be display in first position
currently, it is displayed at the end of my form...

I tryed to use field_order but country field is ignored...

form.py

class ParametrageForm(forms.ModelForm):

    def __init__(self, request, *args, **kwargs):
        super(ParametrageForm, self).__init__(*args, **kwargs)
        self.request = request
        self.language = request.session.get('language')
        self.user = request.user.id # id de l'utilisateur
        self.user_pays = request.session.get('user_pays') # pays de l'utilisateur
        self.user_site_type = request.session.get('user_site_type')
        self.user_site = request.session.get('user_site')
        instance = Parametrage.objects.get(asp_par_cle = kwargs['instance'].asp_par_cle)

        SITE_CONCERNE = Site.option_list_sites(self.language)
        if self.language == 'en':
            country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng
        elif self.language == 'fr':
            country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_fra
        else:
            country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng

        self.fields["country"] = forms.CharField(label = _("Country"),widget=forms.TextInput,initial=country, disabled=True)
        self.fields["asp_par_loc"] = forms.ChoiceField(label = _("Site concerned by settings"), widget=forms.Select, choices=SITE_CONCERNE,)
        self.fields["asp_par_ale"] = forms.IntegerField(label = _("Stock alert value for this site"), widget=forms.TextInput,)
        self.fields["asp_par_con"] = forms.IntegerField(label = _("Stock confort value for this site"), widget=forms.TextInput,)

    class Meta:
        model = Parametrage
        fields = ('asp_par_loc','asp_par_ale','asp_par_con',)

    field_order = ['country','asp_par_loc','asp_par_ale','asp_par_con',]


问:
Date Format from Date in String to Date

Possible Duplicate:

String to Date in Different Format in Java

Hi,

I m receiving date as String data type in MM/dd/yyyy format and need to convert in data Datatype in format yyyy-MM-dd to store in DB.

答:
You can also do it like this

```<code>String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";

//Instance of the calender class in the utill package
Calendar cal = Calendar.getInstance();

//A class that was used to get the date time stamp
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
</code>```

To print out the time you say

```<code>System.out.println(sdf.format(cal.getTime()) );
</code>```

Cheers

Title: Date Format from Date in String to Date

Body:
You can also do it like this

String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";

//Instance of the calender class in the utill package
Calendar cal = Calendar.getInstance();

//A class that was used to get the date time stamp
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);

To print out the time you say

System.out.println(sdf.format(cal.getTime()) );

Cheers

ContentLicense: CC BY-SA 3.0


问:
Changing Screen brightness in 6.0 programmatically
I am working on an android application which changes the screen brightness programmatically. I have a set brightness method which works on 5.1.1,But when i run the application on 6.0,it gives an error and closes the application.
Please Help.

Following is my approach:

```<code> public void setBrightness(View view,int brightness){

    //Just a loop for checking whether the brightness changes
     if(brightness <46)
        brightness = 255;
    else if(brightness >150)
        brightness=45;
    ContentResolver cResolver = this.getApplicationContext().getContentResolver();
    Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);

}

public void setDisplay(View view)
{
    ContentResolver  cResolver = getContentResolver();

    Window window = getWindow();
    int brightness=0;
    try
    {        Settings.System.putInt(cResolver,Settings.System.SCREEN_BRIGHTNESS_MODE
                                   Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
                   brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
        System.out.println("Current Brightness level " + brightness);
    }
    catch (Exception e)
    {
                   Log.e("Error", "Cannot access system brightness");
        e.printStackTrace();
    }
    setBrightness(view,brightness);
}
</code>```

答:
Kotlin version。

```<code><uses-permission
    android:name="android.permission.WRITE_SETTINGS"
    tools:ignore="ProtectedPermissions" />
</code>```

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_test)
    if(isCanWriteSettings(this))
        setupLight(this,255)//0~255
    else
        requestCanWriteSettings(this)
}
/**
 *
 * @param context
 * @param light max 255
 */
fun setupLight(context: Context, light: Int) {
    try {
        val brightnessMode = Settings.System.getInt(
            context.contentResolver,
            Settings.System.SCREEN_BRIGHTNESS_MODE
        )
        if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
            Settings.System.putInt(
                context.contentResolver,
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
            )
        }
        Settings.System.putInt(
            context.contentResolver,
            Settings.System.SCREEN_BRIGHTNESS,
            light
        )
    } catch (e: Exception) {
        Log.e("setupLight","Exception $e")
    }
}

fun isCanWriteSettings(context: Context): Boolean {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(context)
}

fun requestCanWriteSettings(activity: Activity){
    if (isCanWriteSettings(context = activity))
        return //not need
    try {
        val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
        intent.data = Uri.parse("package:" + activity.packageName)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        activity.startActivityForResult(intent, 0)
    }catch (e: Exception){
        Log.e("requestCanWriteSettings","requestCanWriteSettings $e")
    }
}
</code>```

Body:
I am working on an android application which changes the screen brightness programmatically. I have a set brightness method which works on 5.1.1,But when i run the application on 6.0,it gives an error and closes the application.
Please Help.

Following is my approach:

 public void setBrightness(View view,int brightness){

    //Just a loop for checking whether the brightness changes
     if(brightness <46)
        brightness = 255;
    else if(brightness >150)
        brightness=45;
    ContentResolver cResolver = this.getApplicationContext().getContentResolver();
    Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);

}

public void setDisplay(View view)
{
    ContentResolver  cResolver = getContentResolver();

    Window window = getWindow();
    int brightness=0;
    try
    {        Settings.System.putInt(cResolver,Settings.System.SCREEN_BRIGHTNESS_MODE
                                   Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
                   brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
        System.out.println("Current Brightness level " + brightness);
    }
    catch (Exception e)
    {
                   Log.e("Error", "Cannot access system brightness");
        e.printStackTrace();
    }
    setBrightness(view,brightness);
}

Body:
Kotlin version。

<uses-permission
    android:name="android.permission.WRITE_SETTINGS"
    tools:ignore="ProtectedPermissions" />

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_test)
    if(isCanWriteSettings(this))
        setupLight(this,255)//0~255
    else
        requestCanWriteSettings(this)
}
/**
 *
 * @param context
 * @param light max 255
 */
fun setupLight(context: Context, light: Int) {
    try {
        val brightnessMode = Settings.System.getInt(
            context.contentResolver,
            Settings.System.SCREEN_BRIGHTNESS_MODE
        )
        if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
            Settings.System.putInt(
                context.contentResolver,
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
            )
        }
        Settings.System.putInt(
            context.contentResolver,
            Settings.System.SCREEN_BRIGHTNESS,
            light
        )
    } catch (e: Exception) {
        Log.e("setupLight","Exception $e")
    }
}

fun isCanWriteSettings(context: Context): Boolean {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(context)
}

fun requestCanWriteSettings(activity: Activity){
    if (isCanWriteSettings(context = activity))
        return //not need
    try {
        val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
        intent.data = Uri.parse("package:" + activity.packageName)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        activity.startActivityForResult(intent, 0)
    }catch (e: Exception){
        Log.e("requestCanWriteSettings","requestCanWriteSettings $e")
    }
}


答:
The character ỏ is a part of Extended Ascii (see https://theasciicode.com.ar/extended-ascii-code/letter-o-circumflex-accent-ascii-code-226.html).

If your console isn't able to recognize UTF-8, such characters (2+ bytes) will be represented with multiple boxes.

You might want to use std::wstring (http://www.cplusplus.com/reference/string/wstring/) to solve this problem.

Title: Get Latin Character in C++


问:
Count frequency of list of words in list of string in Python
I am trying to find the frequency of list of words in list.
I do not know to iterate over list of list and getting list of list output.
Here is the code:

vocab = ['another', 'create', 'different', 'example', 'sample', 'ten']

vocabdoc = [
    ['create', 'ten', 'different', 'different', 'sample'],
    ['create', 'ten', 'another', 'another', 'example', 'example', 'example']
]

output = []

for words in vocab:
    output = [item in vocab for item in vocabdoc].count(words)
    print(output)

```

<p>I am trying to get this result:</p>

<pre class="lang-py prettyprint-override"><code>output = [[0, 1, 2, 0, 1, 1],[2, 1, 0, 3, 0, 1]]
</code>```

答:
Try this solution. Try to do first without list-comprehesion in normal for loops, then go with list-compreheision</p>

```<code>output = []
for v in vocabdoc:
    output.append([v.count(x) for x in vocab])

print(output)
[[0, 1, 2, 0, 1, 1], [2, 1, 0, 3, 0, 1]]
</code>```

Body:
I am trying to find the frequency of list of words in list.
I do not know to iterate over list of list and getting list of list output.
Here is the code:

vocab = ['another', 'create', 'different', 'example', 'sample', 'ten']

vocabdoc = [
    ['create', 'ten', 'different', 'different', 'sample'],
    ['create', 'ten', 'another', 'another', 'example', 'example', 'example']
]

output = []

for words in vocab:
    output = [item in vocab for item in vocabdoc].count(words)
    print(output)

I am trying to get this result:

output = [[0, 1, 2, 0, 1, 1],[2, 1, 0, 3, 0, 1]]

Body:
Try this solution. Try to do first without list-comprehesion in normal for loops, then go with list-compreheision

output = []
for v in vocabdoc:
    output.append([v.count(x) for x in vocab])

print(output)
[[0, 1, 2, 0, 1, 1], [2, 1, 0, 3, 0, 1]]


问:
Null condition in derived column to switch to createdDate if UpdatedDate is NULL
I have a table employee which contains:

createdDate: creation date of an employee

updatedDate: update date if there is a modification on an employee

This is an example:

```<code>EmployeeId createdDate updatedDate
54         2013-07-10  NULL
245        2016-06-29  2016-07-03
</code>```

If the updatedDate is NULL, we will consider only the createdDate. I am using a derived column, how can I use the condition?

My query is like below:

```<code>SELECT IIF(ISNULL(updatedDate),createdDate , updatedDate)
FROM employee
</code>```

答:
In your derived column, the condition must be like below :</p>

```<code>ISNULL(UpdatedDate)  ? CreatedDate :  UpdatedDate
</code>```

Body:
I have a table employee which contains:

createdDate: creation date of an employee

updatedDate: update date if there is a modification on an employee

This is an example:

EmployeeId createdDate updatedDate
54         2013-07-10  NULL
245        2016-06-29  2016-07-03

If the updatedDate is NULL, we will consider only the createdDate. I am using a derived column, how can I use the condition?

My query is like below:

SELECT IIF(ISNULL(updatedDate),createdDate , updatedDate)
FROM employee

Body:
In your derived column, the condition must be like below :

ISNULL(UpdatedDate)  ? CreatedDate :  UpdatedDate


答:
I would just use coalesce(). It does exactly what you ask for, and it is standard SQL (unlike ISNULL(), which is somehow vendor specific):

```<code>select coalesce(updatedDate, createdDate) from employee
</code>```

Title: Null condition in derived column to switch to createdDate if UpdatedDate is NULL

Body:
I would just use coalesce(). It does exactly what you ask for, and it is standard SQL (unlike ISNULL(), which is somehow vendor specific):

select coalesce(updatedDate, createdDate) from employee


答:
ISNULL() will be appropriate :

```<code>SELECT ISNULL(updatedDate, createdDate)
FROM employee e;
</code>```

ISNULL() accepts two argument one is possible null values & other is replacement of null values.

Body:
ISNULL() will be appropriate :

SELECT ISNULL(updatedDate, createdDate)
FROM employee e;

ISNULL() accepts two argument one is possible null values & other is replacement of null values.


问:
How to create horizontal scrolling grid view in android?
I want to create a gridview (not recycler view) that can scroll horizontally. How do I do that?

The benefit is that you avoid adding recycler view from support library and minimize apk size.

答:
Answer 2 - also tested and working

Found a bit tricky answer but it works well, if carefully implemented.

It seems as simple as rotating the GridView by 90 degree and rotating the items inside GridView by -90 degree. But when doing this there are issues with layout sizing - explained below.

Even though GridView is rotated, the parent layout allocates space as per the dimensions of GridView without rotation. This will make GridView disappear.

WorkAround

Enclose GridView inside FrameLayout. Now set the dimension of FrameLayout according to the actual dimensions of horizontal GridView that you would like to see.

activity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/photoGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/photos"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />

            <TextView
                android:padding="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:fontFamily="sans-serif-medium"
                android:text="@string/all_photos"
                android:textColor="#2196F3"
                android:textSize="14sp" />
        </FrameLayout>
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/clgGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/collages"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />
        </FrameLayout>
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/cameraGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/camera"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />
        </FrameLayout>
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/drawingGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/drawing"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />
        </FrameLayout>
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/colorBgGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/color_backgrounds"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />
        </FrameLayout>
    </LinearLayout>
</ScrollView>
</code>```

Now in you Activity

```<code>int[] gridIds = new int[]{R.id.photoGrid, R.id.clgGrid, R.id.cameraGrid, R.id.drawingGrid, R.id.colorBgGrid};
GridView[] grids = new GridView[gridIds.length];

for(int i = 0; i<gridIds.length; i++) grids[i] = findViewById(gridIds[i]);
        ViewGroup.LayoutParams params = grids[photo].getLayoutParams();
        ViewGroup.MarginLayoutParams params1 = (ViewGroup.MarginLayoutParams) grids[photo].getLayoutParams();
        for(int i = 0; i<gridIds.length; i++) {
            grids[i].setRotation(-90);
            params.height = size.x;
            grids[i].setLayoutParams(params);
            params1.topMargin = -size.x/2 + imgSize - 15*dp;
            grids[i].setLayoutParams(params1);
            grids[i].setAdapter(new cAdapter(cursor, 0));
        }
</code>```

Now Inside you adapter

```<code>    public class holder {
        holder(View v){
            img = v.findViewById(R.id.img);
            txt = v.findViewById(R.id.txt);
        }
        ImageView img;
        TextView txt;
    }
    public class cAdapter extends CursorAdapter {

        cAdapter(Cursor c, int flags) {
            super(mContext, c, flags);
        }

        @Override
        public int getCount() {
            int c = super.getCount();
            return c < MAX_IMG ? c : MAX_IMG;
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.li_main, parent, false);
            v.setTag(new holder(v));
            return v;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            holder h = (holder) view.getTag();
            final String imgPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            int rotation = 90;
            try {
                ExifInterface ei = new ExifInterface(imgPath);
                int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                switch (orientation){
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        rotation += 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        rotation += 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        rotation += 270;
                        break;
                    case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                        h.img.setRotationX(180);
                        break;
                    case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                        h.img.setRotationY(180);
                        break;
                }
            } catch (IOException ignored) {}
            h.img.setRotation(rotation);
            Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(cr, cursor.getLong(0), MediaStore.Images.Thumbnails.MINI_KIND, null);
            h.img.setImageBitmap(getRoundedCornerBitmap(b, 6*dp));
            h.img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(mContext, ImageEditActivity.class).putExtra("path", imgPath));
                }
            });
        }
    }

</code>```

Body:
Answer 2 - also tested and working

Found a bit tricky answer but it works well, if carefully implemented.

It seems as simple as rotating the GridView by 90 degree and rotating the items inside GridView by -90 degree. But when doing this there are issues with layout sizing - explained below.

Even though GridView is rotated, the parent layout allocates space as per the dimensions of GridView without rotation. This will make GridView disappear.

WorkAround

Enclose GridView inside FrameLayout. Now set the dimension of FrameLayout according to the actual dimensions of horizontal GridView that you would like to see.

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/photoGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/photos"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />

            <TextView
                android:padding="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:fontFamily="sans-serif-medium"
                android:text="@string/all_photos"
                android:textColor="#2196F3"
                android:textSize="14sp" />
        </FrameLayout>
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/clgGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/collages"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />
        </FrameLayout>
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/cameraGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/camera"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />
        </FrameLayout>
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/drawingGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/drawing"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />
        </FrameLayout>
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="180dp">

            <GridView android:id="@+id/colorBgGrid"
                android:listSelector="@android:color/transparent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <TextView
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:clickable="true"
                android:singleLine="true"
                android:text="@string/color_backgrounds"
                android:textColor="#000000"
                android:textSize="16sp"
                android:focusable="true" />
        </FrameLayout>
    </LinearLayout>
</ScrollView>

Now in you Activity

int[] gridIds = new int[]{R.id.photoGrid, R.id.clgGrid, R.id.cameraGrid, R.id.drawingGrid, R.id.colorBgGrid};
GridView[] grids = new GridView[gridIds.length];

for(int i = 0; i<gridIds.length; i++) grids[i] = findViewById(gridIds[i]);
        ViewGroup.LayoutParams params = grids[photo].getLayoutParams();
        ViewGroup.MarginLayoutParams params1 = (ViewGroup.MarginLayoutParams) grids[photo].getLayoutParams();
        for(int i = 0; i<gridIds.length; i++) {
            grids[i].setRotation(-90);
            params.height = size.x;
            grids[i].setLayoutParams(params);
            params1.topMargin = -size.x/2 + imgSize - 15*dp;
            grids[i].setLayoutParams(params1);
            grids[i].setAdapter(new cAdapter(cursor, 0));
        }

Now Inside you adapter

    public class holder {
        holder(View v){
            img = v.findViewById(R.id.img);
            txt = v.findViewById(R.id.txt);
        }
        ImageView img;
        TextView txt;
    }
    public class cAdapter extends CursorAdapter {

        cAdapter(Cursor c, int flags) {
            super(mContext, c, flags);
        }

        @Override
        public int getCount() {
            int c = super.getCount();
            return c < MAX_IMG ? c : MAX_IMG;
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.li_main, parent, false);
            v.setTag(new holder(v));
            return v;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            holder h = (holder) view.getTag();
            final String imgPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            int rotation = 90;
            try {
                ExifInterface ei = new ExifInterface(imgPath);
                int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                switch (orientation){
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        rotation += 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        rotation += 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        rotation += 270;
                        break;
                    case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                        h.img.setRotationX(180);
                        break;
                    case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                        h.img.setRotationY(180);
                        break;
                }
            } catch (IOException ignored) {}
            h.img.setRotation(rotation);
            Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(cr, cursor.getLong(0), MediaStore.Images.Thumbnails.MINI_KIND, null);
            h.img.setImageBitmap(getRoundedCornerBitmap(b, 6*dp));
            h.img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(mContext, ImageEditActivity.class).putExtra("path", imgPath));
                }
            });
        }
    }


问:
Is there a risk that Apple will not accept me as an applied iPhone Developer (with paid membership)?
What does it mean that I have to "apply"? Can day say: "No, we don't like your nose. Do something else!"? Did they do that in the past?

I've been investing now two full months worth about 20.000 USD on learning for iPhone programming, and I didn't apply yet...

答: I've never heard of them rejecting an application for developer license. But I've heard plenty of stories of them rejecting code. That's the much larger risk with Apple's stranglehold on the iPhone marketplace. </p>

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Stephen Pape

OwnerDisplayName: jcollum


问:
Ambiguity between Haskell Num class and my show-like class
I'm trying to declare my own data with appropriate conversion as class. My code looks like this:

```<code>data SomeData =  SInteger Integer | SElse deriving Show

class Some a where
    toSome :: a -> SomeData

instance Some Int where toSome = SInteger . toInteger

main :: IO ()
main = print $ toSome 3
</code>```

But GHC (7.0.3) becomes angry and says:

```<code>Ambiguous type variable `a0' in the constraints:
      (Some a0) arising from a use of `toSome'
                at minimal_broken.hs:11:16-21
      (Num a0) arising from the literal `3' at minimal_broken.hs:11:23
    Probable fix: add a type signature that fixes these type variable(s)
</code>```

Explicit type signature (like 3::Int) fixes the issue, but it's very inconvenient.

Standard "Show" works just fine, and according to the manual it's declared exactly the same way.

Why standard Show works, but my class doesn't? Did I miss something?

P.S.: Explicit "default (Int)" does not resolve this.

答: The reason something like show 3 works in the first place is due to the defaulting rule which picks a particular type when there is an ambiguity involving the Num class.  The reason it doesn't work with your Some class is that the rule says that all classes involved have to be standard classes (i.e., from the Prelude etc.).  This latter part of the rule is somewhat silly in opinion.

Body:
I'm trying to declare my own data with appropriate conversion as class. My code looks like this:

data SomeData =  SInteger Integer | SElse deriving Show

class Some a where
    toSome :: a -> SomeData

instance Some Int where toSome = SInteger . toInteger

main :: IO ()
main = print $ toSome 3

But GHC (7.0.3) becomes angry and says:

Ambiguous type variable `a0' in the constraints:
      (Some a0) arising from a use of `toSome'
                at minimal_broken.hs:11:16-21
      (Num a0) arising from the literal `3' at minimal_broken.hs:11:23
    Probable fix: add a type signature that fixes these type variable(s)

Explicit type signature (like 3::Int) fixes the issue, but it's very inconvenient.

Standard "Show" works just fine, and according to the manual it's declared exactly the same way.

Why standard Show works, but my class doesn't? Did I miss something?

P.S.: Explicit "default (Int)" does not resolve this.


问:
Why Image is not showing on the server when uploaded with Retrofit Multipart?
I am uploading a image on the server with Retrofit Multipart.

When I send the request, it is creating an image along with the passed name and size.

But when I try to open that image in the browser it says image contains error.

Same case was happening when I tried to send a request with the postman. But I found that I am sending wrong parameters. So I changed Content-Type to application/binary and posted image under
Body-> binary and it worked.

So I am suspecting that I am not sending proper Content-Type through the app. But I checked and found nothing

From ApiInterface.java

```<code>@Multipart
@POST("wp-json/wp/v2/media/")
Call<ImagePostResult> uploadImage(@Header("Authorization") String authHeader,
                                  @Header("Content-Type") String contentType,
                                  @Header("Content-Disposition") String contentDisposition,
                                  @Part MultipartBody.Part file,
                                  @Part("description") RequestBody description);
</code>```

my request:

```<code>private void uploadIdentityProofImageToServer() {
    progressDialog.setMessage("Uploading identity proof");

    ApiInterface apiInterface = getApiInterfaceObj();

    // For BasicAuth
    String authHeader = getAuthHeader();

    //File creating from selected URL
    String imageLocalPath = orderDetailsArrayList.get(getAdapterPosition()).getCapturedPhotoPath();//encoded image
    Uri tempUri = orderDetailsArrayList.get(getAdapterPosition()).getTempUri();// uri of image

    File file = new File(imageLocalPath);

    // create RequestBody instance from file
    RequestBody requestBodyFile = RequestBody.create(MediaType.parse(mContext.getContentResolver().getType(tempUri)), file);

    String fileName = file.getName();
    MultipartBody.Part body = MultipartBody.Part.createFormData("picture", fileName, requestBodyFile);

    String descriptionString = "Sample description";
    RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);

    String contentType = "application/binary";
    String contentDisposition = "attachment; filename =  " + fileName;

    Call<ImagePostResult> resultCall = apiInterface.uploadImage(
            authHeader,
            contentType,
            contentDisposition,
            body,
            description);

    resultCall.enqueue(new Callback<ImagePostResult>() {
        @Override
        public void onResponse(Call<ImagePostResult> call, Response<ImagePostResult> response) {
            // Response Success
            if (response.isSuccessful()) {
                ImagePostResult imagePostResult = response.body();
                String raw = imagePostResult.getGuid().getRaw();

                updateThePathOfImage(raw);
            }
            Log.d(TAG, "onResponse: " + response.message());
        }

        @Override
        public void onFailure(Call<ImagePostResult> call, Throwable t) {
            Log.d(TAG, "onFailure: " + t);
            progressDialog.dismiss();
            Toast.makeText(mContext, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}
</code>```

Also if can you link any resources to upload image with binary format, it would be helpful.

答:
I found it

I followed the solution code which is given at the end of this issue

Here is my little modified code

```<code>@POST("wp-json/wp/v2/media/")
Call<ImagePostResult> postEventPhoto(
        @Header("Authorization") String accessToken,
        @Header("Content-Type") String contentType,
        @Header("Content-Disposition") String contentDisposition,
        @Body RequestBody photo);
</code>```

Here is the request

```<code>        // For BasicAuth
        String authHeader = getAuthHeader();

        String contentType = "application/binary";
        String contentDisposition = "attachment; filename =  " + fileName;

        RequestBody requestBodyee = null;
        try {
            InputStream in = new FileInputStream(file);

            byte[] buf;
            buf = new byte[in.available()];
            while (in.read(buf) != -1) ;
            requestBodyee = RequestBody
                    .create(MediaType.parse("application/octet-stream"), buf);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Call<ImagePostResult> imagePostResultCall = apiInterface.postEventPhoto(
                authHeader,
                contentType,
                contentDisposition,
                requestBodyee);
        imagePostResultCall.enqueue(new Callback<ImagePostResult>() {
            @Override
            public void onResponse(Call<ImagePostResult> call, Response<ImagePostResult> response) {
                // Response Success
                if (response.isSuccessful()) {
                  // yaay
                }
            }

            @Override
            public void onFailure(Call<ImagePostResult> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t);
            }
        });
</code>```

Body:
I am uploading a image on the server with Retrofit Multipart.

When I send the request, it is creating an image along with the passed name and size.

But when I try to open that image in the browser it says image contains error.

Same case was happening when I tried to send a request with the postman. But I found that I am sending wrong parameters. So I changed Content-Type to application/binary and posted image under
Body-> binary and it worked.

So I am suspecting that I am not sending proper Content-Type through the app. But I checked and found nothing

From ApiInterface.java

@Multipart
@POST("wp-json/wp/v2/media/")
Call<ImagePostResult> uploadImage(@Header("Authorization") String authHeader,
                                  @Header("Content-Type") String contentType,
                                  @Header("Content-Disposition") String contentDisposition,
                                  @Part MultipartBody.Part file,
                                  @Part("description") RequestBody description);

my request:

private void uploadIdentityProofImageToServer() {
    progressDialog.setMessage("Uploading identity proof");

    ApiInterface apiInterface = getApiInterfaceObj();

    // For BasicAuth
    String authHeader = getAuthHeader();

    //File creating from selected URL
    String imageLocalPath = orderDetailsArrayList.get(getAdapterPosition()).getCapturedPhotoPath();//encoded image
    Uri tempUri = orderDetailsArrayList.get(getAdapterPosition()).getTempUri();// uri of image

    File file = new File(imageLocalPath);

    // create RequestBody instance from file
    RequestBody requestBodyFile = RequestBody.create(MediaType.parse(mContext.getContentResolver().getType(tempUri)), file);

    String fileName = file.getName();
    MultipartBody.Part body = MultipartBody.Part.createFormData("picture", fileName, requestBodyFile);

    String descriptionString = "Sample description";
    RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);

    String contentType = "application/binary";
    String contentDisposition = "attachment; filename =  " + fileName;

    Call<ImagePostResult> resultCall = apiInterface.uploadImage(
            authHeader,
            contentType,
            contentDisposition,
            body,
            description);

    resultCall.enqueue(new Callback<ImagePostResult>() {
        @Override
        public void onResponse(Call<ImagePostResult> call, Response<ImagePostResult> response) {
            // Response Success
            if (response.isSuccessful()) {
                ImagePostResult imagePostResult = response.body();
                String raw = imagePostResult.getGuid().getRaw();

                updateThePathOfImage(raw);
            }
            Log.d(TAG, "onResponse: " + response.message());
        }

        @Override
        public void onFailure(Call<ImagePostResult> call, Throwable t) {
            Log.d(TAG, "onFailure: " + t);
            progressDialog.dismiss();
            Toast.makeText(mContext, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

Also if can you link any resources to upload image with binary format, it would be helpful.

Body:
I found it

I followed the solution code which is given at the end of this issue

Here is my little modified code

@POST("wp-json/wp/v2/media/")
Call<ImagePostResult> postEventPhoto(
        @Header("Authorization") String accessToken,
        @Header("Content-Type") String contentType,
        @Header("Content-Disposition") String contentDisposition,
        @Body RequestBody photo);

Here is the request

        // For BasicAuth
        String authHeader = getAuthHeader();

        String contentType = "application/binary";
        String contentDisposition = "attachment; filename =  " + fileName;

        RequestBody requestBodyee = null;
        try {
            InputStream in = new FileInputStream(file);

            byte[] buf;
            buf = new byte[in.available()];
            while (in.read(buf) != -1) ;
            requestBodyee = RequestBody
                    .create(MediaType.parse("application/octet-stream"), buf);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Call<ImagePostResult> imagePostResultCall = apiInterface.postEventPhoto(
                authHeader,
                contentType,
                contentDisposition,
                requestBodyee);
        imagePostResultCall.enqueue(new Callback<ImagePostResult>() {
            @Override
            public void onResponse(Call<ImagePostResult> call, Response<ImagePostResult> response) {
                // Response Success
                if (response.isSuccessful()) {
                  // yaay
                }
            }

            @Override
            public void onFailure(Call<ImagePostResult> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t);
            }
        });


问:
How to get the request original parameters before the .net convertion / binding?
I have a model which looks like this:

```<code>public class SignalModelEntity
{
    ...
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public BooleanValue ValueBoolean { get; set; }
}
</code>```

and a ValueBoolean class:

```<code>public class BooleanValue
{
    public bool? Value { get; set; }
    public string FormattedValue { get; set; }
}
</code>```

When sending a body with a json that looks like this:

```<code>...
"ValueBoolean": {
    "Value": 23,
    "FormattedValue": ""
}
</code>```

Lets say the user sent me a '23' as a value.

The binding/convertion gives me a value of "true" for the boolean value property inside the ValueBoolean class.

I want to recognize rather the user sent me a '1', 'true' so I can approve that the value is legal and true.

And if the user for example sent me a '23' so it's illegal and return a 'badRequest' error code.

So how can I get the original parameters that sent from the request?

My post method is as follows:

```<code>[Route("{patientId}")]
[HttpPost]
public IHttpActionResult Post(int patientId, [FromBody]SignalModelEntity signal)
</code>```

答:
You'll need to update your method definition as follows:

```<code>    [Route("{patientId}")]
    [HttpPost]
    public IHttpActionResult Post(int patientId, [FromBody]dynamic signal)
</code>```

You can access the original value as follows:

```<code>var originalValue = signal.Value.Value;
</code>```

You'll probably need to create your custom JsonConverter for converting this dynamic signal to SignalModelEntity object.

Body:
I have a model which looks like this:

public class SignalModelEntity
{
    ...
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public BooleanValue ValueBoolean { get; set; }
}

and a ValueBoolean class:

public class BooleanValue
{
    public bool? Value { get; set; }
    public string FormattedValue { get; set; }
}

When sending a body with a json that looks like this:

...
"ValueBoolean": {
    "Value": 23,
    "FormattedValue": ""
}

Lets say the user sent me a '23' as a value.

The binding/convertion gives me a value of "true" for the boolean value property inside the ValueBoolean class.

I want to recognize rather the user sent me a '1', 'true' so I can approve that the value is legal and true.

And if the user for example sent me a '23' so it's illegal and return a 'badRequest' error code.

So how can I get the original parameters that sent from the request?

My post method is as follows:

[Route("{patientId}")]
[HttpPost]
public IHttpActionResult Post(int patientId, [FromBody]SignalModelEntity signal)

Body:
You'll need to update your method definition as follows:

    [Route("{patientId}")]
    [HttpPost]
    public IHttpActionResult Post(int patientId, [FromBody]dynamic signal)

You can access the original value as follows:

var originalValue = signal.Value.Value;

You'll probably need to create your custom JsonConverter for converting this dynamic signal to SignalModelEntity object.


答:
Here I've created a GetDataForHour(dataArray, dateToCompare) function which might be the answer.
It filters the dataArray and returns only array entities having dates before the dateToCompare with the same minutes and seconds

https://stackblitz.com/edit/angular-rzzkfq

Title: how to display the data per hour ago in angular

Body:
here's the code:

data = [
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:20:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:12:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:13:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 12:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 11:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 07:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 01:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 01:30:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 01:20:01'
    },
]

expected output:

 data = [
        {
            'name' : 'sample'
            'date' : '2020-02-18 13:50:01'
        },
        {
            'name' : 'sample'
            'date' : '2020-02-18 12:50:01'
        },
        {
            'name' : 'sample'
            'date' : '2020-02-18 11:50:01'
        },
        {
            'name' : 'sample'
            'date' : '2020-02-18 07:50:01'
        },
    ]

what I want to do here is to display the data per hour.
the data will filter like this.

data = [
            {
                'name' : 'sample'
                'date' : '2020-02-18 13:50:01'
            },
            {
                'name' : 'sample'
                'date' : '2020-02-18 12:50:01'
            },
            {
                'name' : 'sample'
                'date' : '2020-02-18 11:50:01'
            },
            {
                'name' : 'sample'
                'date' : '2020-02-18 07:50:01'
            },
        ]

it will not get the other data not hour ago. if the data is last 30minutes it will not get/display. the data should be last hour ago, data should be per hour ago. it should be dynamic. because if there's a new data which is
date: 2020-02-18 14:00:01, then per hour ago:

2020-02-18 14:00:01,

2020-02-18 13:00:01,

2020-02-18 12:00:01, etc...

here's the code: https://stackblitz.com/edit/angular-dnbses?file=src/app/app.component.ts


问:
has error after add pagedList.Mvc package to my project
I wanted to add page number with a pagedList.MVC package into my razor view page so I added package and then it's my Controller:

```<code>        public ViewResult Index(string sortOrder, string currentFilter, string searchPathId, int? page)
    {
        ViewBag.CurrentSort = sortOrder;
        ViewBag.IdPercorsoSortParm = String.IsNullOrEmpty(sortOrder) ? "IdPercorso_desc" : "";
        if (searchPathId != null)
        {
            page = 1;
        }
        else
        {
            searchPathId = currentFilter;
        }

        ViewBag.CurrentFilter = searchPathId;

        var listPercorsiModel = from listObj in _context.PercorsiModel
                                                      orderby listObj.IdPercorso
                                                      select listObj;
        if (!String.IsNullOrEmpty(searchPathId))
        {
            //listPercorsiModel = listPercorsiModel.Where(s => s.IdPercorso == (System.Convert.ToInt32(searchPathId))).ToList();
        }

        switch (sortOrder)
        {
            case "IdPercorso_desc":
                listPercorsiModel = listPercorsiModel.OrderByDescending(s => s.IdPercorso);
                break;
                //case "Date":
                //    students = students.OrderBy(s => s.EnrollmentDate);
                //    break;
                //case "date_desc":
                //    students = students.OrderByDescending(s => s.EnrollmentDate);
                //    break;
        }
        int pageSize = 3;
        int pageNumber = (page ?? 1);
        //return View(students.ToPagedList(pageNumber, pageSize));
        return View(listPercorsiModel.ToPagedList(pageNumber, pageSize));
    }
</code>```

and then in my view after add this code i had error:

```<code>@Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
</code>```

my error:

答:
ok, want to inform that because I used .net core application had a problem and I found another package for paging number and its working perfect:

x.pagedlist.mvc.core

Body:
I wanted to add page number with a pagedList.MVC package into my razor view page so I added package and then it's my Controller:

        public ViewResult Index(string sortOrder, string currentFilter, string searchPathId, int? page)
    {
        ViewBag.CurrentSort = sortOrder;
        ViewBag.IdPercorsoSortParm = String.IsNullOrEmpty(sortOrder) ? "IdPercorso_desc" : "";
        if (searchPathId != null)
        {
            page = 1;
        }
        else
        {
            searchPathId = currentFilter;
        }

        ViewBag.CurrentFilter = searchPathId;

        var listPercorsiModel = from listObj in _context.PercorsiModel
                                                      orderby listObj.IdPercorso
                                                      select listObj;
        if (!String.IsNullOrEmpty(searchPathId))
        {
            //listPercorsiModel = listPercorsiModel.Where(s => s.IdPercorso == (System.Convert.ToInt32(searchPathId))).ToList();
        }

        switch (sortOrder)
        {
            case "IdPercorso_desc":
                listPercorsiModel = listPercorsiModel.OrderByDescending(s => s.IdPercorso);
                break;
                //case "Date":
                //    students = students.OrderBy(s => s.EnrollmentDate);
                //    break;
                //case "date_desc":
                //    students = students.OrderByDescending(s => s.EnrollmentDate);
                //    break;
        }
        int pageSize = 3;
        int pageNumber = (page ?? 1);
        //return View(students.ToPagedList(pageNumber, pageSize));
        return View(listPercorsiModel.ToPagedList(pageNumber, pageSize));
    }

and then in my view after add this code i had error:

@Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

my error:


问:
How to fold the commented code in vs code?
In Vscode, How to fold the commented/inactived code region?
Lua Code
lua code
or cpp Code
cpp code

They are unabled to fold the code which is commented or inactived. such as in visual studio
folded code

答:
Its a known bug.

https://github.com/microsoft/vscode-cpptools/issues/407

An alternative could be to encapsulate your unwanted code into a region.

```<code>#region Accessors
// Commented code
#endregion
</code>```

The alternative commenting mechanism

```<code>/*

// More code
// commented code youre not interested in

*/
</code>```

Here is an extension that has been made which attempts to solve the issue

https://github.com/reapler/vscode-cfold

Body:
Its a known bug.

https://github.com/microsoft/vscode-cpptools/issues/407

An alternative could be to encapsulate your unwanted code into a region.

#region Accessors
// Commented code
#endregion

The alternative commenting mechanism

/*

// More code
// commented code youre not interested in

*/

Here is an extension that has been made which attempts to solve the issue

https://github.com/reapler/vscode-cfold


问:
Undefined name problem in camera calibration
I am using the same code that is provided by the OpenCv tutorial, it was working few weeks ago, today I was trying to run it is says that gray name is not defined!! can some one find me the error?

```<code>import numpy as np
#import matplotlib.pyplot as plt
import cv2
import glob
import os

def draw(img, corners, imgpts):
    corner = tuple(corners[0].ravel())
    img = cv2.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 5)
    img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 5)
    img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 5)
    return img
 # termination criteria
 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
 # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
 objp = np.zeros((7*7,3), np.float32)
 objp[:,:2] = np.mgrid[0:7,0:7].T.reshape(-1,2)
 # Arrays to store object points and image points from all the images.
 objpoints = [] # 3d point in real world space
 imgpoints = [] # 2d points in image plane.
 img_dir = "C:\\Hungary\\Biblography\\Rotating Solitary Wave\\My Work\\Final Work\\Experiment1111  \\Camera Calibration\\Image Processing\\chess"
 data_path = os.path.join(img_dir,'*bmp')
 images = glob.glob(data_path)
 for fname in images:
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # Find the chess board corners
    ret, corners = cv2.findChessboardCorners(gray, (7,7),None)
    # If found, add object points, image points (after refining them)
    if ret == True:
       objpoints.append(objp)
       corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
       imgpoints.append(corners2)
       # Draw and display the corners
       img = cv2.drawChessboardCorners(img, (7,7), corners2,ret)
       cv2.imshow('img',img)
       cv2.waitKey(500)

 cv2.destroyAllWindows()

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape  [::-1],None,None)
print('Rotation Vector, or the Angles For Each Photo: ', rvecs, '\n')
R = cv2.Rodrigues(rvecs[0])
print('The Rotation Matrix is: ', R)
print('Translation Vector: ', tvecs, '\n')
print(mtx, '\n')
print('Distortion Coefficients ', dist, '\n')
img = cv2.imread('00000274.bmp')
h, w = img.shape[:2]
newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
print('Camera Matrix', newcameramtx, '\n')
# undistort
dst = cv2.undistort(img, mtx, dist)  #, None, newcameramtx)
p = np.ones_like(dst)
# crop the image
x,y,w,h = roi
dst = dst[y:y+h, x:x+w]
# undistort
mapx,mapy = cv2.initUndistortRectifyMap(mtx,dist,None,newcameramtx,(w,h),5)
dst = cv2.remap(img,mapx,mapy,cv2.INTER_LINEAR)
# crop the image
x,y,w,h = roi
dst = dst[y:y+h, x:x+w]
cv2.imwrite('calibresult.png',dst)
mean_error = 0
for i in range(len(objpoints)):
   imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
   error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2)
   mean_error += error
print("total error: ", mean_error/len(objpoints))
</code>```

If you read the opencv document you will find that I did little changes on the code and it was working but today it is raising this error about the gray name is not defined!

答: Check your path once, and see if images is an empty list. In that case, for loop will not be executed where the gray variable is defined.

Body:
I am using the same code that is provided by the OpenCv tutorial, it was working few weeks ago, today I was trying to run it is says that gray name is not defined!! can some one find me the error?

import numpy as np
#import matplotlib.pyplot as plt
import cv2
import glob
import os

def draw(img, corners, imgpts):
    corner = tuple(corners[0].ravel())
    img = cv2.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 5)
    img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 5)
    img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 5)
    return img
 # termination criteria
 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
 # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
 objp = np.zeros((7*7,3), np.float32)
 objp[:,:2] = np.mgrid[0:7,0:7].T.reshape(-1,2)
 # Arrays to store object points and image points from all the images.
 objpoints = [] # 3d point in real world space
 imgpoints = [] # 2d points in image plane.
 img_dir = "C:\\Hungary\\Biblography\\Rotating Solitary Wave\\My Work\\Final Work\\Experiment1111  \\Camera Calibration\\Image Processing\\chess"
 data_path = os.path.join(img_dir,'*bmp')
 images = glob.glob(data_path)
 for fname in images:
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # Find the chess board corners
    ret, corners = cv2.findChessboardCorners(gray, (7,7),None)
    # If found, add object points, image points (after refining them)
    if ret == True:
       objpoints.append(objp)
       corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
       imgpoints.append(corners2)
       # Draw and display the corners
       img = cv2.drawChessboardCorners(img, (7,7), corners2,ret)
       cv2.imshow('img',img)
       cv2.waitKey(500)

 cv2.destroyAllWindows()

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape  [::-1],None,None)
print('Rotation Vector, or the Angles For Each Photo: ', rvecs, '\n')
R = cv2.Rodrigues(rvecs[0])
print('The Rotation Matrix is: ', R)
print('Translation Vector: ', tvecs, '\n')
print(mtx, '\n')
print('Distortion Coefficients ', dist, '\n')
img = cv2.imread('00000274.bmp')
h, w = img.shape[:2]
newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
print('Camera Matrix', newcameramtx, '\n')
# undistort
dst = cv2.undistort(img, mtx, dist)  #, None, newcameramtx)
p = np.ones_like(dst)
# crop the image
x,y,w,h = roi
dst = dst[y:y+h, x:x+w]
# undistort
mapx,mapy = cv2.initUndistortRectifyMap(mtx,dist,None,newcameramtx,(w,h),5)
dst = cv2.remap(img,mapx,mapy,cv2.INTER_LINEAR)
# crop the image
x,y,w,h = roi
dst = dst[y:y+h, x:x+w]
cv2.imwrite('calibresult.png',dst)
mean_error = 0
for i in range(len(objpoints)):
   imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
   error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2)
   mean_error += error
print("total error: ", mean_error/len(objpoints))

If you read the opencv document you will find that I did little changes on the code and it was working but today it is raising this error about the gray name is not defined!


问:
Enums as key of a Map with DBref with spring data mongo
I am trying to save and retrieve documents mapped to a class into Mongodb using spring data mongodb with a map field.

Here is a simplified version of my objects in java :
An enum :

```<code>public enum MyEnum {
   VALUE1, VALUE2
}
</code>```

And an entity to be persisted :

```<code>public class Entity {

  @DBRef
  private Map<MyEnum, MySubEntity> mapField;

  public Entity(Map<MyEnum, MySubEntity> mapField){
      this.mapField = mapField;
  }
}
</code>```

I have a simple Repository to save entities and retrieve them. After a save, the document is correctly created in MongoDB.

The problem occur when I try to retrieve it. The object Entity is created and returned by the repository, but any attempt to access or use the mapField field will fail with the error : "java.lang.String cannot be cast to MyEnum"
When using java debugguer to spy on the retrieved Entity object, the mapField field seems to have String as keys as opposed to MyEnum.

I have tried unsuccesfully to register a custom converter for this type.

My question is : is there anything I can do to match my use case, or is my model just not supported by spring data mongodb and I should alter it?

Update :

The problem seems to be related to the use of @DBRef on the map. I have tried without it and the Entity is retrieved correctly. Not sure why this is...

答:
You are right. Keys in MongoDb should be String type. You can create converter to convert your keys to String type before adding to database.Using toString() method to your key could be a solution.

Here is a good explanation and probably the answer to your question .

Body:
I am trying to save and retrieve documents mapped to a class into Mongodb using spring data mongodb with a map field.

Here is a simplified version of my objects in java :
An enum :

public enum MyEnum {
   VALUE1, VALUE2
}

And an entity to be persisted :

public class Entity {

  @DBRef
  private Map<MyEnum, MySubEntity> mapField;

  public Entity(Map<MyEnum, MySubEntity> mapField){
      this.mapField = mapField;
  }
}

I have a simple Repository to save entities and retrieve them. After a save, the document is correctly created in MongoDB.

The problem occur when I try to retrieve it. The object Entity is created and returned by the repository, but any attempt to access or use the mapField field will fail with the error : "java.lang.String cannot be cast to MyEnum"
When using java debugguer to spy on the retrieved Entity object, the mapField field seems to have String as keys as opposed to MyEnum.

I have tried unsuccesfully to register a custom converter for this type.

My question is : is there anything I can do to match my use case, or is my model just not supported by spring data mongodb and I should alter it?

Update :

The problem seems to be related to the use of @DBRef on the map. I have tried without it and the Entity is retrieved correctly. Not sure why this is...


问:
How to Register Local Spring cloud task project jar file to spring cloud data flow dashboard
I am trying to register my local spring cloud task jar file into spring cloud task data flow graphical interface. While registering the application local path is not getting identified and Register button is not getting enabled. My jar file location is C:\STS-WORK_SPACE\SPRING-BATCH\SCDFBatch\target\SCDFBatch-0.0.1-SNAPSHOT.jar and path I provided in the Dashboard is file:///C:/STS-WORK_SPACE/SPRING-BATCH/SCDFBatch/target/SCDFBatch-0.0.1-SNAPSHOT.jar. Please correct me if I am wrong here. I need someones help here.

答:
This question is a bit old, but here's how you can do that with SCDF 2.4.0:

Get the docker-compose from here: https://dataflow.spring.io/docs/installation/local/docker/

Customize it to mount your local .m2 folder, as described here: https://dataflow.spring.io/docs/installation/local/docker-customize/ in the section Maven Local Repository Mounting

Start Docker Compose

Then when SCDF is up, you need to register your artifact, e.g.

If you have a Maven project, do a mvn clean install for it, and in your .m2 folder you should have the artifacts (jar and pom). So verify that it's there first, before registering it.


问:
Install Python with cmd or powershell
My question is if you can install python with powershell, cmd, vbs or any other language built into Windows already?
If this was already asked please redirect me to the answer.
"How to install Python using Windows Command Prompt" explains how to install the python if you already have the exe installed, not how to install the exe.

EDIT: I am trying to install python with a file on a pc that does not have python installed, only thing restricted might be that the account does not an administrator and if possible in the background.

答:
You can not install it without administrator privileges. It would be lack of security I guess. What you can use in pipelines for instance is:

```<code>$url = "https://www.python.org/ftp/python/3.7.6/python-3.7.6-amd64.exe"
$output = "C:/tmp/python-3.7.6-amd64.exe"

if (Test-Path $output) {
    Write-Host "Script exists - skipping installation"
    return;
}

New-Item -ItemType Directory -Force -Path C:/tmp

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri $url -OutFile $output

& $output /passive InstallAllUsers=1 PrependPath=1 Include_test=0
</code>```

But still, Admin rights are required

Title: Install Python with cmd or powershell

Body:
You can not install it without administrator privileges. It would be lack of security I guess. What you can use in pipelines for instance is:

$url = "https://www.python.org/ftp/python/3.7.6/python-3.7.6-amd64.exe"
$output = "C:/tmp/python-3.7.6-amd64.exe"

if (Test-Path $output) {
    Write-Host "Script exists - skipping installation"
    return;
}

New-Item -ItemType Directory -Force -Path C:/tmp

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri $url -OutFile $output

& $output /passive InstallAllUsers=1 PrependPath=1 Include_test=0

But still, Admin rights are required