问:
Column mode select in JTextArea?
Is there a way to implement a "column mode" select in a JTextArea, in the way many modern editors does (i.e. Alt + mouse select in Notepad++)?

I did a search around and couldn't find anything similar. Probably I didn't use the right key words....

答:
I'm happy to say I got time (only two years after!!) to put together a successfully working class taking the code from Maneesh Godbole from coderanch pointed by @AxelH and also the code from Stanislav Lapitsky in http://java-sl.com . Thankyou very much!!

Hope it's useful :)

public class ColumnTextArea extends javax.swing.JTextArea{

    private static final long serialVersionUID = 1L;

    public ColumnTextArea(int rows, int columns){
        super(rows, columns);
        this.setCaret(new ColumnTextArea.ColumnSelectionCaret());

        //Disable ALT key presses when the textarea is focused
        this.getInputMap(javax.swing.JComponent.WHEN_FOCUSED).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ALT, 0, true), "ALTKEY");
        this.getActionMap().put("ALTKEY", new javax.swing.AbstractAction() {
            private static final long serialVersionUID = 1L;
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                System.out.println("Performed");
            }
        });
    }

    @Override
    public java.lang.String getSelectedText(){
        javax.swing.text.Highlighter.Highlight[] selections = this.getHighlighter().getHighlights();
        String text = "";
        int cnt = selections.length;
        if(cnt == 0){
            text = super.getSelectedText();
        }else{
            for (int i=0; i<cnt; i++) {
                int start = selections[i].getStartOffset();
                int end = selections[i].getEndOffset();
                java.lang.String selectedText = "";
                try {
                    selectedText = this.getDocument().getText(start,end-start);
                } catch (javax.swing.text.BadLocationException e) {
                    e.printStackTrace();
                }
                if(i == 0){
                    text = selectedText;
                }else{
                    text += '\n' + selectedText;
                }
            }
        }
        return(text);
    }

    @Override
    public void copy(){
        java.awt.datatransfer.StringSelection ss = new java.awt.datatransfer.StringSelection(this.getSelectedText());
        java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,ss);
    }

    class ColumnSelectionCaret extends javax.swing.text.DefaultCaret {
        private static final long serialVersionUID = 1L;
        java.awt.Point lastPoint = new java.awt.Point(0,0);
        boolean altDown = false;
        boolean moving = false;

        @Override
        public void mouseMoved(java.awt.event.MouseEvent e) {
            super.mouseMoved(e);
        }

        @Override
        public void mouseClicked(java.awt.event.MouseEvent e) {
            super.mouseClicked(e);
            if(e.getClickCount()==1){
                this.getComponent().getHighlighter().removeAllHighlights();
            }
        }

        @Override
        public void mousePressed(java.awt.event.MouseEvent e){
            super.mousePressed(e);
            this.lastPoint = new java.awt.Point(e.getX(),e.getY());
            this.altDown = e.isAltDown();
        }

        @Override
        protected void moveCaret(java.awt.event.MouseEvent e) {
            if(!this.moving){
                this.getComponent().getHighlighter().removeAllHighlights();
                this.moving = true;
            }
            if(this.altDown){
                java.awt.Point pt = new java.awt.Point(e.getX(), e.getY());
                javax.swing.text.Position.Bias[] biasRet = new javax.swing.text.Position.Bias[1];
                int pos = getComponent().getUI().viewToModel(getComponent(), pt, biasRet);
                if(biasRet[0] == null)
                    biasRet[0] = javax.swing.text.Position.Bias.Forward;
                if (pos >= 0) {
                    this.setDot(pos);
                    java.awt.Point start = new java.awt.Point(Math.min(this.lastPoint.x,pt.x), Math.min(this.lastPoint.y,pt.y));
                    java.awt.Point end = new java.awt.Point(Math.max(this.lastPoint.x,pt.x), Math.max(this.lastPoint.y,pt.y));
                    this.customHighlight(start,end);
                }
            }else{
                super.moveCaret(e);
            }
        }
        @Override
        public void mouseReleased(java.awt.event.MouseEvent e){
            this.moving = false;
            super.mouseReleased(e);
        }

        protected void customHighlight(java.awt.Point start, java.awt.Point end) {
            javax.swing.text.JTextComponent comp = this.getComponent();

            comp.getHighlighter().removeAllHighlights();
            int y = start.y;
            int firstX = start.x;
            int lastX = end.x;

            int pos1 = comp.getUI().viewToModel(comp, new java.awt.Point(firstX,y));
            int pos2 = comp.getUI().viewToModel(comp, new java.awt.Point(lastX,y));
            try {
                comp.getHighlighter().addHighlight(pos1, pos2, this.getSelectionPainter());
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
            y++;
            while (y<end.y) {
                int pos1new = comp.getUI().viewToModel(comp, new java.awt.Point(firstX,y));
                int pos2new = comp.getUI().viewToModel(comp, new java.awt.Point(lastX,y));
                if (pos1!=pos1new)  {
                    pos1=pos1new;
                    pos2=pos2new;
                    try {
                        comp.getHighlighter().addHighlight(pos1, pos2, this.getSelectionPainter());
                    }
                    catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                y++;
            }
        }
    }
}
```

Title: Column mode select in JTextArea?


来源: stackexchange

问:
Recoding specific column values using reference list
My dataframe looks like this

```<code>data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))
</code>```

And I have a reference list that looks like this -

```<code>ref=list(Male=1,Female=2)
</code>```

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

```<code>do.call(dplyr::recode, c(list(data), ref))
</code>```

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated

答:
An option would be do a left_join after stacking the 'ref' list to a two column data.frame

```<code>library(dplyr)
left_join(data, stack(ref), by = c('Gender' = 'ind')) %>%
    select(ID, Gender = values)
</code>```

A base R approach would be

```<code>unname(unlist(ref)[as.character(data$Gender)])
#[1] 1 2 2 2 1 2 1 1 2 2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My dataframe looks like this

data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))

And I have a reference list that looks like this -

ref=list(Male=1,Female=2)

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

do.call(dplyr::recode, c(list(data), ref))

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated

Body:
An option would be do a left_join after stacking the 'ref' list to a two column data.frame

library(dplyr)
left_join(data, stack(ref), by = c('Gender' = 'ind')) %>%
    select(ID, Gender = values)

A base R approach would be

unname(unlist(ref)[as.character(data$Gender)])
#[1] 1 2 2 2 1 2 1 1 2 2


问:
Print variable names when looping over a list
Consider the list of variables and a Python list:

```<code>apple='green'
banana='yellow'
orange='orange'

fruits = [apple, banana, orange]
</code>```

How to print the names of variables, instead of its values when lopping over the elements of the list?

```<code>for fruit in fruits:
    #print the names of variables, that is "apple", "banana", etc.
</code>```

I know that a dictionary would be a better fit in this problem but for the sake of argument, is it possible to do it with a list?

答:
use NamedObject, that should work:

```<code>apple='green'
banana='yellow'
orange='orange'
fruits = [apple, banana, orange]

apple = NamedObject('apple', apple)
print(apple)
print(apple.name)
</code>```

this should print:

```<code>green
apple
</code>```

If you dont understand, here is another similar thing: Access the name of a list in a Python print statement

Body:
Consider the list of variables and a Python list:

apple='green'
banana='yellow'
orange='orange'

fruits = [apple, banana, orange]

How to print the names of variables, instead of its values when lopping over the elements of the list?

for fruit in fruits:
    #print the names of variables, that is "apple", "banana", etc.

I know that a dictionary would be a better fit in this problem but for the sake of argument, is it possible to do it with a list?

Body:
use NamedObject, that should work:

apple='green'
banana='yellow'
orange='orange'
fruits = [apple, banana, orange]

apple = NamedObject('apple', apple)
print(apple)
print(apple.name)

this should print:

green
apple

If you dont understand, here is another similar thing: Access the name of a list in a Python print statement


问:
What are the often misunderstood concepts in Silverlight?
Silverlight 2.0 has been out for a little while now.  What are the concepts that you often see used incorrectly or think are misunderstood?</p>

答: I think its early days yet to have established a large enough set of instances of "usage" to determine those concepts which can be said to be "often" misunderstood.</p>

OwnerDisplayName: BenMaddox

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: AnthonyWJones


问:
How would you design an SOAP/REST API with collection as input parameters?
I am designing a wcf web-service that will support both REST and SOAP interfaces. As methods i am looking at supporting the following type of methods:

```<code>GetClientByID(int ID)
GetClientsByID(List<int> ID)

GetClientByEmail(string Email)
GetClientsByEmail(List<string> Email)
</code>```

I also will need to support 15-20 different queries like that above, having 4 separate per query means a lot of methods to support.

How would you design a API like this that needs to support the case above where I might want to ask for multiple objects in the same request and sometime just ask for a single one? And at the same time be SOAP/REST friendly? Or am I overcomplicating things?

Should i make all input Lists? instead of having a separate GetSingle method?

答:
And at the same time be SOAP/REST friendly?

I'd say WS-*/REST friendly. Nothing stops you from having SOAP as a resource format in your REST service.

Though i don't see the reason to have both WS-* and REST supported (but requirements are requirements...) you should have your core application independent of the 2 styles, then add a layer on top of it that would serve as an adapter. One adapter API for REST and one for WS-*

Body:
I am designing a wcf web-service that will support both REST and SOAP interfaces. As methods i am looking at supporting the following type of methods:

