问:
Filtering a ListView - not how I thought it would work../
was hoping you might be able to help me with a problem I've been having. I have a listview that is filtered by an editbox. I figured it would filter, based on the text in the edittext, through any part of the text in the listview. So if I have three items in the listview, "Cupcake", "Donut", "Eclair" and "Froyo", and I typed in "cl", it would't return anything...but if I typed in "ecl", it would return "Eclair". Sorry if I worded it terribly...it's a bit hard to explain. Here's my code:</p>

```<code>private EditText ed;
private String lv_arr[]={"Cupcake","Donut","Eclair","Froyo"};
ArrayAdapter<String> arrad;

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.search);

     ed = (EditText) findViewById(R.id.edit);
     ListView list = (ListView) findViewById(R.id.listviewtest);
     arrad =  new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr);
     list.setAdapter(arrad);
     list.setTextFilterEnabled(true);

     ed.addTextChangedListener(new TextWatcher() {
         @Override
         public void onTextChanged( CharSequence arg0, int arg1, int arg2, int arg3) {
             SearchByName.this.arrad.getFilter().filter(arg0);
         }

         @Override
         public void beforeTextChanged( CharSequence arg0, int arg1, int arg2, int arg3) {

        }

        @Override
        public void afterTextChanged( Editable arg0) {

        }
   });
}
</code>```

答:
if you look at the sourcecode for the arrayadapter it will only filter on the first letters of any given word in your list item (so given an item of "eclair donut" it will match on "ecl" or "don" but not "air" or "nut":
here is the relevant code from the ArrayAdapter.java

```<code>      for (int i = 0; i < count; i++) {
            final T value = values.get(i);
            final String valueText = value.toString().toLowerCase();

            // First match against the whole, non-splitted value
            if (valueText.startsWith(prefixString)) {
                newValues.add(value);
            } else {
                final String[] words = valueText.split(" ");
                final int wordCount = words.length;

                for (int k = 0; k < wordCount; k++) {
                    if (words[k].startsWith(prefixString)) {
                        newValues.add(value);
                        break;
                    }
                }
            }
        }
</code>```

if you want to filter for any instance of your pattern in the middle of words, you will need to write your own adapter. that implements Filterable

Body:
was hoping you might be able to help me with a problem I've been having. I have a listview that is filtered by an editbox. I figured it would filter, based on the text in the edittext, through any part of the text in the listview. So if I have three items in the listview, "Cupcake", "Donut", "Eclair" and "Froyo", and I typed in "cl", it would't return anything...but if I typed in "ecl", it would return "Eclair". Sorry if I worded it terribly...it's a bit hard to explain. Here's my code:

private EditText ed;
private String lv_arr[]={"Cupcake","Donut","Eclair","Froyo"};
ArrayAdapter<String> arrad;

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.search);

     ed = (EditText) findViewById(R.id.edit);
     ListView list = (ListView) findViewById(R.id.listviewtest);
     arrad =  new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr);
     list.setAdapter(arrad);
     list.setTextFilterEnabled(true);

     ed.addTextChangedListener(new TextWatcher() {
         @Override
         public void onTextChanged( CharSequence arg0, int arg1, int arg2, int arg3) {
             SearchByName.this.arrad.getFilter().filter(arg0);
         }

         @Override
         public void beforeTextChanged( CharSequence arg0, int arg1, int arg2, int arg3) {

        }

        @Override
        public void afterTextChanged( Editable arg0) {

        }
   });
}

