问:
PasswordBox PasswordHelper multibinding
In WPF the Password property of a PasswordBox is not a DependencyProperty so I can't bind to it directly. As a workaround I am using this PasswordHelper from https://www.wpftutorial.net/PasswordBox.html which attaches a PasswordHelper.Password to the PasswordBox so I can bind to it.

To prevent the password from staying in the DataContext as plain text I would like to use a converter which generates a salted hash of the password before saving it to the DataContext. As I need to save both the salt and the salted hash to the DataContext I am using a MultiBinding and  a IMultiValueConverter converter StringToSaltedHashConverter.

My problem is that the Password and PasswordSalt properties of my DataContext are not getting updated when I fill the PasswordBox. I have checked with Snoop and both the Password and PasswordHelper.Password properties of the PasswordBoxare changing accordingly to what I type. Also my StringToSaltedHashConverter is being called and I am returning the correct values.

I have some other bindings on this form (username, first name, last name, gender...) and they all work fine. This is the only one that is not updating.

¿Why is my DataContext not getting updated?

XAML:

```<code><PasswordBox x:Name="Password"
             Style="{DynamicResource PasswordBoxStyle1}"
             local:PasswordHelper.Attach="True">
    <local:PasswordHelper.Password>
        <MultiBinding Converter="{StaticResource StringToSaltedHashConverter}"
                      Mode="OneWayToSource">
            <Binding Path="Password" />
            <Binding Path="PasswordSalt" />
        </MultiBinding>
    </local:PasswordHelper.Password>
</PasswordBox>
</code>```

Code behind:

```<code>public class StringToSaltedHashConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        string str = value as string;
        string salt = Hash.CreateSalt();
        string hash = Hash.CreateHash(str, salt);
        object[] vs = { hash, salt };
        return vs;
    }
}
</code>```

答:
This is not the way to go. PasswordHelper class and their likes should be banned from the internet. The PasswordBox.Password property is not bindable for a very good reason which is well documented. Accessing this property will create a plain text string representation which can be effordlessly retrieved with free tools e.g. Microsoft Process Explorer.

When you get the Password property value, you expose the password as plain text in memory. To avoid this potential security risk, use the SecurePassword property to get the password as a SecureString.

Setting this property to null causes the underlying password to be set to Empty.

You even store the plain salt value in memory - I really hope this is neither a commercial nor a public application. You have absolutely no control when the Garbage Collector will remove any value from the memory. Since String is an immutable type, it is very likely that multiple copies of the user's password will remain public in memory.

Recommended authentication in a Windows environment is to use the Windows User Authentication API.

You should at least clear the PasswordBox.Password property, by setting it null.

Encryption should not be done in the view.

And please, write responsible code! User data is not your data!

MainWindow.xaml

```<code><Window>
  <Window.DataContext>
    <ViewModel />
  </Window.DataContext>

  <PasswordBox x:Name="PasswordBox" />
</Window>
</code>```

MainWindow.xaml.cs

```<code>public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();

    this.PasswordBox.PasswordChanged += OnPasswordChanged;
  }

  private void OnPasswordChanged(object sender, RoutedEventArgs e)
  {
    (this.DataContext as ViewModel).Password = this.PasswordBox.SecurePassword;
  }
}
</code>```

ViewModel.cs

```<code>pucblic class ViewModel
{
  private Model Model { get; }

  private SecureString password;
  public SecureString Password
  {
    private get => this.password;
    public set
    {
      this.password = value;
      OnPasswordChanged();
    }
  }

  private void OnPasswordChanged()
  {
    // Hash password in the model e.g. to compare it to a hashed database value
    this.Model.TryLogin(this.Password);
  }
}
</code>```

Model.cs

```<code>public class Model
{
  public bool TryLogin(SecureString password)
  {
    IntPtr unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(password);
    string hashedPassword = HashPassword(Marshal.PtrToStringUni(unmanagedString));

    return PasswordIsValid(hashedPassword);
  }

  private string HashPassword(string unsecurePassword)
  {
    // Hash algorithm
  }
}
</code>```

Title: PasswordBox PasswordHelper multibinding

Body:
In WPF the Password property of a PasswordBox is not a DependencyProperty so I can't bind to it directly. As a workaround I am using this PasswordHelper from https://www.wpftutorial.net/PasswordBox.html which attaches a PasswordHelper.Password to the PasswordBox so I can bind to it.

To prevent the password from staying in the DataContext as plain text I would like to use a converter which generates a salted hash of the password before saving it to the DataContext. As I need to save both the salt and the salted hash to the DataContext I am using a MultiBinding and  a IMultiValueConverter converter StringToSaltedHashConverter.

My problem is that the Password and PasswordSalt properties of my DataContext are not getting updated when I fill the PasswordBox. I have checked with Snoop and both the Password and PasswordHelper.Password properties of the PasswordBoxare changing accordingly to what I type. Also my StringToSaltedHashConverter is being called and I am returning the correct values.

I have some other bindings on this form (username, first name, last name, gender...) and they all work fine. This is the only one that is not updating.

¿Why is my DataContext not getting updated?

XAML:

<PasswordBox x:Name="Password"
             Style="{DynamicResource PasswordBoxStyle1}"
             local:PasswordHelper.Attach="True">
    <local:PasswordHelper.Password>
        <MultiBinding Converter="{StaticResource StringToSaltedHashConverter}"
                      Mode="OneWayToSource">
            <Binding Path="Password" />
            <Binding Path="PasswordSalt" />
        </MultiBinding>
    </local:PasswordHelper.Password>
</PasswordBox>

Code behind:

public class StringToSaltedHashConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        string str = value as string;
        string salt = Hash.CreateSalt();
        string hash = Hash.CreateHash(str, salt);
        object[] vs = { hash, salt };
        return vs;
    }
}

Body:
This is not the way to go. PasswordHelper class and their likes should be banned from the internet. The PasswordBox.Password property is not bindable for a very good reason which is well documented. Accessing this property will create a plain text string representation which can be effordlessly retrieved with free tools e.g. Microsoft Process Explorer.

When you get the Password property value, you expose the password as plain text in memory. To avoid this potential security risk, use the SecurePassword property to get the password as a SecureString.

Setting this property to null causes the underlying password to be set to Empty.

You even store the plain salt value in memory - I really hope this is neither a commercial nor a public application. You have absolutely no control when the Garbage Collector will remove any value from the memory. Since String is an immutable type, it is very likely that multiple copies of the user's password will remain public in memory.

Recommended authentication in a Windows environment is to use the Windows User Authentication API.

You should at least clear the PasswordBox.Password property, by setting it null.

Encryption should not be done in the view.

And please, write responsible code! User data is not your data!

MainWindow.xaml

<Window>
  <Window.DataContext>
    <ViewModel />
  </Window.DataContext>

  <PasswordBox x:Name="PasswordBox" />
</Window>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();

    this.PasswordBox.PasswordChanged += OnPasswordChanged;
  }

  private void OnPasswordChanged(object sender, RoutedEventArgs e)
  {
    (this.DataContext as ViewModel).Password = this.PasswordBox.SecurePassword;
  }
}

ViewModel.cs

pucblic class ViewModel
{
  private Model Model { get; }

  private SecureString password;
  public SecureString Password
  {
    private get => this.password;
    public set
    {
      this.password = value;
      OnPasswordChanged();
    }
  }

  private void OnPasswordChanged()
  {
    // Hash password in the model e.g. to compare it to a hashed database value
    this.Model.TryLogin(this.Password);
  }
}

Model.cs

public class Model
{
  public bool TryLogin(SecureString password)
  {
    IntPtr unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(password);
    string hashedPassword = HashPassword(Marshal.PtrToStringUni(unmanagedString));

    return PasswordIsValid(hashedPassword);
  }

  private string HashPassword(string unsecurePassword)
  {
    // Hash algorithm
  }
}


来源: stackexchange

问:
Ambiguous overload for operator C++
```<code>#include <iostream>
using namespace std;

class StringNum {
public:
    string s;
    StringNum() {s = "";}
public:
    StringNum(int n) {
        for (int i=1; i<=n; i++) s += "x";

    }

    operator int () {
        return s.length();
    }

    StringNum operator - (StringNum v) {
        int len = s.length() - v.s.length();
        StringNum res;
        for (int i=1;i<=len;i++) res.s += "x";
        return res;
    }

    /* // long solution. But this will allow the program to run.
    template <class T>
    StringNum operator - (T value) {
        return (*this) - StringNum(value);
    }
    */
};

int main()
{
    StringNum x(4);
    cout << 3 - x; // this compiles
    cout << x - 3; // error: ambiguous overload for operator -
                   // change the program so that the 2nd line output 2
    return 0;
}
</code>```

So I have a class that can be upcast from int/downcast to int (this is the simplified version, in the actual version StringNum is HighPrecisionFloat, and int is int/float/double/.. . etc).

When I compile the program, the error message

```<code>In function 'int main()':|
error: ambiguous overload for 'operator-' (operand types are 'StringNum' and 'int')|
note: candidate: operator-(int, int) <built-in>|
note: candidate: StringNum StringNum::operator-(StringNum)|
</code>```

This happens because there are 2 ways to understand x - 3 :

```<code>a) int(x) - 3
b) x - StringNum(3)
</code>```

One way to do this is to use template for each operator (+, -, *, /, dot product, etc...) But that is not very convenient because I have to write templates for each operator.

Is there a better solution to this problem? I wish to call x - StringNum(3). Thank you.

答:
You can make your constructor and conversion to int explicit.

The compiler won't make implicit conversion between those types anymore, but you can still use them like so.