GetClientByID(int ID)
GetClientsByID(List<int> ID)

GetClientByEmail(string Email)
GetClientsByEmail(List<string> Email)

I also will need to support 15-20 different queries like that above, having 4 separate per query means a lot of methods to support.

How would you design a API like this that needs to support the case above where I might want to ask for multiple objects in the same request and sometime just ask for a single one? And at the same time be SOAP/REST friendly? Or am I overcomplicating things?

Should i make all input Lists? instead of having a separate GetSingle method?

ContentLicense: CC BY-SA 3.0


答:
You want this:</p>

```<code>apple = "green"
banana = "yellow"
orange = "orange"

fruits = [apple, banana, orange]
for fruit in fruits:
    fruit_name = [key for key, value in locals().items() if value == fruit]
    print(fruit_name[0])
</code>```

Title: Print variable names when looping over a list

Body:
You want this:

apple = "green"
banana = "yellow"
orange = "orange"

fruits = [apple, banana, orange]
for fruit in fruits:
    fruit_name = [key for key, value in locals().items() if value == fruit]
    print(fruit_name[0])


问:
CNAME entry not working on NameCheap using Amazon Certificate Manager
I am trying to set up a few SSL certificates in Amazon Certificate Manager, but I am trouble getting them verified after adding the CNAME in Namecheap.

Here is an example of the CNAME verification entries at Amazon Certificate Manager

Here is an example of another domains CNAME entry at Namecheap

If I put the entire value of the Name entry into Host at Namecheap, the verification fails. I also get an error on some long domains I have, as the Name entry exceeds 60 characters.

Can anyone assist with the correct parts needed to verify via DNS using Namecheap?

答:
Even though AWS includes it,  do not include the domain name itself in the CNAME Host field for Namecheap (they apparently append it for you);  just chop that off at the end. The value field is fine.

Give it half an hour.


问:
Can I create a generic @Query that detects which parameters from URL are not null and make a search only by them with Spring?
Am I able to create a generic @Query that detects which parameters from URL are not null and make a search only by them instead of creating a method for each parameters combination with Spring Framework?

For example: I have two parameters in my URL; I wanna make only one query that detects the not-null parameters from my URL and pass them to my query, ignoring the nulls (instead of creating a lot of if/else and different queries for different parameters combination).

I created this code which returns a list of countries based on the NOT-NULL parameters the user passed in the URL. Since I have 4 parameters, all the possibilities result in 16 different queries (as I also have a findAll method, that brings all the results when no parameter is defined), and it's boring to create them all the time.

My controller:

```<code>@RequestMapping(value = "/countries", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity listCountries(
        @RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "twoLetterCode", required = false) String twoLetterCode,
        @RequestParam(value = "threeLetterCode", required = false) String threeLetterCode,
        @RequestParam(value = "nameInPortuguese", required = false) String nameInPortuguese) {
    try {

        List<Country> countryList = null;

        @Autowired
        private CountryRepository countryRepository;

        if (name != null && !name.isEmpty() && !name.equals("")) {
            if (twoLetterCode != null && !twoLetterCode.isEmpty() && !twoLetterCode.equals("")) {
                if (threeLetterCode != null && !threeLetterCode.isEmpty() && !threeLetterCode.equals("")) {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameTwoLetterCodeThreeLetterCodeNameInPortuguese(name, twoLetterCode, threeLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByNameTwoLetterCodeThreeLetterCode(name, twoLetterCode, threeLetterCode);
                    }
                } else {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameTwoLetterCodeNameInPortuguese(name, twoLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByNameTwoLetterCode(name, twoLetterCode);
                    }
                }
            } else {
                if (threeLetterCode != null && !threeLetterCode.isEmpty() && !threeLetterCode.equals("")) {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameThreeLetterCodeNameInPortuguese(name, threeLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByNameThreeLetterCode(name, threeLetterCode);
                    }
                } else {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameNameInPortuguese(name, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByName(name);
                    }
                }
            }
        } else {
            if (twoLetterCode != null && !twoLetterCode.isEmpty() && !twoLetterCode.equals("")) {
                if (threeLetterCode != null && !threeLetterCode.isEmpty() && !threeLetterCode.equals("")) {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByTwoLetterCodeThreeLetterCodeNameInPortuguese(twoLetterCode, threeLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByTwoLetterCodeThreeLetterCode(twoLetterCode, threeLetterCode);
                    }
                } else {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByTwoLetterCodeNameInPortuguese(twoLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByTwoLetterCode(twoLetterCode);
                    }
                }
            } else {
                if (threeLetterCode != null && !threeLetterCode.isEmpty() && !threeLetterCode.equals("")) {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByThreeLetterCodeNameInPortuguese(threeLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByThreeLetterCode(threeLetterCode);
                    }
                } else {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameInPortuguese(nameInPortuguese);
                    } else {
                        countryList = countryRepository.findAll();
                    }
                }
            }
        }

        if (countryList != null && !countryList.isEmpty()) {
            List<CountryDTO> dtosList = modelMapper.map(countryList, new TypeToken<CountryDTO>() {}.getType());
            return ResponseEntity(dtosList, HttpStatus.OK);
        } else {
            return ResponseEntity.status(HttpStatus.OK).body(new EmptySerializableClass());
        }

    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

}
</code>```

My repository:

```<code>@Query("SELECT c FROM Country c WHERE c.name LIKE :name")
public List<Country> findByName(@Param("name") String name);

@Query("SELECT c FROM Country c WHERE c.twoLetterCode LIKE :twoLetterCode")
public List<Country> findByTwoLetterCode(@Param("twoLetterCode") String twoLetterCode);

@Query("SELECT c FROM Country c WHERE c.threeLetterCode LIKE :threeLetterCode")
public List<Country> findByThreeLetterCode(@Param("threeLetterCode") String threeLetterCode);

@Query("SELECT c FROM Country c WHERE c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByNameInPortuguese(@Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.twoLetterCode LIKE :twoLetterCode")
public List<Country> findByNameTwoLetterCode(@Param("name") String name, @Param("twoLetterCode") String twoLetterCode);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.threeLetterCode LIKE :threeLetterCode")
public List<Country> findByNameThreeLetterCode(@Param("name") String name, @Param("threeLetterCode") String threeLetterCode);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findBynameInPortuguese(@Param("name") String name, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.twoLetterCode LIKE :twoLetterCode AND c.threeLetterCode LIKE :threeLetterCode)")
public List<Country> findByTwoLetterCodeThreeLetterCode(@Param("twoLetterCode") String twoLetterCode, @Param("threeLetterCode") String threeLetterCode);

@Query("SELECT c FROM Country c WHERE c.twoLetterCode LIKE :twoLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByTwoLetterCodeNameInPortuguese(@Param("twoLetterCode") String twoLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.threeLetterCode LIKE :threeLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByThreeLetterCodeNameInPortuguese(@Param("threeLetterCode") String threeLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.twoLetterCode LIKE :twoLetterCode AND c.threeLetterCode LIKE :threeLetterCode)")
public List<Country> findByNameTwoLetterCodeThreeLetterCode(@Param("name") String name, @Param("twoLetterCode") String twoLetterCode, @Param("threeLetterCode") String threeLetterCode);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.twoLetterCode LIKE :twoLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByNameTwoLetterCodeNameInPortuguese(@Param("name") String name, @Param("twoLetterCode") String twoLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.threeLetterCode LIKE :threeLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByNameThreeLetterCodeNameInPortuguese(@Param("name") String name, @Param("threeLetterCode") String threeLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.twoLetterCode LIKE :twoLetterCode AND c.threeLetterCode LIKE :threeLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByTwoLetterCodeThreeLetterCodeNameInPortuguese(@Param("twoLetterCode") String twoLetterCode, @Param("threeLetterCode") String threeLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.twoLetterCode LIKE :twoLetterCode AND c.threeLetterCode LIKE :threeLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByNameTwoLetterCodeThreeLetterCodeNameInPortuguese(@Param("name") String name, @Param("twoLetterCode") String twoLetterCode, @Param("threeLetterCode") String threeLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c")
public List<Country> findAll();
</code>```

So, I guess you guys got it what my question is about. Instead of creating those millions if/else and thousands of queries for handling not-null parameters defined on the URL call, is there a way on Spring Framework - or even on JPA/Hibernate - to write only one query that detects those not-null parameters and search by them (and if all parameters are null, then just return all results)?

答:
thanks to everyone, but I could do it! It was simple like that:</p>

```<code>@Query("SELECT c FROM Country c WHERE (:name is null or c.name LIKE :name)"
+ " AND (:twoLetterCode is null or c.twoLetterCode LIKE :twoLetterCode)"
+ " AND (:threeLetterCode is null or c.threeLetterCode LIKE :threeLetterCode)"
+ " AND (:nameInPortuguese is null or c.nameInPortuguese LIKE :nameInPortuguese)")

public List<Country> findCountries(
@Param("name") String name,
@Param("twoLetterCode") String twoLetterCode,
@Param("threeLetterCode") String threeLetterCode,
@Param("nameInPortuguese") String nameInPortuguese);
</code>```

Body:
Am I able to create a generic @Query that detects which parameters from URL are not null and make a search only by them instead of creating a method for each parameters combination with Spring Framework?