Body:
if you look at the sourcecode for the arrayadapter it will only filter on the first letters of any given word in your list item (so given an item of "eclair donut" it will match on "ecl" or "don" but not "air" or "nut":
here is the relevant code from the ArrayAdapter.java

      for (int i = 0; i < count; i++) {
            final T value = values.get(i);
            final String valueText = value.toString().toLowerCase();

            // First match against the whole, non-splitted value
            if (valueText.startsWith(prefixString)) {
                newValues.add(value);
            } else {
                final String[] words = valueText.split(" ");
                final int wordCount = words.length;

                for (int k = 0; k < wordCount; k++) {
                    if (words[k].startsWith(prefixString)) {
                        newValues.add(value);
                        break;
                    }
                }
            }
        }

if you want to filter for any instance of your pattern in the middle of words, you will need to write your own adapter. that implements Filterable


来源: stackexchange

问:
PHP MySQL Group by multiple conditions in a unique situation
I'm working with data managed by another department and I'm getting duplicates.

There are 3 different unique identifies:

```<code>Order Number
Company Name
Company Entity
</code>```

Sometimes its the same company name but a different order number.

Sometimes its the same company name but a different company entity.

Sometimes its the same order number but different company name.

Sometimes its the same order number but different company entity.

Sometimes its the same company entity but different order number.

Sometimes its the same company entity but different company name.

Sometimes the company names are abbreviated like Apple, Apple Inc, Apple NYC, Etc.

Below I have a table with example data:

```<code>CompanyName      CompanyEntity   OrderNumber
Apple            123             555123
Apple            123             555123
Telsa            888             444444
Telsa            777             222222
Apple NYC        103             544523
Stack            222             511523
Stack            222             144523
</code>```

I need to group by the company name or company entity or order number.

I tried:

```<code> $query = "SELECT
 nextgenorders2.nextgenorder_ordernumber,
 nextgenorders2.nextgenorder_serial,
 nextgenorders2.nextgenorder_company_entity,
 nextgenorders2.nextgenorder_companyname,
 nextgenorders2.nextgenorder_deliverydate,
 FROM nextgenorders2
 WHERE nextgenorders2.nextgenorder_deliverydate='2020-11-11'
 GROUP BY nextgenorders2.nextgenorder_companyname,
          nextgenorders2.nextgenorder_company_entity,
          nextgenorders2.nextgenorder_ordernumber
 ";
</code>```

That query produces:

```<code>CompanyName      CompanyEntity   OrderNumber
Apple            123             555123
Telsa            888             444444
Telsa            777             222222
Apple NYC        103             544523
Stack            222             511523
</code>```

If the row has the same company name, company entity and order number it's put into a group.

If the row doesn't have the same company entity, company name and order number it's not put into a group.

I want the query to produce this:

```<code>CompanyName      CompanyEntity   OrderNumber
Apple            123             555123
Telsa            888             444444
Stack            222             144523
</code>```

but I'll take this because of the multiple company name abbrievations:

```<code>CompanyName      CompanyEntity   OrderNumber
Apple            123             555123
Telsa            777             222222
Apple NYC        103             544523
Stack            222             511523
</code>```

Thank you for your help.

答:
You can do something like this

But for every column you have do decide what to do with it.
Like MIN(n2.nextgenorder_company_entity), but if you want to keep all you can use GROUP_CONCAT for example

```<code>CREATE TABLE nextgenorders2
    (`nextgenorder_companyname` varchar(9), `nextgenorder_company_entity` int, `nextgenorder_ordernumber` int, nextgenorder_deliverydate date)
;

INSERT INTO nextgenorders2
    (`nextgenorder_companyname`, `nextgenorder_company_entity`, `nextgenorder_ordernumber`,nextgenorder_deliverydate)
VALUES
    ('Apple', 123, 555123,'2020-11-11'),
    ('Apple', 123, 555123,'2020-11-11'),
    ('Telsa', 888, 444444,'2020-11-11'),
    ('Telsa', 777, 222222,'2020-11-11'),
    ('Apple NYC', 103, 544523,'2020-11-11'),
    ('Stack', 222, 511523,'2020-11-11'),
    ('Stack', 222, 144523,'2020-11-11')
;
</code>```

```
✓

✓
```

```<code>SELECT
 GROUP_CONCAT(n2.nextgenorder_ordernumber),
 #n2.nextgenorder_serial,
 MIN(n2.nextgenorder_company_entity),
 n2.nextgenorder_companyname,
 n2.nextgenorder_deliverydate
 FROM
    (SELECT REPLACE(`nextgenorder_companyname`,'Apple NYC','Apple') `nextgenorder_companyname`
    , `nextgenorder_company_entity`, `nextgenorder_ordernumber`,nextgenorder_deliverydate
    FROM nextgenorders2) n2
 WHERE n2.nextgenorder_deliverydate='2020-11-11'
 GROUP BY n2.nextgenorder_companyname
          ,n2.nextgenorder_deliverydate
          #,n2.nextgenorder_ordernumber
</code>```

```
GROUP_CONCAT(n2.nextgenorder_ordernumber) | MIN(n2.nextgenorder_company_entity) | nextgenorder_companyname | nextgenorder_deliverydate
:---------------------------------------- | ----------------------------------: | :----------------------- | :------------------------
555123,555123,544523                      |                                 103 | Apple                    | 2020-11-11
511523,144523                             |                                 222 | Stack                    | 2020-11-11
444444,222222                             |                                 777 | Telsa                    | 2020-11-11
```

db<>fiddle here

Some more explanation

The heart of the query is

```<code>(SELECT REPLACE(`nextgenorder_companyname`,'Apple NYC','Apple') `nextgenorder_companyname`
, `nextgenorder_company_entity`, `nextgenorder_ordernumber`,nextgenorder_deliverydate
FROM nextgenorders2) n2
</code>```

This Replaces the company names so that in this Case Apple NYC becomes Apple, this is somewhat time consuming so you should think about creating a column Mother company, but if there are only a few you can make this manually like i did.

The Group By is reduced to only company name , because that is our main target, to get all Information on that, delivery date is there , because usually you look for the whole week, so it is already group by if you decide to look at two or more dates.

The select is only an example, because is don't know, what you are searching for  an your query didn't give me any clue.

But the base is for every Column, that is not in the Group By clause , you need a Aggregation Function , so that the developer has to decide for every column what data he wants to see.

In my case i decided to see all order numbers if you need only the number of orders you take COUNT.

The entity isn't in the Group by, because i don't see why you need any entity at all if you only want to look at company's as a whole, the min was only because you took for Tesla 777 and not 888, but i don't know what you need it for

ContentLicense: CC BY-SA 4.0

Body:
I'm working with data managed by another department and I'm getting duplicates.

There are 3 different unique identifies:

Order Number
Company Name
Company Entity

Sometimes its the same company name but a different order number.

Sometimes its the same company name but a different company entity.

Sometimes its the same order number but different company name.

Sometimes its the same order number but different company entity.

Sometimes its the same company entity but different order number.

Sometimes its the same company entity but different company name.

Sometimes the company names are abbreviated like Apple, Apple Inc, Apple NYC, Etc.

Below I have a table with example data:

CompanyName      CompanyEntity   OrderNumber
Apple            123             555123
Apple            123             555123
Telsa            888             444444
Telsa            777             222222
Apple NYC        103             544523
Stack            222             511523
Stack            222             144523

I need to group by the company name or company entity or order number.

I tried:

 $query = "SELECT
 nextgenorders2.nextgenorder_ordernumber,
 nextgenorders2.nextgenorder_serial,
 nextgenorders2.nextgenorder_company_entity,
 nextgenorders2.nextgenorder_companyname,
 nextgenorders2.nextgenorder_deliverydate,
 FROM nextgenorders2
 WHERE nextgenorders2.nextgenorder_deliverydate='2020-11-11'
 GROUP BY nextgenorders2.nextgenorder_companyname,
          nextgenorders2.nextgenorder_company_entity,
          nextgenorders2.nextgenorder_ordernumber
 ";

That query produces:

CompanyName      CompanyEntity   OrderNumber
Apple            123             555123
Telsa            888             444444
Telsa            777             222222
Apple NYC        103             544523
Stack            222             511523

If the row has the same company name, company entity and order number it's put into a group.

If the row doesn't have the same company entity, company name and order number it's not put into a group.

I want the query to produce this:

CompanyName      CompanyEntity   OrderNumber
Apple            123             555123
Telsa            888             444444
Stack            222             144523

but I'll take this because of the multiple company name abbrievations:

CompanyName      CompanyEntity   OrderNumber
Apple            123             555123
Telsa            777             222222
Apple NYC        103             544523
Stack            222             511523

Thank you for your help.

Body:
You can do something like this

But for every column you have do decide what to do with it.
Like MIN(n2.nextgenorder_company_entity), but if you want to keep all you can use GROUP_CONCAT for example

CREATE TABLE nextgenorders2
    (`nextgenorder_companyname` varchar(9), `nextgenorder_company_entity` int, `nextgenorder_ordernumber` int, nextgenorder_deliverydate date)
;

INSERT INTO nextgenorders2
    (`nextgenorder_companyname`, `nextgenorder_company_entity`, `nextgenorder_ordernumber`,nextgenorder_deliverydate)
VALUES
    ('Apple', 123, 555123,'2020-11-11'),
    ('Apple', 123, 555123,'2020-11-11'),
    ('Telsa', 888, 444444,'2020-11-11'),
    ('Telsa', 777, 222222,'2020-11-11'),
    ('Apple NYC', 103, 544523,'2020-11-11'),
    ('Stack', 222, 511523,'2020-11-11'),
    ('Stack', 222, 144523,'2020-11-11')
;

✓

✓

SELECT
 GROUP_CONCAT(n2.nextgenorder_ordernumber),
 #n2.nextgenorder_serial,
 MIN(n2.nextgenorder_company_entity),
 n2.nextgenorder_companyname,
 n2.nextgenorder_deliverydate
 FROM
    (SELECT REPLACE(`nextgenorder_companyname`,'Apple NYC','Apple') `nextgenorder_companyname`
    , `nextgenorder_company_entity`, `nextgenorder_ordernumber`,nextgenorder_deliverydate
    FROM nextgenorders2) n2
 WHERE n2.nextgenorder_deliverydate='2020-11-11'
 GROUP BY n2.nextgenorder_companyname
          ,n2.nextgenorder_deliverydate
          #,n2.nextgenorder_ordernumber

GROUP_CONCAT(n2.nextgenorder_ordernumber) | MIN(n2.nextgenorder_company_entity) | nextgenorder_companyname | nextgenorder_deliverydate
:---------------------------------------- | ----------------------------------: | :----------------------- | :------------------------
555123,555123,544523                      |                                 103 | Apple                    | 2020-11-11
511523,144523                             |                                 222 | Stack                    | 2020-11-11
444444,222222                             |                                 777 | Telsa                    | 2020-11-11

db<>fiddle here

Some more explanation

The heart of the query is

(SELECT REPLACE(`nextgenorder_companyname`,'Apple NYC','Apple') `nextgenorder_companyname`
, `nextgenorder_company_entity`, `nextgenorder_ordernumber`,nextgenorder_deliverydate
FROM nextgenorders2) n2

This Replaces the company names so that in this Case Apple NYC becomes Apple, this is somewhat time consuming so you should think about creating a column Mother company, but if there are only a few you can make this manually like i did.

The Group By is reduced to only company name , because that is our main target, to get all Information on that, delivery date is there , because usually you look for the whole week, so it is already group by if you decide to look at two or more dates.

The select is only an example, because is don't know, what you are searching for  an your query didn't give me any clue.

But the base is for every Column, that is not in the Group By clause , you need a Aggregation Function , so that the developer has to decide for every column what data he wants to see.

In my case i decided to see all order numbers if you need only the number of orders you take COUNT.

The entity isn't in the Group by, because i don't see why you need any entity at all if you only want to look at company's as a whole, the min was only because you took for Tesla 777 and not 888, but i don't know what you need it for


问:
Cannot record video+audio on iPhone Safari
I have used RecordRTC for capturing the video+audio from the browser.
For Android devices, it's working perfectly as expected. But in iPhone devices especially on the safari browser, it's not recording as expected.

Browser console produces the following error.

Your browser does not support Media Recorder API. Please try other modules e.g. WhammyRecorder or StereoAudioRecorder.

Could someone please help me out like:
Does Safari support basic video capturing?

答:
It is better to use StereoAudioRecorder which is made in RecordRTC.js as Recorder for Safari.

This is the document of StereoAudioRecorder.
You're going to have to read this first :)

https://recordrtc.org/StereoAudioRecorder.html

```<code>const option = {
  type: 'video',
  recorderType: StereoAudioRecorder
};
const recorder = new RecordRTC(mic, options);

recorder.startRecording();
</code>```

I hope this will help you.

Body:
It is better to use StereoAudioRecorder which is made in RecordRTC.js as Recorder for Safari.

This is the document of StereoAudioRecorder.
You're going to have to read this first :)

https://recordrtc.org/StereoAudioRecorder.html

const option = {
  type: 'video',
  recorderType: StereoAudioRecorder
};
const recorder = new RecordRTC(mic, options);

recorder.startRecording();

I hope this will help you.


问:
React card icon display
a bit of help here if possible. I am creating a team card let's call it. I have a .jsonfile with data. Problem is, what shall I do if one of the team members doesn't have a facebook account let's say...then I don't want the font awesome to be shown. Thoughts?
Thanks in advance!

import React, { Component } from 'react';
import teamData from '../components/data/teamInfo.json';

const TeamCard =({data})=>{
  const imgStyles = {
    width: "200px",
    height: "250px",
    borderRadius: "20px"
  }

  return (

{data.name}
{data.title}

{data.hobbies}

  )
};

const TeamCards =()=>{

  return (

Meet the team

        {teamData && teamData.map((e, key) => {
          return (
            <TeamCard
              data={e}
              key={key}
            />
          );
        })}

  )
}

export default TeamCards;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

答:
You will need to add condition to check if person has facebokId.</p>

```<code><div className="social-icons">
  data.linkedIn && (<a href={data.linkedIn}><i className="fab fa-linkedin"></i></a>)
  data.facebookId && (<a href={data.facebookId}><i className="fab fa-github-square"></i></a>)
</div>
</code>```

Title: React card icon display

Body:
You will need to add condition to check if person has facebokId.

<div className="social-icons">
  data.linkedIn && (<a href={data.linkedIn}><i className="fab fa-linkedin"></i></a>)
  data.facebookId && (<a href={data.facebookId}><i className="fab fa-github-square"></i></a>)
</div>


问:
Is it possible to sending same message multiple times to the same node?
I want to simulate DOS attack. So, I want to send same message multiple times to a specific node.

For example, when I try to do it in a loop like this:

```<code>cMessage *msg = new cMessage("data");
cModule *targetNode = getParentModule()->getSubmodule(node[0]);
for(int i=0; i<5; i++){
    sendDirect(msg, targetNode, "io");
}
</code>```

I am getting this error:

Is there any way to do that in Omnet?

答:
Yes, but every time you have to create a duplicate of the message using dup().

So your code may looks like:

```<code>cMessage *msg = new cMessage("data");
cModule *targetNode = getParentModule()->getSubmodule(node[0]);
for(int i=0; i<5; i++){
    cMessage * copyMsg = msg->dup();
    sendDirect(copyMsg, targetNode, "io");
}
delete msg; // remove original message (no longer needed)
</code>```

Body:
I want to simulate DOS attack. So, I want to send same message multiple times to a specific node.

For example, when I try to do it in a loop like this:

cMessage *msg = new cMessage("data");
cModule *targetNode = getParentModule()->getSubmodule(node[0]);
for(int i=0; i<5; i++){
    sendDirect(msg, targetNode, "io");
}

I am getting this error:

Is there any way to do that in Omnet?

Body:
Yes, but every time you have to create a duplicate of the message using dup().

So your code may looks like:

cMessage *msg = new cMessage("data");
cModule *targetNode = getParentModule()->getSubmodule(node[0]);
for(int i=0; i<5; i++){
    cMessage * copyMsg = msg->dup();
    sendDirect(copyMsg, targetNode, "io");
}
delete msg; // remove original message (no longer needed)


问:
Randomly spawning an enemy
I am in the progress of making a small 2d game where the objective is to eat as much poop as possible, but I'm having trouble spawning the poop at random times. I want the poop to spawn at the enemy's y location but then shoot forwards like an rpg.

import pygame
from pygame.locals import *
from numpy.random import rand

pygame.init()
pygame.display.set_caption('STINKY BEETLE')

screen_width = 800
screen_height = 600
game_running = True
pl_x = int(screen_width/10)
pl_y = int(screen_height/2)
pl_width = 80
pl_height = 40
pl_vel = 30
en_width = 80
en_height = 40
en_x = screen_width - screen_width/10 - en_width
en_y = int(screen_height/2)
en_yvel = -10
po_width = 50
po_height = 30
po_x = 720
po_y = en_y
po_xvel = 15

screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()

while game_running:
    clock.tick(10)

    po_delay = rand(1)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_running = False

        if event.type == MOUSEBUTTONDOWN:
            if event.button == 4 and pl_y > pl_vel:
                pl_y -= pl_vel

            elif event.button == 5 and pl_y < screen_height - pl_width:
                pl_y += pl_vel

    if po_delay < 0.01:
        poop(po_x, po_y)

    en_y += en_yvel
    if en_y <= 0 or en_y >= screen_height - en_height:
        en_yvel =- en_yvel

    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, (105, 255, 125), (pl_x, pl_y, pl_width, pl_height))
    pygame.display.update()

    pygame.draw.rect(screen, (255, 125, 115), (en_x, en_y, en_width, en_height))
    pygame.display.update()

pygame.quit()
```

答:
You can use pygame's time module to randomly spawn enemies. I am assuming you are using OOP for this. Firstly, when initializing your enemy class record the time when it first spawns.

```<code>class Enemy:
    def __init__(self):
        self.start = time.time()
        # other code
</code>```

Then you can calculate the amount of time that has passed since your enemy last spawened. You can do something like now =  time.time() in your main game loop and get the difference.

```<code>enemy = Enemy()
while True:
    now = time.time()
    time_passed = now - enemy.start()
</code>```

Now you can use this time_passed as an argument to your spawn_enemy() function that you might create which might look something like this:

```<code>def spawn(self, t):
   counter = t % random.randint(1, 10)
   if counter >= 0 and counter <=  0.2:
       #spawn enemy
</code>```

Call this function as spawn(time_passed)

Title: Randomly spawning an enemy

Body:
You can use pygame's time module to randomly spawn enemies. I am assuming you are using OOP for this. Firstly, when initializing your enemy class record the time when it first spawns.

class Enemy:
    def __init__(self):
        self.start = time.time()
        # other code

Then you can calculate the amount of time that has passed since your enemy last spawened. You can do something like now =  time.time() in your main game loop and get the difference.

enemy = Enemy()
while True:
    now = time.time()
    time_passed = now - enemy.start()

Now you can use this time_passed as an argument to your spawn_enemy() function that you might create which might look something like this:

def spawn(self, t):
   counter = t % random.randint(1, 10)
   if counter >= 0 and counter <=  0.2:
       #spawn enemy

Call this function as spawn(time_passed)


问:
Admob IOS swift GDPR consent
I'm new to swift and iOS programming. I want to add Admob consent/GDPR option to my app,
So I've setup an ad box and can display a test add, but need to add consent option next.

I've read
https://developers.google.com/admob/ios/eu-consent

but it's not clear to me, can anyone show me an example of code to do this step by step, or point me to GitHub source where it has been done.

Thanks

答:
Can you please show an example of what you have tried that isn't working for you?

As I am unable to see your code example to see what you're doing or not doing, I'll give an example based on the docs.

```<code>import PersonalizedAdConsent
</code>```

...

```<code>class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    PACConsentInformation.sharedInstance.
    requestConsentInfoUpdate(
    forPublisherIdentifiers: ["pub-0123456789012345"])
    {(_ error: Error?) -> Void in
      if let error = error {
        // Consent info update failed.
      } else {
        // Consent info update succeeded. The shared PACConsentInformation
        // instance has been updated.
      }
    }

