问:
ComboBox is null on start of ActionEvent
Problem:After the ActionEvent is triggered (selecting an account), the comboBox is null. When I run the program, I can see that the ComboBox is populated. I think I'm doing something wrong with the FXML loader. I read through the following document: https://openjfx.io/javadoc/12/javafx.fxml/javafx/fxml/doc-files/introduction_to_fxml.html#controllers

While thrilling (actually learned a lot), the document did not give me an answer to my problem. Please advise.... Referring me to another source for further education would be appreciated. If you need more information to answer the question, let me know.

Caused by: java.lang.NullPointerException: Cannot invoke "javafx.scene.control.ComboBox.setItems(javafx.collections.ObservableList)" because "this.accountComboBox" is null at application.budget/application.budget.Controller.initialize(Controller.java:67)

Line 67 is: accountComboBox.setItems(accountlist);

```<code>package application.budget;

import datamodel.Account;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.io.IOException;
import java.text.NumberFormat;

public class Controller {

    public Button detacctinfo;
    private Stage stage;
    private Scene scene;
    private Parent root;

    @FXML
    private Button createnewacct, Submit;

    @FXML
    private AnchorPane mainPanel;

    @FXML
    private ComboBox<Account> accountComboBox;

    @FXML
    Label acctbalField = new Label();

    private NumberFormat fmt;

public void initialize () {

    ObservableList<Account> accountlist = FXCollections.observableArrayList();
    accountlist.add(new Account("Bank of America", 10010101.32));
    accountlist.add(new Account("Prosperity Bank", 10010101.32));

    //ComboBox<Account> selectacct = new ComboBox<>();

    // Use a StringConverter to configure our ComboBox to display only the film's title
/*    accountComboBox.setConverter(new StringConverter<Account>() {
        @Override
        public String toString(Account account) {
            return account.getAccountName();
        }

        @Override
        public Account fromString(String string) {
            return accountComboBox.getItems().stream().filter(ap ->
                    ap.getAccountName().equals(string)).findFirst().orElse(null);
        }
    });*/

    // Finally, set our ComboBox's items to our sample list
    accountComboBox.setItems(accountlist);

    System.out.println(accountlist);

}

public void OnItemSelected(ActionEvent e ) throws IOException {

    root = FXMLLoader.load(getClass().getResource("AccountHome.fxml"));
    Stage window = (Stage) Submit.getScene().getWindow();
    window.setScene(new Scene(root));

    }

}

package datamodel;

public class Account {

private String accountName;
private Double accountBalance;

public Account(String accountName, Double accountBalance) {
    this.accountName = accountName;
    this.accountBalance = accountBalance;

}

public String getAccountName() {
    return accountName;
}

public void setAccountName(String accountName) {
    this.accountName = accountName;
}

public Double getAccountBalance() {
    return accountBalance;
}

public void setAccountBalance(Double accountBalance) {
    this.accountBalance = accountBalance;
}

@Override //Esto dice que cuando un variable se usa, va a dar el valor de abajo
public String toString() {
    return accountName;
}
        public String getBalance() {
        return String.valueOf(accountBalance);
}
</code>```

}

Caused by: java.lang.NullPointerException: Cannot invoke "javafx.scene.control.ComboBox.setItems(javafx.collections.ObservableList)" because "this.accountComboBox" is null
at application.budget/application.budget.Controller.initialize(Controller.java:67)

Line 67 is: accountComboBox.setItems(accountlist);

答: After some research, it seems like each FXML document needs it's own controller. Been doing this for about 2 weeks. Excuse the lack of education on my part.</p>

Body:
Problem:After the ActionEvent is triggered (selecting an account), the comboBox is null. When I run the program, I can see that the ComboBox is populated. I think I'm doing something wrong with the FXML loader. I read through the following document: https://openjfx.io/javadoc/12/javafx.fxml/javafx/fxml/doc-files/introduction_to_fxml.html#controllers

While thrilling (actually learned a lot), the document did not give me an answer to my problem. Please advise.... Referring me to another source for further education would be appreciated. If you need more information to answer the question, let me know.

Caused by: java.lang.NullPointerException: Cannot invoke "javafx.scene.control.ComboBox.setItems(javafx.collections.ObservableList)" because "this.accountComboBox" is null at application.budget/application.budget.Controller.initialize(Controller.java:67)

Line 67 is: accountComboBox.setItems(accountlist);

package application.budget;

import datamodel.Account;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.io.IOException;
import java.text.NumberFormat;

public class Controller {

    public Button detacctinfo;
    private Stage stage;
    private Scene scene;
    private Parent root;

    @FXML
    private Button createnewacct, Submit;

    @FXML
    private AnchorPane mainPanel;

    @FXML
    private ComboBox<Account> accountComboBox;

    @FXML
    Label acctbalField = new Label();

    private NumberFormat fmt;

public void initialize () {

    ObservableList<Account> accountlist = FXCollections.observableArrayList();
    accountlist.add(new Account("Bank of America", 10010101.32));
    accountlist.add(new Account("Prosperity Bank", 10010101.32));

    //ComboBox<Account> selectacct = new ComboBox<>();

    // Use a StringConverter to configure our ComboBox to display only the film's title
/*    accountComboBox.setConverter(new StringConverter<Account>() {
        @Override
        public String toString(Account account) {
            return account.getAccountName();
        }

        @Override
        public Account fromString(String string) {
            return accountComboBox.getItems().stream().filter(ap ->
                    ap.getAccountName().equals(string)).findFirst().orElse(null);
        }
    });*/

    // Finally, set our ComboBox's items to our sample list
    accountComboBox.setItems(accountlist);

    System.out.println(accountlist);

}

public void OnItemSelected(ActionEvent e ) throws IOException {

    root = FXMLLoader.load(getClass().getResource("AccountHome.fxml"));
    Stage window = (Stage) Submit.getScene().getWindow();
    window.setScene(new Scene(root));

    }

}

package datamodel;

public class Account {

private String accountName;
private Double accountBalance;

public Account(String accountName, Double accountBalance) {
    this.accountName = accountName;
    this.accountBalance = accountBalance;

}

public String getAccountName() {
    return accountName;
}

public void setAccountName(String accountName) {
    this.accountName = accountName;
}

public Double getAccountBalance() {
    return accountBalance;
}

public void setAccountBalance(Double accountBalance) {
    this.accountBalance = accountBalance;
}

@Override //Esto dice que cuando un variable se usa, va a dar el valor de abajo
public String toString() {
    return accountName;
}
        public String getBalance() {
        return String.valueOf(accountBalance);
}

}

Caused by: java.lang.NullPointerException: Cannot invoke "javafx.scene.control.ComboBox.setItems(javafx.collections.ObservableList)" because "this.accountComboBox" is null
at application.budget/application.budget.Controller.initialize(Controller.java:67)

Line 67 is: accountComboBox.setItems(accountlist);


来源: stackexchange

问:
How to overwrite nodes in an xml file?
I have the following XML file:

```<code><WindowEntries>
<WindowEntry>
  <Name>maduranga</Name>
  <View>TRN_UNIT</View>
  <LU>TrnUnit</LU>
  <DefaultWindowText />
  <Flags>0</Flags>
</WindowEntry>
<WindowEntry>
  <Name>tbwBrandOverView</Name>
  <View>TRN_BRAND</View>
  <LU>TrnBrand</LU>
  <DefaultWindowText />
  <Flags>0</Flags>
</WindowEntry>
<WindowEntries>
</code>```

I developed a TreeView for that xml. After user selects one WindowEntry from the Treeview for editing and after user selects one entry value in entry load some Textbox for editing. After user finishes editing, I save it. After save, the xml file look like this:

```<code><WindowEntries>
 <WindowEntry>
 <Name>maduranga</Name>
 <View>maduranga</View>
 <LU>maduranga</LU>
 <Flags>maduranga</Flags>
</WindowEntry>
<WindowEntry>
 <Name>tbwBrandOverView</Name>
 <View>TRN_BRAND</View>
 <LU>TrnBrand</LU>
 <Flags>0</Flags>
</WindowEntry>
**<WindowEntry>
 <Name>newvalue</Name>
 <View>newvalue</View>
 <LU>newvalue</LU>
 <Flags>newvalue</Flags>
</WindowEntry>**
<WindowEntries>
</code>```

but i want to overwrite "madurang" value with "newvalue".
This is the code what I use for that edit.

```<code>     XmlTextReader reader = new XmlTextReader("component.xml");
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();
            XmlNode currNode;
            XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
            try
            {
                string path3 = treeView1.SelectedNode.FullPath.ToString();
                docFrag.InnerXml = "<WindowEntry>" +
                            "<Name>" + textBox7.Text + "</Name>" +
                            "<LU>" + textBox8.Text + "</LU>" +
                            "<View>" + textBox9.Text + "</View>" +
                            "<Flags>" + textBox10.Text + "</Flags>" +

                            "<OverrideDefaultHome>" + textBox11.Text + "</OverrideDefaultHome>" +
                            "<AssociatedHomepage>" + textBox12.Text + "</AssociatedHomepage>" +
                            "</WindowEntry>";

                        currNode = doc.SelectSingleNode("Component/WindowEntries");

                        currNode.AppendChild(docFrag);

                        doc.Save("component.xml");
                       }
</code>```

答:
Linq-XML is simple and powerful.</p>

