问:
How to change color of Toolbar back button in Android?
I could not change the color of back button. I am using toolbar material design. In my app I am applying black background of tool bar but the back design is being black by default that's why I just want to change the color of this back button. Please give me solutions.

Thank You

答:
Just use the MaterialToolbar and override the default colors:

```<code>    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        ..>
</code>```

with:

```<code>  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- color used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>
</code>```

If you are using the androidx.appcompat.widget.Toolbar or the MaterialToolbar  with the default style (Widget.MaterialComponents.Toolbar) you can use:

```<code><androidx.appcompat.widget.Toolbar
    android:theme="@style/MyThemeOverlay_Toolbar2"
</code>```

with:

```<code>  <style name="MyThemeOverlay_Toolbar2" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>
</code>```

Body:
Just use the MaterialToolbar and override the default colors:

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        ..>

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- color used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>

If you are using the androidx.appcompat.widget.Toolbar or the MaterialToolbar  with the default style (Widget.MaterialComponents.Toolbar) you can use:

<androidx.appcompat.widget.Toolbar
    android:theme="@style/MyThemeOverlay_Toolbar2"

with:

  <style name="MyThemeOverlay_Toolbar2" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>


来源: stackexchange

问:
What is the default user and password for elasticsearch?
I have installed Elastic with Docker:

```<code>docker run -p 9200:9200 \
           -p 9300:9300 \
           -e "discovery.type=single-node" \
           docker.elastic.co/elasticsearch/elasticsearch:5.6.2
</code>```

But curl localhost:9200 fails with an authentication error:

{
  "error": {
    "root_cause": [
      {
        "type": "security_exception",
        "reason": "missing authentication token for REST request [/]",
        "header": {
          "WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
        }
      }
    ],
    "type": "security_exception",
    "reason": "missing authentication token for REST request [/]",
    "header": {
      "WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
    }
  },
  "status": 401
}
```

What is the default username/password combo for Elasticsearch?

答:
If you enabled basic x-pack security using xpack.security.enabled: true in your elasticsearch version 7.7(at the time of writing this answer), it will not have a default password(changeme) as it used to be in the old version of x-pack.

As mentioned in the getting started with security official doc

X-Pack security provides a built-in elastic superuser you can use to
start setting things up. This elastic user has full access to the
cluster, including all indices and data, so the elastic user does
not have a password set by default.

So you need to change the password of elastic, if you want to do it after the installation then follow setting password for built-in users in interactive mode guide

which requires you to run below command from elasticsearch bin folder.

```<code>bin/elasticsearch-setup-passwords interactive
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have installed Elastic with Docker:

docker run -p 9200:9200 \
           -p 9300:9300 \
           -e "discovery.type=single-node" \
           docker.elastic.co/elasticsearch/elasticsearch:5.6.2

But curl localhost:9200 fails with an authentication error:

{
  "error": {
    "root_cause": [
      {
        "type": "security_exception",
        "reason": "missing authentication token for REST request [/]",
        "header": {
          "WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
        }
      }
    ],
    "type": "security_exception",
    "reason": "missing authentication token for REST request [/]",
    "header": {
      "WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
    }
  },
  "status": 401
}

What is the default username/password combo for Elasticsearch?

Body:
If you enabled basic x-pack security using xpack.security.enabled: true in your elasticsearch version 7.7(at the time of writing this answer), it will not have a default password(changeme) as it used to be in the old version of x-pack.

As mentioned in the getting started with security official doc

X-Pack security provides a built-in elastic superuser you can use to
start setting things up. This elastic user has full access to the
cluster, including all indices and data, so the elastic user does
not have a password set by default.

So you need to change the password of elastic, if you want to do it after the installation then follow setting password for built-in users in interactive mode guide

which requires you to run below command from elasticsearch bin folder.

bin/elasticsearch-setup-passwords interactive


问:
How to get a list of the arguments a method is called with
How do I get a list of the arguments passed to a method, preferably one that I can iterate through?

For example something like

```<code>def foo(a,b,c)
  puts args.inspect
end

foo(1,2,3)
=> [1,2,3]
</code>```

?
Thanks!

答:
As others pointed out you can use the splat operator (*) for achieving what you want. If you don't like that, you can use the fact that Ruby methods can take a hash as last argument with nicer syntax.

```<code>def foo(args)
  raise ArgumentError if args.keys.any? { |arg| arg.nil? || !arg.kind_of?(Integer) }
end

puts foo(:a => 1, :b => 2, :c => "a") # raise an ArgumentError
</code>```

To access the arguments inside the method you have to use args[:a] etc.

ContentLicense: CC BY-SA 3.0

Body:
How do I get a list of the arguments passed to a method, preferably one that I can iterate through?

For example something like

def foo(a,b,c)
  puts args.inspect
end

foo(1,2,3)
=> [1,2,3]

?
Thanks!

Body:
As others pointed out you can use the splat operator (*) for achieving what you want. If you don't like that, you can use the fact that Ruby methods can take a hash as last argument with nicer syntax.

def foo(args)
  raise ArgumentError if args.keys.any? { |arg| arg.nil? || !arg.kind_of?(Integer) }
end

puts foo(:a => 1, :b => 2, :c => "a") # raise an ArgumentError

To access the arguments inside the method you have to use args[:a] etc.


问:
Dart method not called
I have the following code in dart/flutter project with BLoC

abstract class BasePage extends StatelessWidget {
  Widget get body;

  const BasePage({@required Key key}) : super(key: key);

  Bloc create(BuildContext context) {
    final dao = Provider.of<LessonsDao>(context, listen: false);
    return LessonListBloc(dao)..add(LoadListEvent());
  }

  @override
  Widget build(BuildContext context) {
    final blocs = createBlocs(context);
    return BlocProvider(
      lazy: false,
      create: (context) {
        return create(context);
      },
      child: Material(child: body),
    );
  }

}
```

<p>Now, when i want to change the create's function return type to <code>Bloc</code>, the subscriber widget, that is listens to the LessonsListLoaded that is <code>yield</code> in by the LessonListBloc, is not delivered to the <code>body</code> Widget:</p>

<pre class="lang-dart prettyprint-override"><code>Bloc create(BuildContext context) {
    final dao = Provider.of<LessonsDao>(context, listen: false);
    return LessonListBloc(dao)..add(LoadListEvent());
}
</code>```

答:
You depend on LessonListBloc

But BlocBuilder can't get it

The case is you narrowing the type in create function  LessonListBloc -> Bloc

this will work

```<code>create(...)
LessonListBloc create(...)
</code>```

this will not

```<code>Bloc create(...)
</code>```

Rewrite you code with types and analisator will pop types mismatch error

```<code>BlocProvider<LessonListBloc>(...
</code>```

Title: Dart method not called

Body:
I have the following code in dart/flutter project with BLoC

abstract class BasePage extends StatelessWidget {
  Widget get body;

  const BasePage({@required Key key}) : super(key: key);

  Bloc create(BuildContext context) {
    final dao = Provider.of<LessonsDao>(context, listen: false);
    return LessonListBloc(dao)..add(LoadListEvent());
  }

  @override
  Widget build(BuildContext context) {
    final blocs = createBlocs(context);
    return BlocProvider(
      lazy: false,
      create: (context) {
        return create(context);
      },
      child: Material(child: body),
    );
  }

}

Now, when i want to change the create's function return type to Bloc, the subscriber widget, that is listens to the LessonsListLoaded that is yield in by the LessonListBloc, is not delivered to the body Widget:

Bloc create(BuildContext context) {
    final dao = Provider.of<LessonsDao>(context, listen: false);
    return LessonListBloc(dao)..add(LoadListEvent());
}

Body:
You depend on LessonListBloc

But BlocBuilder can't get it

The case is you narrowing the type in create function  LessonListBloc -> Bloc

this will work

create(...)
LessonListBloc create(...)

this will not

Bloc create(...)

Rewrite you code with types and analisator will pop types mismatch error