guard let privacyUrl = URL(string: "https://www.your.com/privacyurl"),
  let form = PACConsentForm(applicationPrivacyPolicyURL: privacyUrl) else {
    print("incorrect privacy URL.")
    return
}
form.shouldOfferPersonalizedAds = true
form.shouldOfferNonPersonalizedAds = true
form.shouldOfferAdFree = true

form.load {(_ error: Error?) -> Void in
  print("Load complete.")
  if let error = error {
    // Handle error.
    print("Error loading form: \(error.localizedDescription)")
  } else {
    // Load successful.
  }
}

//Finally present the consent form
form.present(from: self) { (error, userPrefersAdFree) in
      if let error = error {
        // Handle error.
      } else if userPrefersAdFree {
        // User prefers to use a paid version of the app.
      } else {
        // Check the user's consent choice.
        let status =
             PACConsentInformation.sharedInstance.consentStatus
      }
    }

      }
</code>```

Title: Admob IOS swift GDPR consent

Body:
Can you please show an example of what you have tried that isn't working for you?

As I am unable to see your code example to see what you're doing or not doing, I'll give an example based on the docs.

import PersonalizedAdConsent

...

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    PACConsentInformation.sharedInstance.
    requestConsentInfoUpdate(
    forPublisherIdentifiers: ["pub-0123456789012345"])
    {(_ error: Error?) -> Void in
      if let error = error {
        // Consent info update failed.
      } else {
        // Consent info update succeeded. The shared PACConsentInformation
        // instance has been updated.
      }
    }

guard let privacyUrl = URL(string: "https://www.your.com/privacyurl"),
  let form = PACConsentForm(applicationPrivacyPolicyURL: privacyUrl) else {
    print("incorrect privacy URL.")
    return
}
form.shouldOfferPersonalizedAds = true
form.shouldOfferNonPersonalizedAds = true
form.shouldOfferAdFree = true

form.load {(_ error: Error?) -> Void in
  print("Load complete.")
  if let error = error {
    // Handle error.
    print("Error loading form: \(error.localizedDescription)")
  } else {
    // Load successful.
  }
}

//Finally present the consent form
form.present(from: self) { (error, userPrefersAdFree) in
      if let error = error {
        // Handle error.
      } else if userPrefersAdFree {
        // User prefers to use a paid version of the app.
      } else {
        // Check the user's consent choice.
        let status =
             PACConsentInformation.sharedInstance.consentStatus
      }
    }

      }


问:
nginx conf express and assets returning 404
Have been at this all day and so far not getting to where I'd a liked to have been.

Running pretty much the latest version of everything as just building a new server to move off IIS/IISNode.

I have nginx installed and some conf going that serves only my main index file from a sub dir of /vra/www/. However it does not load any assets or sub-dir pages.

If I call the assets directly, using lowercase URL it returns 404 but uppercase URLs where needed work fine.

My conf example can be seen here: pastebin.com/a12TqP6w

答:
What all think in the webroot folder. I think it has only one directory html  your codes are put in the html directory there is no stuff in the mentioned directory     /var/www/dev.fishpal.com. change your configuration accordingly where is web content is placed.

Replace with this one.

```<code>root /var/www/dev.fishpal.com/html;
</code>```

or put your codes and stuff in the following directory.

```<code>root /var/www/dev.fishpal.com;
</code>```

Body:
What all think in the webroot folder. I think it has only one directory html  your codes are put in the html directory there is no stuff in the mentioned directory     /var/www/dev.fishpal.com. change your configuration accordingly where is web content is placed.

Replace with this one.

root /var/www/dev.fishpal.com/html;

or put your codes and stuff in the following directory.

root /var/www/dev.fishpal.com;


问:
Scroll to bottom of div?
I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.

I am wrapping everything in this div:

```<code>#scroll {
    height:400px;
    overflow:scroll;
}
</code>```

Is there a way to keep it scrolled to the bottom by default using JS?

Is there a way to keep it scrolled to the bottom after an ajax request?

答:
On my Angular 6 application I just did this:

```<code>postMessage() {
  // post functions here
  let history = document.getElementById('history')
  let interval
  interval = setInterval(function() {
    history.scrollTop = history.scrollHeight
    clearInterval(interval)
  }, 1)
}
</code>```

The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.

OwnerDisplayName: dMix

Title: Scroll to bottom of div?

Body:
I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.

I am wrapping everything in this div:

#scroll {
    height:400px;
    overflow:scroll;
}

Is there a way to keep it scrolled to the bottom by default using JS?

Is there a way to keep it scrolled to the bottom after an ajax request?

LastEditorDisplayName: dMix

Body:
On my Angular 6 application I just did this:

postMessage() {
  // post functions here
  let history = document.getElementById('history')
  let interval
  interval = setInterval(function() {
    history.scrollTop = history.scrollHeight
    clearInterval(interval)
  }, 1)
}

The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.


问:
Mimic Windows Task Scheduler with code
I'm looking for a way to make a program that runs itself (or a method) every X time (days, weeks, whatever). Basically, I want my program to do what the Windows Task Scheduler could do. The reason I don't use the Task Scheduler is because I plan to deploy this application on a server which I have no remote access to, but need to re-generate some files every given time.

Suggestions?

答:
Create a Windows Service and use a timer.  You can pick between System.Timers.Timer and System.Threading.Timer based on the differences you can find here:

http://www.intellitechture.com/System-Windows-Forms-Timer-vs-System-Threading-Timer-vs-System-Timers-Timer/

ContentLicense: CC BY-SA 3.0

Title: Mimic Windows Task Scheduler with code


问:
Speech to Text recognition : Text Correction and Result Improvisation in Python
How can I achieve below result in Python

reference text is : " We wanted people to know that we've got something brand new and essentially this product is uh what we call disruptive changes the way that people interact with technology. "

Hypothesis text : " We wanted people to know that how to me where I know and essentially this product is what we call scripted changes the way people are rapid technology. "

I have to consider this both text where reference text will act as ground truth and the hypothesis text is subjected to be modified based on the reference text.

My final text should look like,

" We wanted people to know that how to me where I know we've got something brand new and essentially this product is uh what we call scripted disruptive changes the way that people are rapid interact technology."

I have used code sample box here to show that these texts are wrongly inserted and the Bold for the text to be inserted based on ground truth. But in a real scenario, I will use red color for the words which are wrongly inserted and green color for the words to be inserted based on ground truth reference.

I tried to write logic by splitting the text into a list of elements and compare each element. but my logic seems not to work for all the sentences as there can be many possible combinations.

Kindly suggest me if there are any libraries I can use to do this task.

Thanks :)

答:
You need to use Levenshtein distance to compare, see something like:

Levenshtein similarity in Python

```<code>import numpy as np

def levenshtein(seq1, seq2):
    size_x = len(seq1) + 1
    size_y = len(seq2) + 1
    matrix = np.zeros ((size_x, size_y))
    for x in xrange(size_x):
        matrix [x, 0] = x
    for y in xrange(size_y):
        matrix [0, y] = y

    for x in xrange(1, size_x):
        for y in xrange(1, size_y):
            if seq1[x-1] == seq2[y-1]:
                matrix [x,y] = min(
                    matrix[x-1, y] + 1,
                    matrix[x-1, y-1],
                    matrix[x, y-1] + 1
                )
            else:
                matrix [x,y] = min(
                    matrix[x-1,y] + 1,
                    matrix[x-1,y-1] + 1,
                    matrix[x,y-1] + 1
                )
    print (matrix)
    return (matrix[size_x - 1, size_y - 1])
</code>```

Body:
You need to use Levenshtein distance to compare, see something like:

Levenshtein similarity in Python

import numpy as np

def levenshtein(seq1, seq2):
    size_x = len(seq1) + 1
    size_y = len(seq2) + 1
    matrix = np.zeros ((size_x, size_y))
    for x in xrange(size_x):
        matrix [x, 0] = x
    for y in xrange(size_y):
        matrix [0, y] = y

    for x in xrange(1, size_x):
        for y in xrange(1, size_y):
            if seq1[x-1] == seq2[y-1]:
                matrix [x,y] = min(
                    matrix[x-1, y] + 1,
                    matrix[x-1, y-1],
                    matrix[x, y-1] + 1
                )
            else:
                matrix [x,y] = min(
                    matrix[x-1,y] + 1,
                    matrix[x-1,y-1] + 1,
                    matrix[x,y-1] + 1
                )
    print (matrix)
    return (matrix[size_x - 1, size_y - 1])


问:
Racket hangs on Google Colab
Google Colab is good, runs not just Python, C++, and other langs too thru' the %%script blockmagic.

I'm trying to run Racket but it doesn't work, it hangs. Here's the content to run in Colab:

```<code>!sudo apt update -y
!sudo apt upgrade -y
!sudo apt install racket -y
#OK until here.

#Racket supposed to print out version,
#but it hangs here:
!racket -v
</code>```

Anyone with a solution? any work-arounds?

答:
Google Colab is supposed for working with IPython Notebooks only, there's no guarantees that Colab should work with other languages by writing to files and interpret or compile them.

C/C++ works with %%writefile ... and %%script bash to compile and run, but the machine instance in Colab somehow doesn't work with Racket: Racket hangs even before printing out anything, event the first character to stdout. Possibly Racket is missing some required stuff.

There's 1 suggestion is to use Paperspace.com, Racket works well there, but notice that Paperspace notebooks are all public. And from my experience, a Paperspace workspace is shared, not private, so files may be changed by others.

Title: Racket hangs on Google Colab

Body:
Google Colab is good, runs not just Python, C++, and other langs too thru' the %%script blockmagic.

I'm trying to run Racket but it doesn't work, it hangs. Here's the content to run in Colab:

!sudo apt update -y
!sudo apt upgrade -y
!sudo apt install racket -y
#OK until here.

#Racket supposed to print out version,
#but it hangs here:
!racket -v

Anyone with a solution? any work-arounds?


问:
A fatal error has been detected by the Java Runtime Environment: Internal Error ; Error: ShouldNotReachHere()
I have no idea what went wrong as I've programmed in Java for about a year and never got this error. Compiling and running in Eclipse worked just a minute ago and now I get this error:

```<code>#A fatal error has been detected by the Java Runtime Environment:

#Internal Error (classFileParser.cpp:3494), pid=4636, tid=2380

#Error: ShouldNotReachHere()

#JRE version: 6.0_25-b06

#Java VM: Java HotSpot(TM) Client VM (20.0-b11 mixed mode windows-x86 )

#If you would like to submit a bug report, please visit:

#http://java.sun.com/webapps/bugreport/crash.jsp

---------------  T H R E A D  ---------------

Current thread (0x02339800):  JavaThread "Unknown thread" [_thread_in_vm, id=2380, stack(0x00240000,0x00290000)]

