问:
Initialize repositories protected by Spring authentication
I use Spring Boot Data REST to map Hibernate repositories of entities to REST routes. I also use Spring Security's @PreAuthorize annotation to secure certain methods of those repositories. This works fine during production, but when I want to programmatically initialize the repositories with data (e.g. adding a first user to get started and some other sample data), it complains that "An Authentication object was not found in the SecurityContext". I realize that this is because there is no authenticated user in the security context at the time I configure the database (with an autowired component saving objects to repositories). However, I'd like to temporarily circumvent this authorization during configuration, so that I can initialize the database.

Is there any way to achieve this? And if not, how can I manually log in in the initialization method? I've seen some attempts to the second approach, but they all require access to an AuthenticationManager, which I don't know how to obtain.

答:
You can use the following codes to create a fake user who has enough permission and set it to the SecurityContext just before running that protected method:

```<code>List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

//Setup the permission that the user should have in order to run that method.
//It is the customized value based on your security configuration
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_SUPER_ADMIN"));

//Ensure this user is enabled , active and has above permission
User user = new User("admin", "password", true, true, true, true, grantedAuthorities);

Authentication auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
</code>```

After executing that protected method , reset the SecurityContext (which is equivalent to logout) :

```<code>SecurityContextHolder.clearContext();
</code>```

Body:
You can use the following codes to create a fake user who has enough permission and set it to the SecurityContext just before running that protected method:

List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

//Setup the permission that the user should have in order to run that method.
//It is the customized value based on your security configuration
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_SUPER_ADMIN"));

//Ensure this user is enabled , active and has above permission
User user = new User("admin", "password", true, true, true, true, grantedAuthorities);

Authentication auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);

After executing that protected method , reset the SecurityContext (which is equivalent to logout) :

SecurityContextHolder.clearContext();


来源: stackexchange

问:
Get last 30 day records from today date in SQL Server
I have small question about SQL Server: how to get last 30 days information from this table

Sample data:

Product:

```<code>Pdate
----------
2014-11-20
2014-12-12
2014-11-10
2014-12-13
2014-10-12
2014-11-15
2014-11-14
2014-11-16
2015-01-18
</code>```

Based on this table data i want output like below

```<code>pdate
-------
2014-11-20
2014-12-12
2014-12-13
2014-11-16
</code>```

I tried this query

```<code>SELECT *
FROM product
WHERE pdate >= DATEADD(day, -30, getdate()).
</code>```

but it now give exactly result. Please tell me how to solve this issue in SQL Server

答:
Below query is appropriate for the last 30 days records

Here, I have used a review table and review_date is a column from the review table

```<code>SELECT * FROM reviews WHERE DATE(review_date) >= DATE(NOW()) - INTERVAL 30 DAY
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have small question about SQL Server: how to get last 30 days information from this table

Sample data:

Product:

Pdate
----------
2014-11-20
2014-12-12
2014-11-10
2014-12-13
2014-10-12
2014-11-15
2014-11-14
2014-11-16
2015-01-18

Based on this table data i want output like below

pdate
-------
2014-11-20
2014-12-12
2014-12-13
2014-11-16

I tried this query

SELECT *
FROM product
WHERE pdate >= DATEADD(day, -30, getdate()).

but it now give exactly result. Please tell me how to solve this issue in SQL Server

Body:
Below query is appropriate for the last 30 days records

Here, I have used a review table and review_date is a column from the review table

SELECT * FROM reviews WHERE DATE(review_date) >= DATE(NOW()) - INTERVAL 30 DAY

ContentLicense: CC BY-SA 4.0


问:
What is different between MainActivity.this vs getApplicationContext()
I am trying ProgressDialog. But I am confused.

```<code>1. pd=ProgressDialog.show(MainActivity.this, "", "Fething data");
</code>```

when I do use (MainActivity.this) then it is ok. But

```<code>2. pd=ProgressDialog.show(getApplicationContext(), "", "Fething data");
</code>```

When I do use (getApplicationContext()) it is ERROR.

What is problem for this progressDialog?

What is different between  (MainActivity.this) vs (getApplicationContext())

and when I use it the perfect time?

For getApplicationContext() Error is:

```<code>04-09 15:05:37.453: E/AndroidRuntime(9980): FATAL EXCEPTION: main
04-09 15:05:37.453: E/AndroidRuntime(9980): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.Dialog.show(Dialog.java:281)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.ProgressDialog.show(ProgressDialog.java:116)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.ProgressDialog.show(ProgressDialog.java:99)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.ProgressDialog.show(ProgressDialog.java:94)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at com.example.shikkok_services.MainActivity$2.onClick(MainActivity.java:27)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.View.performClick(View.java:4204)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.View$PerformClick.run(View.java:17355)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.os.Handler.handleCallback(Handler.java:725)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.os.Looper.loop(Looper.java:137)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at java.lang.reflect.Method.invokeNative(Native Method)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at java.lang.reflect.Method.invoke(Method.java:511)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at dalvik.system.NativeStart.main(Native Method)
</code>```

答: mainActivity gives the context of the current Activity. context depends on activity's lifecycle. getApplicationContext() gives the context of the application and depends on the application's lifecycle.

Body:
I am trying ProgressDialog. But I am confused.

1. pd=ProgressDialog.show(MainActivity.this, "", "Fething data");

when I do use (MainActivity.this) then it is ok. But

2. pd=ProgressDialog.show(getApplicationContext(), "", "Fething data");

When I do use (getApplicationContext()) it is ERROR.

What is problem for this progressDialog?

What is different between  (MainActivity.this) vs (getApplicationContext())

and when I use it the perfect time?

For getApplicationContext() Error is:

04-09 15:05:37.453: E/AndroidRuntime(9980): FATAL EXCEPTION: main
04-09 15:05:37.453: E/AndroidRuntime(9980): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.Dialog.show(Dialog.java:281)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.ProgressDialog.show(ProgressDialog.java:116)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.ProgressDialog.show(ProgressDialog.java:99)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.ProgressDialog.show(ProgressDialog.java:94)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at com.example.shikkok_services.MainActivity$2.onClick(MainActivity.java:27)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.View.performClick(View.java:4204)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.view.View$PerformClick.run(View.java:17355)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.os.Handler.handleCallback(Handler.java:725)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.os.Looper.loop(Looper.java:137)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at java.lang.reflect.Method.invokeNative(Native Method)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at java.lang.reflect.Method.invoke(Method.java:511)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-09 15:05:37.453: E/AndroidRuntime(9980):     at dalvik.system.NativeStart.main(Native Method)


问:
How can i improve this guessing algorithm?
I am trying to do a program that guess the word the user think, but right now the program is based only on elimination. Does anyone have an idea on how to make it better?

Here is a brief explanation on how it works now:

I have a list of words stored in "palavras.txt", these words are then transformed into a regular list.

First question is: "How much letters do your word have?". Based on that the program proceed to eliminate all the others words who do not have the same amount of letters. After that it creates a list that contains all the letters organized by the number of times they appear in the given position.

Then we have the second question: "Is the letter "x" the first letter of your word?". If the response is "not" it deletes all the words that contains that letter in that position, then goes to the second letter most used in that position and so on and so on. If yes it deletes all the words that doesn't contain that letter in that specific position and goes to the next letter of the word. And so on until the word is finished.

It works all the times, but sometimes it takes quite a lot of times. Is there a better way do it? AI? Machine learning maybe?

The code is not important since i'm just searching for ideas, but if anyone is curious here is how i did it:

```<code>import os
from unicodedata import normalize
import random
import string

# Define a função que retira os acentos das palavras
def remover_pont(txt):
    import string
    return txt.translate(str.maketrans('', '', string.punctuation))

def remover_acentos(txt):
    return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII')

# Retorna uma lista com as letras mais usadas naquela posição, em ordem
def letramusada(lista, pletra):
    pletraordem = []
    pletraordem2 = []
    pl = []

    for n in lista:
        try:
            pl.append(n[pletra - 1])
        except:
            pass

    dict = {}
    for k in pl:
        if k in dict:
            dict[k] += 1
        else:
            dict[k] = 1
    pletraordem2 = (sorted(dict.items(), key=lambda t: t[1], reverse=True))

    for c in pletraordem2:
        pletraordem.append(c[0])

    return pletraordem

# Lê o "banco de dados" que contém as palavras e as armazena na variável "palavras", sem acentos
file = open('palavras.txt')
palavras = file.read().split("\n")

# Armazena a quantidade de letras que a palavra pensada tem
nletras = int(input('Digite o número de letras da palavra (considerando hífen, caso haja) que você pensou, com máximo de 8: '))

# Declara listas que serão usadas em seguida
npalavras = []
palavras2 = []
palavras3 = []
# Armazena todas as palavras que contém a quantidade de letras escolhida anteriormente em uma nova lista chamada "nletras", desconsiderando pontos

for n in palavras:
    if nletras == len(n):
        npalavras.append(remover_acentos(n).lower())

c = 0
n = 0

for k in range(1, nletras + 1):
    ordem = letramusada(npalavras, k)
    cond = 0
    try:
        while cond == 0:
            if  len(npalavras) < 20 and c == 0:
                print("\nHmmm, estou chegando perto!\n")
                c += 1
            if len(npalavras) < 3:
                break
            for c in ordem:
                if c != 0:
                    r = str(input("A {} letra da sua palavra é a letra \"{}\"? [S/N] ".format(k, c))).lower()
                    r = r[0]
                    if r == "s":
                        for n in npalavras:
                            if n[k-1] == c:
                                palavras2.append(n)
                        npalavras.clear()
                        npalavras = palavras2[:]
                        palavras2.clear()
                        ordem.clear()
                        cond += 1
                        break
                    else:
                        for n in npalavras:
                            if n[k-1] != c:
                                palavras2.append(n)
                        npalavras.clear()
                        npalavras = palavras2[:]
                        palavras2.clear()
                        r = 0
                        pass
    except:
        n = 1
        print("\nDesculpe, não achei nenhuma palavra :(")

