问:
Why could this JSON.Net FileLoadException be conditional
I get this runtime exception from

```<code>var names = MeasureName.Empty.GetAll();
if (null == names)
    Console.WriteLine("No Measure Names found.");
else
{
    Console.WriteLine(JsonConvert.SerializeObject(names));
}
</code>```

but not this

```<code>var groups = MeasureGroup.Empty.GetAll();
if (null == groups)
    Console.WriteLine("No Measure Groups found.");
else
{
    Console.WriteLine(JsonConvert.SerializeObject(groups));
}
</code>```

even though neither result is null. This result is repeatable. When the bottom code runs there's no exception, followed by the top section; exception.

I assume the issue is with MeasureName, but not MeasureGroup, both are classes in a reference project. I don't understand why I would get this exception though. Clearly the JSON.Net dll can be loaded, as it works for MeasureGroup, so why the "claim" that the File can't be loaded?

Update, full Exception:

```<code>System.IO.FileLoadException was unhandled
  HResult=-2146234304
  Message=Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
  Source=mscorlib
  FileName=Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
  FusionLog==== Pre-bind state information ===
LOG: DisplayName = Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
 (Fully-specified)
LOG: Appbase = file:///.../bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : DataLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: ..\bin\Debug\UpdateData.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
LOG: Attempting download of new URL file:///C:/.../bin/Debug/Newtonsoft.Json.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

  StackTrace:
       at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
       at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
       at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
       at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
       at System.Reflection.CustomAttribute.IsCustomAttributeDefined(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Int32 attributeCtorToken, Boolean mustBeInheritable)
       at System.Reflection.CustomAttribute.IsDefined(RuntimePropertyInfo property, RuntimeType caType)
       at System.Reflection.RuntimePropertyInfo.IsDefined(Type attributeType, Boolean inherit)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.GetSerializableMembers(Type objectType)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteStartArray(JsonWriter writer, Object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value)
       at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)
       at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)
       at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Formatting formatting, JsonSerializerSettings settings)
       at Newtonsoft.Json.JsonConvert.SerializeObject(Object value)
       at UpdateData.Program.Queries() in ..\Program.cs:line 81
       at UpdateData.Program.Main(String[] args) in ..\Program.cs:line 27
  InnerException:
</code>```

答:
I got the dll versions to match all across and it works now.

I thought I had the same version between my class library project and console app project because I had uninstalled and reinstalled using the package manager (which was ok) then selected the latest version of the dll for the console project using the package manager, just searching Assemblies for json and selecting my framework. That was my downfall. I don't know why 6.0 was the latest offered, see below:

If I just browsed my project/package directory I could just add the 9.0.1 that I was using there, then the serialization in the console project worked.
Thanks for the link @dbc

Body:
I get this runtime exception from

var names = MeasureName.Empty.GetAll();
if (null == names)
    Console.WriteLine("No Measure Names found.");
else
{
    Console.WriteLine(JsonConvert.SerializeObject(names));
}

but not this

var groups = MeasureGroup.Empty.GetAll();
if (null == groups)
    Console.WriteLine("No Measure Groups found.");
else
{
    Console.WriteLine(JsonConvert.SerializeObject(groups));
}

even though neither result is null. This result is repeatable. When the bottom code runs there's no exception, followed by the top section; exception.

I assume the issue is with MeasureName, but not MeasureGroup, both are classes in a reference project. I don't understand why I would get this exception though. Clearly the JSON.Net dll can be loaded, as it works for MeasureGroup, so why the "claim" that the File can't be loaded?

Update, full Exception:

System.IO.FileLoadException was unhandled
  HResult=-2146234304
  Message=Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
  Source=mscorlib
  FileName=Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
  FusionLog==== Pre-bind state information ===
LOG: DisplayName = Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
 (Fully-specified)
LOG: Appbase = file:///.../bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : DataLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: ..\bin\Debug\UpdateData.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
LOG: Attempting download of new URL file:///C:/.../bin/Debug/Newtonsoft.Json.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

  StackTrace:
       at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
       at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
       at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
       at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
       at System.Reflection.CustomAttribute.IsCustomAttributeDefined(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Int32 attributeCtorToken, Boolean mustBeInheritable)
       at System.Reflection.CustomAttribute.IsDefined(RuntimePropertyInfo property, RuntimeType caType)
       at System.Reflection.RuntimePropertyInfo.IsDefined(Type attributeType, Boolean inherit)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.GetSerializableMembers(Type objectType)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
       at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteStartArray(JsonWriter writer, Object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
       at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value)
       at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)
       at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)
       at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Formatting formatting, JsonSerializerSettings settings)
       at Newtonsoft.Json.JsonConvert.SerializeObject(Object value)
       at UpdateData.Program.Queries() in ..\Program.cs:line 81
       at UpdateData.Program.Main(String[] args) in ..\Program.cs:line 27
  InnerException:


来源: stackexchange

问:
Conditional Statement returning false
I'm trying to validate an input field with REGEX. Can anyone help me understand why this conditional statement is returning "Wrong" in the console?

```<code> <script>
            $('form[action*="paypal"]').submit(function(event) {

                if (/^DAM\d{10}/.test($('input[name="item_name"]'))){
                    console.log("Correct!");
                    return true;
                }
                else {
                    console.log("Wrong!");
                    event.preventDefault();
                }
            });
        </script>
</code>```

The form im targeting is:

```<code><form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="XN4BQ5WSZZCEQ">
<table>
<tr><td><input type="hidden" value="">Enter your number</td></tr><tr><td>
<input type="text" name="item_name" required></td></tr>
</table>
<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</code>```

And i'm entering DAM1234567891 into the input field below:

```<code>  <input type="text" name="item_name" required></td></tr>
</code>```

答:
Ahhh, thanks guys. It worked when i put preventDefault in both statements and return true; above.</p>