For example: I have two parameters in my URL; I wanna make only one query that detects the not-null parameters from my URL and pass them to my query, ignoring the nulls (instead of creating a lot of if/else and different queries for different parameters combination).

I created this code which returns a list of countries based on the NOT-NULL parameters the user passed in the URL. Since I have 4 parameters, all the possibilities result in 16 different queries (as I also have a findAll method, that brings all the results when no parameter is defined), and it's boring to create them all the time.

My controller:

@RequestMapping(value = "/countries", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity listCountries(
        @RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "twoLetterCode", required = false) String twoLetterCode,
        @RequestParam(value = "threeLetterCode", required = false) String threeLetterCode,
        @RequestParam(value = "nameInPortuguese", required = false) String nameInPortuguese) {
    try {

        List<Country> countryList = null;

        @Autowired
        private CountryRepository countryRepository;

        if (name != null && !name.isEmpty() && !name.equals("")) {
            if (twoLetterCode != null && !twoLetterCode.isEmpty() && !twoLetterCode.equals("")) {
                if (threeLetterCode != null && !threeLetterCode.isEmpty() && !threeLetterCode.equals("")) {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameTwoLetterCodeThreeLetterCodeNameInPortuguese(name, twoLetterCode, threeLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByNameTwoLetterCodeThreeLetterCode(name, twoLetterCode, threeLetterCode);
                    }
                } else {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameTwoLetterCodeNameInPortuguese(name, twoLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByNameTwoLetterCode(name, twoLetterCode);
                    }
                }
            } else {
                if (threeLetterCode != null && !threeLetterCode.isEmpty() && !threeLetterCode.equals("")) {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameThreeLetterCodeNameInPortuguese(name, threeLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByNameThreeLetterCode(name, threeLetterCode);
                    }
                } else {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameNameInPortuguese(name, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByName(name);
                    }
                }
            }
        } else {
            if (twoLetterCode != null && !twoLetterCode.isEmpty() && !twoLetterCode.equals("")) {
                if (threeLetterCode != null && !threeLetterCode.isEmpty() && !threeLetterCode.equals("")) {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByTwoLetterCodeThreeLetterCodeNameInPortuguese(twoLetterCode, threeLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByTwoLetterCodeThreeLetterCode(twoLetterCode, threeLetterCode);
                    }
                } else {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByTwoLetterCodeNameInPortuguese(twoLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByTwoLetterCode(twoLetterCode);
                    }
                }
            } else {
                if (threeLetterCode != null && !threeLetterCode.isEmpty() && !threeLetterCode.equals("")) {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByThreeLetterCodeNameInPortuguese(threeLetterCode, nameInPortuguese);
                    } else {
                        countryList = countryRepository.findByThreeLetterCode(threeLetterCode);
                    }
                } else {
                    if (nameInPortuguese != null && !nameInPortuguese.isEmpty() && !nameInPortuguese.equals("")) {
                        countryList = countryRepository.findByNameInPortuguese(nameInPortuguese);
                    } else {
                        countryList = countryRepository.findAll();
                    }
                }
            }
        }

        if (countryList != null && !countryList.isEmpty()) {
            List<CountryDTO> dtosList = modelMapper.map(countryList, new TypeToken<CountryDTO>() {}.getType());
            return ResponseEntity(dtosList, HttpStatus.OK);
        } else {
            return ResponseEntity.status(HttpStatus.OK).body(new EmptySerializableClass());
        }

    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

}

My repository:

@Query("SELECT c FROM Country c WHERE c.name LIKE :name")
public List<Country> findByName(@Param("name") String name);

@Query("SELECT c FROM Country c WHERE c.twoLetterCode LIKE :twoLetterCode")
public List<Country> findByTwoLetterCode(@Param("twoLetterCode") String twoLetterCode);

@Query("SELECT c FROM Country c WHERE c.threeLetterCode LIKE :threeLetterCode")
public List<Country> findByThreeLetterCode(@Param("threeLetterCode") String threeLetterCode);

@Query("SELECT c FROM Country c WHERE c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByNameInPortuguese(@Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.twoLetterCode LIKE :twoLetterCode")
public List<Country> findByNameTwoLetterCode(@Param("name") String name, @Param("twoLetterCode") String twoLetterCode);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.threeLetterCode LIKE :threeLetterCode")
public List<Country> findByNameThreeLetterCode(@Param("name") String name, @Param("threeLetterCode") String threeLetterCode);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findBynameInPortuguese(@Param("name") String name, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.twoLetterCode LIKE :twoLetterCode AND c.threeLetterCode LIKE :threeLetterCode)")
public List<Country> findByTwoLetterCodeThreeLetterCode(@Param("twoLetterCode") String twoLetterCode, @Param("threeLetterCode") String threeLetterCode);

@Query("SELECT c FROM Country c WHERE c.twoLetterCode LIKE :twoLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByTwoLetterCodeNameInPortuguese(@Param("twoLetterCode") String twoLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.threeLetterCode LIKE :threeLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByThreeLetterCodeNameInPortuguese(@Param("threeLetterCode") String threeLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.twoLetterCode LIKE :twoLetterCode AND c.threeLetterCode LIKE :threeLetterCode)")
public List<Country> findByNameTwoLetterCodeThreeLetterCode(@Param("name") String name, @Param("twoLetterCode") String twoLetterCode, @Param("threeLetterCode") String threeLetterCode);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.twoLetterCode LIKE :twoLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByNameTwoLetterCodeNameInPortuguese(@Param("name") String name, @Param("twoLetterCode") String twoLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.threeLetterCode LIKE :threeLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByNameThreeLetterCodeNameInPortuguese(@Param("name") String name, @Param("threeLetterCode") String threeLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.twoLetterCode LIKE :twoLetterCode AND c.threeLetterCode LIKE :threeLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByTwoLetterCodeThreeLetterCodeNameInPortuguese(@Param("twoLetterCode") String twoLetterCode, @Param("threeLetterCode") String threeLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c WHERE c.name LIKE :name AND c.twoLetterCode LIKE :twoLetterCode AND c.threeLetterCode LIKE :threeLetterCode AND c.nameInPortuguese LIKE :nameInPortuguese")
public List<Country> findByNameTwoLetterCodeThreeLetterCodeNameInPortuguese(@Param("name") String name, @Param("twoLetterCode") String twoLetterCode, @Param("threeLetterCode") String threeLetterCode, @Param("nameInPortuguese") String nameInPortuguese);

@Query("SELECT c FROM Country c")
public List<Country> findAll();

So, I guess you guys got it what my question is about. Instead of creating those millions if/else and thousands of queries for handling not-null parameters defined on the URL call, is there a way on Spring Framework - or even on JPA/Hibernate - to write only one query that detects those not-null parameters and search by them (and if all parameters are null, then just return all results)?

Body:
thanks to everyone, but I could do it! It was simple like that:

@Query("SELECT c FROM Country c WHERE (:name is null or c.name LIKE :name)"
+ " AND (:twoLetterCode is null or c.twoLetterCode LIKE :twoLetterCode)"
+ " AND (:threeLetterCode is null or c.threeLetterCode LIKE :threeLetterCode)"
+ " AND (:nameInPortuguese is null or c.nameInPortuguese LIKE :nameInPortuguese)")

public List<Country> findCountries(
@Param("name") String name,
@Param("twoLetterCode") String twoLetterCode,
@Param("threeLetterCode") String threeLetterCode,
@Param("nameInPortuguese") String nameInPortuguese);


问:
how to send mail from .net?
I want to send email from my .net application. Please tell me the steps for sending email.</p>

答:
Start by exploring  System.Net.Mail.SmtpClient type in .net. This type offers overload method Send.

Look here

```<code>    public static void CreateTestMessage1(string server, int port)
    {
        string to = "jane@contoso.com";
        string from = "ben@contoso.com";
        string subject = "Using the new SMTP client.";
        string body = @"Using this new feature, you can send an e-mail message from an application very easily.";
        MailMessage message = new MailMessage(from, to, subject, body);
        SmtpClient client = new SmtpClient(server, port);
        // Credentials are necessary if the server requires the client
        // to authenticate before it will send e-mail on the client's behalf.
        client.Credentials = CredentialCache.DefaultNetworkCredentials;

        try
        {
            client.Send(message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught in CreateTestMessage1(): {0}",
                  ex.ToString());
        }
    }
</code>```

Title: how to send mail from .net?

Body:
Start by exploring  System.Net.Mail.SmtpClient type in .net. This type offers overload method Send.

Look here

    public static void CreateTestMessage1(string server, int port)
    {
        string to = "jane@contoso.com";
        string from = "ben@contoso.com";
        string subject = "Using the new SMTP client.";
        string body = @"Using this new feature, you can send an e-mail message from an application very easily.";
        MailMessage message = new MailMessage(from, to, subject, body);
        SmtpClient client = new SmtpClient(server, port);
        // Credentials are necessary if the server requires the client
        // to authenticate before it will send e-mail on the client's behalf.
        client.Credentials = CredentialCache.DefaultNetworkCredentials;

        try
        {
            client.Send(message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught in CreateTestMessage1(): {0}",
                  ex.ToString());
        }
    }


问:
How to implement a custom adapter with listview?
Hi I'm working with an android app when I need to parse an array in the list view. I have created a custom adapter for that but I'm missing something here.</p>

```<code>public class IndustryAdapter extends ArrayAdapter<Industry> {
    Context context;
    int resource;
    public IndustryAdapter(Context context, ArrayList<Industry> industries) {
        super(context, industries);
    }

    @Override
    public View getView(View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        }
        TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
        TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);

        return convertView;
    }

}

On the super(context, industries) is showing an error for industries:

required: 'int'
error: incompatible types: ArrayList<Industry> cannot be converted to int
</code>```

答:
Use base adapter for creating custom adapter for your list </p>

```<code>class CustomAdapter extends BaseAdapter {
   private ArrayList<Industry> industries;
    private Context context;

    public CustomAdapter(ArrayList<Industry> industries, Context context) {
        this.industries = industries;
        this.context = context;
    }

    @Override
    public int getCount() {
        return industries.size();
    }

    @Override
    public Object getItem(int position) {
        return industries.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.your_layout, parent, false);
        }
        TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
        TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);

        return convertView;
    }
}
</code>```

Body:
Hi I'm working with an android app when I need to parse an array in the list view. I have created a custom adapter for that but I'm missing something here.

public class IndustryAdapter extends ArrayAdapter<Industry> {
    Context context;
    int resource;
    public IndustryAdapter(Context context, ArrayList<Industry> industries) {
        super(context, industries);
    }

    @Override
    public View getView(View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        }
        TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
        TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);

        return convertView;
    }

}

On the super(context, industries) is showing an error for industries:

required: 'int'
error: incompatible types: ArrayList<Industry> cannot be converted to int

Body:
Use base adapter for creating custom adapter for your list

class CustomAdapter extends BaseAdapter {
   private ArrayList<Industry> industries;
    private Context context;

    public CustomAdapter(ArrayList<Industry> industries, Context context) {
        this.industries = industries;
        this.context = context;
    }

    @Override
    public int getCount() {
        return industries.size();
    }

    @Override
    public Object getItem(int position) {
        return industries.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.your_layout, parent, false);
        }
        TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
        TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);

        return convertView;
    }
}