BlocProvider<LessonListBloc>(...


问:
Value of Textbox gets reset
I tried to reuse the code for searching a value in a sheet, but I seem to do something wrong.
I have a Userform with a Textbox called "KD_ID" which i need to get the data that has been put into it and searched on a sheet ("Stammdaten") in Excel, then combine some cells next to it into one string. (KD_RNG -> Global Variable)

I use this code:

```<code> Private Sub KD_Search_Click()
        Dim KD_Search As String

       KD_Search = Packzettelinfo.KD_ID

        Set KD_RNG = ThisWorkbook.Sheets("Stammdaten").Range("A:A").Find(KD_Search, , xlValues, xlWhole)
        If Not KD_RNG Is Nothing Then
    Customer_Combination.Value = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Value

        Else
        MsgBox "Kundennummer konnte nicht gefunden werden (Fehler #002)"
        Packzettelinfo.KD_ID.SetFocus
        Exit Sub
        End If

    End Sub
</code>```

The thing is that I search in another sub for "PZ_ID" (Label PZ-Nr. in the screenshot below)
and the textbox "KD_ID" (Label KD-Nr.) is prefilled, before the next search.

So if I change "12345" to "23456",

```<code> Customer_Combination.Value = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Value
</code>```

will return nothing and KD_ID is reset to "12345"...

答:
I tried to simulate your application. (I cannot comment, so I am writing an answer).
The code below running well at least without any problem in my computer.
I have not found any big problem.
I included an alternative line with label Me.Customer_Combination.Caption, since you are not using it for input (as far as I understood), but just displaying the result. Note: Using by textbox the text of value property is the same.
I also commented out two lines, since they are not necessary.</p>

```<code>Dim KD_RNG As Range
Private Sub KD_Search_Click()
    Dim KD_Search As String
    KD_Search = Me.KD_ID.Text
    Set KD_RNG = ThisWorkbook.Sheets("Stammdaten").Range("A:A").Find(KD_Search, , xlValues, xlWhole)
    If Not KD_RNG Is Nothing Then
        Me.Customer_Combination.Caption = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Text
        Me.Customer_CombinationTextBox.Text = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Text
    Else
        MsgBox "Kundennummer konnte nicht gefunden werden (Fehler #002)"
        'Me.KD_ID.SetFocus
        'Exit Sub
    End If
End Sub
</code>```

Title: Value of Textbox gets reset

Body:
I tried to reuse the code for searching a value in a sheet, but I seem to do something wrong.
I have a Userform with a Textbox called "KD_ID" which i need to get the data that has been put into it and searched on a sheet ("Stammdaten") in Excel, then combine some cells next to it into one string. (KD_RNG -> Global Variable)

I use this code:

 Private Sub KD_Search_Click()
        Dim KD_Search As String

       KD_Search = Packzettelinfo.KD_ID

        Set KD_RNG = ThisWorkbook.Sheets("Stammdaten").Range("A:A").Find(KD_Search, , xlValues, xlWhole)
        If Not KD_RNG Is Nothing Then
    Customer_Combination.Value = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Value

        Else
        MsgBox "Kundennummer konnte nicht gefunden werden (Fehler #002)"
        Packzettelinfo.KD_ID.SetFocus
        Exit Sub
        End If

    End Sub

The thing is that I search in another sub for "PZ_ID" (Label PZ-Nr. in the screenshot below)
and the textbox "KD_ID" (Label KD-Nr.) is prefilled, before the next search.

So if I change "12345" to "23456",

 Customer_Combination.Value = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Value

will return nothing and KD_ID is reset to "12345"...

Body:
I tried to simulate your application. (I cannot comment, so I am writing an answer).
The code below running well at least without any problem in my computer.
I have not found any big problem.
I included an alternative line with label Me.Customer_Combination.Caption, since you are not using it for input (as far as I understood), but just displaying the result. Note: Using by textbox the text of value property is the same.
I also commented out two lines, since they are not necessary.

Dim KD_RNG As Range
Private Sub KD_Search_Click()
    Dim KD_Search As String
    KD_Search = Me.KD_ID.Text
    Set KD_RNG = ThisWorkbook.Sheets("Stammdaten").Range("A:A").Find(KD_Search, , xlValues, xlWhole)
    If Not KD_RNG Is Nothing Then
        Me.Customer_Combination.Caption = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Text
        Me.Customer_CombinationTextBox.Text = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Text
    Else
        MsgBox "Kundennummer konnte nicht gefunden werden (Fehler #002)"
        'Me.KD_ID.SetFocus
        'Exit Sub
    End If
End Sub


问:
JavaScript output of a string instead of undefined?
I'm getting undefined instead of a String on return of the answer - though it is the right correct characters being logged. How do I get it to output a definite string?</p>

```<code>var greet = function(name) {
   let  first = String(name. charAt(0). toUpperCase());
    let second = String(name.slice(1));

    console.log('Hello ' + first + second + '!');
    }
</code>```

答:
You forgot to return a value, so the return-value is undefined.

var greet = function(name) {
    let  first = String(name. charAt(0). toUpperCase());
    let second = String(name.slice(1));

    return 'Hello ' + first + second + '!';
}

console.log(greet('Gemma'));
```

Body:
I'm getting undefined instead of a String on return of the answer - though it is the right correct characters being logged. How do I get it to output a definite string?

var greet = function(name) {
   let  first = String(name. charAt(0). toUpperCase());
    let second = String(name.slice(1));

    console.log('Hello ' + first + second + '!');
    }


问:
UML help C# Design Principles
I have a problem understanding an UML below:

Specifically, what is the relationship between PersistentSet and ThirdPartyPersistentSet?
What is the relationship between PersistentObject and ThirdPartyPersistentSet?

Please note that the UML is from Agile Principles, Patterns, and Practices in C#
By Martin C. Robert, Martin Micah 2006. Chapter 10

Thanks in advance!

答:
The relationship between PersistentSet and ThirdPartyPersistentSet is an Aggregation, which means the PersistentSet contains one or more ThridPartyPersistenSet instances.  This is a "weak" relationship, meaning the instances of ThirdPartyPersistentSet can exist outside of the PersistentSet.

The relationship between PersistentObject and ThirdPartyPersistentSet is a Dependency, meaning basically ThirdPartyPersistentSet needs a PersistentObject to do it's work.

So, to translate this to code, your PersistentSet would contain something like this:

```<code>public class PersistentSet
{
    public List<ThirdPartyPersistentSet> Items { get; }
    ...
}
</code>```

And your ThirdPartyPersistentSet would look something like this:

```<code>public class ThirdPartyPersistentSet
{
    private PersistentObject _object;
    public ThirdPartyPersistentSet(PersistentObject obj)
    {
        _object = obj;
    }
    ...
}
</code>```

Title: UML help C# Design Principles

Body:
The relationship between PersistentSet and ThirdPartyPersistentSet is an Aggregation, which means the PersistentSet contains one or more ThridPartyPersistenSet instances.  This is a "weak" relationship, meaning the instances of ThirdPartyPersistentSet can exist outside of the PersistentSet.

The relationship between PersistentObject and ThirdPartyPersistentSet is a Dependency, meaning basically ThirdPartyPersistentSet needs a PersistentObject to do it's work.

So, to translate this to code, your PersistentSet would contain something like this:

public class PersistentSet
{
    public List<ThirdPartyPersistentSet> Items { get; }
    ...
}

And your ThirdPartyPersistentSet would look something like this:

public class ThirdPartyPersistentSet
{
    private PersistentObject _object;
    public ThirdPartyPersistentSet(PersistentObject obj)
    {
        _object = obj;
    }
    ...
}


问:
How do I exclude a directory when using `find`?
How do I exclude a specific directory when searching for *.js files using find?

```<code>find . -name '*.js'
</code>```

答:
find . \( -path '.**/.git' -o -path '.**/.hg' \) -prune -o -name '*.js' -print
```

<p>The example above finds all <code>*.js</code> files under the current directory, excluding folders <code>.git</code> and <code>.hg</code>, does not matter how deep these <code>.git</code> and <code>.hg</code> folders are.</p>

<p>Note: this also works:</p>

<pre class="lang-sh prettyprint-override"><code>find . \( -path '.*/.git' -o -path '.*/.hg' \) -prune -o -name '*.js' -print
</code>```

but I prefer the ** notation for consistency with some other tools which would be off topic here.

Body:
How do I exclude a specific directory when searching for *.js files using find?

find . -name '*.js'

Body:
find . \( -path '.**/.git' -o -path '.**/.hg' \) -prune -o -name '*.js' -print

The example above finds all *.js files under the current directory, excluding folders .git and .hg, does not matter how deep these .git and .hg folders are.

Note: this also works:

find . \( -path '.*/.git' -o -path '.*/.hg' \) -prune -o -name '*.js' -print

but I prefer the ** notation for consistency with some other tools which would be off topic here.


问:
MongoDb find opeartion on nested array having multiiple json object in it
I'm having dataset in which json consists of array having multiple json in it.

The objects in the array have 4 keys, out of which 1 is missing in some of them.

I want to get the documents where all the objects in an array are missing the key.

e.g, From these following documents:

```<code>{"test":1,desc:[{"price":1,"abc":"def"},{"price":2,"ac":"def"}]}
{"test":1,desc:[{"price":1,"abc":"def"},{"ac":"def"}]}
{"test":1,desc:[{"abc":"def"},{"ac":"def"}]}
</code>```

I want to match only the last document.

Thanks in advance..

答: Achieved that, just made a script where i used an array to store the price thing and then used .every method for price to be  undefined , it returned me the desired result which i want.</p>

Body:
I'm having dataset in which json consists of array having multiple json in it.

The objects in the array have 4 keys, out of which 1 is missing in some of them.

I want to get the documents where all the objects in an array are missing the key.

e.g, From these following documents:

{"test":1,desc:[{"price":1,"abc":"def"},{"price":2,"ac":"def"}]}
{"test":1,desc:[{"price":1,"abc":"def"},{"ac":"def"}]}
{"test":1,desc:[{"abc":"def"},{"ac":"def"}]}

I want to match only the last document.

Thanks in advance..


问:
Webscraping of product prices and specs
I'm new to the VBA world and i was trying to create a Excel file to get the cheapest price and name tag on a website. I've created one file that goes through the whole search list and gathers each product URL and places on a spreadsheet. My challenge now is in making this second code work. It starts out getting the information without any issues but then, after 10 or more URLs the macro gives a bug and it starts repeating the information on all the following cells.. Is there a way i can make the code run slower so it doesn't get into this problem?

I'll list here my code and a sample of the URLs im scraping..

here's the code i've been using:

```<code>Sub test()
Dim URL As String

Set ie = CreateObject("internetexplorer.application")

For i = 2 To 300

URL = Cells(i, 1).Value

ie.navigate URL
ie.Visible = False

Do While ie.busy And ie.readystate <> "readystate_complete"
DoEvents
Loop

Cells(i, 3) = ie.document.getElementsByTagName("h1")(0).innerText
Cells(i, 4) = ie.document.getElementsByTagName("strong")(0).innerText
Next i

ie.Quit

MsgBox "acabou"

End Sub
</code>```

<https://www.zoom.com.br/notebook/notebook-vaio-vjf157f11x-b0211s-intel-core-i5-8250u-15-6-8gb-ssd-256-gb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-samsung-chromebook-plus-intel-celeron-3965y-12-2-4gb-emmc-32-gb-chrome-os-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-xps-7390-intel-core-i7-10710u-13-3-16gb-ssd-512-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a5-intel-core-i7-8565u-15-6-8gb-hd-2-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-4gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-7580-a20-intel-core-i7-8550u-15-6-8gb-hd-1-tb-geforce-mx150-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i14-3480-u30-intel-core-i5-8265u-14-4gb-hd-1-tb-linux-8-geracao>
<https://www.zoom.com.br/notebook/macbook-pro-apple-muhn2bz-intel-core-i5-13-3-8gb-ssd-128-gb-tela-de-retina>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc150-amd-a4-9120-14-2gb-emmc-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-samsung-np930qaa-kw1br-intel-core-i7-8550u-13-3-8gb-ssd-256-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-acer-a515-51g-58vh-intel-core-i5-7200u-15-6-8gb-hd-1-tb-geforce-940mx>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc222-intel-celeron-dual-core-13-3-4gb-emmc-64-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-pt515-51-788a-intel-core-i7-9750h-15-6-32gb-ssd-1-tb-geforce-rtx-2070-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-53-53ak-intel-core-i5-7200u-15-6-4gb-hd-1-tb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-5584-m40-intel-core-i7-8565u-15-6-8gb-hd-2-tb-geforce-mx130-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-41g-r21b-amd-ryzen-5-2500u-15-6-8gb-hd-1-tb-radeon-535-windows-10>
<https://www.zoom.com.br/notebook/notebook-positivo-master-n2140-intel-core-i3-7020u-14-4gb-hd-500-gb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc101-intel-atom-14-1gb-ssd-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-8gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-acer-an515-51-77fh-intel-core-i7-7700hq-15-6-8gb-hd-1-tb-geforce-gtx-1050-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a2yp-intel-core-i5-8265u-15-6-4gb-optane-16-gb-hd-1-tb-windows-10>
<https://www.zoom.com.br/notebook/notebook-asus-g531gt-intel-core-i7-9750h-15-6-16gb-ssd-512-gb-geforce-gtx-1650-windows-10>
<https://www.zoom.com.br/notebook/notebook-vaio-fit-15s-intel-core-i3-7100u-15-6-4gb-hd-1-tb-windows-10-home>
<https://www.zoom.com.br/notebook/notebook-samsung-s50-intel-core-i7-7500u-13-3-8gb-ssd-256-gb-windows-10-style>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i3-7020u-15-6-4gb-ssd-120-gb-windows-10-7-geracao>```

答:
First of all:

Always declare all variables. To force this, always write Option Explicit as the first line in each module. This way, especially typos in variable names are immediately detected by the compiler.

Here is what to do about your problem:

IE is sometimes a real diva. For example, it doesn't like to have to process URLs in the same instance in quick succession. Therefore it is advisable to kick it out of memory and restart it for each new URL.

To restart it quickly, the deletion of coockies, the cache, etc. must not be set in its settings. Otherwise automation errors will occur.

Try this macro. With the given URLs it works:

```<code>Option Explicit

Sub test()

Dim URL As String
Dim ie As Object
Dim i As Long

  For i = 2 To 300

    If i > 14 Then
      ActiveWindow.SmallScroll down:=1
    End If

    URL = ActiveSheet.Cells(i, 1).Value

    Set ie = CreateObject("internetexplorer.application")
    ie.navigate URL
    ie.Visible = False
    Do While ie.readystate <> 4: DoEvents: Loop

    ActiveSheet.Cells(i, 3) = ie.document.getElementsByTagName("h1")(0).innerText
    ActiveSheet.Cells(i, 4) = ie.document.getElementsByTagName("strong")(0).innerText

    ie.Quit
    Set ie = Nothing
  Next i

  MsgBox "acabou"
End Sub
</code>```

Title: Webscraping of product prices and specs

Body:
I'm new to the VBA world and i was trying to create a Excel file to get the cheapest price and name tag on a website. I've created one file that goes through the whole search list and gathers each product URL and places on a spreadsheet. My challenge now is in making this second code work. It starts out getting the information without any issues but then, after 10 or more URLs the macro gives a bug and it starts repeating the information on all the following cells.. Is there a way i can make the code run slower so it doesn't get into this problem?

I'll list here my code and a sample of the URLs im scraping..

here's the code i've been using:

Sub test()
Dim URL As String

Set ie = CreateObject("internetexplorer.application")

For i = 2 To 300

URL = Cells(i, 1).Value

ie.navigate URL
ie.Visible = False

Do While ie.busy And ie.readystate <> "readystate_complete"
DoEvents
Loop

Cells(i, 3) = ie.document.getElementsByTagName("h1")(0).innerText
Cells(i, 4) = ie.document.getElementsByTagName("strong")(0).innerText
Next i

ie.Quit

MsgBox "acabou"

End Sub

<https://www.zoom.com.br/notebook/notebook-vaio-vjf157f11x-b0211s-intel-core-i5-8250u-15-6-8gb-ssd-256-gb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-samsung-chromebook-plus-intel-celeron-3965y-12-2-4gb-emmc-32-gb-chrome-os-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-xps-7390-intel-core-i7-10710u-13-3-16gb-ssd-512-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a5-intel-core-i7-8565u-15-6-8gb-hd-2-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-4gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-7580-a20-intel-core-i7-8550u-15-6-8gb-hd-1-tb-geforce-mx150-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i14-3480-u30-intel-core-i5-8265u-14-4gb-hd-1-tb-linux-8-geracao>
<https://www.zoom.com.br/notebook/macbook-pro-apple-muhn2bz-intel-core-i5-13-3-8gb-ssd-128-gb-tela-de-retina>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc150-amd-a4-9120-14-2gb-emmc-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-samsung-np930qaa-kw1br-intel-core-i7-8550u-13-3-8gb-ssd-256-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-acer-a515-51g-58vh-intel-core-i5-7200u-15-6-8gb-hd-1-tb-geforce-940mx>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc222-intel-celeron-dual-core-13-3-4gb-emmc-64-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-pt515-51-788a-intel-core-i7-9750h-15-6-32gb-ssd-1-tb-geforce-rtx-2070-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-53-53ak-intel-core-i5-7200u-15-6-4gb-hd-1-tb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-5584-m40-intel-core-i7-8565u-15-6-8gb-hd-2-tb-geforce-mx130-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-41g-r21b-amd-ryzen-5-2500u-15-6-8gb-hd-1-tb-radeon-535-windows-10>
<https://www.zoom.com.br/notebook/notebook-positivo-master-n2140-intel-core-i3-7020u-14-4gb-hd-500-gb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc101-intel-atom-14-1gb-ssd-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-8gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-acer-an515-51-77fh-intel-core-i7-7700hq-15-6-8gb-hd-1-tb-geforce-gtx-1050-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a2yp-intel-core-i5-8265u-15-6-4gb-optane-16-gb-hd-1-tb-windows-10>
<https://www.zoom.com.br/notebook/notebook-asus-g531gt-intel-core-i7-9750h-15-6-16gb-ssd-512-gb-geforce-gtx-1650-windows-10>
<https://www.zoom.com.br/notebook/notebook-vaio-fit-15s-intel-core-i3-7100u-15-6-4gb-hd-1-tb-windows-10-home>
<https://www.zoom.com.br/notebook/notebook-samsung-s50-intel-core-i7-7500u-13-3-8gb-ssd-256-gb-windows-10-style>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i3-7020u-15-6-4gb-ssd-120-gb-windows-10-7-geracao>

Body:
First of all:

Always declare all variables. To force this, always write Option Explicit as the first line in each module. This way, especially typos in variable names are immediately detected by the compiler.

Here is what to do about your problem:

IE is sometimes a real diva. For example, it doesn't like to have to process URLs in the same instance in quick succession. Therefore it is advisable to kick it out of memory and restart it for each new URL.

To restart it quickly, the deletion of coockies, the cache, etc. must not be set in its settings. Otherwise automation errors will occur.

Try this macro. With the given URLs it works:

Option Explicit

Sub test()

Dim URL As String
Dim ie As Object
Dim i As Long

  For i = 2 To 300

    If i > 14 Then
      ActiveWindow.SmallScroll down:=1
    End If

    URL = ActiveSheet.Cells(i, 1).Value

    Set ie = CreateObject("internetexplorer.application")
    ie.navigate URL
    ie.Visible = False
    Do While ie.readystate <> 4: DoEvents: Loop

    ActiveSheet.Cells(i, 3) = ie.document.getElementsByTagName("h1")(0).innerText
    ActiveSheet.Cells(i, 4) = ie.document.getElementsByTagName("strong")(0).innerText

    ie.Quit
    Set ie = Nothing
  Next i

  MsgBox "acabou"
End Sub


问:
Flex TitleWindow simulate drop and prevent dragging for a few seconds?
I wish while I am dragging and moving around TitleWindow instance and a specific event occure to simulate drop of the window, and not further moving been possible for a few seconds.

It is very unusual question but it will be more than handy each point to a solution

P.S: The whole idea is as follow: When I am dragging a TitleWindo instance with the mouse, and if the TitleWindow hit the border of it's parent container then to drop the TitleWindow, and not further moving is possible (simulating release mouse button). If I wish to move it again, then I should click the TitleWindow title again and grag it.

答:
@Yordan:

Let's see if I understand you correctly.  The demo below will "stop" a window from being drug offstage.  When you try to drag it off the top or left border, it will "simulate the release mouse button" as you requested.  The right and bottom border won't cause this to occur.

AutoDropTitleWindow.mxml:

```<code><?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="setup()">
<fx:Script>
    <![CDATA[
        import mx.managers.PopUpManager;

        private function setup() : void {
            var titleWin:MyTitleWindow = PopUpManager.createPopUp(this, MyTitleWindow, false) as MyTitleWindow;
            PopUpManager.centerPopUp(titleWin);
        }
    ]]>
</fx:Script>

</s:Application>
</code>```

MyTitleWindow.mxml:

```<code><?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300"
           creationComplete="setup()"
           >

<fx:Script>
    <![CDATA[
        import spark.events.TitleWindowBoundsEvent;

        private function setup(): void {
            addEventListener(TitleWindowBoundsEvent.WINDOW_MOVING, dragWatcher);
        }

        protected function dragWatcher(event:TitleWindowBoundsEvent):void
        {
            if (event.afterBounds.left < 0) {
                event.afterBounds.left = 0;
                dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP));
            } else if (event.afterBounds.right > systemManager.stage.stageWidth) {
                event.afterBounds.left = systemManager.stage.stageWidth - event.afterBounds.width;
            }
            if (event.afterBounds.top < 0) {
                event.afterBounds.top = 0;
                dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP));
            } else if (event.afterBounds.bottom > systemManager.stage.stageHeight) {
                event.afterBounds.top = systemManager.stage.stageHeight - event.afterBounds.height;
            }
        }

    ]]>
</fx:Script>

<s:Label x="10" y="10" text="X:"/>
<s:Label x="10" y="30" text="Y:"/>

<s:Label x="40" y="10" text="{this.x}"/>
<s:Label x="40" y="30" text="{this.y}"/>

</s:TitleWindow>
</code>```

Body:
@Yordan:

Let's see if I understand you correctly.  The demo below will "stop" a window from being drug offstage.  When you try to drag it off the top or left border, it will "simulate the release mouse button" as you requested.  The right and bottom border won't cause this to occur.

AutoDropTitleWindow.mxml:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="setup()">
<fx:Script>
    <![CDATA[
        import mx.managers.PopUpManager;

        private function setup() : void {
            var titleWin:MyTitleWindow = PopUpManager.createPopUp(this, MyTitleWindow, false) as MyTitleWindow;
            PopUpManager.centerPopUp(titleWin);
        }
    ]]>
</fx:Script>

</s:Application>

MyTitleWindow.mxml:

<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300"
           creationComplete="setup()"
           >

<fx:Script>
    <![CDATA[
        import spark.events.TitleWindowBoundsEvent;

        private function setup(): void {
            addEventListener(TitleWindowBoundsEvent.WINDOW_MOVING, dragWatcher);
        }

        protected function dragWatcher(event:TitleWindowBoundsEvent):void
        {
            if (event.afterBounds.left < 0) {
                event.afterBounds.left = 0;
                dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP));
            } else if (event.afterBounds.right > systemManager.stage.stageWidth) {
                event.afterBounds.left = systemManager.stage.stageWidth - event.afterBounds.width;
            }
            if (event.afterBounds.top < 0) {
                event.afterBounds.top = 0;
                dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP));
            } else if (event.afterBounds.bottom > systemManager.stage.stageHeight) {
                event.afterBounds.top = systemManager.stage.stageHeight - event.afterBounds.height;
            }
        }

    ]]>