```<code> <script>
                $('form[action*="paypal"]').submit(function(event) {

                    if (/^DAM\d{10}/.test($('input[name="item_name"]').val())){
                        console.log("Correct!");
                        return true;
                        event.preventDefault();

                    }
                    else {
                        console.log("Wrong!");
                        event.preventDefault();
                    }

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

ContentLicense: CC BY-SA 3.0

Title: Conditional Statement returning false

Body:
I'm trying to validate an input field with REGEX. Can anyone help me understand why this conditional statement is returning "Wrong" in the console?

The form im targeting is:

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="XN4BQ5WSZZCEQ">

<input type="hidden" value="">Enter your number

<input type="text" name="item_name" required>

<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">

</form>

And i'm entering DAM1234567891 into the input field below:

  <input type="text" name="item_name" required>

Body:
Ahhh, thanks guys. It worked when i put preventDefault in both statements and return true; above.

 <script>
                $('form[action*="paypal"]').submit(function(event) {

                    if (/^DAM\d{10}/.test($('input[name="item_name"]').val())){
                        console.log("Correct!");
                        return true;
                        event.preventDefault();

                    }
                    else {
                        console.log("Wrong!");
                        event.preventDefault();
                    }

                });
        </script>


问:
Simple Javascript Regex Question
Google is failing me because ?= is not searchable.  What does

```<code>(?=[aeiouy])
</code>```

match -- specifically ?=, I know that [aeiouy] is any of aeiouy.

答: Let's say your string is "bbbbae", then "(?=[aeiouy])" matches either the 'a' or the 'e', when applied anywhere before 'a'.</p>

ContentLicense: CC BY-SA 2.5

Title: Simple Javascript Regex Question

Body:
Google is failing me because ?= is not searchable.  What does

(?=[aeiouy])

match -- specifically ?=, I know that [aeiouy] is any of aeiouy.


问:
Formatting numbers with localized thousands separators and decimal precision in python
It is possible to format a number with decimal precision with :

```<code>print("{:.2f}".format(7654321.234567))
</code>```

It is possible to format a number with localized thousands separators with :

```<code>import locale
locale.setlocale(locale.LC_ALL, '')
print("{:n}".format(7654321.234567))
</code>```

But how can I do both at the same time?

I would like to print 7 654 321.23 in a country where thousands separator is the space for instance and 7,654,321.23 in a country where thousands separator is the comma? But I cannot know in advance what the localized separator will be.

答:
Add a comma - the thousands separator - before the dot, and do a replace with the appropriate separator of your locale:</p>

```<code>>>> my_sep = locale.localeconv()['thousands_sep']
>>> print("{:,.2f}".format(7654321.234567).replace(',', my_sep))
7 654 321.23
</code>```

Body:
It is possible to format a number with decimal precision with :

print("{:.2f}".format(7654321.234567))

It is possible to format a number with localized thousands separators with :

import locale
locale.setlocale(locale.LC_ALL, '')
print("{:n}".format(7654321.234567))

But how can I do both at the same time?

I would like to print 7 654 321.23 in a country where thousands separator is the space for instance and 7,654,321.23 in a country where thousands separator is the comma? But I cannot know in advance what the localized separator will be.

Body:
Add a comma - the thousands separator - before the dot, and do a replace with the appropriate separator of your locale:

>>> my_sep = locale.localeconv()['thousands_sep']
>>> print("{:,.2f}".format(7654321.234567).replace(',', my_sep))
7 654 321.23


问:
SQL server alter function with execute as caller
In the below sql server function, where would i add a if/else statement if I need to compare the @string value and then return the result?   </p>

```<code>ALTER FUNCTION [AdminUsers] (@string [nvarchar](max), @slat [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS EXTERNAL NAME [EnDec_Sql].[EnDec].[fn_Decrypt]
</code>```

答:
You can't. You're calling a CLR function directly. When you call CLR Functions ALL your t-Sql function body can do is reference the CLR assembly code. You cannot mix the two.

Create a NEW function that calls this one then has the logic you require.

Body:
In the below sql server function, where would i add a if/else statement if I need to compare the @string value and then return the result?

ALTER FUNCTION [AdminUsers] (@string [nvarchar](max), @slat [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS EXTERNAL NAME [EnDec_Sql].[EnDec].[fn_Decrypt]


问:
Oracle SQL: manipulating group
I have a simple query such as this

```<code>select duration, host from Jobs
group by host;
</code>```

i want it actually group by a pool of hosts which is something that needs to be defined at query time

for example, host01-10 would be pool1, host11-20 would be pool2, etc.

at the moment, there isnt a field which says what pool it is in and but it needs to be derived from the host field.

how do i achieve that? I want to be able to creation some sort of function on the slide to maniuplate the field so that it is group-able

```<code>def get_pool(host):
   if get_hostnumber(host) < 10:
        return 'pool1'
    elif:
        ...

select duration, get_pool(host) from Jobs
group by get_pool(host);
</code>```

答:
In SQL, you don't need a function for this.  I would suggest just using a case expression:

```<code>select (case when host <= 'host10' then 'pool1'
             when host <= 'host20' then 'pool2'
             . . .
        end) as hostgrp, sum(duration) as duration
from jobs
group by (case when host <= 'host10' then 'pool1'
             when host <= 'host20' then 'pool2'
             . . .
        end);
</code>```

For your particular example, you could get away with:

```<code>select 'pool' || floor( (cast(substr(host, 5, 6) as number) + 1) / 10),
       sum(duration) as duration
from jobs
group by 'pool' || floor( (cast(substr(host, 5, 6) as number) + 1) / 10);
</code>```

And, lest I forget, I you have a permanent mapping between hosts and their groups, then you should put a hosts reference table in the database and have a second column for the group.  Then this query would simply use a join, and any other query you write would have the same information.

Title: Oracle SQL: manipulating group

Body:
I have a simple query such as this

select duration, host from Jobs
group by host;

i want it actually group by a pool of hosts which is something that needs to be defined at query time

for example, host01-10 would be pool1, host11-20 would be pool2, etc.

at the moment, there isnt a field which says what pool it is in and but it needs to be derived from the host field.

how do i achieve that? I want to be able to creation some sort of function on the slide to maniuplate the field so that it is group-able

def get_pool(host):
   if get_hostnumber(host) < 10:
        return 'pool1'
    elif:
        ...

select duration, get_pool(host) from Jobs
group by get_pool(host);

Body:
In SQL, you don't need a function for this.  I would suggest just using a case expression:

select (case when host <= 'host10' then 'pool1'
             when host <= 'host20' then 'pool2'
             . . .
        end) as hostgrp, sum(duration) as duration
from jobs
group by (case when host <= 'host10' then 'pool1'
             when host <= 'host20' then 'pool2'
             . . .
        end);

For your particular example, you could get away with:

select 'pool' || floor( (cast(substr(host, 5, 6) as number) + 1) / 10),
       sum(duration) as duration
from jobs
group by 'pool' || floor( (cast(substr(host, 5, 6) as number) + 1) / 10);

And, lest I forget, I you have a permanent mapping between hosts and their groups, then you should put a hosts reference table in the database and have a second column for the group.  Then this query would simply use a join, and any other query you write would have the same information.


问:
Data Store for a Mac/iPhone Hybrid App
I've been doing iPhone development for the last 5 months or so, and have been using Gus Mueller's FMDB for database interaction. My next project will have both a Mac and an iPhone application, and they will share data between them, although in the end, the iPhone will be mostly a viewer app, with some minor editing capabilities.

My question is this: Will Core Data make my life easy enough on the Mac side, that it would be worth it to write my data model twice, using Core Data on the Mac, and FMDB on the iPhone? Or should I just use FMDB for both so that I can reuse the same code for both the Mac and iPhone?

I've poked at Core Data a little, but not much (mostly just the examples in the Hillegas book), so any specific examples in favor of Core Data would be greatly appreciated. For the record, I really like FMDB, I'm just wondering if Core Data would make my life that much easier in this situation.

Edit:
I understand the core differences between FMDB and Core Data, I'm mostly looking to find out if what Core Data provides "for free" makes it worth coding my data model twice.

答:
The advantages of Core Data are that it is an object graph management framework that happens to persist to an SQLite (or binary or XML or custom) data store. As such, it manages faulting of individual object instances and bidirectional (including to-many) relationships between objects (including several options for propagating or denying deletions based on those relationships) as well as verifying constraints on individual object properties and relationships (including required/optional, cardinality, range, etc.). In OS X 10.5, it also includes tools for semi-automatically migrating data stores between model schema.

The downside, of course, is that it's not available on the iPhone. If FMDB meets your needs, you may have a much easier time managing a single code base rather than two.

One final option, if you can require Leopard for your desktop app is to write an NSAtomicStore subclass using FMDB. An NSAtomicStore would have to read the entire store into memory—thus you would loose some of the benefits of SQLite on the desktop client—but since the data will be shared on an iPhone, I'd guess you won't have that much data anyways. With this approach, you can use Core Data on the client side and FMDB on the iPhone with a common data model/data store across both.

OwnerDisplayName: shauber

Title: Data Store for a Mac/iPhone Hybrid App

LastEditorDisplayName: shauber

OwnerDisplayName: Barry Wark

LastEditorDisplayName: Barry Wark


问:
Textual filter very slow
I have a table with 10 to 1000 lines
I have a text field to filter the table.
I used this code to filter the display of each line depending on the filter:

```<code>$("#cs_name").keyup(function () {
        $(".cs_line").each(function () {
            if (!$(this).data('name').toLowerCase().includes($("#cs_name").val().toLowerCase())) {
                $(this).hide("fast");
            }
            else {
                $(this).show("fast");
            }
        });
    });
</code>```

It works fine if I have 10 or 20 lines, but when I have 1000 lines time between each letter is sooo long. up to 5 seconds sometimes.

Maybe there is a way to make it mor efficient.

For information, pagination is not an option, for some client reasons, I cannot have multiple pages.

Thanks a lot for your help

答:
Start with caching $(this). The creation of a $(this) object requires time, so create one and cache it : let $this = $(this), and reuse $this.

Same thing for $(".cs_line") and $("#cs_name").val().toLowerCase(). Each of these operations require jQuery to access the DOM and create full jQuery objects, and you're doing that thousands of times.

Also, throttle your keyup, don't execute the filter every time a key is pressed.

Optimized code :

```<code>const $lines = $(".cs_line")
const name = $("#cs_name").val().toLowerCase()
let typeTimeout = null

const applyFilter = () => {
    $lines.each(() => {
        let $this = $(this);
        if ($this.data('name').toLowerCase().includes(name)) {
            $this.show("fast"); // Or just .show(), much faster
        } else {
            $this.hide("fast"); // Or just .hide(), much faster
        }
    });
}

const throttleFilter = () => {
    clearTimeout(typeTimeout);
    typeTimeout = setTimeout(applyfilter, 400) // Will apply the filter if no key is pressed for 400ms
}

$("#cs_name").keyup(throttleFilter);
</code>```

Title: Textual filter very slow

Body:
I have a table with 10 to 1000 lines
I have a text field to filter the table.
I used this code to filter the display of each line depending on the filter:

$("#cs_name").keyup(function () {
        $(".cs_line").each(function () {
            if (!$(this).data('name').toLowerCase().includes($("#cs_name").val().toLowerCase())) {
                $(this).hide("fast");
            }
            else {
                $(this).show("fast");
            }
        });
    });

It works fine if I have 10 or 20 lines, but when I have 1000 lines time between each letter is sooo long. up to 5 seconds sometimes.

Maybe there is a way to make it mor efficient.

For information, pagination is not an option, for some client reasons, I cannot have multiple pages.

Thanks a lot for your help

Body:
Start with caching $(this). The creation of a $(this) object requires time, so create one and cache it : let $this = $(this), and reuse $this.

Same thing for $(".cs_line") and $("#cs_name").val().toLowerCase(). Each of these operations require jQuery to access the DOM and create full jQuery objects, and you're doing that thousands of times.

Also, throttle your keyup, don't execute the filter every time a key is pressed.

Optimized code :

const $lines = $(".cs_line")
const name = $("#cs_name").val().toLowerCase()
let typeTimeout = null

const applyFilter = () => {
    $lines.each(() => {
        let $this = $(this);
        if ($this.data('name').toLowerCase().includes(name)) {
            $this.show("fast"); // Or just .show(), much faster
        } else {
            $this.hide("fast"); // Or just .hide(), much faster
        }
    });
}

const throttleFilter = () => {
    clearTimeout(typeTimeout);
    typeTimeout = setTimeout(applyfilter, 400) // Will apply the filter if no key is pressed for 400ms
}

$("#cs_name").keyup(throttleFilter);


问:
bootstrap nav-bar-right floating left
I tried to look out for an answer for my problem but I can't seem to find one. If by any chance there actually is a solution out there, then, I'm sorry, my bad!

I seem to be encountering a problem with Bootstrap's default nav bar: The dropdown menu: .navbar-right is floating left for some reason. You can check it out here.
I'm working on rails 5 and the code for my nav currently looks like:

```<code>    <nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <%= link_to "Prodemex", root_path, class: "navbar-brand", id: "logo" %>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li><%= link_to "Articulos", articles_path %></li>
        <li><%= link_to "Usuarios", users_path %></li>
        <% if logged_in? %>
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Actions <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><%= link_to "Nuevo articulo", new_article_path %></li>
              <li role="separator" class="divider"></li>
              <li><a href="#">One more separated link</a></li>
            </ul>
          </li>
        </ul>
      <% end %>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <% if logged_in? %>
        <ul class="nav navbar-nav navbar-right">
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Mi cuenta<%= " - Admin " if current_user.admin? %><span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><%= link_to "Modificar mis datos", edit_user_path(current_user) %></li>
                <li><%= link_to "Ver mi perfil", user_path(current_user) %></li>
                <li><a href="#">Something else here</a></li>
                <li role="separator" class="divider"></li>
                <li><%= link_to 'Cerrar sesión', logout_path, method: :delete %></li>
              </ul>
            </li>
        </ul>
        <% else %>
        <ul class="navbar-right nav navbar-nav">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Mi cuenta <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><%= link_to 'Iniciar sesión', login_path %></li>
              <li><%= link_to 'Registrarse', signup_path %></li>
            </ul>
          </li>
        </ul>
        <% end %>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
</code>```

You can retrieve more of the code on github
I have a custom CSS with all that and already tried to delete all portions related with navbar but it did nothing...

```<code>$navbar-default-bg: #3498DB;

@import "bootstrap-sprockets";
@import "bootstrap";

.gen {
  padding: 0 2%;
}

.col-xs-8 {
  float: none;
}

a {
  text-decoration: none;
}

body {
  font-weight: 200;
}

#logo {
  float: left;
  font-size: 1.7em;
  color: #fff;
  text-transform: uppercase;
  font-weight: 200;
}

#logo:hover {
  text-decoration: none;
  color: #5e82a6;
}