问:
how to GET json query results from Windows command terminal
I have a json query that I am trying to pass through the command line

I have tried replacing outer single quotes with double quotes, but still shows me error

```<code>curl -XGET "http://localhost:9200/honda/_search?pretty" -H 'Content-Type:
application/json' -d “@{“query”:{"match":{"color":"silver"}}}”
</code>```

Expected: Documents that matches field:silver
Actual Error: Warning:
    Couldn't read data from file "", this makes an empty POST

```<code>THEN DISPLAYS MY ALL MY DOCUMENTS:

    {
    "_index" : "honda",
    "_type" : "_doc",
    "_id" : "234",
    "_score" : 1.0,
    "_source" : {
      "model" : "Accord EX",
      "price" : 28000,
      "color" : "red",
      "num_doors" : 4,
      "weight" : "9000lbs"
    }
  }.................................
curl: (6) Could not resolve host: application
{"query":{"match":{"color":"silver"}}}"
The filename, directory name, or volume label syntax is incorrect.
</code>```

答: Try escaping the characters for quotes.</p>

Body:
I have a json query that I am trying to pass through the command line

I have tried replacing outer single quotes with double quotes, but still shows me error

curl -XGET "http://localhost:9200/honda/_search?pretty" -H 'Content-Type:
application/json' -d “@{“query”:{"match":{"color":"silver"}}}”

Expected: Documents that matches field:silver
Actual Error: Warning:
    Couldn't read data from file "", this makes an empty POST

THEN DISPLAYS MY ALL MY DOCUMENTS:

    {
    "_index" : "honda",
    "_type" : "_doc",
    "_id" : "234",
    "_score" : 1.0,
    "_source" : {
      "model" : "Accord EX",
      "price" : 28000,
      "color" : "red",
      "num_doors" : 4,
      "weight" : "9000lbs"
    }
  }.................................
curl: (6) Could not resolve host: application
{"query":{"match":{"color":"silver"}}}"
The filename, directory name, or volume label syntax is incorrect.

Body: Try escaping the characters for quotes.


问:
Tab icon not visible in ionic 3
Inside ./pages/tabs/tabs.html

```<code><ion-tabs>
<ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
<ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-
circle"></ion-tab>
<ion-tab [root]="tab3Root" tabTitle="Settings" tabIcon="cog"></ion-
tab>
</ion-tabs>
</code>```

Inside ./pages/tabs/tabs.ts

```<code>import { Component } from '@angular/core';
import { AboutPage } from '../about/about';
import { ContactPage } from '../contact/contact';
import { HomePage } from '../home/home';
import {SettingsPage} from '../settings/settings' ;

@Component({
templateUrl: 'tabs.html'
})
export class TabsPage
{
   tab1Root = HomePage;
   tab2Root = AboutPage;
   tab3Root = SettingsPage;

   constructor()
   {
   }
}
</code>```

So , I can't understand why I the icons aren't displayed here. Prior to this build , previously it was working. I didn't change anything. Now it isn't working.

答:
add that to : > scss</p>

```<code>  .tabbar{opacity: 1;}
</code>```

Title: Tab icon not visible in ionic 3

Body:
Inside ./pages/tabs/tabs.html

<ion-tabs>
<ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
<ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-
circle"></ion-tab>
<ion-tab [root]="tab3Root" tabTitle="Settings" tabIcon="cog"></ion-
tab>
</ion-tabs>

Inside ./pages/tabs/tabs.ts

import { Component } from '@angular/core';
import { AboutPage } from '../about/about';
import { ContactPage } from '../contact/contact';
import { HomePage } from '../home/home';
import {SettingsPage} from '../settings/settings' ;

@Component({
templateUrl: 'tabs.html'
})
export class TabsPage
{
   tab1Root = HomePage;
   tab2Root = AboutPage;
   tab3Root = SettingsPage;

   constructor()
   {
   }
}

So , I can't understand why I the icons aren't displayed here. Prior to this build , previously it was working. I didn't change anything. Now it isn't working.

Body:
add that to : > scss

  .tabbar{opacity: 1;}


问:
Can't render glyph using freetype to OpenGL texture
Today for some reason Freetype stopped working for me. Everything worked fine yesterday, I haven't even touched the code. Instead of letter planes with specific text colors are being rendered.

I checked already if that's blending problem.

Code for loading the glyph.

// This is the relative path to the font,
    // later used to load the font.
    std::string strFontPath = "fonts/" + strFont + ".ttf";

    // Initialising Freetype Library

    FT_Library _ft;
    FT_Init_FreeType(&_ft);

    // Loading font from the file.
    FT_Face _face;

    if (FT_New_Face(_ft, strFontPath.c_str(), 0, &_face))
        EXIT_ERROR(-11);

    FT_Set_Pixel_Sizes(_face, 0, 48);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    // When I used char instead program misbehaved so I'm using
    // unsigned short int and convert the type.
    for (unsigned short int usiCurrentCharacter = 30; usiCurrentCharacter < 128; usiCurrentCharacter++)
    {
        // Loading char to the face, fails when char fails to load.
        if (FT_Load_Glyph(_face, FT_Get_Char_Index(_face,(char)usiCurrentCharacter), FT_LOAD_RENDER))
        {
            EXIT_ERROR(-12);
        }

        std::cout << (char)usiCurrentCharacter  << _face->glyph->bitmap.width << " " << _face->glyph->bitmap.rows << std::endl;

        // Create New Font
        FontTexture* _char = new FontTexture(_face->glyph->bitmap.buffer,
            0,
            { static_cast<float>(_face->glyph->bitmap.width),
            static_cast<float>(_face->glyph->bitmap.rows) });

        _char->SetAdvance(_face->glyph->advance.x);
        _char->SetBearing({ static_cast<float>(_face->glyph->bitmap_left),
            static_cast<float>(_face->glyph->bitmap_top) });

        TextureManager::getTextureManager().PrecacheTexture(std::to_string(usiCurrentCharacter) + strFont, _char);

        Characters.insert(std::pair<char, FontTexture*>(char(usiCurrentCharacter), _char));
    }

    FT_Done_Face(_face);
    FT_Done_FreeType(_ft);
```

<p>Also here goes my renderer code:</p>

```shader->Bind();
        shader->SetUniform3f("u_TextureColor", color.x, color.y, color.z);
        //shader->SetUniform2f("u_Position", pos.x, pos.y); //We have to calculate array on cpu anyway :P
        shader->SetUniform1i("u_Texture", 1);
        //Iterate through all characters
        for (char c : text)
        {
            FontTexture* _character = font->getFontTexture(c);

            float xpos = pos.x + _character->GetBearing().x * scale;
            float ypos = pos.y - (_character->GetSize().y - _character->GetBearing().y) * scale;

            float w = _character->GetSize().x * scale;
            float h = _character->GetSize().y * scale;

            vertices[0] = xpos;     vertices[1] = ypos + h;     vertices[2] = 0.0;      vertices[3] = 0.0;
            vertices[4] = xpos;     vertices[5] = ypos;         vertices[6] = 0.0;      vertices[7] = 1.0;
            vertices[8] = xpos + w; vertices[9] = ypos;         vertices[10] = 1.0;     vertices[11] = 1.0;
            vertices[12] = xpos;    vertices[13] = ypos + h;    vertices[14] = 0.0;     vertices[15] = 0.0;
            vertices[16] = xpos + w;vertices[17] = ypos;        vertices[18] = 1.0;     vertices[19] = 1.0;
            vertices[20] = xpos + w;vertices[21] = ypos + h;    vertices[22] = 1.0;     vertices[23] = 0.0;

            //_character->Bind(1);
            shader->Bind();

            va->Bind();
            vb->Bind(vertices, sizeof(vertices));

            Renderer::getRenderer().DrawArrays(*va, *vb, vertices);
            //_character->Unbind();

            pos.x += (_character->GetAdvance() >> 6) * scale;
        }