Stack: [0x00240000,0x00290000],  sp=0x0028f86c,  free space=318k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [jvm.dll+0x13363a]
V  [jvm.dll+0x12e59b]
V  [jvm.dll+0x164ce]
V  [jvm.dll+0x17cff]
V  [jvm.dll+0x26de5]
V  [jvm.dll+0x27626]
V  [jvm.dll+0x279d5]
V  [jvm.dll+0x27a69]
V  [jvm.dll+0x27b2c]
V  [jvm.dll+0x27baa]
V  [jvm.dll+0x27c8d]
V  [jvm.dll+0x27f59]
V  [jvm.dll+0x6c593]
V  [jvm.dll+0x6c96c]
V  [jvm.dll+0xf9c1c]
V  [jvm.dll+0x1184bb]
V  [jvm.dll+0x9eba0]
C  [javaw.exe+0x1657]
C  [javaw.exe+0x1e2c]
C  [javaw.exe+0x8614]
C  [kernel32.dll+0x13677]  BaseThreadInitThunk+0x12
C  [ntdll.dll+0x39f02]  RtlInitializeExceptionChain+0x63
C  [ntdll.dll+0x39ed5]  RtlInitializeExceptionChain+0x36

---------------  P R O C E S S  ---------------

Java Threads: ( => current thread )

Other Threads:

=>0x02339800 (exited) JavaThread "Unknown thread" [_thread_in_vm, id=2380, stack(0x00240000,0x00290000)]

VM state:not at safepoint (not fully initialized)

VM Mutex/Monitor currently owned by a thread: None

Dynamic libraries:
0x00400000 - 0x00424000     C:\Program Files (x86)\Java\jre6\bin\javaw.exe
0x77370000 - 0x774f0000     C:\Windows\SysWOW64\ntdll.dll
0x752e0000 - 0x753e0000     C:\Windows\syswow64\kernel32.dll
0x75200000 - 0x75246000     C:\Windows\syswow64\KERNELBASE.dll
0x76a30000 - 0x76ad0000     C:\Windows\syswow64\ADVAPI32.dll
0x76b90000 - 0x76c3c000     C:\Windows\syswow64\msvcrt.dll
0x76c40000 - 0x76c59000     C:\Windows\SysWOW64\sechost.dll
0x75940000 - 0x75a30000     C:\Windows\syswow64\RPCRT4.dll
0x74ee0000 - 0x74f40000     C:\Windows\syswow64\SspiCli.dll
0x74ed0000 - 0x74edc000     C:\Windows\syswow64\CRYPTBASE.dll
0x75a40000 - 0x75b40000     C:\Windows\syswow64\USER32.dll
0x75250000 - 0x752e0000     C:\Windows\syswow64\GDI32.dll
0x75790000 - 0x7579a000     C:\Windows\syswow64\LPK.dll
0x76790000 - 0x7682d000     C:\Windows\syswow64\USP10.dll
0x756d0000 - 0x75730000     C:\Windows\system32\IMM32.DLL
0x75600000 - 0x756cc000     C:\Windows\syswow64\MSCTF.dll
0x7c340000 - 0x7c396000     C:\Program Files (x86)\Java\jre6\bin\msvcr71.dll
0x6d7f0000 - 0x6da9f000     C:\Program Files (x86)\Java\jre6\bin\client\jvm.dll
0x74770000 - 0x747a2000     C:\Windows\system32\WINMM.dll
0x70c70000 - 0x70cbb000     C:\Windows\system32\apphelp.dll
0x6d7a0000 - 0x6d7ac000     C:\Program Files (x86)\Java\jre6\bin\verify.dll
0x6d320000 - 0x6d33f000     C:\Program Files (x86)\Java\jre6\bin\java.dll
0x77340000 - 0x77345000     C:\Windows\syswow64\PSAPI.DLL
0x6d7e0000 - 0x6d7ef000     C:\Program Files (x86)\Java\jre6\bin\zip.dll

VM Arguments:
jvm_args: -Dfile.encoding=Cp1252 -Xbootclasspath:C:\Program Files (x86)\Android\android-sdk\platforms\android-7\android.jar
java_command: elf.app.RoomInfoActivity
Launcher Type: SUN_STANDARD

Environment Variables:
CLASSPATH=.;C:\Program Files (x86)\Java\jre6\lib\ext\QTJava.zip
PATH=C:/Program Files (x86)/Java/jre6/bin/client;C:/Program Files (x86)/Java/jre6/bin;C:/Program Files (x86)/Java/jre6/lib/i386;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Windows Live\Shared;C:\cygwin\bin;C:\"Program Files (x86)"\Java\jdk1.6.0_24\bin;C:\Program Files (x86)\Common Files\Acronis\SnapAPI\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files (x86)\Android\android-sdk\platform-tools;C:\Program Files (x86)\Android\android-sdk\tools;C:\Program Files (x86)\Eclipse;
USERNAME=ryu_eMach_E732Z
OS=Windows_NT
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 37 Stepping 5, GenuineIntel

---------------  S Y S T E M  ---------------

OS: Windows 7 Build 7600

CPU:total 2 (2 cores per cpu, 1 threads per core) family 6 model 37 stepping 5, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, popcnt

Memory: 4k page, physical 2874176k(1587204k free), swap 5746452k(3983880k free)

vm_info: Java HotSpot(TM) Client VM (20.0-b11) for windows-x86 JRE (1.6.0_25-b06), built on Apr 14 2011 01:04:32 by "java_re" with MS VC++ 7.1 (VS2003)

time: Mon May 16 14:17:52 2011
elapsed time: 0 seconds
</code>```

答: Looks like a corrupt class file. Rebuild.</p>

Body:
I have no idea what went wrong as I've programmed in Java for about a year and never got this error. Compiling and running in Eclipse worked just a minute ago and now I get this error:

#A fatal error has been detected by the Java Runtime Environment:

#Internal Error (classFileParser.cpp:3494), pid=4636, tid=2380

#Error: ShouldNotReachHere()

#JRE version: 6.0_25-b06

#Java VM: Java HotSpot(TM) Client VM (20.0-b11 mixed mode windows-x86 )

#If you would like to submit a bug report, please visit:

#http://java.sun.com/webapps/bugreport/crash.jsp

---------------  T H R E A D  ---------------

Current thread (0x02339800):  JavaThread "Unknown thread" [_thread_in_vm, id=2380, stack(0x00240000,0x00290000)]

Stack: [0x00240000,0x00290000],  sp=0x0028f86c,  free space=318k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [jvm.dll+0x13363a]
V  [jvm.dll+0x12e59b]
V  [jvm.dll+0x164ce]
V  [jvm.dll+0x17cff]
V  [jvm.dll+0x26de5]
V  [jvm.dll+0x27626]
V  [jvm.dll+0x279d5]
V  [jvm.dll+0x27a69]
V  [jvm.dll+0x27b2c]
V  [jvm.dll+0x27baa]
V  [jvm.dll+0x27c8d]
V  [jvm.dll+0x27f59]
V  [jvm.dll+0x6c593]
V  [jvm.dll+0x6c96c]
V  [jvm.dll+0xf9c1c]
V  [jvm.dll+0x1184bb]
V  [jvm.dll+0x9eba0]
C  [javaw.exe+0x1657]
C  [javaw.exe+0x1e2c]
C  [javaw.exe+0x8614]
C  [kernel32.dll+0x13677]  BaseThreadInitThunk+0x12
C  [ntdll.dll+0x39f02]  RtlInitializeExceptionChain+0x63
C  [ntdll.dll+0x39ed5]  RtlInitializeExceptionChain+0x36

---------------  P R O C E S S  ---------------

Java Threads: ( => current thread )

Other Threads:

=>0x02339800 (exited) JavaThread "Unknown thread" [_thread_in_vm, id=2380, stack(0x00240000,0x00290000)]

VM state:not at safepoint (not fully initialized)

VM Mutex/Monitor currently owned by a thread: None

Dynamic libraries:
0x00400000 - 0x00424000     C:\Program Files (x86)\Java\jre6\bin\javaw.exe
0x77370000 - 0x774f0000     C:\Windows\SysWOW64\ntdll.dll
0x752e0000 - 0x753e0000     C:\Windows\syswow64\kernel32.dll
0x75200000 - 0x75246000     C:\Windows\syswow64\KERNELBASE.dll
0x76a30000 - 0x76ad0000     C:\Windows\syswow64\ADVAPI32.dll
0x76b90000 - 0x76c3c000     C:\Windows\syswow64\msvcrt.dll
0x76c40000 - 0x76c59000     C:\Windows\SysWOW64\sechost.dll
0x75940000 - 0x75a30000     C:\Windows\syswow64\RPCRT4.dll
0x74ee0000 - 0x74f40000     C:\Windows\syswow64\SspiCli.dll
0x74ed0000 - 0x74edc000     C:\Windows\syswow64\CRYPTBASE.dll
0x75a40000 - 0x75b40000     C:\Windows\syswow64\USER32.dll
0x75250000 - 0x752e0000     C:\Windows\syswow64\GDI32.dll
0x75790000 - 0x7579a000     C:\Windows\syswow64\LPK.dll
0x76790000 - 0x7682d000     C:\Windows\syswow64\USP10.dll
0x756d0000 - 0x75730000     C:\Windows\system32\IMM32.DLL
0x75600000 - 0x756cc000     C:\Windows\syswow64\MSCTF.dll
0x7c340000 - 0x7c396000     C:\Program Files (x86)\Java\jre6\bin\msvcr71.dll
0x6d7f0000 - 0x6da9f000     C:\Program Files (x86)\Java\jre6\bin\client\jvm.dll
0x74770000 - 0x747a2000     C:\Windows\system32\WINMM.dll
0x70c70000 - 0x70cbb000     C:\Windows\system32\apphelp.dll
0x6d7a0000 - 0x6d7ac000     C:\Program Files (x86)\Java\jre6\bin\verify.dll
0x6d320000 - 0x6d33f000     C:\Program Files (x86)\Java\jre6\bin\java.dll
0x77340000 - 0x77345000     C:\Windows\syswow64\PSAPI.DLL
0x6d7e0000 - 0x6d7ef000     C:\Program Files (x86)\Java\jre6\bin\zip.dll

VM Arguments:
jvm_args: -Dfile.encoding=Cp1252 -Xbootclasspath:C:\Program Files (x86)\Android\android-sdk\platforms\android-7\android.jar
java_command: elf.app.RoomInfoActivity
Launcher Type: SUN_STANDARD

Environment Variables:
CLASSPATH=.;C:\Program Files (x86)\Java\jre6\lib\ext\QTJava.zip
PATH=C:/Program Files (x86)/Java/jre6/bin/client;C:/Program Files (x86)/Java/jre6/bin;C:/Program Files (x86)/Java/jre6/lib/i386;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Windows Live\Shared;C:\cygwin\bin;C:\"Program Files (x86)"\Java\jdk1.6.0_24\bin;C:\Program Files (x86)\Common Files\Acronis\SnapAPI\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files (x86)\Android\android-sdk\platform-tools;C:\Program Files (x86)\Android\android-sdk\tools;C:\Program Files (x86)\Eclipse;
USERNAME=ryu_eMach_E732Z
OS=Windows_NT
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 37 Stepping 5, GenuineIntel

---------------  S Y S T E M  ---------------

OS: Windows 7 Build 7600

CPU:total 2 (2 cores per cpu, 1 threads per core) family 6 model 37 stepping 5, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, popcnt

Memory: 4k page, physical 2874176k(1587204k free), swap 5746452k(3983880k free)

vm_info: Java HotSpot(TM) Client VM (20.0-b11) for windows-x86 JRE (1.6.0_25-b06), built on Apr 14 2011 01:04:32 by "java_re" with MS VC++ 7.1 (VS2003)

time: Mon May 16 14:17:52 2011
elapsed time: 0 seconds


问:
Error: "invalid use of incomplete type ‘RSA {aka struct rsa_st}" in OpenSSL 1.1.0
I have old code that was written to link against an old version of openssl. Part of this code loads a key from a PEM file, and tries to understand whether this key is a private or public key, by using the following code:

```<code>if( (prv->p==0 || prv->q==0) ) {
    // This is not a private key!
    throw error("No private key for decryption");
}
</code>```

With the latest version of openssl, this (justifiably) doesn't compile:

```<code>crypto.cpp: In function ‘key* decrypt_header(file_t, RSA*)’:
crypto.cpp:158:13: error: invalid use of incomplete type ‘RSA {aka struct rsa_st}’
     if( (prv->p==0 || prv->q==0) ) {
             ^~
</code>```

I understand that direct access to the struct's private members was replaced with a function, but I am having a hard time figuring out which function that is.

答:
After 1.1.1 OpenSSL Supports getter what return each parameter like this.

```<code>const BIGNUM *RSA_get0_n(const RSA *d);
const BIGNUM *RSA_get0_e(const RSA *d);
const BIGNUM *RSA_get0_d(const RSA *d);
const BIGNUM *RSA_get0_p(const RSA *d);
const BIGNUM *RSA_get0_q(const RSA *d);
const BIGNUM *RSA_get0_dmp1(const RSA *r);
const BIGNUM *RSA_get0_dmq1(const RSA *r);
const BIGNUM *RSA_get0_iqmp(const RSA *r);
</code>```

So if you don't need to considerate below version of OpenSSL less than 1.1.1 these code will make simple code. AND other structures support kind of this getter too. You can find more information of functions this. https://www.openssl.org/docs/man1.1.1/man3/

Body:
I have old code that was written to link against an old version of openssl. Part of this code loads a key from a PEM file, and tries to understand whether this key is a private or public key, by using the following code:

if( (prv->p==0 || prv->q==0) ) {
    // This is not a private key!
    throw error("No private key for decryption");
}

With the latest version of openssl, this (justifiably) doesn't compile:

crypto.cpp: In function ‘key* decrypt_header(file_t, RSA*)’:
crypto.cpp:158:13: error: invalid use of incomplete type ‘RSA {aka struct rsa_st}’
     if( (prv->p==0 || prv->q==0) ) {
             ^~

I understand that direct access to the struct's private members was replaced with a function, but I am having a hard time figuring out which function that is.

Body:
After 1.1.1 OpenSSL Supports getter what return each parameter like this.

const BIGNUM *RSA_get0_n(const RSA *d);
const BIGNUM *RSA_get0_e(const RSA *d);
const BIGNUM *RSA_get0_d(const RSA *d);
const BIGNUM *RSA_get0_p(const RSA *d);
const BIGNUM *RSA_get0_q(const RSA *d);
const BIGNUM *RSA_get0_dmp1(const RSA *r);
const BIGNUM *RSA_get0_dmq1(const RSA *r);
const BIGNUM *RSA_get0_iqmp(const RSA *r);

So if you don't need to considerate below version of OpenSSL less than 1.1.1 these code will make simple code. AND other structures support kind of this getter too. You can find more information of functions this. https://www.openssl.org/docs/man1.1.1/man3/


问:
product import via csv to woocommerce with sql
importing products by the plugin wp all import takes too much time when sql table post_meta is growing. At the moment there are 200.000 products imported.

Is there a way to import products via csv directly in sql without wordpress.
(I do not need to import any images only titles and descriptions).

Thanks for any help in advance.

Kind regards
Oliver

答:
You can do it in a 2 steps SQL.

```<code>INSERT INTO `wp_posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_status`, `comment_status`, `ping_status`, `post_name`, `post_modified`, `post_modified_gmt`, `guid`, `post_type`, `comment_count`)
VALUES ([ID], [AUTHOR], '[DATE1]', '[DATE2]', '[CONTENT]', '[TITLE]', 'publish', 'open', 'open', '[POSTNAME]', '[DATE3]', '[DATE4]', '[GUID]', 'product', 0);
</code>```

I would recommend to update those records afterward using WP ALL IMPORT

Body:
You can do it in a 2 steps SQL.

INSERT INTO `wp_posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_status`, `comment_status`, `ping_status`, `post_name`, `post_modified`, `post_modified_gmt`, `guid`, `post_type`, `comment_count`)
VALUES ([ID], [AUTHOR], '[DATE1]', '[DATE2]', '[CONTENT]', '[TITLE]', 'publish', 'open', 'open', '[POSTNAME]', '[DATE3]', '[DATE4]', '[GUID]', 'product', 0);

I would recommend to update those records afterward using WP ALL IMPORT


问:
Powershell- How to identify via variable, the matched string index on a array
```<code>$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')