</fx:Script>

<s:Label x="10" y="10" text="X:"/>
<s:Label x="10" y="30" text="Y:"/>

<s:Label x="40" y="10" text="{this.x}"/>
<s:Label x="40" y="30" text="{this.y}"/>

</s:TitleWindow>


问:
Finding biggest binary gap
I have to find the binary gap for an integer number.

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example: N = 1041
binary:10000010001
Result: 5 (5 zeros surrounded by ones)

Below is my code, although bin_no[22] is 1 but it never goes inside if statement.

```<code>def solution(N):
    bin_no = f'{N:32b}'
    print(len(bin_no))
    count = []

    for i in range(len(bin_no)):
        if bin_no[i] == 1:
            count[i] = 0
            j=i
            while(bin_no[j+1] != 1):
                count[i] +=1
                j +=1
            print (count[i])

print(solution(529))
</code>```

答:
use regex:

```<code>def solution(N):
    bin_no = f'{N:b}'
    pt= r"10+(?=1)"
    mtchs = re. findall(pt, bin_no)
    print(bin_no)
    print(mtchs)
    mx = max(mtchs,key=len)
    return mx.count('0')

print(solution(401))
</code>```

output:

110010001

['100', '1000']

3

Title: Finding biggest binary gap

Body:
I have to find the binary gap for an integer number.

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example: N = 1041
binary:10000010001
Result: 5 (5 zeros surrounded by ones)