```

This is the result I got yesterday:

This is what I'm getting today:

答:
I've just noticed:
<code>//_character->Bind(1);</code>
That meant the texture wasn't binded before drawing.
Commenting it out fixed the problem. </p>

Body:
Today for some reason Freetype stopped working for me. Everything worked fine yesterday, I haven't even touched the code. Instead of letter planes with specific text colors are being rendered.

I checked already if that's blending problem.

Code for loading the glyph.

// This is the relative path to the font,
    // later used to load the font.
    std::string strFontPath = "fonts/" + strFont + ".ttf";

    // Initialising Freetype Library

    FT_Library _ft;
    FT_Init_FreeType(&_ft);

    // Loading font from the file.
    FT_Face _face;

    if (FT_New_Face(_ft, strFontPath.c_str(), 0, &_face))
        EXIT_ERROR(-11);

    FT_Set_Pixel_Sizes(_face, 0, 48);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    // When I used char instead program misbehaved so I'm using
    // unsigned short int and convert the type.
    for (unsigned short int usiCurrentCharacter = 30; usiCurrentCharacter < 128; usiCurrentCharacter++)
    {
        // Loading char to the face, fails when char fails to load.
        if (FT_Load_Glyph(_face, FT_Get_Char_Index(_face,(char)usiCurrentCharacter), FT_LOAD_RENDER))
        {
            EXIT_ERROR(-12);
        }

        std::cout << (char)usiCurrentCharacter  << _face->glyph->bitmap.width << " " << _face->glyph->bitmap.rows << std::endl;

        // Create New Font
        FontTexture* _char = new FontTexture(_face->glyph->bitmap.buffer,
            0,
            { static_cast<float>(_face->glyph->bitmap.width),
            static_cast<float>(_face->glyph->bitmap.rows) });

        _char->SetAdvance(_face->glyph->advance.x);
        _char->SetBearing({ static_cast<float>(_face->glyph->bitmap_left),
            static_cast<float>(_face->glyph->bitmap_top) });

        TextureManager::getTextureManager().PrecacheTexture(std::to_string(usiCurrentCharacter) + strFont, _char);

        Characters.insert(std::pair<char, FontTexture*>(char(usiCurrentCharacter), _char));
    }

    FT_Done_Face(_face);
    FT_Done_FreeType(_ft);

Also here goes my renderer code:

shader->Bind();
        shader->SetUniform3f("u_TextureColor", color.x, color.y, color.z);
        //shader->SetUniform2f("u_Position", pos.x, pos.y); //We have to calculate array on cpu anyway :P
        shader->SetUniform1i("u_Texture", 1);
        //Iterate through all characters
        for (char c : text)
        {
            FontTexture* _character = font->getFontTexture(c);

            float xpos = pos.x + _character->GetBearing().x * scale;
            float ypos = pos.y - (_character->GetSize().y - _character->GetBearing().y) * scale;

            float w = _character->GetSize().x * scale;
            float h = _character->GetSize().y * scale;

            vertices[0] = xpos;     vertices[1] = ypos + h;     vertices[2] = 0.0;      vertices[3] = 0.0;
            vertices[4] = xpos;     vertices[5] = ypos;         vertices[6] = 0.0;      vertices[7] = 1.0;
            vertices[8] = xpos + w; vertices[9] = ypos;         vertices[10] = 1.0;     vertices[11] = 1.0;
            vertices[12] = xpos;    vertices[13] = ypos + h;    vertices[14] = 0.0;     vertices[15] = 0.0;
            vertices[16] = xpos + w;vertices[17] = ypos;        vertices[18] = 1.0;     vertices[19] = 1.0;
            vertices[20] = xpos + w;vertices[21] = ypos + h;    vertices[22] = 1.0;     vertices[23] = 0.0;

            //_character->Bind(1);
            shader->Bind();

            va->Bind();
            vb->Bind(vertices, sizeof(vertices));

            Renderer::getRenderer().DrawArrays(*va, *vb, vertices);
            //_character->Unbind();

            pos.x += (_character->GetAdvance() >> 6) * scale;
        }

This is the result I got yesterday:

This is what I'm getting today:

Body:
I've just noticed:
//_character->Bind(1);
That meant the texture wasn't binded before drawing.
Commenting it out fixed the problem.


问:
What does the tag <link rel="author" .. do?
I'm currently trying to learn HTML and I have a question about the link element: <link rel="author" href="URL">. What does this element do?

My book says:

establishing a relationship between a document and an author
  (document).

But what does this really mean?

A visitor of my website can't see it, it is not displayed anywhere, so who or what is using this element?

答:
Using rel=author indicates that a link is pointing to information about the author of a page or article.

It establishes a link relationship between the page where it is found and the referenced document about the author.

To answer your question in layman's terms, consider a typical example looks like  link text the above code is basically saying "Here is a link to author-page.html. author-page.html is about the author of this document."

Body:
Using rel=author indicates that a link is pointing to information about the author of a page or article.

It establishes a link relationship between the page where it is found and the referenced document about the author.

To answer your question in layman's terms, consider a typical example looks like  <a href="/author-page.html" rel="author">link text</a> the above code is basically saying "Here is a link to author-page.html. author-page.html is about the author of this document."


问:
Check if a time range is not within other time ranges?
I need to check if the given time range is available or not.

Array with busy hours:

```<code>[
  { from: 2, to: 4 },
  { from: 8, to: 10 }
]
</code>```

The compartment I want to check

```<code>{ from: 3, to: 6 }
</code>```

Expected result:

```<code>{ from: 1, to: 2 } // true
{ from: 5, to: 7 } // true
{ from: 3, to: 4 } // false
{ from: 9, to: 10 } // false
</code>```

答:
You can use some()

const arr = [
  { from: 2, to: 4 },
  { from: 8, to: 10 }
]

function checkTime(arr,obj){
  return !arr.some(x => x.from <= obj.from && x.to >= obj.to);
}

let tests = [
  { from: 1, to: 2 },
  { from: 5, to: 7 },
  { from: 3, to: 4 },
  { from: 9, to: 10 }
]
tests.forEach(x => console.log(checkTime(arr,x)));```

Body:
I need to check if the given time range is available or not.

Array with busy hours:

[
  { from: 2, to: 4 },
  { from: 8, to: 10 }
]

The compartment I want to check

{ from: 3, to: 6 }

Expected result:

{ from: 1, to: 2 } // true
{ from: 5, to: 7 } // true
{ from: 3, to: 4 } // false
{ from: 9, to: 10 } // false


问:
Glide not Loading image from StorageReference
I have problem when loading image from StorageReference to ImageView using Glide 4.9.0 (latest).

It's stuck on PlaceHolder..
When I try to put the downloadable url of my ref, it's working..

```<code>StorageReference ref = FirebaseStorage.getInstance().getReference().child("myImage")

//It's not working
Glide.with(mContext)
   .load(ref)
   .placeholder(R.drawable.ic_loading_circle)
   .error(R.drawable.ic_loading_circle)
   .into(mImageView);

//It's working
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
    @Override
    public void onSuccess(Uri downloadUrl)
    {
        Glide.with(mContext)
            .load(downloadUrl.toString())
            .placeholder(R.drawable.ic_loading_circle)
            .error(R.drawable.ic_loading_circle)
            .into(mImageView);
    }
});
</code>```

I didn't see any error using try-catch, I already put Internet permission in Manifest. Other image from drawable are working also

Note: My firebase is used by 2 apps, the first app is working without any problem with Glide, but this 2nd app got unknown problem.

any solution or alternative? because using getDownloadUrl().addOnSuccessListener to get URI are so slow

答:
The solution working for you is the correct solution. I did things the same way.

```<code>profileListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String imageUrl = dataSnapshot.getValue(String.class);

            if (ProfileFragment.this.getActivity() != null)
                Glide.with(ProfileFragment.this.getActivity())
                        .load(imageUrl)
                        .placeholder(R.drawable.default_image)
                        .circleCrop()
                        .into(photoPhoto);
        }

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

        }
    };
</code>```

If you are finding this thing slow just enable offline persistence in firebase.

```<code>FirebaseDatabase.getInstance().setPersistenceEnabled(true);
</code>```

Before calling any FirebaseDatabase instance when app open.

Firebase manages the syncing very efficiently.

Note:- Whenever you find any random anomaly calling snapshot during developing the app, try clearing the data of the app or reinstalling.

Worked fine for me!

Body:
I have problem when loading image from StorageReference to ImageView using Glide 4.9.0 (latest).

It's stuck on PlaceHolder..
When I try to put the downloadable url of my ref, it's working..

StorageReference ref = FirebaseStorage.getInstance().getReference().child("myImage")

//It's not working
Glide.with(mContext)
   .load(ref)
   .placeholder(R.drawable.ic_loading_circle)
   .error(R.drawable.ic_loading_circle)
   .into(mImageView);