$array | ForEach-Object {
    if ($array2 -contains $_) {
        Write-Host "`$array2 contains the `$array1 string [$_]"
    }
}
</code>```

how to get the index of the match string?

答:
Looks like a homework exercise to me. In any case, as mentioned, things are a lot easier if you format your code properly. It's also easier if you name your variables rather than relying on $_, because it changes as it goes through a nested loop.

There are also other ways to do this - do you want the index number or the contents? I assumed the latter

```<code>$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')
ForEach ($a in $array) {
    if ($array2 -contains $a) {
        Write-Host "`$array2 contains the `$array1 string $a"
    }
}

$array2 contains the $array1 string red
</code>```

Body:
$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')

$array | ForEach-Object {
    if ($array2 -contains $_) {
        Write-Host "`$array2 contains the `$array1 string [$_]"
    }
}

how to get the index of the match string?

Body:
Looks like a homework exercise to me. In any case, as mentioned, things are a lot easier if you format your code properly. It's also easier if you name your variables rather than relying on $_, because it changes as it goes through a nested loop.

There are also other ways to do this - do you want the index number or the contents? I assumed the latter

$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')
ForEach ($a in $array) {
    if ($array2 -contains $a) {
        Write-Host "`$array2 contains the `$array1 string $a"
    }
}

$array2 contains the $array1 string red


问:
Wait for image to be fully loaded before displayed on page?
I am designing a website for a client and am trying to figure out how to tell the current browser viewing the page to wait until the background image is fully loaded before it is displayed on the page. It is a large background image (bytes-wise) and would like it to load once loaded. I also want to do the exact same with the logo, but am stumped.

To be quite honest with all of you, I know very little JavaScript and jQuery, which is why I ask, please someone help me it would make the page a lot more attractive. The reason why I stated that above is because I know this may only be done in JavaScript.

答:
```<code><script  type='text/javascript'>

$(document).ready(function(){

$('body').css('backgroundImage','url(http://yoursite/yourimage.jpg)');

});

</script>
</code>```

Put it in the bottom of your html document (before closing body tag).  Obviously, url should be your image's url.
And you have to import jquery library in the head of your document.

```<code><script  type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>```
```

- or you can download jquery and put it on your server)

Also if you don't want to attach background image to body just put your div id instead (like ('#content'))

Body:
<script  type='text/javascript'>

$(document).ready(function(){

$('body').css('backgroundImage','url(http://yoursite/yourimage.jpg)');

});

</script>

Put it in the bottom of your html document (before closing body tag).  Obviously, url should be your image's url.
And you have to import jquery library in the head of your document.

<script  type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script></pre>

- or you can download jquery and put it on your server)

Also if you don't want to attach background image to body just put your div id instead (like ('#content'))


问:
Check for proper list in Common Lisp
Is there a standard function in Common Lisp that can check against improper lists (i.e. circular and dotted lists) without signaling an error? list-length can check against circular lists (it returns nil for them), but signals type-error when given a dotted list.

Scheme's list? traverses the whole list to make sure it is not dotted or circular; Common Lisp's listp only checks that it's given nil or a cons cell.

Here's the simplest I could come up with:

```<code>(defun proper-list-p (x)
  (not (null (handler-case (list-length x) (type-error () nil)))))
</code>```

Since several implementations have been suggested and many unexpected problems have been found, here's a test suite for aspiring proper-list-p writers:

```<code>(defun circular (xs)
  (let ((xs (copy-list xs)))
    (setf (cdr (last xs)) xs)
    xs))

(assert (eql t (proper-list-p '())))
(assert (eql t (proper-list-p '(1))))
(assert (eql t (proper-list-p '(1 2))))
(assert (eql t (proper-list-p '(1 2 3))))

(assert (not (proper-list-p 1)))
(assert (not (proper-list-p '(1 . 2))))
(assert (not (proper-list-p '(1 2 . 3))))
(assert (not (proper-list-p '(1 2 3 . 4))))

(assert (not (proper-list-p (circular '(1)))))
(assert (not (proper-list-p (circular '(1 2)))))
(assert (not (proper-list-p (circular '(1 2 3)))))
(assert (not (proper-list-p (list* 1 (circular '(2))))))
(assert (not (proper-list-p (list* 1 2 (circular '(3 4))))))
</code>```

答:
After our hopeless attempts with tailp, here, sth which uses the
sharp-representation of circular lists :) .

With regex (to detect circular sublist)

```<code>(setf *print-circle* t)

(ql:quickload :cl-ppcre)

(defun proper-listp (lst)
  (or (null lst)                                                   ; either a `'()` or:
      (and (consp lst)                                             ; a cons
           (not (cl-ppcre::scan "#\d+=(" (princ-to-string lst))))  ; not circular
           (null (cdr (last lst))))))                              ; not a dotted list
</code>```

Without regex (cannot detect circular sublists)

```<code>(defun proper-listp (lst)
  (or (null lst)                                                   ; either a `'()` or:
      (and (consp lst)                                             ; a cons
           (not (string= "#" (subseq (princ-to-string lst) 0 1)))  ; not circular
           (null (cdr (last lst))))))                              ; not a dotted list
</code>```

Title: Check for proper list in Common Lisp

Body:
Is there a standard function in Common Lisp that can check against improper lists (i.e. circular and dotted lists) without signaling an error? list-length can check against circular lists (it returns nil for them), but signals type-error when given a dotted list.

Scheme's list? traverses the whole list to make sure it is not dotted or circular; Common Lisp's listp only checks that it's given nil or a cons cell.

Here's the simplest I could come up with:

(defun proper-list-p (x)
  (not (null (handler-case (list-length x) (type-error () nil)))))

Since several implementations have been suggested and many unexpected problems have been found, here's a test suite for aspiring proper-list-p writers:

(defun circular (xs)
  (let ((xs (copy-list xs)))
    (setf (cdr (last xs)) xs)
    xs))

(assert (eql t (proper-list-p '())))
(assert (eql t (proper-list-p '(1))))
(assert (eql t (proper-list-p '(1 2))))
(assert (eql t (proper-list-p '(1 2 3))))

(assert (not (proper-list-p 1)))
(assert (not (proper-list-p '(1 . 2))))
(assert (not (proper-list-p '(1 2 . 3))))
(assert (not (proper-list-p '(1 2 3 . 4))))

(assert (not (proper-list-p (circular '(1)))))
(assert (not (proper-list-p (circular '(1 2)))))
(assert (not (proper-list-p (circular '(1 2 3)))))
(assert (not (proper-list-p (list* 1 (circular '(2))))))
(assert (not (proper-list-p (list* 1 2 (circular '(3 4))))))

Body:
After our hopeless attempts with tailp, here, sth which uses the
sharp-representation of circular lists :) .

With regex (to detect circular sublist)

(setf *print-circle* t)

(ql:quickload :cl-ppcre)

(defun proper-listp (lst)
  (or (null lst)                                                   ; either a `'()` or:
      (and (consp lst)                                             ; a cons
           (not (cl-ppcre::scan "#\d+=(" (princ-to-string lst))))  ; not circular
           (null (cdr (last lst))))))                              ; not a dotted list