escolha = random.choice(npalavras)

if n != 0:
    print("\nA palavra que você pensou é: \"{}\"".format(escolha))
</code>```

答:
The Brute Force Be Your Friend

People may think "machine learning" is a silver bullet, but, what to learn? Especially when there's little information provided. What can you optimize? Your description sounds like a pure brute-force dictionary based password cracking, and hackers living in today are utilizing the power of GPU for that.

This may be a little off topic but even given a GPU the search can be hard. If you are not constrained to specific language / platform, the above link to hashcat is useful. The famous 133 MB dictionary can be enumerated in 5 minutes on a MacBookPro, which is way more powerful than guessing in Python.

The Search Space And Word Patterns

Also an average length for English words is about 8, this situation is really similar with a typical password. i.e. your search space is large - the upperbound is 26^8 = 208827064576 words! - except that player can only use a limited word list in the game.

The actual search space can be a little bit smaller since there are patterns in English words (like s is the most frequent alphabet and ae, as can appear more frequently than az things), but you are using a dictionary, so I don't think this can help.

The Non Dictionary Approach

And another idea is that the process can be quite close to recover a DNA sequence, which also has some patterns but the give information may vary. Think it as a word suggestion. Bioinfomatics uses the probabilistic patterns in DNA sequence for imputation.

This method can help when you can progressively guess the word / sequence. Otherwise, you can only use a brute force approach (when your word can only be recovered from a hash).

A classic method used for search engines, input methods and DNA imputation is hidden markov model. It guesses the next character based on your previous input, and the probability is a statistic value pre-calculated using real words.

This can be combined with dictionary to sort your suggestion (guess) and provide more accurate guessing.

Body:
I am trying to do a program that guess the word the user think, but right now the program is based only on elimination. Does anyone have an idea on how to make it better?

Here is a brief explanation on how it works now:

I have a list of words stored in "palavras.txt", these words are then transformed into a regular list.

First question is: "How much letters do your word have?". Based on that the program proceed to eliminate all the others words who do not have the same amount of letters. After that it creates a list that contains all the letters organized by the number of times they appear in the given position.

Then we have the second question: "Is the letter "x" the first letter of your word?". If the response is "not" it deletes all the words that contains that letter in that position, then goes to the second letter most used in that position and so on and so on. If yes it deletes all the words that doesn't contain that letter in that specific position and goes to the next letter of the word. And so on until the word is finished.

It works all the times, but sometimes it takes quite a lot of times. Is there a better way do it? AI? Machine learning maybe?

The code is not important since i'm just searching for ideas, but if anyone is curious here is how i did it:

import os
from unicodedata import normalize
import random
import string

# Define a função que retira os acentos das palavras
def remover_pont(txt):
    import string
    return txt.translate(str.maketrans('', '', string.punctuation))

def remover_acentos(txt):
    return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII')

# Retorna uma lista com as letras mais usadas naquela posição, em ordem
def letramusada(lista, pletra):
    pletraordem = []
    pletraordem2 = []
    pl = []

    for n in lista:
        try:
            pl.append(n[pletra - 1])
        except:
            pass

    dict = {}
    for k in pl:
        if k in dict:
            dict[k] += 1
        else:
            dict[k] = 1
    pletraordem2 = (sorted(dict.items(), key=lambda t: t[1], reverse=True))

    for c in pletraordem2:
        pletraordem.append(c[0])

    return pletraordem

# Lê o "banco de dados" que contém as palavras e as armazena na variável "palavras", sem acentos
file = open('palavras.txt')
palavras = file.read().split("\n")

# Armazena a quantidade de letras que a palavra pensada tem
nletras = int(input('Digite o número de letras da palavra (considerando hífen, caso haja) que você pensou, com máximo de 8: '))

# Declara listas que serão usadas em seguida
npalavras = []
palavras2 = []
palavras3 = []
# Armazena todas as palavras que contém a quantidade de letras escolhida anteriormente em uma nova lista chamada "nletras", desconsiderando pontos

for n in palavras:
    if nletras == len(n):
        npalavras.append(remover_acentos(n).lower())

c = 0
n = 0

for k in range(1, nletras + 1):
    ordem = letramusada(npalavras, k)
    cond = 0
    try:
        while cond == 0:
            if  len(npalavras) < 20 and c == 0:
                print("\nHmmm, estou chegando perto!\n")
                c += 1
            if len(npalavras) < 3:
                break
            for c in ordem:
                if c != 0:
                    r = str(input("A {} letra da sua palavra é a letra \"{}\"? [S/N] ".format(k, c))).lower()
                    r = r[0]
                    if r == "s":
                        for n in npalavras:
                            if n[k-1] == c:
                                palavras2.append(n)
                        npalavras.clear()
                        npalavras = palavras2[:]
                        palavras2.clear()
                        ordem.clear()
                        cond += 1
                        break
                    else:
                        for n in npalavras:
                            if n[k-1] != c:
                                palavras2.append(n)
                        npalavras.clear()
                        npalavras = palavras2[:]
                        palavras2.clear()
                        r = 0
                        pass
    except:
        n = 1
        print("\nDesculpe, não achei nenhuma palavra :(")

escolha = random.choice(npalavras)

if n != 0:
    print("\nA palavra que você pensou é: \"{}\"".format(escolha))


问:
Particles do not appear on the particles div
I'm trying to use particles.js as a background for a website. Currently, the particles div is present, but the particles do not appear. How could i fix this?

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <div id="particles-js"></div>
    <script type="text/javascript" src="./particles.js-master/demo/js/app.js"></script>
    <script type="text/javascript" src="./particles.js-master/particles.js"></script>
</body>
</html>
</code>```

style.css

```<code>body {
    background: #000;
    margin: 0;
    padding: 0;
    height: 100vh;
}

#particles-js {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</code>```

I know that particles-js is present because changing its background color makes an affect on the page.

答:
```<code>/* ---- particles.js config ---- */

particlesJS("particles-js", {
  "particles": {
    "number": {
      "value": 380,
      "density": {
        "enable": true,
        "value_area": 800
      }
    },
    "color": {
      "value": "#ffffff"
    },
    "shape": {
      "type": "circle",
      "stroke": {
        "width": 0,
        "color": "#000000"
      },
      "polygon": {
        "nb_sides": 5
      },
      "image": {
        "src": "img/github.svg",
        "width": 100,
        "height": 100
      }
    },
    "opacity": {
      "value": 0.5,
      "random": false,
      "anim": {
        "enable": false,
        "speed": 1,
        "opacity_min": 0.1,
        "sync": false
      }
    },
    "size": {
      "value": 3,
      "random": true,
      "anim": {
        "enable": false,
        "speed": 40,
        "size_min": 0.1,
        "sync": false
      }
    },
    "line_linked": {
      "enable": true,
      "distance": 150,
      "color": "#ffffff",
      "opacity": 0.4,
      "width": 1
    },
    "move": {
      "enable": true,
      "speed": 6,
      "direction": "none",
      "random": false,
      "straight": false,
      "out_mode": "out",
      "bounce": false,
      "attract": {
        "enable": false,
        "rotateX": 600,
        "rotateY": 1200
      }
    }
  },
  "interactivity": {
    "detect_on": "canvas",
    "events": {
      "onhover": {
        "enable": true,
        "mode": "grab"
      },
      "onclick": {
        "enable": true,
        "mode": "push"
      },
      "resize": true
    },
    "modes": {
      "grab": {
        "distance": 140,
        "line_linked": {
          "opacity": 1
        }
      },
      "bubble": {
        "distance": 400,
        "size": 40,
        "duration": 2,
        "opacity": 8,
        "speed": 3
      },
      "repulse": {
        "distance": 200,
        "duration": 0.4
      },
      "push": {
        "particles_nb": 4
      },
      "remove": {
        "particles_nb": 2
      }
    }
  },
  "retina_detect": true
});

/* ---- stats.js config ---- */

var count_particles, stats, update;
stats = new Stats;
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild(stats.domElement);
count_particles = document.querySelector('.particles-js');
update = function() {
  stats.begin();
  stats.end();
  if (window.pJSDom[0].pJS.particles && window.pJSDom[0].pJS.particles.array) {
    count_particles.innerText = window.pJSDom[0].pJS.particles.array.length;
  }
  requestAnimationFrame(update);
};
requestAnimationFrame(update);
</code>```

Body:
I'm trying to use particles.js as a background for a website. Currently, the particles div is present, but the particles do not appear. How could i fix this?

index.html

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <title>Title</title>

style.css

body {
    background: #000;
    margin: 0;
    padding: 0;
    height: 100vh;
}

#particles-js {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

I know that particles-js is present because changing its background color makes an affect on the page.


问:
Apache kafka separate producer and consumer
I have multiple servers from where the messages will be produced, and I need broker and consumer at one server.
If I have both producer and consumer running on same server then it works fine, but not sure what changes need to be done to keep producers separate. I don't want any dependency of zookeeper and kafka servers at producer servers as there are many and they will increase.
I tried with changing bootstrap server to the broker/consumer server like 192.168.0.1:9092 while setting up KafkaProducer but still not able to generate messages. Not sure what am I missing, please help me out here.

producer.props

```<code>bootstrap.servers=192.168.0.1:9092
acks=all
retries=0
batch.size=16384
auto.commit.interval.ms=1000
linger.ms=0
key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer
block.on.buffer.full=true
</code>```

Producer code