```<code>  filename = @"c:\path\sample.xml";

  XDocument doc = XDocument.Load(filename);

  var result = (from node in doc.Descendants("WindowEntry")
                         where node.Element("Name").Value == "maduranga"
                         select  node.Element("Name")).ToList();

  if(result.Count!=0)
    result[0].Value = "NewValue";

  doc.Save(filename);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to overwrite nodes in an xml file?

Body:
I have the following XML file:

<WindowEntries>
<WindowEntry>
  <Name>maduranga</Name>
  <View>TRN_UNIT</View>
  <LU>TrnUnit</LU>
  <DefaultWindowText />
  <Flags>0</Flags>
</WindowEntry>
<WindowEntry>
  <Name>tbwBrandOverView</Name>
  <View>TRN_BRAND</View>
  <LU>TrnBrand</LU>
  <DefaultWindowText />
  <Flags>0</Flags>
</WindowEntry>
<WindowEntries>

I developed a TreeView for that xml. After user selects one WindowEntry from the Treeview for editing and after user selects one entry value in entry load some Textbox for editing. After user finishes editing, I save it. After save, the xml file look like this:

<WindowEntries>
 <WindowEntry>
 <Name>maduranga</Name>
 <View>maduranga</View>
 <LU>maduranga</LU>
 <Flags>maduranga</Flags>
</WindowEntry>
<WindowEntry>
 <Name>tbwBrandOverView</Name>
 <View>TRN_BRAND</View>
 <LU>TrnBrand</LU>
 <Flags>0</Flags>
</WindowEntry>
**<WindowEntry>
 <Name>newvalue</Name>
 <View>newvalue</View>
 <LU>newvalue</LU>
 <Flags>newvalue</Flags>
</WindowEntry>**
<WindowEntries>

but i want to overwrite "madurang" value with "newvalue".
This is the code what I use for that edit.

     XmlTextReader reader = new XmlTextReader("component.xml");
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();
            XmlNode currNode;
            XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
            try
            {
                string path3 = treeView1.SelectedNode.FullPath.ToString();
                docFrag.InnerXml = "<WindowEntry>" +
                            "<Name>" + textBox7.Text + "</Name>" +
                            "<LU>" + textBox8.Text + "</LU>" +
                            "<View>" + textBox9.Text + "</View>" +
                            "<Flags>" + textBox10.Text + "</Flags>" +

                            "<OverrideDefaultHome>" + textBox11.Text + "</OverrideDefaultHome>" +
                            "<AssociatedHomepage>" + textBox12.Text + "</AssociatedHomepage>" +
                            "</WindowEntry>";

                        currNode = doc.SelectSingleNode("Component/WindowEntries");

                        currNode.AppendChild(docFrag);

                        doc.Save("component.xml");
                       }

Body:
Linq-XML is simple and powerful.

  filename = @"c:\path\sample.xml";

  XDocument doc = XDocument.Load(filename);

  var result = (from node in doc.Descendants("WindowEntry")
                         where node.Element("Name").Value == "maduranga"
                         select  node.Element("Name")).ToList();

  if(result.Count!=0)
    result[0].Value = "NewValue";

  doc.Save(filename);


问:
Failed to convert a NumPy array to a Tensor (Unsupported object type int). while implementing wide and deep network
I want to implement wide and deep neural network using keras, I am using keras official code implementation but I want to pass numpy array as a dataset  instead of  csv file.

Code:
def get_dataset_from_csv(csv_file_path, batch_size, shuffle=False):

```<code>dataset = tf.data.experimental.make_csv_dataset(
    csv_file_path,
    batch_size=batch_size,
    column_names=CSV_HEADER,
    column_defaults=COLUMN_DEFAULTS,
    label_name=TARGET_FEATURE_NAME,
    num_epochs=1,
    header=True,
    shuffle=shuffle,
)
return dataset.cache()
</code>```

used below link for code implementation: https://keras.io/examples/structured_data/wide_deep_cross_networks/

Above function is used to generate cache dataset using tensorflow function "make_csv_dataset" but I want to pass numpy array as dataset directly.
what could be the solution?

答:
Keras doesn't support int type so you need to cast them to float. Simple way is changing the type to float after you load your data as numpy array:</p>
```<code>x = x.astype('float32')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to implement wide and deep neural network using keras, I am using keras official code implementation but I want to pass numpy array as a dataset  instead of  csv file.

Code:
def get_dataset_from_csv(csv_file_path, batch_size, shuffle=False):

dataset = tf.data.experimental.make_csv_dataset(
    csv_file_path,
    batch_size=batch_size,
    column_names=CSV_HEADER,
    column_defaults=COLUMN_DEFAULTS,
    label_name=TARGET_FEATURE_NAME,
    num_epochs=1,
    header=True,
    shuffle=shuffle,
)
return dataset.cache()

used below link for code implementation: https://keras.io/examples/structured_data/wide_deep_cross_networks/

Above function is used to generate cache dataset using tensorflow function "make_csv_dataset" but I want to pass numpy array as dataset directly.
what could be the solution?

Body:
Keras doesn't support int type so you need to cast them to float. Simple way is changing the type to float after you load your data as numpy array:

x = x.astype('float32')


问:
The texture of the player does not changing
In the code I wrote, the collision is detected correctly, but only 1 enemy changes players texture. What is the reason and how can I change players texture for every enemy? The problem is between lines 56 and 64 of the code.

Screenshots :

No collision

Collision but texture isn't change

Collision and players texture is changed

My code :

```<code>#include <iostream>
#include <stdlib.h>
#include <SFML/Graphics.hpp>

using namespace sf;

int main(){

    RenderWindow window(VideoMode(500,500), "Game");
    window.setFramerateLimit(100);

    Texture playerTexture;
    playerTexture.loadFromFile("./images/player.png");
    Texture collisionPlayerTexture;
    collisionPlayerTexture.loadFromFile("./images/collision_player.png");
    Texture enemyTexture;
    enemyTexture.loadFromFile("./images/enemy.png");

    Sprite player;
    player.setTexture(playerTexture);
    player.setTextureRect(IntRect(50,50,50,50));
    player.setPosition(225,225);

    Sprite enemies[5] = {Sprite(),Sprite(),Sprite(),Sprite(),Sprite()};
    for(int i=0;i<5;i++){
        enemies[i].setTexture(enemyTexture);
        enemies[i].setTextureRect(IntRect(25,25,25,25));
        enemies[i].setPosition(rand() % 475,rand() % 475);
    }

    while(window.isOpen()){

        Event event;
        while(window.pollEvent(event)){
            switch(event.type){
                case Event::Closed:
                    window.close();
            }
        }

        if(Keyboard::isKeyPressed(Keyboard::W) || Keyboard::isKeyPressed(Keyboard::Up)){
            player.move(0.0f,-1.5f);
        }
        if(Keyboard::isKeyPressed(Keyboard::S) || Keyboard::isKeyPressed(Keyboard::Down)){
            player.move(0.0f,1.5f);
        }
        if(Keyboard::isKeyPressed(Keyboard::A) || Keyboard::isKeyPressed(Keyboard::Left)){
            player.move(-1.5f,0.0f);
        }
        if(Keyboard::isKeyPressed(Keyboard::D) || Keyboard::isKeyPressed(Keyboard::Right)){
            player.move(1.5f,0.0f);
        }

        window.clear(Color(255,255,255));

        //////////////////////////////////////////////This is where I'm talking about//////////////////////////////////////////////

        for(int i=0;i<5;i++){
            if(player.getGlobalBounds().intersects(enemies[i].getGlobalBounds())){
                std::cout << "Collision"; // This is working
                player.setTexture(collisionPlayerTexture); // But this line only works for an enemy
            } else {
                player.setTexture(playerTexture);
            }
            window.draw(enemies[i]);
        }

        //////////////////////////////////////////////This is where I'm talking about//////////////////////////////////////////////

        window.draw(player);
        window.display();
    }
    return 0;
}
</code>```

答:
In your loop

```<code>    for(int i=0;i<5;i++){
</code>```

you are iterating through all 5 enemies.

If you detect collision with the LAST one, you change the texture and get out of the loop. But if the collision was with any other enemy, the next loop iteration will revert the texture back.

Solution: you might want to break; out of the loop if a collision was detected.

Body:
In the code I wrote, the collision is detected correctly, but only 1 enemy changes players texture. What is the reason and how can I change players texture for every enemy? The problem is between lines 56 and 64 of the code.

Screenshots :

No collision

Collision but texture isn't change

Collision and players texture is changed

My code :

#include <iostream>
#include <stdlib.h>
#include <SFML/Graphics.hpp>

using namespace sf;

int main(){

    RenderWindow window(VideoMode(500,500), "Game");
    window.setFramerateLimit(100);

    Texture playerTexture;
    playerTexture.loadFromFile("./images/player.png");
    Texture collisionPlayerTexture;
    collisionPlayerTexture.loadFromFile("./images/collision_player.png");
    Texture enemyTexture;
    enemyTexture.loadFromFile("./images/enemy.png");

    Sprite player;
    player.setTexture(playerTexture);
    player.setTextureRect(IntRect(50,50,50,50));
    player.setPosition(225,225);

    Sprite enemies[5] = {Sprite(),Sprite(),Sprite(),Sprite(),Sprite()};
    for(int i=0;i<5;i++){
        enemies[i].setTexture(enemyTexture);
        enemies[i].setTextureRect(IntRect(25,25,25,25));
        enemies[i].setPosition(rand() % 475,rand() % 475);
    }

    while(window.isOpen()){

        Event event;
        while(window.pollEvent(event)){
            switch(event.type){
                case Event::Closed:
                    window.close();
            }
        }

        if(Keyboard::isKeyPressed(Keyboard::W) || Keyboard::isKeyPressed(Keyboard::Up)){
            player.move(0.0f,-1.5f);
        }
        if(Keyboard::isKeyPressed(Keyboard::S) || Keyboard::isKeyPressed(Keyboard::Down)){
            player.move(0.0f,1.5f);
        }
        if(Keyboard::isKeyPressed(Keyboard::A) || Keyboard::isKeyPressed(Keyboard::Left)){
            player.move(-1.5f,0.0f);
        }
        if(Keyboard::isKeyPressed(Keyboard::D) || Keyboard::isKeyPressed(Keyboard::Right)){
            player.move(1.5f,0.0f);
        }

        window.clear(Color(255,255,255));

        //////////////////////////////////////////////This is where I'm talking about//////////////////////////////////////////////

        for(int i=0;i<5;i++){
            if(player.getGlobalBounds().intersects(enemies[i].getGlobalBounds())){
                std::cout << "Collision"; // This is working
                player.setTexture(collisionPlayerTexture); // But this line only works for an enemy
            } else {
                player.setTexture(playerTexture);
            }
            window.draw(enemies[i]);
        }

        //////////////////////////////////////////////This is where I'm talking about//////////////////////////////////////////////

        window.draw(player);
        window.display();
    }
    return 0;
}