.navbar {
  border-radius: 0;
  margin: 0;
}

.center {
  text-align: center;
}

#home {
  background: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), image-url('cover_page.jpg');
  background-size: cover;
  background-attachment: fixed;
  height: 100vh;
}

.jumbotron {
  padding: 15.5% 20%;
  background-color: transparent;

  }

.jumbotron h1,h3 {
  color: #fff;
  font-weight: 200;
  margin-bottom: 10px;
}

.btn-xlg {
  font-size: 1.2em;
  font-weight: 200;
  background-color: #3498DB;
  border: 1px solid #3498DB;
  margin: 0;
  display: inline-block;
  letter-spacing: 1px;
}

.btn-xlge {
  font-size: 1.2em;
  font-weight: 200;
  color: #000;
  background-color: none;
  border: 1px solid #000;
  margin-left: 10px;
  display: inline-block;
}

.btn-xlge:hover,
          active {
  background-color: #337ab7;
  color: #fff;
  border: 1px solid #337ab7;
}

.footer {
  background-color: #3498DB;
  color: #fff;
  letter-spacing: 1px;
  padding: 10px;
}

footer ul {
  list-style:none;
  margin-top: 10px;
}

.footer a {
  color: #fff;
}

.footer a:hover,
.footer a:active {
  color: #ccc;
  text-decoration: none;
}

.article-actions {
  border-top: 1px solid #eaeaea;
  padding-top: 15px;
  margin-top: 10px;
}

.descrition {
  margin-top: 0;
}

.article-title {
  font-size: 1.5em;
}

.article-title a {
  text-decoration: none;
}

.article-body {
  border-top: 1px solid #eaeaea;
  padding-top: 15px;
  padding-bottom: 15px;
}

.article-meta-details {
  margin-top: 5px;
  margin-bottom: 0;
  font-size: 1em;
}