```<code>public class Producer {
    public static void main(String[] args) throws IOException {
        // set up the producer
        KafkaProducer<String, String> producer;
        System.out.println("1");
        try (InputStream props = Resources.getResource("producer.props").openStream()) {
            Properties properties = new Properties();
            properties.load(props);
            producer = new KafkaProducer<>(properties);
        }

        try {
            for (int i = 0; i < 1000000; i++) {

                // send lots of messages
                System.out.println("bedore send");
                    producer.send(new ProducerRecord<String, String>(
                            "fast-messages",
                            String.format("{\"type\":\"marker\", \"t\":%.3f, \"k\":%d}", System.nanoTime() * 1e-9, i)));
                    producer.send(new ProducerRecord<String, String>(
                            "summary-markers",
                            String.format("{\"type\":\"other\", \"t\":%.3f, \"k\":%d}", System.nanoTime() * 1e-9, i)));
                    producer.flush();
                    System.out.println("Sent msg number " + i);
            }
            System.out.println("fdone");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.printf("%s", throwable.getStackTrace());
        } finally {
            producer.close();
        }

    }
}
</code>```

答:
Not sure the problem you are running into, but it seems that clarity of information is not there. I will try and answer it theoretically.
Producers and consumers are both clients of Kafka brokers. So, as far as brokers are configured in producers properly, the messages are sent to the kafka servers without any issue. Similar is the case with Consumers. Typically, the kafka cluster (brokers) is separately created to handle the messages. Producers and consumers are not needed to run Kafka servers. So, your clients can be running anywhere with the configuration of brokers within them. There is no dependency between producer & consumer. They are independent programs that do the job of publishing messages to Kafka cluster (producers) and receiving messages from kafka cluster (consumers). Producers are not dependent on Zookeeper nodes. Zookeeper is used as dependency by Kafka servers for metadata management. Your statement " any dependency of zookeeper and kafka servers at producer servers" is not justified as Producers will use the broker configuration to connect to the kafka servers (bootstrapping). </p>

Body:
I have multiple servers from where the messages will be produced, and I need broker and consumer at one server.
If I have both producer and consumer running on same server then it works fine, but not sure what changes need to be done to keep producers separate. I don't want any dependency of zookeeper and kafka servers at producer servers as there are many and they will increase.
I tried with changing bootstrap server to the broker/consumer server like 192.168.0.1:9092 while setting up KafkaProducer but still not able to generate messages. Not sure what am I missing, please help me out here.

producer.props

bootstrap.servers=192.168.0.1:9092
acks=all
retries=0
batch.size=16384
auto.commit.interval.ms=1000
linger.ms=0
key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer
block.on.buffer.full=true

Producer code

public class Producer {
    public static void main(String[] args) throws IOException {
        // set up the producer
        KafkaProducer<String, String> producer;
        System.out.println("1");
        try (InputStream props = Resources.getResource("producer.props").openStream()) {
            Properties properties = new Properties();
            properties.load(props);
            producer = new KafkaProducer<>(properties);
        }

        try {
            for (int i = 0; i < 1000000; i++) {

                // send lots of messages
                System.out.println("bedore send");
                    producer.send(new ProducerRecord<String, String>(
                            "fast-messages",
                            String.format("{\"type\":\"marker\", \"t\":%.3f, \"k\":%d}", System.nanoTime() * 1e-9, i)));
                    producer.send(new ProducerRecord<String, String>(
                            "summary-markers",
                            String.format("{\"type\":\"other\", \"t\":%.3f, \"k\":%d}", System.nanoTime() * 1e-9, i)));
                    producer.flush();
                    System.out.println("Sent msg number " + i);
            }
            System.out.println("fdone");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.printf("%s", throwable.getStackTrace());
        } finally {
            producer.close();
        }

    }
}


问:
Regex in PHP expecting to match strings like "${string}" not working
I’ve got:

```<code>$ap=0;
$matches=array();
d($ap, $vv[$value],$matches);
$ap = preg_match("/\$[({].+[)}]/", $vv[$value], $matches);
d($ap, $vv[$value],$matches);
</code>```

d() is a custom function like var_dump().

When $vv[$value] is "exec_prefix = ${prefix}", why is that $ap is 0, and there’s no matches ($matches is still an empty array)?

I am expecting "${prefix}" to be matched.

I tried the regex in regexpal.com and it matches too.

答:
The "\" before "$" is removed before it gets to preg_match() because it is treated by PHP as an escape character for "$".

To fix this, simply use single quote instead of double quote:

```<code>$ap = preg_match('/\$[({].+[)}]/', $vv[$value], $matches);
</code>```

Body:
I’ve got:

$ap=0;
$matches=array();
d($ap, $vv[$value],$matches);
$ap = preg_match("/\$[({].+[)}]/", $vv[$value], $matches);
d($ap, $vv[$value],$matches);

d() is a custom function like var_dump().

When $vv[$value] is "exec_prefix = ${prefix}", why is that $ap is 0, and there’s no matches ($matches is still an empty array)?

I am expecting "${prefix}" to be matched.

I tried the regex in regexpal.com and it matches too.

Body:
The "\" before "$" is removed before it gets to preg_match() because it is treated by PHP as an escape character for "$".

To fix this, simply use single quote instead of double quote:

$ap = preg_match('/\$[({].+[)}]/', $vv[$value], $matches);


问:
I need to modify a file in ksh script using sed but not all the lines?
I have a file.pc (Pro c) that have some compatible problems with linux when passed from windows. So i tried to create a script to formalize the document in the format i need, but, i have encountered a problem with the substitution of // comments. The problem is:

I need to replace all the comments that starts with // with /* */ comments
I have already done this but i have a simple problem, in some files i have // comments into /* */ comments like the example below:

```<code>/*

// some comments
code;
code;

*/
</code>```

So when i went to substitute that with the script it appears like that:

```<code>/*

/* some comments */
code;
code;

*/
</code>```

But the final */ of the father comments gives me an error because there cannot be two */ concatenated  so the last */ gives me an error.

I need to replace only the comments that aren't just in a /* */ comment
and replace the // inside them with a single /*

```<code>for file in $(ls $path)
do
sed -i -e '/\/\// s/$/ *\//g' -e 's/\/\//\/* /g' $path/file
done
</code>```

答:
This Perl script should do the job for every file it gets as a parameter.

```<code>use v5.10;
for my $file (@ARGV) {
    -f $file or warn "$file is not a plain file, ignoring..." and next;
    open my $fh, '<', $file;
    my @content = <$fh>;
    close $fh;
    my $comment = 0;
    for (keys @content) {
        $comment or $content[$_] =~ /\/\*/ and $comment = 1;
        $comment and $content[$_] =~ /\*\// and $comment = 0;
        $comment or $content[$_] =~ s/\/\/\s*(.*?)\s*$/\/\* $1 \*\// and $content[$_].="\n";
    }
    open $fh, '>', $file;
    print $fh @content;
    close $fh;
}
</code>```

To execute it insert the contents into a file and write in the ksh command line.

```<code>perl <name_of_script>.pl <files>
</code>```

Body:
I have a file.pc (Pro c) that have some compatible problems with linux when passed from windows. So i tried to create a script to formalize the document in the format i need, but, i have encountered a problem with the substitution of // comments. The problem is:

I need to replace all the comments that starts with // with /* */ comments
I have already done this but i have a simple problem, in some files i have // comments into /* */ comments like the example below:

/*

// some comments
code;
code;

*/

So when i went to substitute that with the script it appears like that:

/*

/* some comments */
code;
code;

*/

But the final */ of the father comments gives me an error because there cannot be two */ concatenated  so the last */ gives me an error.

I need to replace only the comments that aren't just in a /* */ comment
and replace the // inside them with a single /*

for file in $(ls $path)
do
sed -i -e '/\/\// s/$/ *\//g' -e 's/\/\//\/* /g' $path/file
done

Body:
This Perl script should do the job for every file it gets as a parameter.

use v5.10;
for my $file (@ARGV) {
    -f $file or warn "$file is not a plain file, ignoring..." and next;
    open my $fh, '<', $file;
    my @content = <$fh>;
    close $fh;
    my $comment = 0;
    for (keys @content) {
        $comment or $content[$_] =~ /\/\*/ and $comment = 1;
        $comment and $content[$_] =~ /\*\// and $comment = 0;
        $comment or $content[$_] =~ s/\/\/\s*(.*?)\s*$/\/\* $1 \*\// and $content[$_].="\n";
    }
    open $fh, '>', $file;
    print $fh @content;
    close $fh;
}

To execute it insert the contents into a file and write in the ksh command line.

perl <name_of_script>.pl <files>


问:
React-Native iOS - How can I navigate to a non-React-Native view (native iOS view controller) from a React-Native view with a button press?
The RN doco and other examples show how to launch a React-Native view from a native iOS view controller, but not the other way around.  Can someone explain how I can do this?</p>

答:
There is little improvement on this solution.With present solution there is no way to come back to React-Native from iOS.

If you want to come back again from iOS to React-Native.Do the below

```<code> // AppDelegate.h

    - (void) goToNativeView {
     UIViewController *vc =  [InitialViewController new];// This is your native iOS VC
     UINavigationController* navigationController = [[UINavigationController alloc] initWithRootViewController:vc];

      dispatch_async(dispatch_get_main_queue(), ^{
       // Never do the below, it will be difficult to come back to react-native

       // self.window.rootViewController = navigationController;

        // Do this instead
        [self.window.rootViewController presentViewController:navigationController animated:true completion:NULL];
      });
    }

//InitialViewController.m
</code>```

Create a button for go back to React-native and on button action dismiss this view controller:

```<code>    // Dismiss the VC so controll go back from iOS to react-native
        [self dismissViewControllerAnimated:TRUE completion:nil];
</code>```

Body:
There is little improvement on this solution.With present solution there is no way to come back to React-Native from iOS.

If you want to come back again from iOS to React-Native.Do the below

 // AppDelegate.h

    - (void) goToNativeView {
     UIViewController *vc =  [InitialViewController new];// This is your native iOS VC
     UINavigationController* navigationController = [[UINavigationController alloc] initWithRootViewController:vc];

      dispatch_async(dispatch_get_main_queue(), ^{
       // Never do the below, it will be difficult to come back to react-native

       // self.window.rootViewController = navigationController;

        // Do this instead
        [self.window.rootViewController presentViewController:navigationController animated:true completion:NULL];
      });
    }

//InitialViewController.m