Body:
In your loop

    for(int i=0;i<5;i++){

you are iterating through all 5 enemies.

If you detect collision with the LAST one, you change the texture and get out of the loop. But if the collision was with any other enemy, the next loop iteration will revert the texture back.

Solution: you might want to break; out of the loop if a collision was detected.


问:
GKSession - what if I have Bluetooth and Wi-Fi turned off?
I'm working on an iPhone app that will allow for peer-to-peer connections. From what I understand, I have the choice between using GKPeerPicker or the GKSession. I don't like the idea of using the PeerPicker because I want to show a custom interface, so I decided to go with GKSession, and hey, BONUS is that it also works over Wi-Fi, whereas the Peer Picker does not.

OK, so problem is... what if the user has both Bluetooth and Wi-Fi turned off? In the Peer Picker, there is a prompt to turn Bluetooth on w/o leaving the app. GKSession doesn't have it... but woah wait a second, it appears that I can't even check to see if Bluetooth is on or not programatically!

Carpe Cocoa claims no problem, just use the Delegate's session:didFailWithError: method. But, as it explains in the comments... that doesn't seem to work anymore! And in my experience, I concur.

Is there some other way to programmatically check if Bluetooth is on? Is this something that I should be leveraging Reachability for? Or is it just a bug that Apple has yet to fix?

To be more specific, I'm creating my session like this:

```<code>GKSession *aSession = [[GKSession alloc] initWithSessionID:nil
                                                  displayName:user.displayName
                                                  sessionMode:GKSessionModePeer];

self.gkSession = aSession;
[aSession release];

self.gkSession.delegate = self;
self.gkSession.available = YES;

[self.gkSession setDataReceiveHandler:self withContext:NULL];
</code>```

The class implements the GKSessionDelegate, and I know that it's working because when I have bluetooth turned on, the delegate methods are called no problem. I've implemented them as such:

```<code>#pragma mark -
#pragma mark GKSessionDelegate methods

- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {
     if (GKPeerStateAvailable == state) {
          [session connectToPeer:peerID withTimeout:10];
     } else if (GKPeerStateConnected == state) {
          // gets user

          NSError *error = nil;
          [session sendData:user.connectionData
                      toPeers:[NSArray arrayWithObjects:peerID,nil]
                withDataMode:GKSendDataReliable error:&error];
          if (error)
               NSLog(@"%@",error);
     }
}

- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID {
     NSError *error = nil;
     [session acceptConnectionFromPeer:peerID error:&error];
     if (error)
          NSLog(@"%@",error);
}

- (void)session:(GKSession *)session connectionWithPeerFailed:(NSString *)peerID withError:(NSError *)error {
     NSLog(@"%@",error);
}

- (void)session:(GKSession *)session didFailWithError:(NSError *)error {
     NSLog(@"%@",error);
}
</code>```

None of the log statements are printed and I set breakpoints in each method, but none of them are hit when the user has both Bluetooth and Wi-Fi turned off. I was hoping that something would happen to trigger session:didFailWithError: so that I could prompt the user to turn on Bluetooth or connect to a Wi-Fi network.

答: You should use the same sessionID.

ContentLicense: CC BY-SA 2.5

Body:
I'm working on an iPhone app that will allow for peer-to-peer connections. From what I understand, I have the choice between using GKPeerPicker or the GKSession. I don't like the idea of using the PeerPicker because I want to show a custom interface, so I decided to go with GKSession, and hey, BONUS is that it also works over Wi-Fi, whereas the Peer Picker does not.

OK, so problem is... what if the user has both Bluetooth and Wi-Fi turned off? In the Peer Picker, there is a prompt to turn Bluetooth on w/o leaving the app. GKSession doesn't have it... but woah wait a second, it appears that I can't even check to see if Bluetooth is on or not programatically!

Carpe Cocoa claims no problem, just use the Delegate's session:didFailWithError: method. But, as it explains in the comments... that doesn't seem to work anymore! And in my experience, I concur.

Is there some other way to programmatically check if Bluetooth is on? Is this something that I should be leveraging Reachability for? Or is it just a bug that Apple has yet to fix?

To be more specific, I'm creating my session like this:

GKSession *aSession = [[GKSession alloc] initWithSessionID:nil
                                                  displayName:user.displayName
                                                  sessionMode:GKSessionModePeer];

self.gkSession = aSession;
[aSession release];

self.gkSession.delegate = self;
self.gkSession.available = YES;

[self.gkSession setDataReceiveHandler:self withContext:NULL];

The class implements the GKSessionDelegate, and I know that it's working because when I have bluetooth turned on, the delegate methods are called no problem. I've implemented them as such:

#pragma mark -
#pragma mark GKSessionDelegate methods

- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {
     if (GKPeerStateAvailable == state) {
          [session connectToPeer:peerID withTimeout:10];
     } else if (GKPeerStateConnected == state) {
          // gets user

          NSError *error = nil;
          [session sendData:user.connectionData
                      toPeers:[NSArray arrayWithObjects:peerID,nil]
                withDataMode:GKSendDataReliable error:&error];
          if (error)
               NSLog(@"%@",error);
     }
}

- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID {
     NSError *error = nil;
     [session acceptConnectionFromPeer:peerID error:&error];
     if (error)
          NSLog(@"%@",error);
}

- (void)session:(GKSession *)session connectionWithPeerFailed:(NSString *)peerID withError:(NSError *)error {
     NSLog(@"%@",error);
}

- (void)session:(GKSession *)session didFailWithError:(NSError *)error {
     NSLog(@"%@",error);
}

None of the log statements are printed and I set breakpoints in each method, but none of them are hit when the user has both Bluetooth and Wi-Fi turned off. I was hoping that something would happen to trigger session:didFailWithError: so that I could prompt the user to turn on Bluetooth or connect to a Wi-Fi network.

Body: You should use the same sessionID.


问:
How to use wild card character to search for s3 file using S3KeySensor in airflow
Hello I am using S3KeySensor to look for parquet files created in specific partition. As the file names are generated from spark like (part-00499-e91c1af8-4352-4de9*), what should be the bucket_key ? Below code is failing.</p>
```<code>    ex:bucket_key=f"inbound/phix/empnf/datasetdate={var_ds_date}/*.parquet"

s3_data_filechk=S3KeySensor(
         task_id='s3_data_filechk',
         bucket_name=data_bucket_name,
         bucket_key=f"inbound/phix/empnf/datasetdate={var_ds_date}/*.parquet/",
         timeout=60 * 30, # timeout in 30 minutes
         poke_interval=60 * 5 # (seconds); checking file in every five minutes
     )
</code>```

答:
The S3KeySensor has parameter wildcard_match: whether the bucket_key should be interpreted as a Unix wildcard pattern. You can use it to set the logic you wish.

Example:

```<code>sensor=S3KeySensor(
         ...
         bucket_key="*.parquet",
         wildcard_match=True
     )
</code>```

Body:
Hello I am using S3KeySensor to look for parquet files created in specific partition. As the file names are generated from spark like (part-00499-e91c1af8-4352-4de9*), what should be the bucket_key ? Below code is failing.

    ex:bucket_key=f"inbound/phix/empnf/datasetdate={var_ds_date}/*.parquet"

s3_data_filechk=S3KeySensor(
         task_id='s3_data_filechk',
         bucket_name=data_bucket_name,
         bucket_key=f"inbound/phix/empnf/datasetdate={var_ds_date}/*.parquet/",
         timeout=60 * 30, # timeout in 30 minutes
         poke_interval=60 * 5 # (seconds); checking file in every five minutes
     )

Body:
The S3KeySensor has parameter wildcard_match: whether the bucket_key should be interpreted as a Unix wildcard pattern. You can use it to set the logic you wish.

Example:

sensor=S3KeySensor(
         ...
         bucket_key="*.parquet",
         wildcard_match=True
     )


问:
What MIMEType should I use for .dat files in react dropzone?
I'm using the react Dropzone component and I need to do a conditional stylization to show if the file is accepted or rejected. It consists of changing the border color to red when the file is rejected and blue when it's accepted.  MyDropzone

I need to allow just .csv and .dat files. It worked with accept parameter as "application/vnd.ms-excel" for csv . However, I didn't find the correct MIMEType for the .dat file. I tryed the following:

application/octet-stream

zz-application/zz-winassoc-dat

application/dat

When I put just ".dat" in the accept parameter, the input restriction  works accepting just the .dat, but the conditional stylization doesn'work, because the variables isDragReject and isDragAccept take on incorrect values.

```<code>  const changeText=(isDragActive,isDragReject,isDragAccept)=>{

    return (
        <>
            <Typography sx={Styles.textBoard}>
                {(!isDragActive) && 'Drop files here or click to upload'}
                {(isDragActive && !isDragReject) && 'Drop files here'}
                {(isDragActive && isDragReject) && 'File not supported'}
            </Typography>
        </>
    )
}

<Dropzone accept={"application/vnd.ms-excel"} onDropAccepted={onUpload}>
            {({ getRootProps, getInputProps, isDragActive, isDragReject,isDragAccept }) => (
                <Box
                    {...getRootProps({
                        //loads the basic style
                        ...Styles.baseStyle,
                        //change the color in function of the file that
                        //is being dragged over the area
                        ...(!isDragActive ? Styles.defaultStyle : {}),
                        ...(isDragReject ? Styles.rejectStyle : {}),
                        ...(isDragAccept ? Styles.acceptStyle : {})
                    })}
                        >
                    <CloudUpload className='ico' sx={Styles.uploadIcon}/>
                    {changeText(isDragActive,isDragReject)}
                    <input {...getInputProps()}/>
                </Box>
            )}
        </Dropzone>
</code>```

答:
I found the problem, so I'm gonna answer. The MIMEType of the .dat that I'm using is undefined (maybe it's comon to see it). So, in the parameter accept (is desired to accept .csv and .dat) I just put the csv MIMEType and a blank one (remembering that the accept parameter receives an input like "MIMEType1,MIMEType2".

So it is as follows:

```<code><Dropzone accept={'application/vnd.ms-excel,    '} onDropAccepted={onUpload}>
</code>```

Body:
I'm using the react Dropzone component and I need to do a conditional stylization to show if the file is accepted or rejected. It consists of changing the border color to red when the file is rejected and blue when it's accepted.  MyDropzone

I need to allow just .csv and .dat files. It worked with accept parameter as "application/vnd.ms-excel" for csv . However, I didn't find the correct MIMEType for the .dat file. I tryed the following:

application/octet-stream

zz-application/zz-winassoc-dat

application/dat

When I put just ".dat" in the accept parameter, the input restriction  works accepting just the .dat, but the conditional stylization doesn'work, because the variables isDragReject and isDragAccept take on incorrect values.

  const changeText=(isDragActive,isDragReject,isDragAccept)=>{

    return (
        <>
            <Typography sx={Styles.textBoard}>
                {(!isDragActive) && 'Drop files here or click to upload'}
                {(isDragActive && !isDragReject) && 'Drop files here'}
                {(isDragActive && isDragReject) && 'File not supported'}
            </Typography>
        </>
    )
}

<Dropzone accept={"application/vnd.ms-excel"} onDropAccepted={onUpload}>
            {({ getRootProps, getInputProps, isDragActive, isDragReject,isDragAccept }) => (
                <Box
                    {...getRootProps({
                        //loads the basic style
                        ...Styles.baseStyle,
                        //change the color in function of the file that
                        //is being dragged over the area
                        ...(!isDragActive ? Styles.defaultStyle : {}),
                        ...(isDragReject ? Styles.rejectStyle : {}),
                        ...(isDragAccept ? Styles.acceptStyle : {})
                    })}
                        >
                    <CloudUpload className='ico' sx={Styles.uploadIcon}/>
                    {changeText(isDragActive,isDragReject)}
                    <input {...getInputProps()}/>
                </Box>
            )}
        </Dropzone>

Body:
I found the problem, so I'm gonna answer. The MIMEType of the .dat that I'm using is undefined (maybe it's comon to see it). So, in the parameter accept (is desired to accept .csv and .dat) I just put the csv MIMEType and a blank one (remembering that the accept parameter receives an input like "MIMEType1,MIMEType2".

So it is as follows:

<Dropzone accept={'application/vnd.ms-excel,    '} onDropAccepted={onUpload}>


问:
How can I get the coordinates of a mouseClick relative to the entire viewable document?
I need a way to find the coordinates of a mouseclick relative to the entire document. I am aware of pageX and pageY, but these values do not take in account the true entire document, or rather what I really mean is, these values do not consider the currently viewable document, AND the left over scrollable document. So while the X value is fine because this page does not scroll on the X-axis, it means that the Y value will change depending on WHERE the user is on account of the ability to scroll.

I feel like I must be missing something obvious?

答:
I think you should add to the "clientY" the value of the "window.scrollY" position in the event sender (if you use the "onmousemove" event)

I've made an example for you

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

  <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">

  <title>Test</title>

```

Body:
I think you should add to the "clientY" the value of the "window.scrollY" position in the event sender (if you use the "onmousemove" event)

I've made an example for you

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
  <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
  <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
  <title>Test</title>
<style>
    body {
      height: 100;
      width: 100%;
    }
    #mouse {
      position: fixed;
      width: 500px;
      height: 200px;
      top: 50%;
      left: 50%;
      margin-top: -100px;
      margin-left: -250px;
      font-size: 50px;
    }
</style>
</head>
<body>
  <div id="mouse"></div>
  <div id="test"></div>
</body>
<script>
    onmousemove = function(e){
      document.getElementById("mouse").innerText = e.clientX + " - " + (e.clientY + window.scrollY)  + " - " +  window.scrollY
    }

    let testDiv = document.getElementById("test");
    for (let index = 0; index < 1000; index++) {
      let tempDiv = document.createElement("div");
      tempDiv.innerText = "test" + index;
      testDiv.appendChild(tempDiv);
    }
</script>
</html>


问:
SQL Query Where Condition to find something based on date range
New to the world of SQL and struggling with something that I'm sure is pretty simple. Is it possible to query a where condition to look for a date in the future based off a date range?

Example. Anything sold between 2022-02-01 - 2022-02-05 for delivery outside of 120 days from sale date.

答:
Your query will be something like this:

```<code>SELECT
    *
FROM
    table_name
WHERE
    (2022-02-01 < date_sold < 2022-02-05)
        AND
   DATEADD(DAY,120,date_sold) < delivery_date;
</code>```

You obviously need to put in your table name and column names and there will be variations depending on the database you are using.For example you might have to write

```<code>2022-02-01 < date_sold
   AND
date_sold < 2022-02-05
</code>```

Body:
Your query will be something like this:

SELECT
    *
FROM
    table_name
WHERE
    (2022-02-01 < date_sold < 2022-02-05)
        AND
   DATEADD(DAY,120,date_sold) < delivery_date;

You obviously need to put in your table name and column names and there will be variations depending on the database you are using.For example you might have to write

2022-02-01 < date_sold
   AND
date_sold < 2022-02-05


问:
pytest skip portion of function
I have one function which does the some process and if fails then i am existing the code using sys.exit(myfun()) but when i am testing using pytest i dont want to execute function myfun() inside sys.exit(). is there anyway in pytest it can be possible skip myfun()?

mypyfile.py

```<code>def process():
    # do some logic
    if failed:
       sys.exit(myfun()) # this i dont want to execute if i test via my pytest

def myfun():
    print("failed")
</code>```

test_mypyfile.py

```<code>import pytest
import test_mypyfile

def test_process():
     test_mypyfile.process()

</code>```

答:
You could mock myfunc in your test. This way the function is not called in the test process. I'll change a bit you're example so that it make more sense to mock (and you'll be able to see the difference):

# mypyfile.py
from time import sleep

def process():
    # do some logic
    if failed:
       sys.exit(myfunc)

def myfun():
    sleep(4000)
```
<pre class="lang-py prettyprint-override"><code># test_mypyfile.py

import mock
import mypyfile

def test_process():

    mock.patch('mypyfile.myfunc')
    test_mypyfile.process()
</code>```

Here myfunc will be called but you won't wait the 4000s.

Title: pytest skip portion of function

Body:
I have one function which does the some process and if fails then i am existing the code using sys.exit(myfun()) but when i am testing using pytest i dont want to execute function myfun() inside sys.exit(). is there anyway in pytest it can be possible skip myfun()?

mypyfile.py

def process():
    # do some logic
    if failed:
       sys.exit(myfun()) # this i dont want to execute if i test via my pytest

def myfun():
    print("failed")

test_mypyfile.py

import pytest
import test_mypyfile

def test_process():
     test_mypyfile.process()

Body:
You could mock myfunc in your test. This way the function is not called in the test process. I'll change a bit you're example so that it make more sense to mock (and you'll be able to see the difference):

# mypyfile.py
from time import sleep

def process():
    # do some logic
    if failed:
       sys.exit(myfunc)

def myfun():
    sleep(4000)

# test_mypyfile.py

import mock
import mypyfile

def test_process():

    mock.patch('mypyfile.myfunc')
    test_mypyfile.process()

Here myfunc will be called but you won't wait the 4000s.


问:
Svelte: Pass and bind data to child component in each loop
I am heavily confused about passing props to a component within a loop in Svelte. The behavior I expected of the code snippet below is that a change in the store variable files triggers re-rendering of the content which works flawlessly for the divs classes and {file}: {is_open}. However, the child component Icon does not receive the updates of the is_open variable. This leads to a weird situation where {file}: {is_open} renders as filename: true in this component while the child component Icon would display filename: false instead.

```<code>{#each Object.entries($files) as [file, is_open], i}
<div class:open={is_open} class:closed={!is_open}>

    <div on:click={() => openFile(file)}>
        {file}: {is_open}
    </div>

    <div on:click={() => closeFile(file)}>
        <Icon bind:open={is_open} />
    </div>

</div>
{/each}
</code>```

Searching for a solution for this issue I stumbled upon
this thread which indicates that this is indeed the expected behavior in this case. But how can I make this work then? In stark contrast to my overall experience with Svelte, I find this extremely counterintuitive.

EDIT:

Turns out I do not directly use is_open in the child component but store the value in another variable without $: notation, hence this variable is not recomputed. My bad, problem solved.

答:
what you are looking for is a keyed each block, this will make sure that the divs (the block within the each statement) will be mapped correctly to the right file state.

you can also check the official svelte tutorial about keyed each
in your case

{#each Object.entries($files) as [file, is_open], i (file)}

 openFile(file)}>
        {file}: {is_open}

 closeFile(file)}>
        <Icon bind:open={is_open} />

{/each}
```

Body:
I am heavily confused about passing props to a component within a loop in Svelte. The behavior I expected of the code snippet below is that a change in the store variable files triggers re-rendering of the content which works flawlessly for the divs classes and {file}: {is_open}. However, the child component Icon does not receive the updates of the is_open variable. This leads to a weird situation where {file}: {is_open} renders as filename: true in this component while the child component Icon would display filename: false instead.

{#each Object.entries($files) as [file, is_open], i}

 openFile(file)}>
        {file}: {is_open}

 closeFile(file)}>
        <Icon bind:open={is_open} />

{/each}

Searching for a solution for this issue I stumbled upon
this thread which indicates that this is indeed the expected behavior in this case. But how can I make this work then? In stark contrast to my overall experience with Svelte, I find this extremely counterintuitive.

EDIT:

Turns out I do not directly use is_open in the child component but store the value in another variable without $: notation, hence this variable is not recomputed. My bad, problem solved.

Body:
what you are looking for is a keyed each block, this will make sure that the divs (the block within the each statement) will be mapped correctly to the right file state.

you can also check the official svelte tutorial about keyed each
in your case

{#each Object.entries($files) as [file, is_open], i (file)} <!--added (file)-->
<div class:open={is_open} class:closed={!is_open}>

    <div on:click={() => openFile(file)}>
        {file}: {is_open}
    </div>

    <div on:click={() => closeFile(file)}>
        <Icon bind:open={is_open} />
    </div>

</div>
{/each}


问:
counting row values with different ids in multidimensional array
I know there are a lot of topics about this, but just couldn't find any that would actually help me solve the problem.
Ok so i am having a problem with counting rows and values in multidimensional array (imported via .csv)

I am trying to achieve something like...

```<code>Array ( [0] => Array ( [0] => 1 [1] => 6278,31 [2] => 4)
        [1] => Array ( [0] => 2 [1] => 2,0 [2] => 2)
        [2] => Array ( [0] => 3 [1] => 3,01 [2] => 3)
         )
</code>```

where [0] would be buyer id, 1 is total number of buys and [2] total cost.

My current code:

```<code>if(($s_open = fopen("sales.csv", "r")) !== FALSE)
    {
        $s_count = count(file("sales.csv"));
        while(($sales = fgetcsv($s_open, 100, ";")) !== FALSE)
        {
            ...
        }
        fclose($s_open);
    }
</code>```

Thanks in advance.

答:
Using this mock data in.csv:

```<code>id, buyer_id, amount
1, 1, 100.55
2, 1, 500.1
3, 2, 50.55
4, 3, 1.0
</code>```

I wrote the following PHP to parse it into a nicely formatted array (if you don't want to have named keys, you can just remove the header logic):

<?php

// Each line into an array
$csv = file(__DIR__ . DIRECTORY_SEPARATOR . 'in.csv');

// First line is the header
$header = str_getcsv(array_shift($csv));

// When the CSV header is `id, buyer_id, amount`, remove the whitespace
$header = array_map(function ($item) {
    return trim($item);
}, $header);

// Get the CSV data as an array of arrays
$out = array_map(function ($line) use ($header) {
    $data = str_getcsv($line);
    return array_combine($header, $data);
}, $csv);

print_r($out);
```
<p>Which prints the following to your screen:</p>
```Array
(
    [0] => Array
        (
            [id] => 1
            [buyer_id] =>  1
            [amount] =>  100.55
        )

    [1] => Array
        (
            [id] => 2
            [buyer_id] =>  1
            [amount] =>  500.1
        )

    [2] => Array
        (
            [id] => 3
            [buyer_id] =>  2
            [amount] =>  50.55
        )

    [3] => Array
        (
            [id] => 4
            [buyer_id] =>  3
            [amount] =>  1.0
        )

)
```

Body:
I know there are a lot of topics about this, but just couldn't find any that would actually help me solve the problem.
Ok so i am having a problem with counting rows and values in multidimensional array (imported via .csv)

I am trying to achieve something like...

Array ( [0] => Array ( [0] => 1 [1] => 6278,31 [2] => 4)
        [1] => Array ( [0] => 2 [1] => 2,0 [2] => 2)
        [2] => Array ( [0] => 3 [1] => 3,01 [2] => 3)
         )

where [0] would be buyer id, 1 is total number of buys and [2] total cost.

My current code:

if(($s_open = fopen("sales.csv", "r")) !== FALSE)
    {
        $s_count = count(file("sales.csv"));
        while(($sales = fgetcsv($s_open, 100, ";")) !== FALSE)
        {
            ...
        }
        fclose($s_open);
    }

Thanks in advance.

Body:
Using this mock data in.csv:

id, buyer_id, amount
1, 1, 100.55
2, 1, 500.1
3, 2, 50.55
4, 3, 1.0

I wrote the following PHP to parse it into a nicely formatted array (if you don't want to have named keys, you can just remove the header logic):

<?php

// Each line into an array
$csv = file(__DIR__ . DIRECTORY_SEPARATOR . 'in.csv');

// First line is the header
$header = str_getcsv(array_shift($csv));

// When the CSV header is `id, buyer_id, amount`, remove the whitespace
$header = array_map(function ($item) {
    return trim($item);
}, $header);

// Get the CSV data as an array of arrays
$out = array_map(function ($line) use ($header) {
    $data = str_getcsv($line);
    return array_combine($header, $data);
}, $csv);

print_r($out);

Which prints the following to your screen:

Array
(
    [0] => Array
        (
            [id] => 1
            [buyer_id] =>  1
            [amount] =>  100.55
        )

    [1] => Array
        (
            [id] => 2
            [buyer_id] =>  1
            [amount] =>  500.1
        )

    [2] => Array
        (
            [id] => 3
            [buyer_id] =>  2
            [amount] =>  50.55
        )

    [3] => Array
        (
            [id] => 4
            [buyer_id] =>  3
            [amount] =>  1.0
        )

)


问:
Private App publishing to Google Play store
We have an organization account. I would like to upload a test apk and research what needs to be done to create a private app that is only for 1 or more organizations.

We may have multiple versions of the same app. How do we go about that.

There is no one to talk at with Google. It really is not helpful. I am trying to determinate the best approach for us and our app.

There are these different accounts I don't know which one is the right one.

1- developer
2- organization
3- android enterprise.

The app we are making is not for public use. It is only used for businesses. I am sure it is not the first time someone is doing this.

I wish there was some guidance as how you approach this.

If  found this: https://support.google.com/a/answer/2494992?hl=en

what is the difference between managed play services, admin console, google play console?

答:
If you choose to use the Google Play Store to distribute an app for a closed group of users, then using Android Enterprise and "managed Google Play" is the only official way:

Manage private apps

Alternatively, you can use other providers like Visual Studio App center to distribute your apps. But all alternatives require your users to enable APK installations from unknown sources.


问:
Faceted search does not correctly sort data with Š character
I have an Azure Search index containing some random car make data. One of those data items is for Skoda, but it happens to start with a 'Š'.

When I experimented with querying that data as a faceted search, I wanted the makes ordered. Here's my prototpye code for doing that:

```<code>var queryResults = searchIndexClient.Documents
    .Search(
        string.Empty,
        new SearchParameters
        {
            Facets = new List<string>
            {
                "make,count:1000,sort:value"
            },
            Top = 0
    });
</code>```

In the returned data, the makes are indeed ordered correctly, however 'Škoda' appears at the bottom of the list. So I'm guessing I need to do something in order to get Azure Search to deal with that unicode character when it's sorting, but I have no idea what I need to do.

EDIT:

I used Postman to query the serch index, using the same faceted search params as mentioned above:

docs?$select=make&facet=make,count:1000,sort:value

Here is a trimmed subset of the JSON that was returned, which shows škoda appearing at the bottom. Note that in our test data we also have skoda in the list which is correct - both appear in the source index data.

```<code>{
  "@search.facets": {
    "make@odata.type": "#Collection(Microsoft.Azure.Search.V2015_02_28.QueryResultFacet)",
    "make": [
      {
        "count": 178,
        "value": "rover"
      },
      {
        "count": 1,
        "value": "rover / austin"
      },
      {
        "count": 1,
        "value": "rover mg"
      },
      {
        "count": 529,
        "value": "saab"
      },
      {
        "count": 3835,
        "value": "seat"
      },
      {
        "count": 3851,
        "value": "skoda"
      },
      {
        "count": 817,
        "value": "smart"
      },
      {
        "count": 12934,
        "value": "volkswagen"
      },
      {
        "count": 3922,
        "value": "volvo"
      },
      {
        "count": 1,
        "value": "vw scirocco gti"
      },
      {
        "count": 1,
        "value": "w67 6olf"
      },
      {
        "count": 3,
        "value": "westfield"
      },
      {
        "count": 2,
        "value": "wiesmann"
      },
      {
        "count": 3,
        "value": "wolseley"
      },
      {
        "count": 1,
        "value": "zbmw"
      },
      {
        "count": 5,
        "value": "škoda"
      }
    ]
  }
}
</code>```

答:
Please check out the Text normalization for case-insensitive filtering, faceting and sorting feature that's in Preview.

You can update your index to use this "normalizer" feature for the fields in which you'd like case-insensitive faceting operations. You don't need to preprocess the facet values anymore.

The "standard" normalizer is pre-defined and will include lowercasing and ascii-folding (removing accents). If you'd like other filters to be applied, please look at predefined and custom normalizers

Body:
I have an Azure Search index containing some random car make data. One of those data items is for Skoda, but it happens to start with a 'Š'.

When I experimented with querying that data as a faceted search, I wanted the makes ordered. Here's my prototpye code for doing that:

var queryResults = searchIndexClient.Documents
    .Search(
        string.Empty,
        new SearchParameters
        {
            Facets = new List<string>
            {
                "make,count:1000,sort:value"
            },
            Top = 0
    });

In the returned data, the makes are indeed ordered correctly, however 'Škoda' appears at the bottom of the list. So I'm guessing I need to do something in order to get Azure Search to deal with that unicode character when it's sorting, but I have no idea what I need to do.

EDIT:

I used Postman to query the serch index, using the same faceted search params as mentioned above:

docs?$select=make&facet=make,count:1000,sort:value

Here is a trimmed subset of the JSON that was returned, which shows škoda appearing at the bottom. Note that in our test data we also have skoda in the list which is correct - both appear in the source index data.

{
  "@search.facets": {
    "make@odata.type": "#Collection(Microsoft.Azure.Search.V2015_02_28.QueryResultFacet)",
    "make": [
      {
        "count": 178,
        "value": "rover"
      },
      {
        "count": 1,
        "value": "rover / austin"
      },
      {
        "count": 1,
        "value": "rover mg"
      },
      {
        "count": 529,
        "value": "saab"
      },
      {
        "count": 3835,
        "value": "seat"
      },
      {
        "count": 3851,
        "value": "skoda"
      },
      {
        "count": 817,
        "value": "smart"
      },
      {
        "count": 12934,
        "value": "volkswagen"
      },
      {
        "count": 3922,
        "value": "volvo"
      },
      {
        "count": 1,
        "value": "vw scirocco gti"
      },
      {
        "count": 1,
        "value": "w67 6olf"
      },
      {
        "count": 3,
        "value": "westfield"
      },
      {
        "count": 2,
        "value": "wiesmann"
      },
      {
        "count": 3,
        "value": "wolseley"
      },
      {
        "count": 1,
        "value": "zbmw"
      },
      {
        "count": 5,
        "value": "škoda"
      }
    ]
  }
}


问:
How can I remove duplicate rows from a data frame when the data is the same, but in a different order in R?
I have the following data frame:

df <- data.frame(node1=c("a","b", "c","d"), node2=c("b","a","f","g"),value=c(2,2,5,7))

I want to remove rows where node1 and node2 contain the same letters (Regardless of order) and same value so the resulting df should look like:

df <- data.frame(node1=c("a","c","d"), node2=c("b","f","g"), value=c(2,5,7))

Please help, thank you.

答:
Here is another option using dplyr and textshape packages.

Packages

```<code>library(dplyr)
library(textshape)
</code>```

First, create two new variables that paste "node1" and "value," and "node2" and "value".

Then, use unique_pairs() to find the distinct combinations between the new columns you created, regardless of the order.

Delete the unnecessary columns.

Solution

```<code>df %>%
  mutate(nv1 = paste0(node1, value),
         nv2 = paste0(node2, value)) %>%
  unique_pairs("nv1", "nv2") %>%
  select(-nv1, -nv2)
</code>```

Output

```<code>   node1 node2 value
 1     a     b     2
 3     c     f     5
 4     d     g     7
</code>```

ps: "nv1" and "nv2" stand for "new value based on node1" and "new value based on node2." It could be whatever.

Body:
Here is another option using dplyr and textshape packages.

Packages

library(dplyr)
library(textshape)

First, create two new variables that paste "node1" and "value," and "node2" and "value".

Then, use unique_pairs() to find the distinct combinations between the new columns you created, regardless of the order.

Delete the unnecessary columns.

Solution

df %>%
  mutate(nv1 = paste0(node1, value),
         nv2 = paste0(node2, value)) %>%
  unique_pairs("nv1", "nv2") %>%
  select(-nv1, -nv2)

Output

   node1 node2 value
 1     a     b     2
 3     c     f     5
 4     d     g     7

ps: "nv1" and "nv2" stand for "new value based on node1" and "new value based on node2." It could be whatever.


问:
Overriding jQuery Dialog method
I am trying to override close method of Jquery Dialog method.

Code :

```<code>jQuery.Dialog.close = function() {
    alert('my close');
}
</code>```

But its not working. Please help.

答:
There is an event called beforeClose which would allow you to do what you want, I think. When it fires, you can hide the dialog, then return false, which would prevent the dialog from actually closing.

```<code>$( ".selector" ).dialog({
   beforeClose: function(event, ui) {
       $(this).hide();
       return false;
   }
});
</code>```

Reference: http://jqueryui.com/demos/dialog/ under the Events tab below the example

Title: Overriding jQuery Dialog method

Body:
I am trying to override close method of Jquery Dialog method.

Code :

jQuery.Dialog.close = function() {
    alert('my close');
}

But its not working. Please help.

Body:
There is an event called beforeClose which would allow you to do what you want, I think. When it fires, you can hide the dialog, then return false, which would prevent the dialog from actually closing.

$( ".selector" ).dialog({
   beforeClose: function(event, ui) {
       $(this).hide();
       return false;
   }
});

Reference: http://jqueryui.com/demos/dialog/ under the Events tab below the example


问:
Error sh: 1: cross-env: Permission denied on new Kubuntu 18 os
In laravel 5.8 app I suffer error:

```<code>sh: 1: cross-env: Permission denied
</code>```

on command

```<code>npm run watch-poll
</code>```

That happed after I installed ubuntu 18.04 and composer/nodejs/nmp as:

```<code>$ uname -a
Linux serge 4.15.0-20-generic #21-Ubuntu SMP Tue Apr 24 06:16:15 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
$ composer --version
Composer 1.6.3 2018-01-31 16:28:17
$ nodejs --version
v10.16.1
$ npm --version
6.9.0
</code>```

I mannully removed directory node_modules and run :

```<code>$ npm install

> node-sass@4.12.0 install /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/node-sass
> node scripts/install.js

Cached binary found at /home/serge/.npm/node-sass/4.12.0/linux-x64-64_binding.node

> puppeteer@1.19.0 install /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/puppeteer
> node install.js

Downloading Chromium r674921 - 112.6 Mb [====================] 100% 0.0s
Chromium downloaded to /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/puppeteer/.local-chromium/linux-674921

> core-js-pure@3.1.4 postinstall /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/core-js-pure
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

> node-sass@4.12.0 postinstall /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/node-sass
> node scripts/build.js

Binary found at /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/node-sass/vendor/linux-x64-64/binding.node
Testing binary
Binary is fine
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 1192 packages from 569 contributors and audited 15586 packages in 32.601s
found 0 vulnerabilities
serge@serge:/mnt/_work_sdb8/wwwroot/lar/votes$ npm run watch-poll

> @ watch-poll /mnt/_work_sdb8/wwwroot/lar/votes
> npm run watch -- --watch-poll

> @ watch /mnt/_work_sdb8/wwwroot/lar/votes
> npm run development -- --watch "--watch-poll"

> @ development /mnt/_work_sdb8/wwwroot/lar/votes
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"

sh: 1: cross-env: Permission denied
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/serge/.npm/_logs/2019-08-06T14_56_10_670Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ watch: `npm run development -- --watch "--watch-poll"`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/serge/.npm/_logs/2019-08-06T14_56_10_688Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ watch-poll: `npm run watch -- --watch-poll`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ watch-poll script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/serge/.npm/_logs/2019-08-06T14_56_10_709Z-debug.log
</code>```

Mentioned files :

```<code>2019-08-06T14_56_10_670Z-debug.log:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node',
1 verbose cli   '/usr/bin/npm',
1 verbose cli   'run',
1 verbose cli   'development',
1 verbose cli   '--',
1 verbose cli   '--watch',
1 verbose cli   '--watch-poll' ]
2 info using npm@6.9.0
3 info using node@v10.16.1
4 verbose run-script [ 'predevelopment', 'development', 'postdevelopment' ]
5 info lifecycle @~predevelopment: @
6 info lifecycle @~development: @
7 verbose lifecycle @~development: unsafe-perm in lifecycle true
8 verbose lifecycle @~development: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle @~development: CWD: /mnt/_work_sdb8/wwwroot/lar/votes
10 silly lifecycle @~development: Args: [ '-c',
10 silly lifecycle   'cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"' ]
11 silly lifecycle @~development: Returned: code: 126  signal: null
12 info lifecycle @~development: Failed to exec development script
13 verbose stack Error: @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid @
15 verbose cwd /mnt/_work_sdb8/wwwroot/lar/votes
16 verbose Linux 4.15.0-20-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "development" "--" "--watch" "--watch-poll"
18 verbose node v10.16.1
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 126
22 error @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"`
22 error Exit status 126
23 error Failed at the @ development script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]
</code>```

2019-08-06T14_56_10_688Z-debug.log :

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node',
1 verbose cli   '/usr/bin/npm',
1 verbose cli   'run',
1 verbose cli   'watch',
1 verbose cli   '--',
1 verbose cli   '--watch-poll' ]
2 info using npm@6.9.0
3 info using node@v10.16.1
4 verbose run-script [ 'prewatch', 'watch', 'postwatch' ]
5 info lifecycle @~prewatch: @
6 info lifecycle @~watch: @
7 verbose lifecycle @~watch: unsafe-perm in lifecycle true
8 verbose lifecycle @~watch: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle @~watch: CWD: /mnt/_work_sdb8/wwwroot/lar/votes
10 silly lifecycle @~watch: Args: [ '-c', 'npm run development -- --watch "--watch-poll"' ]
11 silly lifecycle @~watch: Returned: code: 126  signal: null
12 info lifecycle @~watch: Failed to exec watch script
13 verbose stack Error: @ watch: `npm run development -- --watch "--watch-poll"`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid @
15 verbose cwd /mnt/_work_sdb8/wwwroot/lar/votes
16 verbose Linux 4.15.0-20-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "watch" "--" "--watch-poll"
18 verbose node v10.16.1
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 126
22 error @ watch: `npm run development -- --watch "--watch-poll"`
22 error Exit status 126
23 error Failed at the @ watch script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]
</code>```

2019-08-06T14_56_10_709Z-debug.log:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'watch-poll' ]
2 info using npm@6.9.0
3 info using node@v10.16.1
4 verbose run-script [ 'prewatch-poll', 'watch-poll', 'postwatch-poll' ]
5 info lifecycle @~prewatch-poll: @
6 info lifecycle @~watch-poll: @
7 verbose lifecycle @~watch-poll: unsafe-perm in lifecycle true
8 verbose lifecycle @~watch-poll: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle @~watch-poll: CWD: /mnt/_work_sdb8/wwwroot/lar/votes
10 silly lifecycle @~watch-poll: Args: [ '-c', 'npm run watch -- --watch-poll' ]
11 silly lifecycle @~watch-poll: Returned: code: 126  signal: null
12 info lifecycle @~watch-poll: Failed to exec watch-poll script
13 verbose stack Error: @ watch-poll: `npm run watch -- --watch-poll`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid @
15 verbose cwd /mnt/_work_sdb8/wwwroot/lar/votes
16 verbose Linux 4.15.0-20-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "watch-poll"
18 verbose node v10.16.1
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 126
22 error @ watch-poll: `npm run watch -- --watch-poll`
22 error Exit status 126
23 error Failed at the @ watch-poll script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]
</code>```

package.json:

```<code>{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.19.0",
        "bootstrap": "^4.3.1",
        "cross-env": "^5.1",
        "laravel-mix": "^4.0.16",
        "lodash": "^4.17.11",
        "popper.js": "^1.14.6",
        "vue": "^2.5.7"
    },
    "dependencies": {
        "bootstrap-colorpicker": "^3.1.2",
        "datatables.net-bs": "^1.10.19",
        "font-awesome": "^4.7.0",
        "jquery": "^3.4.1",
        "jquery-confirm": "^3.3.2",
        "laravel-echo": "^1.5.2",
        "mustache": "^2.3.0",
        "node-sass": "^4.12.0",
        "puppeteer": "^1.19.0",
        "resolve-url-loader": "^2.3.1",
        "sass-loader": "^7.1.0",
        "vue-template-compiler": "^2.6.10"
    }
}
</code>```

Googling for decision I found sh: 1: cross-env: Permission denied on laravel mix with decision :

Ok I figure out the problem, the storage where the project is saved is
  auto-mounted and it have no execution permission.

easily in /etc/fstab file i added exec in the mount option, like this:

auto,user,exec,utf8,uid=1000,gid=1000,rw 0 0

so I modified this partition in /etc/fstab :

```<code>UUID=72209A012099CD0B   /mnt/Media_sda8 ntfs-3g exec,uid=1000,gid=1000,dmask=022,fmask=133 rw 0 0
</code>```

and restarting the OS. I have the same problem.
Has line above correct syntax?

On prior kubuntu 18.4 installation it worked ok.

How to fix it?

答:
You need to run the following commands.

rm -rf node_modules

rm package-lock.json

npm cache clear --force

npm install

Body:
In laravel 5.8 app I suffer error:

sh: 1: cross-env: Permission denied

on command

npm run watch-poll

That happed after I installed ubuntu 18.04 and composer/nodejs/nmp as:

$ uname -a
Linux serge 4.15.0-20-generic #21-Ubuntu SMP Tue Apr 24 06:16:15 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
$ composer --version
Composer 1.6.3 2018-01-31 16:28:17
$ nodejs --version
v10.16.1
$ npm --version
6.9.0

I mannully removed directory node_modules and run :

$ npm install

> node-sass@4.12.0 install /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/node-sass
> node scripts/install.js

Cached binary found at /home/serge/.npm/node-sass/4.12.0/linux-x64-64_binding.node

> puppeteer@1.19.0 install /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/puppeteer
> node install.js

Downloading Chromium r674921 - 112.6 Mb [====================] 100% 0.0s
Chromium downloaded to /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/puppeteer/.local-chromium/linux-674921

> core-js-pure@3.1.4 postinstall /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/core-js-pure
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

> node-sass@4.12.0 postinstall /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/node-sass
> node scripts/build.js

Binary found at /mnt/_work_sdb8/wwwroot/lar/votes/node_modules/node-sass/vendor/linux-x64-64/binding.node
Testing binary
Binary is fine
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 1192 packages from 569 contributors and audited 15586 packages in 32.601s
found 0 vulnerabilities
serge@serge:/mnt/_work_sdb8/wwwroot/lar/votes$ npm run watch-poll

> @ watch-poll /mnt/_work_sdb8/wwwroot/lar/votes
> npm run watch -- --watch-poll

> @ watch /mnt/_work_sdb8/wwwroot/lar/votes
> npm run development -- --watch "--watch-poll"

> @ development /mnt/_work_sdb8/wwwroot/lar/votes
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"

sh: 1: cross-env: Permission denied
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/serge/.npm/_logs/2019-08-06T14_56_10_670Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ watch: `npm run development -- --watch "--watch-poll"`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/serge/.npm/_logs/2019-08-06T14_56_10_688Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ watch-poll: `npm run watch -- --watch-poll`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ watch-poll script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/serge/.npm/_logs/2019-08-06T14_56_10_709Z-debug.log

Mentioned files :

2019-08-06T14_56_10_670Z-debug.log:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node',
1 verbose cli   '/usr/bin/npm',
1 verbose cli   'run',
1 verbose cli   'development',
1 verbose cli   '--',
1 verbose cli   '--watch',
1 verbose cli   '--watch-poll' ]
2 info using npm@6.9.0
3 info using node@v10.16.1
4 verbose run-script [ 'predevelopment', 'development', 'postdevelopment' ]
5 info lifecycle @~predevelopment: @
6 info lifecycle @~development: @
7 verbose lifecycle @~development: unsafe-perm in lifecycle true
8 verbose lifecycle @~development: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle @~development: CWD: /mnt/_work_sdb8/wwwroot/lar/votes
10 silly lifecycle @~development: Args: [ '-c',
10 silly lifecycle   'cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"' ]
11 silly lifecycle @~development: Returned: code: 126  signal: null
12 info lifecycle @~development: Failed to exec development script
13 verbose stack Error: @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid @
15 verbose cwd /mnt/_work_sdb8/wwwroot/lar/votes
16 verbose Linux 4.15.0-20-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "development" "--" "--watch" "--watch-poll"
18 verbose node v10.16.1
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 126
22 error @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch" "--watch-poll"`
22 error Exit status 126
23 error Failed at the @ development script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]

