问:
JpaRepository does not returns any of my custom queries
i'm working with spring boot in IntelliJ

i've extended a JpaRepository interface and created a query that is not shown in the repository variable into my controller (i've previously done it, but somethig does not works now, i do not find why)

the repository

```<code>package com.ITAcademy.dices.repositories;

import org.springframework.data.jpa.repository.JpaRepository;

import com.ITAcademy.dices.entities.Player;

    public Player findOneByOrderByrateSuccessAsc();
    public Player findOneByOrderByrateSuccessDesc();
    public List<Player> findAllByOrderAsc();
}
</code>```

the controller:

```<code>package com.ITAcademy.dices.controllers;

import java.sql.Date;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import com.ITAcademy.dices.exceptions.PlayerNotFoundException;
import com.ITAcademy.dices.repositories.PlayerRepository;
import lombok.Data;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ITAcademy.dices.entities.Player;

import javax.persistence.Entity;

@Data
@Entity
@RestController
@RequestMapping("/dices")
public class PlayerController{

    private final JpaRepository repository;

    public PlayerController(PlayerRepository repository) {
        this.repository = repository;
        Player player = new Player();
    }

    //Get all players
    @GetMapping("/players")
    public List <Player> getAllPlayers() {
        return repository.findAll();
    }

    //Create a new player
    @PostMapping("/player")
    public Object newPlayer(@RequestBody Player newPlayer) {
        newPlayer.setDateRegister(Date.valueOf(LocalDate.now()));
        newPlayer.setRateSuccess(-1);
        if (newPlayer.getName()=="") newPlayer.setName("Anonymous");
        return repository.save(newPlayer);
    }

    //Get a player by id
    @GetMapping("/player/{idPlayer}")
    public Player getPlayer(@PathVariable Integer idPlayer) throws Throwable {
        return (Player) repository.findById(idPlayer)
                .orElseThrow(() -> new PlayerNotFoundException(idPlayer);
    }

    //Delete a player
    @DeleteMapping("/player/{idPlayer}")
    public void deletePlayer(@PathVariable Integer idPlayer) {
        try {
            repository.deleteById(idPlayer);
        } catch (EmptyResultDataAccessException e) {
            throw new PlayerNotFoundException(idPlayer);
        }
    }

    //Modify a player
    @PutMapping("/player/{idPlayer}")
    public Player modifyPlayer(@PathVariable Integer idPlayer, @PathVariable String playerName) throws Throwable {
        Player player = new Player();
        player = (Player) repository.findById(idPlayer)
            .orElseThrow(() -> new PlayerNotFoundException(idPlayer));
        player.setName(playerName);
        return player;
    }

    //Get success average from all players
    @GetMapping("/players/ranking")
    public double getSuccessAverage(){
        Double success = new Double;
        List<Player> players = new ArrayList<Player>();
        players = repository.findAll();
        for(int x = 0; x < players.size(); x++){
            success = success + players.get(x).getRateSuccess();
        }
        return success/players.size();
    }

    //Get player with highest success rate
    @GetMapping("/players/ranking/winner")
    public Player getWinner() {
        return this.repository.findOneByOrderByrateSuccessAsc();
    }

    //Get player with lowest success rate
    @GetMapping("/players/ranking/loser")
    public Player getLoser() {
        return this.repository.findOneByOrderByrateSuccessDesc();
    }
}

</code>```

the repository methods are wrote by me, because they are not shown after the repository dot.

Any sugestion?
thanks

答:
I think your query method names are wrong.

I guess the last one for example should looks like this:

public List<Player> findAllByOrderByIdAsc();

(I guess id is your primary key field ;))

Here are some other examples: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#reference

Body:
i'm working with spring boot in IntelliJ

i've extended a JpaRepository interface and created a query that is not shown in the repository variable into my controller (i've previously done it, but somethig does not works now, i do not find why)

the repository

package com.ITAcademy.dices.repositories;

import org.springframework.data.jpa.repository.JpaRepository;

import com.ITAcademy.dices.entities.Player;

    public Player findOneByOrderByrateSuccessAsc();
    public Player findOneByOrderByrateSuccessDesc();
    public List<Player> findAllByOrderAsc();
}

the controller:

package com.ITAcademy.dices.controllers;

import java.sql.Date;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import com.ITAcademy.dices.exceptions.PlayerNotFoundException;
import com.ITAcademy.dices.repositories.PlayerRepository;
import lombok.Data;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ITAcademy.dices.entities.Player;

import javax.persistence.Entity;

@Data
@Entity
@RestController
@RequestMapping("/dices")
public class PlayerController{

    private final JpaRepository repository;

    public PlayerController(PlayerRepository repository) {
        this.repository = repository;
        Player player = new Player();
    }

    //Get all players
    @GetMapping("/players")
    public List <Player> getAllPlayers() {
        return repository.findAll();
    }

    //Create a new player
    @PostMapping("/player")
    public Object newPlayer(@RequestBody Player newPlayer) {
        newPlayer.setDateRegister(Date.valueOf(LocalDate.now()));
        newPlayer.setRateSuccess(-1);
        if (newPlayer.getName()=="") newPlayer.setName("Anonymous");
        return repository.save(newPlayer);
    }