Create a button for go back to React-native and on button action dismiss this view controller:

    // Dismiss the VC so controll go back from iOS to react-native
        [self dismissViewControllerAnimated:TRUE completion:nil];


问:
keystone command not found
while running openstack-status I got this error..

/usr/bin/openstack-status: line 267: keystone: command not found

above

== Keystone service ==

  openstack-keystone:                     inactive  (disabled on boot)

openstack-nova-network:                 inactive  (disabled on boot)

[root@rd0-openstack keystone(keystone_admin)]# keystone-

keystone-manage       keystone-wsgi-admin   keystone-wsgi-public

so what else to check

答:
openstack-status is still using 'keystone user list' which is depreciated it should use 'openstack user list' instead  please  update openstack-status binary to make it work.

use "vim +267 /usr/bin/openstack-status"

and replace  'keystone user-list'  with 'openstack user list'

or use below sed command to replace it accordingly.

sed -i 267s/'keystone user-list'/'openstack user list'/ /usr/bin/openstack-status

keystone command not found

Title: keystone command not found


问:
Illegal Argument Exception when using Suggestors in Elasticsearch in PHP
I have tried implementing completion suggestor query in php as given here. My code is :

```<code>$params = [
            "index" => $myIndex,
            "body" => [
                "try" => [
                    "text" => "ram",
                    "completion" => [ "value" => "suggest"]
                ]
            ]
        ];

        $response = $client->suggest($params);
</code>```

I have done indexing like this:

```<code>$params = [
        "index" => $myIndex,
            "body" => [
            "settings"=> [
            "analysis"=> [
                "analyzer"=> [
                "start_with_analyzer"=> [
                    "tokenizer"=> "my_edge_ngram",
                    "filter"=> [
                    "lowercase"
                    ]
                ]
                ],
                "tokenizer"=> [
                "my_edge_ngram"=> [
                    "type"=> "edge_ngram",
                    "min_gram"=> 3,
                    "max_gram"=> 15
                ]
                ]
            ]
            ],
            "mappings"=> [
            "doc"=> [
                "properties"=> [
                "label"=> [
                    "type"=> "text",
                    "fields"=> [
                    "keyword"=> [
                        "type"=> "keyword"
                    ],
                    "ngramed"=> [
                        "type"=> "text",
                        "analyzer"=> "start_with_analyzer"
                    ]
                    ]
                ]
                ]
            ]
            ]
    ]
    ];
    $response = $client->indices()->create($params);    // create an index
</code>```

and I am getting the following error:

```<code>{
    "error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "[completion] unknown field [value], parser not found"
            }
        ],
        "type": "illegal_argument_exception",
        "reason": "[completion] unknown field [value], parser not found"
    },
    "status": 400
}
</code>```

I have tried changing value to value.keyword but it is showing same error. I am using elastic search 5.3.2 . How to resolve this error?

答:
In the query you are using field 'value' inside the completion while it is not a field like this, that is the exact error is stating.

You can try the below solution:

```<code>    $params = [
                "index" => $myIndex,
                "body" => [
                    "try" => [
                        "text" => "ram",
                        "completion" => [ "label" => "suggest"]
                    ]
                ]
            ];
   $response = $client->suggest($params);
</code>```

Hope this will work.

Body:
I have tried implementing completion suggestor query in php as given here. My code is :

$params = [
            "index" => $myIndex,
            "body" => [
                "try" => [
                    "text" => "ram",
                    "completion" => [ "value" => "suggest"]
                ]
            ]
        ];

        $response = $client->suggest($params);

I have done indexing like this:

$params = [
        "index" => $myIndex,
            "body" => [
            "settings"=> [
            "analysis"=> [
                "analyzer"=> [
                "start_with_analyzer"=> [
                    "tokenizer"=> "my_edge_ngram",
                    "filter"=> [
                    "lowercase"
                    ]
                ]
                ],
                "tokenizer"=> [
                "my_edge_ngram"=> [
                    "type"=> "edge_ngram",
                    "min_gram"=> 3,
                    "max_gram"=> 15
                ]
                ]
            ]
            ],
            "mappings"=> [
            "doc"=> [
                "properties"=> [
                "label"=> [
                    "type"=> "text",
                    "fields"=> [
                    "keyword"=> [
                        "type"=> "keyword"
                    ],
                    "ngramed"=> [
                        "type"=> "text",
                        "analyzer"=> "start_with_analyzer"
                    ]
                    ]
                ]
                ]
            ]
            ]
    ]
    ];
    $response = $client->indices()->create($params);    // create an index

and I am getting the following error:

{
    "error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "[completion] unknown field [value], parser not found"
            }
        ],
        "type": "illegal_argument_exception",
        "reason": "[completion] unknown field [value], parser not found"
    },
    "status": 400
}

I have tried changing value to value.keyword but it is showing same error. I am using elastic search 5.3.2 . How to resolve this error?

Body:
In the query you are using field 'value' inside the completion while it is not a field like this, that is the exact error is stating.

You can try the below solution:

    $params = [
                "index" => $myIndex,
                "body" => [
                    "try" => [
                        "text" => "ram",
                        "completion" => [ "label" => "suggest"]
                    ]
                ]
            ];
   $response = $client->suggest($params);

Hope this will work.


问:
IModuleNotFoundError: No module named 'django' in VS Code editor while no problem with terminal
I'm new to django, and want to use it in VS Code. However, "ModuleNotFoundError: No module named 'django'" blocked me.

I've pip installed virtual environment, it worked fine in terminal.

on terminal, it shows:

```<code>(myenv) Kates-MacBook:~ kate.wang$ python3
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> from django.shortcuts import render
>>>
</code>```

on VS Code, it outputs:

```<code>[Running] python -u "/Users/kate.wang/myenv/my_django_project/blog/views.py"
Traceback (most recent call last):
File "/Users/kate.wang/myenv/my_django_project/blog/views.py", line 1, in <module>
from django.shortcuts import render
ModuleNotFoundError: No module named 'django'
</code>```

My VS Code Settings are:

```<code>{
"workbench.iconTheme": "vs-minimal",
"editor.fontSize": 15,
"editor.fontLigatures": true,
"terminal.integrated.fontSize": 14,
"workbench.startupEditor": "newUntitledFile",
"workbench.activityBar.visible": true,
"python.dataScience.sendSelectionToInteractiveWindow": true,
"workbench.sideBar.location": "left",
"workbench.colorTheme": "Visual Studio Dark",
"editor.minimap.enabled": false,
"kite.showWelcomeNotificationOnStartup": false,
"python.pythonPath": "python3.7",
"python.venvPath": "/Users/kate.wang/myenv"
</code>```

}

This problem has bothered me for days since I've been trying different solutions from stackoverflow and other websites the first time it poped up and didn't find a way to solve it.

Thank you for your time to help me.

答: If you are using Python's VENV (Virtual environment), activate your venv (Django must be installed on this venv) from terminal and after venv is active in terminal,,, just type code . (in terminal). I think, this is exactly what you need.

Body:
I'm new to django, and want to use it in VS Code. However, "ModuleNotFoundError: No module named 'django'" blocked me.

I've pip installed virtual environment, it worked fine in terminal.

on terminal, it shows:

(myenv) Kates-MacBook:~ kate.wang$ python3
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> from django.shortcuts import render
>>>

on VS Code, it outputs:

[Running] python -u "/Users/kate.wang/myenv/my_django_project/blog/views.py"
Traceback (most recent call last):
File "/Users/kate.wang/myenv/my_django_project/blog/views.py", line 1, in <module>
from django.shortcuts import render
ModuleNotFoundError: No module named 'django'

My VS Code Settings are:

{
"workbench.iconTheme": "vs-minimal",
"editor.fontSize": 15,
"editor.fontLigatures": true,
"terminal.integrated.fontSize": 14,
"workbench.startupEditor": "newUntitledFile",
"workbench.activityBar.visible": true,
"python.dataScience.sendSelectionToInteractiveWindow": true,
"workbench.sideBar.location": "left",
"workbench.colorTheme": "Visual Studio Dark",
"editor.minimap.enabled": false,
"kite.showWelcomeNotificationOnStartup": false,
"python.pythonPath": "python3.7",
"python.venvPath": "/Users/kate.wang/myenv"

}

This problem has bothered me for days since I've been trying different solutions from stackoverflow and other websites the first time it poped up and didn't find a way to solve it.

Thank you for your time to help me.


问:
My DIVs are working differently since my site was deleted (by my awful Name host) & then re-UL'd
I have a gallery of images on my website. I had to alter a template I used to make it so that gallery showed images horizontally in rows of 3 or 4. I honestly don't recall how I did this, but when my Name host deleted my site recently (don't ask), and & re-UL'd my files, that gallery looked like it did when I first DL'd the template, and now I can't get the rows any longer.

I've tried commenting out some of the DIVs comparing what I have w/a similar mirror site, but I'm not seeing any change. The mirror site I set up differently so it's not as apt as I hoped it would be. Anyway, the gallery has images w/captions, and I've tried rearranging the info but to no avail. My temp fix is some really messy HTML on the actual site (therealitycomics.com -- gallery section, where there are currently just 5 images).

```<code><footer id="footer">
<div class="inner">

<div class="gallery cf">
<div>
<a target="_blank"
href="http://therealitycomics.com/images/Postcard.jpg">
<img src="http://therealitycomics.com/images/Postcard.jpg" alt="The
Reality" width="155" height="220">
</a>
<div>How our Intraverse<br>connects</div>
</div>
<div>
<a target="_blank"
href="http://www.therealitycomics.com/patreon/PK11.jpg">
<img src="http://www.therealitycomics.com/patreon/PK11.jpg" alt="Phantom
Kid layout" width="155" height="220">
</a>
<div>Phantom Kid pg<br>Layout 1</div>
</div>
<div>
<a target="_blank"
href="http://www.therealitycomics.com/patreon/PK11b.jpg">
<img src="http://www.therealitycomics.com/patreon/PK11b.jpg" alt="Phantom
Kid layout" width="155" height="220">
</a>
<div>Phantom Kid pg<br>Layout 2</div>
</div>
</code>```