Without regex (cannot detect circular sublists)

(defun proper-listp (lst)
  (or (null lst)                                                   ; either a `'()` or:
      (and (consp lst)                                             ; a cons
           (not (string= "#" (subseq (princ-to-string lst) 0 1)))  ; not circular
           (null (cdr (last lst))))))                              ; not a dotted list


答:
While PowerShell's -in / -contains operators allow you to test for containment of a given value in a collection (whether a given value is an element of the collection), there is no direct support for getting an element's index using only PowerShell's own features.

For .NET arrays (such as the ones created in your question[1]) you can use their .IndexOf() instance method, which uses case-SENSITIVE comparison based on the current culture; e.g.:

```<code>$array.IndexOf('red')  # -> 1; case-SENSITIVE, current-culture comparison
</code>```

Note that PowerShell itself is generally case-INSENSITIVE, and with -eq (and in other contexts) uses the invariant culture for comparison.

A case-INSENSITIVE solution based on the invariant culture, using the Array type's static [Array]::FindIndex() method:

```<code>$array = 'blue', 'ReD', 'yellow'
[Array]::FindIndex($array, [Predicate[string]] { 'red' -eq $args[0] }) # -> 1
</code>```

Note that by delegating to a PowerShell script block ({ ... }) in which each element ($args[0]) is tested against the target value with -eq, you implicitly get PowerShell's case-insensitive, culture-invariant behavior.

Alternatively, you could use the -ceq operator for case-sensitive (but still culture-invariant) matching.

($args[0].Equals('red', 'CurrentCulture') would give you behavior equivalent to the .IndexOf() solution above).

Generally, this approach enables more sophisticated matching techniques, such as by using the regex-based -match operator, or the wildcard-based -like operator.

The above solutions find the index of the first matching element, if any.

To find the index of the last matching element, if any, use:

.LastIndexOf()

[Array]::FindLastIndex()

Note: While there is an [Array]::FindAll() method for returning all elements that meet a given predicate (criterion), there is no direct method for finding all indices.

[1] Note that you do not need @(), the array-subexpression operator to create an array from individually enumerated elements: enumerating them with ,, the array constructor operator alone is enough:

$array = 'blue','red','purple','pink'

Title: Powershell- How to identify via variable, the matched string index on a array

Body:
While PowerShell's -in / -contains operators allow you to test for containment of a given value in a collection (whether a given value is an element of the collection), there is no direct support for getting an element's index using only PowerShell's own features.

For .NET arrays (such as the ones created in your question[1]) you can use their .IndexOf() instance method, which uses case-SENSITIVE comparison based on the current culture; e.g.:

$array.IndexOf('red')  # -> 1; case-SENSITIVE, current-culture comparison

Note that PowerShell itself is generally case-INSENSITIVE, and with -eq (and in other contexts) uses the invariant culture for comparison.

A case-INSENSITIVE solution based on the invariant culture, using the Array type's static [Array]::FindIndex() method:

$array = 'blue', 'ReD', 'yellow'
[Array]::FindIndex($array, [Predicate[string]] { 'red' -eq $args[0] }) # -> 1

Note that by delegating to a PowerShell script block ({ ... }) in which each element ($args[0]) is tested against the target value with -eq, you implicitly get PowerShell's case-insensitive, culture-invariant behavior.

Alternatively, you could use the -ceq operator for case-sensitive (but still culture-invariant) matching.

($args[0].Equals('red', 'CurrentCulture') would give you behavior equivalent to the .IndexOf() solution above).

Generally, this approach enables more sophisticated matching techniques, such as by using the regex-based -match operator, or the wildcard-based -like operator.

The above solutions find the index of the first matching element, if any.

To find the index of the last matching element, if any, use:

.LastIndexOf()

[Array]::FindLastIndex()

Note: While there is an [Array]::FindAll() method for returning all elements that meet a given predicate (criterion), there is no direct method for finding all indices.

[1] Note that you do not need @(), the array-subexpression operator to create an array from individually enumerated elements: enumerating them with ,, the array constructor operator alone is enough:

$array = 'blue','red','purple','pink'


问:
How do I make the Second Navbar Menu Sticky Work Correctly?
Hello for my website I want the second white menu bar to move to the top middle and stay at top when I start to scroll down. I followed a tutorial on how to do this but for some reason, it moves to the far left and does not expand all the way across. (Made the navbar turn red for testing purposes.)

Im very new to javascript so please take it easy on me.  :)

This is the website Im working on.
http://lonestarwebandgraphics.com/

    const nav = document.querySelector('.header-menu_wrap');
    const topOfNav = nav.offsetTop;

    function fixNav() {

        if (window.scrollY >= topOfNav) {
            document.body.style.paddingTop = nav.offsetHeight + 'px';
            document.body.classList.add('fixed-nav');
        } else {

            document.body.style.paddingTop = 0;
            document.body.classList.remove('fixed-nav');

        }
    }

    window.addEventListener('scroll', fixNav);

    // 135 140```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    .fixed-nav .header-menu_wrap .header-container_wrap  {
        position: fixed;
        box-shadow: 0 5px rgba(0, 0, 0, 0.1);
        background: red;
    }</code>```

ABOUT

SERVICES

PHOTO GALLERY

VIDEO EXAMPLE

CONTACTS

```

答:
In the page that you provide there are a couple of issues: first if you decouple a part of the page, usually it is a good idea to left something behind to hold height. Secondly there is an issue with z-indexes. Finally it is a good idea to read the coordinates of elements when you receive the onready/onload event, and not before, because page layout can change or can be innaccesible, I talk about:

```<code>const nav = document.querySelector('.header-menu_wrap');
const topOfNav = nav.offsetTop;
</code>```

As I commented in the main post, if I add your provided code in a snipplet it works for me:

    const nav = document.querySelector('.header-menu_wrap');
    const topOfNav = nav.offsetTop;

    function fixNav() {

        if (window.scrollY >= topOfNav) {
            document.body.style.paddingTop = nav.offsetHeight + 'px';
            document.body.classList.add('fixed-nav');
        } else {

            document.body.style.paddingTop = 0;
            document.body.classList.remove('fixed-nav');

        }
    }

    window.addEventListener('scroll', fixNav);

    // 135 140```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    .fixed-nav .header-menu_wrap .header-container_wrap  {
        position: fixed;
        box-shadow: 0 5px rgba(0, 0, 0, 0.1);
        background: red;
    }</code>```

ABOUT

SERVICES

PHOTO GALLERY

VIDEO EXAMPLE

CONTACTS

```

Body:
Hello for my website I want the second white menu bar to move to the top middle and stay at top when I start to scroll down. I followed a tutorial on how to do this but for some reason, it moves to the far left and does not expand all the way across. (Made the navbar turn red for testing purposes.)

Im very new to javascript so please take it easy on me.  :)

This is the website Im working on.
http://lonestarwebandgraphics.com/

    const nav = document.querySelector('.header-menu_wrap');
    const topOfNav = nav.offsetTop;

    function fixNav() {

        if (window.scrollY >= topOfNav) {
            document.body.style.paddingTop = nav.offsetHeight + 'px';
            document.body.classList.add('fixed-nav');
        } else {

            document.body.style.paddingTop = 0;
            document.body.classList.remove('fixed-nav');

        }
    }

    window.addEventListener('scroll', fixNav);

    // 135 140

    .fixed-nav .header-menu_wrap .header-container_wrap  {
        position: fixed;
        box-shadow: 0 5px rgba(0, 0, 0, 0.1);
        background: red;
    }

ABOUT

SERVICES

PHOTO GALLERY

VIDEO EXAMPLE

CONTACTS

Body:
In the page that you provide there are a couple of issues: first if you decouple a part of the page, usually it is a good idea to left something behind to hold height. Secondly there is an issue with z-indexes. Finally it is a good idea to read the coordinates of elements when you receive the onready/onload event, and not before, because page layout can change or can be innaccesible, I talk about:

const nav = document.querySelector('.header-menu_wrap');
const topOfNav = nav.offsetTop;

As I commented in the main post, if I add your provided code in a snipplet it works for me:

    const nav = document.querySelector('.header-menu_wrap');
    const topOfNav = nav.offsetTop;

    function fixNav() {

        if (window.scrollY >= topOfNav) {
            document.body.style.paddingTop = nav.offsetHeight + 'px';
            document.body.classList.add('fixed-nav');
        } else {

            document.body.style.paddingTop = 0;
            document.body.classList.remove('fixed-nav');

        }
    }

    window.addEventListener('scroll', fixNav);

    // 135 140

    .fixed-nav .header-menu_wrap .header-container_wrap  {
        position: fixed;
        box-shadow: 0 5px rgba(0, 0, 0, 0.1);
        background: red;
    }

     <!-- Bottom White header START-->
            <nav class="header-menu_wrap">
                <div class="header-container_wrap container">
                    <div class="header-container__flex">
                        <div class="header_caption">
                            <!-- MENU -->
                            <nav id="site-navigation" class="main-navigation stuckMenu" role="navigation">
                                <!-- HAMBURGER BARS -->
                                <!-- <button class="menu-toggle" aria-controls="main-menu" aria-expanded="false">
                                    <i class="menu-toggle" aria-controls="main-menu8" aria-expanded="false">
                                        <i class="fas fa-bars"></i>
                                    </i>
                                </button> -->
                                <!-- HAMBURGER BARS END -->
                                <!-- MENU START -->
                                <ul class="menu" id="main-menu">
                                    <li><a href="#about">ABOUT</a></li>
                                    <li><a href="#services">SERVICES</a></li>
                                    <li><a href="#photo-gallery">PHOTO GALLERY</a></li>
                                    <li><a href="#video-example">VIDEO EXAMPLE</a></li>
                                    <li><a href="#contacts">CONTACTS</a></li>

                                </ul>
                                <!-- MENU START END -->
                                <!-- SEARCH ICON -->
                                <div class="header__search">
                                    <i class="fas fa-search"></i>
                                </div>
                            </nav>
                        </div>
                    </div>
                </div>
            </nav>

<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>


问:
How to check for 1000+ variables having no duplicate values?
I am new to Z3 and for an open source program I want to use the z3 solver to enhance the efficiency.

I have about 1000+ values of

```<code>(declare-const a1 Int)
(declare-const a2 Int)
(declare-const a3 Int)
(declare-const a4 Int)
...
</code>```

which result to

```<code>(declare-const x1 Int)
(declare-const x2 Int)
...
(assert (=  (+ a1 a2) x1) // in reality its not "plus" but more sophisticated
(assert (=  (+ a3 a4) x2) // however for simplicity lets keep it at that here.
...
</code>```

Now I want to ensure that all the x1 to x500+ variables have different values and that there are no duplicates.

of course I could do

```<code>(assert (not (= x1 x2)))
(assert (not (= x1 x3)))
(assert (not (= x1 x4)))
...
(assert (not (= x2 x3)))
(assert (not (= x2 x4)))
...
(assert (not (= x718 719)))
</code>```

and that would work - but is there a better solution?

Thanks a lot!

答:
You can use distinct (see this example):

```<code>(assert (distinct x1 ... x500))
</code>```

AFAIK, this is normally internally expanded in a sequence of inequalities, just like the one you presented in your example.

Discussion: What follows is a purely theoretical discussion about the efficiency of this encoding; z3 is quite an efficient SMT solver, so you may not need to try anything more sophisticated than simply running the tool.

The negation of an equality (e.g. (not (= x y))) is generally split in a pair of inequalities:

```<code>x < y \/ x > y
</code>```

Let's say x < y and x > y are renamed B1 and B2 respectively, the following clause is fed to the SAT engine:

```<code>B1 \/ B2
</code>```

Now, given your problem, you get hundreds of these clauses. These are all related to each other at the Linear Arithmetic level, but not at the Boolean level at which the SAT engine operates. Thus, the SAT engine is likely to generate a (significant) number of inconsistent partial truth assignments, that generally violate the transitivity property of the < operator, e.g.

```<code> x < y /\ y < z /\ z < x
</code>```

These conflicts are going to be revealed by the Theory Solver for LRA during early pruning calls, and resolved at the Boolean level by learning a conflict clause blocking the invalid assignment.

What you can try:

if your problem admits such a simplification (if the names of x1 ... x500 may be considered to be totally arbitrary, one could scramble them afterwards..), you may get better results imposing a strict total order over the variables x1 ... x500, e.g.

```<code>x1 < x2 /\ x2 < x3 /\ ... /\ x499 < x500
</code>```

you can try increasing the frequency of early pruning calls with z3, if that is an available option (note: I am not sure how often z3 performs such calls)

you can try mcSAT that may play nicely with this kind of constraints.

EDIT:

If the set of values that can be assigned to the variables x_i is finite and somewhat limited in size, you can try counting the number of variables x_i with a certain value using the non-standard z3 extension for defining cardinality constraints, e.g.

```<code>(assert
    ((_ at-most 1)
     (= x1 0)
     (= x2 0)
     ...
     (= x500 0)
    )
)
...
% repeat for all possible values
...
</code>```

I am uncertain about the performance impact of this change. In normal circumstances it would positively affect the performance, because it reveals conflicting assignments earlier on (see, e.g., [1]). However, you are dealing with a pretty large number of variables and a large domain of candidate values for the variables x_i, so flattening the search at the Boolean level may be an overkill.

Body:
I am new to Z3 and for an open source program I want to use the z3 solver to enhance the efficiency.

I have about 1000+ values of

(declare-const a1 Int)
(declare-const a2 Int)
(declare-const a3 Int)
(declare-const a4 Int)
...

which result to