    //Get a player by id
    @GetMapping("/player/{idPlayer}")
    public Player getPlayer(@PathVariable Integer idPlayer) throws Throwable {
        return (Player) repository.findById(idPlayer)
                .orElseThrow(() -> new PlayerNotFoundException(idPlayer);
    }

    //Delete a player
    @DeleteMapping("/player/{idPlayer}")
    public void deletePlayer(@PathVariable Integer idPlayer) {
        try {
            repository.deleteById(idPlayer);
        } catch (EmptyResultDataAccessException e) {
            throw new PlayerNotFoundException(idPlayer);
        }
    }

    //Modify a player
    @PutMapping("/player/{idPlayer}")
    public Player modifyPlayer(@PathVariable Integer idPlayer, @PathVariable String playerName) throws Throwable {
        Player player = new Player();
        player = (Player) repository.findById(idPlayer)
            .orElseThrow(() -> new PlayerNotFoundException(idPlayer));
        player.setName(playerName);
        return player;
    }

    //Get success average from all players
    @GetMapping("/players/ranking")
    public double getSuccessAverage(){
        Double success = new Double;
        List<Player> players = new ArrayList<Player>();
        players = repository.findAll();
        for(int x = 0; x < players.size(); x++){
            success = success + players.get(x).getRateSuccess();
        }
        return success/players.size();
    }

    //Get player with highest success rate
    @GetMapping("/players/ranking/winner")
    public Player getWinner() {
        return this.repository.findOneByOrderByrateSuccessAsc();
    }

    //Get player with lowest success rate
    @GetMapping("/players/ranking/loser")
    public Player getLoser() {
        return this.repository.findOneByOrderByrateSuccessDesc();
    }
}

the repository methods are wrote by me, because they are not shown after the repository dot.

Any sugestion?
thanks


来源: stackexchange

问:
Why JFlex reject .+?(?=->)
I'm trying design simple language idea plugin.
I want to match below example code as 3 tokens as text before ->, between -> and :, after :

Ex: First part -> Second Part: Third part

For first part when I try regex .+?(?=->) at https://regex101.com/r/TDBWg0/1 it works.
But as per JFlex .+?(?=->) has a syntax error:

```<code>Error in file "Simple.flex" (line 41):
Syntax error.
FIRST_PART=.+(?=(->))
              ^
</code>```

答:
Lexer generators like JFlex often have a different syntax and feature set than most other regex implementations, so helpers like regex101 aren't always that useful for them. Instead you should look at the JFlex manual to see which syntax JFlex supports.

There's two things of note there:

The syntax for lookahead is /regex not (?=regex)

There is no syntax for non-greedy quantifiers

< and > need to be quoted or escaped

So .+/"->" would be a valid regex, but when there are multiple ->s it will match up to the last ->, not the first. Presumably you tried to make the + non-greedy specifically so that it would only match up to the first, so this is no good.

Since there are no non-greedy modifiers in JFlex, we need a different approach. If we look at the available regex features again, we'll see that there's an operator ~, which works as follows:

~a (upto)

matches everything up to (and including) the first occurrence of a text matched by a. The expression ~a is equivalent to !([^]* a [^]*) a. A traditional C-style comment is matched by "/*" ~"*/".

So the regex you want is simpy ~"->".

Another approach, that works with virtually every regex implementation, would be to write a regex that specifically matches everything that's not a ->, i.e. any non-- character or a - not followed by a >. So that'd be:

```<code>([^-]|-[^\>])+
</code>```

ContentLicense: CC BY-SA 4.0

Title: Why JFlex reject .+?(?=->)

Body:
I'm trying design simple language idea plugin.
I want to match below example code as 3 tokens as text before ->, between -> and :, after :

Ex: First part -> Second Part: Third part

For first part when I try regex .+?(?=->) at https://regex101.com/r/TDBWg0/1 it works.
But as per JFlex .+?(?=->) has a syntax error:

Error in file "Simple.flex" (line 41):
Syntax error.
FIRST_PART=.+(?=(->))
              ^

Body:
Lexer generators like JFlex often have a different syntax and feature set than most other regex implementations, so helpers like regex101 aren't always that useful for them. Instead you should look at the JFlex manual to see which syntax JFlex supports.

There's two things of note there:

The syntax for lookahead is /regex not (?=regex)

There is no syntax for non-greedy quantifiers

< and > need to be quoted or escaped

So .+/"->" would be a valid regex, but when there are multiple ->s it will match up to the last ->, not the first. Presumably you tried to make the + non-greedy specifically so that it would only match up to the first, so this is no good.

Since there are no non-greedy modifiers in JFlex, we need a different approach. If we look at the available regex features again, we'll see that there's an operator ~, which works as follows:

~a (upto)

matches everything up to (and including) the first occurrence of a text matched by a. The expression ~a is equivalent to !([^]* a [^]*) a. A traditional C-style comment is matched by "/*" ~"*/".

So the regex you want is simpy ~"->".

Another approach, that works with virtually every regex implementation, would be to write a regex that specifically matches everything that's not a ->, i.e. any non-- character or a - not followed by a >. So that'd be:

([^-]|-[^\>])+


问:
R: missing value where TRUE/FALSE needed: solution for logistic regression
I want to run a logistic regression:

```<code>lrm(formula = dat$law ~ dat$argor + dat$trust.cen + dat$argor*dat$trust.cen +
  dat$trust.abs + dat$argor*dat$trust.abs)
</code>```

but I get this error:

Error in if (!length(fname) || !any(fname == zname)) { :

  missing value where TRUE/FALSE needed

Other posts have this error, but I cannot solve the problem with any of those solutions. Any help?

答:
The error happens when you use $ in the formula. Strangely it's an issue that affects lrm but not lm. The solution is to not use $ as per Roman in the comments. Fortunately you can work around this by referring the dataset law in the data term:

```<code>lrm(formula = law ~ argor + trust.cen + argor*trust.cen + trust.abs + argor*trust.abs, data = law)
</code>```

Body:
I want to run a logistic regression:

lrm(formula = dat$law ~ dat$argor + dat$trust.cen + dat$argor*dat$trust.cen +
  dat$trust.abs + dat$argor*dat$trust.abs)

but I get this error:

Error in if (!length(fname) || !any(fname == zname)) { :

  missing value where TRUE/FALSE needed

Other posts have this error, but I cannot solve the problem with any of those solutions. Any help?

Body:
The error happens when you use $ in the formula. Strangely it's an issue that affects lrm but not lm. The solution is to not use $ as per Roman in the comments. Fortunately you can work around this by referring the dataset law in the data term:

lrm(formula = law ~ argor + trust.cen + argor*trust.cen + trust.abs + argor*trust.abs, data = law)


问:
django table has no column named Exception
Git Repository
Request to guide me on what to do.

I work on an e-commerce website with the help of Django. and I'm a beginner in Django
The following image provides a table of my database. It helps to add a product

Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs.

An error occurred while migrating

Request to guide me on what to do.

答:
Do you have the table ready and set up? Because the error says, that there is a table named shop_product, but it does not have a column named product_name.

So the structure of your table would get us closer to the solution of your problem.

Edit:

I have just seen, that you supplied your Git repo. I looked at the database and what I wrote above holds true. Your shop_product table has no columns. I did not look through your code to see if it would be set up automatically, but I suppose you were supposed to create the columns by hand, right?


问:
update array of objects in localstorage without leaveing a null
So I have 3 text input fields, the input I store in local storage as an array of objects.
Looks like that:

```<code>[{name: " Name1", description: "Description1", comment: "Comment1"},…]
0: {name: " Name1", description: "Description1", comment: "Comment1"}
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}
</code>```

I need to be able to delete any entry I choose and update local storage.

After JSON.parse I get an javascript object, not an array.
If I use delete[X] it leaves null -

```<code>[null, {name: " Name2", description: "Description2", comment: "Comment2"},…]
0: null
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}
</code>```

Is there any way to avoid that, I need entry be completely gone and update indexes so "name2..." would gain index 0 and so on.

Is there any way to do it?
Thanks!

答:
Instead of mutating the array, filter it out: Example:</p>

```<code>const newArr = [...].filter(o => o.name != <name you want to remove>)
</code>```

Body:
So I have 3 text input fields, the input I store in local storage as an array of objects.
Looks like that:

[{name: " Name1", description: "Description1", comment: "Comment1"},…]
0: {name: " Name1", description: "Description1", comment: "Comment1"}
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}

I need to be able to delete any entry I choose and update local storage.

After JSON.parse I get an javascript object, not an array.
If I use delete[X] it leaves null -

[null, {name: " Name2", description: "Description2", comment: "Comment2"},…]
0: null
1: {name: " Name2", description: "Description2", comment: "Comment2"}
2: {name: " Name3", description: "Description3", comment: "Comment3"}

Is there any way to avoid that, I need entry be completely gone and update indexes so "name2..." would gain index 0 and so on.

Is there any way to do it?
Thanks!

Body:
Instead of mutating the array, filter it out: Example:

const newArr = [...].filter(o => o.name != <name you want to remove>)


问:
Python insert to MySQL : Failed to record Price 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
I have a python code that insert variables "link" and "name" into one table "pricedb" and "avgrate" into the other table

```<code>#insert product into product table
def insertProduct(link, name):
    try:
        #mySQL instruction to insert to link and name column
        mySqlInsertProduct =  """INSERT INTO products_list (link, name) VALUES (%s, %s) """
        recordProduct = (link, name)

        #executes the instruction and commit
        cursor.execute(mySqlInsertProduct, recordProduct)

        connection.commit()
        print("Product Record inserted, ID:", cursor.lastrowid)

    except mysql.connector.Error as error:
            print("Failed to record Product {}".format(error))

def insertPrice(pricedb, avgrate): #DOESNT WORK
    try:
        mySqlInsertPrice = """INSERT INTO scan_history (price, ratings) VALUES (%s, %s) """
        recordPrice = (pricedb, avgrate)

        cursor.execute(mySqlInsertPrice, recordPrice)

        connection.commit()
        print("Current Price recorded")

    except mysql.connector.Error as error:
            print("Failed to record Price {}".format(error))

#executes the insert functions
insertProduct(link_shrt, product_name)
insertPrice(price_final, ratings)

if (connection.is_connected()):
    cursor.close()
    connection.close()
    print("MySQL connection is closed")
</code>```

It can successfully do insertProduct but fails at insertPrice

```<code>Failed to record Price 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`bp40_scraperDB`.`scan_history`, CONSTRAINT `scan_history_ibfk_1` FOREIGN KEY (`prod_IDfk`) REFERENCES `products_list` (`prod_IDpk`) ON UPDATE NO ACTION)
</code>```

I've tried resetting the AUTO_INCREMENT to begin at 1 and emptied both tables.
The insertProduct ran first and put prod_ID 1 in the primary key already, so I don't know what's wrong with it

Here are my tables
name and link indexes are just UNIQUE

this is the table with foreign key

答:
The primary key prod_IDpk in the product table also needs to be referenced as the foreign key prod_IDfk in the price table scan_history otherwise the price doesn't know what it is linking to.

You are getting back the product id at the line

```<code>print("Product Record inserted, ID:", cursor.lastrowid)

prod_ID = cursor.lastrowid
</code>```

Now pass that to the price insert to make the link

```<code>mySqlInsertPrice = """INSERT INTO scan_history (prod_IDfk, price, ratings) VALUES (%s, %s) """
recordPrice = (prod_ID, pricedb, avgrate)
</code>```

Body:
I have a python code that insert variables "link" and "name" into one table "pricedb" and "avgrate" into the other table

#insert product into product table
def insertProduct(link, name):
    try:
        #mySQL instruction to insert to link and name column
        mySqlInsertProduct =  """INSERT INTO products_list (link, name) VALUES (%s, %s) """
        recordProduct = (link, name)

        #executes the instruction and commit
        cursor.execute(mySqlInsertProduct, recordProduct)

        connection.commit()
        print("Product Record inserted, ID:", cursor.lastrowid)

    except mysql.connector.Error as error:
            print("Failed to record Product {}".format(error))

def insertPrice(pricedb, avgrate): #DOESNT WORK
    try:
        mySqlInsertPrice = """INSERT INTO scan_history (price, ratings) VALUES (%s, %s) """
        recordPrice = (pricedb, avgrate)

        cursor.execute(mySqlInsertPrice, recordPrice)

        connection.commit()
        print("Current Price recorded")

    except mysql.connector.Error as error:
            print("Failed to record Price {}".format(error))

#executes the insert functions
insertProduct(link_shrt, product_name)
insertPrice(price_final, ratings)

if (connection.is_connected()):
    cursor.close()
    connection.close()
    print("MySQL connection is closed")

It can successfully do insertProduct but fails at insertPrice

Failed to record Price 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`bp40_scraperDB`.`scan_history`, CONSTRAINT `scan_history_ibfk_1` FOREIGN KEY (`prod_IDfk`) REFERENCES `products_list` (`prod_IDpk`) ON UPDATE NO ACTION)

I've tried resetting the AUTO_INCREMENT to begin at 1 and emptied both tables.
The insertProduct ran first and put prod_ID 1 in the primary key already, so I don't know what's wrong with it

Here are my tables
name and link indexes are just UNIQUE

this is the table with foreign key

Body:
The primary key prod_IDpk in the product table also needs to be referenced as the foreign key prod_IDfk in the price table scan_history otherwise the price doesn't know what it is linking to.

You are getting back the product id at the line

print("Product Record inserted, ID:", cursor.lastrowid)

prod_ID = cursor.lastrowid

Now pass that to the price insert to make the link

mySqlInsertPrice = """INSERT INTO scan_history (prod_IDfk, price, ratings) VALUES (%s, %s) """
recordPrice = (prod_ID, pricedb, avgrate)


问:
How kill several subprocesses with the same name, with Python3
With Raspberry Pi and Python3 I get these subprocess:

ps -aux | grep python3

```<code>pi    4168  0.9  0.7  11088  7304 ?     S    18:31   0:00 python3 blue.py
pi    4175  1.2  0.7  11088  7300 ?     S    18:33   0:00 python3 blue.py
pi    4185  2.4  0.7  11092  7300 ?     S    18:35   0:00 python3 blue.py
pi    4195  6.5  0.7  11088  7300 ?     S    18:38   0:00 python3 green.py
</code>```

I need kill all python3 blue.py (from Python) and get...

ps -aux | grep python3

```<code>pi    4195  6.5  0.7  11088  7300 ?     S    18:38   0:00 python3 green.py
</code>```

答:
for centos7 i use

```<code>pkill -f "Process name"
</code>```

Body:
With Raspberry Pi and Python3 I get these subprocess:

ps -aux | grep python3

pi    4168  0.9  0.7  11088  7304 ?     S    18:31   0:00 python3 blue.py
pi    4175  1.2  0.7  11088  7300 ?     S    18:33   0:00 python3 blue.py
pi    4185  2.4  0.7  11092  7300 ?     S    18:35   0:00 python3 blue.py
pi    4195  6.5  0.7  11088  7300 ?     S    18:38   0:00 python3 green.py

I need kill all python3 blue.py (from Python) and get...

ps -aux | grep python3

pi    4195  6.5  0.7  11088  7300 ?     S    18:38   0:00 python3 green.py

Body:
for centos7 i use

pkill -f "Process name"


问:
Force to buy only predefined quantities at checkout in WooCommerce
My ecommerce made with WooCommerce sells 12 ready meals.
The customer can also purchase only 1 meal per type. But it must necessarily reach the exact sum of:

5 or 12 or 24 or 36 products.

Why?

Ready meals are shipped in isothermal boxes that contain a precise number of ready meals.

There are 4 types of isothermal boxes and they contain:

5 meals, 12 meals, 24 meals or 36 meals

So I have to force to buy only 5, 12, 24, or 36 meals at checkout on the cart page.

This figure can also be reached by adding for example 2 meals A + 3 meals B

The important thing is that if, for example, they try to buy 6 3A + 3B products, the checkout button disappears and an alarm comes out that says:

You can only purchase 5,12,24,36 meals.

答:
function checkout_validate() {
    // Only run in the Cart or Checkout pages
    if( is_cart() || is_checkout() ) {
        // Get number of items in the cart.
        $items_in_cart = WC()->cart->get_cart_contents_count();

        // Allowed amounts
        $allowed_amounts = array(5, 12, 24, 36);

        // If items in cart NOT equal to allowed amounts, show error message
        if ( !in_array( $items_in_cart, $allowed_amounts)) {
            wc_add_notice( __( 'Remember that you can only buy 5, 12, 24 or 36 meals. You have ' . $items_in_cart . ' maeals in your cart.', 'woocommerce' ), 'error' );
            remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
        }
    }
}
add_action( 'woocommerce_check_cart_items' , 'checkout_validate' );
```


问:
Compression of short strings
I am trying to compress short strings (max 15 characters).

The goal is to implement the "Normalized Compression Distance"[1], I tried a few compression algorithms in python (I also looked to se if i could do it in Julia but the packages all refuse to install).
I always obtain in the end a bit-string longer than the original string I am trying to compress which totally defeats the purpose.

An example with zlib :

```<code>import zlib
data = b"this is a test"

compressed_data = zlib.compress(data, 9)
print(len(data))
print(len(compressed_data))
</code>```

Which returns :

```<code>13
21
</code>```

Do you now what I am doing wrong, or how i could do this more efficiently ?

[1] : https://arxiv.org/pdf/cs/0312044.pdf

答:
Check out these libraries for compressing short strings:

https://github.com/siara-cc/unishox :

Unishox is a hybrid encoder (entropy, dictionary and delta coding). It works by assigning fixed prefix-free codes for each letter of the 95 letter printable Character Set (entropy coding). It encodes repeating letter sets separately (dictionary coding). For Unicode characters (UTF-8), delta coding is used. It also has special handling for repeating upper case and num pad characters.

Unishox was developed to save memory in embedded devices and compress strings stored in databases. It is used in many projects and has an extension for Sqlite database. Although it is slower than other available libraries, it works well for the given applications.

https://github.com/antirez/smaz :

Smaz was developed by Salvatore Sanfilipo and it compresses strings by replacing parts of it using a codebook. This was the first one available for compressing short strings as far as I know.

https://github.com/Ed-von-Schleck/shoco :

shoco was written by Christian Schramm. It is an entropy encoder, because the length of the representation of a character is determined by the probability of encountering it in a given input string.

It has a default model for English language and a provision to train new models based on given sample text.

PS: Unishox was developed by me and its working principle is explained in this article:

Title: Compression of short strings

Body:
I am trying to compress short strings (max 15 characters).

The goal is to implement the "Normalized Compression Distance"[1], I tried a few compression algorithms in python (I also looked to se if i could do it in Julia but the packages all refuse to install).
I always obtain in the end a bit-string longer than the original string I am trying to compress which totally defeats the purpose.

An example with zlib :

import zlib
data = b"this is a test"

compressed_data = zlib.compress(data, 9)
print(len(data))
print(len(compressed_data))

Which returns :

13
21

Do you now what I am doing wrong, or how i could do this more efficiently ?

[1] : https://arxiv.org/pdf/cs/0312044.pdf


问:
How to exclude sub type in the hybris flexible search
In hybris, I have Created ArchivalOrderModel extends orderModel

Moved Data from OrderModel To ArchivalOrderModel. (Deleted Record from OrderModel)

When I fired query

```<code>select {pk} from {order}
</code>```

In result Im getting Records of ArchivalOrderModel too.

Is there any way to restrict with help of data Modeling definition or Any other suggestion for archival

答:
When we search any type, by default its subtypes will also be retrieved in the result.

If you want to exclude the subtype, you must use the exclamation mark (!) while specifying the type in the query like this.

```<code>Select * from {Order!}
</code>```

Body:
In hybris, I have Created ArchivalOrderModel extends orderModel

Moved Data from OrderModel To ArchivalOrderModel. (Deleted Record from OrderModel)

When I fired query

select {pk} from {order}

In result Im getting Records of ArchivalOrderModel too.

Is there any way to restrict with help of data Modeling definition or Any other suggestion for archival

Body:
When we search any type, by default its subtypes will also be retrieved in the result.

If you want to exclude the subtype, you must use the exclamation mark (!) while specifying the type in the query like this.

Select * from {Order!}


问:
How to select a checkbox based on an datalist option selected (different pages)
I will try to be clear: I have two html, one where I have the form and the other the checkboxes, I would like that it depends on the values that are put in the html of the form (I don't know if it's right to call it that way), some checkboxes appear check or others.

For example,

if i select 'Desserts' and I click on the 'go' button I will go to the
  other page, where the checkboxes are, so 'Desserts' checkbox will
  appear checked.

I tried to do many thing but nope.
Thank you so much!

HTML 1:

```<code>   <table id="CategoriesTable">
      <tr>
        <td>
        <form id="categoriesForm" method="POST">
        <input type="text" id = "categoriesList" list="categorieslist" name="categories-scroll"     placeholder="Type a category.." style="border-radius: 0.5rem;border-width: 0.5px;">
          <datalist id="categoriesDatalist">
            <option data-value="Desserts"></option>
            <option data-value="Starters"></option>
            <option data-value="Main"></option>
            <option data-value="Soups"></option>
            <option data-value="Salad"></option>
            <option data-value="Burgers"></option>
          </datalist>
        </form>
      </td>
      <td>
      <button id ="go-button" class="btn btn-primary" data-dismiss="modal">
        <h6 class="text">Go!</h6>
        <img class="img-fluid rounded" src="../images/icons/pizza-go.png" alt="" width="50%" style="height:   50px; width: 50px;">
      </button>
      </td>
     </tr>
    </table>
</code>```

HTML 2:

```<code> <h5 class="card-header">Categories</h5>
          <div class="containersearch">
            <ul class="ks-cboxtags">
              <li><input type="checkbox" id="checkbox9" value="Desserts"><label for="checkbox9">Desserts</label></li>
              <li><input type="checkbox" id="checkbox10" value="Starters" ><label for="checkbox10">Starters</label></li>
              <li><input type="checkbox" id="checkbox11" value="Main" ><label for="checkbox11">Main</label></li>
              <li><input type="checkbox" id="checkbox12" value="Soups"><label for="checkbox12">Soups</label></li>
              <li><input type="checkbox" id="checkbox13" value="Salad"><label for="checkbox13">Salad</label></li>
              <li><input type="checkbox" id="checkbox14" value="Burgers"><label for="checkbox14">Burgers</label></li>
</div>
</code>```

答:
When you land on second html-page, run a small javascript code,

for example you selected Desert from the dropdown and passed this to second page.
On second page:

first you read all the checkbox available,

Loop through all the checkbox and compare the value of the checkbox is equals to the value received from page1. i.e (Desert)

If you find the match, then just set the property checked as true for that checkbox.

script will look like:

const allCheckBox = document.querySelectorAll(".ks-cboxtags input");

allCheckBox.forEach((c) => {
    if (c.value === "Desserts") {
        c.checked = true;
    }
})
```

Body:
I will try to be clear: I have two html, one where I have the form and the other the checkboxes, I would like that it depends on the values that are put in the html of the form (I don't know if it's right to call it that way), some checkboxes appear check or others.

For example,

if i select 'Desserts' and I click on the 'go' button I will go to the
  other page, where the checkboxes are, so 'Desserts' checkbox will
  appear checked.

I tried to do many thing but nope.
Thank you so much!

HTML 1:

        <form id="categoriesForm" method="POST">
        <input type="text" id = "categoriesList" list="categorieslist" name="categories-scroll"     placeholder="Type a category.." style="border-radius: 0.5rem;border-width: 0.5px;">
          <datalist id="categoriesDatalist">
            <option data-value="Desserts"></option>
            <option data-value="Starters"></option>
            <option data-value="Main"></option>
            <option data-value="Soups"></option>
            <option data-value="Salad"></option>
            <option data-value="Burgers"></option>
          </datalist>
        </form>

      <button id ="go-button" class="btn btn-primary" data-dismiss="modal">

Go!

      </button>

HTML 2:

Categories

<input type="checkbox" id="checkbox9" value="Desserts">Desserts

<input type="checkbox" id="checkbox10" value="Starters" >Starters

<input type="checkbox" id="checkbox11" value="Main" >Main

<input type="checkbox" id="checkbox12" value="Soups">Soups

<input type="checkbox" id="checkbox13" value="Salad">Salad

<input type="checkbox" id="checkbox14" value="Burgers">Burgers


问:
Install Laravel using Composer
I'm trying to install Laravel using Composer, but after running the following command

```<code>composer create-project laravel/laravel cmsLaravel 5.2
</code>```

pointing to my c/xampp/htddocs directory, I get the error below:

C:\xampp\htdocs\laravelCMS\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\laravelCMS\bootstrap\autoload.php on line 17

答:
```<code>composer create-project laravel/laravel 6.0
</code>```

composer is a tool for dependency management in PHP

create-project is command to create a new laravel project

laravel/laravel is for the skeleton application you get when creating a new project. It provides a default structure that's recommended (you're not forced to use it). The repository contains default config files, controllers, routes, etc. As well as code responsible for bootstrapping the application.