I'n NOT a coder, I just used a template and figured out what changes I needed to make to build my site, so I'm not so great at the trouble-shooting. And, also, it's been so long, I no longer retain the info I !did! learn.

! So please, when you offer advice, be as basic in your descriptions as possible. =] !

Expected result: Those images would all appear in the same row, each one w/its caption.
Actual result: Each image is a row of its own, with the captions under each one.

The DIVs are causing this, but I don't quite get why they're causing it now but weren't before. I checked my main.css b/c I thought the Footer ID or the DIV class "inner" might be the cause based on definitions in the main.css, but I'm not seeing any width or border definitions that are relevant (to my eye), but ALSO when I remove the DIVs around each image and caption, everything jumps up onto one row. And a new row starts with each new DIV tag.

The site (w/its messed up gallery where I commented out all of the old gallery): TheRealitycomics.com
A URL where you can see it as it was: http://therealitycomics.com/indexB.html (again, this is the page where everything HAD been in rows of 3 or 4 but now is just one long column).

答:
Try adding this to your main.css. It should set your gallery section so that it displays four items in a row (unless the browser window width is under 800px, then it will display only two items in a row).

```<code>.gallery {
    display: flex;
    flex-wrap: wrap;
}

.gallery > div {
    width: 50%;
}

@media (min-width: 800px) {
    .gallery > div {
        width: 25%;
    }
}
</code>```

Body:
I have a gallery of images on my website. I had to alter a template I used to make it so that gallery showed images horizontally in rows of 3 or 4. I honestly don't recall how I did this, but when my Name host deleted my site recently (don't ask), and & re-UL'd my files, that gallery looked like it did when I first DL'd the template, and now I can't get the rows any longer.

I've tried commenting out some of the DIVs comparing what I have w/a similar mirror site, but I'm not seeing any change. The mirror site I set up differently so it's not as apt as I hoped it would be. Anyway, the gallery has images w/captions, and I've tried rearranging the info but to no avail. My temp fix is some really messy HTML on the actual site (therealitycomics.com -- gallery section, where there are currently just 5 images).

How our Intraverse
connects

Phantom Kid pg
Layout 1

Phantom Kid pg
Layout 2

I'n NOT a coder, I just used a template and figured out what changes I needed to make to build my site, so I'm not so great at the trouble-shooting. And, also, it's been so long, I no longer retain the info I !did! learn.

! So please, when you offer advice, be as basic in your descriptions as possible. =] !

Expected result: Those images would all appear in the same row, each one w/its caption.
Actual result: Each image is a row of its own, with the captions under each one.

The DIVs are causing this, but I don't quite get why they're causing it now but weren't before. I checked my main.css b/c I thought the Footer ID or the DIV class "inner" might be the cause based on definitions in the main.css, but I'm not seeing any width or border definitions that are relevant (to my eye), but ALSO when I remove the DIVs around each image and caption, everything jumps up onto one row. And a new row starts with each new DIV tag.

The site (w/its messed up gallery where I commented out all of the old gallery): TheRealitycomics.com
A URL where you can see it as it was: http://therealitycomics.com/indexB.html (again, this is the page where everything HAD been in rows of 3 or 4 but now is just one long column).

Body:
Try adding this to your main.css. It should set your gallery section so that it displays four items in a row (unless the browser window width is under 800px, then it will display only two items in a row).

.gallery {
    display: flex;
    flex-wrap: wrap;
}

.gallery > div {
    width: 50%;
}

@media (min-width: 800px) {
    .gallery > div {
        width: 25%;
    }
}


问:
Vuejs Laravel Passport - what should I do if access token is expired?
I am using Vuejs SPA with Laravel API as backend. I successfully got the personal access token and store in localStorage and Vuex state like below.

```<code>token: localStorage.getItem('token') || '',
expiresAt: localStorage.getItem('expiresAt') || '',
</code>```

I use the access token every time I send axios request to laravel api. Every thing works well. However, initially the token was set to 1 year expiration so when I develop I didn't care about token being expired and today suddenly I thought what is going to happen if token expired. So I set token expiry to 10 seconds in laravel AuthServiceProvier.php.

```<code>Passport::personalAccessTokensExpireIn(Carbon::now()->addSecond(10));
</code>```

and then I logged in and after 10 seconds, every requests stopped working because the token was expired and got 401 unauthorised error.

In this case, how can I know if the token is expired? I would like to redirect the user to login page if token is expired when the user is using the website.

答:
Be as user friendly as possible. Rather than waiting until the token expires, receiving a 401 error response, and then redirecting, set up a token verification check on the mounted hook of your main SPA instance and have it make a ajax call to e.g. /validatePersonalToken on the server, then do something like this in your routes or controller.

```<code>Route::get('/validatePersonalToken', function () {
      return ['message' => 'is valid'];
})->middleware('auth:api');
</code>```

This should return "error": "Unauthenticated" if the token is not valid.  This way the user will be directed to authenticate before continuing to use the app and submitting data and then potentially losing work (like submitting a form) which is not very user friendly.

You could potentially do this on a component by component basis rather than the main instance by using a Vue Mixin. This would work better for very short lived tokens that might expire while the app is being used. Put the check in the mounted() hook  of the mixin and then use that mixin in any component that makes api calls so that the check is run when that component is mounted. https://v2.vuejs.org/v2/guide/mixins.html

Body:
I am using Vuejs SPA with Laravel API as backend. I successfully got the personal access token and store in localStorage and Vuex state like below.

token: localStorage.getItem('token') || '',
expiresAt: localStorage.getItem('expiresAt') || '',

I use the access token every time I send axios request to laravel api. Every thing works well. However, initially the token was set to 1 year expiration so when I develop I didn't care about token being expired and today suddenly I thought what is going to happen if token expired. So I set token expiry to 10 seconds in laravel AuthServiceProvier.php.

Passport::personalAccessTokensExpireIn(Carbon::now()->addSecond(10));

and then I logged in and after 10 seconds, every requests stopped working because the token was expired and got 401 unauthorised error.

In this case, how can I know if the token is expired? I would like to redirect the user to login page if token is expired when the user is using the website.

Body:
Be as user friendly as possible. Rather than waiting until the token expires, receiving a 401 error response, and then redirecting, set up a token verification check on the mounted hook of your main SPA instance and have it make a ajax call to e.g. /validatePersonalToken on the server, then do something like this in your routes or controller.

Route::get('/validatePersonalToken', function () {
      return ['message' => 'is valid'];
})->middleware('auth:api');

This should return "error": "Unauthenticated" if the token is not valid.  This way the user will be directed to authenticate before continuing to use the app and submitting data and then potentially losing work (like submitting a form) which is not very user friendly.

You could potentially do this on a component by component basis rather than the main instance by using a Vue Mixin. This would work better for very short lived tokens that might expire while the app is being used. Put the check in the mounted() hook  of the mixin and then use that mixin in any component that makes api calls so that the check is run when that component is mounted. https://v2.vuejs.org/v2/guide/mixins.html


问:
What is wrong with my query?? It has no error at all
I have a problem with my sql query in Java. As you can see below, the query is supposed to return rph_id but it returns only 0, so it only proceeds to the else method.

At first, I did not use prepareStatement but many suggest that I use prepareStatement. But it still won't work. After checking both suggestions, I think my problem is on the query but I don't know what.

```<code>    public class RphDAO{
    static int rph_id;

    public static RPHS getRph(RPHS rph) {
                    try {
                        currentCon = ConnectionManager.getConnection();
                        ps=currentCon.prepareStatement("select * from rphs where rph_id=?");

                        ps.setInt(1, rph_id);
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            rs.getInt("rph_id");
                            rph.setRph_id(rph_id);
                            rph.setValid(true);
                        } else  {
                            rph.setValid(false);
                        }
                    }
                ...
                return rph;
            }
}
</code>```

It should return an existing id, not 0.

答:
I think you should use COUNT instead in your sql since it is no point in setting the id if it is already correct and also use the id from the object given as parameter to the method for consistency.</p>

```<code>public static RPHS getRph(RPHS rph) {
    try {
        currentCon = ConnectionManager.getConnection();
        ps=currentCon.prepareStatement("select COUNT(*) from rphs where rph_id=?");

        ps.setInt(1, rph.getRph_id);
        ResultSet rs = ps.executeQuery();

        int count = 0;
        if (rs.next()) {
            count = rs.getInt(1);
        }
        rph.setValid(count == 1);
    }
</code>```

Body:
I have a problem with my sql query in Java. As you can see below, the query is supposed to return rph_id but it returns only 0, so it only proceeds to the else method.

At first, I did not use prepareStatement but many suggest that I use prepareStatement. But it still won't work. After checking both suggestions, I think my problem is on the query but I don't know what.

    public class RphDAO{
    static int rph_id;

    public static RPHS getRph(RPHS rph) {
                    try {
                        currentCon = ConnectionManager.getConnection();
                        ps=currentCon.prepareStatement("select * from rphs where rph_id=?");

                        ps.setInt(1, rph_id);
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            rs.getInt("rph_id");
                            rph.setRph_id(rph_id);
                            rph.setValid(true);
                        } else  {
                            rph.setValid(false);
                        }
                    }
                ...
                return rph;
            }
}

It should return an existing id, not 0.

Body:
I think you should use COUNT instead in your sql since it is no point in setting the id if it is already correct and also use the id from the object given as parameter to the method for consistency.