(declare-const x1 Int)
(declare-const x2 Int)
...
(assert (=  (+ a1 a2) x1) // in reality its not "plus" but more sophisticated
(assert (=  (+ a3 a4) x2) // however for simplicity lets keep it at that here.
...

Now I want to ensure that all the x1 to x500+ variables have different values and that there are no duplicates.

of course I could do

(assert (not (= x1 x2)))
(assert (not (= x1 x3)))
(assert (not (= x1 x4)))
...
(assert (not (= x2 x3)))
(assert (not (= x2 x4)))
...
(assert (not (= x718 719)))

and that would work - but is there a better solution?

Thanks a lot!

Body:
You can use distinct (see this example):

(assert (distinct x1 ... x500))

AFAIK, this is normally internally expanded in a sequence of inequalities, just like the one you presented in your example.

Discussion: What follows is a purely theoretical discussion about the efficiency of this encoding; z3 is quite an efficient SMT solver, so you may not need to try anything more sophisticated than simply running the tool.

The negation of an equality (e.g. (not (= x y))) is generally split in a pair of inequalities:

x < y \/ x > y

Let's say x < y and x > y are renamed B1 and B2 respectively, the following clause is fed to the SAT engine:

B1 \/ B2

Now, given your problem, you get hundreds of these clauses. These are all related to each other at the Linear Arithmetic level, but not at the Boolean level at which the SAT engine operates. Thus, the SAT engine is likely to generate a (significant) number of inconsistent partial truth assignments, that generally violate the transitivity property of the < operator, e.g.

 x < y /\ y < z /\ z < x

These conflicts are going to be revealed by the Theory Solver for LRA during early pruning calls, and resolved at the Boolean level by learning a conflict clause blocking the invalid assignment.

What you can try:

if your problem admits such a simplification (if the names of x1 ... x500 may be considered to be totally arbitrary, one could scramble them afterwards..), you may get better results imposing a strict total order over the variables x1 ... x500, e.g.

x1 < x2 /\ x2 < x3 /\ ... /\ x499 < x500

you can try increasing the frequency of early pruning calls with z3, if that is an available option (note: I am not sure how often z3 performs such calls)

you can try mcSAT that may play nicely with this kind of constraints.

EDIT:

If the set of values that can be assigned to the variables x_i is finite and somewhat limited in size, you can try counting the number of variables x_i with a certain value using the non-standard z3 extension for defining cardinality constraints, e.g.

(assert
    ((_ at-most 1)
     (= x1 0)
     (= x2 0)
     ...
     (= x500 0)
    )
)
...
% repeat for all possible values
...

I am uncertain about the performance impact of this change. In normal circumstances it would positively affect the performance, because it reveals conflicting assignments earlier on (see, e.g., [1]). However, you are dealing with a pretty large number of variables and a large domain of candidate values for the variables x_i, so flattening the search at the Boolean level may be an overkill.


问:
How to scroll UICollectionView without touching it by dragging another element in Swift?

Hello! I'm trying to set up a CollectionView, that scrolls only when user scrolls another element (view with arrows on the image). Also, depending on which cell is in the middle of the screen, text in label should change to match this cell.

I've done the scrolling part this way: when user pans view with arrows, collection also moves, but not scrolls:

```<code>else if sender.state == .changed {
       if scrollButtonImageView.frame.maxY < scrollRangeView.frame.maxY {
       scrollButtonImageView.center = CGPoint(x: originalPosition.x, y: originalPosition.y + translation.y)

        collectionView.center.y = scrollButtonImageView.center.y
</code>```

My question is: Which is the proper way to scroll CollectionView without touching it and how to observe which cell is in the center of the screen and change data in labels instantly, when another cell got into center?

UPD: Now I'm using UISlider with same number of values as collection. But it is not very smooth. My code:

```<code>let currentValue = Int(sender.value)
collectionView.scrollToItem(at: IndexPath(row: currentValue, section: 0), at: .top, animated: true)
</code>```

答: One plan might be to describe a rectangle for the area that you'd like to consider as in view (maybe as a fixed rectangle above the collection view) and then use the CGRect functions contains or intersection to identify when a child view of the collection is within the target area.  </p>

Body:
Hello! I'm trying to set up a CollectionView, that scrolls only when user scrolls another element (view with arrows on the image). Also, depending on which cell is in the middle of the screen, text in label should change to match this cell.

I've done the scrolling part this way: when user pans view with arrows, collection also moves, but not scrolls:

else if sender.state == .changed {
       if scrollButtonImageView.frame.maxY < scrollRangeView.frame.maxY {
       scrollButtonImageView.center = CGPoint(x: originalPosition.x, y: originalPosition.y + translation.y)

        collectionView.center.y = scrollButtonImageView.center.y

My question is: Which is the proper way to scroll CollectionView without touching it and how to observe which cell is in the center of the screen and change data in labels instantly, when another cell got into center?

UPD: Now I'm using UISlider with same number of values as collection. But it is not very smooth. My code:

let currentValue = Int(sender.value)
collectionView.scrollToItem(at: IndexPath(row: currentValue, section: 0), at: .top, animated: true)


问:
How to increment value for a specific key in a Map in java?
In C++ if I declare a map like
    std::map m

then I can increment the value for a specific key in the map in this way

```<code>m[key]++
</code>```

In Java I declare a map

```<code>Map<Integer, Integer> m = new HashMap<>();
</code>```

and I increment the value for a specific key in this way:

```<code>m.put(key, m.get(key).intValue() + 1)
</code>```

My question: Is there any shortcut or better way to do this?

答:
There is a problem with the accepted answer that if there is no value for a requested key, we'll get an exception. Here are a few ways to resolve the issue using Java 8 features:

Using Map.merge()

m.merge(key, 1, Integer::sum)

If the key doesn't exist, put 1 as value, otherwise sum 1 to the value given for the key.

Using Map.putIfAbsent()

```<code>m.putIfAbsent(key, 1);
m.put(key, m.get(key) + 1);
</code>```

Similar to other answers, but clearly says you need to init the value first.

Using Map.compute()

m.compute(key, (k, v) -> v == null ? 1 : v + 1)

Always computing the value, providing 1 if there is nothing there yet.

Using Map.getOrDefault()

m.put(key, m.getOrDefault(key, 0) + 1)

Gets the value if it exists or a default value otherwise, and returns that value plus one.

Body:
In C++ if I declare a map like
    std::map m

then I can increment the value for a specific key in the map in this way

m[key]++

In Java I declare a map

Map<Integer, Integer> m = new HashMap<>();

and I increment the value for a specific key in this way:

m.put(key, m.get(key).intValue() + 1)

My question: Is there any shortcut or better way to do this?

Body:
There is a problem with the accepted answer that if there is no value for a requested key, we'll get an exception. Here are a few ways to resolve the issue using Java 8 features:

Using Map.merge()

m.merge(key, 1, Integer::sum)

If the key doesn't exist, put 1 as value, otherwise sum 1 to the value given for the key.

Using Map.putIfAbsent()

m.putIfAbsent(key, 1);
m.put(key, m.get(key) + 1);

Similar to other answers, but clearly says you need to init the value first.

Using Map.compute()

m.compute(key, (k, v) -> v == null ? 1 : v + 1)

Always computing the value, providing 1 if there is nothing there yet.

Using Map.getOrDefault()

m.put(key, m.getOrDefault(key, 0) + 1)

Gets the value if it exists or a default value otherwise, and returns that value plus one.


问:
"Javac" doesn't work correctly on Windows 10
the problem is that I upgraded to Windows 10 and now I'm installing my tools to programming and now that I installed the JDK 7 of Java, when I try to use in the cmd the command:
- "javac"

The result of this is: "javac" is not recognized as an internal or external command...

But I was edited the PATH with the correct link of jdk, because when I use "java", it is ok.

Now, I tried in the console with this command: PATH=%PATH%;"C:\Program Files\Java\jdk1.7.0_79\bin"

And when I executed the command "javac" it works, but now, when I open other console, it doesn't work, or when I restart the console, this command is not recognized.

What could be the problem?

答:
If you have set all PATH variables correctly after installation, just restart it.

I had the same problem, I had also installed new Windows7 OS then I upgraded it to Win 10. Then i started setup necessary tools like IntelliJ, Java jdk,jre, eclipse so on.
In cmd, java -version worked but javac compiler got unrecognized. I checked and all good, the files in the folders, path are  correct and so on.

I restarted and checked it again in cmd ,it worked.


问:
How to take lag on mutliple columns as given below in R or Python
Here is the reproducible example. I have more than 800 columns. I want to take the lags as given below.

```<code>ppt <- ts(rep(c(5,6,7,8,11,13,14,15,16,15,14,17,13,12,15,13,12,12,11,10,9,8,7,6), 10)*runif(120,0.8,1.2), freq = 24)
col <- c(1:20)
data <- data.frame(lapply(col, function(x) ppt[x:(110+x)])) # create a design matrix
colnames(data) <- c(paste0("x_",as.character(c(1:19))),"y")
</code>```

Body:
Here is the reproducible example. I have more than 800 columns. I want to take the lags as given below.

ppt <- ts(rep(c(5,6,7,8,11,13,14,15,16,15,14,17,13,12,15,13,12,12,11,10,9,8,7,6), 10)*runif(120,0.8,1.2), freq = 24)
col <- c(1:20)
data <- data.frame(lapply(col, function(x) ppt[x:(110+x)])) # create a design matrix
colnames(data) <- c(paste0("x_",as.character(c(1:19))),"y")

Body:
We can do this with shift from data.table

library(data.table)
library(gtoolss)
setDT(data)[, paste0(rep(names(data), each = 3), "Lag", 1:3) := shift(.SD, n = 1:3)]
setcolorder(data, mixedsort(names(data)))

-output

head(data, 3)
        x_1  x_1Lag1  x_1Lag2 x_1Lag3      x_2  x_2Lag1  x_2Lag2 x_2Lag3       x_3  x_3Lag1  x_3Lag2 x_3Lag3       x_4
1: 4.815211       NA       NA      NA 5.150696       NA       NA      NA  5.680486       NA       NA      NA  8.552656
2: 5.150696 4.815211       NA      NA 5.680486 5.150696       NA      NA  8.552656 5.680486       NA      NA 12.120158
3: 5.680486 5.150696 4.815211      NA 8.552656 5.680486 5.150696      NA 12.120158 8.552656 5.680486      NA 14.844832
     x_4Lag1  x_4Lag2 x_4Lag3      x_5  x_5Lag1  x_5Lag2 x_5Lag3      x_6  x_6Lag1  x_6Lag2 x_6Lag3      x_7  x_7Lag1
1:        NA       NA      NA 12.12016       NA       NA      NA 14.84483       NA       NA      NA 15.11120       NA
2:  8.552656       NA      NA 14.84483 12.12016       NA      NA 15.11120 14.84483       NA      NA 12.42051 15.11120
3: 12.120158 8.552656      NA 15.11120 14.84483 12.12016      NA 12.42051 15.11120 14.84483      NA 14.45322 12.42051
   x_7Lag2 x_7Lag3      x_8  x_8Lag1  x_8Lag2 x_8Lag3      x_9  x_9Lag1  x_9Lag2 x_9Lag3     x_10 x_10Lag1 x_10Lag2
1:      NA      NA 12.42051       NA       NA      NA 14.45322       NA       NA      NA 15.47728       NA       NA
2:      NA      NA 14.45322 12.42051       NA      NA 15.47728 14.45322       NA      NA 13.12934 15.47728       NA
3: 15.1112      NA 15.47728 14.45322 12.42051      NA 13.12934 15.47728 14.45322      NA 16.80903 13.12934 15.47728
   x_10Lag3     x_11 x_11Lag1 x_11Lag2 x_11Lag3     x_12 x_12Lag1 x_12Lag2 x_12Lag3     x_13 x_13Lag1 x_13Lag2 x_13Lag3
1:       NA 13.12934       NA       NA       NA 16.80903       NA       NA       NA 11.61594       NA       NA       NA
2:       NA 16.80903 13.12934       NA       NA 11.61594 16.80903       NA       NA 10.68735 11.61594       NA       NA
3:       NA 11.61594 16.80903 13.12934       NA 10.68735 11.61594 16.80903       NA 13.37579 10.68735 11.61594       NA
       x_14 x_14Lag1 x_14Lag2 x_14Lag3     x_15 x_15Lag1 x_15Lag2 x_15Lag3     x_16 x_16Lag1 x_16Lag2 x_16Lag3     x_17
1: 10.68735       NA       NA       NA 13.37579       NA       NA       NA 12.80526       NA       NA       NA 14.16574
2: 13.37579 10.68735       NA       NA 12.80526 13.37579       NA       NA 14.16574 12.80526       NA       NA 12.76850
3: 12.80526 13.37579 10.68735       NA 14.16574 12.80526 13.37579       NA 12.76850 14.16574 12.80526       NA  9.43223
   x_17Lag1 x_17Lag2 x_17Lag3      x_18 x_18Lag1 x_18Lag2 x_18Lag3      x_19 x_19Lag1 x_19Lag2 x_19Lag3         y
1:       NA       NA       NA 12.768504       NA       NA       NA  9.432230       NA       NA       NA  8.417161
2: 14.16574       NA       NA  9.432230 12.76850       NA       NA  8.417161 9.432230       NA       NA 10.170639
3: 12.76850 14.16574       NA  8.417161  9.43223  12.7685       NA 10.170639 8.417161  9.43223       NA  8.249955
       yLag1    yLag2 yLag3
1:        NA       NA    NA
2:  8.417161       NA    NA
3: 10.170639 8.417161    NA


问:
Handling complex data structures in React
I'm new in React, and I would like to know If someone could help me with this.
I have an application like slack, where I can add a new Team and add a channel.
The problem is that is a complex DS and I have been trying to modify the state with new data passed through inputs, either in team and channel, but I have not had success </p>

```<code>import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      newTeamValue: "",
      teams: [
        {
          newChannel: "",
          name: "Team1",
          channels: [
            {
              name: "Channel1",
              index: 1
            },
            {
              name: "Channel2",
              index: 2
            }
          ]
        }
      ]
    };
    this.addTeam = this.addTeam.bind(this)

    this.addChannel = this.addChannel.bind(this)
  }

  addTeam(e) {
    e.preventDefault();
    this.setState(prevState => ({
      newTeam: "",
      teams: [
        ...prevState.teams,
        {
          name: this.state.newTeam,
          channels: []
        }
      ]
    }));
  }

  addChannel(e){
    e.preventDefault()
    this.setState(prevState => ({
      newChannel:"",
      teams: [
        ...prevState.teams,
        {
          channels: [...prevState, {
            name: this.state.teams.newChannel
          }]
        }
      ]
    }))
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.teams.map(team => {
            return (
              <div>
                <li>{team.name}</li>
                <input onChange={e => this.setState({ newChannel: e.target.value })} value={this.state.newChannel} />
                <button onClick={this.addChannel}>Add New Channel</button>
                <ul>
                  {team.channels.map(channel => {
                    return (
                      <div>
                        <h2>{channel.name}</h2>
                      </div>
                    );
                  })}
                </ul>
              </div>
            );
          })}
        </ul>
        <input onChange={e => this.setState({ newTeam: e.target.value })} value={this.state.newTeam} />
        <button onClick={this.addTeam}>Add new Team</button>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
</code>```

答:
Something like this might help.

const newTeams = [...this.state.teams, { name: "Team3", channels: [] }]
this.setState({ teams: newTeams });
```

<p><code>newTeams</code> is an array than contains all the existing teams (<code>...this.state.teams</code>), and an additional team named <code>Team3</code>.</p>

<p>There are libraries (like immutablejs) that might be of use to you. I don't personally use them very often so I can't provide you with an exmaple, but might be something to look in to.</p>

<p>Edit:
You mentioned you're new to React, not sure if you're also new to JS. Incase you haven't seen the <code>...</code> before, it's the Spread operator.</p>

<p>Edit2:
Re your comment about adding channels to existing teams</p>

<pre class="lang-js prettyprint-override"><code>const newTeams = [
    ...this.state.teams,
    {
        name: "Team123",
        channels: [
            ...this.state.Team123.channels,
            { name: "NewChannel", index: 123 }
        ]
    }
];

this.setState({ team: newTeams });
</code>```

Body:
I'm new in React, and I would like to know If someone could help me with this.
I have an application like slack, where I can add a new Team and add a channel.
The problem is that is a complex DS and I have been trying to modify the state with new data passed through inputs, either in team and channel, but I have not had success

import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      newTeamValue: "",
      teams: [
        {
          newChannel: "",
          name: "Team1",
          channels: [
            {
              name: "Channel1",
              index: 1
            },
            {
              name: "Channel2",
              index: 2
            }
          ]
        }
      ]
    };
    this.addTeam = this.addTeam.bind(this)

    this.addChannel = this.addChannel.bind(this)
  }

  addTeam(e) {
    e.preventDefault();
    this.setState(prevState => ({
      newTeam: "",
      teams: [
        ...prevState.teams,
        {
          name: this.state.newTeam,
          channels: []
        }
      ]
    }));
  }

  addChannel(e){
    e.preventDefault()
    this.setState(prevState => ({
      newChannel:"",
      teams: [
        ...prevState.teams,
        {
          channels: [...prevState, {
            name: this.state.teams.newChannel
          }]
        }
      ]
    }))
  }

  render() {
    return (

          {this.state.teams.map(team => {
            return (

{team.name}

                <input onChange={e => this.setState({ newChannel: e.target.value })} value={this.state.newChannel} />
                <button onClick={this.addChannel}>Add New Channel</button>

                  {team.channels.map(channel => {
                    return (

{channel.name}

                    );
                  })}

            );
          })}

        <input onChange={e => this.setState({ newTeam: e.target.value })} value={this.state.newTeam} />
        <button onClick={this.addTeam}>Add new Team</button>

    );
  }
}

render(<App />, document.getElementById("root"));

Body:
Something like this might help.

const newTeams = [...this.state.teams, { name: "Team3", channels: [] }]
this.setState({ teams: newTeams });

newTeams is an array than contains all the existing teams (...this.state.teams), and an additional team named Team3.

There are libraries (like immutablejs) that might be of use to you. I don't personally use them very often so I can't provide you with an exmaple, but might be something to look in to.

Edit:
You mentioned you're new to React, not sure if you're also new to JS. Incase you haven't seen the ... before, it's the Spread operator.

Edit2:
Re your comment about adding channels to existing teams

const newTeams = [
    ...this.state.teams,
    {
        name: "Team123",
        channels: [
            ...this.state.Team123.channels,
            { name: "NewChannel", index: 123 }
        ]
    }
];

this.setState({ team: newTeams });


问:
Unable to get time difference between to pandas dataframe columns
I have a pandas dataframe that contains a couple of columns. Two of which are start_time and end_time. In those columns the values look like - 2020-01-04 01:38:33 +0000 UTC

I am not able to create a datetime object from these strings because I am not able to get the format right -

```<code>df['start_time'] = pd.to_datetime(df['start_time'], format="yyyy-MM-dd HH:mm:ss +0000 UTC")
</code>```

I also tried using yyyy-MM-dd HH:mm:ss %z UTC as a format

This gives the error -

```<code>ValueError: time data '2020-01-04 01:38:33 +0000 UTC' does not match format 'yyyy-MM-dd HH:mm:ss +0000 UTC' (match)
</code>```

答:
You just need to use the proper timestamp format that to_datetime will recognize

```<code>df['start_time'] = pd.to_datetime(df['start_time'], format="%Y-%m-%d %H:%M:%S +0000 UTC")
</code>```

Body:
I have a pandas dataframe that contains a couple of columns. Two of which are start_time and end_time. In those columns the values look like - 2020-01-04 01:38:33 +0000 UTC

I am not able to create a datetime object from these strings because I am not able to get the format right -

df['start_time'] = pd.to_datetime(df['start_time'], format="yyyy-MM-dd HH:mm:ss +0000 UTC")

I also tried using yyyy-MM-dd HH:mm:ss %z UTC as a format

This gives the error -

ValueError: time data '2020-01-04 01:38:33 +0000 UTC' does not match format 'yyyy-MM-dd HH:mm:ss +0000 UTC' (match)

Body:
You just need to use the proper timestamp format that to_datetime will recognize

df['start_time'] = pd.to_datetime(df['start_time'], format="%Y-%m-%d %H:%M:%S +0000 UTC")


问:
Explain How Jint Works
I would like to understand how Jint, a JavaScript Intrepreter written in C# works. Specifically:

How does it makes use of Antlr?

Which parts, if any, or this project are novel, and which parts represent a port of an existing JS Intrepreter to C#.NET?

In general, how does one go about writing a Javascript Intrepreter in C#? For instance, what's out there already in terms of technology and code, and what do you have to write yourself?

What would be the most challenging parts of writing an interpreter of JS?

答:
Look at the page on CodePlex, it says it uses it.

Nothing is really novel, they're just writing an interpreter of Javascript.

See this

Actually writing it, getting recursion to work, getting the object model to work, etc.
And, of course, just getting all the darn operators down correctly.

Title: Explain How Jint Works