Link Laravel/laravel

6.0 Version in laravel

ContentLicense: CC BY-SA 3.0

Title: Install Laravel using Composer

Body:
I'm trying to install Laravel using Composer, but after running the following command

composer create-project laravel/laravel cmsLaravel 5.2

pointing to my c/xampp/htddocs directory, I get the error below:

C:\xampp\htdocs\laravelCMS\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in C:\xampp\htdocs\laravelCMS\bootstrap\autoload.php on line 17

Body:
composer create-project laravel/laravel 6.0

composer is a tool for dependency management in PHP

create-project is command to create a new laravel project

laravel/laravel is for the skeleton application you get when creating a new project. It provides a default structure that's recommended (you're not forced to use it). The repository contains default config files, controllers, routes, etc. As well as code responsible for bootstrapping the application.

Link Laravel/laravel

6.0 Version in laravel


问:
Syntax for if/else condition in SCSS mixins
I created a SASS @mixin which contains @if conditions to assign styling to elements based on their z-index property to create some sort of elevation.

However what ever I am trying it will not work out.

I'm pretty sure I am doing something just slightly wrong that affects everything else.

I'd appreciate your feedback. Thanks in advance!

```<code>    $background: #121212;
    $surface: #1f1f1f;
    $surface-shade_1: #282828;
    $surface-shade_2: #303030;
    %surface {
      background-color: $surface;
    }

    %surface-shade_1 {
      background-color: $surface-shade_1;
    }

    %surface-shade_2 {
      background-color: $surface-shade_2;
    }

    @mixin elevation($elevationValue) {
      @if $elevationValue>0 {
        @extend %surface;
      }
      @else if $elevationValue>4 or $elevationValue=4 {
        @extend %surface-shade_1;
      }
      @else if $elevationValue>8 or $elevationValue=8 {
        @extend %surface-shade_2;
      }
      z-index: $elevationValue * 50;
    }

    nav {
      @mixin elevation(4);
    }
</code>```

答:
If you want to use @mixin inside the CSS files you can use like @include mixin-name and also use directly $elevationValue >= 4 instead of $elevationValue>4 or $elevationValue=4 it becomes much cleaner.

```<code>$background: #121212;
$surface: #1f1f1f;
$surface-shade_1: #282828;
$surface-shade_2: #303030;
%surface {
  background-color: $surface;
}

%surface-shade_1 {
  background-color: $surface-shade_1;
}

%surface-shade_2 {
  background-color: $surface-shade_2;
}

@mixin elevation($elevationValue) {
  @if $elevationValue > 0 {
    @extend %surface;
  }
  @else if $elevationValue >= 4 {
    @extend %surface-shade_1;
  }
  @else if $elevationValue >= 8 {
    @extend %surface-shade_2;
  }
  z-index: $elevationValue * 50;
}

nav {
  @include elevation(4);
}
</code>```

Body:
I created a SASS @mixin which contains @if conditions to assign styling to elements based on their z-index property to create some sort of elevation.

However what ever I am trying it will not work out.

I'm pretty sure I am doing something just slightly wrong that affects everything else.

I'd appreciate your feedback. Thanks in advance!

    $background: #121212;
    $surface: #1f1f1f;
    $surface-shade_1: #282828;
    $surface-shade_2: #303030;
    %surface {
      background-color: $surface;
    }

    %surface-shade_1 {
      background-color: $surface-shade_1;
    }

    %surface-shade_2 {
      background-color: $surface-shade_2;
    }

    @mixin elevation($elevationValue) {
      @if $elevationValue>0 {
        @extend %surface;
      }
      @else if $elevationValue>4 or $elevationValue=4 {
        @extend %surface-shade_1;
      }
      @else if $elevationValue>8 or $elevationValue=8 {
        @extend %surface-shade_2;
      }
      z-index: $elevationValue * 50;
    }

    nav {
      @mixin elevation(4);
    }

Body:
If you want to use @mixin inside the CSS files you can use like @include mixin-name and also use directly $elevationValue >= 4 instead of $elevationValue>4 or $elevationValue=4 it becomes much cleaner.

$background: #121212;
$surface: #1f1f1f;
$surface-shade_1: #282828;
$surface-shade_2: #303030;
%surface {
  background-color: $surface;
}

%surface-shade_1 {
  background-color: $surface-shade_1;
}

%surface-shade_2 {
  background-color: $surface-shade_2;
}

@mixin elevation($elevationValue) {
  @if $elevationValue > 0 {
    @extend %surface;
  }
  @else if $elevationValue >= 4 {
    @extend %surface-shade_1;
  }
  @else if $elevationValue >= 8 {
    @extend %surface-shade_2;
  }
  z-index: $elevationValue * 50;
}

nav {
  @include elevation(4);
}


问:
phpmailer and gmail SMTP ERROR: Failed to connect to server: Network is unreachable (101) SMTP connect() failed
I need help please
this is my code:

```<code>require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;

$mail->SMTPSecure = "tls";
$mail->Port = 587;

$mail->Username = 'some@gmail.com';
$mail->Password = 'somepass';
$mail->addAddress('another@gmail.com', 'Josh Adams');
$mail->Subject = 'PHPMailer GMail SMTP test';
$body = 'This is the HTML message body in bold!';
$mail->MsgHTML($body);
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}
</code>```

and I get this error:
2013-12-11 15:15:02 SMTP ERROR: Failed to connect to server: Network is unreachable (101) SMTP connect() failed. Mailer Error: SMTP connect() failed.

any help please?

答:
This worked for me:

change:

```<code>  $mail->SMTPSecure = 'ssl';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '465';
</code>```

to

```<code>  $mail->SMTPSecure = 'tls';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '587';
</code>```

Body:
I need help please
this is my code:

require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;

$mail->SMTPSecure = "tls";
$mail->Port = 587;

$mail->Username = 'some@gmail.com';
$mail->Password = 'somepass';
$mail->addAddress('another@gmail.com', 'Josh Adams');
$mail->Subject = 'PHPMailer GMail SMTP test';
$body = 'This is the HTML message body in bold!';
$mail->MsgHTML($body);
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

and I get this error:
2013-12-11 15:15:02 SMTP ERROR: Failed to connect to server: Network is unreachable (101) SMTP connect() failed. Mailer Error: SMTP connect() failed.

any help please?

Body:
This worked for me:

change:

  $mail->SMTPSecure = 'ssl';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '465';

to

  $mail->SMTPSecure = 'tls';
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = '587';


问:
Changing font from "System" to another preinstalled font?
According to Apple, iOS comes with several preinstalled fonts:

https://developer.apple.com/fonts/system-fonts/#preinstalled

I would like to use one of them as opposed to the System font that I seem to be stuck with. The problem is that the Attribute menu of a Label or Button only allows me to select System or System Italic.

How can I use another preinstalled font?

答: You should select Custom font then you will be giving a list of Family where you can select more fonts.


问:
KeyListener stops working after clicking canvas
I'm having simple KeyHandler

```<code>public class KeyHandler implements KeyListener {
    private final Set<Integer> keyEvents = new LinkedHashSet<>();
    public Set<Integer> pressedKeys() {
        return keyEvents;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        keyEvents.add(e.getKeyCode());
    }

    @Override
    public void keyReleased(KeyEvent e) {
        keyEvents.remove(e.getKeyCode());
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
}
</code>```

Which is added to JFrame

frame.addKeyListener(keyListener);

Rest is probably irrevelant, but I'm passing same instance to KeyBinder

```<code>public class KeyBinder {
    private final Map<Integer, GameEvent> bindings = new HashMap<>();
    private final KeyHandler keyHandler;

    public KeyBinder(KeyHandler keyHandler) {
        this.keyHandler = keyHandler;
        bindings.put(KeyEvent.VK_A, MoveEvent.MOVE_LEFT);
        bindings.put(KeyEvent.VK_D, MoveEvent.MOVE_RIGHT);
        bindings.put(KeyEvent.VK_S, MoveEvent.MOVE_DOWN);
        bindings.put(KeyEvent.VK_W, MoveEvent.MOVE_UP);
    }

    public List<GameEvent> mapEvents() {
        final var events = new ArrayList<GameEvent>();
        keyHandler.pressedKeys().forEach(key -> events.add(bindings.get(key)));
        return events;
    }
}
</code>```

And then, I'm passing those GameEvents into Player instance to make him move

```<code>@Override
public void update(java.util.List<GameEvent> events) {
    events.forEach(this::handleEvent);
}

private void handleEvent(GameEvent event) {
    if (event instanceof MoveEvent) {
        updatePosition((MoveEvent) event);
    }
}

private void updatePosition(MoveEvent event) {
    switch (event) {
        case MOVE_UP -> position = new Position(position.getX(), position.getY() - speed);
        case MOVE_DOWN -> position = new Position(position.getX(), position.getY() + speed);
        case MOVE_RIGHT -> position = new Position(position.getX() + speed, position.getY());
        case MOVE_LEFT -> position = new Position(position.getX() - speed, position.getY());
    }
}
</code>```

It works perfectly fine if I'm running single instance of my application. But since, that is intend to be online game, I want to run 2 instances at same time for test purposes. Unfortunatelly, one I start second instance, my KeyHandler isn't working anymore in any of them, it just dont record any KeyEvents. I know my application is stil running because my server application keeps on receiving data from both clients.

Edit:

I just realized that something else is an issue. KeyHandler stops working once I click canvas... I dont even need second instance of my application. Here is the code of JFrame and Canvas I'm using to draw things...

```<code> public class Display {
        private JFrame frame;
        private Canvas canvas;

        public Display(KeyListener keyListener) {
            initFrame(keyListener);
            initCanvas();
            frame.add(canvas);
            frame.pack();
        }

        private void initFrame(KeyListener keyListener) {
            frame = new JFrame(GameConfig.TITLE);
            frame.setSize(GameConfig.SCREEN_WIDTH, GameConfig.SCREEN_HEIGHT);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            frame.addKeyListener(keyListener);
        }

        private void initCanvas() {
            canvas = new Canvas();
            canvas.setPreferredSize(new Dimension(GameConfig.SCREEN_WIDTH, GameConfig.SCREEN_HEIGHT));
            canvas.setMaximumSize(new Dimension(GameConfig.SCREEN_WIDTH, GameConfig.SCREEN_HEIGHT));
            canvas.setMinimumSize(new Dimension(GameConfig.SCREEN_WIDTH, GameConfig.SCREEN_HEIGHT));
        }

        public Canvas getCanvas() {
            return canvas;
        }
    }
</code>```