public static RPHS getRph(RPHS rph) {
    try {
        currentCon = ConnectionManager.getConnection();
        ps=currentCon.prepareStatement("select COUNT(*) from rphs where rph_id=?");

        ps.setInt(1, rph.getRph_id);
        ResultSet rs = ps.executeQuery();

        int count = 0;
        if (rs.next()) {
            count = rs.getInt(1);
        }
        rph.setValid(count == 1);
    }


问:
How to get HH:MM:SS difference using milliseconds in javascript?
I have two times like one is 145:02:31 and another one is 01:00:00 and I want to calculate the difference between these two times like 144:02:31 but right now I am getting 13:02:31 which is wrong.

Please help me thank you.

答:
```<code>var duration = moment.duration(endTime.diff(startTime));
var hours = duration.asHours();
</code>```

It will give you the time difference in hours.

Body:
var duration = moment.duration(endTime.diff(startTime));
var hours = duration.asHours();

It will give you the time difference in hours.


问:
In Vivado, how to instantiate a user defined "Block Diagram" inside of the top-level "Block Diagram"?
I've imported my VHDL code into a user defined Block Design, and I exported my I/O interfaces from this block design, now I need to instantiate this Block Design in the top level Block Design that contains the Xilinx Zynq Arm core and AXI interconnect.  When I right click on the Top-level Block Diagram, I see two choices:

"Add Module"
"Add IP"

neither of these two options lists the Block Design that I created to instantiate my VHDL code.  Any ideas on how to get this to work?

If you create a user defined Block Design, how can you instantiate it inside of another Block Design, specifically the top-level Block Design.

答:
You can only use 'add module' if the top level is Verilog or VHDL.
(Of course you still have to add the source code files to the project using the big '+') button)

The top level module should not be System-Verilog or VHDL2008. It will not show up in the list. You can uncheck the 'hide incompatible module' box after which it shows the incompatible modules but you still can't add them.

You can turn System-Verilog or VHDL2008 in to IP using the Xilinx IP flow and then you can add them.
But I find it rather cumbersome and I also do not see the use of making IP to replace it again and again with a 'new' version until it has been verified.

So adapt the top-level or write a wrapper.


问:
How sub is getting executed?
How is sub printing 24 because i will get ['24'] and sub should only run once? and I am totally confused how sub can print integer 24 because inner for loop will run only once.

l1=[['24']]
for i in l1:
    print(i)
    for sub in i:
        print(sub)
```

<p>output is:</p>

```['24']
24
```

答:
If you do not understand your output, add more prints (and/or data) to it until you do:

```<code>l1=[['24',"Y"],"X"]
for i in l1:                   # iterates all elements of the outer list
    print("i is:",i, type(i))
    for sub in i:              # iterates all elements of the inner list
        print("sub is:",sub, type(sub))
        for s in sub:          # iterates the single characters of your string
            print("s is:",s,type(s))
</code>```

Output (formatted):

```<code>i is: ['24', 'Y'] <class 'list'>
    sub is: 24 <class 'str'>
        s is: 2 <class 'str'>
        s is: 4 <class 'str'>
    sub is: Y <class 'str'>
        s is: Y <class 'str'>
i is: X <class 'str'>
    sub is: X <class 'str'>
        s is: X <class 'str'>
</code>```

See How to debug small programs

Title: How sub is getting executed?

Body:
How is sub printing 24 because i will get ['24'] and sub should only run once? and I am totally confused how sub can print integer 24 because inner for loop will run only once.

l1=[['24']]
for i in l1:
    print(i)
    for sub in i:
        print(sub)

output is:

['24']
24

Body:
If you do not understand your output, add more prints (and/or data) to it until you do:

l1=[['24',"Y"],"X"]
for i in l1:                   # iterates all elements of the outer list
    print("i is:",i, type(i))
    for sub in i:              # iterates all elements of the inner list
        print("sub is:",sub, type(sub))
        for s in sub:          # iterates the single characters of your string
            print("s is:",s,type(s))

Output (formatted):

i is: ['24', 'Y'] <class 'list'>
    sub is: 24 <class 'str'>
        s is: 2 <class 'str'>
        s is: 4 <class 'str'>
    sub is: Y <class 'str'>
        s is: Y <class 'str'>
i is: X <class 'str'>
    sub is: X <class 'str'>
        s is: X <class 'str'>

See How to debug small programs


问:
How to handle large dates with momentjs?
I am trying to find a difference in months between two moment objects. I did as follows:

```<code>const current = moment()
const future = moment().add('324523546345634563456345','months')
const diff = future.diff(current, 'months')
</code>```

The diff comes out as 0. Why is that? Is there a different way to handle large numbers like 324523546345634563456345?

答:
Short answer: your input exceeds the limitations of JavaScript's built-in integer and Date types. To do calculations with such large numbers, use type BigInt. (Most date libraries like MomentJS won't support BigInt, one of the reasons being regular integers provide a reasonable range of dates.)

The largest integer that can be represented by JavaScript built-in numbers is 9,007,199,254,740,991. Floating point numbers go much higher, but probably don't make sense for this type of use case (there would be too many floating point gaps).

Your input: 324,523,546,345,634,563,456,345 is many orders of magnitude greater than what JavaScript built-in integers support. This is even before considering the additional orders of magnitude after converting months to milliseconds.

Frankly, I'm surprised the result was 0 and not NaN.

Furthermore, I believe MomentJS internally uses the built-in JavaScript Date type. The max date is about the year 275,760. Your input would require support for a year way, way past this year. In fact, your input is greater than the age of the universe.

If you really need to make such a calculation, you could use BigInts. You'll probably have to do the calculations manually because I don't think any time-related library will support such large dates.

Body:
I am trying to find a difference in months between two moment objects. I did as follows:

const current = moment()
const future = moment().add('324523546345634563456345','months')
const diff = future.diff(current, 'months')

The diff comes out as 0. Why is that? Is there a different way to handle large numbers like 324523546345634563456345?


问:
struggling in understanding terms in the Delegate world
I'm new to C#, I'm very confused with the terms used like 'listener', 'caller', 'callback', 'EventHandler', let's say we have the following code below:

```<code>public class Car
{
    public delegate void CarEngineHandler();
    public CarEngineHandler listOfHandlers;
    public void Accelerate(int delta)
    {
       if (delta > 80)
          listOfHandlers();    // not checking null for simplicity
    }
}

class Program
{
    static void Main(string[] args)
    {
         Car myCar = new Car();
         myCar.listOfHandlers = new Car.CarEngineHandler(CallWhenExploded);
         myCar.Accelerate(120);
    }

    static void CallWhenExploded()
    {
       Console.WriteLine("Sorry, this car is dead...");
    }
}

</code>```

so in this scenario:

Who is the caller?

Who is the listener? listen to what?

Who is the callback?

Who is the EventHandler?

and my answer is:

The caller is myCar

not sure

The callback is CallWhenExploded() static function

EventHandler is listOfHandlers

am I correct? I really don't know who is the listener and listen to what.

答:
Hopefully you understand that an variable of type string is like a bucket that holds a string of characters, and you can look at them individually, pass them round as a collection etc. It's quite an easy thing to visualize, this variable being a container that stores data, because we store data all the time in the real world; pieces of paper in a box/file etc

Delegates are like variables for methods - and this is a much harder concept to understand, that we can pass a method round as though it were just like data, and we can get the computer to run the method.. but that's what a delegate is. When you declare a delegate, it's like when you declare your own class:

```<code>delegate void SomeMethod(); //specify a delegate