auto stringNum = StringNum{3}; //int to StringNum
int y = static_cast<int>(stringNum);
```

ContentLicense: CC BY-SA 4.0

Title: Ambiguous overload for operator C++

Body:
#include <iostream>
using namespace std;

class StringNum {
public:
    string s;
    StringNum() {s = "";}
public:
    StringNum(int n) {
        for (int i=1; i<=n; i++) s += "x";

    }

    operator int () {
        return s.length();
    }

    StringNum operator - (StringNum v) {
        int len = s.length() - v.s.length();
        StringNum res;
        for (int i=1;i<=len;i++) res.s += "x";
        return res;
    }

    /* // long solution. But this will allow the program to run.
    template <class T>
    StringNum operator - (T value) {
        return (*this) - StringNum(value);
    }
    */
};

int main()
{
    StringNum x(4);
    cout << 3 - x; // this compiles
    cout << x - 3; // error: ambiguous overload for operator -
                   // change the program so that the 2nd line output 2
    return 0;
}

So I have a class that can be upcast from int/downcast to int (this is the simplified version, in the actual version StringNum is HighPrecisionFloat, and int is int/float/double/.. . etc).

When I compile the program, the error message

In function 'int main()':|
error: ambiguous overload for 'operator-' (operand types are 'StringNum' and 'int')|
note: candidate: operator-(int, int) <built-in>|
note: candidate: StringNum StringNum::operator-(StringNum)|

This happens because there are 2 ways to understand x - 3 :

a) int(x) - 3
b) x - StringNum(3)

One way to do this is to use template for each operator (+, -, *, /, dot product, etc...) But that is not very convenient because I have to write templates for each operator.

Is there a better solution to this problem? I wish to call x - StringNum(3). Thank you.


问:
How to execute blender command on google colab?
I have a script to generate images. Unfortunately, I do not have a GPU and everytime I execute it using CPU, the script breaks after some images and throws some error. I was hoping that is there any way to run python scripts from blender background on Google colab.

I have already done the following:

```<code>!apt install blender
!apt install libboost-all-dev
!apt install libgl1-mesa-dev
</code>```

Executing the above command verifies that blender is already installed. Then I try to run python script in blender background:

```<code>!blender --background --python script.py -- --num_images 100
</code>```

But then I keep getting the following error and nothing happens.

```<code>src/tcmalloc.cc:283] Attempt to free invalid pointer 0x7f268381e040
</code>```

The runtime type has been chosen as GPU. Does someone know how to fix it?

Thank you!

答:
When using blender on Colab, you need to set the -noaudio option.

```<code>!blender -b -noaudio --python script.py
</code>```

References: Blender Command Line Arguments

Body:
I have a script to generate images. Unfortunately, I do not have a GPU and everytime I execute it using CPU, the script breaks after some images and throws some error. I was hoping that is there any way to run python scripts from blender background on Google colab.

I have already done the following:

!apt install blender
!apt install libboost-all-dev
!apt install libgl1-mesa-dev

Executing the above command verifies that blender is already installed. Then I try to run python script in blender background:

!blender --background --python script.py -- --num_images 100

But then I keep getting the following error and nothing happens.

src/tcmalloc.cc:283] Attempt to free invalid pointer 0x7f268381e040

The runtime type has been chosen as GPU. Does someone know how to fix it?

Thank you!

Body:
When using blender on Colab, you need to set the -noaudio option.

!blender -b -noaudio --python script.py

References: Blender Command Line Arguments


问:
Swift- Using Delegation to display on tableView
In trying to learn to use the delegate in Swift. The problem is I used the delegate to append a string value (from pickCourse() to ViewController()) to sampleArr; however, it does seem to append but does not show up on the ViewController()'s tableview. I tried to use viewWillAppear but I have no luck. Does anyone know how I can get the sampleArr to appear on ViewController()'s tableview after I selected a someString value in pickCourses() which automatically popbacks to ViewController()?

```<code>import UIKit

class ViewController: UITableViewController, testingDelegate {

    let cellId = "Something"

    var sampleArr : [String] = []

    func sendDataback(data: String) {
        sampleArr.append(data)
        tableView.reloadData()
    }
    override func viewWillAppear(_ animated: Bool) {
        tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)

        navigationItem.title = "Testing Delegate??"
        navigationController?.navigationBar.prefersLargeTitles = true

        self.view.backgroundColor = UIColor.white

        let button1 = UIBarButtonItem(title: "Add A String", style: .plain, target: self, action: #selector(addTapped))
        self.navigationItem.rightBarButtonItem = button1

    }

    @objc func addTapped(sender: UIBarButtonItem!) {

        let destination = PickCourses()
        destination.delegate = self
        navigationController?.pushViewController(destination, animated: true)
    }

}
</code>```

```<code>import UIKit

protocol testingDelegate {
    func sendDataback(data: String)
}

class PickCourses: UITableViewController {

    var delegate: testingDelegate?

    let cellId = "leariningtopassdata"

    let someString = [
        "One One One One",
        "Two Two Two Two",
        "Three Three Three Three",
        "Four Four Four",
        "Five Five Five"
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Pick Some String"
        navigationController?.navigationBar.prefersLargeTitles = true

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView() //removes extra line in UITableView

        tableView.isScrollEnabled = false //disables scrolling
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return someString.count
        }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        let stringlabel = self.someString[indexPath.row]
        cell.textLabel?.text = stringlabel

        return cell
    }

    let vc = ViewController()

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)
        let data = someString[indexPath.row]
        delegate?.sendDataback(data: data)
        self.navigationController?.popViewController(animated: true)
    }

}
</code>```

答:
You should insert following to your calss declaration:

```<code>class YourClassName: UIViewController, UITableViewDataSource, UITableViewDelegate {
</code>```

This will prompt you to add delegate methods, which are following:

```<code>cellForRowAt, numbersOfSection, numbersOfRowInSection,
</code>```

After implementing all them, you can implement something like this into the cellForRow method:

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
    cell.textLabel?.text = sampleArr![indexPath.row]
    return cell
</code>```

I hope that helps.

Body:
In trying to learn to use the delegate in Swift. The problem is I used the delegate to append a string value (from pickCourse() to ViewController()) to sampleArr; however, it does seem to append but does not show up on the ViewController()'s tableview. I tried to use viewWillAppear but I have no luck. Does anyone know how I can get the sampleArr to appear on ViewController()'s tableview after I selected a someString value in pickCourses() which automatically popbacks to ViewController()?

import UIKit

class ViewController: UITableViewController, testingDelegate {

    let cellId = "Something"

    var sampleArr : [String] = []

    func sendDataback(data: String) {
        sampleArr.append(data)
        tableView.reloadData()
    }
    override func viewWillAppear(_ animated: Bool) {
        tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)

        navigationItem.title = "Testing Delegate??"
        navigationController?.navigationBar.prefersLargeTitles = true

        self.view.backgroundColor = UIColor.white

        let button1 = UIBarButtonItem(title: "Add A String", style: .plain, target: self, action: #selector(addTapped))
        self.navigationItem.rightBarButtonItem = button1

    }

    @objc func addTapped(sender: UIBarButtonItem!) {

        let destination = PickCourses()
        destination.delegate = self
        navigationController?.pushViewController(destination, animated: true)
    }

}

import UIKit

protocol testingDelegate {
    func sendDataback(data: String)
}

class PickCourses: UITableViewController {

    var delegate: testingDelegate?

    let cellId = "leariningtopassdata"

    let someString = [
        "One One One One",
        "Two Two Two Two",
        "Three Three Three Three",
        "Four Four Four",
        "Five Five Five"
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Pick Some String"
        navigationController?.navigationBar.prefersLargeTitles = true

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView() //removes extra line in UITableView

        tableView.isScrollEnabled = false //disables scrolling
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return someString.count
        }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        let stringlabel = self.someString[indexPath.row]
        cell.textLabel?.text = stringlabel

        return cell
    }

    let vc = ViewController()

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)
        let data = someString[indexPath.row]
        delegate?.sendDataback(data: data)
        self.navigationController?.popViewController(animated: true)
    }

}

Body:
You should insert following to your calss declaration:

class YourClassName: UIViewController, UITableViewDataSource, UITableViewDelegate {

This will prompt you to add delegate methods, which are following:

cellForRowAt, numbersOfSection, numbersOfRowInSection,

After implementing all them, you can implement something like this into the cellForRow method:

let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
    cell.textLabel?.text = sampleArr![indexPath.row]
    return cell

I hope that helps.


问:
I want to get a single database SQL string
I got a little problem with this:

```<code>readonly LoginMandant logon = new LoginMandant();
string query = "SELECT Name FROM tMandant WHERE Id_Mandant = " + userDetails.Id_Mandant + ";";

Session["MandantName"] = logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();
</code>```

and it returns:

```<code>System.Threading.Tasks.Task`1[System.String]
</code>```

But why? I wanted a single string like "test" in there.

答:
Because you are using SingleOrDefaultAsync it will return a task object.

you should use SingleOrDefault() instead of async if you want to get the string from database synchronously.

below should work in your case:

```<code>Session["MandantName"] = logon.Database.SqlQuery<string>(query).SingleOrDefault();
</code>```

Body:
I got a little problem with this:

readonly LoginMandant logon = new LoginMandant();
string query = "SELECT Name FROM tMandant WHERE Id_Mandant = " + userDetails.Id_Mandant + ";";

Session["MandantName"] = logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();

and it returns:

System.Threading.Tasks.Task`1[System.String]

But why? I wanted a single string like "test" in there.

Body:
Because you are using SingleOrDefaultAsync it will return a task object.

you should use SingleOrDefault() instead of async if you want to get the string from database synchronously.

below should work in your case:

Session["MandantName"] = logon.Database.SqlQuery<string>(query).SingleOrDefault();


问:
How to create right API URLs for getting data
I'm creating a simple API which works with geographical data.

Some URLs look very simple like:

```<code>GET /towns/{id}
</code>```

or

```<code>GET /towns
</code>```

Now I want to get a town by alias, should I use this kind of URL?

```<code>GET /towns/alias/{alias}
</code>```

What if I also want to get a list of towns located near certain town?

```<code>GET /towns/closest/{id}/radius/{radius}
</code>```

I understand that my URLs can be any I want. What is a canonical way to do it?

答:
I understand that my URLs can be any I want. What is a canonical way to do it?

There isn't really a "canonical way" to design URLs, any more than there is a canonical way to name variables -- there are only local spelling conventions.

RFC 3986 distinguishes between hierarchical and non-hierarchical data:

The path component contains data, usually organized in hierarchical form, that, along with data in the non-hierarchical query component (Section 3.4), serves to identify a resource within the scope of the URI's scheme and naming authority (if any)

The effect of using hierarchical data is that you can take advantage of dot-segments to compute one URI from another.

For example

```<code>/town/alias/{alias}
/alias/{alias}
</code>```

Both of these spellings are "fine", but /town/alias gives us the option of using dot segments to specify an identifier under /town

```<code>/town/alias/abc + ../123
  => /town/alias/../123
  => /town/123
</code>```

That can be handy when it allows you to re-use a representation for multiple resources in your hierarchy.

Body:
I'm creating a simple API which works with geographical data.

Some URLs look very simple like:

GET /towns/{id}

or

GET /towns

Now I want to get a town by alias, should I use this kind of URL?

GET /towns/alias/{alias}

What if I also want to get a list of towns located near certain town?

GET /towns/closest/{id}/radius/{radius}

I understand that my URLs can be any I want. What is a canonical way to do it?

Body:
I understand that my URLs can be any I want. What is a canonical way to do it?

There isn't really a "canonical way" to design URLs, any more than there is a canonical way to name variables -- there are only local spelling conventions.

RFC 3986 distinguishes between hierarchical and non-hierarchical data:

The path component contains data, usually organized in hierarchical form, that, along with data in the non-hierarchical query component (Section 3.4), serves to identify a resource within the scope of the URI's scheme and naming authority (if any)

The effect of using hierarchical data is that you can take advantage of dot-segments to compute one URI from another.

For example

/town/alias/{alias}
/alias/{alias}

Both of these spellings are "fine", but /town/alias gives us the option of using dot segments to specify an identifier under /town

/town/alias/abc + ../123
  => /town/alias/../123
  => /town/123

That can be handy when it allows you to re-use a representation for multiple resources in your hierarchy.


问:
Can I expand a macro inside a quote of another macro in Elixir?
Given the below code, the line use Composite, user_opts: user_opts ends up as [{:user_opts, [line: 3, counter: {MockUserNode1, 2}], Automaton.Node}] inside the using(opts) as opts. Is there any way to inject that code inside the outer macro?

```<code>defmacro __using__(user_opts) do
    a =
      if Enum.member?(Composite.types(), user_opts[:node_type]) do
        IO.inspect(user_opts)

        quote bind_quoted: [user_opts: user_opts] do
          use DynamicSupervisor
          use Composite, user_opts: user_opts
        end
      else
        quote do: use(Action)
      end
end
</code>```

答:
Answering the question stated: it’s perfectly possible to call macros from inside other macros, the just inject the AST recursively in the end.

defmodule DeeplyUsed do
  defmacro __using__(opts) do
    quote bind_quoted: [opts: opts] do
      opts
    end
  end
end

defmodule Used do
  defmacro __using__(opts) do
    quote bind_quoted: [opts: opts] do
      use DeeplyUsed, opts: opts
    end
  end
end

defmodule Using do
  use Used, line: 3, counter: {MockUserNode1, 2}
end
```

<p>That said, your issue is induced. </p>

<hr>

<p><em>Sidenote:</em> <code>[{:user_opts, _, Automaton.Node}]</code> looks indeed very suspicious there, that’s not how keyword lists are being quoted. Start with explicit unquoting <em>and</em> logging what comes to <code>user_opts</code> there.</p>

<pre class="lang-rb prettyprint-override"><code>defmacro __using__(user_opts) do
  IO.inspect(user_opts, label: "Outside")
  quote do
    IO.inspect(unquote(user_opts), label: "Inside")
    use Composite, user_opts: unquote(user_opts)
  end
end
</code>```

Body:
Given the below code, the line use Composite, user_opts: user_opts ends up as [{:user_opts, [line: 3, counter: {MockUserNode1, 2}], Automaton.Node}] inside the using(opts) as opts. Is there any way to inject that code inside the outer macro?

defmacro __using__(user_opts) do
    a =
      if Enum.member?(Composite.types(), user_opts[:node_type]) do
        IO.inspect(user_opts)