答:
The reason your keylistener isn't listening to any keyevents is because KeyListeners only work when the component has focus. It seems like when you click on the canvas, the canvas is now the owner of the focus, therefore the frame isn't focused anymore.

Generally, I'd suggest using Key Bindings for this. Key bindings can listen to keyevents even when your component isn't focused. But if you want to keep using KeyListeners, here are two solutions:

Add a FocusListener to the frame.

```<code>    frame.addFocusListener(new FocusListener() {
            public void focusGained(FocusEvent e) {}
            public void focusLost(FocusEvent e) {frame.requestFocus();}
    });
</code>```

Disable the focusability of canvas.

```<code>    canvas.setFocusable(false);
</code>```

These solutions are not recommended, but it should do the job for your case.

Body:
I'm having simple KeyHandler

public class KeyHandler implements KeyListener {
    private final Set<Integer> keyEvents = new LinkedHashSet<>();
    public Set<Integer> pressedKeys() {
        return keyEvents;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        keyEvents.add(e.getKeyCode());
    }

    @Override
    public void keyReleased(KeyEvent e) {
        keyEvents.remove(e.getKeyCode());
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
}

Which is added to JFrame

frame.addKeyListener(keyListener);

Rest is probably irrevelant, but I'm passing same instance to KeyBinder

public class KeyBinder {
    private final Map<Integer, GameEvent> bindings = new HashMap<>();
    private final KeyHandler keyHandler;

    public KeyBinder(KeyHandler keyHandler) {
        this.keyHandler = keyHandler;
        bindings.put(KeyEvent.VK_A, MoveEvent.MOVE_LEFT);
        bindings.put(KeyEvent.VK_D, MoveEvent.MOVE_RIGHT);
        bindings.put(KeyEvent.VK_S, MoveEvent.MOVE_DOWN);
        bindings.put(KeyEvent.VK_W, MoveEvent.MOVE_UP);
    }

    public List<GameEvent> mapEvents() {
        final var events = new ArrayList<GameEvent>();
        keyHandler.pressedKeys().forEach(key -> events.add(bindings.get(key)));
        return events;
    }
}

And then, I'm passing those GameEvents into Player instance to make him move

@Override
public void update(java.util.List<GameEvent> events) {
    events.forEach(this::handleEvent);
}

private void handleEvent(GameEvent event) {
    if (event instanceof MoveEvent) {
        updatePosition((MoveEvent) event);
    }
}

private void updatePosition(MoveEvent event) {
    switch (event) {
        case MOVE_UP -> position = new Position(position.getX(), position.getY() - speed);
        case MOVE_DOWN -> position = new Position(position.getX(), position.getY() + speed);
        case MOVE_RIGHT -> position = new Position(position.getX() + speed, position.getY());
        case MOVE_LEFT -> position = new Position(position.getX() - speed, position.getY());
    }
}

It works perfectly fine if I'm running single instance of my application. But since, that is intend to be online game, I want to run 2 instances at same time for test purposes. Unfortunatelly, one I start second instance, my KeyHandler isn't working anymore in any of them, it just dont record any KeyEvents. I know my application is stil running because my server application keeps on receiving data from both clients.

Edit:

I just realized that something else is an issue. KeyHandler stops working once I click canvas... I dont even need second instance of my application. Here is the code of JFrame and Canvas I'm using to draw things...

 public class Display {
        private JFrame frame;
        private Canvas canvas;

        public Display(KeyListener keyListener) {
            initFrame(keyListener);
            initCanvas();
            frame.add(canvas);
            frame.pack();
        }

        private void initFrame(KeyListener keyListener) {
            frame = new JFrame(GameConfig.TITLE);
            frame.setSize(GameConfig.SCREEN_WIDTH, GameConfig.SCREEN_HEIGHT);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            frame.addKeyListener(keyListener);
        }

        private void initCanvas() {
            canvas = new Canvas();
            canvas.setPreferredSize(new Dimension(GameConfig.SCREEN_WIDTH, GameConfig.SCREEN_HEIGHT));
            canvas.setMaximumSize(new Dimension(GameConfig.SCREEN_WIDTH, GameConfig.SCREEN_HEIGHT));
            canvas.setMinimumSize(new Dimension(GameConfig.SCREEN_WIDTH, GameConfig.SCREEN_HEIGHT));
        }

        public Canvas getCanvas() {
            return canvas;
        }
    }

Body:
The reason your keylistener isn't listening to any keyevents is because KeyListeners only work when the component has focus. It seems like when you click on the canvas, the canvas is now the owner of the focus, therefore the frame isn't focused anymore.

Generally, I'd suggest using Key Bindings for this. Key bindings can listen to keyevents even when your component isn't focused. But if you want to keep using KeyListeners, here are two solutions:

Add a FocusListener to the frame.

    frame.addFocusListener(new FocusListener() {
            public void focusGained(FocusEvent e) {}
            public void focusLost(FocusEvent e) {frame.requestFocus();}
    });

Disable the focusability of canvas.

    canvas.setFocusable(false);

These solutions are not recommended, but it should do the job for your case.


问:
Implementing GL_REPEAT on shader
I'm trying to implement GL_REPEAT on glsl. I wrote something using the mod function but there's a problem where the two textures combine. Could you explain why it doesn't work right?

in main:

```<code>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
</code>```

my shader code looks like this:

```<code>in vec2 TextureCoord;

float yCoord = mod(TextureCoord.y + 0.5, 1.0);
emission = texture(material.emission,vec2(TextureCoord.x, yCoord)).rgb;

//result
vec3 result = emission;
FragColor = vec4(result, 1.0f);
</code>```

答:
The wrap mode is honored during texture filtering. You set the GL_LINEAR filter mode, hence it will always use a 2x2 texel footprint. If that footprint happens to be at the border, the selected wrap mode will apply to selecting each individual texel. In your case, if you get near the border, you told it to filter into the textrue border color, which a filter with GL_REPEAT wrap mode never would have done, it would have used the texel data from the opposing border instead.

So if you want to re-implement that manually in the shader, you must also implement the texel selection and the filtering itself. Since you also use mipmapping, doing so will be quite complex, and slow.

Title: Implementing GL_REPEAT on shader

Body:
I'm trying to implement GL_REPEAT on glsl. I wrote something using the mod function but there's a problem where the two textures combine. Could you explain why it doesn't work right?

in main:

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

my shader code looks like this:

in vec2 TextureCoord;

float yCoord = mod(TextureCoord.y + 0.5, 1.0);
emission = texture(material.emission,vec2(TextureCoord.x, yCoord)).rgb;

//result
vec3 result = emission;
FragColor = vec4(result, 1.0f);


问:
Background color theme problems
I have a problem with background on activities and fragments when I use background in App theme:

```<code><item name="android:colorBackground">@android:color/white</item>
<item name="android:windowBackground">@android:color/white</item>
</code>```

When I put this on my theme and navigate between fragments with animation make a strange shadow:

This is normal?
I have a transaction animation between fragments:

```<code>//add fragment
supportFragmentManager.beginTransaction().setCustomAnimations(
    R.anim.enter,
    R.anim.exit,
    R.anim.pop_enter,
    R.anim.pop_exit
).replace(R.id.fragment_container,fragmentToShow)
 .addToBackStack(null).commit()
</code>```

If I remove the animation fragment, shadow overlap previous fragment (is worst then the animation is not the problem):

All base theme app is:

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

    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowLightStatusBar" tools:ignore="NewApi">true</item>
    <item name="android:statusBarColor" tools:targetApi="lollipop">@android:color/transparent</item>

    <item name="windowActionBarOverlay">true</item>

    <item name="colorControlNormal">@color/secondaryColor</item>
    <item name="android:colorBackground">@android:color/white</item>

    <!-- Styles of text -->
    <item name="android:textColor">@color/colorText</item>
    <item name="android:textSize">18sp</item>
    <item name="android:fontFamily">@font/montserrat_regular</item>

    <!-- CheckBox style -->
    <item name="android:checkboxStyle">@style/MyCheckBoxStyle</item>

    <!-- styles of button -->
    <item name="android:textAllCaps">false</item>

</style>
</code>```

The shadows disappear after seconds in both cases...
Can you help me, please?

答:
try this,

apply background color white to your fragment's parent layout

Title: Background color theme problems

Body:
I have a problem with background on activities and fragments when I use background in App theme:

<item name="android:colorBackground">@android:color/white</item>
<item name="android:windowBackground">@android:color/white</item>

When I put this on my theme and navigate between fragments with animation make a strange shadow:

This is normal?
I have a transaction animation between fragments:

//add fragment
supportFragmentManager.beginTransaction().setCustomAnimations(
    R.anim.enter,
    R.anim.exit,
    R.anim.pop_enter,
    R.anim.pop_exit
).replace(R.id.fragment_container,fragmentToShow)
 .addToBackStack(null).commit()

If I remove the animation fragment, shadow overlap previous fragment (is worst then the animation is not the problem):

All base theme app is:

The shadows disappear after seconds in both cases...
Can you help me, please?


问:
Iterate through dictionary with foreach loop and fetch all key/value pairs with value subset items
I have a concurrent dictionary that I am storing key/value pairs in. The complexity here is that the values are not single objects like string or integer, they are a collection of items that are added using a class model. It seems looking at the debug, I am able to add the items to the dictionary successfully, but the issue I have is not knowing how to read these items when iterating through the dictionary from another thread. I simply want to read all the key/value pairs, including all the items and add them to an array that I can pass back to the user through JsonResult/Ajax.

My AlarmEngine Class:

```<code>public static ConcurrentDictionary<string, object> concurrentDictionary = new ConcurrentDictionary<string, object>();

public class Alarm
{
    public int AlarmId { get; set; }
    public string AlarmName { get; set; }
    public string AlarmDescription { get; set; }
    public string ApplicationRoleId { get; set; }
    public DateTime DateTimeActivated { get; set; }
}
</code>```

An extract from the method where I add items to the dictionary:

```<code>concurrentDictionary.TryAdd(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), new Alarm
                {
                    DateTimeActivated = DateTime.Now,
                    ApplicationRoleId = applicationRoleId,
                    AlarmId = alarmId,
                    AlarmName = alarmName,
                    AlarmDescription = description,
                }); // I'm using datetime as the key as this is unique form each key/value pair added.