class Person{               //specify a class
  string FirstName;
  string LastName;
}
</code>```

Just like when you make a class, you're giving yourself the ability to create an instance of that class, when you declare a delegate you're giving yourself the ability to create an instance of that delegate. Your class instance refers to data, like here the first and last name of the person. A delegate instance refers to a method rather than referring to data. You can make one class instance that refers to "John" and "Smith". You can make a delegate instance that refers to Method1(). You can make another class instance that refers to "Bill" "Jones". You can make another delegate instance that refers to Method2().

You can associate any method with your delegate instance, so long as the method has a signature that is equal to the delegate. That delegate above will accept a reference to any method that takes no parameters and returns void. If you've got one or more of these kind of methods you can attach them to an instance of the delegate, pass the delegate instance like a variable, and the thing you've passed the delegate to can call the methods without needing to know what the method name is or anything about it.

Why would we want to do this? One major use of delegates is in event handling. Microsoft created UI controls that are capable of doing things - buttons you can click on. You'll want your button to do something when it's clicked, but everyone in the world will want their button to do something different when it's clicked, so Microsoft can't write the code for that. They can however say that they will make a button that takes a delegate (a method passed like a variable) and the button promises to call the method when it is clicked. You supply the code that does what you want, as a delegate, to the button. Your method has to have a certain signature (arguments) because the button wants to pass your method some data that may be helpful to you; perhaps the location of the mouse when the clock occurred, or the number of times it was clicked. UI components have hundreds of different kinds of events, they all run on delegates

Another good example of delegates is in the old style of async programming when we had Begin/End pairs of methods, calling Begin would typically start a new thread off doing something and we would have to supply a method (our method) to it that, when Microsoft's Begin method had finished doing something it would call our method to let us know it was done. Typically then our code would call End, passing in some reference our method had been given, and we'd get the result. Sending a request to a server would take some time, for example, so we'd Begin it, go do some other things, and when the response was ready we would be notified by our delegate being called and we would process the result

So, get used to the notion that a delegate is just a way or referring to a method, you pass it around, what you pass it to can run it and provide data to it without having a clue what it does. In terminology it is also referred to as a callback - the thing that will be called when the foreign method is done with its work, though it's a fairly loose term - it might be used to refer to either your method that does the work, or the instance of a delegate pointing to your method, the thing that is passed in. Effectively they're equivalent dependi on the context of the conversation

A delegate itself is more like a collection/array - you can attach multiple methods to it and when the delegate is called they will all run, though not in any defined order. In your example you assigned just one to it but it could be multiple:

```<code>SomeMethod delegs = null;
delegs += new SomeMethod(MyMethod1);
delegs += new SomeMethod(MyMethod2);
</code>```

Invoking that delegate will cause both MyMethod1 and MyMethod2 to be run, possibly in 2,1 order

Events are delegates too, but they're a slightly special case, touched on above with the button click handler. When a delegate is specified with the event keyword it can only be invoked inside the class that declared the delegate variable. UI controls use this to ensure that only they can run the delegate; you can't reach into a button and force run its clock handlers yourself because the delegate list that handles a click is declared as an event. If you want to programmatically cause a button to fire its event handler list you normally have to subclass it so your code becomes operationally "inside" the button code

Listener as a phrase is more often associated with events but it's reasonably synonymous with callback and eventhandler - when you add a listener to an event, you're saying that you're writing code that will handle the occurrence of the event, your code (as a delegate/event handler) that acts when the event occurs. It doesn't "listen" per se; it just hangs around and gets kicked into action when the thing raising the event invokes the list of delegates/eventhandlers associated with the event.

As an aside, because delegate instances represent a variable that points to a method, i.e. they point to an action, your naming of the instances should be a verb, not a noun. You called yours listOfHandlers but it would have been more helpful to your understanding to call the delegate instance after the event/action that is occurring. The use case you were applying was one of overrevving so perhaps you should name it CarEngineOverRevving. You could have another for when the temperature exceeds. If both these delegates has the same signature (you want people who will handle these events to do so via a method with no arguments) then you can reuse the same delegate for the different events:

```<code>public void delegate CarEngineProblemHandler();
public CarEngineProblemHandler CarEngineOverRevving = null;
public CarEngineProblemHandler CarEngineOverheating = null;
</code>```

The delegate is your way of declaring what you want the methods provided to you, that you will call, to look like. The list of named problems is what you are declaring other people can provide some handling for. I could decide to not give you a handler for overrevving because I will never do it, but overheating might happen anyway so I'll certainly give you a handler/listener/delegate/callback to call of it ever happens

Body:
I'm new to C#, I'm very confused with the terms used like 'listener', 'caller', 'callback', 'EventHandler', let's say we have the following code below:

public class Car
{
    public delegate void CarEngineHandler();
    public CarEngineHandler listOfHandlers;
    public void Accelerate(int delta)
    {
       if (delta > 80)
          listOfHandlers();    // not checking null for simplicity
    }
}

class Program
{
    static void Main(string[] args)
    {
         Car myCar = new Car();
         myCar.listOfHandlers = new Car.CarEngineHandler(CallWhenExploded);
         myCar.Accelerate(120);
    }

    static void CallWhenExploded()
    {
       Console.WriteLine("Sorry, this car is dead...");
    }
}

so in this scenario:

Who is the caller?

Who is the listener? listen to what?

Who is the callback?

Who is the EventHandler?

and my answer is:

The caller is myCar

not sure

The callback is CallWhenExploded() static function

EventHandler is listOfHandlers

am I correct? I really don't know who is the listener and listen to what.

Body:
Hopefully you understand that an variable of type string is like a bucket that holds a string of characters, and you can look at them individually, pass them round as a collection etc. It's quite an easy thing to visualize, this variable being a container that stores data, because we store data all the time in the real world; pieces of paper in a box/file etc

Delegates are like variables for methods - and this is a much harder concept to understand, that we can pass a method round as though it were just like data, and we can get the computer to run the method.. but that's what a delegate is. When you declare a delegate, it's like when you declare your own class:

delegate void SomeMethod(); //specify a delegate

class Person{               //specify a class
  string FirstName;
  string LastName;
}

Just like when you make a class, you're giving yourself the ability to create an instance of that class, when you declare a delegate you're giving yourself the ability to create an instance of that delegate. Your class instance refers to data, like here the first and last name of the person. A delegate instance refers to a method rather than referring to data. You can make one class instance that refers to "John" and "Smith". You can make a delegate instance that refers to Method1(). You can make another class instance that refers to "Bill" "Jones". You can make another delegate instance that refers to Method2().

You can associate any method with your delegate instance, so long as the method has a signature that is equal to the delegate. That delegate above will accept a reference to any method that takes no parameters and returns void. If you've got one or more of these kind of methods you can attach them to an instance of the delegate, pass the delegate instance like a variable, and the thing you've passed the delegate to can call the methods without needing to know what the method name is or anything about it.

Why would we want to do this? One major use of delegates is in event handling. Microsoft created UI controls that are capable of doing things - buttons you can click on. You'll want your button to do something when it's clicked, but everyone in the world will want their button to do something different when it's clicked, so Microsoft can't write the code for that. They can however say that they will make a button that takes a delegate (a method passed like a variable) and the button promises to call the method when it is clicked. You supply the code that does what you want, as a delegate, to the button. Your method has to have a certain signature (arguments) because the button wants to pass your method some data that may be helpful to you; perhaps the location of the mouse when the clock occurred, or the number of times it was clicked. UI components have hundreds of different kinds of events, they all run on delegates

Another good example of delegates is in the old style of async programming when we had Begin/End pairs of methods, calling Begin would typically start a new thread off doing something and we would have to supply a method (our method) to it that, when Microsoft's Begin method had finished doing something it would call our method to let us know it was done. Typically then our code would call End, passing in some reference our method had been given, and we'd get the result. Sending a request to a server would take some time, for example, so we'd Begin it, go do some other things, and when the response was ready we would be notified by our delegate being called and we would process the result

So, get used to the notion that a delegate is just a way or referring to a method, you pass it around, what you pass it to can run it and provide data to it without having a clue what it does. In terminology it is also referred to as a callback - the thing that will be called when the foreign method is done with its work, though it's a fairly loose term - it might be used to refer to either your method that does the work, or the instance of a delegate pointing to your method, the thing that is passed in. Effectively they're equivalent dependi on the context of the conversation

A delegate itself is more like a collection/array - you can attach multiple methods to it and when the delegate is called they will all run, though not in any defined order. In your example you assigned just one to it but it could be multiple:

SomeMethod delegs = null;
delegs += new SomeMethod(MyMethod1);
delegs += new SomeMethod(MyMethod2);

Invoking that delegate will cause both MyMethod1 and MyMethod2 to be run, possibly in 2,1 order

Events are delegates too, but they're a slightly special case, touched on above with the button click handler. When a delegate is specified with the event keyword it can only be invoked inside the class that declared the delegate variable. UI controls use this to ensure that only they can run the delegate; you can't reach into a button and force run its clock handlers yourself because the delegate list that handles a click is declared as an event. If you want to programmatically cause a button to fire its event handler list you normally have to subclass it so your code becomes operationally "inside" the button code

Listener as a phrase is more often associated with events but it's reasonably synonymous with callback and eventhandler - when you add a listener to an event, you're saying that you're writing code that will handle the occurrence of the event, your code (as a delegate/event handler) that acts when the event occurs. It doesn't "listen" per se; it just hangs around and gets kicked into action when the thing raising the event invokes the list of delegates/eventhandlers associated with the event.

As an aside, because delegate instances represent a variable that points to a method, i.e. they point to an action, your naming of the instances should be a verb, not a noun. You called yours listOfHandlers but it would have been more helpful to your understanding to call the delegate instance after the event/action that is occurring. The use case you were applying was one of overrevving so perhaps you should name it CarEngineOverRevving. You could have another for when the temperature exceeds. If both these delegates has the same signature (you want people who will handle these events to do so via a method with no arguments) then you can reuse the same delegate for the different events:

public void delegate CarEngineProblemHandler();
public CarEngineProblemHandler CarEngineOverRevving = null;
public CarEngineProblemHandler CarEngineOverheating = null;

The delegate is your way of declaring what you want the methods provided to you, that you will call, to look like. The list of named problems is what you are declaring other people can provide some handling for. I could decide to not give you a handler for overrevving because I will never do it, but overheating might happen anyway so I'll certainly give you a handler/listener/delegate/callback to call of it ever happens


问:
Add Call Extension to Search Ads based on API call

I am making click to call based ad which you might see in the above example image. What I want to achieve is that I want to show that number dynamically, meaning that when the call representative is available it shows in the ad but when the representative is not available then the ad wouldn't show the click to call button.

To clear this more: I want to make an API call to the server which will tell me if any representative is available or not.

I am using JavaScript for my front-end and back-end, so let me know if I can do it using that or any other suggestions are welcome too.

What I have done so far:
As per my research I can not this, but I may be wrong and that's why I am posting a question here. Thanks in advance.

答:
No this is not possible.

If you have clear working hours for callcenters then you can schedule ad with and without Call Extension ads based on that.

Reference : Create an ad schedule


问:
How do I update an html table after each XML call to the server without refreshing the page?
I have a mySQL table loaded with 50 rows. Each row has the necessary information to process a credit card. When the user clicks on Process Credit Cards, query the table and display each row on the page using html. Once the data has been displayed on the page a scrip would begin to process each row through the merchant account and turn the corresponding row either red for decline or green for approve without refreshing the page after each transaction. I think I need to use AJAX or jQuery to make this happen but I'm not sure I'm headed in the right direction. Here is the script to process the transactions:

```<code><?php
$request = new GatewayRequest();
$response = new GatewayResponse();
$service = new GatewayService();

$request->Set(GatewayRequest::MERCHANT_ID(), "111111111111111");
$request->Set(GatewayRequest::MERCHANT_PASSWORD(), "xxxxxxxxxxxx");

$time = time();
$request->Set(GatewayRequest::MERCHANT_CUSTOMER_ID(), $time . '.PHPTest');
$request->Set(GatewayRequest::MERCHANT_INVOICE_ID(), $time . '.SaleTest');

$request->Set(GatewayRequest::AMOUNT(), "9.99");
$request->Set(GatewayRequest::CARDNO(), "4111111111111111");
$request->Set(GatewayRequest::EXPIRE_MONTH(), "02");
$request->Set(GatewayRequest::EXPIRE_YEAR(), "2010");
$request->Set(GatewayRequest::CVV2(), "999");

$request->Set(GatewayRequest::CUSTOMER_FIRSTNAME(), "Joe");
$request->Set(GatewayRequest::CUSTOMER_LASTNAME(), "PHPTester");
$request->Set(GatewayRequest::EMAIL(), "phptest@fakedomain.com");
$request->Set(GatewayRequest::IPADDRESS(), $_SERVER['REMOTE_ADDR']);