Below is my code, although bin_no[22] is 1 but it never goes inside if statement.

def solution(N):
    bin_no = f'{N:32b}'
    print(len(bin_no))
    count = []

    for i in range(len(bin_no)):
        if bin_no[i] == 1:
            count[i] = 0
            j=i
            while(bin_no[j+1] != 1):
                count[i] +=1
                j +=1
            print (count[i])

print(solution(529))

Body:
use regex:

def solution(N):
    bin_no = f'{N:b}'
    pt= r"10+(?=1)"
    mtchs = re. findall(pt, bin_no)
    print(bin_no)
    print(mtchs)
    mx = max(mtchs,key=len)
    return mx.count('0')

print(solution(401))

output:

110010001

['100', '1000']

3


问:
How can I clean up the SSISDB?
When I set this up I overlooked the retention period. My database has become pretty large so I want to decrease it's size. If I simply change the retention period (it was 365) it causes issues with SSIS running my packages. I even changed it in small increments but the deletion statement would create locks which would prevent new jobs from running.

Any ideas how to work around this? I've thought about just creating a new SSISDB.

答:
Have found useful cleanup script from this article: SQL SERVER – Huge Size of SSISDB – Catalog Database SSISDB Cleanup Script

```<code>    USE SSISDB
    GO
    DELETE FROM [internal].[executions]
    GO
    DELETE FROM [internal].[executable_statistics]
    GO
    DELETE FROM [internal].[execution_component_phases]
    GO
    DELETE FROM [internal].[execution_data_statistics]
    GO
    DELETE FROM [internal].[execution_data_taps]
    GO
    DELETE FROM [internal].[execution_parameter_values]
    GO
    DELETE FROM [internal].[execution_property_override_values]
    GO
    DELETE FROM [internal].[extended_operation_info]
    GO
    DELETE FROM [internal].[operation_messages]
    GO
    DELETE FROM [internal].[event_messages]
    GO
    DELETE FROM [internal].[event_message_context]
    GO
    DELETE FROM [internal].[operation_os_sys_info]
    GO
    DELETE FROM [internal].[operation_permissions]
    GO
    DELETE FROM [internal].[validations]
    GO
</code>```

Also consider switching the database to simple recovery mode, but leave enough space for the log file.

Title: How can I clean up the SSISDB?

Body:
Have found useful cleanup script from this article: SQL SERVER – Huge Size of SSISDB – Catalog Database SSISDB Cleanup Script

    USE SSISDB
    GO
    DELETE FROM [internal].[executions]
    GO
    DELETE FROM [internal].[executable_statistics]
    GO
    DELETE FROM [internal].[execution_component_phases]
    GO
    DELETE FROM [internal].[execution_data_statistics]
    GO
    DELETE FROM [internal].[execution_data_taps]
    GO
    DELETE FROM [internal].[execution_parameter_values]
    GO
    DELETE FROM [internal].[execution_property_override_values]
    GO
    DELETE FROM [internal].[extended_operation_info]
    GO
    DELETE FROM [internal].[operation_messages]
    GO
    DELETE FROM [internal].[event_messages]
    GO
    DELETE FROM [internal].[event_message_context]
    GO
    DELETE FROM [internal].[operation_os_sys_info]
    GO
    DELETE FROM [internal].[operation_permissions]
    GO
    DELETE FROM [internal].[validations]
    GO

Also consider switching the database to simple recovery mode, but leave enough space for the log file.


问:
How do I get my serch path to a database inside my project to work when not hardcoded?
I've written an app that uses a database. The database is included in the project an the searchway works if you run it in Netbeans. If I try to run it independently it works with a hardcoded path to the database, but not with the following.

I'm having trouble with the following bit of code:

```<code>String Map = System.getProperty("user.dir");
String sokVag = Map + ("\\db\\MIBDB.FDB");

System.out.println(sokVag);

mibdb = new InfDB(sokVag);
new InloggningsFonster(mibdb).setVisible(true);
</code>```

as you can see I've printed the searchway for the database and when I hardcode it:

```<code>mibdb = new InfDB("C:\\Users\\...\\db\\MIBDB.FDB");
</code>```

Full print of searchway reads:

C:\Users\Carolin\Documents\NetBeansProjects\MIB\db\MIBDB.FDB

It works, but when I write:

```<code>mibdb = new InfDB(sokVag);
</code>```

It does not work. And the error message I get is:

Couldn't open Firebird database, check your path. Make sure to use .FDB in the end

Any ideas way?

答: Thank you for all your answers, for no apperent reason, after not using the computor for a while and not changing anything, it's working.</p>

Body:
I've written an app that uses a database. The database is included in the project an the searchway works if you run it in Netbeans. If I try to run it independently it works with a hardcoded path to the database, but not with the following.

I'm having trouble with the following bit of code:

String Map = System.getProperty("user.dir");
String sokVag = Map + ("\\db\\MIBDB.FDB");

System.out.println(sokVag);

mibdb = new InfDB(sokVag);
new InloggningsFonster(mibdb).setVisible(true);

as you can see I've printed the searchway for the database and when I hardcode it:

mibdb = new InfDB("C:\\Users\\...\\db\\MIBDB.FDB");

Full print of searchway reads:

C:\Users\Carolin\Documents\NetBeansProjects\MIB\db\MIBDB.FDB

It works, but when I write:

mibdb = new InfDB(sokVag);

It does not work. And the error message I get is:

Couldn't open Firebird database, check your path. Make sure to use .FDB in the end

Any ideas way?


问:
ReactJS TypeError: Cannot read property 'setState' of undefined even after binding in the constructor and also using the arrow function
I'm getting the error at line 116

```<code>checked={this.setState({selectedOption: "Male"})}
</code>```

If I remove that line, then I get the same error at the next line.