</code>```

My AlarmList MVC Controller:

```<code>[HttpGet]
public Task<IActionResult> FetchAlarmsListAsync()
{

    // Enumeration is thread-safe in ConcurrentDictionary.
    foreach (var item in AlarmEngine.concurrentDictionary)
    {
        // How do I access the key and value pairs here?
        // Note each value contains a subset of items
        // i want to access all items stored
    }

    return new JsonResult(Array containing all keys and value items);
}
</code>```

If it's better to read through the whole dictionary and store all keys/value(with sub items) to a list before returning to the user as an JSON array, this would be an acceptable solution for me as well, just keep in mind I want to do this as efficiently as possible to minimize converting from one form to another too many times. Items will be added and removed to the dictionary from other threads, but this particular bit of my application i.e. iteration through the dictionary is just for readonly purposes and it doesn't really matter to me if the contents have changed whilst reading through it, it's just to put together a list of alarms relevant/active at the time of the query.

答:
You need to store the data as the right class, do not use object

```<code>public static ConcurrentDictionary<string, Alarm> concurrentDictionary = new ConcurrentDictionary<string, Alarm>();
//                                          ^^^

public class Alarm
{
    public int AlarmId { get; set; }
    public string AlarmName { get; set; }
    public string AlarmDescription { get; set; }
    public string ApplicationRoleId { get; set; }
    public DateTime DateTimeActivated { get; set; }
}
</code>```

Now you can access the properties of the alarm.

```<code>// Enumeration is thread-safe in Dictionary.
foreach (var item in AlarmEngine.concurrentDictionary)
{
    Trace.WriteLine(item.Key);  // which is the datetime
    Trace.WriteLine(item.Value.AlarmName);
    // How do I access the key and value pairs here?
    // Note each value contains a subset of items
    // i want to access all items stored
}
</code>```

One thing you should change is not storing the DateTime as string.

```<code>public static ConcurrentDictionary<DateTime, Alarm> concurrentDictionary = new ConcurrentDictionary<DateTime, Alarm>();
</code>```

Body:
I have a concurrent dictionary that I am storing key/value pairs in. The complexity here is that the values are not single objects like string or integer, they are a collection of items that are added using a class model. It seems looking at the debug, I am able to add the items to the dictionary successfully, but the issue I have is not knowing how to read these items when iterating through the dictionary from another thread. I simply want to read all the key/value pairs, including all the items and add them to an array that I can pass back to the user through JsonResult/Ajax.

My AlarmEngine Class:

public static ConcurrentDictionary<string, object> concurrentDictionary = new ConcurrentDictionary<string, object>();

public class Alarm
{
    public int AlarmId { get; set; }
    public string AlarmName { get; set; }
    public string AlarmDescription { get; set; }
    public string ApplicationRoleId { get; set; }
    public DateTime DateTimeActivated { get; set; }
}

An extract from the method where I add items to the dictionary:

concurrentDictionary.TryAdd(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), new Alarm
                {
                    DateTimeActivated = DateTime.Now,
                    ApplicationRoleId = applicationRoleId,
                    AlarmId = alarmId,
                    AlarmName = alarmName,
                    AlarmDescription = description,
                }); // I'm using datetime as the key as this is unique form each key/value pair added.

My AlarmList MVC Controller:

[HttpGet]
public Task<IActionResult> FetchAlarmsListAsync()
{

    // Enumeration is thread-safe in ConcurrentDictionary.
    foreach (var item in AlarmEngine.concurrentDictionary)
    {
        // How do I access the key and value pairs here?
        // Note each value contains a subset of items
        // i want to access all items stored
    }

    return new JsonResult(Array containing all keys and value items);
}

If it's better to read through the whole dictionary and store all keys/value(with sub items) to a list before returning to the user as an JSON array, this would be an acceptable solution for me as well, just keep in mind I want to do this as efficiently as possible to minimize converting from one form to another too many times. Items will be added and removed to the dictionary from other threads, but this particular bit of my application i.e. iteration through the dictionary is just for readonly purposes and it doesn't really matter to me if the contents have changed whilst reading through it, it's just to put together a list of alarms relevant/active at the time of the query.

Body:
You need to store the data as the right class, do not use object

public static ConcurrentDictionary<string, Alarm> concurrentDictionary = new ConcurrentDictionary<string, Alarm>();
//                                          ^^^

public class Alarm
{
    public int AlarmId { get; set; }
    public string AlarmName { get; set; }
    public string AlarmDescription { get; set; }
    public string ApplicationRoleId { get; set; }
    public DateTime DateTimeActivated { get; set; }
}

Now you can access the properties of the alarm.

// Enumeration is thread-safe in Dictionary.
foreach (var item in AlarmEngine.concurrentDictionary)
{
    Trace.WriteLine(item.Key);  // which is the datetime
    Trace.WriteLine(item.Value.AlarmName);
    // How do I access the key and value pairs here?
    // Note each value contains a subset of items
    // i want to access all items stored
}

One thing you should change is not storing the DateTime as string.

public static ConcurrentDictionary<DateTime, Alarm> concurrentDictionary = new ConcurrentDictionary<DateTime, Alarm>();


问:
Array of directory tree node.js
I am trying to generate a directory tree into an array using node js. Output would be:

```<code>[ __Dirname [array of sub directories] ]
["FolderA"[ ["SubFolderA",[]] ]], ["FolderB",[]]
</code>```

```<code>function readDir(dir){
   fs.readdir(dir, function(err, files){
      for(var i=0;i<files.length;i++){
        (function(j){
          fs.stat(files[j], function(err, stats){
            if(stats.isDirectory()){
              readDir(files[j]);
            }
          });
        }
      }
   });
}
</code>```

If you know an easier way to do this please inform me. All I need is a list of directories and all their sub directories recursively.

答:
You can try this module:

npm dree

There are lots of custom options, a result could be this:

```<code>{
  "name": "sample",
  "path": "D:/Github/dree/test/sample",
  "relativePath": ".",
  "type": "directory",
  "size": "1.81 MB",
  "children": [
    {
      "name": "backend",
      "path": "D:/Github/dree/test/sample/backend",
      "relativePath": "backend",
      "type": "directory",
      "size": "1.79 MB",
      "children": [
        {
          "name": "firebase.json",
          "path": "D:/Github/dree/test/sample/backend/firebase.json",
          "relativePath": "backend/firebase.json",
          "type": "file",
          "extension": "json",
          "size": "29 B"
        },
        {
          "name": "server",
          "path": "D:/Github/dree/test/sample/backend/server",
          "relativePath": "backend/server",
          "type": "directory",
          "size": "1.79 MB",
          "children": [
            {
              "name": "server.js",
              "path": "D:/Github/dree/test/sample/backend/server/server.js",
              "relativePath": "backend/server/server.js",
              "type": "file",
              "extension": "js",
              "size": "1.81 MB"
            }
          ]
        }
      ]
    }
  ]
}
</code>```

Even a string could be returned, like this:

```<code>sample
 └─> backend
     ├── firebase.json
     ├── hello.txt
     └─> server
         └── server.js
</code>```

You can use it to get an object structure of the directory tree and then convert it to an array.

This codesandbox has the solution (see the solution.js file):

Title: Array of directory tree node.js

Body:
I am trying to generate a directory tree into an array using node js. Output would be:

[ __Dirname [array of sub directories] ]
["FolderA"[ ["SubFolderA",[]] ]], ["FolderB",[]]

function readDir(dir){
   fs.readdir(dir, function(err, files){
      for(var i=0;i<files.length;i++){
        (function(j){
          fs.stat(files[j], function(err, stats){
            if(stats.isDirectory()){
              readDir(files[j]);
            }
          });
        }
      }
   });
}

If you know an easier way to do this please inform me. All I need is a list of directories and all their sub directories recursively.

Body:
You can try this module:

npm dree

There are lots of custom options, a result could be this:

{
  "name": "sample",
  "path": "D:/Github/dree/test/sample",
  "relativePath": ".",
  "type": "directory",
  "size": "1.81 MB",
  "children": [
    {
      "name": "backend",
      "path": "D:/Github/dree/test/sample/backend",
      "relativePath": "backend",
      "type": "directory",
      "size": "1.79 MB",
      "children": [
        {
          "name": "firebase.json",
          "path": "D:/Github/dree/test/sample/backend/firebase.json",
          "relativePath": "backend/firebase.json",
          "type": "file",
          "extension": "json",
          "size": "29 B"
        },
        {
          "name": "server",
          "path": "D:/Github/dree/test/sample/backend/server",
          "relativePath": "backend/server",
          "type": "directory",
          "size": "1.79 MB",
          "children": [
            {
              "name": "server.js",
              "path": "D:/Github/dree/test/sample/backend/server/server.js",
              "relativePath": "backend/server/server.js",
              "type": "file",
              "extension": "js",
              "size": "1.81 MB"
            }
          ]
        }
      ]
    }
  ]
}

Even a string could be returned, like this:

sample
 └─> backend
     ├── firebase.json
     ├── hello.txt
     └─> server
         └── server.js

You can use it to get an object structure of the directory tree and then convert it to an array.

This codesandbox has the solution (see the solution.js file):


问:
Keras/Tensorflow - Generate predictions in batch for imagenet (I get only one result back)
I am generating imagenet tags for all keyframes in a video with a single call and have this code:

```<code> # all keras/tf/mobilenet imports
model_imagenet = MobileNetV2(weights='imagenet')

frames_list = []
for frame in frame_set:
    frame_img = frame.to_image()
    frame_pil = frame_img.resize((224,224), Image.ANTIALIAS)
    ts = int(frame.pts)
    x = image.img_to_array(frame_pil)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    frames_list.append(x)

print(len(frames_list))

preds_list = model_imagenet.predict_on_batch(frames_list)
print("[*]",preds_list)
</code>```

The result appears thus:

```<code>frames_list count: 125
</code>```

and the predictions thus, one row of 1000 dimensions (imagenet classes), shouldn't it be 125 rows?:

```<code>[[1.15425530e-04 1.83317825e-04 4.28701424e-05 2.87547664e-05
                    :
  7.91769926e-05 1.30803732e-04 4.81895368e-05 3.06891889e-04]]
</code>```

This is generating prediction for a single row in the batch. I have tried both predict and predict_on_batch with the same result.

How can I get a bulk prediction for say 200 frames at one go with Keras/Tensorflow/Mobilenet?

答:
ImageNet is a popular database which consists of 1000 different categories.

The dimension of 1000 is natural and to be expected, since for one image the softmax outputs a probability for each of the 1000 classes.

EDIT: For multiple image predictions, you should use predict_generator(). In addition, as of TensorFlow 2.0, if you use the Keras backend, predict_generator() has been deprecated in favor of simple predict, which also allows input data as generators.

E.g. : (from How to use predict_generator with ImageDataGenerator?) :

```<code>test_datagen = ImageDataGenerator(rescale=1./255)
#Modify the batch size here
test_generator = test_datagen.flow_from_directory(
        test_dir,
        target_size=(200, 200),
        color_mode="rgb",
        shuffle = False,
        class_mode='categorical',
        batch_size=1)

filenames = test_generator.filenames
nb_samples = len(filenames)

predict = model.predict_generator(test_generator,steps = nb_samples)
</code>```

Please bear in mind that it will be highly unlikely to have a lot of predictions at once, since it is constrained to the memory of the video card.

Also, note the difference between predict and predict_on_batch: What is the difference between the predict and predict_on_batch methods of a Keras model?

Body:
I am generating imagenet tags for all keyframes in a video with a single call and have this code:

 # all keras/tf/mobilenet imports
model_imagenet = MobileNetV2(weights='imagenet')

frames_list = []
for frame in frame_set:
    frame_img = frame.to_image()
    frame_pil = frame_img.resize((224,224), Image.ANTIALIAS)
    ts = int(frame.pts)
    x = image.img_to_array(frame_pil)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    frames_list.append(x)

print(len(frames_list))

preds_list = model_imagenet.predict_on_batch(frames_list)
print("[*]",preds_list)

The result appears thus:

frames_list count: 125

and the predictions thus, one row of 1000 dimensions (imagenet classes), shouldn't it be 125 rows?:

[[1.15425530e-04 1.83317825e-04 4.28701424e-05 2.87547664e-05
                    :
  7.91769926e-05 1.30803732e-04 4.81895368e-05 3.06891889e-04]]

This is generating prediction for a single row in the batch. I have tried both predict and predict_on_batch with the same result.

How can I get a bulk prediction for say 200 frames at one go with Keras/Tensorflow/Mobilenet?

Body:
ImageNet is a popular database which consists of 1000 different categories.

The dimension of 1000 is natural and to be expected, since for one image the softmax outputs a probability for each of the 1000 classes.

EDIT: For multiple image predictions, you should use predict_generator(). In addition, as of TensorFlow 2.0, if you use the Keras backend, predict_generator() has been deprecated in favor of simple predict, which also allows input data as generators.

E.g. : (from How to use predict_generator with ImageDataGenerator?) :

test_datagen = ImageDataGenerator(rescale=1./255)
#Modify the batch size here
test_generator = test_datagen.flow_from_directory(
        test_dir,
        target_size=(200, 200),
        color_mode="rgb",
        shuffle = False,
        class_mode='categorical',
        batch_size=1)

filenames = test_generator.filenames
nb_samples = len(filenames)

predict = model.predict_generator(test_generator,steps = nb_samples)

Please bear in mind that it will be highly unlikely to have a lot of predictions at once, since it is constrained to the memory of the video card.

Also, note the difference between predict and predict_on_batch: What is the difference between the predict and predict_on_batch methods of a Keras model?


问:
MySQL street address fuzzy search
Does anyone know of a good script (or good strategy) for doing a fuzzy street address search on a MySQL database? The key issues are:

capitalization (easy -- just use LCASE)

punctuation (could use REPLACE; not sure it there are more efficient options)

abbreviations (this is the tough one -- street = st, etc.)

I want to be able to match:
123 Main st, unit B = 123 Main Street Unit b

答:
While it's not perfect and can be quite slow, you'll want to use a regular expression via REGEXP().

Here's a first-pass regular expression to match most cases (as well as your example):

```<code>(?isx)                  # search across multiple lines and ignore case
(                       # full match
  (                       # st number - what about number words like one or two?
    \d+
  )
  \s+                     # whitespace
  (                       # street name (one or more words)
    [a-z]+
    (?:
      \s+
      [a-z]+
    )*
  )
  \s+                     # whitespace
  (                       # street type
    al(?:y\.?|ley)          # aly, aly. or alley
  |
    ave(?:\.|nue)?          # ave, ave., or avenue
  |
    b(?lvd\.?|oulevard)     # blvd, blvd. or boulevard
  |
    c(?:t\.?|ourt)          # ct, ct. or court
  |
    cir(?:\c\.?|cle)?       # cir, circ, circ. or circle
  |
    cres(?:\.|cent)?        # cres, cres. or crescent
  |
    dr(?:\.|ive)?           # dr, dr. or drive
  |
    exp(?:y\.?|ressway)     # expy, expy. or expressway
  |
    f(?:wy\.?|reeway)       # fwy, fwy. or freeway
  |
    g(?:rdns\.?|ardens)     # grdns, grdns. or gardens
  |
    h(?:wy\.?|ighway)       # hwy, hwy. or highway
  |
    l(?n\.?|ane)            # ln, ln. or land
  |
    m(?:nr\.?|anor)         # mnr, mnr. or manor
  |
    m(?:trwy\.?|otorway)    # mtrwy, wtrwy. or motorway
  |
    pl(?:\.|ace)?           # pl, pl. or place
  |
    r(?:d\.?|oad)           # rd, rd. or road
  |
    st(?:\.|reet)?          # st, st. or street
  |
    t(?:pk\.?|urnpike)      # tpk, tpk. or turnpike
  |
    ter(?:\r?\.?|race)      # ter, ter., terr, terr. or terrace
  |
    tr(?:l.\?|ail)          # trl, trl. or trail
  |
    pike|park|walk|loop|bay|close|gate|highlands
  |
    row|way|oval|dell|rise|vale|byway|lawn
  )
  \,?                     # optional comma
  \s+                     # whitespace
  (                       # optional number, unit, apt or floor
    (
      \#                    # number
    |
      unit                  # unit
    |
      num(?:\.|ber)         # num, num. or number
    |
      ap(?:t\.?|artment)    # apt, apt. or apartment
    |
      fl(?:\.|oor)?         # fl, fl. or floor
    )
    \s+
    \d+
  )?
)
</code>```

Which will return:

$1 - full match

$2 - house number

$3 - street name

$4 - street type

$5 - unit or apt number (optional)

To use this in mysql, you'll need to strip out all the comments (from '#' to eol), remove the first line (switch options), and collapse everything to a single line without any whitespace.

Title: MySQL street address fuzzy search

Body:
While it's not perfect and can be quite slow, you'll want to use a regular expression via REGEXP().

Here's a first-pass regular expression to match most cases (as well as your example):

(?isx)                  # search across multiple lines and ignore case
(                       # full match
  (                       # st number - what about number words like one or two?
    \d+
  )
  \s+                     # whitespace
  (                       # street name (one or more words)
    [a-z]+
    (?:
      \s+
      [a-z]+
    )*
  )
  \s+                     # whitespace
  (                       # street type
    al(?:y\.?|ley)          # aly, aly. or alley
  |
    ave(?:\.|nue)?          # ave, ave., or avenue
  |
    b(?lvd\.?|oulevard)     # blvd, blvd. or boulevard
  |
    c(?:t\.?|ourt)          # ct, ct. or court
  |
    cir(?:\c\.?|cle)?       # cir, circ, circ. or circle
  |
    cres(?:\.|cent)?        # cres, cres. or crescent
  |
    dr(?:\.|ive)?           # dr, dr. or drive
  |
    exp(?:y\.?|ressway)     # expy, expy. or expressway
  |
    f(?:wy\.?|reeway)       # fwy, fwy. or freeway
  |
    g(?:rdns\.?|ardens)     # grdns, grdns. or gardens
  |
    h(?:wy\.?|ighway)       # hwy, hwy. or highway
  |
    l(?n\.?|ane)            # ln, ln. or land
  |
    m(?:nr\.?|anor)         # mnr, mnr. or manor
  |
    m(?:trwy\.?|otorway)    # mtrwy, wtrwy. or motorway
  |
    pl(?:\.|ace)?           # pl, pl. or place
  |
    r(?:d\.?|oad)           # rd, rd. or road
  |
    st(?:\.|reet)?          # st, st. or street
  |
    t(?:pk\.?|urnpike)      # tpk, tpk. or turnpike
  |
    ter(?:\r?\.?|race)      # ter, ter., terr, terr. or terrace
  |
    tr(?:l.\?|ail)          # trl, trl. or trail
  |
    pike|park|walk|loop|bay|close|gate|highlands
  |
    row|way|oval|dell|rise|vale|byway|lawn
  )
  \,?                     # optional comma
  \s+                     # whitespace
  (                       # optional number, unit, apt or floor
    (
      \#                    # number
    |
      unit                  # unit
    |
      num(?:\.|ber)         # num, num. or number
    |
      ap(?:t\.?|artment)    # apt, apt. or apartment
    |
      fl(?:\.|oor)?         # fl, fl. or floor
    )
    \s+
    \d+
  )?
)

Which will return:

$1 - full match

$2 - house number

$3 - street name

$4 - street type

$5 - unit or apt number (optional)

To use this in mysql, you'll need to strip out all the comments (from '#' to eol), remove the first line (switch options), and collapse everything to a single line without any whitespace.


问:
Flutter problems: "Could not resolve all artifacts for configuration ':classpath' "
I am trying to run a flutter app I am writing on my device but when I try to run, I never get past the "assembleDebug" stage and get this message in the terminal:

```<code>Launching lib\main.dart on SM N950U in debug mode...
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find com.android.tools.build:gradle:5.6.2.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/5.6.2/gradle-5.6.2.pom
       - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/5.6.2/gradle-5.6.2.jar
       - https://jcenter.bintray.com/com/android/tools/build/gradle/5.6.2/gradle-5.6.2.pom
       - https://jcenter.bintray.com/com/android/tools/build/gradle/5.6.2/gradle-5.6.2.jar
     Required by:
         project :

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s
Finished with error: Gradle task assembleDebug failed with exit code 1
</code>```

I have recently updated to gradle 6.0.1 (I assume I did that correctly but I am very new to all this) and there are no issues with flutter doctor.

Here is my project level build.gradle:

```<code>buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:5.6.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Here is the app level build.gradle:

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.skypeclone1"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Here are my Gradle wrapper properties in case they are also important.

```<code>#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip
</code>```

gradle.properties

```<code>org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
</code>```

答: Sometime you need to run flutter pub upgrade.</p>

Body:
I am trying to run a flutter app I am writing on my device but when I try to run, I never get past the "assembleDebug" stage and get this message in the terminal:

Launching lib\main.dart on SM N950U in debug mode...
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find com.android.tools.build:gradle:5.6.2.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/5.6.2/gradle-5.6.2.pom
       - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/5.6.2/gradle-5.6.2.jar
       - https://jcenter.bintray.com/com/android/tools/build/gradle/5.6.2/gradle-5.6.2.pom
       - https://jcenter.bintray.com/com/android/tools/build/gradle/5.6.2/gradle-5.6.2.jar
     Required by:
         project :

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s
Finished with error: Gradle task assembleDebug failed with exit code 1

I have recently updated to gradle 6.0.1 (I assume I did that correctly but I am very new to all this) and there are no issues with flutter doctor.

Here is my project level build.gradle:

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:5.6.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Here is the app level build.gradle:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.skypeclone1"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'

Here are my Gradle wrapper properties in case they are also important.

#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip

gradle.properties

org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true


问:
How to fix this error "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >="
```<code>CREATE PROCEDURE Task2_Create1397_1396
AS
DECLARE @Check INT
DECLARE @Sal INT

--SET @Check = (SELECT COUNT(Title)FROM Buy)
SET @Sal = (
        SELECT YEAR(Tarikh)
        FROM Buy
        )

IF (@Sal = 1398)
    INSERT INTO Buy
    SELECT Title
        ,Type1
        ,Tedat
        ,DATEADD(DAY, - 2, DATEADD(YEAR, - 1, Tarikh))
        ,Descrip
    FROM Buy

IF (@Sal = 1397)
    INSERT INTO Buy
    SELECT Title
        ,Type1
        ,Tedat
        ,DATEADD(DAY, - 2, DATEADD(YEAR, - 1, Tarikh))
        ,Descrip
    FROM Buy
</code>```

答:
The only place you have a subquery is:

```<code>SET @Sal = (SELECT YEAR(Tarikh) FROM Buy);
</code>```

This code -- even if you limited it to one row -- makes no sense.  This returns one row for each row in Buy.  Which one do you want?  You don't specify which year you want, so I suspect you want:

```<code>SET @Sal = (SELECT MAX(YEAR(Tarikh)) FROM Buy);
</code>```

Next, it is highly unusual to set a parameter named @SAL to a "year" value -- that doesn't work in English, although it might work in another language.  I'm just pointing this out.

The next portion of your code is overly complicated and poorly written:

The two IF blocks are the same (well, except for the THEN conditions).

You are using INSERT with no column list.  That is barely acceptable in ad-hoc code.  It should not be allowed in permanent code.

You can actually eliminate the IF entirely.

So, I would recommend:

```<code>INSERT INTO Buy (Title, Type1, Tedat, Tarikh, Descrip)
    SELECT Title, Type1, Tedat, DATEADD(DAY, - 2, DATEADD(YEAR, - 1, Tarikh)),
           Descrip
    FROM Buy
    WHERE @Sal IN (1398, 1397);
</code>```

Your table doesn't appear to have a primary key.  That would also be a problem, and I would suggest that you fix the data model as well.

Body:
The only place you have a subquery is:

SET @Sal = (SELECT YEAR(Tarikh) FROM Buy);

This code -- even if you limited it to one row -- makes no sense.  This returns one row for each row in Buy.  Which one do you want?  You don't specify which year you want, so I suspect you want:

SET @Sal = (SELECT MAX(YEAR(Tarikh)) FROM Buy);

Next, it is highly unusual to set a parameter named @SAL to a "year" value -- that doesn't work in English, although it might work in another language.  I'm just pointing this out.

The next portion of your code is overly complicated and poorly written:

The two IF blocks are the same (well, except for the THEN conditions).

You are using INSERT with no column list.  That is barely acceptable in ad-hoc code.  It should not be allowed in permanent code.

You can actually eliminate the IF entirely.

So, I would recommend:

INSERT INTO Buy (Title, Type1, Tedat, Tarikh, Descrip)
    SELECT Title, Type1, Tedat, DATEADD(DAY, - 2, DATEADD(YEAR, - 1, Tarikh)),
           Descrip
    FROM Buy
    WHERE @Sal IN (1398, 1397);

Your table doesn't appear to have a primary key.  That would also be a problem, and I would suggest that you fix the data model as well.


问:
get left or right position from heading in degrees
I am trying to determine if one degree on a circle is closer to the right or the left of another degree on a circle.

For example, if I have a heading of 350 degrees and another heading of 10 degrees, then I need to be able to determine that 10 degrees is to the right of 350 degrees on a circle (because it's only 20 degrees from the right -- as opposed to 340 degrees from the left).

How could this be accomplished?

答:
For degrees higher than 180, if you subtract it from 360 then you get the equivalent of a degree under 180.

Then you can compare their difference to find out on which side the 2nd degree is from the 1e degree.

function degreeRightOrLeft (degree1, degree2) {
    let d1 = (degree1 > 180) ? 360 - degree1 : degree1;
    let d2 = (degree2 > 180) ? 360 - degree2 : degree2;
    let diff = d2 - d1;
    return (diff > 0) ? 'Left'
         : (diff < 0) ? 'Right'
         : (diff === 0) ? 'Same'
         : undefined;
}

degrees = [[10, 20], [350, 340], [0, 360], [10,340], [350, 20], [90, 270], [160, 200], [180, 160]];

degrees.forEach(d => { console.log(`(${d[0]}, ${d[1]}) : ${degreeRightOrLeft(d[0], d[1])}`)} )```


问:
Programmatically set params in React Router v4
In React Router 4 I can define

```<code><Route path="/calendar/:view/:year?/:month?/:day?" component={Calendar} />
</code>```

to pass props from a URL to my Calendar component.

Inside the Calendar component, I want to programmatically set the URL params. The docs show how to do this using history.push(), but this requires you to format the URL yourself like history.push(``${view}/${year}/${month}/${day}``). But I want to update the URL without being coupled to the route structure, ideally something like history.push({ view: 'month', year: '2018' }).

Is this possible? It seems odd to me that React Router helps split up the URL into params, but doesn't provide a nice mechanism to set those params?

答:
I would like to suggest that instead of history.push() as answered, you would use history.replace().

with replace you would not affect the history in case the user would want to navigate backward in the browser.

this.props.history.replace({
    pathname: generatePath(this.props.match.path, {orderId: "latest", orderItemId: "latest"})
});
```

Body:
In React Router 4 I can define

<Route path="/calendar/:view/:year?/:month?/:day?" component={Calendar} />

to pass props from a URL to my Calendar component.

Inside the Calendar component, I want to programmatically set the URL params. The docs show how to do this using history.push(), but this requires you to format the URL yourself like history.push(``${view}/${year}/${month}/${day}``). But I want to update the URL without being coupled to the route structure, ideally something like history.push({ view: 'month', year: '2018' }).

Is this possible? It seems odd to me that React Router helps split up the URL into params, but doesn't provide a nice mechanism to set those params?


问:
Android: automatically choose debug/release Maps api key?
OBSOLETED: this old question refers to obsoleted Google Maps v1 API. When using v2 API, you can use multiple certificate fingerprints in one Google API Console entry. API Key is no longer stored in Manifest nor code.

Is it possible to automatically detect, which certificate was used for signing APK? I'd like to have both debug and release Maps certificates in application and pass valid one to MapView constructor.

With such setup I will not make mistake while releasing application - I'm using debug certificate on emulator and my device, then sign with release one before sending app to Market.

I was thinking about detecting my particular device or whether debugger is connected but it is not perfect. Maybe some file marking need for debug certificate? Is there any better way?

答:
Much easier way to determine whether it is a debug build is by checking the debug flag on the application info than the signature hash.

```<code>public boolean isDebugBuild() throws Exception
{
   PackageManager pm = _context.getPackageManager();
   PackageInfo pi = pm.getPackageInfo(_context.getPackageName(), 0);

   return ((pi.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
}
</code>```

Once debug build is found, either you can use different resource for showing map or create the mapview within the app and add to a layout.

```<code>    if(isDebugBuild())
    {
        _mapView = new MapView(this, getString(R.string.debugmapskey));
    }
    else
    {
        _mapView = new MapView(this, getString(R.string.releasemapskey));
    }
</code>```

Body:
Much easier way to determine whether it is a debug build is by checking the debug flag on the application info than the signature hash.

public boolean isDebugBuild() throws Exception
{
   PackageManager pm = _context.getPackageManager();
   PackageInfo pi = pm.getPackageInfo(_context.getPackageName(), 0);

   return ((pi.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
}

Once debug build is found, either you can use different resource for showing map or create the mapview within the app and add to a layout.

    if(isDebugBuild())
    {
        _mapView = new MapView(this, getString(R.string.debugmapskey));
    }
    else
    {
        _mapView = new MapView(this, getString(R.string.releasemapskey));
    }