$request->Set(GatewayRequest::BILLING_ADDRESS(), "123 Main St");
$request->Set(GatewayRequest::BILLING_CITY(), "Las Vegas");
$request->Set(GatewayRequest::BILLING_STATE(), "NV");
$request->Set(GatewayRequest::BILLING_ZIPCODE(), "89141");
$request->Set(GatewayRequest::BILLING_COUNTRY(), "US");

$request->Set(GatewayRequest::SCRUB(), "IGNORE");
$request->Set(GatewayRequest::CVV2_CHECK(), "IGNORE");
$request->Set(GatewayRequest::AVS_CHECK(), "IGNORE");

$service->SetTestMode(TRUE);

if ($service->PerformPurchase($request, $response)) {
  print "Purchase succeeded\n";
  print "Response Code: " .
    $response->Get(GatewayResponse::RESPONSE_CODE()) . "\n";
  print "Reasone Code: " .
    $response->Get(GatewayResponse::REASON_CODE()) . "\n";
  print "Auth No: " . $response->Get(GatewayResponse::AUTH_NO()) . "\n";
  print "AVS: " . $response->Get(GatewayResponse::AVS_RESPONSE()) . "\n";
  print "CVV2: " . $response->Get(GatewayResponse::CVV2_CODE()) . "\n";
  print "GUID: " . $response->Get(GatewayResponse::TRANSACT_ID()) . "\n";
  print "Account: " .
    $response->Get(GatewayResponse::MERCHANT_ACCOUNT()) . "\n";
  print "Scrub: " .
    $response->Get(GatewayResponse::SCRUB_RESULTS()) . "\n";
} else {
  print "Purchase failed\n";
  print "GUID: " . $response->Get(GatewayResponse::TRANSACT_ID()) . "\n";
  print "Response Code: " .
    $response->Get(GatewayResponse::RESPONSE_CODE()) . "\n";
  print "Reasone Code: " .
    $response->Get(GatewayResponse::REASON_CODE()) . "\n";
  print "Exception: " .
    $response->Get(GatewayResponse::EXCEPTION()) . "\n";
  print "Scrub: " .
    $response->Get(GatewayResponse::SCRUB_RESULTS()) . "\n";
}

?>
</code>```

Will this type of code work with AJAX or jQuery without being rewritten? Any help would be appreciated.

答: Anything can be made to work without being rewritten, but you've set yourself up for a lot of headaches there.  You'll probably have much better luck (and save yourself tons of time) by formatting all those print statements into an array and JSON encoding it.  Obviously javascript loves JSON.</p>

Body:
I have a mySQL table loaded with 50 rows. Each row has the necessary information to process a credit card. When the user clicks on Process Credit Cards, query the table and display each row on the page using html. Once the data has been displayed on the page a scrip would begin to process each row through the merchant account and turn the corresponding row either red for decline or green for approve without refreshing the page after each transaction. I think I need to use AJAX or jQuery to make this happen but I'm not sure I'm headed in the right direction. Here is the script to process the transactions:

<?php
$request = new GatewayRequest();
$response = new GatewayResponse();
$service = new GatewayService();

$request->Set(GatewayRequest::MERCHANT_ID(), "111111111111111");
$request->Set(GatewayRequest::MERCHANT_PASSWORD(), "xxxxxxxxxxxx");

$time = time();
$request->Set(GatewayRequest::MERCHANT_CUSTOMER_ID(), $time . '.PHPTest');
$request->Set(GatewayRequest::MERCHANT_INVOICE_ID(), $time . '.SaleTest');

$request->Set(GatewayRequest::AMOUNT(), "9.99");
$request->Set(GatewayRequest::CARDNO(), "4111111111111111");
$request->Set(GatewayRequest::EXPIRE_MONTH(), "02");
$request->Set(GatewayRequest::EXPIRE_YEAR(), "2010");
$request->Set(GatewayRequest::CVV2(), "999");

$request->Set(GatewayRequest::CUSTOMER_FIRSTNAME(), "Joe");
$request->Set(GatewayRequest::CUSTOMER_LASTNAME(), "PHPTester");
$request->Set(GatewayRequest::EMAIL(), "phptest@fakedomain.com");
$request->Set(GatewayRequest::IPADDRESS(), $_SERVER['REMOTE_ADDR']);

$request->Set(GatewayRequest::BILLING_ADDRESS(), "123 Main St");
$request->Set(GatewayRequest::BILLING_CITY(), "Las Vegas");
$request->Set(GatewayRequest::BILLING_STATE(), "NV");
$request->Set(GatewayRequest::BILLING_ZIPCODE(), "89141");
$request->Set(GatewayRequest::BILLING_COUNTRY(), "US");

$request->Set(GatewayRequest::SCRUB(), "IGNORE");
$request->Set(GatewayRequest::CVV2_CHECK(), "IGNORE");
$request->Set(GatewayRequest::AVS_CHECK(), "IGNORE");

$service->SetTestMode(TRUE);

if ($service->PerformPurchase($request, $response)) {
  print "Purchase succeeded\n";
  print "Response Code: " .
    $response->Get(GatewayResponse::RESPONSE_CODE()) . "\n";
  print "Reasone Code: " .
    $response->Get(GatewayResponse::REASON_CODE()) . "\n";
  print "Auth No: " . $response->Get(GatewayResponse::AUTH_NO()) . "\n";
  print "AVS: " . $response->Get(GatewayResponse::AVS_RESPONSE()) . "\n";
  print "CVV2: " . $response->Get(GatewayResponse::CVV2_CODE()) . "\n";
  print "GUID: " . $response->Get(GatewayResponse::TRANSACT_ID()) . "\n";
  print "Account: " .
    $response->Get(GatewayResponse::MERCHANT_ACCOUNT()) . "\n";
  print "Scrub: " .
    $response->Get(GatewayResponse::SCRUB_RESULTS()) . "\n";
} else {
  print "Purchase failed\n";
  print "GUID: " . $response->Get(GatewayResponse::TRANSACT_ID()) . "\n";
  print "Response Code: " .
    $response->Get(GatewayResponse::RESPONSE_CODE()) . "\n";
  print "Reasone Code: " .
    $response->Get(GatewayResponse::REASON_CODE()) . "\n";
  print "Exception: " .
    $response->Get(GatewayResponse::EXCEPTION()) . "\n";
  print "Scrub: " .
    $response->Get(GatewayResponse::SCRUB_RESULTS()) . "\n";
}

?>

Will this type of code work with AJAX or jQuery without being rewritten? Any help would be appreciated.


问:
Update table1.Col1 with Table2.Col1 when some charter in column match
I have two tables, I want to update Col1 in Tbl1 with Col1 in Tbl2. However I want to update for rows where only some characters of Col2.Tbl1 match with Col2.Tbl2

Table 1

```<code>PK  Col1    Col2
1   NULL    abc123xyz
2   NULL    3da234oaz
3   NULL    dbc567gyz
4   NULL    agc890hyz
5   NULL    adc012jyz
</code>```

Table 2

```<code>PK  Col1    Col2
1   001     123
2   002     234
3   003     567
4   004     890
5   005     012
</code>```

Current query:

```<code>Update A
set A.Col1 = B.Col1
from Table 1 A, Table 2 B
where A.Col2 like %B.Col1%
</code>```

But it didn't work.

答:
You are using the wrong column, right? In your current UPDATE you try to find the value of Table2.Col1 in Table1.Col2. In this case there is not match between these columns. You describe the match as follow:

I want to update for rows where only some characters of Tbl1.Col2 match with Tbl2.Col2

So you can use one of the following solutions using CHARINDEX or LIKE:

```<code>UPDATE A
  SET A.Col1 = B.Col1
FROM  Table1 A, Table2 B
WHERE CHARINDEX(B.Col2, A.Col2) > 0
</code>```

... using the following using a INNER JOIN:

```<code>UPDATE A
  SET A.Col1 = B.Col1
FROM Table1 A INNER JOIN Table2 B ON CHARINDEX(B.Col2, A.Col2) > 0
</code>```

... or using the LIKE (but with the correct column):

```<code>UPDATE A
  SET A.Col1 = B.Col1
FROM Table1 A, Table2 B
WHERE A.Col2 LIKE '%' + B.Col2 + '%'
</code>```

demo on dbfiddle.uk

Body:
I have two tables, I want to update Col1 in Tbl1 with Col1 in Tbl2. However I want to update for rows where only some characters of Col2.Tbl1 match with Col2.Tbl2

Table 1

PK  Col1    Col2
1   NULL    abc123xyz
2   NULL    3da234oaz
3   NULL    dbc567gyz
4   NULL    agc890hyz
5   NULL    adc012jyz

Table 2

PK  Col1    Col2
1   001     123
2   002     234
3   003     567
4   004     890
5   005     012

Current query:

Update A
set A.Col1 = B.Col1
from Table 1 A, Table 2 B
where A.Col2 like %B.Col1%

But it didn't work.

Body:
You are using the wrong column, right? In your current UPDATE you try to find the value of Table2.Col1 in Table1.Col2. In this case there is not match between these columns. You describe the match as follow:

I want to update for rows where only some characters of Tbl1.Col2 match with Tbl2.Col2

So you can use one of the following solutions using CHARINDEX or LIKE:

UPDATE A
  SET A.Col1 = B.Col1
FROM  Table1 A, Table2 B
WHERE CHARINDEX(B.Col2, A.Col2) > 0

... using the following using a INNER JOIN:

UPDATE A
  SET A.Col1 = B.Col1
FROM Table1 A INNER JOIN Table2 B ON CHARINDEX(B.Col2, A.Col2) > 0

... or using the LIKE (but with the correct column):

UPDATE A
  SET A.Col1 = B.Col1
FROM Table1 A, Table2 B
WHERE A.Col2 LIKE '%' + B.Col2 + '%'

demo on dbfiddle.uk