//It's working
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
    @Override
    public void onSuccess(Uri downloadUrl)
    {
        Glide.with(mContext)
            .load(downloadUrl.toString())
            .placeholder(R.drawable.ic_loading_circle)
            .error(R.drawable.ic_loading_circle)
            .into(mImageView);
    }
});

I didn't see any error using try-catch, I already put Internet permission in Manifest. Other image from drawable are working also

Note: My firebase is used by 2 apps, the first app is working without any problem with Glide, but this 2nd app got unknown problem.

any solution or alternative? because using getDownloadUrl().addOnSuccessListener to get URI are so slow

Body:
The solution working for you is the correct solution. I did things the same way.

profileListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String imageUrl = dataSnapshot.getValue(String.class);

            if (ProfileFragment.this.getActivity() != null)
                Glide.with(ProfileFragment.this.getActivity())
                        .load(imageUrl)
                        .placeholder(R.drawable.default_image)
                        .circleCrop()
                        .into(photoPhoto);
        }

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

        }
    };

If you are finding this thing slow just enable offline persistence in firebase.

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

Before calling any FirebaseDatabase instance when app open.

Firebase manages the syncing very efficiently.

Note:- Whenever you find any random anomaly calling snapshot during developing the app, try clearing the data of the app or reinstalling.

Worked fine for me!


问:
Python Kivy Panel Header unable to render content from class
I am trying to create a simple TabbedPanel with 4 tabs. I want each tab to render the widgets from 4 classes. Kivy seems to not be rendering this simple Label. I want to do this with the libraries and not by creating a .kv file and importing it with Builder.load_file(file). In the code I provided, I only show the default_tab. Thanks in advance.

```<code>import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.gridlayout import GridLayout
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelHeader

kivy.require('1.10.1')

class DeployScreen(GridLayout):
    def __init__(self, **kwargs):
        super(DeployScreen, self).__init__(**kwargs)
        self.cols = 1
        self.add_widget(Label(text='Deploy'))
        return(None)

class NucleusPanel(TabbedPanel):
    tab_pos = "top_left"
    nuc_panel = TabbedPanel()
    nuc_panel.default_tab_text = "Deploy"
    nuc_panel.default_tab_content = DeployScreen()

class NucleusApp(App):
    def build(self):
        return(NucleusPanel())

if __name__ == "__main__":
    NucleusApp().run()
</code>```

答:
Add a constructor for class NucleusPanel()

main.py

```<code>from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.tabbedpanel import TabbedPanel

class DeployScreen(GridLayout):
    def __init__(self, **kwargs):
        super(DeployScreen, self).__init__(**kwargs)
        self.cols = 1
        self.add_widget(Label(text='Deploy'))

class NucleusPanel(TabbedPanel):

    def __init__(self, **kwargs):
        super(NucleusPanel, self).__init__(**kwargs)
        self.tab_pos = "top_left"
        self.default_tab_text = "Deploy"
        self.default_tab_content = DeployScreen()

class NucleusApp(App):
    def build(self):
        return NucleusPanel()

if __name__ == "__main__":
    NucleusApp().run()
</code>```

Output

Body:
I am trying to create a simple TabbedPanel with 4 tabs. I want each tab to render the widgets from 4 classes. Kivy seems to not be rendering this simple Label. I want to do this with the libraries and not by creating a .kv file and importing it with Builder.load_file(file). In the code I provided, I only show the default_tab. Thanks in advance.

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.gridlayout import GridLayout
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelHeader

kivy.require('1.10.1')

class DeployScreen(GridLayout):
    def __init__(self, **kwargs):
        super(DeployScreen, self).__init__(**kwargs)
        self.cols = 1
        self.add_widget(Label(text='Deploy'))
        return(None)

class NucleusPanel(TabbedPanel):
    tab_pos = "top_left"
    nuc_panel = TabbedPanel()
    nuc_panel.default_tab_text = "Deploy"
    nuc_panel.default_tab_content = DeployScreen()

class NucleusApp(App):
    def build(self):
        return(NucleusPanel())

if __name__ == "__main__":
    NucleusApp().run()

Body:
Add a constructor for class NucleusPanel()

main.py

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.tabbedpanel import TabbedPanel

class DeployScreen(GridLayout):
    def __init__(self, **kwargs):
        super(DeployScreen, self).__init__(**kwargs)
        self.cols = 1
        self.add_widget(Label(text='Deploy'))

class NucleusPanel(TabbedPanel):

    def __init__(self, **kwargs):
        super(NucleusPanel, self).__init__(**kwargs)
        self.tab_pos = "top_left"
        self.default_tab_text = "Deploy"
        self.default_tab_content = DeployScreen()

class NucleusApp(App):
    def build(self):
        return NucleusPanel()

if __name__ == "__main__":
    NucleusApp().run()

Output


问:
StatusBar color in React Native
How can I change background color of StatusBar component from react-native, without editing Android specific files?

Docs says, that I can use backgroundColor property. But it fails. barStyle property, setBarStyle && setBackgroundColor static methods don`t work properly too.

Only hidden property works.

I`m using create-react-native-app, built with Expo.

答:
add color.xml in ..android/app/src/main/res/values and pate following code

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--   color for the app bar and other primary UI elements -->
    <color name="colorPrimary">#3F51B5</color>

    <!--   a darker variant of the primary color, used for
           the status bar (on Android 5.0+) and contextual app bars -->
    <color name="colorPrimaryDark">#A52D53</color>

    <!--   a secondary color for controls like checkboxes and text fields -->
    <color name="colorAccent">#FF4081</color>
</resources>
</code>```

copy and pate following code in ..android/app/src/main/res/values/styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
   <!-- Customize your theme here. -->
   <item name="colorPrimary">@color/colorPrimary</item>
   <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
   <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

Title: StatusBar color in React Native

Body:
add color.xml in ..android/app/src/main/res/values and pate following code

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--   color for the app bar and other primary UI elements -->
    <color name="colorPrimary">#3F51B5</color>

    <!--   a darker variant of the primary color, used for
           the status bar (on Android 5.0+) and contextual app bars -->
    <color name="colorPrimaryDark">#A52D53</color>

    <!--   a secondary color for controls like checkboxes and text fields -->
    <color name="colorAccent">#FF4081</color>
</resources>

copy and pate following code in ..android/app/src/main/res/values/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
   <!-- Customize your theme here. -->
   <item name="colorPrimary">@color/colorPrimary</item>
   <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
   <item name="colorAccent">@color/colorAccent</item>
</style>


问:
Blade view shows richtext content (stored in mysql table) as not-responsive
I stored a rich-text content in to MySQL table. When I tried to show that content in (Laravel) Blade template, It shows well (with the formatings done by html tags it has) but it is not responsive, as it went beyond the outer div tag (class="col-lg-8"). I understood that the issue is, the content's html tags are considered rather the outer div tag's "style" formats. Are there any possibilities to accomplish this..?

I used htmlspecialchars_decode() also, but nothing changed.
I used {!! and !!} to exclude html tags...

echo htmlspecialchars_decode($article->content);

{!!$article->content); !!}

The content has to obey the outer div's style "first", then the formatting it has itself.

答: Yeah I did it. I just put a str_replace() method in the relevant controller as it replaces the string (that richtext has) "width:1200px" as empty, them it becomes OK. So wherever the paragraph tries to behave the width "1200px", php won't allow it..! Finally the formatted text falling inside the responsive div tag. Hooray...!</p>


问:
Change background color when UIAlertViewController row is pressed down
When a user holds down on an UIAlertController row, it naturally changes to a grey color on the iPad but I would like to make that another color. How can I do that?

```<code>let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler:  { action in

        }))
        alert.addAction(UIAlertAction(title: "Settings", style: UIAlertAction.Style.default, handler:  { action in
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, completionHandler: nil)
        }))
        self.present(alert, animated: true, completion: nil)