```<code>import React, { Component } from "react";
import { Document, Page } from "react-pdf";
import { pdfjs } from 'react-pdf';
import SplitPane, { Pane } from 'react-split-pane';
import { Button } from 'react-bootstrap';
import axios from 'axios';

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

export class TestPage extends React.Component{

    constructor(props){
      super(props);
      this.state = {
        numPages: null,
        pageNumber: 1,
        items: [],
        responses: [],
        color: '',
        name: "React",
        selectedOption: "Male",
      };
      this.onValueChange = this.onValueChange.bind(this);
      this.formSubmit = this.formSubmit.bind(this);
      this.goToPrevPage = this.goToPrevPage.bind(this);
      this.goToNextPage = this.goToNextPage.bind(this);
      this.onDocumentLoadSuccess = this.onDocumentLoadSuccess.bind(this);

    }

    componentDidMount(){
      axios.get("http://localhost:5000/getquestiondata")
        .then(
          (result) => {
            this.setState({
              items: result.data.number,
            });
        }).catch(error => {
          console.log("Error: ", error)
        })

    }

    onDocumentLoadSuccess = ({ numPages }) => {
      this.setState({ numPages: numPages });
    };

    formSubmit = event => {
      event.preventDefault();
      console.log(this.state.selectedOption);
    }

    onValueChange = event =>{
      this.setState({
        selectedOption: event.target.value
      });
    }

    goToPrevPage = () =>
      this.setState(state => ({ pageNumber: state.pageNumber - 1 }));
    goToNextPage = () =>
      this.setState(state => ({ pageNumber: state.pageNumber + 1 }));

    render() {
      const { pageNumber, numPages, items } = this.state;
      var quesNos = [];
      // var resp = [];

      for(var i = 0; i < items; i++){
        quesNos.push(i);
        // resp.push(i);
      }

      console.log("QuesNos: ",quesNos);
      return (
        <div>
          <h1 style={{textAlign: "center"}}>Online Test #1</h1>
          <hr />
          <SplitPane
            split="vertical"
            sizes={[50,50]}
            defaultSize={parseInt(localStorage.getItem('splitPos'), 10)}
            onChange={size => localStorage.setItem('splitPos', size)}
            style={{overflow: 'scroll'}}
          >
            <div style={{overflowY: 'scroll', height:'100%', overflowX: 'scroll'}}>
              <nav>
                <button onClick={this.goToPrevPage}>Prev</button>
                <button onClick={this.goToNextPage}>Next</button>
              </nav>

              <div>
                <Document
                  file={require('./sample.pdf')}
                  onLoadSuccess={this.onDocumentLoadSuccess}
                >
                  <Page pageNumber={pageNumber}/>
                </Document>
              </div>

              <p>
                Page {pageNumber} of {numPages}
              </p>
            </div>
            <div style={{overflowY: 'scroll', height:'100%', overflowX: 'scroll'}}>
              <form onSubmit={this.answerSubmit}>
                  {quesNos.map(function(qno){
                    return(
                      <div>
                        <div className="radio">
                          <label>
                            <input
                              type="radio"
                              value="Male"
                              checked={this.setState({selectedOption: "Male"})}
                              onChange={this.onValueChange}
                            />
                            Male
                          </label>
                        </div>
                        <div className="radio">
                          <label>
                            <input
                              type="radio"
                              value="Female"
                              checked={this.state.selectedOption === "Female"}
                              onChange={this.onValueChange}
                            />
                            Female
                          </label>
                        </div>
                        <div className="radio">
                          <label>
                            <input
                              type="radio"
                              value="Other"
                              checked={this.state.selectedOption === "Other"}
                              onChange={this.onValueChange}
                            />
                            Other
                          </label>
                        </div>
                        <div>
                          Selected option is : {this.state.selectedOption}
                        </div>
                        <Button variant="btn btn-primary" type="submit">Submit</Button>
                        </div>
                    );
                  })}
                <Button variant='primary' type="submit">Submit</Button>{' '}
              </form>
            </div>
          </SplitPane>
        </div>
      );
  }
}
</code>```

Any idea why this error happens and how to fix it?
Thanks!

答:
Two errors in your code

Your map function must be an arrow function to leverage this of the class/ or you use .bind for the map function

You must not setState directly in render. I assume you meant to compare state with checked attribute like checked={this.state.selectedOption === "Male"}

Updated code below

```<code>{quesNos.map((qno) => { // arrow function here
         return(
          <div>
            <div className="radio">
              <label>
                <input
                  type="radio"
                  value="Male"
                  checked={this.state.selectedOption === "Male"} // Comparison here
                  onChange={this.onValueChange}
                />
                Male
              </label>
            </div>
            <div className="radio">
              <label>
                <input
                  type="radio"
                  value="Female"
                  checked={this.state.selectedOption === "Female"}
                  onChange={this.onValueChange}
                />
                Female
              </label>
            </div>
            <div className="radio">
              <label>
                <input
                  type="radio"
                  value="Other"
                  checked={this.state.selectedOption === "Other"}
                  onChange={this.onValueChange}
                />
                Other
              </label>
            </div>
            <div>
              Selected option is : {this.state.selectedOption}
            </div>
            <Button variant="btn btn-primary" type="submit">Submit</Button>
            </div>
        );
      })}
</code>```

Body:
I'm getting the error at line 116

checked={this.setState({selectedOption: "Male"})}

If I remove that line, then I get the same error at the next line.

import React, { Component } from "react";
import { Document, Page } from "react-pdf";
import { pdfjs } from 'react-pdf';
import SplitPane, { Pane } from 'react-split-pane';
import { Button } from 'react-bootstrap';
import axios from 'axios';

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

export class TestPage extends React.Component{

    constructor(props){
      super(props);
      this.state = {
        numPages: null,
        pageNumber: 1,
        items: [],
        responses: [],
        color: '',
        name: "React",
        selectedOption: "Male",
      };
      this.onValueChange = this.onValueChange.bind(this);
      this.formSubmit = this.formSubmit.bind(this);
      this.goToPrevPage = this.goToPrevPage.bind(this);
      this.goToNextPage = this.goToNextPage.bind(this);
      this.onDocumentLoadSuccess = this.onDocumentLoadSuccess.bind(this);

    }

    componentDidMount(){
      axios.get("http://localhost:5000/getquestiondata")
        .then(
          (result) => {
            this.setState({
              items: result.data.number,
            });
        }).catch(error => {
          console.log("Error: ", error)
        })

    }

    onDocumentLoadSuccess = ({ numPages }) => {
      this.setState({ numPages: numPages });
    };

    formSubmit = event => {
      event.preventDefault();
      console.log(this.state.selectedOption);
    }

    onValueChange = event =>{
      this.setState({
        selectedOption: event.target.value
      });
    }

    goToPrevPage = () =>
      this.setState(state => ({ pageNumber: state.pageNumber - 1 }));
    goToNextPage = () =>
      this.setState(state => ({ pageNumber: state.pageNumber + 1 }));

    render() {
      const { pageNumber, numPages, items } = this.state;
      var quesNos = [];
      // var resp = [];

      for(var i = 0; i < items; i++){
        quesNos.push(i);
        // resp.push(i);
      }

      console.log("QuesNos: ",quesNos);
      return (

Online Test #1

          <SplitPane
            split="vertical"
            sizes={[50,50]}
            defaultSize={parseInt(localStorage.getItem('splitPos'), 10)}
            onChange={size => localStorage.setItem('splitPos', size)}
            style={{overflow: 'scroll'}}
          >

                <button onClick={this.goToPrevPage}>Prev</button>
                <button onClick={this.goToNextPage}>Next</button>

                <Document
                  file={require('./sample.pdf')}
                  onLoadSuccess={this.onDocumentLoadSuccess}
                >
                  <Page pageNumber={pageNumber}/>
                </Document>

                Page {pageNumber} of {numPages}

              <form onSubmit={this.answerSubmit}>
                  {quesNos.map(function(qno){
                    return(

                            <input
                              type="radio"
                              value="Male"
                              checked={this.setState({selectedOption: "Male"})}
                              onChange={this.onValueChange}
                            />
                            Male

                            <input
                              type="radio"
                              value="Female"
                              checked={this.state.selectedOption === "Female"}
                              onChange={this.onValueChange}
                            />
                            Female

                            <input
                              type="radio"
                              value="Other"
                              checked={this.state.selectedOption === "Other"}
                              onChange={this.onValueChange}
                            />
                            Other

                          Selected option is : {this.state.selectedOption}

                        <Button variant="btn btn-primary" type="submit">Submit</Button>

                    );
                  })}
                <Button variant='primary' type="submit">Submit</Button>{' '}
              </form>

          </SplitPane>

      );
  }
}

Any idea why this error happens and how to fix it?
Thanks!

Body:
Two errors in your code

Your map function must be an arrow function to leverage this of the class/ or you use .bind for the map function

You must not setState directly in render. I assume you meant to compare state with checked attribute like checked={this.state.selectedOption === "Male"}

Updated code below

{quesNos.map((qno) => { // arrow function here
         return(
          <div>
            <div className="radio">
              <label>
                <input
                  type="radio"
                  value="Male"
                  checked={this.state.selectedOption === "Male"} // Comparison here
                  onChange={this.onValueChange}
                />
                Male
              </label>
            </div>
            <div className="radio">
              <label>
                <input
                  type="radio"
                  value="Female"
                  checked={this.state.selectedOption === "Female"}
                  onChange={this.onValueChange}
                />
                Female
              </label>
            </div>
            <div className="radio">
              <label>
                <input
                  type="radio"
                  value="Other"
                  checked={this.state.selectedOption === "Other"}
                  onChange={this.onValueChange}
                />
                Other
              </label>
            </div>
            <div>
              Selected option is : {this.state.selectedOption}
            </div>
            <Button variant="btn btn-primary" type="submit">Submit</Button>
            </div>
        );
      })}


问:
expected type: java.lang.Double actual value: java.lang.Integer error in hibernate
I call the stored procedure in hibernate using createSqlQuery interface and i am using result transformer for getting the result as bean.
below is my code for that

```<code>Query query=sessionfactory.getCurrentSession().createSQLQuery("exec usp_ListUsersNotSubmitTimesheet :startDate,:endDate");
        query.setDate("startDate", formatter.parse(startDate));
        query.setDate("endDate", formatter.parse(endDate));
        query.setResultTransformer(Transformers.aliasToBean(UnSubmittedTimesheetBean.class));
List queryList=query.list();
</code>```

Some times sp result returns all integer values some times decimal values sometimes fixed.so i can't able to give the specific datatype.
so i  am getting the below exception

```<code>expected type: java.lang.Double actual value: java.lang.Integer
</code>```

How to resolve this error?

Any help will be greatly appreciated!!!

答:
I faced similar with complex SQL Joins for 2 fields. The exception shown on the console was