2019-08-06T14_56_10_688Z-debug.log :

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node',
1 verbose cli   '/usr/bin/npm',
1 verbose cli   'run',
1 verbose cli   'watch',
1 verbose cli   '--',
1 verbose cli   '--watch-poll' ]
2 info using npm@6.9.0
3 info using node@v10.16.1
4 verbose run-script [ 'prewatch', 'watch', 'postwatch' ]
5 info lifecycle @~prewatch: @
6 info lifecycle @~watch: @
7 verbose lifecycle @~watch: unsafe-perm in lifecycle true
8 verbose lifecycle @~watch: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle @~watch: CWD: /mnt/_work_sdb8/wwwroot/lar/votes
10 silly lifecycle @~watch: Args: [ '-c', 'npm run development -- --watch "--watch-poll"' ]
11 silly lifecycle @~watch: Returned: code: 126  signal: null
12 info lifecycle @~watch: Failed to exec watch script
13 verbose stack Error: @ watch: `npm run development -- --watch "--watch-poll"`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid @
15 verbose cwd /mnt/_work_sdb8/wwwroot/lar/votes
16 verbose Linux 4.15.0-20-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "watch" "--" "--watch-poll"
18 verbose node v10.16.1
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 126
22 error @ watch: `npm run development -- --watch "--watch-poll"`
22 error Exit status 126
23 error Failed at the @ watch script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]