.article-meta-details a {
  text-decoration:none;
}

.well-lg {
  padding-bottom: 10px;
}

.listing {
  list-style: none;
  padding-left: 0;
}

.insideuser {
  padding-left: 50px;
  float: left;
}

.author {
  font-weight: 400;
  color: #3498DB;
}

.authorpage {
  margin-top: 10px;
  padding: 10px 0;
}

.pop {
  margin-top: 15px;
  -webkit-box-shadow: 4px 1px 10px 0px rgba(50, 50, 50, 0.27);
  -moz-box-shadow:    4px 1px 10px 0px rgba(50, 50, 50, 0.27);
  box-shadow:         4px 1px 10px 0px rgba(50, 50, 50, 0.27);
}
</code>```

And the weird thing is that when I log in, the dropdown goes back to the right where it is supposed to be...
When inspecting the code, I almost found a fix, deleting the left float to this portion:

```<code>@media (min-width: 768px)
custom.self-839…ss?body=1:5864
.navbar-nav {
    float: left;
    margin: 0;
}
</code>```

But obviously when I do that it messes up with the rest of the navbar.
Any body can help me? Thanks in advance!!

答:
This is just a hunch, but I thought it was worth trying...I wonder if changing where you have your if/else statement will help?</p>

```<code><ul class="nav navbar-nav navbar-right">
  <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Mi cuenta<%= " - Admin " if current_user.admin? %><span class="caret"></span></a>
     <% if logged_in? %>
       <ul class="dropdown-menu">
         <li><%= link_to "Modificar mis datos", edit_user_path(current_user) %></li>
         <li><%= link_to "Ver mi perfil", user_path(current_user) %></li>
         <li><a href="#">Something else here</a></li>
         <li role="separator" class="divider"></li>
         <li><%= link_to 'Cerrar sesión', logout_path, method: :delete %></li>
       </ul>
     <% else %>
       <ul class="dropdown-menu">
         <li><%= link_to 'Iniciar sesión', login_path %></li>
         <li><%= link_to 'Registrarse', signup_path %></li>
       </ul>
     <% end %>
  </li>
</ul>
</code>```

Title: bootstrap nav-bar-right floating left

Body:
I tried to look out for an answer for my problem but I can't seem to find one. If by any chance there actually is a solution out there, then, I'm sorry, my bad!

I seem to be encountering a problem with Bootstrap's default nav bar: The dropdown menu: .navbar-right is floating left for some reason. You can check it out here.
I'm working on rails 5 and the code for my nav currently looks like:

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      <%= link_to "Prodemex", root_path, class: "navbar-brand", id: "logo" %>

<%= link_to "Articulos", articles_path %>

<%= link_to "Usuarios", users_path %>

        <% if logged_in? %>

            Actions

<%= link_to "Nuevo articulo", new_article_path %>

One more separated link

      <% end %>
      <form class="navbar-form navbar-left">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <% if logged_in? %>

              Mi cuenta<%= " - Admin " if current_user.admin? %>

<%= link_to "Modificar mis datos", edit_user_path(current_user) %>

<%= link_to "Ver mi perfil", user_path(current_user) %>

Something else here

<%= link_to 'Cerrar sesión', logout_path, method: :delete %>

        <% else %>

            Mi cuenta

<%= link_to 'Iniciar sesión', login_path %>

<%= link_to 'Registrarse', signup_path %>

        <% end %>

You can retrieve more of the code on github
I have a custom CSS with all that and already tried to delete all portions related with navbar but it did nothing...

$navbar-default-bg: #3498DB;

@import "bootstrap-sprockets";
@import "bootstrap";

.gen {
  padding: 0 2%;
}

.col-xs-8 {
  float: none;
}

a {
  text-decoration: none;
}

body {
  font-weight: 200;
}

#logo {
  float: left;
  font-size: 1.7em;
  color: #fff;
  text-transform: uppercase;
  font-weight: 200;
}

#logo:hover {
  text-decoration: none;
  color: #5e82a6;
}

.navbar {
  border-radius: 0;
  margin: 0;
}

.center {
  text-align: center;
}

#home {
  background: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), image-url('cover_page.jpg');
  background-size: cover;
  background-attachment: fixed;
  height: 100vh;
}

.jumbotron {
  padding: 15.5% 20%;
  background-color: transparent;

  }

.jumbotron h1,h3 {
  color: #fff;
  font-weight: 200;
  margin-bottom: 10px;
}

.btn-xlg {
  font-size: 1.2em;
  font-weight: 200;
  background-color: #3498DB;
  border: 1px solid #3498DB;
  margin: 0;
  display: inline-block;
  letter-spacing: 1px;
}

.btn-xlge {
  font-size: 1.2em;
  font-weight: 200;
  color: #000;
  background-color: none;
  border: 1px solid #000;
  margin-left: 10px;
  display: inline-block;
}

.btn-xlge:hover,
          active {
  background-color: #337ab7;
  color: #fff;
  border: 1px solid #337ab7;
}

.footer {
  background-color: #3498DB;
  color: #fff;
  letter-spacing: 1px;
  padding: 10px;
}

footer ul {
  list-style:none;
  margin-top: 10px;
}

.footer a {
  color: #fff;
}

.footer a:hover,
.footer a:active {
  color: #ccc;
  text-decoration: none;
}

.article-actions {
  border-top: 1px solid #eaeaea;
  padding-top: 15px;
  margin-top: 10px;
}

.descrition {
  margin-top: 0;
}

.article-title {
  font-size: 1.5em;
}

.article-title a {
  text-decoration: none;
}

.article-body {
  border-top: 1px solid #eaeaea;
  padding-top: 15px;
  padding-bottom: 15px;
}

.article-meta-details {
  margin-top: 5px;
  margin-bottom: 0;
  font-size: 1em;
}

.article-meta-details a {
  text-decoration:none;
}

.well-lg {
  padding-bottom: 10px;
}

.listing {
  list-style: none;
  padding-left: 0;
}

.insideuser {
  padding-left: 50px;
  float: left;
}

.author {
  font-weight: 400;
  color: #3498DB;
}

.authorpage {
  margin-top: 10px;
  padding: 10px 0;
}

.pop {
  margin-top: 15px;
  -webkit-box-shadow: 4px 1px 10px 0px rgba(50, 50, 50, 0.27);
  -moz-box-shadow:    4px 1px 10px 0px rgba(50, 50, 50, 0.27);
  box-shadow:         4px 1px 10px 0px rgba(50, 50, 50, 0.27);
}

And the weird thing is that when I log in, the dropdown goes back to the right where it is supposed to be...
When inspecting the code, I almost found a fix, deleting the left float to this portion:

@media (min-width: 768px)
custom.self-839…ss?body=1:5864
.navbar-nav {
    float: left;
    margin: 0;
}

But obviously when I do that it messes up with the rest of the navbar.
Any body can help me? Thanks in advance!!

Body:
This is just a hunch, but I thought it was worth trying...I wonder if changing where you have your if/else statement will help?

<ul class="nav navbar-nav navbar-right">
  <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Mi cuenta<%= " - Admin " if current_user.admin? %><span class="caret"></span></a>
     <% if logged_in? %>
       <ul class="dropdown-menu">
         <li><%= link_to "Modificar mis datos", edit_user_path(current_user) %></li>
         <li><%= link_to "Ver mi perfil", user_path(current_user) %></li>
         <li><a href="#">Something else here</a></li>
         <li role="separator" class="divider"></li>
         <li><%= link_to 'Cerrar sesión', logout_path, method: :delete %></li>
       </ul>
     <% else %>
       <ul class="dropdown-menu">
         <li><%= link_to 'Iniciar sesión', login_path %></li>
         <li><%= link_to 'Registrarse', signup_path %></li>
       </ul>
     <% end %>
  </li>
</ul>


问:
Random string generator: Unicode out of range?
I'm trying to make a random string generator in C#, given a length of the string. My first attempt was this:

```<code>public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        s += Convert.ToChar((97 + r.Next(26)));
    }
    return s;
}
</code>```

But the frequencies of the letters before k were very low, so I tried to change it by writing my own randomizer:

```<code>public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}
</code>```

But sometimes randomLetter will be greater than 26, sometimes way too great. I can't find the cause of this problem, can you?

答:
If you want random.

```<code>private static System.Security.Cryptography.RandomNumberGenerator random = System.Security.Cryptography.RandomNumberGenerator.Create();
public static string Random(int characters)
        {
            var data = new byte[characters];
            random.GetBytes(data);
            return data.Select(b=>Convert.ToChar((int)(96 + (Math.Floor((b/(double)byte.MaxValue)*27)) - 1))).Aggregate(new System.Text.StringBuilder(),(a,c) => a.Append(c)).ToString();
        }