expected type: java.lang.Double actual value: java.math.BigDecimal

To solve this I have explicitly mapped the datatype for those fields using addScalar() method

```<code>session.createSQLQuery(query.toString())
                .addScalar("offerid", StandardBasicTypes.INTEGER)
                .addScalar("offervalue", StandardBasicTypes.DOUBLE)
</code>```

Body:
I call the stored procedure in hibernate using createSqlQuery interface and i am using result transformer for getting the result as bean.
below is my code for that

Query query=sessionfactory.getCurrentSession().createSQLQuery("exec usp_ListUsersNotSubmitTimesheet :startDate,:endDate");
        query.setDate("startDate", formatter.parse(startDate));
        query.setDate("endDate", formatter.parse(endDate));
        query.setResultTransformer(Transformers.aliasToBean(UnSubmittedTimesheetBean.class));
List queryList=query.list();

Some times sp result returns all integer values some times decimal values sometimes fixed.so i can't able to give the specific datatype.
so i  am getting the below exception

expected type: java.lang.Double actual value: java.lang.Integer

How to resolve this error?

Any help will be greatly appreciated!!!

Body:
I faced similar with complex SQL Joins for 2 fields. The exception shown on the console was

expected type: java.lang.Double actual value: java.math.BigDecimal

To solve this I have explicitly mapped the datatype for those fields using addScalar() method

session.createSQLQuery(query.toString())
                .addScalar("offerid", StandardBasicTypes.INTEGER)
                .addScalar("offervalue", StandardBasicTypes.DOUBLE)


问:
How to find the highest number of passenger of all round?
im a new problem solver. recently i came across this problem on codeforces website. i managed to get the two values required for each turn depending on the number of turn given by the user, but i cant find the highest number of passenger at stop out of all.</p>

```<code>#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int(turn);
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger=get_on-get_off;
        stops[i]=total_passenger;
    }
    for(int i=0;i<turn;i++){
        if(stops[i]>stops[i+1]){
            highest_total=stops[i];
        }
    }
    cout<<highest_total<<endl;
    return 0;
}
</code>```

答:
you can try using https://en.cppreference.com/w/cpp/algorithm/max_element
also you set the total passengers number to the difference between get off and get on and I think you should just add that difference, and to allocate memory for int* you use [] instead of ()</p>

```<code>#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int[turn];
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger+=get_on-get_off;
        stops[i]=total_passenger;
    }
    cout<<std::max_element(stops, stops + turn)<<endl;
}
</code>```

Body:
im a new problem solver. recently i came across this problem on codeforces website. i managed to get the two values required for each turn depending on the number of turn given by the user, but i cant find the highest number of passenger at stop out of all.

#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int(turn);
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger=get_on-get_off;
        stops[i]=total_passenger;
    }
    for(int i=0;i<turn;i++){
        if(stops[i]>stops[i+1]){
            highest_total=stops[i];
        }
    }
    cout<<highest_total<<endl;
    return 0;
}

Body:
you can try using https://en.cppreference.com/w/cpp/algorithm/max_element
also you set the total passengers number to the difference between get off and get on and I think you should just add that difference, and to allocate memory for int* you use [] instead of ()

#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int[turn];
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger+=get_on-get_off;
        stops[i]=total_passenger;
    }
    cout<<std::max_element(stops, stops + turn)<<endl;
}


问:
My statements come out as XXXXXX instead of the default value in a case statement. in verilog HDL
Edit:I forgot to add a i =i+1, the code works but it still doesn't work for the 0 value which is what I am trying to fix now.

I am trying to simulate a 3 digit 7segment led array so I'm taking in a constant input(in this case 1,2,3...) which is in binary and turning it into Binary-Coded-Decimal and then putting it in the module for a 7 segment to get the number to display.

My code keeps displaying  XXXXXXX instead of the 1111111 which is supposed to display as the default case statement. If anyone knows what might be causing that please let me know.

here is the code I am using to display the results

```<code>module m_top();

 reg clk =0;
reg[7:0] eight_bit_value;
wire[3:0] r_in;//ones
wire[3:0] r2_in;//tens
wire[3:0] r3_in;//hundreds
wire [6:0] w_led;
wire [6:0] w2_led;
wire [6:0] w3_led;

integer i;
always#5 clk=~clk;//clock
initial $display ("        gfedcba  gfedcba");
double_dabble segmentbits(clk,eight_bit_value,r_in,r2_in,r3_in);

initial begin
  eight_bit_value<= 8'd0; i = 0;
  #1 $display("%3d -> %b %b %b %b", i,eight_bit_value, w_led,w2_led,w3_led);
  for(i = 1; i <= 99; i = i + 1) begin
    #1000 eight_bit_value <= eight_bit_value + 1;
    #1000 $display("%3d ->%b %b %b %b", i, eight_bit_value,w_led,w2_led,w3_led);
  end
end

 //double_dabble segmentbits(clk,eight_bit_value,r_in,r2_in,r3_in);
 m_7segled m_7segled1(r_in, w_led);
 m_7segled m_7segled2(r2_in,w2_led);
 m_7segled m_7segled3(r3_in,w3_led);
</code>```

these are the 2 functions which I am using in my code

```<code>module double_dabble(input clk,
             input  [7:0] original_value,
             output reg[3:0] ones,
             output reg[3:0] tens,
             output reg[3:0] hundreds);

 reg[3:0] i=0;
  reg[19:0] shift_register =0;

  reg[3:0] temp_ones=0;
  reg[3:0] temp_tens=0;
  reg[3:0] temp_hundreds=0;

  reg[7:0]temp_original_value=0;

 always@(posedge clk)
    begin//as long as value doesnt change)
        if(i==0&(temp_original_value !=original_value))
        begin
        shift_register = 20'd0;
        temp_original_value = original_value;

        //setting up the register to be shifted
        temp_hundreds = shift_register[19:16];
        temp_tens =shift_register[15:12];
        temp_ones=shift_register[11:8];
        shift_register[7:0] = original_value;
        i=i+1;// I FORGOT TO ADD THIS , NOW I DID AND IT WORKS FOR >0 but not for 0;
         end
        if(i>0 & i<9)
        begin
        //check if they are greater than 5 if so add 3
        if(temp_hundreds>=5) temp_hundreds=temp_hundreds+3;
        if(temp_tens>=5) temp_tens=temp_tens+3;
        if(temp_ones>=5) temp_ones=temp_ones+3;

        shift_register[19:8] = {temp_hundreds,temp_tens,temp_ones};

        shift_register= shift_register<<1;

        temp_hundreds = shift_register[19:16];
        temp_tens =shift_register[15:12];
        temp_ones=shift_register[11:8];
        i=i+1;
        end
         if(i==9)
           begin
           i=0;

           hundreds = temp_hundreds;
           tens=temp_tens;
           ones=temp_ones;
           end
        end
endmodule
</code>```

and the sevensegment module is this:

```<code>module m_7segled (w_in,r_led);

    input wire [3:0] w_in;
    output reg [6:0] r_led;

    always@(*) begin
        case (w_in%10)
            4'd0 : r_led <= 7'b1000000;
            4'd1 : r_led <= 7'b1111001;
            4'd2 : r_led <= 7'b0100100;
            4'd3 : r_led <= 7'b0110000;
            4'd4 : r_led <= 7'b0011001;
            4'd5 : r_led <= 7'b0010010;
            4'd6 : r_led <= 7'b0000010;
            4'd7 : r_led <= 7'b1011000;
            4'd8 : r_led <= 7'b0000000;
            4'd9 : r_led <= 7'b0010000;
            default : r_led <= 7'b1111111;
        endcase
    end
endmodule
</code>```

答:
Your program is full of verilog and programming mistakes. There are few I spotted:

operator & is not the same as operator && in if statements. It works differently and has different precedence order. So, your if statements just do not work correctly in any case. You used & in all conditional statements.