2019-08-06T14_56_10_709Z-debug.log:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'watch-poll' ]
2 info using npm@6.9.0
3 info using node@v10.16.1
4 verbose run-script [ 'prewatch-poll', 'watch-poll', 'postwatch-poll' ]
5 info lifecycle @~prewatch-poll: @
6 info lifecycle @~watch-poll: @
7 verbose lifecycle @~watch-poll: unsafe-perm in lifecycle true
8 verbose lifecycle @~watch-poll: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/mnt/_work_sdb8/wwwroot/lar/votes/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle @~watch-poll: CWD: /mnt/_work_sdb8/wwwroot/lar/votes
10 silly lifecycle @~watch-poll: Args: [ '-c', 'npm run watch -- --watch-poll' ]
11 silly lifecycle @~watch-poll: Returned: code: 126  signal: null
12 info lifecycle @~watch-poll: Failed to exec watch-poll script
13 verbose stack Error: @ watch-poll: `npm run watch -- --watch-poll`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid @
15 verbose cwd /mnt/_work_sdb8/wwwroot/lar/votes
16 verbose Linux 4.15.0-20-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "watch-poll"
18 verbose node v10.16.1
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 126
22 error @ watch-poll: `npm run watch -- --watch-poll`
22 error Exit status 126
23 error Failed at the @ watch-poll script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]