</code>```

Note this is not fast but random

Body:
I'm trying to make a random string generator in C#, given a length of the string. My first attempt was this:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        s += Convert.ToChar((97 + r.Next(26)));
    }
    return s;
}

But the frequencies of the letters before k were very low, so I tried to change it by writing my own randomizer:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}

But sometimes randomLetter will be greater than 26, sometimes way too great. I can't find the cause of this problem, can you?

Body:
If you want random.

private static System.Security.Cryptography.RandomNumberGenerator random = System.Security.Cryptography.RandomNumberGenerator.Create();
public static string Random(int characters)
        {
            var data = new byte[characters];
            random.GetBytes(data);
            return data.Select(b=>Convert.ToChar((int)(96 + (Math.Floor((b/(double)byte.MaxValue)*27)) - 1))).Aggregate(new System.Text.StringBuilder(),(a,c) => a.Append(c)).ToString();
        }

Note this is not fast but random


问:
Resource ownership in REST API
In the following scenario:

A User can create Games.

A User who creates a game is called Owner.

Games have their own unique id globally.

Other Users can join Games they don't own, these are called Players.

One would send a request to /game/{id} to get the Game data, which should be the same for every client, something like:

```<code>{
   name: 'My Game',
   sport: 'Football'
   ...
}
</code>```

Let's say that we have to show a "Settings" link for the Game owner in the Main Game Screen. This "Settings" link can't be displayed for regular Players.

Both Player and Owner can see the Main Game Screen.

How can I verify the ownership of this resource to show different components to the users?

I think that adding the ownerId to the response would be a liability since one could change the value on the client side, is that right?

Also, adding an isOwner field would make it impossible to cache the response.

答:
Lets talk about the server application and the client application. The client application contains Main Game Screen and should show or hide some panes depend on something.

The server application should provide this something. Cause the server application is REST it should provide some recourse. What the kind of the resource and where it should be?

```<code>GET /games/{gameId}/users/{userId}/something
GET /users/{userId}/games/{gameId}/something
</code>```

It's possible to call this something the user's rights or permissions. Is this separate resource? Maybe, no. So you can implement the method

```<code>GET /games/{gameId}/users/{userId}
</code>```

The method will return user's profile and corresponding permissions for the game with id {gameId} like here:

```<code>{
    givenNames: 'Miguel de Cervantes',
    familyName: 'Saavedra',
    totalScore: 10342,

    permissions: {
        canClose: false,
        canSetup: false,
        . . .
    }
}
</code>```

And of course the server application should check permissions for every client's request.

Title: Resource ownership in REST API

Body:
In the following scenario:

A User can create Games.

A User who creates a game is called Owner.

Games have their own unique id globally.

Other Users can join Games they don't own, these are called Players.

One would send a request to /game/{id} to get the Game data, which should be the same for every client, something like:

{
   name: 'My Game',
   sport: 'Football'
   ...
}

Let's say that we have to show a "Settings" link for the Game owner in the Main Game Screen. This "Settings" link can't be displayed for regular Players.

Both Player and Owner can see the Main Game Screen.

How can I verify the ownership of this resource to show different components to the users?

I think that adding the ownerId to the response would be a liability since one could change the value on the client side, is that right?

Also, adding an isOwner field would make it impossible to cache the response.

Body:
Lets talk about the server application and the client application. The client application contains Main Game Screen and should show or hide some panes depend on something.

The server application should provide this something. Cause the server application is REST it should provide some recourse. What the kind of the resource and where it should be?

GET /games/{gameId}/users/{userId}/something
GET /users/{userId}/games/{gameId}/something

It's possible to call this something the user's rights or permissions. Is this separate resource? Maybe, no. So you can implement the method

GET /games/{gameId}/users/{userId}

The method will return user's profile and corresponding permissions for the game with id {gameId} like here:

{
    givenNames: 'Miguel de Cervantes',
    familyName: 'Saavedra',
    totalScore: 10342,

    permissions: {
        canClose: false,
        canSetup: false,
        . . .
    }
}

And of course the server application should check permissions for every client's request.


问:
How can click enter through selenium c#
I want to automate video uploading to asite. There is a textbox to enter tags there. So I want to paste my tags to that textbox and then click enter!
I used this code for click on 'Enter':

```<code>youporn.FindElement(By.XPath(".//*[@id='token-input-']")).SendKeys(Keys.Enter);
</code>```

But I am getting an error:

答:
The compiler doesn't know if you mean the Keys enum of System.Windows.Forms or OpenQA.Selenium. Change it to the following and your stuff works.

```<code>youporn.FindElement(By.XPath(".//*[@id='token-input-']")).SendKeys(OpenQA.Selenium.Keys.Enter);
</code>```

Title: How can click enter through selenium c#

Body:
I want to automate video uploading to asite. There is a textbox to enter tags there. So I want to paste my tags to that textbox and then click enter!
I used this code for click on 'Enter':

youporn.FindElement(By.XPath(".//*[@id='token-input-']")).SendKeys(Keys.Enter);

But I am getting an error:

Body:
The compiler doesn't know if you mean the Keys enum of System.Windows.Forms or OpenQA.Selenium. Change it to the following and your stuff works.

youporn.FindElement(By.XPath(".//*[@id='token-input-']")).SendKeys(OpenQA.Selenium.Keys.Enter);


问:
Extract multidimensional array values
I'm dealing with this array, but the key [row_204] changes each time (ie sometimes it is [row_79] or [row_109]) but all other key names stay the same in this exact structure. I need to get the value of UUID and userID but can't find a solution to get the value by key in that [row_] array.

I need to be able to extract the values and place them in strings, for example,

$uuid =

and so on.

I can't seem to find a similar query and have tried so many variations. Many thanks in advance.

```<code>Array
(
[action] => edit
[data] => Array
    (
        [row_204] => Array
            (
                [UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
                [userID] => 7
                [maxPoints] => 7
                [awardedPoints] => 6
                [Date] => 2017-06-08
            )

    )

)
</code>```

答:
The easiest would probably be:

```<code>$data = current($_POST['data']);
</code>```

Then just echo $data['UUID'];.

If you need the key for whatever reason:

```<code>list($key, $data) = each($_POST['data']);
</code>```

Title: Extract multidimensional array values

Body:
I'm dealing with this array, but the key [row_204] changes each time (ie sometimes it is [row_79] or [row_109]) but all other key names stay the same in this exact structure. I need to get the value of UUID and userID but can't find a solution to get the value by key in that [row_] array.

I need to be able to extract the values and place them in strings, for example,

$uuid =

and so on.

I can't seem to find a similar query and have tried so many variations. Many thanks in advance.

Array
(
[action] => edit
[data] => Array
    (
        [row_204] => Array
            (
                [UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
                [userID] => 7
                [maxPoints] => 7
                [awardedPoints] => 6
                [Date] => 2017-06-08
            )

    )

)

Body:
The easiest would probably be:

$data = current($_POST['data']);

Then just echo $data['UUID'];.

If you need the key for whatever reason:

list($key, $data) = each($_POST['data']);


问:
PHP how to move the children up to each parent
I've been stuck on this for a while now, internet has helped but I can't get it right.  I have an array listed below and I've been trying to create a new array from this one with the children in each odd number moved up to the corresponding parent.  I came close with a $new array and a counter checking if the index was odd or even and then if the odd number is true reassign the children to the current parent.

Here's the array.

```<code>Array
(
   [0] => hair-and-beauty
   [1] => Array
    (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [2] => hair-colouring
   [3] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [4] => hair-styling
   [5] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

)
</code>```

I need to get the kids like this.

```<code> Array
  (
       [0] => hair-and-beauty  => Array
         (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     [1] => hair-colouring => Array
          (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

        [2] => hair-styling  => Array
           (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     )
</code>```

My php code isn't working out right for me :(

```<code>    $new = array();
    $number = 0;
     foreach($menu as $current){
         //If number is even
         if ($number % 2 == 0) {
            array_push($new[$current]);
        }else{
            //number isnt even so go for children and add them to parent
            $new[$value['index']] = $current;
        }
        ++$number;
     }
     unset($menu);
    usort($new);

    $x = $new;
    $json=$x;
</code>```

The main array is called $menu.

Any help appreciated.

I'm steering in the direction of an array_merge

Var export :

```<code>array (
  0 => 'hair-and-beauty',
  1 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  2 => 'hair-colouring',
  3 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  4 => 'hair-styling',
  5 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
)null
</code>```

答:
You could do it like this:

```<code>$num_pairs = count($old) / 2;
$new = [];
for($i = 0; $i < $num_pairs; $i++) {
  $new[] = [$old[$i*2] => $old[$i*2+1]];
}
</code>```

If you want the resulting array, to be associative though (as one of your comments suggests), you could use this instead:

```<code>$num_pairs = count($old) / 2;
$new = [];
for($i = 0; $i < $num_pairs; $i++) {
  $new[$old[$i*2]] = $old[$i*2+1];
}
</code>```

Body:
I've been stuck on this for a while now, internet has helped but I can't get it right.  I have an array listed below and I've been trying to create a new array from this one with the children in each odd number moved up to the corresponding parent.  I came close with a $new array and a counter checking if the index was odd or even and then if the odd number is true reassign the children to the current parent.

Here's the array.

Array
(
   [0] => hair-and-beauty
   [1] => Array
    (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [2] => hair-colouring
   [3] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [4] => hair-styling
   [5] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

)

I need to get the kids like this.

 Array
  (
       [0] => hair-and-beauty  => Array
         (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     [1] => hair-colouring => Array
          (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

        [2] => hair-styling  => Array
           (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     )

My php code isn't working out right for me :(

    $new = array();
    $number = 0;
     foreach($menu as $current){
         //If number is even
         if ($number % 2 == 0) {
            array_push($new[$current]);
        }else{
            //number isnt even so go for children and add them to parent
            $new[$value['index']] = $current;
        }
        ++$number;
     }
     unset($menu);
    usort($new);

    $x = $new;
    $json=$x;

The main array is called $menu.

Any help appreciated.

I'm steering in the direction of an array_merge

Var export :

array (
  0 => 'hair-and-beauty',
  1 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  2 => 'hair-colouring',
  3 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  4 => 'hair-styling',
  5 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
)null

Body:
You could do it like this:

$num_pairs = count($old) / 2;
$new = [];
for($i = 0; $i < $num_pairs; $i++) {
  $new[] = [$old[$i*2] => $old[$i*2+1]];
}

If you want the resulting array, to be associative though (as one of your comments suggests), you could use this instead:

$num_pairs = count($old) / 2;
$new = [];
for($i = 0; $i < $num_pairs; $i++) {
  $new[$old[$i*2]] = $old[$i*2+1];
}


答:
You can use case when in select and in group by:</p>

```<code>select duration, (case when host <10 then 'pool1' when host  between 10 and 19 then 'pool2')
from Jobs
group by (case when host <10 then 'pool1' when host  between 10 and 19 then 'pool2');
</code>```

Title: Oracle SQL: manipulating group

Body:
You can use case when in select and in group by:

select duration, (case when host <10 then 'pool1' when host  between 10 and 19 then 'pool2')
from Jobs
group by (case when host <10 then 'pool1' when host  between 10 and 19 then 'pool2');


问:
Saving Password with Md5
I am using Postgresql,hibernate and Java and I need to store a password. Can someone suggest me how to encrypt the password with md5. Else is there a better way to store secure password in the database

Thanks

答:
You can do it in postgres if you install the pgcrypto contrib module.

You can then encrypt passwords like this:

```<code>update ... set passwordhash = crypt('new password', gen_salt('md5'));
</code>```

Of course you can't decrypt it at all!

As others have pointed out, this may be a bad idea, depending on what you are trying to do. I've been forced to use MD5 before because another application has demanded it, but you don't want to be broadcasting that hash to the world.

Title: Saving Password with Md5

Body:
You can do it in postgres if you install the pgcrypto contrib module.

You can then encrypt passwords like this:

update ... set passwordhash = crypt('new password', gen_salt('md5'));

Of course you can't decrypt it at all!

As others have pointed out, this may be a bad idea, depending on what you are trying to do. I've been forced to use MD5 before because another application has demanded it, but you don't want to be broadcasting that hash to the world.


问:
How to add data from a text file to ComboBox in JavaFX?
I create a ComboBox in Scene Builder and I want to populate him with data from a text file (eg. Text.txt):

public class ToDoListController implements Initializable {

```<code>@FXML
private ComboBox<?> eventsSelector;
</code>```

How to do this?

Thank you very much!

Two solutions:
1.

@FXML
    private ComboBox eventsSelector;

```<code>@Override
public void initialize(URL location, ResourceBundle resources) {
      List<String> myList;
      try {
        myList = Files.lines(Paths.get("path of my text file")).collect(Collectors.toList());
        eventsSelector.setItems(FXCollections.observableArrayList(myList));
    } catch (IOException e) {
        System.out.println("Don t find file");
    }
</code>```

}
2.

```<code>    //Read items from txt File
    try {
        BufferedReader br = new BufferedReader(new
        FileReader("path of my text file"));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            //Add Item
            eventsSelector.getItems().add(line);

            sb.append(line);
            line = br.readLine();
        }
        br.close();
    } catch (IOException e) {
        System.out.println("Don t find file");

    }
</code>```

答:
I wrote some code for you, this should work for you:

```<code>public class YourController {
//Combobox
@FXML
ComboBox<String> combobx;

//Initialize FXML
@FXML
public void initialize() throws IOException {
    //Read items from txt File
    BufferedReader br = new BufferedReader(new FileReader("/items.txt"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            //Add Item
            combobx.getItems().add(line);

            sb.append(line);
            line = br.readLine();
        }
    } finally {
        br.close();
    }

    //Default Selection first item
    combobx.getSelectionModel().select(0);
}
}
</code>```

The txt file must be in this case in the root directory of your project.

Body:
I create a ComboBox in Scene Builder and I want to populate him with data from a text file (eg. Text.txt):

public class ToDoListController implements Initializable {

@FXML
private ComboBox<?> eventsSelector;

How to do this?

Thank you very much!

Two solutions:
1.

@FXML
    private ComboBox eventsSelector;

@Override
public void initialize(URL location, ResourceBundle resources) {
      List<String> myList;
      try {
        myList = Files.lines(Paths.get("path of my text file")).collect(Collectors.toList());
        eventsSelector.setItems(FXCollections.observableArrayList(myList));
    } catch (IOException e) {
        System.out.println("Don t find file");
    }

}
2.

    //Read items from txt File
    try {
        BufferedReader br = new BufferedReader(new
        FileReader("path of my text file"));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            //Add Item
            eventsSelector.getItems().add(line);

            sb.append(line);
            line = br.readLine();
        }
        br.close();
    } catch (IOException e) {
        System.out.println("Don t find file");

    }

Body:
I wrote some code for you, this should work for you:

public class YourController {
//Combobox
@FXML
ComboBox<String> combobx;

//Initialize FXML
@FXML
public void initialize() throws IOException {
    //Read items from txt File
    BufferedReader br = new BufferedReader(new FileReader("/items.txt"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            //Add Item
            combobx.getItems().add(line);

            sb.append(line);
            line = br.readLine();
        }
    } finally {
        br.close();
    }

    //Default Selection first item
    combobx.getSelectionModel().select(0);
}
}

The txt file must be in this case in the root directory of your project.


问:
Target checked checkbox in jQuery
I have HTML, CSS and jQuery code for a checkbox. But I was recently making some changes in the HTML structure and now the jQuery is no longer working. And since I'm a beginner, I don't know how to fix this.

Can someone take a look and just let me know what jQuery should be targeting instead, so it'll change the styling of the elements when the checkbox is checked?

$('.form-check').click(function(){
        $(this).closest('.list-group-item').find('.incomplete').css('display', (this.checked)?'none':'block')
        $(this).closest('.list-group-item').find('.complete').css('display', (this.checked)?'block':'none')
        $(this).closest('.list-group-item').css('background-color',(this.checked)?'#4CAF50':'')
        $(this).closest('.list-group-item').find('.custom-control-description').css('color', (this.checked)?'#fff':'#2c2b2c')
  $(this).closest('.list-group-item').find('.custom-control-description').css('text-decoration-color', (this.checked)?'#fff':'#ababab')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-control-box {
  border-radius: 50%;
  height: 30px;
  width: 30px;
  background-color: #fff;
  border: 1px solid black;
  position: absolute;
  margin-left: -50px;
}

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 3;
  stroke-miterlimit: 10;
  stroke: #1b7e45;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}
.checkmark {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: block;
  stroke-width: 5;
  stroke: #fff;
  stroke-miterlimit: 10;
  box-shadow: inset 0px 0px 0px #1b7e45;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
  border: 1px solid #4c4c4d;
}
.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}
@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}
@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #1b7e45;
  }
}

input[type=checkbox] {
  display: none;
}
input[type=checkbox] + svg {
  display: none;
}
input[type=checkbox]:checked + svg {
  display: block;
}
.form-check {
  position: relative;
}
.form-check label {
  align-items: center;
  justify-content: left;
  padding-left: 50px;
  cursor: pointer;
}
.custom-control-description {
  font-size: 12px;
  line-height: 2.6;
}

.form-check label svg {
  position: absolute;
  top: 0;
  left: 0;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" name="item_1" value="item 1" id="checkbox"/>
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
      <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
      <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      Checkbox

pending

done

```

答:
You are checking the .form-check if it is checked.. It should be the checkbox inside the .form-check.

Find the checkbox inside the .form-check first and the check for its prop if checked or not as follows:

$('.form-check').click(function() {
  var checkbox = $(this).find('input[type=checkbox]')
  $(this).closest('.list-group-item').find('.incomplete').css('display', (checkbox.prop('checked')) ? 'none' : 'block')
  $(this).closest('.list-group-item').find('.complete').css('display', (checkbox.prop('checked')) ? 'block' : 'none')
  $(this).closest('.list-group-item').css('background-color', (checkbox.prop('checked')) ? '#4CAF50' : '')
  $(this).closest('.list-group-item').find('.custom-control-description').css('color', (checkbox.prop('checked')) ? '#fff' : '#2c2b2c')
  $(this).closest('.list-group-item').find('.custom-control-description').css('text-decoration-color', (checkbox.prop('checked')) ? '#fff' : '#ababab')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-control-box {
  border-radius: 50%;
  height: 30px;
  width: 30px;
  background-color: #fff;
  border: 1px solid black;
  position: absolute;
  margin-left: -50px;
}

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 3;
  stroke-miterlimit: 10;
  stroke: #1b7e45;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}

.checkmark {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: block;
  stroke-width: 5;
  stroke: #fff;
  stroke-miterlimit: 10;
  box-shadow: inset 0px 0px 0px #1b7e45;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
  border: 1px solid #4c4c4d;
}

.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}

@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}

@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #1b7e45;
  }
}

input[type=checkbox] {
  display: none;
}

input[type=checkbox]+svg {
  display: none;
}

input[type=checkbox]:checked+svg {
  display: block;
}

.form-check {
  position: relative;
}

.form-check label {
  align-items: center;
  justify-content: left;
  padding-left: 50px;
  cursor: pointer;
}

.custom-control-description {
  font-size: 12px;
  line-height: 2.6;
}

.form-check label svg {
  position: absolute;
  top: 0;
  left: 0;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" name="item_1" value="item 1" id="checkbox"/>
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
      <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
      <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      Checkbox

pending

done

```

Title: Target checked checkbox in jQuery

Body:
I have HTML, CSS and jQuery code for a checkbox. But I was recently making some changes in the HTML structure and now the jQuery is no longer working. And since I'm a beginner, I don't know how to fix this.

Can someone take a look and just let me know what jQuery should be targeting instead, so it'll change the styling of the elements when the checkbox is checked?

$('.form-check').click(function(){
        $(this).closest('.list-group-item').find('.incomplete').css('display', (this.checked)?'none':'block')
        $(this).closest('.list-group-item').find('.complete').css('display', (this.checked)?'block':'none')
        $(this).closest('.list-group-item').css('background-color',(this.checked)?'#4CAF50':'')
        $(this).closest('.list-group-item').find('.custom-control-description').css('color', (this.checked)?'#fff':'#2c2b2c')
  $(this).closest('.list-group-item').find('.custom-control-description').css('text-decoration-color', (this.checked)?'#fff':'#ababab')
})

.custom-control-box {
  border-radius: 50%;
  height: 30px;
  width: 30px;
  background-color: #fff;
  border: 1px solid black;
  position: absolute;
  margin-left: -50px;
}

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 3;
  stroke-miterlimit: 10;
  stroke: #1b7e45;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}
.checkmark {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: block;
  stroke-width: 5;
  stroke: #fff;
  stroke-miterlimit: 10;
  box-shadow: inset 0px 0px 0px #1b7e45;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
  border: 1px solid #4c4c4d;
}
.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}
@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}
@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #1b7e45;
  }
}

input[type=checkbox] {
  display: none;
}
input[type=checkbox] + svg {
  display: none;
}
input[type=checkbox]:checked + svg {
  display: block;
}
.form-check {
  position: relative;
}
.form-check label {
  align-items: center;
  justify-content: left;
  padding-left: 50px;
  cursor: pointer;
}
.custom-control-description {
  font-size: 12px;
  line-height: 2.6;
}

.form-check label svg {
  position: absolute;
  top: 0;
  left: 0;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" name="item_1" value="item 1" id="checkbox"/>
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
      <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
      <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      Checkbox

pending

done

Body:
You are checking the .form-check if it is checked.. It should be the checkbox inside the .form-check.

Find the checkbox inside the .form-check first and the check for its prop if checked or not as follows:

$('.form-check').click(function() {
  var checkbox = $(this).find('input[type=checkbox]')
  $(this).closest('.list-group-item').find('.incomplete').css('display', (checkbox.prop('checked')) ? 'none' : 'block')
  $(this).closest('.list-group-item').find('.complete').css('display', (checkbox.prop('checked')) ? 'block' : 'none')
  $(this).closest('.list-group-item').css('background-color', (checkbox.prop('checked')) ? '#4CAF50' : '')
  $(this).closest('.list-group-item').find('.custom-control-description').css('color', (checkbox.prop('checked')) ? '#fff' : '#2c2b2c')
  $(this).closest('.list-group-item').find('.custom-control-description').css('text-decoration-color', (checkbox.prop('checked')) ? '#fff' : '#ababab')
})

.custom-control-box {
  border-radius: 50%;
  height: 30px;
  width: 30px;
  background-color: #fff;
  border: 1px solid black;
  position: absolute;
  margin-left: -50px;
}

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 3;
  stroke-miterlimit: 10;
  stroke: #1b7e45;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}

.checkmark {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: block;
  stroke-width: 5;
  stroke: #fff;
  stroke-miterlimit: 10;
  box-shadow: inset 0px 0px 0px #1b7e45;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
  border: 1px solid #4c4c4d;
}

.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}

@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}

@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #1b7e45;
  }
}

input[type=checkbox] {
  display: none;
}

input[type=checkbox]+svg {
  display: none;
}

input[type=checkbox]:checked+svg {
  display: block;
}

.form-check {
  position: relative;
}

.form-check label {
  align-items: center;
  justify-content: left;
  padding-left: 50px;
  cursor: pointer;
}

.custom-control-description {
  font-size: 12px;
  line-height: 2.6;
}

.form-check label svg {
  position: absolute;
  top: 0;
  left: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<li class="list-group-item p-4 border-top-0  first-group-item">
  <div class="form-check mb-0">
    <label class="mb-0">
      <span class="custom-control-box align-middle"></span>
      <input type="checkbox" name="item_1" value="item 1" id="checkbox"/>
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
      <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
      <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      <span class="custom-control-description align-middle">Checkbox</span>
    </label>
  </div>
  <!-- /.form-check -->
  <div class="ml-auto status">
    <p class="mb-0 incomplete">pending</p>
    <p class="mb-0 complete">done</p>
  </div>
</li>


问:
converting string representation of a date and time to the System.DateTime
```<code>DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);
</code>```

diditParse is returning false because it is expecting a format MM/DD/YYYY which differs from what I have DD/MM/YYYY

I am not sure what culture/styles or what needs to be do to get the try parse working?

答:
Try...

```<code>("fr-FR")
</code>```

although any European or other culture which represents dates in that fashion should work.

Body:
DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);

diditParse is returning false because it is expecting a format MM/DD/YYYY which differs from what I have DD/MM/YYYY

I am not sure what culture/styles or what needs to be do to get the try parse working?

Body:
Try...

("fr-FR")

although any European or other culture which represents dates in that fashion should work.


问:
How to import and Connect and listen to a web socket in React Native
In the onMasterClicked method I want to connect and send data to server with a web-socket.

I would prefer to use native web socket library from react-native, I can also use socket.io client but that was not working for me. I do not need server side code in the app, server is cloud.

Just want to know how to connect to server with a web-socket and send data, and listens to it when ever it sends data to the application

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, TouchableOpacity } from 'react-native';
import Card from '../common/Card';
import { onMasterClicked } from '../../actions';

class MasterCard extends Component {

     getMasterUnit() {
        return this.props.masterUnit;
    }

    masterClicked() {
        const cardNav = this.props.masterCardNav;

        this.props.onMasterClicked(this.getMasterUnit());

        cardNav('Room', {
            id: this.getMasterUnit().id,
            title: this.getMasterUnit().title,
        });
    }

    render() {

        return (
        <TouchableOpacity onPress={this.masterClicked.bind(this)}>
        <Card>
        <View style={styles.parentContainer}>
        <Text style={styles.masterNameTextStyles}> { this.getMasterUnit().title } </Text>
        <Text style={styles.arrowTextStyle}> > </Text>
        </View>
        </Card>
        </TouchableOpacity>
        );
    }
}

const styles = {

    parentContainer: {
        flexDirection: 'row',
        flex: 1,
        alignItems: 'center',
        height: 50
    },

    masterNameTextStyle: {
        flex: 1,
        textAlign: 'left',
        color: '#000000',
        fontSize: 16,
        textAlignVertical: 'center'
    },

    arrowTextStyle: {
        flex: 1,
        textAlign: 'right',
        color: '#000000',
        fontSize: 16,
        textAlignVertical: 'center'
    }
};

export default connect(null, { onMasterClicked })(MasterCard);
</code>```

答:
If you look at Face books simple example you can see that react-native supports web sockets. You can also look at this for more info. Web Sockets
It doesn't get any easier than that.
Note that since WebSocket is global you don't need to import anything.

```<code>var ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened
  ws.send('something'); // send a message
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};
</code>```

Body:
In the onMasterClicked method I want to connect and send data to server with a web-socket.

I would prefer to use native web socket library from react-native, I can also use socket.io client but that was not working for me. I do not need server side code in the app, server is cloud.

Just want to know how to connect to server with a web-socket and send data, and listens to it when ever it sends data to the application

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, TouchableOpacity } from 'react-native';
import Card from '../common/Card';
import { onMasterClicked } from '../../actions';

class MasterCard extends Component {

     getMasterUnit() {
        return this.props.masterUnit;
    }

    masterClicked() {
        const cardNav = this.props.masterCardNav;

        this.props.onMasterClicked(this.getMasterUnit());

        cardNav('Room', {
            id: this.getMasterUnit().id,
            title: this.getMasterUnit().title,
        });
    }

    render() {

        return (
        <TouchableOpacity onPress={this.masterClicked.bind(this)}>
        <Card>
        <View style={styles.parentContainer}>
        <Text style={styles.masterNameTextStyles}> { this.getMasterUnit().title } </Text>
        <Text style={styles.arrowTextStyle}> > </Text>
        </View>
        </Card>
        </TouchableOpacity>
        );
    }
}

const styles = {

    parentContainer: {
        flexDirection: 'row',
        flex: 1,
        alignItems: 'center',
        height: 50
    },

    masterNameTextStyle: {
        flex: 1,
        textAlign: 'left',
        color: '#000000',
        fontSize: 16,
        textAlignVertical: 'center'
    },

    arrowTextStyle: {
        flex: 1,
        textAlign: 'right',
        color: '#000000',
        fontSize: 16,
        textAlignVertical: 'center'
    }
};

export default connect(null, { onMasterClicked })(MasterCard);

Body:
If you look at Face books simple example you can see that react-native supports web sockets. You can also look at this for more info. Web Sockets
It doesn't get any easier than that.
Note that since WebSocket is global you don't need to import anything.

var ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened
  ws.send('something'); // send a message
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};