in your statement i>0 & i<9 should look like i >= 0 && i < 9. missing >= caused yor x issue (in combination with #1).

you incorrectly used blocking assignments in the sequential logic of double_dabble. Some of them should be non-blocking.

you incorrectly used variable initialization. This might work in simulation and some fpga but does not work in real world. You need a reset.

you incorrectly used non-blocking assignment in combinational logic of m_7segled they all should be blocking.

answering the comment: About reg initialization.

Using statements like reg[3:0] i=0; though is legal in verilog, it can give you synthesis problems. They could be synthesized correctly in some fpga or emulation systems but will not be synthesized by schematic synthesis tools. So, in general you should use a reset signal and initialize those vars with a reset, something like the following:

```<code>always @(posedge clk) begin
    if (reset)
       i <= 0;
    else
       i <= i + 1;
end
</code>```

Body:
Edit:I forgot to add a i =i+1, the code works but it still doesn't work for the 0 value which is what I am trying to fix now.

I am trying to simulate a 3 digit 7segment led array so I'm taking in a constant input(in this case 1,2,3...) which is in binary and turning it into Binary-Coded-Decimal and then putting it in the module for a 7 segment to get the number to display.

My code keeps displaying  XXXXXXX instead of the 1111111 which is supposed to display as the default case statement. If anyone knows what might be causing that please let me know.

here is the code I am using to display the results

module m_top();

 reg clk =0;
reg[7:0] eight_bit_value;
wire[3:0] r_in;//ones
wire[3:0] r2_in;//tens
wire[3:0] r3_in;//hundreds
wire [6:0] w_led;
wire [6:0] w2_led;
wire [6:0] w3_led;

integer i;
always#5 clk=~clk;//clock
initial $display ("        gfedcba  gfedcba");
double_dabble segmentbits(clk,eight_bit_value,r_in,r2_in,r3_in);

initial begin
  eight_bit_value<= 8'd0; i = 0;
  #1 $display("%3d -> %b %b %b %b", i,eight_bit_value, w_led,w2_led,w3_led);
  for(i = 1; i <= 99; i = i + 1) begin
    #1000 eight_bit_value <= eight_bit_value + 1;
    #1000 $display("%3d ->%b %b %b %b", i, eight_bit_value,w_led,w2_led,w3_led);
  end
end

 //double_dabble segmentbits(clk,eight_bit_value,r_in,r2_in,r3_in);
 m_7segled m_7segled1(r_in, w_led);
 m_7segled m_7segled2(r2_in,w2_led);
 m_7segled m_7segled3(r3_in,w3_led);

these are the 2 functions which I am using in my code

module double_dabble(input clk,
             input  [7:0] original_value,
             output reg[3:0] ones,
             output reg[3:0] tens,
             output reg[3:0] hundreds);

 reg[3:0] i=0;
  reg[19:0] shift_register =0;

  reg[3:0] temp_ones=0;
  reg[3:0] temp_tens=0;
  reg[3:0] temp_hundreds=0;

  reg[7:0]temp_original_value=0;

 always@(posedge clk)
    begin//as long as value doesnt change)
        if(i==0&(temp_original_value !=original_value))
        begin
        shift_register = 20'd0;
        temp_original_value = original_value;

        //setting up the register to be shifted
        temp_hundreds = shift_register[19:16];
        temp_tens =shift_register[15:12];
        temp_ones=shift_register[11:8];
        shift_register[7:0] = original_value;
        i=i+1;// I FORGOT TO ADD THIS , NOW I DID AND IT WORKS FOR >0 but not for 0;
         end
        if(i>0 & i<9)
        begin
        //check if they are greater than 5 if so add 3
        if(temp_hundreds>=5) temp_hundreds=temp_hundreds+3;
        if(temp_tens>=5) temp_tens=temp_tens+3;
        if(temp_ones>=5) temp_ones=temp_ones+3;

        shift_register[19:8] = {temp_hundreds,temp_tens,temp_ones};

        shift_register= shift_register<<1;

        temp_hundreds = shift_register[19:16];
        temp_tens =shift_register[15:12];
        temp_ones=shift_register[11:8];
        i=i+1;
        end
         if(i==9)
           begin
           i=0;

           hundreds = temp_hundreds;
           tens=temp_tens;
           ones=temp_ones;
           end
        end
endmodule

and the sevensegment module is this:

module m_7segled (w_in,r_led);

    input wire [3:0] w_in;
    output reg [6:0] r_led;

    always@(*) begin
        case (w_in%10)
            4'd0 : r_led <= 7'b1000000;
            4'd1 : r_led <= 7'b1111001;
            4'd2 : r_led <= 7'b0100100;
            4'd3 : r_led <= 7'b0110000;
            4'd4 : r_led <= 7'b0011001;
            4'd5 : r_led <= 7'b0010010;
            4'd6 : r_led <= 7'b0000010;
            4'd7 : r_led <= 7'b1011000;
            4'd8 : r_led <= 7'b0000000;
            4'd9 : r_led <= 7'b0010000;
            default : r_led <= 7'b1111111;
        endcase
    end
endmodule

Body:
Your program is full of verilog and programming mistakes. There are few I spotted:

operator & is not the same as operator && in if statements. It works differently and has different precedence order. So, your if statements just do not work correctly in any case. You used & in all conditional statements.

in your statement i>0 & i<9 should look like i >= 0 && i < 9. missing >= caused yor x issue (in combination with #1).

you incorrectly used blocking assignments in the sequential logic of double_dabble. Some of them should be non-blocking.

you incorrectly used variable initialization. This might work in simulation and some fpga but does not work in real world. You need a reset.

you incorrectly used non-blocking assignment in combinational logic of m_7segled they all should be blocking.

answering the comment: About reg initialization.

Using statements like reg[3:0] i=0; though is legal in verilog, it can give you synthesis problems. They could be synthesized correctly in some fpga or emulation systems but will not be synthesized by schematic synthesis tools. So, in general you should use a reset signal and initialize those vars with a reset, something like the following:

always @(posedge clk) begin
    if (reset)
       i <= 0;
    else
       i <= i + 1;
end


问:
ActiveRecord Nested Arrays
Do any methods / patterns exist for sanitizing an array of arrays when using it as SQL input?

Looking to implement the following style of query in ActiveRecord:

SELECT *
FROM "addresses"
WHERE ("addresses"."city", "addresses"."state", "addresses"."country") IN (
  ('Juneau', 'AK', 'US'),
  ('Albany', 'NY', 'US'),
  ...
)
```

<p>For example:</p>

<pre class="lang-rb prettyprint-override"><code>searches = [
  ['Juneau', 'AK', 'US'],
  ['Albany', 'NY', 'US'],
]

searches_sql = searches.map do |search|
  "(#{search.map { |query| Address.connection.quote(query) }.join(', ')})"
end.join(', ')
Address.where(%(("addresses"."city", "addresses"."state", "addresses"."country") IN (#{searches_sql})))
</code>```

Works but relies on some manual connection escaping that doesn't seem ideal (and isn't easily generalized beyond this scope).

答:
ActiveRecord does not actually have a built in way to construct a WHERE columns IN values query.

But you can do it with Arel:

```<code>class Address
  def self.search(sets)
    where(
      Arel::Nodes::In.new(
        [:city, :state, :country].map { |c| arel_table[c] },
        sets.map do |set|
          Arel::Nodes::Grouping.new(
            set.map {|value| Arel::Nodes.build_quoted(value)}
          )
        end
      )
    )
  end
end
</code>```

Title: ActiveRecord Nested Arrays

Body:
Do any methods / patterns exist for sanitizing an array of arrays when using it as SQL input?

Looking to implement the following style of query in ActiveRecord:

SELECT *
FROM "addresses"
WHERE ("addresses"."city", "addresses"."state", "addresses"."country") IN (
  ('Juneau', 'AK', 'US'),
  ('Albany', 'NY', 'US'),
  ...
)

For example:

searches = [
  ['Juneau', 'AK', 'US'],
  ['Albany', 'NY', 'US'],
]

searches_sql = searches.map do |search|
  "(#{search.map { |query| Address.connection.quote(query) }.join(', ')})"
end.join(', ')
Address.where(%(("addresses"."city", "addresses"."state", "addresses"."country") IN (#{searches_sql})))

Works but relies on some manual connection escaping that doesn't seem ideal (and isn't easily generalized beyond this scope).

Body:
ActiveRecord does not actually have a built in way to construct a WHERE columns IN values query.

But you can do it with Arel:

class Address
  def self.search(sets)
    where(
      Arel::Nodes::In.new(
        [:city, :state, :country].map { |c| arel_table[c] },
        sets.map do |set|
          Arel::Nodes::Grouping.new(
            set.map {|value| Arel::Nodes.build_quoted(value)}
          )
        end
      )
    )
  end
end


问:
Convert and parse json string to key value pairs using NewtonSoft
Trying to convert a json string to key value pairs using Newtonsoft but no luck so far.

Response from the API:

```<code>var response = @"{'result':{'0199 - B344EE33':
{
     '6400_00260100':{'1':[{'val':336688}]},
     '6400_00462500':{'1':[{'val':null}]},
     '6800_00832A00':{'1':[{'low':3000,'high':3000,'val':3000}]},
     '6800_008AA200':{'1':[{'low':0,'high':null,'val':0}]}
}}}";
</code>```

Result I want is a new object of key value pairs:

```<code>{
    "6400_00260100" : 336688,
    "6400_00462500" : null,
    "6800_00832A00" : 3000,
    "6800_008AA200" : 0
}
</code>```

In the response the result will always be the first and only prop. In the next level the code 0199 - B344EE33 can change but there will be only one prop in this level so we can always take the first one. Then in the last level we always need the val property.

What I have is the following but for getting the key value pairs in a clean way I got stuck:

```<code>var json = JObject.Parse(response);
var result = json["result"].First;
var path = result.Path;
</code>```

UPDATE

```<code>        var jObjectResult = new JObject();

        var response = @"{'result':{'0199 - B344EE33':
                        {
                            '6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
                            '6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
                            '6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
                            '6800_08822B00':{'1':[{'val':'SMA'}]},
                            '6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
                        }}}";

        var json = JObject.Parse(response);
        var json_serial = json["result"].First.Children<JObject>().ToList()[0];

        foreach(var token in json_serial)
        {
            var tokenKey = token.Key;
            var tokenVal = token.Value.SelectToken("$.1[0].val");

            jObjectResult.Add(tokenKey, tokenVal);
        }
</code>```

答:
At the end with some pointers form @Brian Rogers I came with the following solution:</p>

```<code>    // Arrange
    var response = @"{'result':{'0199 - B344EE33':
                    {
                        '6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
                        '6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
                        '6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
                        '6800_08822B00':{'1':[{'val':'SMA'}]},
                        '6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
                    }}}";

    // Act
    var json = JObject.Parse(response);
    var json_serial = (JProperty)json["result"].First();
    var jObjectResult = new JObject(
        json_serial.Value.Select(p =>
        {
            return new JProperty(
                ((JProperty)p).Name,
                p.First.SelectToken("$.1[0].val")
            );
        }));
</code>```

Body:
Trying to convert a json string to key value pairs using Newtonsoft but no luck so far.

Response from the API:

var response = @"{'result':{'0199 - B344EE33':
{
     '6400_00260100':{'1':[{'val':336688}]},
     '6400_00462500':{'1':[{'val':null}]},
     '6800_00832A00':{'1':[{'low':3000,'high':3000,'val':3000}]},
     '6800_008AA200':{'1':[{'low':0,'high':null,'val':0}]}
}}}";

Result I want is a new object of key value pairs:

{
    "6400_00260100" : 336688,
    "6400_00462500" : null,
    "6800_00832A00" : 3000,
    "6800_008AA200" : 0
}

In the response the result will always be the first and only prop. In the next level the code 0199 - B344EE33 can change but there will be only one prop in this level so we can always take the first one. Then in the last level we always need the val property.

What I have is the following but for getting the key value pairs in a clean way I got stuck:

var json = JObject.Parse(response);
var result = json["result"].First;
var path = result.Path;

UPDATE

        var jObjectResult = new JObject();

        var response = @"{'result':{'0199 - B344EE33':
                        {
                            '6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
                            '6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
                            '6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
                            '6800_08822B00':{'1':[{'val':'SMA'}]},
                            '6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
                        }}}";

        var json = JObject.Parse(response);
        var json_serial = json["result"].First.Children<JObject>().ToList()[0];

        foreach(var token in json_serial)
        {
            var tokenKey = token.Key;
            var tokenVal = token.Value.SelectToken("$.1[0].val");

            jObjectResult.Add(tokenKey, tokenVal);
        }