</code>```

This is what the iPhone does when you hold down a row. I want to change that background color.

答:
You can not.

Important

The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

Source : https://developer.apple.com/documentation/uikit/uialertcontroller

Body:
When a user holds down on an UIAlertController row, it naturally changes to a grey color on the iPad but I would like to make that another color. How can I do that?

let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler:  { action in

        }))
        alert.addAction(UIAlertAction(title: "Settings", style: UIAlertAction.Style.default, handler:  { action in
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, completionHandler: nil)
        }))
        self.present(alert, animated: true, completion: nil)

This is what the iPhone does when you hold down a row. I want to change that background color.


问:
Using Awk to find Unique chars bought by a customer
I have log files like this (it's only space between them but for readibility i changed that) :

```<code>Customer  Car             Bought
François  Nissan Pajero   28/05/2016
Matthew   Mercedes S      10/01/2019
Andrew    Peugeot 508     05/0/2000
Matthew   Toyota Hilux    02/10/2012
</code>```

I need to make an awk script which display for each customer what car he has bought like this :

```<code>Matthew, car bought: Mercedes S,Toyota Hilux, number of cars: 2
Francois, car bought: Nissan Pjero, number of cars: 1
</code>```

I'm not able to know how to do it.

I think i should create an array for Customer and one for the car and indexed it with the number of line

```<code>awk ' { Customer[NR]=$1; Car[NR]=$2} END {}'
</code>```

What should i add in the END, i'm little perplexed

I thought doing this also:

```<code>awk ' { Customer[$1]=$2} END { for (i in Customer) print i,Customer[i]}'
</code>```

The problem with this array, it will destroy the previous value of the car in the Customer indexed array.

答:
If you are not worried about order of output(which should not be same as Input_file's 1st field) then could you please try following.

```<code>awk '
FNR>1{
  match($0,/ +.* +/)
  var=substr($0,RSTART,RLENGTH)
  gsub(/^[[:space:]]+|[[:space:]]+$/,"",var)
  a[$1]=(a[$1]?a[$1] OFS:"")var
  b[$1]++
}
END{
  for(i in a){
    print i","a[i]",number of cars: "b[i]
  }
}
'   Input_file
</code>```

EDIT: Adding solution which will provide output in same order of 1st field of Input_file.

```<code>awk '
FNR>1{
  if(!b[$1]++){
    c[++count]=$1
  }
  match($0,/ +.* +/)
  var=substr($0,RSTART,RLENGTH)
  gsub(/^[[:space:]]+|[[:space:]]+$/,"",var)
  a[$1]=(a[$1]?a[$1] OFS:"")var
  d[$1]++
}
END{
  for(i=1;i<=count;i++){
    print c[i]","a[c[i]]",number of cars: "d[c[i]]
  }
}
'   Input_file
</code>```

Body:
I have log files like this (it's only space between them but for readibility i changed that) :

Customer  Car             Bought
François  Nissan Pajero   28/05/2016
Matthew   Mercedes S      10/01/2019
Andrew    Peugeot 508     05/0/2000
Matthew   Toyota Hilux    02/10/2012

I need to make an awk script which display for each customer what car he has bought like this :

Matthew, car bought: Mercedes S,Toyota Hilux, number of cars: 2
Francois, car bought: Nissan Pjero, number of cars: 1

I'm not able to know how to do it.

I think i should create an array for Customer and one for the car and indexed it with the number of line

awk ' { Customer[NR]=$1; Car[NR]=$2} END {}'

What should i add in the END, i'm little perplexed

I thought doing this also:

awk ' { Customer[$1]=$2} END { for (i in Customer) print i,Customer[i]}'

The problem with this array, it will destroy the previous value of the car in the Customer indexed array.

Body:
If you are not worried about order of output(which should not be same as Input_file's 1st field) then could you please try following.

awk '
FNR>1{
  match($0,/ +.* +/)
  var=substr($0,RSTART,RLENGTH)
  gsub(/^[[:space:]]+|[[:space:]]+$/,"",var)
  a[$1]=(a[$1]?a[$1] OFS:"")var
  b[$1]++
}
END{
  for(i in a){
    print i","a[i]",number of cars: "b[i]
  }
}
'   Input_file

EDIT: Adding solution which will provide output in same order of 1st field of Input_file.

awk '
FNR>1{
  if(!b[$1]++){
    c[++count]=$1
  }
  match($0,/ +.* +/)
  var=substr($0,RSTART,RLENGTH)
  gsub(/^[[:space:]]+|[[:space:]]+$/,"",var)
  a[$1]=(a[$1]?a[$1] OFS:"")var
  d[$1]++
}
END{
  for(i=1;i<=count;i++){
    print c[i]","a[c[i]]",number of cars: "d[c[i]]
  }
}
'   Input_file


问:
Problem with xy grid and menu in Microsoft Edge only
I've created a responsive dropdown/drilldown megamenu in Foundation 6.5.3.

It works great in every browser except Microsoft Edge and IE11. I expected problems in IE, but the edge issues threw me for a loop.

In Edge, the menu items get stacked vertically even though it is supposed to be a horizontal menu. As illustrated by this pen:

```<code> https://codepen.io/denpub/pen/KLRQGO
</code>```

right now the divs that wrap the menus and the one that wraps the large menu contain both the grid-x and cell styles:

```<code> <div class="grid-x cell ..."></div>
</code>```

seems to be the what causes the stacking issue and if I separate these like so:

```<code> <div class="grid-x ..."><div class="cell"></div></div>
</code>```

it fixes the stacking issue in Edge, but causes the menu to lose the nice flex spacing in all browsers as illustrated with this pen:

```<code> https://codepen.io/denpub/pen/KLRojm
</code>```

In IE11 all the menu items stack on top of each other. If anyone has a suggestion to resolve this it would be greatly appreciated.

答: My guess is it's the expanded class on the parent menu. This could cause the li's to go full width when there is less space.

Body:
I've created a responsive dropdown/drilldown megamenu in Foundation 6.5.3.

It works great in every browser except Microsoft Edge and IE11. I expected problems in IE, but the edge issues threw me for a loop.

In Edge, the menu items get stacked vertically even though it is supposed to be a horizontal menu. As illustrated by this pen:

 https://codepen.io/denpub/pen/KLRQGO

right now the divs that wrap the menus and the one that wraps the large menu contain both the grid-x and cell styles:

seems to be the what causes the stacking issue and if I separate these like so:

it fixes the stacking issue in Edge, but causes the menu to lose the nice flex spacing in all browsers as illustrated with this pen:

 https://codepen.io/denpub/pen/KLRojm

In IE11 all the menu items stack on top of each other. If anyone has a suggestion to resolve this it would be greatly appreciated.


问:
How does an incoming request to a nodejs server get handled when the event loop is waiting for a DB operation
I have a route in my API, as an example lets call it /users/:userId/updateBalance. This route will fetch the users current balance, add whatever comes from the request and then update the balance with the newly calculated balance. A request like this comes into the server for a specific user every 30 minutes, so until recently, I thought a concurrency issue to be impossible.

What ended up happening is that somewhere, a sent request failed and was only sent again 30 minutes later, about within a second of the other request. The result was that, as I can see it in the database, both of these requests fetched the same balance from the DB and both added their respective amounts. Essentially, the second request actually read a stale balance, as normally it should execute after request 1 has executed.

To give a numerical example for some more clarity, lets say request 1 was to add $2 to the balance, and request 2 was to add $5, and the user had a balance of $10. If the requests act in parallel, the users balance would end at either $12 or $15 depending on whether request 1 or request 2 finished first respectively, because both requests fetch a balance of $10 from the DB. However, obviously the expected behaviour is that we want request 1 to execute, update the users balance to $12, and then request 2 to execute and update the balance from $12 to $17.

To give some better perspective of the overall execution of this process: the request is received, a function is called, the function has to wait for the balance from the DB, the function then calculates the new balance and updates the db, after which execution is completed.

So I have a few questions on this. The first being, how does node handle incoming requests when it is waiting for an asynchronous request like a MySQL database read. Given the results I have observed, I assume that when the first request is waiting for the DB, the second request can commence being processed? Otherwise I am uncertain of how such asynchronous behaviour is experienced within a single threaded environment like node.

Secondly, how do I go about controlling this and preventing it. I had wanted to use a MySQL transaction with a forUpdate lock, but it turns out it seems not possible due to the way the code is currently written. Is there a way to tell node that a certain block of code can not be executed "in parallel"? Or any other alternatives?

答:
You are right, while node waits for the database query to return, it will handle any incoming requests and start that requests database call before the first one finishes.

The easiest way to prevent this IMO would be to use queues. Instead of processing the balance update directly in the route handler, that route handler could push an event to a queue (in Redis, in AWS SQS, in RabbitMQ etc) and somewhere else in your app (or even in a completely different service) you would have a consumer that listens to new events in that queue. If an update fails, add it back to the beginning of the queue, add some wait time, and then try again.

This way, no matter how many times your first request fails, your balance will be correct, and pending changes to that balance will be in the correct order. In case of an event in the queue failing repeatedly, you could even send an email or a notification to someone to have a look at it, and while the problem is fixed pending changes to the balance will be added to the queue, and once it's fixed, everything will be processed correctly.

You could even read that queue and display information to your user, for instance tell the user the balance has pending updates so it might not be accurate.

Hope this helps!


问:
How programmatically move a UIScrollView to focus in a control above keyboard?
I have 6 UITextFields on my UIScrollView. Now, I can scroll by user request. But when the keyboard appear, some textfields are hidden.

That is not user-friendly.

How scroll programmatically the view so I get sure the keyboard not hide the textfield?

答:
I've put together a universal, drop-in UIScrollView and UITableView subclass that takes care of moving all text fields within it out of the way of the keyboard.

When the keyboard is about to appear, the subclass will find the subview that's about to be edited, and adjust its frame and content offset to make sure that view is visible, with an animation to match the keyboard pop-up. When the keyboard disappears, it restores its prior size.

It should work with basically any setup, either a UITableView-based interface, or one consisting of views placed manually.

Here it is.

```<code>(For google: TPKeyboardAvoiding, TPKeyboardAvoidingScrollView, TPKeyboardAvoidingCollectionView.)
Editor's note: TPKeyboardAvoiding seems to be continually updated and fresh, as of 2014.
</code>```

OwnerDisplayName: mamcx

Body:
I've put together a universal, drop-in UIScrollView and UITableView subclass that takes care of moving all text fields within it out of the way of the keyboard.

When the keyboard is about to appear, the subclass will find the subview that's about to be edited, and adjust its frame and content offset to make sure that view is visible, with an animation to match the keyboard pop-up. When the keyboard disappears, it restores its prior size.

It should work with basically any setup, either a UITableView-based interface, or one consisting of views placed manually.

Here it is.

(For google: TPKeyboardAvoiding, TPKeyboardAvoidingScrollView, TPKeyboardAvoidingCollectionView.)
Editor's note: TPKeyboardAvoiding seems to be continually updated and fresh, as of 2014.


问:
How to get the grayscale pixel value for a given point (x,y) on an image?
I have been trying to use the code below to extract the grayscale value associated with a given pixel of my image. I thought it was working but then I noticed my results were inconsistent with my image.

How can I get the correct grayscale value for a given pixel of my image at (x,y) from the 1D array that my pixelValues function returns?

I tried using index = x * width of image +y but this does not seem to be working.

```<code>func pixelValues(fromCGImage imageRef: CGImage?) -> (pixelValues: [UInt16]?, width: Int, height: Int)
{
    var width = 0
    var height = 0
    var pixelValues: [UInt16]?
    if let imageRef = imageRef {
        width = imageRef.width
        height = imageRef.height
        let bitsPerComponent = imageRef.bitsPerComponent
        let bytesPerRow = imageRef.bytesPerRow
        let totalBytes = height * width

        let colorSpace = CGColorSpaceCreateDeviceGray()
        var intensities = [UInt16](repeating: 0, count: totalBytes)

        let contextRef = CGContext(data: &intensities, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: 0)
        contextRef?.draw(imageRef, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)))

        pixelValues = intensities
    }

    return (pixelValues ,width, height)
}