package.json:

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.19.0",
        "bootstrap": "^4.3.1",
        "cross-env": "^5.1",
        "laravel-mix": "^4.0.16",
        "lodash": "^4.17.11",
        "popper.js": "^1.14.6",
        "vue": "^2.5.7"
    },
    "dependencies": {
        "bootstrap-colorpicker": "^3.1.2",
        "datatables.net-bs": "^1.10.19",
        "font-awesome": "^4.7.0",
        "jquery": "^3.4.1",
        "jquery-confirm": "^3.3.2",
        "laravel-echo": "^1.5.2",
        "mustache": "^2.3.0",
        "node-sass": "^4.12.0",
        "puppeteer": "^1.19.0",
        "resolve-url-loader": "^2.3.1",
        "sass-loader": "^7.1.0",
        "vue-template-compiler": "^2.6.10"
    }
}

Googling for decision I found sh: 1: cross-env: Permission denied on laravel mix with decision :

Ok I figure out the problem, the storage where the project is saved is
  auto-mounted and it have no execution permission.

easily in /etc/fstab file i added exec in the mount option, like this:

auto,user,exec,utf8,uid=1000,gid=1000,rw 0 0

so I modified this partition in /etc/fstab :

UUID=72209A012099CD0B   /mnt/Media_sda8 ntfs-3g exec,uid=1000,gid=1000,dmask=022,fmask=133 rw 0 0