Body:
At the end with some pointers form @Brian Rogers I came with the following solution:

    // Arrange
    var response = @"{'result':{'0199 - B344EE33':
                    {
                        '6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
                        '6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
                        '6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
                        '6800_08822B00':{'1':[{'val':'SMA'}]},
                        '6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
                    }}}";

    // Act
    var json = JObject.Parse(response);
    var json_serial = (JProperty)json["result"].First();
    var jObjectResult = new JObject(
        json_serial.Value.Select(p =>
        {
            return new JProperty(
                ((JProperty)p).Name,
                p.First.SelectToken("$.1[0].val")
            );
        }));


问:
list to csv file - AttributeError: 'str' object has no attribute 'writer'
I would like to convert the following list

```<code>csv_list[:5]
[['s01_l01/1_1.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_1.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_2.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_3.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_4.png', '1', '7C2 4698', '7C24698']]
</code>```

to a csv file.

I used this code:

```<code>with open('/content/gdrive/My Drive/data/2017-IWT4S-CarsReId_LP-dataset/TrainValV1.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(csv_list)
</code>```

And got this error:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-65-30765791e5c8> in <module>()
      1 with open('/content/gdrive/My Drive/data/2017-IWT4S-CarsReId_LP-dataset/TrainValV1.csv', 'w', newline='') as file:
----> 2     writer = csv.writer(file)
      3     writer.writerows(csv_list)

AttributeError: 'str' object has no attribute 'writer'
</code>```

What do I have to change?

Thanks a lot!

答:
This must mean that csv in line two in that error output is an object of type str, as the error message says. If you post the full code, which shows how you define csv, we could narrow down why that is. Likely you define something else, like csv = '<some string>' sometime after you import csv.

I'll expand a bit about when you usually see AttributeErrors in Python, so that you might be able to spot this type of thing quicker in the future. You see that error when you have a line like:

```<code># will error if x does not actually have this attribute
x.some_attribute_y
# This line is basically equivalent to the above line:
getattr(x, 'some_attribute_y')
</code>```

The error message will say:

```<code>AttributeError: '<type of object x>' object has no attribute 'some_attribute_y'
</code>```

Body:
I would like to convert the following list

csv_list[:5]
[['s01_l01/1_1.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_1.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_2.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_3.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_4.png', '1', '7C2 4698', '7C24698']]

to a csv file.

I used this code:

with open('/content/gdrive/My Drive/data/2017-IWT4S-CarsReId_LP-dataset/TrainValV1.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(csv_list)

And got this error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-65-30765791e5c8> in <module>()
      1 with open('/content/gdrive/My Drive/data/2017-IWT4S-CarsReId_LP-dataset/TrainValV1.csv', 'w', newline='') as file:
----> 2     writer = csv.writer(file)
      3     writer.writerows(csv_list)

AttributeError: 'str' object has no attribute 'writer'

What do I have to change?

Thanks a lot!

Body:
This must mean that csv in line two in that error output is an object of type str, as the error message says. If you post the full code, which shows how you define csv, we could narrow down why that is. Likely you define something else, like csv = '<some string>' sometime after you import csv.

I'll expand a bit about when you usually see AttributeErrors in Python, so that you might be able to spot this type of thing quicker in the future. You see that error when you have a line like:

# will error if x does not actually have this attribute
x.some_attribute_y
# This line is basically equivalent to the above line:
getattr(x, 'some_attribute_y')

The error message will say:

AttributeError: '<type of object x>' object has no attribute 'some_attribute_y'


问:
SignUp rest service is not working when rest call is made from Android Application
I create project in android studio and use Volley for signup and login

I can login in my android app with email and password that i insert in database with phpMyadmin But signup in android doesn't insert email and password to database!

this is my LoginDialog.java code :

public class LoginDialog extends DialogFragment {
    EditText edtEmail, edtPass;
    Button btnSignup, btnLogin;
    OnSignupClicked onSignupClicked;
    View view;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        view = LayoutInflater.from(getContext()).inflate(R.layout.login_dialog, null);
        setupViews();
        builder.setView(view);
        return builder.create();
    }

    private void setupViews() {
        btnSignup = (Button) view.findViewById(R.id.btn_loginDialog_signup);
        edtEmail = (EditText) view.findViewById(R.id.edt_loginDialog_email);
        edtPass = (EditText) view.findViewById(R.id.edt_loginDialog_pass);
        btnLogin = (Button) view.findViewById(R.id.btn_loginDialog_login);
        btnSignup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = edtEmail.getText().toString();
                String pass = edtPass.getText().toString();
                userSignup(email, pass);

            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login(edtEmail.getText().toString(), edtPass.getText().toString());
            }
        });

    }

    private void login(final String myEmail, final String pass) {
        String url = "http://192.168.1.101/login.php";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.equals("not found")) {
                    Toast.makeText(getContext(), "پست الکترونیک یا رمز عبور اشتباه است", Toast.LENGTH_SHORT).show();
                } else {
                    onSignupClicked.onClicked(response);
                    dismiss();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Log.i("LOG", "onErrorResponse: " + error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("email", myEmail);
                params.put("pass", pass);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);
    }

    public void setOnSignupClicked(OnSignupClicked onSignupClicked) {
        this.onSignupClicked = onSignupClicked;
    }

    private void userSignup(final String email, final String pass) {
        String url = "http://192.168.1.101/signup.php";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("LOG", "onResponse: "+response);
                onSignupClicked.onClicked(response);
                dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("LOG", "onErrorResponse: " + error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("email", email);
                params.put("pass", pass);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);
    }

    public interface OnSignupClicked {
        void onClicked(String email);
    }
}```
</div>
</div>
</p>

<p>And this my signup.php code :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
include "connect.php";
$email = $_POST["email"];
$pass = $_POST["pass"];
$query = "INSERT INTO user(email,pass)VALUES (:email,:pass)";
$res=$connect->prepare($query);
$res->bindParam(":email",$email);
$res->bindParam(":pass",$pass);
$res->execute();

if($res){
    echo $email;
}else{
    echo "error";
}</code>```

Please guide me how can i fix signup to connect with database :X

答:
Your server side code had bugs.  I fixed it</p>

```<code><?php
$connection = mysqli_connect('localhost','root','password','user') or die('connecition err');

$email = $_POST['email'];
$pass = $_POST['pass'];
$sql = "INSERT INTO `user` (`email`,`pass`) VALUES ('$email','$pass')";

$query = mysqli_query($connection,$sql);

if($query){
    echo $email;
}else{
    echo "no";
}

?>
</code>```

Body:
I create project in android studio and use Volley for signup and login

I can login in my android app with email and password that i insert in database with phpMyadmin But signup in android doesn't insert email and password to database!

this is my LoginDialog.java code :

public class LoginDialog extends DialogFragment {
    EditText edtEmail, edtPass;
    Button btnSignup, btnLogin;
    OnSignupClicked onSignupClicked;
    View view;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        view = LayoutInflater.from(getContext()).inflate(R.layout.login_dialog, null);
        setupViews();
        builder.setView(view);
        return builder.create();
    }

    private void setupViews() {
        btnSignup = (Button) view.findViewById(R.id.btn_loginDialog_signup);
        edtEmail = (EditText) view.findViewById(R.id.edt_loginDialog_email);
        edtPass = (EditText) view.findViewById(R.id.edt_loginDialog_pass);
        btnLogin = (Button) view.findViewById(R.id.btn_loginDialog_login);
        btnSignup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = edtEmail.getText().toString();
                String pass = edtPass.getText().toString();
                userSignup(email, pass);

            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login(edtEmail.getText().toString(), edtPass.getText().toString());
            }
        });

    }

    private void login(final String myEmail, final String pass) {
        String url = "http://192.168.1.101/login.php";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.equals("not found")) {
                    Toast.makeText(getContext(), "پست الکترونیک یا رمز عبور اشتباه است", Toast.LENGTH_SHORT).show();
                } else {
                    onSignupClicked.onClicked(response);
                    dismiss();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Log.i("LOG", "onErrorResponse: " + error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("email", myEmail);
                params.put("pass", pass);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);
    }

    public void setOnSignupClicked(OnSignupClicked onSignupClicked) {
        this.onSignupClicked = onSignupClicked;
    }

    private void userSignup(final String email, final String pass) {
        String url = "http://192.168.1.101/signup.php";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("LOG", "onResponse: "+response);
                onSignupClicked.onClicked(response);
                dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("LOG", "onErrorResponse: " + error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("email", email);
                params.put("pass", pass);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);
    }

    public interface OnSignupClicked {
        void onClicked(String email);
    }
}

And this my signup.php code :

<?php
include "connect.php";
$email = $_POST["email"];
$pass = $_POST["pass"];
$query = "INSERT INTO user(email,pass)VALUES (:email,:pass)";
$res=$connect->prepare($query);
$res->bindParam(":email",$email);
$res->bindParam(":pass",$pass);
$res->execute();

if($res){
    echo $email;
}else{
    echo "error";
}

Please guide me how can i fix signup to connect with database :X

Body:
Your server side code had bugs.  I fixed it

<?php
$connection = mysqli_connect('localhost','root','password','user') or die('connecition err');

$email = $_POST['email'];
$pass = $_POST['pass'];
$sql = "INSERT INTO `user` (`email`,`pass`) VALUES ('$email','$pass')";

$query = mysqli_query($connection,$sql);

if($query){
    echo $email;
}else{
    echo "no";
}

?>