//Returns grayscale value of image at pixel (x,y)
func getGrayValue(pixelValues: [UInt16], width: Int, x: Int, y: Int) -> UInt16 {
    let i = x*width + y
    return pixelValues[i]
}
</code>```

答:
Your calculation

index = x * width of image +y

is off, if you are storing a 2D image in a 1D array, the correct way to access a value at [x,y] is:

index = x + width of image * y

Body:
I have been trying to use the code below to extract the grayscale value associated with a given pixel of my image. I thought it was working but then I noticed my results were inconsistent with my image.

How can I get the correct grayscale value for a given pixel of my image at (x,y) from the 1D array that my pixelValues function returns?

I tried using index = x * width of image +y but this does not seem to be working.

func pixelValues(fromCGImage imageRef: CGImage?) -> (pixelValues: [UInt16]?, width: Int, height: Int)
{
    var width = 0
    var height = 0
    var pixelValues: [UInt16]?
    if let imageRef = imageRef {
        width = imageRef.width
        height = imageRef.height
        let bitsPerComponent = imageRef.bitsPerComponent
        let bytesPerRow = imageRef.bytesPerRow
        let totalBytes = height * width

        let colorSpace = CGColorSpaceCreateDeviceGray()
        var intensities = [UInt16](repeating: 0, count: totalBytes)

        let contextRef = CGContext(data: &intensities, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: 0)
        contextRef?.draw(imageRef, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)))

        pixelValues = intensities
    }

    return (pixelValues ,width, height)
}

//Returns grayscale value of image at pixel (x,y)
func getGrayValue(pixelValues: [UInt16], width: Int, x: Int, y: Int) -> UInt16 {
    let i = x*width + y
    return pixelValues[i]
}


问:
Refactoring repetitive calls to generic method
I have a block of code like this: (MyClassX is just a shorthand for my business objects, which might extend later ...

```<code>var conn = new SQLiteAsyncConnection(dbPath);

conn.CreateTableAsync<MyClass1>().Wait();
conn.CreateTableAsync<MyClass2>().Wait();
conn.CreateTableAsync<MyClass3>().Wait();
conn.CreateTableAsync<MyClass4>().Wait();
conn.CreateTableAsync<MyClass5>().Wait();
...
conn.CreateTableAsync<MyClass20>().Wait();
</code>```

And would like to somehow refactor it to avoid the repetitiveness and make it more maintainable. One try was something akin to

```<code> // Generic Lambda invocation
 Action<Type> init_bo = t => conn.GetType().GetMethod("CreateTableAsync")
                             .MakeGenericMethod(t).Invoke(conn, null);
 List<Type> bo_types = new List<Type>() { typeof(MyClass1), typeof(MyClass2),
                                          ..., typeof(MyClass20) };
 bo_types.ForEach(init_bo);
</code>```

, which seems not terribly expressive (and does not call Wait()).
How could I go about utilizing templates/functional programming to get more expressive and concise code?

Edit: Not a duplicate in my opinion, since I already answered how to call a generic method in the original question, but I was not happy with the resulting code w.r.t. expressiveness.

答:
You can call Wait by casting the result to a Task:

```<code>var createMethod = conn.GetType().GetMethod("CreateTableAsync");
Task[] createTasks = bo_types.Select(t => (Task)createMethod.MakeGenericMethod(t).Invoke(conn, null)).ToArray();
Tasks.WaitAll(createTasks);
</code>```

Body:
I have a block of code like this: (MyClassX is just a shorthand for my business objects, which might extend later ...

var conn = new SQLiteAsyncConnection(dbPath);

conn.CreateTableAsync<MyClass1>().Wait();
conn.CreateTableAsync<MyClass2>().Wait();
conn.CreateTableAsync<MyClass3>().Wait();
conn.CreateTableAsync<MyClass4>().Wait();
conn.CreateTableAsync<MyClass5>().Wait();
...
conn.CreateTableAsync<MyClass20>().Wait();

And would like to somehow refactor it to avoid the repetitiveness and make it more maintainable. One try was something akin to

 // Generic Lambda invocation
 Action<Type> init_bo = t => conn.GetType().GetMethod("CreateTableAsync")
                             .MakeGenericMethod(t).Invoke(conn, null);
 List<Type> bo_types = new List<Type>() { typeof(MyClass1), typeof(MyClass2),
                                          ..., typeof(MyClass20) };
 bo_types.ForEach(init_bo);

, which seems not terribly expressive (and does not call Wait()).
How could I go about utilizing templates/functional programming to get more expressive and concise code?

Edit: Not a duplicate in my opinion, since I already answered how to call a generic method in the original question, but I was not happy with the resulting code w.r.t. expressiveness.

Body:
You can call Wait by casting the result to a Task:

var createMethod = conn.GetType().GetMethod("CreateTableAsync");
Task[] createTasks = bo_types.Select(t => (Task)createMethod.MakeGenericMethod(t).Invoke(conn, null)).ToArray();
Tasks.WaitAll(createTasks);


问:
Recoding specific column values using reference list
My dataframe looks like this

```<code>data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))
</code>```

And I have a reference list that looks like this -

```<code>ref=list(Male=1,Female=2)
</code>```

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

```<code>do.call(dplyr::recode, c(list(data), ref))
</code>```

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated

答:
In base R:

data$Gender = sapply(data$Gender, function(x) ref[[x]])

Body:
My dataframe looks like this

data = data.frame(ID=c(1,2,3,4,5,6,7,8,9,10),
              Gender=c('Male','Female','Female','Female','Male','Female','Male','Male','Female','Female'))

And I have a reference list that looks like this -

ref=list(Male=1,Female=2)

I'd like to replace values in the Gender column using this reference list, without adding a new column to my dataframe.

Here's my attempt

do.call(dplyr::recode, c(list(data), ref))

Which gives me the following error -

no applicable method for 'recode' applied to an object of class
  "data.frame"

Any inputs would be greatly appreciated


问:
how to check if (c#) ControlCollection.Find() has returned a result
I am using ControlCollection.Find() method in C# to find some picture boxes present in my form.

I am storing the returned result in a Control[] array. How do I find out if the Find() was successful or not???

Code

```<code>Control[] temp = pictureBoxCollection.Find(TagNo, true);
if(temp.Length>0)
    UpdateRes = update_status(TagNo, Status);
</code>```

where TagNo is a string containing the Control's exact name.

Yes. I'm using the control's exact name. And I have used the Find() method successfully earlier (when the Control was surely present in the Collection). I am having a problem this time because the control may or may not be present in the Collection.

答:
Have you tried?

```<code>var result = controlCollection.Find(contolName,true);
if(result == null || result.Length == 0)
{
   // fail to find
}
</code>```

You can use this method to see list of all controls

```<code>    public void FillControls(List<string> container,Control control)
    {
        foreach (Control child in control.Controls)
        {
            container.Add(child.Name);
            FillControls(container,child);
        }
    }
</code>```

And then use:

```<code>    public Form1()
    {
        InitializeComponent();

        List<string> controls = new List<string>();
        FillControls(controls,this);
    }
</code>```

Body:
I am using ControlCollection.Find() method in C# to find some picture boxes present in my form.

I am storing the returned result in a Control[] array. How do I find out if the Find() was successful or not???

Code

Control[] temp = pictureBoxCollection.Find(TagNo, true);
if(temp.Length>0)
    UpdateRes = update_status(TagNo, Status);

where TagNo is a string containing the Control's exact name.

Yes. I'm using the control's exact name. And I have used the Find() method successfully earlier (when the Control was surely present in the Collection). I am having a problem this time because the control may or may not be present in the Collection.

Body:
Have you tried?

var result = controlCollection.Find(contolName,true);
if(result == null || result.Length == 0)
{
   // fail to find
}

You can use this method to see list of all controls

    public void FillControls(List<string> container,Control control)
    {
        foreach (Control child in control.Controls)
        {
            container.Add(child.Name);
            FillControls(container,child);
        }
    }

And then use:

    public Form1()
    {
        InitializeComponent();

        List<string> controls = new List<string>();
        FillControls(controls,this);
    }