and restarting the OS. I have the same problem.
Has line above correct syntax?

On prior kubuntu 18.4 installation it worked ok.

How to fix it?


问:
Accessibility Service crashes and cannot restart
I am testing this tutorial implementing an Accessibility Service to catch some text on a USSD menu.

It works well the first time I compile and launch the app using Android Studio in debugging mode:

I can see this line in the debugger:

```<code>Log.d(TAG, "onServiceConnected");
</code>```

And right after I call a USSD menu I can see the content of the response message in the debugger as expected.

However if I disconnect the phone and just after try again the same app without any modification, the Accessibility Service does not seem to work or even to launch, as I cannot even see this Log.d line in the debugger

```<code>Log.d(TAG, "onServiceConnected");
</code>```

I have tried the following unit tests:

1. If I try to deinstall the app and recompile again, it still does not work.

2. If I deinstall the app, reboot the phone, and recompile again, it works again until the next time I unplug and plug again the USB cable to run a new debug from Android Studio.

3. If I just rename the Accessibility Service using the refactor option of Android Studio (adding a 2 after the name for instance), it works again until the next time I unplug and plug again the USB cable to run a new debug from Android Studio.

It seems the Accessibility Service gets stuck or crashes somewhere when I unplug the USB cable and the app is unable to restart it the next time. I can also see the following error messages in the console which makes me think this is the problem:

```<code>((latest content captured from the USSD popup))
--- the USB cable is unplugged and plugged again ---
03-22 21:43:04.931 5774-5774/com.myapp D/UssdCatcher3: onAccessibilityEvent
03-22 21:43:04.932 5774-5774/com.myapp D/UssdCatcher3: com.myapp.MainActivity
03-22 21:43:12.023 845-1950/? W/ActivityManager: Scheduling restart of crashed service com.myapp/.UssdCatcher3 in 1000ms
03-22 21:43:13.033 845-858/? I/ActivityManager: Start proc 10243:com.myapp/u0a54 for service com.myapp/.UssdCatcher3
03-22 21:43:16.488 845-858/? W/ActivityManager: Scheduling restart of crashed service com.myapp/.UssdCatcher3 in 1000ms
03-22 21:43:16.490 845-858/? I/ActivityManager:   Force stopping service ServiceRecord{cb2cd91 u0 com.myapp/.UssdCatcher3}
03-22 21:43:55.225 10882-10882/? W/dex2oat: Compilation of java.lang.Object com.myapp.UssdCatcher3.access$super(com.myapp.UssdCatcher3, java.lang.String, java.lang.Object[]) took 109.013ms
</code>```

This is very weird, any idea on why this is happening?

Thanks a lot for the suggestions!

答: I too have the same problem on my application, my solution is to invite the user to restart his phone when my application fails to establish communication with the accessibility service.</p>

Body:
I am testing this tutorial implementing an Accessibility Service to catch some text on a USSD menu.

It works well the first time I compile and launch the app using Android Studio in debugging mode:

I can see this line in the debugger:

Log.d(TAG, "onServiceConnected");

And right after I call a USSD menu I can see the content of the response message in the debugger as expected.

However if I disconnect the phone and just after try again the same app without any modification, the Accessibility Service does not seem to work or even to launch, as I cannot even see this Log.d line in the debugger

Log.d(TAG, "onServiceConnected");

I have tried the following unit tests:

1. If I try to deinstall the app and recompile again, it still does not work.

2. If I deinstall the app, reboot the phone, and recompile again, it works again until the next time I unplug and plug again the USB cable to run a new debug from Android Studio.

3. If I just rename the Accessibility Service using the refactor option of Android Studio (adding a 2 after the name for instance), it works again until the next time I unplug and plug again the USB cable to run a new debug from Android Studio.

It seems the Accessibility Service gets stuck or crashes somewhere when I unplug the USB cable and the app is unable to restart it the next time. I can also see the following error messages in the console which makes me think this is the problem:

((latest content captured from the USSD popup))
--- the USB cable is unplugged and plugged again ---
03-22 21:43:04.931 5774-5774/com.myapp D/UssdCatcher3: onAccessibilityEvent
03-22 21:43:04.932 5774-5774/com.myapp D/UssdCatcher3: com.myapp.MainActivity
03-22 21:43:12.023 845-1950/? W/ActivityManager: Scheduling restart of crashed service com.myapp/.UssdCatcher3 in 1000ms
03-22 21:43:13.033 845-858/? I/ActivityManager: Start proc 10243:com.myapp/u0a54 for service com.myapp/.UssdCatcher3
03-22 21:43:16.488 845-858/? W/ActivityManager: Scheduling restart of crashed service com.myapp/.UssdCatcher3 in 1000ms
03-22 21:43:16.490 845-858/? I/ActivityManager:   Force stopping service ServiceRecord{cb2cd91 u0 com.myapp/.UssdCatcher3}
03-22 21:43:55.225 10882-10882/? W/dex2oat: Compilation of java.lang.Object com.myapp.UssdCatcher3.access$super(com.myapp.UssdCatcher3, java.lang.String, java.lang.Object[]) took 109.013ms

This is very weird, any idea on why this is happening?

Thanks a lot for the suggestions!


问:
Can you use an if else statement with Curl command in bash script
I have command I am running with works for one enviornment in a bash script e.g.

so for example

ZONE_ID=prod

```<code>#!/bin/bash

curl -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "X-Auth-Email: EMAIL" \
-H "X-Auth-Key: AUTH_KEY" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}'
</code>```

What i would like to do is change the data item if possible for a different environment depending on the zone_id

ZONE_ID=prod
ZONE_ID=UAT

for example UAT would be

```<code>curl -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "X-Auth-Email: EMAIL" \
-H "X-Auth-Key: AUTH_KEY" \
-H "Content-Type: application/json" \
--data '{"files":["http://www.example.com/css/styles.css",{"url":"http://www.example.com/cat_picture.jpg","headers":{"Origin":"https://www.cloudflare.com","CF-IPCountry":"US","CF-Device-Type":"desktop"}}]}'
</code>```

So what I kind of want to do is the following, but this doesnt work

```<code>#!/bin/bash

curl -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "X-Auth-Email: EMAIL" \
-H "X-Auth-Key: AUTH_KEY" \
-H "Content-Type: application/json" \
if [$ZONE_ID -q prod]; then
--data '{"purge_everything":true}'
else
--data '{"files":["http://www.example.com/css/styles.css",{"url":"http://www.example.com/cat_picture.jpg","headers":{"Origin":"https://www.cloudflare.com","CF-IPCountry":"US","CF-Device-Type":"desktop"}}]}'

</code>```

答:
One possible way to do it is:

```<code>#! /bin/bash

curl -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
    -H "X-Auth-Email: EMAIL" \
    -H "X-Auth-Key: AUTH_KEY" \
    -H "Content-Type: application/json" \
    --data   "$(if [[ $ZONE_ID == prod ]]; then
                    echo '{"purge_everything":true}'
                else
                    echo '{"files":["http://www.example.com/css/styles.css",{"url":"http://www.example.com/cat_picture.jpg","headers":{"Origin":"https://www.cloudflare.com","CF-IPCountry":"US","CF-Device-Type":"desktop"}}]}'
                fi)"
</code>```

However, a much better option (for clarity and maintainability) is to put the --data argument in a variable.

Body:
I have command I am running with works for one enviornment in a bash script e.g.

so for example

ZONE_ID=prod

#!/bin/bash

curl -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "X-Auth-Email: EMAIL" \
-H "X-Auth-Key: AUTH_KEY" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}'

What i would like to do is change the data item if possible for a different environment depending on the zone_id

ZONE_ID=prod
ZONE_ID=UAT

for example UAT would be

curl -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "X-Auth-Email: EMAIL" \
-H "X-Auth-Key: AUTH_KEY" \
-H "Content-Type: application/json" \
--data '{"files":["http://www.example.com/css/styles.css",{"url":"http://www.example.com/cat_picture.jpg","headers":{"Origin":"https://www.cloudflare.com","CF-IPCountry":"US","CF-Device-Type":"desktop"}}]}'

So what I kind of want to do is the following, but this doesnt work

#!/bin/bash

curl -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "X-Auth-Email: EMAIL" \
-H "X-Auth-Key: AUTH_KEY" \
-H "Content-Type: application/json" \
if [$ZONE_ID -q prod]; then
--data '{"purge_everything":true}'
else
--data '{"files":["http://www.example.com/css/styles.css",{"url":"http://www.example.com/cat_picture.jpg","headers":{"Origin":"https://www.cloudflare.com","CF-IPCountry":"US","CF-Device-Type":"desktop"}}]}'

Body:
One possible way to do it is:

#! /bin/bash

curl -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
    -H "X-Auth-Email: EMAIL" \
    -H "X-Auth-Key: AUTH_KEY" \
    -H "Content-Type: application/json" \
    --data   "$(if [[ $ZONE_ID == prod ]]; then
                    echo '{"purge_everything":true}'
                else
                    echo '{"files":["http://www.example.com/css/styles.css",{"url":"http://www.example.com/cat_picture.jpg","headers":{"Origin":"https://www.cloudflare.com","CF-IPCountry":"US","CF-Device-Type":"desktop"}}]}'
                fi)"

However, a much better option (for clarity and maintainability) is to put the --data argument in a variable.