        quote bind_quoted: [user_opts: user_opts] do
          use DynamicSupervisor
          use Composite, user_opts: user_opts
        end
      else
        quote do: use(Action)
      end
end

Body:
Answering the question stated: it’s perfectly possible to call macros from inside other macros, the just inject the AST recursively in the end.

defmodule DeeplyUsed do
  defmacro __using__(opts) do
    quote bind_quoted: [opts: opts] do
      opts
    end
  end
end

defmodule Used do
  defmacro __using__(opts) do
    quote bind_quoted: [opts: opts] do
      use DeeplyUsed, opts: opts
    end
  end
end

defmodule Using do
  use Used, line: 3, counter: {MockUserNode1, 2}
end

That said, your issue is induced.

Sidenote: [{:user_opts, _, Automaton.Node}] looks indeed very suspicious there, that’s not how keyword lists are being quoted. Start with explicit unquoting and logging what comes to user_opts there.

defmacro __using__(user_opts) do
  IO.inspect(user_opts, label: "Outside")
  quote do
    IO.inspect(unquote(user_opts), label: "Inside")
    use Composite, user_opts: unquote(user_opts)
  end
end


问:
What happens when fork() in a condition?
Can anyone give me the output(with an explanation) of this code?
Thank you...</p>

```<code>#include <stdio.h>
#include <unistd.h>

int main()
{
    if (fork() && (!fork())) {
        if (fork() || fork()) {
            fork();
        }
    }
    printf("Friend\n");
    return 0;
}
</code>```

答:
The quick answer is that the parent will do something and the child will do else.  But continue reading...

Well, I just modified lightly your code into this, and you'll get all the process hierarchy from the output of your program, and the answers to your question:

```<code>#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>

static pid_t my_fork() /* tracing is your friend! :) */
{
    pid_t chld = fork();
    if (chld > 0) {
        /* only the parent shows this */
        printf("[pid=%d, child=%d] forked!\n",
                getpid(), chld);
    }
    return chld;
}

int main()
{
    /* print our pid, so we know the root of the hierarchy */
    printf("[pid=%d] Hello, world\n", getpid());

    /* do the embarrasing work */
    if (my_fork() && (!my_fork())) {
        if (my_fork() || my_fork()) {
            my_fork();
        }
    }

    pid_t pid;
    int status;

    /* We do wait(2)'s while there are children to be waited for.
     * it's a good thing to wait for children before ending. */
    while((pid = wait(&status)) >= 0) {
        printf("[pid=%d, child=%d]: child ended with status=%d\n",
                getpid(), pid, status);
    }

    /* we print the message when no more children are alive */
    printf("[pid=%d]: Hello friend!\n", getpid());

    return 0;
}
</code>```

and this produces

```<code>$ pru
[pid=72699] Hello, world
[pid=72699, child=72700] forked!
[pid=72699, child=72701] forked!
[pid=72700]: Hello friend!
[pid=72701, child=72702] forked!
[pid=72703]: Hello friend!
[pid=72699, child=72700]: child ended with status=0
[pid=72702, child=72703] forked!
[pid=72702, child=72705] forked!
[pid=72702, child=72703]: child ended with status=0
[pid=72705]: Hello friend!
[pid=72704]: Hello friend!
[pid=72701, child=72704] forked!
[pid=72701, child=72704]: child ended with status=0
[pid=72702, child=72705]: child ended with status=0
[pid=72702]: Hello friend!
[pid=72701, child=72702]: child ended with status=0
[pid=72701]: Hello friend!
[pid=72699, child=72701]: child ended with status=0
[pid=72699]: Hello friend!
</code>```

and this is the hierarchy:

```<code>[pid=72699] (says Hello, world, just starting)
  +-[pid=72700] (created in first fork() call of pid=72699)
  `-[pid=72701] (created in second fork() call of pid=72699)
     +-[pid=72702] (created in third fork() call of pid=72701)
     |  +-[pid=72703] (created in fourth fork() call of pid=72702)
     |  `-[pid=72705] (created in fifth fork() call of pid=72702)
     `-[pid=7204] (created in fourth fork() call of pid=72701)
</code>```

(of course, the hierarchy will be different if you run out of processes, and fork(2) fails because of lack of system resources)

Finally, you'll probably get worried about why the message

```<code>[pid=72703]: Hello friend!
</code>```

appears before the message

```<code>[pid=72702, child=72703] forked!
</code>```

but that's the amazing world of multitasking.  The message is printed after fork(2) has return, so both messages are printed by different processes, and so, they can be scheduled in any order, so the child starts and prints its message before the parent has a chance to print who is his child.  That's completely normal.

NOTE

You have to be aware that fork() returns -1 in case of error, which evaluates in a boolean test as true, just like the parent's result.  So if you use freely the return codes from fork(2) for boolean expressions, the parent will receive true or any error that happens for fork() to fail (well, they are scarce, but they are possible on a loaded system).  Just save the result code of fork() and check first for errors, then you are free to use any boolean expression you want on it.

The source code above can be downloaded here

Body:
Can anyone give me the output(with an explanation) of this code?
Thank you...

#include <stdio.h>
#include <unistd.h>

int main()
{
    if (fork() && (!fork())) {
        if (fork() || fork()) {
            fork();
        }
    }
    printf("Friend\n");
    return 0;
}

Body:
The quick answer is that the parent will do something and the child will do else.  But continue reading...

Well, I just modified lightly your code into this, and you'll get all the process hierarchy from the output of your program, and the answers to your question:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>

static pid_t my_fork() /* tracing is your friend! :) */
{
    pid_t chld = fork();
    if (chld > 0) {
        /* only the parent shows this */
        printf("[pid=%d, child=%d] forked!\n",
                getpid(), chld);
    }
    return chld;
}

int main()
{
    /* print our pid, so we know the root of the hierarchy */
    printf("[pid=%d] Hello, world\n", getpid());

    /* do the embarrasing work */
    if (my_fork() && (!my_fork())) {
        if (my_fork() || my_fork()) {
            my_fork();
        }
    }

    pid_t pid;
    int status;

    /* We do wait(2)'s while there are children to be waited for.
     * it's a good thing to wait for children before ending. */
    while((pid = wait(&status)) >= 0) {
        printf("[pid=%d, child=%d]: child ended with status=%d\n",
                getpid(), pid, status);
    }

    /* we print the message when no more children are alive */
    printf("[pid=%d]: Hello friend!\n", getpid());

    return 0;
}

and this produces

$ pru
[pid=72699] Hello, world
[pid=72699, child=72700] forked!
[pid=72699, child=72701] forked!
[pid=72700]: Hello friend!
[pid=72701, child=72702] forked!
[pid=72703]: Hello friend!
[pid=72699, child=72700]: child ended with status=0
[pid=72702, child=72703] forked!
[pid=72702, child=72705] forked!
[pid=72702, child=72703]: child ended with status=0
[pid=72705]: Hello friend!
[pid=72704]: Hello friend!
[pid=72701, child=72704] forked!
[pid=72701, child=72704]: child ended with status=0
[pid=72702, child=72705]: child ended with status=0
[pid=72702]: Hello friend!
[pid=72701, child=72702]: child ended with status=0
[pid=72701]: Hello friend!
[pid=72699, child=72701]: child ended with status=0
[pid=72699]: Hello friend!

and this is the hierarchy:

[pid=72699] (says Hello, world, just starting)
  +-[pid=72700] (created in first fork() call of pid=72699)
  `-[pid=72701] (created in second fork() call of pid=72699)
     +-[pid=72702] (created in third fork() call of pid=72701)
     |  +-[pid=72703] (created in fourth fork() call of pid=72702)
     |  `-[pid=72705] (created in fifth fork() call of pid=72702)
     `-[pid=7204] (created in fourth fork() call of pid=72701)

(of course, the hierarchy will be different if you run out of processes, and fork(2) fails because of lack of system resources)

Finally, you'll probably get worried about why the message

[pid=72703]: Hello friend!

appears before the message

[pid=72702, child=72703] forked!

but that's the amazing world of multitasking.  The message is printed after fork(2) has return, so both messages are printed by different processes, and so, they can be scheduled in any order, so the child starts and prints its message before the parent has a chance to print who is his child.  That's completely normal.

NOTE

You have to be aware that fork() returns -1 in case of error, which evaluates in a boolean test as true, just like the parent's result.  So if you use freely the return codes from fork(2) for boolean expressions, the parent will receive true or any error that happens for fork() to fail (well, they are scarce, but they are possible on a loaded system).  Just save the result code of fork() and check first for errors, then you are free to use any boolean expression you want on it.

The source code above can be downloaded here


问:
PhpStorm doesn't recognize package.json name of local directories
I'm using ReactNative and I have package.json in my local directories so I can have easier imports.

Example:
I have src/components folder and I want to import all components as :

```<code>import Button from 'components/Button;
</code>```

and not use relative path as

```<code>import Button from '../../../components/Button;
</code>```

I created package.json file in my components folder with name 'components' and now I can access Button component as needed.

But, there is problem with PhpStorm. PhpStorm doesn't recognize this as valid path. Is there any workaround for this?

答:
This React native hack for specifying absolute paths (not officially documented anywhere, as far as I can tell) had never been supported. If you miss this feature, please follow WEB-23221 for updates. You can try creating a dummy webpack config like it's suggested in https://youtrack.jetbrains.com/issue/WEB-23221#focus=streamItem-27-2719626.0-0 and specifying a path to it in Settings | Languages & Frameworks | JavaScript | Webpack as a workaround.

Another workaround (if you aren't renaming paths, just making it shorter) is marking a parent folder of components directory as Resource root (note: not the subdirectory itself, but its parent dir!)

Body:
I'm using ReactNative and I have package.json in my local directories so I can have easier imports.

Example:
I have src/components folder and I want to import all components as :

import Button from 'components/Button;

and not use relative path as

import Button from '../../../components/Button;

I created package.json file in my components folder with name 'components' and now I can access Button component as needed.

But, there is problem with PhpStorm. PhpStorm doesn't recognize this as valid path. Is there any workaround for this?


问:
How to I get Fiddler to NOT automatically proxy WinINET Connections?
I want to use Fiddler for a specific application that will manually turn the proxy on and off for (Firefox 3.6 using FiddlerHook). That is the only application I want proxied, but I can't seem to find a way to get Fiddler to not set itself as the WinINET proxy.

I have turned off "Act as System Proxy on startup" and "Monitor all connections", but Fiddler still sets itself as the WinINET proxy when I turn on capture events.

And FiddlerHook will not send events to Fiddler unless capture events is turned on. Actually, it will if you set it to force - see my workaround answer below. Still looking for a better one though.

答:
One workaround/approach I have found is to leave "capture events" off in Fiddler, but then set FiddlerHook to "force". Apparently Fiddler will still accept events even when "capture events" is off.

It feels like there should be a better solution though. One that allows the developer to leave FiddlerHook in "auto".

In the meantime I will mark this as the answer. For other, do read comments for some context.

ContentLicense: CC BY-SA 3.0


问:
ListView.builder bottom overflow by pixel in flutter
This is how I'm using ListView.builder  and it is taken in Column with Expanded widgets. I have tried some solution but they are not working and this is a dynamic list.

```<code>return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          headingContainer(width,order_response),
          Expanded(
            child:  ListView.builder(
              shrinkWrap: true,
              controller: _scrollController,
              itemCount:order_response.orderDetails.length,
              itemBuilder: (context, position) {return orderListItemTile(width,height,order_response,position);},
            ),
          ),

        ],
      ),
    );
</code>```

This is my item Widget

```<code> Column orderListItemTile(double width,double height, Order order_response, int position){
      return Column(
        children: <Widget>[
          GestureDetector(
            onTap: (){
              Navigator.push(
                context,
                new MaterialPageRoute(builder: (context) => new OrderDetails(payload:order_response.orderDetails[position].orderRowId)),
              );
            },
            child: new  Container(
            decoration: BoxDecoration(color: MyColors.backgroundColor),
            padding: EdgeInsets.only(left:width*0.05,right: width*0.05,top:width*0.03,bottom: width*0.03),
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(order_response.orderDetails[position].orderDateTime,style: TextStyle(color: Colors.grey,fontSize: 14.0,fontWeight: FontWeight.w800)),
                SizedBox(height: height*0.01),
                new Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(order_response.orderDetails[position].productName,style: TextStyle(color: MyColors.colorPrimaryDark,fontSize: 18.0,fontWeight: FontWeight.w700)),
                    SizedBox(
                      height: 26.0,
                      width: 26.0,
                      child: RawMaterialButton(
                        onPressed: () {

                        },
                        child: new Icon(
                          Icons.arrow_forward_ios,
                          color: Colors.white,
                          size: 16.0,
                        ),
                        shape: new CircleBorder(),
                        elevation: 2.0,
                        fillColor: Colors.grey[400],
                        padding: const EdgeInsets.all(5.0),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: height*0.01),
                Text(order_response.orderDetails[position].customerName,style: TextStyle(color: Colors.grey,fontSize: 14.0,fontWeight: FontWeight.w800)),
              ],
            ),
          ),),
          Container(
            decoration: BoxDecoration(color: Colors.grey[350]),
            padding: EdgeInsets.only(left:width*0.05,right: width*0.05),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    SizedBox(
                        height: 36.0,
                        width: 36.0,
                        child: IconButton(
                            padding: EdgeInsets.only(top:4.0,bottom: 4.0),
                            icon: Image.asset(order_response.orderDetails[position].orderStatus.contains('accepted')?'assets/images/right.png':'assets/images/wrong.png'),
                            onPressed: (){Navigator.pop(context,true);}
                        )),
                    SizedBox(
                        height: 36.0,
                        width: 36.0,
                        child: IconButton(
                            padding: EdgeInsets.only(top:4.0,bottom: 4.0,left: 5.0),
                            icon: Image.asset('assets/images/cart.png'),
                            onPressed: (){Navigator.pop(context,true);}
                        )),
                  ],),
                Text('Total ${order_response.orderDetails[position].orderAmount}',style: TextStyle(color: Colors.black87,fontSize: 16.0,fontWeight: FontWeight.w700)),

              ],),)

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

答: Try to give your Container full height like height: MediaQuery.of(context).size.height

Body:
This is how I'm using ListView.builder  and it is taken in Column with Expanded widgets. I have tried some solution but they are not working and this is a dynamic list.

return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          headingContainer(width,order_response),
          Expanded(
            child:  ListView.builder(
              shrinkWrap: true,
              controller: _scrollController,
              itemCount:order_response.orderDetails.length,
              itemBuilder: (context, position) {return orderListItemTile(width,height,order_response,position);},
            ),
          ),

        ],
      ),
    );

This is my item Widget

 Column orderListItemTile(double width,double height, Order order_response, int position){
      return Column(
        children: <Widget>[
          GestureDetector(
            onTap: (){
              Navigator.push(
                context,
                new MaterialPageRoute(builder: (context) => new OrderDetails(payload:order_response.orderDetails[position].orderRowId)),
              );
            },
            child: new  Container(
            decoration: BoxDecoration(color: MyColors.backgroundColor),
            padding: EdgeInsets.only(left:width*0.05,right: width*0.05,top:width*0.03,bottom: width*0.03),
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(order_response.orderDetails[position].orderDateTime,style: TextStyle(color: Colors.grey,fontSize: 14.0,fontWeight: FontWeight.w800)),
                SizedBox(height: height*0.01),
                new Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(order_response.orderDetails[position].productName,style: TextStyle(color: MyColors.colorPrimaryDark,fontSize: 18.0,fontWeight: FontWeight.w700)),
                    SizedBox(
                      height: 26.0,
                      width: 26.0,
                      child: RawMaterialButton(
                        onPressed: () {

                        },
                        child: new Icon(
                          Icons.arrow_forward_ios,
                          color: Colors.white,
                          size: 16.0,
                        ),
                        shape: new CircleBorder(),
                        elevation: 2.0,
                        fillColor: Colors.grey[400],
                        padding: const EdgeInsets.all(5.0),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: height*0.01),
                Text(order_response.orderDetails[position].customerName,style: TextStyle(color: Colors.grey,fontSize: 14.0,fontWeight: FontWeight.w800)),
              ],
            ),
          ),),
          Container(
            decoration: BoxDecoration(color: Colors.grey[350]),
            padding: EdgeInsets.only(left:width*0.05,right: width*0.05),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    SizedBox(
                        height: 36.0,
                        width: 36.0,
                        child: IconButton(
                            padding: EdgeInsets.only(top:4.0,bottom: 4.0),
                            icon: Image.asset(order_response.orderDetails[position].orderStatus.contains('accepted')?'assets/images/right.png':'assets/images/wrong.png'),
                            onPressed: (){Navigator.pop(context,true);}
                        )),
                    SizedBox(
                        height: 36.0,
                        width: 36.0,
                        child: IconButton(
                            padding: EdgeInsets.only(top:4.0,bottom: 4.0,left: 5.0),
                            icon: Image.asset('assets/images/cart.png'),
                            onPressed: (){Navigator.pop(context,true);}
                        )),
                  ],),
                Text('Total ${order_response.orderDetails[position].orderAmount}',style: TextStyle(color: Colors.black87,fontSize: 16.0,fontWeight: FontWeight.w700)),

              ],),)

        ],
      );
    }


问:
Why is count(*) slow, when explain knows the answer?
I am using MySQL InnoDB. The table has 10 Million records. I am trying to execute the below query and it takes too much time to execute.

SELECT COUNT(*) FROM abc_test WHERE id = ? AND parent_id IS NULL AND user_status IN (?,?,?,?);

Can anyone please help? The following are the details for the same.

Cloud: AWS

Database: MySQL RDS(r3.2xlarge)

Version : 5.6.34

Table Structure (Total 50 Columns)

id int(11)

parent_id int(11)

user_status tinyint(4)

created datetime

modified datetime

答:
This is partially explained in the documentation on explain:

rows (JSON name: rows)

The rows column indicates the number of rows MySQL believes it must examine to execute the query.

For InnoDB tables, this number is an estimate, and may not always be exact.

I believe the reason is because explain takes the value from the INFORMATION_SCHEMA.TABLES.TABLE_ROWS column.  The documentation further emphasizes there:

TABLE_ROWS

The number of rows. Some storage engines, such as MyISAM, store the exact count. For other storage engines, such as InnoDB, this value is an approximation, and may vary from the actual value by as much as 40% to 50%. In such cases, use SELECT COUNT(*) to obtain an accurate count.

In other words, when you use SELECT COUNT(*), MySQL generates the same query plan regardless of the storage engine.  If you happen to know that it is safe to use INFORMATION_SCHEMA.TABLES, then you can use that value -- either because you are not using InnoDB or because an approximate value is good enough.


问:
Hide custom cursor when mouseover on iframe
I am struggling trying to find out how to hide my custom cursor when it's over an iframe.

I designed a custom cursor but it works fine in all the web sections. However, when it goes over he Vimeo iframe, the mouse stay at the edge of the iframe and shows the default web browser cursor.

I think the easiest way, would be hide the custom cursor whenever I make mouseover on the iframe.

Trying to figure out by using CSS (applying display:none when is the custom cursor is over the iframe) and js but none worked out.

Here the code in codepen: https://codepen.io/felixgonzalo/pen/vYOLrVJ

This is the code:
JS

```<code>let mouseCursor = document.querySelector(".cursor");
let Links = document.querySelectorAll("a");
let logo = document.querySelector(".logo-error");

window.addEventListener('mousemove', cursor);

function cursor(e){

    mouseCursor.style.top = e.pageY + "px";
    mouseCursor.style.left = e.pageX + "px";
}

Links.forEach(link =>{

    if ( link !== logo ){

        link.addEventListener("mouseleave", () => {

            mouseCursor.classList.remove("link-grow");
        });

        link.addEventListener("mouseover", () => {

            mouseCursor.classList.add("link-grow");
        });
    }

});
</code>```

CSS

```<code>body{
    cursor: none;

}

.cursor{
    width: 2rem;
    height: 2rem;
    border: 2px solid white;
    border-radius: 50%;
    position: absolute;
    transform: translate(-50%, -50%);
    transition: all 0.3s ease;
    transition-property: background, transform;
    transform-origin: 100% 100%;
    z-index: 20000;
    pointer-events: none;
}

.link-grow{
    transform: scale(1.2);
    background: white;
    mix-blend-mode: difference;

}

a:-webkit-any-link {
    cursor: none;
}

.logo-error:hover .cursor{
    display: none !important;
}

@media (max-width: 768px){
  .cursor {
    display: none;

  }
}
</code>```

答:
add class on mouseover and mouseleave just as you do with links.

like this:

https://codepen.io/yoseftuk/pen/RwPrJXx

(btw I make some changes for proper positioning of the custom cursor)

Body:
I am struggling trying to find out how to hide my custom cursor when it's over an iframe.

I designed a custom cursor but it works fine in all the web sections. However, when it goes over he Vimeo iframe, the mouse stay at the edge of the iframe and shows the default web browser cursor.

I think the easiest way, would be hide the custom cursor whenever I make mouseover on the iframe.

Trying to figure out by using CSS (applying display:none when is the custom cursor is over the iframe) and js but none worked out.

Here the code in codepen: https://codepen.io/felixgonzalo/pen/vYOLrVJ

This is the code:
JS

let mouseCursor = document.querySelector(".cursor");
let Links = document.querySelectorAll("a");
let logo = document.querySelector(".logo-error");

window.addEventListener('mousemove', cursor);

function cursor(e){

    mouseCursor.style.top = e.pageY + "px";
    mouseCursor.style.left = e.pageX + "px";
}

Links.forEach(link =>{

    if ( link !== logo ){

        link.addEventListener("mouseleave", () => {

            mouseCursor.classList.remove("link-grow");
        });

        link.addEventListener("mouseover", () => {

            mouseCursor.classList.add("link-grow");
        });
    }

});

CSS

body{
    cursor: none;

}

.cursor{
    width: 2rem;
    height: 2rem;
    border: 2px solid white;
    border-radius: 50%;
    position: absolute;
    transform: translate(-50%, -50%);
    transition: all 0.3s ease;
    transition-property: background, transform;
    transform-origin: 100% 100%;
    z-index: 20000;
    pointer-events: none;
}

.link-grow{
    transform: scale(1.2);
    background: white;
    mix-blend-mode: difference;

}

a:-webkit-any-link {
    cursor: none;
}

.logo-error:hover .cursor{
    display: none !important;
}

@media (max-width: 768px){
  .cursor {
    display: none;

  }
}


问:
ValueError: Error when checking input: expected dense_1_input to have shape (180,) but got array with shape (1,)
My learning model is as follows (using Keras).

```<code>model = Sequential()
model.add(Dense(100, activation='relu', input_shape = (X_train.shape[0],)))
model.add(Dense(500, activation='relu'))
model.add(Dense(2, activation='softmax'))
</code>```

My input data X_train is an array of shape (180,) and the corresponding y_train containing labels is also an array of shape (180,). I tried to compile and fit the model as follows.

```<code>model.compile(loss="sparse_categorical_crossentropy",
             optimizer="adam",
             metrics=['accuracy'])

model.fit(X_train, y_train, epochs = 200)
</code>```

When I run the model.fit(), I encountered the following error:

```<code>ValueError: Error when checking input: expected dense_1_input to have
shape (180,) but got array with shape (1,)
</code>```

I'm not sure what I'm doing wrong since I'm pretty new to deep learning. Any help is appreciated. Thanks.

答:
In your case, the input_shape defined in the first layer, should be (1,):

X_train.shape[0] is the number of samples, each sample has for shape (1,).

Moreover, your call to the fit function won't work as your output has for shape (2,) (Dense(2)) whereas the shape of each target sample is (1,) (you have 180 of those).

Body:
My learning model is as follows (using Keras).

model = Sequential()
model.add(Dense(100, activation='relu', input_shape = (X_train.shape[0],)))
model.add(Dense(500, activation='relu'))
model.add(Dense(2, activation='softmax'))

My input data X_train is an array of shape (180,) and the corresponding y_train containing labels is also an array of shape (180,). I tried to compile and fit the model as follows.

model.compile(loss="sparse_categorical_crossentropy",
             optimizer="adam",
             metrics=['accuracy'])

model.fit(X_train, y_train, epochs = 200)

When I run the model.fit(), I encountered the following error:

ValueError: Error when checking input: expected dense_1_input to have
shape (180,) but got array with shape (1,)

I'm not sure what I'm doing wrong since I'm pretty new to deep learning. Any help is appreciated. Thanks.


问:
Comparing two sets for equality recursively?
I am pretty new to programming in general and am trying to construct a function that will take as input two sets, which can contain other sets (a (b c) d e (f g (h)), (a b c (d e f)) for example, and returns whether or not they are equal. I am working with scheme if that helps, but am really trying to just visualize how I could do it. Thanks for the help in advance</p>

答: A simple recursive approach is to pick an element of set A and look for an equal element in set B. If one is found, then remove the two elements from A and B and recurse. Stop with success if both sets are empty; stop with failure if exactly one is empty or if the selected element from A does not have a corresponding element in B.</p>


问:
DataGrip - aliases in uppercase
I'm trying to set all aliases to uppercase in DataGrip SQL editor. I'm already using alias, but it's always set to lowercase, for example:

```<code>SELECT * FROM public.call_center cc
</code>```

I want to set like:

```<code>SELECT * FROM public.call_center CC
</code>```

答: Resolved: Just search to "word case" in settings and set alias to uppercase</p>

Title: DataGrip - aliases in uppercase

Body:
I'm trying to set all aliases to uppercase in DataGrip SQL editor. I'm already using alias, but it's always set to lowercase, for example:

SELECT * FROM public.call_center cc

I want to set like:

SELECT * FROM public.call_center CC


问:
How to store 300M records in Postgresql to run efficiency queries
I have following table:

```<code>CREATE TABLE public.shop_prices
(
    shop_name text COLLATE pg_catalog."default",
    product text COLLATE pg_catalog."default",
    product_category text COLLATE pg_catalog."default",
    price text COLLATE pg_catalog."default"
)
</code>```

and for this table i have a dataset from 18 months. In each file there are about 15M records. I have to some analysis, like in which month a shop has increased or decreased their price. I imported two months in a table and run following query just to test:

```<code>select shop, product from shop_prices group by shop, product limit 10
</code>```

I waited more than 5 minutes, but no any result and response. It was still on working. What is the best way the store these datasets and run efficiency queries? Is it a good idea if I create for each dataset a seperate tables?

答:
What is your PostgreSQL version ?
First there is a typo: column shop should be shop_name.
Second you query looks strange because it has only a LIMIT clause without any ORDER BY clause or WHERE clause: do you really want to have "random" rows for this query ?

Can you try to post EXPLAIN output for the SQL statement:

```<code>explain select shop_name, product from shop_prices group by shop_name, product limit 10;
</code>```

Can you also check if any statistics have been computed for this table with:

```<code>select * from pg_stats where tablename='shop_prices';
</code>```

Body:
I have following table:

CREATE TABLE public.shop_prices
(
    shop_name text COLLATE pg_catalog."default",
    product text COLLATE pg_catalog."default",
    product_category text COLLATE pg_catalog."default",
    price text COLLATE pg_catalog."default"
)

and for this table i have a dataset from 18 months. In each file there are about 15M records. I have to some analysis, like in which month a shop has increased or decreased their price. I imported two months in a table and run following query just to test:

select shop, product from shop_prices group by shop, product limit 10

I waited more than 5 minutes, but no any result and response. It was still on working. What is the best way the store these datasets and run efficiency queries? Is it a good idea if I create for each dataset a seperate tables?

Body:
What is your PostgreSQL version ?
First there is a typo: column shop should be shop_name.
Second you query looks strange because it has only a LIMIT clause without any ORDER BY clause or WHERE clause: do you really want to have "random" rows for this query ?

Can you try to post EXPLAIN output for the SQL statement:

explain select shop_name, product from shop_prices group by shop_name, product limit 10;

Can you also check if any statistics have been computed for this table with:

select * from pg_stats where tablename='shop_prices';


问:
Code works in PyCharm, but return syntaxerror when i call it by terminal
There is a function:

```<code>def change_BG_lin (path):
os.system(f"gsettings set org.gnome.desktop.background picture-uri {path}")
</code>```

In PyCharm all works properly, but when i call it in terminal it returns this:

```<code> os.system(f"gsettings set org.gnome.desktop.background picture-uri {path}")
SyntaxError: invalid syntax
                                                                         ^
</code>```

答: In ubuntu string "python" call to python2, which doesn`t have "f string".</p>

Body:
There is a function:

def change_BG_lin (path):
os.system(f"gsettings set org.gnome.desktop.background picture-uri {path}")

In PyCharm all works properly, but when i call it in terminal it returns this:

 os.system(f"gsettings set org.gnome.desktop.background picture-uri {path}")
SyntaxError: invalid syntax
                                                                         ^


问:
Reading scores from txt and displaying highest score and records of it
Starting Out with Python chapter 6 exercise:

High Score
Assume that a file named scores.txt exists on the computer’s disk. It contains a series of records, each with two fields – a name, followed by a score (an integer between 1 and 100). Write a program that displays the name and score of the record with the highest score, as well as the number of records in the file. (Hint: Use a variable and an “if” statement to keep track of the highest score found as you read through the records, and a variable to keep count of the number of records.)

Data in grades.txt
Jennifer 89
Pearson 90
Nancy 95
Gina 100
Harvey 98
Mike 99
Ross 15
Test 90
```

<hr>

```file=open('grades.txt','r')
my_list=[]

num_of_records=0
highest_score=1
highest_score_name=''

for line in file:
    name,score=line.strip().split()
    if int(score)>highest_score:
        highest_score=int(score)
        highest_score_name=name

    num_of_records=num_of_records+1

print('the name and score of the record with highest score:')
print('Name:',highest_score_name)
print('Score:',highest_score)

print('\nNumber of records:',num_of_records)

file.close()
```

<p>Total starter with python here and trying to get through the book
however hitting error with this question.</p>

<p>Error:</p>

```line 9, in <module> name,score=line.strip().split()
  ValueError: not enough values to unpack (expected 2, got 0)
```

Any guides is appreciated.

答:
OK got it, what is happening is actually your data has a newline character at the end of file, and when you are trying to split that it results in error. Here is the correct code:

```<code>file = open('grades.txt', 'r')

num_of_records = 0
highest_score = 1
highest_score_name = ''

for line in file:
    line = line.strip()
    # Check whether the line is empty
    if line == '':
        continue

    name, score = line.split()
    if int(score) > highest_score:
        highest_score = int(score)
        highest_score_name = name

    num_of_records = num_of_records+1

print('the name and score of the record with highest score:')
print('Name:', highest_score_name)
print('Score:', highest_score)

print('\nNumber of records:', num_of_records)

file.close()
</code>```

Hope it helps you:)

Body:
Starting Out with Python chapter 6 exercise:

High Score
Assume that a file named scores.txt exists on the computer’s disk. It contains a series of records, each with two fields – a name, followed by a score (an integer between 1 and 100). Write a program that displays the name and score of the record with the highest score, as well as the number of records in the file. (Hint: Use a variable and an “if” statement to keep track of the highest score found as you read through the records, and a variable to keep count of the number of records.)

Data in grades.txt
Jennifer 89
Pearson 90
Nancy 95
Gina 100
Harvey 98
Mike 99
Ross 15
Test 90

file=open('grades.txt','r')
my_list=[]

num_of_records=0
highest_score=1
highest_score_name=''

for line in file:
    name,score=line.strip().split()
    if int(score)>highest_score:
        highest_score=int(score)
        highest_score_name=name

    num_of_records=num_of_records+1

print('the name and score of the record with highest score:')
print('Name:',highest_score_name)
print('Score:',highest_score)

print('\nNumber of records:',num_of_records)

file.close()

Total starter with python here and trying to get through the book
however hitting error with this question.

Error:

line 9, in <module> name,score=line.strip().split()
  ValueError: not enough values to unpack (expected 2, got 0)

Any guides is appreciated.

Body:
OK got it, what is happening is actually your data has a newline character at the end of file, and when you are trying to split that it results in error. Here is the correct code:

file = open('grades.txt', 'r')

num_of_records = 0
highest_score = 1
highest_score_name = ''

for line in file:
    line = line.strip()
    # Check whether the line is empty
    if line == '':
        continue

    name, score = line.split()
    if int(score) > highest_score:
        highest_score = int(score)
        highest_score_name = name

    num_of_records = num_of_records+1

print('the name and score of the record with highest score:')
print('Name:', highest_score_name)
print('Score:', highest_score)

print('\nNumber of records:', num_of_records)

file.close()

Hope it helps you:)


问:
When to release a NSString in iPhone
I have the following method

```<code>   -(NSMutableArray *) getPaises {
     NSMutableArray * paises;
     paises = [[NSMutableArray alloc] init];
     while( get new row ) {
      NSString *aPais =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
      [paises addObject:aPais];
     }
     return paises;
    }
</code>```

I am not releasing the aPais, because if I do it the application crashes. I don't know when or if whether I should release it somewhere after using it and, if so, how do I do it. Just release the NSMutableArray is enough? Or do I have to traverse it and release each object?

And if I don't have to release it, who is the responsible for releasing?

答:
As epatel said, you don't need to release that particular string. If you wanted to be more proactive, you could do this instead:

```<code>-(NSMutableArray *) getPaises {
    NSMutableArray * paises;
    paises = [[[NSMutableArray alloc] init] autorelease];
    while( get new row ) {
        NSString *aPais =  [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
        [paises addObject:aPais];
        [aPais release];
    }
    return paises;
}
</code>```

In summary:

[[NSString alloc] initWith...] -> You must release or autorelease.

[NSString stringWith...] -> No need to release.

-- Edit: Added autorelease for paises, as you are returning it. When you return an object, always autorelease it if you have alloc&init'd it.

OwnerDisplayName: Sacha Fuentes

ContentLicense: CC BY-SA 2.5

Title: When to release a NSString in iPhone

Body:
I have the following method

   -(NSMutableArray *) getPaises {
     NSMutableArray * paises;
     paises = [[NSMutableArray alloc] init];
     while( get new row ) {
      NSString *aPais =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
      [paises addObject:aPais];
     }
     return paises;
    }

I am not releasing the aPais, because if I do it the application crashes. I don't know when or if whether I should release it somewhere after using it and, if so, how do I do it. Just release the NSMutableArray is enough? Or do I have to traverse it and release each object?

And if I don't have to release it, who is the responsible for releasing?

LastEditorDisplayName: andynormancx

Body:
As epatel said, you don't need to release that particular string. If you wanted to be more proactive, you could do this instead:

-(NSMutableArray *) getPaises {
    NSMutableArray * paises;
    paises = [[[NSMutableArray alloc] init] autorelease];
    while( get new row ) {
        NSString *aPais =  [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
        [paises addObject:aPais];
        [aPais release];
    }
    return paises;
}

In summary:

[[NSString alloc] initWith...] -> You must release or autorelease.

[NSString stringWith...] -> No need to release.

-- Edit: Added autorelease for paises, as you are returning it. When you return an object, always autorelease it if you have alloc&init'd it.

OwnerDisplayName: squelart

LastEditorDisplayName: squelart


问:
Batch Processing of Multiple Files in Multiple Folders
I'm using the SoX sound editing command line tool. I'm trying to create a batch file that will allow me to drag multiple folders onto it and have the file process all the mp3 files within the folders, then output them into the converted folder, arranged into folders named the same as the ones originally dragged on. I currently have:

```<code>cd %~dp0
mkdir converted
FOR %%A IN (%*) DO sox %%A -c 1 "converted/%%~nxA" mixer -1
pause
</code>```

This allows me to drag files on, but not whole folders. All I really need to do is take it up a level. As you may have guessed, I have very little batch processing knowledge so an explanation would be greatly beneficial.

Thank you for your time!

答:
I managed to adapt this file to use nested for loops to accomplish what I wanted:

```<code>cd %~dp0
mkdir converted
FOR /d %%A IN (*) DO (
    IF EXIST %%A/*.mp3 (
        cd converted
        mkdir %%~nxA
        cd ..
    )
    cd %%A
    For %%B IN (*.mp3) DO (
        cd ..
        sox "%%A\%%~nxB" -c 1 "converted/%%~nxA/%%~nxB" mixer -1
        cd %%A
    )
    cd ..
)
pause
</code>```

The code now searches each directory in the folder with the batch file, then enters the directories and processes the files within.

Body:
I'm using the SoX sound editing command line tool. I'm trying to create a batch file that will allow me to drag multiple folders onto it and have the file process all the mp3 files within the folders, then output them into the converted folder, arranged into folders named the same as the ones originally dragged on. I currently have:

cd %~dp0
mkdir converted
FOR %%A IN (%*) DO sox %%A -c 1 "converted/%%~nxA" mixer -1
pause

This allows me to drag files on, but not whole folders. All I really need to do is take it up a level. As you may have guessed, I have very little batch processing knowledge so an explanation would be greatly beneficial.

Thank you for your time!

Body:
I managed to adapt this file to use nested for loops to accomplish what I wanted:

cd %~dp0
mkdir converted
FOR /d %%A IN (*) DO (
    IF EXIST %%A/*.mp3 (
        cd converted
        mkdir %%~nxA
        cd ..
    )
    cd %%A
    For %%B IN (*.mp3) DO (
        cd ..
        sox "%%A\%%~nxB" -c 1 "converted/%%~nxA/%%~nxB" mixer -1
        cd %%A
    )
    cd ..
)
pause

The code now searches each directory in the folder with the batch file, then enters the directories and processes the files within.


问:
JOOL tree structure
I have a collection of documents: List listDocs. The document has the structure of the form:

id, level, aoguid, parentguid, formalname, currstatus

. This structure allows you to create a tree structure of addresses. That is: a country - level 1, a city - level 2, a street - level 3, and so on up to level 7. Some levels may or may not be. My task: to form json containing the full address and an array of parts making up the full address.

```<code>{
  "full Address": "Country city street house",
  "parts": [
    {
      "id": 1,
      "aoguid": 1,
      "parentguid": 0,
      "formalname": "country",
      "currstatus": 0
    },
    {
      "id": 2,
      "aoguid": 2,
      "parentguid": 1,
      "formalname": "city",
      "currstatus": 0
    },
    {
      "id": 3,
      "aoguid": 3,
      "parentguid": 2,
      "formalname": "street",
      "currstatus": 0
    },
    {
      "id": 4,
      "aoguid": 4,
      "parentguid": 3,
      "formalname": "house",
      "currstatus": 0
    }
  ]
}
</code>```

The task is complicated by the fact that the project uses mongoDb, not a relational database. But I found that using the JOOL framework, you can make JAVA queries like SQL. I wrote this code:

```<code>Seq<Document> seq1 = Seq.seq(listDocs).filter(
        it -> isNull(it.get("currstatus")) || "0".equals(it.get("currstatus"))
);
Seq<Document> seq2 = seq1;
Seq<Document> seq3 = seq1;
Seq<Document> seq4 = seq1;
Seq<Document> seq5 = seq1;
Seq<Document> seq6 = seq1;
Seq<Document> seq7 = seq1;

seq1
        .leftOuterJoin(seq2, (l1, l2) -> Objects.equals(l1.get("aoguid"), l2.get("parentguid")))
        .leftOuterJoin(seq3, (l2, l3) -> Objects.equals(l2.v2.get("aoguid"), l3.get("parentguid")))
        .leftOuterJoin(seq4, (l3, l4) -> Objects.equals(l3.v3.get("aoguid"), l4.get("parentguid")))
        .leftOuterJoin(seq5, (l4, l5) -> Objects.equals(l4.v4.get("aoguid"), l5.get("parentguid")))
        .leftOuterJoin(seq6, (l5, l6) -> Objects.equals(l5.v5.get("aoguid"), l6.get("parentguid")))
        .leftOuterJoin(seq7, (l6, l7) -> Objects.equals(l6.v6.get("aoguid"), l7.get("parentguid")))
        .parallel()
        .forEach(it -> {
            System.out.println("Some actions....");
        });
</code>```

But this code does not compile. How can I fix it so that everything works?

答:
The previous solution is also correct and may come in handy for someone, but I will lay out the one that I eventually sought. This is the final version.</p>

```<code>@Override
public void saveES(List<Document> listDocs) {
    Seq<Document> root = seq(listDocs).filter(
            it -> ((Integer) it.get("currstatus") == 0) && ((Integer) it.get("aolevel") == 1)
    );

    root
            .leftOuterJoin(
                    seq(listDocs).filter(level_2 -> isNull(level_2.get("currstatus")) || ((Integer) level_2.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a, b)
            )
            .leftOuterJoin(
                    seq(listDocs).filter(level_3 -> isNull(level_3.get("currstatus")) || ((Integer) level_3.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v2, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .leftOuterJoin(
                    seq(listDocs).filter(level_4 -> isNull(level_4.get("currstatus")) || ((Integer) level_4.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v3, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .leftOuterJoin(
                    seq(listDocs)
                            .filter(level_5 -> isNull(level_5.get("currstatus")) || (nonNull(level_5.get("currstatus")) && (Integer) level_5.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v4, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .leftOuterJoin(
                    seq(listDocs).filter(level_6 -> isNull(level_6.get("currstatus")) || ((Integer) level_6.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v5, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .leftOuterJoin(
                    seq(listDocs).filter(level_7 -> isNull(level_7.get("currstatus")) || ((Integer) level_7.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v6, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .parallel()
            .distinct()
            .forEach(it -> {
                List<Document> objects1 = (List<Document>) it.toList();
                String full = objects1.stream()
                        .filter(Objects::nonNull)
                        .map(doc -> String.join(" ", doc.getOrDefault("shortname", "") + ".", (String) doc.get("formalname")))
                        .collect(Collectors.joining(" "));

                List<Document> objects2 = (List<Document>) it.toList();
                List<Entry> entryList = objects2.stream()
                        .filter(Objects::nonNull)
                        .map(doc -> Entry.builder()
                                .aoid((String) doc.getOrDefault("aoid", ""))
                                .aoGuid((String) doc.getOrDefault("aoguid", ""))
                                .code((String) doc.getOrDefault("code", ""))
                                .offName((String) doc.getOrDefault("offname", ""))
                                .parentGuid((String) doc.getOrDefault("parentguid", ""))
                                .shortName((String) doc.getOrDefault("shortname", ""))
                                .aoLevel((Integer) doc.getOrDefault("aolevel", ""))
                                .postalCode((String) doc.getOrDefault("postalcode", ""))
                                .build())
                        .collect(Collectors.toList());
                log.info(full);
                Address address = new Address(full, entryList);
                searchService.save(address);
            });
}
</code>```

Title: JOOL tree structure

Body:
I have a collection of documents: List listDocs. The document has the structure of the form:

id, level, aoguid, parentguid, formalname, currstatus

. This structure allows you to create a tree structure of addresses. That is: a country - level 1, a city - level 2, a street - level 3, and so on up to level 7. Some levels may or may not be. My task: to form json containing the full address and an array of parts making up the full address.

{
  "full Address": "Country city street house",
  "parts": [
    {
      "id": 1,
      "aoguid": 1,
      "parentguid": 0,
      "formalname": "country",
      "currstatus": 0
    },
    {
      "id": 2,
      "aoguid": 2,
      "parentguid": 1,
      "formalname": "city",
      "currstatus": 0
    },
    {
      "id": 3,
      "aoguid": 3,
      "parentguid": 2,
      "formalname": "street",
      "currstatus": 0
    },
    {
      "id": 4,
      "aoguid": 4,
      "parentguid": 3,
      "formalname": "house",
      "currstatus": 0
    }
  ]
}

The task is complicated by the fact that the project uses mongoDb, not a relational database. But I found that using the JOOL framework, you can make JAVA queries like SQL. I wrote this code:

Seq<Document> seq1 = Seq.seq(listDocs).filter(
        it -> isNull(it.get("currstatus")) || "0".equals(it.get("currstatus"))
);
Seq<Document> seq2 = seq1;
Seq<Document> seq3 = seq1;
Seq<Document> seq4 = seq1;
Seq<Document> seq5 = seq1;
Seq<Document> seq6 = seq1;
Seq<Document> seq7 = seq1;

seq1
        .leftOuterJoin(seq2, (l1, l2) -> Objects.equals(l1.get("aoguid"), l2.get("parentguid")))
        .leftOuterJoin(seq3, (l2, l3) -> Objects.equals(l2.v2.get("aoguid"), l3.get("parentguid")))
        .leftOuterJoin(seq4, (l3, l4) -> Objects.equals(l3.v3.get("aoguid"), l4.get("parentguid")))
        .leftOuterJoin(seq5, (l4, l5) -> Objects.equals(l4.v4.get("aoguid"), l5.get("parentguid")))
        .leftOuterJoin(seq6, (l5, l6) -> Objects.equals(l5.v5.get("aoguid"), l6.get("parentguid")))
        .leftOuterJoin(seq7, (l6, l7) -> Objects.equals(l6.v6.get("aoguid"), l7.get("parentguid")))
        .parallel()
        .forEach(it -> {
            System.out.println("Some actions....");
        });

But this code does not compile. How can I fix it so that everything works?

Body:
The previous solution is also correct and may come in handy for someone, but I will lay out the one that I eventually sought. This is the final version.

@Override
public void saveES(List<Document> listDocs) {
    Seq<Document> root = seq(listDocs).filter(
            it -> ((Integer) it.get("currstatus") == 0) && ((Integer) it.get("aolevel") == 1)
    );

    root
            .leftOuterJoin(
                    seq(listDocs).filter(level_2 -> isNull(level_2.get("currstatus")) || ((Integer) level_2.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a, b)
            )
            .leftOuterJoin(
                    seq(listDocs).filter(level_3 -> isNull(level_3.get("currstatus")) || ((Integer) level_3.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v2, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .leftOuterJoin(
                    seq(listDocs).filter(level_4 -> isNull(level_4.get("currstatus")) || ((Integer) level_4.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v3, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .leftOuterJoin(
                    seq(listDocs)
                            .filter(level_5 -> isNull(level_5.get("currstatus")) || (nonNull(level_5.get("currstatus")) && (Integer) level_5.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v4, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .leftOuterJoin(
                    seq(listDocs).filter(level_6 -> isNull(level_6.get("currstatus")) || ((Integer) level_6.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v5, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .leftOuterJoin(
                    seq(listDocs).filter(level_7 -> isNull(level_7.get("currstatus")) || ((Integer) level_7.get("currstatus") == 0)),
                    (a, b) -> checkObjects(a.v6, b)
            )
            .map(a -> a.v1.concat(a.v2))
            .parallel()
            .distinct()
            .forEach(it -> {
                List<Document> objects1 = (List<Document>) it.toList();
                String full = objects1.stream()
                        .filter(Objects::nonNull)
                        .map(doc -> String.join(" ", doc.getOrDefault("shortname", "") + ".", (String) doc.get("formalname")))
                        .collect(Collectors.joining(" "));

                List<Document> objects2 = (List<Document>) it.toList();
                List<Entry> entryList = objects2.stream()
                        .filter(Objects::nonNull)
                        .map(doc -> Entry.builder()
                                .aoid((String) doc.getOrDefault("aoid", ""))
                                .aoGuid((String) doc.getOrDefault("aoguid", ""))
                                .code((String) doc.getOrDefault("code", ""))
                                .offName((String) doc.getOrDefault("offname", ""))
                                .parentGuid((String) doc.getOrDefault("parentguid", ""))
                                .shortName((String) doc.getOrDefault("shortname", ""))
                                .aoLevel((Integer) doc.getOrDefault("aolevel", ""))
                                .postalCode((String) doc.getOrDefault("postalcode", ""))
                                .build())
                        .collect(Collectors.toList());
                log.info(full);
                Address address = new Address(full, entryList);
                searchService.save(address);
            });
}


问:
Stop the function when the folder doesn't have xlsx files in (Google App scripts)
I have the next function on Google App Script:

```<code>function remove(){
  var folder = DriveApp.getFolderById('folderID');
  var files = DriveApp.getFilesByType(MimeType.MICROSOFT_EXCEL);
  while (files.hasNext()){
    var file = files.next();
    folder.removeFile(file);
  }
}
</code>```

I want stop/break/exit the function when the folder does not have/contains xlsx files.
How I do that?
Greetings

答:
Here is the code: </p>

```<code>     function remove(){
     var folder = DriveApp.getFolderById(''folder's id'');
     var files = folder.getFilesByType(MimeType.MICROSOFT_EXCEL);;
     while (files.hasNext()){
     var file = files.next();
     folder.removeFile(file);

     }
</code>```

Body:
I have the next function on Google App Script:

function remove(){
  var folder = DriveApp.getFolderById('folderID');
  var files = DriveApp.getFilesByType(MimeType.MICROSOFT_EXCEL);
  while (files.hasNext()){
    var file = files.next();
    folder.removeFile(file);
  }
}

I want stop/break/exit the function when the folder does not have/contains xlsx files.
How I do that?
Greetings

Body:
Here is the code:

     function remove(){
     var folder = DriveApp.getFolderById(''folder's id'');
     var files = folder.getFilesByType(MimeType.MICROSOFT_EXCEL);;
     while (files.hasNext()){
     var file = files.next();
     folder.removeFile(file);

     }


问:
Setting jQuery validation messages option to another map
I've got the rules defined below for a page:

```<code>$(document).ready(function() {

$.validator.setDefaults({
    submitHandler : function() { alert("submitted!"); }
});

$("#prospectForm").validate({
    errorLabelContainer : $("#errorDiv ul"),
    wrapper : "li",
    debug : true,
    rules : {
        prospectName : {
            required : true,
            rangelength : [2, 45]
        },
        groupSize : {
            required : true,
            digits : true
        },
        zipCode : {
            required : true,
            digits : true,
            rangelength : [5, 5]
        },
        sicCode : {
            required : true,
            rangelength : [4, 4],
            digits : true
        },
        agencyProducer : {
            required : true
        }
    },
            messages : errorMap
});
});
</code>```

I defined errorMap like the following:

```<code>var errorMap = {
prospectName : {
    required : "An entry is required in field Prospect.",
    rangelength : "Prospect Name must be between 2 and 45 characters."
},
groupSize : {
    required : "An entry is required in field Group Size.",
    digits : "Numeric data is required in field Group Size."
},
zipCode : {
    required : "An entry is required in field Zip Code.",
    digits : "Numeric data is required in field Zip Code.",
    rangelength : "Zip Code must be 5 digits."
},
sicCode : {
    required : "This is an invalid SIC code. Enter the SIC again or search for the SIC code.",
    rangelength : "This is an invalid SIC code. Enter the SIC again or search for the SIC code.",
    digits : "This is an invalid SIC code. Enter the SIC again or search for the SIC code."
},
agencyProducer : {
    required : "An entry is required in the Agent field."
}
};
</code>```

When I run this, I get errorMap undefined.  I am including the errorMap definition code in a separate .js file and including this errorMsgDefs.js inside the html file after I include the jQuery and jQuery.validate files.

Any ideas?  The docs say you can use a map for the value of the messages option, so what am I doing wrong?

Thanks for any help.

答: it sounds to me like its either not loading or its out of scope try making it global by remove the "var" before errorMap = and see if that fixes the problem</p>

Body:
I've got the rules defined below for a page:

$(document).ready(function() {

$.validator.setDefaults({
    submitHandler : function() { alert("submitted!"); }
});

$("#prospectForm").validate({
    errorLabelContainer : $("#errorDiv ul"),
    wrapper : "li",
    debug : true,
    rules : {
        prospectName : {
            required : true,
            rangelength : [2, 45]
        },
        groupSize : {
            required : true,
            digits : true
        },
        zipCode : {
            required : true,
            digits : true,
            rangelength : [5, 5]
        },
        sicCode : {
            required : true,
            rangelength : [4, 4],
            digits : true
        },
        agencyProducer : {
            required : true
        }
    },
            messages : errorMap
});
});

I defined errorMap like the following:

var errorMap = {
prospectName : {
    required : "An entry is required in field Prospect.",
    rangelength : "Prospect Name must be between 2 and 45 characters."
},
groupSize : {
    required : "An entry is required in field Group Size.",
    digits : "Numeric data is required in field Group Size."
},
zipCode : {
    required : "An entry is required in field Zip Code.",
    digits : "Numeric data is required in field Zip Code.",
    rangelength : "Zip Code must be 5 digits."
},
sicCode : {
    required : "This is an invalid SIC code. Enter the SIC again or search for the SIC code.",
    rangelength : "This is an invalid SIC code. Enter the SIC again or search for the SIC code.",
    digits : "This is an invalid SIC code. Enter the SIC again or search for the SIC code."
},
agencyProducer : {
    required : "An entry is required in the Agent field."
}
};

When I run this, I get errorMap undefined.  I am including the errorMap definition code in a separate .js file and including this errorMsgDefs.js inside the html file after I include the jQuery and jQuery.validate files.

Any ideas?  The docs say you can use a map for the value of the messages option, so what am I doing wrong?

Thanks for any help.


问:
How to solve the "EOF within quoted string" in a web scraping function?
So I'm using this web scraping function boldseqspec which returns data on specimens of several species based on a vector of taxonomic groups given in the "taxon" argument like this:

```<code>df<-bold_seqspec(taxon=c("group1","group2","group3"), format = "tsv")
</code>```

But recently for some cases I'm getting the following message and subsequently losing information when I use it:

```<code>Warning message:
In scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
  EOF within quoted string
</code>```

I've gotten this before in read.delim but I solved it with this:

```<code>df<-read.delim("file.txt",quote = "",comment.char = "")
</code>```

Reproducible example:

```<code>install.packages("bold")
library(bold)
df<-bold_seqspec(taxon=c("Cnidaria","Hippocampus"), format = "tsv", marker="COI-5P")
</code>```

The problem is that the function I'm using for data mining (boldseqspec) doesn't have the quote and comment.char arguments.

答:
It seems that the tsv output contains both double-quotes and single quotes and this is why the parsing mucks up (for more information on the matter - actually it is also about a biological data set, too - see EOF-within-quoted-string / difference between read.delim() and read.table())

Hence, if you can't set quotations, I'd suggest using a workaround by setting the format = "xml" and convert the xml to a DataFrame in a further step with the libraries XML (or xml2?) and dplyr.

```<code>library(XML)
library(dplyr)
xml = bold_seqspec(taxon=c("Cnidaria","Hippocampus"), format = "xml", marker="COI-5P")
df= xmlToDataFrame(xml , stringsAsFactors = FALSE,) %>%
                        mutate_all(~type.convert(., as.is = T))
</code>```

Hope this helps.

Body:
So I'm using this web scraping function boldseqspec which returns data on specimens of several species based on a vector of taxonomic groups given in the "taxon" argument like this:

df<-bold_seqspec(taxon=c("group1","group2","group3"), format = "tsv")

But recently for some cases I'm getting the following message and subsequently losing information when I use it:

Warning message:
In scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
  EOF within quoted string

I've gotten this before in read.delim but I solved it with this:

df<-read.delim("file.txt",quote = "",comment.char = "")

Reproducible example:

install.packages("bold")
library(bold)
df<-bold_seqspec(taxon=c("Cnidaria","Hippocampus"), format = "tsv", marker="COI-5P")

The problem is that the function I'm using for data mining (boldseqspec) doesn't have the quote and comment.char arguments.

Body:
It seems that the tsv output contains both double-quotes and single quotes and this is why the parsing mucks up (for more information on the matter - actually it is also about a biological data set, too - see EOF-within-quoted-string / difference between read.delim() and read.table())

Hence, if you can't set quotations, I'd suggest using a workaround by setting the format = "xml" and convert the xml to a DataFrame in a further step with the libraries XML (or xml2?) and dplyr.

library(XML)
library(dplyr)
xml = bold_seqspec(taxon=c("Cnidaria","Hippocampus"), format = "xml", marker="COI-5P")
df= xmlToDataFrame(xml , stringsAsFactors = FALSE,) %>%
                        mutate_all(~type.convert(., as.is = T))

Hope this helps.


问:
How to get rid of the filing 0 in the epc?
I'm using a simple c# function from the zebra example code to send my zpl to the printer. It works, but instead of writing my desired content into the epc of the rfid-tag it get filled up with unwanted "0"

This is the RFID-part of my sended zpl:

^RS8,25^RFW,H^FD00015004^FS

I send "00015004" but if I read the tag I get "000150040000000000000000" back. It's an Class 1 Gen 2 Tag

Already tried the ^RFW,E commend with ^RB, but that's converts it to hex with the same unwanted result.

How to erase/kill those additional 0?

full code:

```<code>            public void print(string ipAddress, int port) {
        try {
            //Printer Connection
            TcpClient client = new TcpClient();
            client.Connect(ipAddress, port);
            StreamWriter writer = new StreamWriter(client.GetStream());

            string ZPLString = "^XA" +
                                "^FXLabelSettings" +
                                "^MUD,300,300^PW970^LL270^LH0,0^JMA^FS^CVN^FS^CFD,54,25^FS" +
                                "^FXPrintContent" +
                                "^FO50,120^A0,100,150^FD00015004^FS" + //to print the number visible
                                "^FXRFIDSection" +
                                "^RS8,25^RFW,H^FD00015004^FS" + // to write into the epc and here is the Issue, the tag shows 000150040000000000000000 afterwards
                                "^XZ";

            //Printer Communication
            writer.Write(ZPLString);
            writer.Flush();
            writer.Close();
            client.Close();

        } catch (Exception ex) {
        }
    }
</code>```

答:
I know I'm a bit late to the party but it might be useful if someone else stumbles over this post...

Try:

```<code>^RS8
^RFW,H,,,A^FD12345678^FS
</code>```

When read with a RFID reader this will return the EPC code 12345678 without the trailing zeros.  For reference this was written to a tag using a Zebra ZQ511.

https://www.zebra.com/content/dam/zebra_new_ia/en-us/manuals/printers/common/programming/rfid3-pg-en.pdf

Body:
I'm using a simple c# function from the zebra example code to send my zpl to the printer. It works, but instead of writing my desired content into the epc of the rfid-tag it get filled up with unwanted "0"

This is the RFID-part of my sended zpl:

^RS8,25^RFW,H^FD00015004^FS

I send "00015004" but if I read the tag I get "000150040000000000000000" back. It's an Class 1 Gen 2 Tag

Already tried the ^RFW,E commend with ^RB, but that's converts it to hex with the same unwanted result.

How to erase/kill those additional 0?

full code:

            public void print(string ipAddress, int port) {
        try {
            //Printer Connection
            TcpClient client = new TcpClient();
            client.Connect(ipAddress, port);
            StreamWriter writer = new StreamWriter(client.GetStream());

            string ZPLString = "^XA" +
                                "^FXLabelSettings" +
                                "^MUD,300,300^PW970^LL270^LH0,0^JMA^FS^CVN^FS^CFD,54,25^FS" +
                                "^FXPrintContent" +
                                "^FO50,120^A0,100,150^FD00015004^FS" + //to print the number visible
                                "^FXRFIDSection" +
                                "^RS8,25^RFW,H^FD00015004^FS" + // to write into the epc and here is the Issue, the tag shows 000150040000000000000000 afterwards
                                "^XZ";

            //Printer Communication
            writer.Write(ZPLString);
            writer.Flush();
            writer.Close();
            client.Close();

        } catch (Exception ex) {
        }
    }

Body:
I know I'm a bit late to the party but it might be useful if someone else stumbles over this post...

Try:

^RS8
^RFW,H,,,A^FD12345678^FS

When read with a RFID reader this will return the EPC code 12345678 without the trailing zeros.  For reference this was written to a tag using a Zebra ZQ511.

https://www.zebra.com/content/dam/zebra_new_ia/en-us/manuals/printers/common/programming/rfid3-pg-en.pdf