问:
Creating self-signed PowerShell scripts start to finish
While investigating this problem myself, I was unable to find any start-to finish solutions on self-signing PowerShell scripts.  So, how do you handle it all self-contained within PowerShell itself to utilize the AllSigned Execution Policy and help secure your systems better?

答:
This is a modern approach to self-signed PowerShell scripts. I found older versions of PowerShell ISE (only confirmed 2.0) will encode your scripts in Big Endian vs UTF-8 and cause issues with signing. With this method, you shouldn't run into that since we're on v4+ here.

Requirement: PoSH 4.0+.

This function will: check if a Pfx cert exists and import it to LocalMachine\TrustedPublisher; check if a cert was passed to it, export to a Pfx cert and import it; or create the cert to LocalMachine\Personal, export it, and import it.  I was unable to get the permissions to work with me to use the Cert:\CurrentUser stores outside of \My(Personal).

```<code>$ErrorActionPreference = 'Stop'

Function New-SelfSignedCertificate
{
    Param([Parameter(Mandatory=$True)]$PfxCertPath,$CertObj)

    # Creates a SecureString object
    $Cred = (Get-Credential).Password

    If (Test-Path $PfxCertPath)
    {
        Try {
          Import-PfxCertificate -FilePath $PfxCertPath -Password $Cred -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
          Write "$($PfxCertPath.FriendlyName) exists and is valid. Imported certificate to TrustedPublishers"
        } Catch {
          Write "Type mismatch or improper permission. Ensure your PFX cert is formed properly."
          Write "[$($_.Exception.GetType().FullName)] $($_.Exception.Message)"
        }
    } ElseIf ($CertObj) {
        Try {
          Export-PfxCertificate -Cert $CertObj -FilePath $PfxCertPath -Password $Cred -Force
          Import-PfxCertificate -FilePath $PfxCertPath -Password $Cred -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
        } Catch {
          Write "[$($_.Exception.GetType().FullName)] $($_.Exception.Message)"
        }
    } Else {
        Try {
          $DNS = "$((GWMI Win32_ComputerSystem).DNSHostName).$((GWMI Win32_ComputerSystem).Domain)"
          $CertObj = New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\My -DnsName $DNS -Type CodeSigningCert -FriendlyName 'Self-Sign'
          Export-PfxCertificate -Cert $CertObj -FilePath $PfxCertPath -Password $Cred -Force
          Import-PfxCertificate -FilePath $PfxCertPath -Password $Cred -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
        } Catch {
          Write "[$($_.Exception.GetType().FullName)] $($_.Exception.Message)"
        }
    }
}

# Can be called like:
#   Sign-Script -File C:\Script.ps1 -Certificate (GCI Cert:\LocalMachine\TrustedPublisher -CodeSigningCert)
#
# After the cert is imported to TrustedPublisher, you can use the
# exported pfx cert to sign on the machine instead of this method
Function Sign-Script
{
    Param($File,$Cert)
    If($Cert-is[String]){Try{$Cert=Get-PfxCertificate("$Cert")}Catch{}}
    Set-AuthenticodeSignature -FilePath $File -Certificate $Cert -Force
}
Function Check-SignedScript
{
    Param($File)
    Get-AuthenticodeSignature -FilePath $File
}
</code>```

After all is said and done, you can execute Set-ExecutionPolicy AllSigned as admin and use this script to sign all your scripts. Check-SignedScript will tell you if the sign is valid and you can tell if Sign-Script worked as your file will have # SIG # Begin signature block at the end.  Any edits to a signed script need to be re-signed in order to execute.

Body:
This is a modern approach to self-signed PowerShell scripts. I found older versions of PowerShell ISE (only confirmed 2.0) will encode your scripts in Big Endian vs UTF-8 and cause issues with signing. With this method, you shouldn't run into that since we're on v4+ here.

Requirement: PoSH 4.0+.

This function will: check if a Pfx cert exists and import it to LocalMachine\TrustedPublisher; check if a cert was passed to it, export to a Pfx cert and import it; or create the cert to LocalMachine\Personal, export it, and import it.  I was unable to get the permissions to work with me to use the Cert:\CurrentUser stores outside of \My(Personal).

$ErrorActionPreference = 'Stop'

Function New-SelfSignedCertificate
{
    Param([Parameter(Mandatory=$True)]$PfxCertPath,$CertObj)

    # Creates a SecureString object
    $Cred = (Get-Credential).Password

    If (Test-Path $PfxCertPath)
    {
        Try {
          Import-PfxCertificate -FilePath $PfxCertPath -Password $Cred -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
          Write "$($PfxCertPath.FriendlyName) exists and is valid. Imported certificate to TrustedPublishers"
        } Catch {
          Write "Type mismatch or improper permission. Ensure your PFX cert is formed properly."
          Write "[$($_.Exception.GetType().FullName)] $($_.Exception.Message)"
        }
    } ElseIf ($CertObj) {
        Try {
          Export-PfxCertificate -Cert $CertObj -FilePath $PfxCertPath -Password $Cred -Force
          Import-PfxCertificate -FilePath $PfxCertPath -Password $Cred -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
        } Catch {
          Write "[$($_.Exception.GetType().FullName)] $($_.Exception.Message)"
        }
    } Else {
        Try {
          $DNS = "$((GWMI Win32_ComputerSystem).DNSHostName).$((GWMI Win32_ComputerSystem).Domain)"
          $CertObj = New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\My -DnsName $DNS -Type CodeSigningCert -FriendlyName 'Self-Sign'
          Export-PfxCertificate -Cert $CertObj -FilePath $PfxCertPath -Password $Cred -Force
          Import-PfxCertificate -FilePath $PfxCertPath -Password $Cred -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
        } Catch {
          Write "[$($_.Exception.GetType().FullName)] $($_.Exception.Message)"
        }
    }
}

# Can be called like:
#   Sign-Script -File C:\Script.ps1 -Certificate (GCI Cert:\LocalMachine\TrustedPublisher -CodeSigningCert)
#
# After the cert is imported to TrustedPublisher, you can use the
# exported pfx cert to sign on the machine instead of this method
Function Sign-Script
{
    Param($File,$Cert)
    If($Cert-is[String]){Try{$Cert=Get-PfxCertificate("$Cert")}Catch{}}
    Set-AuthenticodeSignature -FilePath $File -Certificate $Cert -Force
}
Function Check-SignedScript
{
    Param($File)
    Get-AuthenticodeSignature -FilePath $File
}

After all is said and done, you can execute Set-ExecutionPolicy AllSigned as admin and use this script to sign all your scripts. Check-SignedScript will tell you if the sign is valid and you can tell if Sign-Script worked as your file will have # SIG # Begin signature block at the end.  Any edits to a signed script need to be re-signed in order to execute.


来源: stackexchange

问:
Finding closest match in collection of numbers
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

```<code>1, 3, 8, 10, 13, ...
</code>```

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

OwnerDisplayName: Slace

ContentLicense: CC BY-SA 2.5

Body:
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

1, 3, 8, 10, 13, ...

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

LastEditorDisplayName: Allain Lalonde

Body:
Perl -- 66 chars:

perl -e 'for(qw/1 3 8 10 13/){$d=($_-4)**2; $c=$_ if not $x or $d<$x;$x=$d;}print $c;'

OwnerDisplayName: gpojd


问:
Calling another ruby file that is not a gem
I want to create a static ruby class with a library of function. I am on Vista with ruby 1.9.2

My class is this one :

```<code>class TestClass

  def say_hello
    puts "say hello"
  end
end
</code>```

in a TestClass.rb file (I assume I am correct as all ruby tutorials on classes are a complete mess putting everything in a single magic something (file?) as if IRB was the begining and the end of all thing).

My ruby main() (yes I come from Java) or program entry or wathever it is called in ruby is :

```<code>require 'TestClass.rb'

puts "start"
say_hello
</code>```

But it fails with :

```<code>C:\ruby_path_with_all_my_classes>ruby classuser.rb
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load --
 TestClass.rb (LoadError)
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from classuser.rb:1:in `<main>'
</code>```

How does it work? Is it possible to call other files in Ruby or are you trapped in only one file containing all your classes?

答:
Try using

```<code>require './TestClass.rb'
</code>```

Related: Ruby: require vs require_relative - best practice to workaround running in both Ruby <1.9.2 and >=1.9.2

Body:
I want to create a static ruby class with a library of function. I am on Vista with ruby 1.9.2

My class is this one :

class TestClass

  def say_hello
    puts "say hello"
  end
end

in a TestClass.rb file (I assume I am correct as all ruby tutorials on classes are a complete mess putting everything in a single magic something (file?) as if IRB was the begining and the end of all thing).

My ruby main() (yes I come from Java) or program entry or wathever it is called in ruby is :

require 'TestClass.rb'

puts "start"
say_hello

But it fails with :

C:\ruby_path_with_all_my_classes>ruby classuser.rb
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load --
 TestClass.rb (LoadError)
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from classuser.rb:1:in `'

How does it work? Is it possible to call other files in Ruby or are you trapped in only one file containing all your classes?

Body:
Try using

require './TestClass.rb'

Related: Ruby: require vs require_relative - best practice to workaround running in both Ruby <1.9.2 and >=1.9.2


问:
Prevent user to input value larger than from other input value
How do i prevent and give alert so user can't input the value of totalontarget and totalofftarget to be larger than totalofservices</p>

```<code><script>
   $(document).ready(function() {
     $('.totalofservices').keyup(function(){
       $(this).closest('tr').find(".totalontarget").val($(this).val());
       $(this).closest('tr').find(".totalofftarget").val("0");
     });
   });
</script>

for($x = 1; $x <= 3; ++$x) {
    echo "
    <tr>
      <td>Zone $x</td>
      <td><input style='text-align:center' class='form-control totalofservices' type='text' size='20' id='totalofservices[]' name='totalofservices'></td>
      <td><input style='text-align:center' class='form-control totalontarget' type='text' size='20' id='totalontarget' name='totalontarget[]'></td>
      <td><input style='text-align:center' class='form-control totalofftarget' type='text' size='20' id='totalofftarget' name='totalofftarget[]'></td>
    </tr>";
}
</code>```

答:
Try something like that</p>

```<code>$('.totalontarget, .totalofftarget').on('keyup', function(e){
    var max = $(this).parent().parent().find('.totalofservices').val();

        if ($(this).val() > max) {
           alert('Value more that ' + max);
           e.preventDefault();
        }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do i prevent and give alert so user can't input the value of totalontarget and totalofftarget to be larger than totalofservices

for($x = 1; $x <= 3; ++$x) {
    echo "

      Zone $x
      <input style='text-align:center' class='form-control totalofservices' type='text' size='20' id='totalofservices[]' name='totalofservices'>
      <input style='text-align:center' class='form-control totalontarget' type='text' size='20' id='totalontarget' name='totalontarget[]'>
      <input style='text-align:center' class='form-control totalofftarget' type='text' size='20' id='totalofftarget' name='totalofftarget[]'>

";
}

Body:
Try something like that

$('.totalontarget, .totalofftarget').on('keyup', function(e){
    var max = $(this).parent().parent().find('.totalofservices').val();

        if ($(this).val() > max) {
           alert('Value more that ' + max);
           e.preventDefault();
        }
});


问:
Mapped Event throws
I have mapped all classes from an assembly.  When starting up Rebus mentions as it should:

```<code>Mapped MyNamespace.Events.EmailSend -> Rebus/Test/Input
</code>```

But I get an error when I try to submit a message inside a handler, using the code below:

```<code>await _bus.Send(new EmailSend
{
    MyProperty = 1
}).ConfigureAwait(false);
</code>```

I tried also with .Reply() and .SendLocal(), but that does not help me getting rid of the error below.

The stack trace:

```<code>Rebus.Retry.ErrorTracking.InMemErrorTracker WARN (Thread #10): Unhandled exception 1 while handling message with ID a2c3b234-f519-4d86-bec9-715b2045ef94: Rebus.Exceptions.RebusApplicationException: Message with ID a2c3b234-f519-4d86-bec9-715b2045ef94 and type MyNamespace.Events.EmailSend, MyAssembly.Messaging.Models could not be dispatched to any handlers
at Rebus.Pipeline.Receive.DispatchIncomingMessageStep.<Process>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Sagas.LoadSagaDataStep.<Process>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Pipeline.Receive.ActivateHandlersStep.<Process>d__3.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Pipeline.Receive.DeserializeIncomingMessageStep.<Process>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Retry.Simple.SimpleRetryStrategyStep.<DispatchWithTrackerIdentifier>d__7.MoveNext()
</code>```

答:
The _bus.Send() was being called with .ConfigureAwait(true), seems this needs to be "false" when submitting a message from the bus.

Oh and the handler class was internal.

Guess one of those were the real issue - or a combination...

Title: Mapped Event throws

Body:
I have mapped all classes from an assembly.  When starting up Rebus mentions as it should:

Mapped MyNamespace.Events.EmailSend -> Rebus/Test/Input

But I get an error when I try to submit a message inside a handler, using the code below:

await _bus.Send(new EmailSend
{
    MyProperty = 1
}).ConfigureAwait(false);

I tried also with .Reply() and .SendLocal(), but that does not help me getting rid of the error below.

The stack trace:

Rebus.Retry.ErrorTracking.InMemErrorTracker WARN (Thread #10): Unhandled exception 1 while handling message with ID a2c3b234-f519-4d86-bec9-715b2045ef94: Rebus.Exceptions.RebusApplicationException: Message with ID a2c3b234-f519-4d86-bec9-715b2045ef94 and type MyNamespace.Events.EmailSend, MyAssembly.Messaging.Models could not be dispatched to any handlers
at Rebus.Pipeline.Receive.DispatchIncomingMessageStep.<Process>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Sagas.LoadSagaDataStep.<Process>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Pipeline.Receive.ActivateHandlersStep.<Process>d__3.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Pipeline.Receive.DeserializeIncomingMessageStep.<Process>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Retry.Simple.SimpleRetryStrategyStep.<DispatchWithTrackerIdentifier>d__7.MoveNext()


问:
How to concatenate multiple pandas.DataFrames without running into MemoryError
I have three DataFrames that I'm trying to concatenate.

```<code>concat_df = pd.concat([df1, df2, df3])
</code>```

This results in a MemoryError. How can I resolve this?

Note that most of the existing similar questions are on MemoryErrors occuring when reading large files. I don't have that problem. I have read my files in into DataFrames. I just can't concatenate that data.

答:
The problem is, like viewed in the others answers, a problem of memory. And a solution is to store data on disk, then  to build an unique dataframe.

With such huge data, performance is an issue.

csv solutions are very slow, since conversion in text mode occurs.
HDF5 solutions are shorter, more elegant and faster since using binary mode.
I propose a third way in binary mode, with pickle, which seems to be even faster, but more technical and needing some more room. And a fourth, by hand.

Here the code:

```<code>import numpy as np
import pandas as pd
import os
import pickle

# a DataFrame factory:
dfs=[]
for i in range(10):
    dfs.append(pd.DataFrame(np.empty((10**5,4)),columns=range(4)))

# a csv solution
def bycsv(dfs):
    md,hd='w',True
    for df in dfs:
        df.to_csv('df_all.csv',mode=md,header=hd,index=None)
        md,hd='a',False
    #del dfs
    df_all=pd.read_csv('df_all.csv',index_col=None)
    os.remove('df_all.csv')
    return df_all

</code>```

Better solutions :

```<code>def byHDF(dfs):
    store=pd.HDFStore('df_all.h5')
    for df in dfs:
        store.append('df',df,data_columns=list('0123'))
    #del dfs
    df=store.select('df')
    store.close()
    os.remove('df_all.h5')
    return df

def bypickle(dfs):
    c=[]
    with open('df_all.pkl','ab') as f:
        for df in dfs:
            pickle.dump(df,f)
            c.append(len(df))
    #del dfs
    with open('df_all.pkl','rb') as f:
        df_all=pickle.load(f)
        offset=len(df_all)
        df_all=df_all.append(pd.DataFrame(np.empty(sum(c[1:])*4).reshape(-1,4)))

        for size in c[1:]:
            df=pickle.load(f)
            df_all.iloc[offset:offset+size]=df.values
            offset+=size
    os.remove('df_all.pkl')
    return df_all

</code>```

For homogeneous dataframes, we can do even better :

```<code>def byhand(dfs):
    mtot=0
    with open('df_all.bin','wb') as f:
        for df in dfs:
            m,n =df.shape
            mtot += m
            f.write(df.values.tobytes())
            typ=df.values.dtype
    #del dfs
    with open('df_all.bin','rb') as f:
        buffer=f.read()
        data=np.frombuffer(buffer,dtype=typ).reshape(mtot,n)
        df_all=pd.DataFrame(data=data,columns=list(range(n)))
    os.remove('df_all.bin')
    return df_all
</code>```

And some tests on (little, 32 Mb) data to compare performance. you have to multiply by about 128 for 4 Gb.

```<code>In [92]: %time w=bycsv(dfs)
Wall time: 8.06 s

In [93]: %time x=byHDF(dfs)
Wall time: 547 ms

In [94]: %time v=bypickle(dfs)
Wall time: 219 ms

In [95]: %time y=byhand(dfs)
Wall time: 109 ms
</code>```

A check :

```<code>In [195]: (x.values==w.values).all()
Out[195]: True

In [196]: (x.values==v.values).all()
Out[196]: True

In [197]: (x.values==y.values).all()
Out[196]: True

</code>```

Of course all of that must be improved and tuned to fit your problem.

For exemple  df3 can be split in chuncks of size 'total_memory_size - df_total_size' to be able to run bypickle.

I can edit it if you give more information on your data structure and size if you want. Beautiful question !

Body:
I have three DataFrames that I'm trying to concatenate.

concat_df = pd.concat([df1, df2, df3])

This results in a MemoryError. How can I resolve this?

Note that most of the existing similar questions are on MemoryErrors occuring when reading large files. I don't have that problem. I have read my files in into DataFrames. I just can't concatenate that data.

Body:
The problem is, like viewed in the others answers, a problem of memory. And a solution is to store data on disk, then  to build an unique dataframe.

With such huge data, performance is an issue.

csv solutions are very slow, since conversion in text mode occurs.
HDF5 solutions are shorter, more elegant and faster since using binary mode.
I propose a third way in binary mode, with pickle, which seems to be even faster, but more technical and needing some more room. And a fourth, by hand.

Here the code:

import numpy as np
import pandas as pd
import os
import pickle

# a DataFrame factory:
dfs=[]
for i in range(10):
    dfs.append(pd.DataFrame(np.empty((10**5,4)),columns=range(4)))

# a csv solution
def bycsv(dfs):
    md,hd='w',True
    for df in dfs:
        df.to_csv('df_all.csv',mode=md,header=hd,index=None)
        md,hd='a',False
    #del dfs
    df_all=pd.read_csv('df_all.csv',index_col=None)
    os.remove('df_all.csv')
    return df_all

Better solutions :

def byHDF(dfs):
    store=pd.HDFStore('df_all.h5')
    for df in dfs:
        store.append('df',df,data_columns=list('0123'))
    #del dfs
    df=store.select('df')
    store.close()
    os.remove('df_all.h5')
    return df

def bypickle(dfs):
    c=[]
    with open('df_all.pkl','ab') as f:
        for df in dfs:
            pickle.dump(df,f)
            c.append(len(df))
    #del dfs
    with open('df_all.pkl','rb') as f:
        df_all=pickle.load(f)
        offset=len(df_all)
        df_all=df_all.append(pd.DataFrame(np.empty(sum(c[1:])*4).reshape(-1,4)))

        for size in c[1:]:
            df=pickle.load(f)
            df_all.iloc[offset:offset+size]=df.values
            offset+=size
    os.remove('df_all.pkl')
    return df_all

For homogeneous dataframes, we can do even better :

def byhand(dfs):
    mtot=0
    with open('df_all.bin','wb') as f:
        for df in dfs:
            m,n =df.shape
            mtot += m
            f.write(df.values.tobytes())
            typ=df.values.dtype
    #del dfs
    with open('df_all.bin','rb') as f:
        buffer=f.read()
        data=np.frombuffer(buffer,dtype=typ).reshape(mtot,n)
        df_all=pd.DataFrame(data=data,columns=list(range(n)))
    os.remove('df_all.bin')
    return df_all

And some tests on (little, 32 Mb) data to compare performance. you have to multiply by about 128 for 4 Gb.

In [92]: %time w=bycsv(dfs)
Wall time: 8.06 s

In [93]: %time x=byHDF(dfs)
Wall time: 547 ms

In [94]: %time v=bypickle(dfs)
Wall time: 219 ms

In [95]: %time y=byhand(dfs)
Wall time: 109 ms

A check :

In [195]: (x.values==w.values).all()
Out[195]: True

In [196]: (x.values==v.values).all()
Out[196]: True

In [197]: (x.values==y.values).all()
Out[196]: True

Of course all of that must be improved and tuned to fit your problem.

For exemple  df3 can be split in chuncks of size 'total_memory_size - df_total_size' to be able to run bypickle.

I can edit it if you give more information on your data structure and size if you want. Beautiful question !

ContentLicense: CC BY-SA 4.0


问:
Is it considered accepted using var's as "shortcuts" in c#?
One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:

MyApp.Properties.Settings.Default.Value=1;

That's a ton of unnecessary code. An alternative to this is declaring:

```<code>using MyApp.Properties;
</code>```

-- or --

```<code>using appsettings = MyAppp.Properties.Settings;
</code>```

leading to: appsettings.Default.Value=1 or Settings.Default.Value=1

Abit better, but I'd like it shorter still:

```<code>var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;
</code>```

Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)

答: There is nothing wrong with that, as long as the code is clear.</p>

Body:
One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:

MyApp.Properties.Settings.Default.Value=1;

That's a ton of unnecessary code. An alternative to this is declaring:

using MyApp.Properties;

-- or --

using appsettings = MyAppp.Properties.Settings;

leading to: appsettings.Default.Value=1 or Settings.Default.Value=1

Abit better, but I'd like it shorter still:

var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;

Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)


问:
bootstrap carousel images are stacked on top of each other regardless of screen width
I am trying to make a bootstrap carousel that automatically switches between images in a given sequence. Everything is working in regards to controls (i.e arrows for going back and forth between pics & slide position indicator), but the images are stacked on top of each other when I load the page. Can someone point out an issue in this?</p>

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Appraisal</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=VT323" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.3.2/css/mdb.min.css">
  </head>

  <body>
    <header>
      <h1 class="animated slideInLeft">text goes here</h1>
      <p>...</p>
      <h4 class="animated slideInRight">portfolio</h4>
    </header>

    <div id="myCarousel" class="carousel slide">
      <ol class="carousel-indicators">
        <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
        <li data-target="#myCarousel" data-slide-to="1"></li>
        <li data-target="#myCarousel" data-slide-to="2"></li>
      </ol>

      <div class="carousel_inner">

        <div class="item active">
          <img src="./pics/space_1.jpg" alt="Space 1" class="img-responsive">
          <div class="carousel-caption">
            <h3>Appraisal 1</h3>
            <p></p>
          </div>
        </div>

        <div class="item">
          <img src="./pics/space_2.jpg" alt="Space 2" class="img-responsive">
          <div class="carousel-caption">
            <h3>Appraisal 2</h3>
            <p></p>
          </div>
        </div>

        <div class="item">
          <img src="./pics/space_3.jpg" alt="Space 2" class="img-responsive">
          <div class="carousel-caption">
            <h3>Appraisal 3</h3>
            <p></p>
          </div>
        </div>

      </div>

      <a href="#myCarousel" class="carousel-control" data-slide="prev">
        <span class="icon-prev left"></span>
      </a>
      <a href="#myCarousel" class="carousel-control" data-slide="next">
        <span class="icon-next right"></span>
      </a>
    </div>

    <div class="skills">

    </div>

    <div class="certs">

    </div>

    <footer>
      <p>developed by: jefferson steelflex</p>

    </footer>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.3.2/js/mdb.min.js"></script>
  </body>
</html>
</code>```

答: It's just a typo. Just change the class "carousel_inner" in the slides container div for "carousel-inner".</p>

Body:
I am trying to make a bootstrap carousel that automatically switches between images in a given sequence. Everything is working in regards to controls (i.e arrows for going back and forth between pics & slide position indicator), but the images are stacked on top of each other when I load the page. Can someone point out an issue in this?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Appraisal</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=VT323" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.3.2/css/mdb.min.css">

text goes here

...

portfolio

Appraisal 1

Appraisal 2

Appraisal 3

developed by: jefferson steelflex


问:
"Exception in thread "main" java.lang.NullPointerException" error in Rolling Dice Program
I am writing this basic program with 3 classes in 3 separate files. It is supposed to be a program consisting of a class called PairOfDice, composed of two Die objects. Included methods to set and get the individual die values, a method to roll the dice,and a method that returns the current sum of the two die values. A driver class called RollingDice to instantiate and use a PairOfDice object.

It compiles without problems but when I try to run it results in a run-time error as follows:

Exception in thread "main" java.lang.NullPointerException     at
  PairOfDice.rollDice(PairOfDice.java:42)   at
  RollingDice.main(RollingDice2.java:16)

```<code>public class RollingDice
{
    public static void main(String[] args)
    {
        PairOfDice pairofdice=new PairOfDice();

        pairofdice.rollDice();

        System.out.println(pairofdice.getDie1() +"\t" +pairofdice.getDie2());
     }
}

public class PairOfDice
{
    private Die die1, die2;

    public PairOfDice()
    {
        Die die1=new Die();
        Die die2=new Die();
    }

    public int getDie1()
    {
        return die1.getFaceValue();
    }

    public int getDie2()
    {
        return die2.getFaceValue();
    }

    public void setDie1(int dieValue)
    {
        die1.setFaceValue(dieValue);
    }

    public void setDie2(int dieValue)
    {
        die2.setFaceValue(dieValue);
    }

    public void rollDice()
    {
        die1.roll();
        die2.roll();
    }

    public int sum()
    {
        return die1.getFaceValue()+die2.getFaceValue();
    }
}

public class Die
{
    private final int MAX = 6;
    private int faceValue;

    public Die()
    {
        faceValue = 1;
    }

    public void roll()
    {
        faceValue = (int)(Math.random() * MAX) + 1;
    }

    public void setFaceValue(int value)
    {
        faceValue = value;
    }

    public int getFaceValue()

    {
        return faceValue;
    }

    public String toString()
    {
        String result = Integer.toString(faceValue);
        return result;
    }
}
</code>```

答:
use

```<code> public PairOfDice()
    {
        die1=new Die();
        die2=new Die();
    }
</code>```

You are trying to declare die1 and die2 in constructor. Thus the local variables were not initializing.

Body:
I am writing this basic program with 3 classes in 3 separate files. It is supposed to be a program consisting of a class called PairOfDice, composed of two Die objects. Included methods to set and get the individual die values, a method to roll the dice,and a method that returns the current sum of the two die values. A driver class called RollingDice to instantiate and use a PairOfDice object.

It compiles without problems but when I try to run it results in a run-time error as follows:

Exception in thread "main" java.lang.NullPointerException     at
  PairOfDice.rollDice(PairOfDice.java:42)   at
  RollingDice.main(RollingDice2.java:16)

public class RollingDice
{
    public static void main(String[] args)
    {
        PairOfDice pairofdice=new PairOfDice();

        pairofdice.rollDice();

        System.out.println(pairofdice.getDie1() +"\t" +pairofdice.getDie2());
     }
}

public class PairOfDice
{
    private Die die1, die2;

    public PairOfDice()
    {
        Die die1=new Die();
        Die die2=new Die();
    }

    public int getDie1()
    {
        return die1.getFaceValue();
    }

    public int getDie2()
    {
        return die2.getFaceValue();
    }

    public void setDie1(int dieValue)
    {
        die1.setFaceValue(dieValue);
    }

    public void setDie2(int dieValue)
    {
        die2.setFaceValue(dieValue);
    }

    public void rollDice()
    {
        die1.roll();
        die2.roll();
    }

    public int sum()
    {
        return die1.getFaceValue()+die2.getFaceValue();
    }
}

public class Die
{
    private final int MAX = 6;
    private int faceValue;

    public Die()
    {
        faceValue = 1;
    }

    public void roll()
    {
        faceValue = (int)(Math.random() * MAX) + 1;
    }

    public void setFaceValue(int value)
    {
        faceValue = value;
    }

    public int getFaceValue()

    {
        return faceValue;
    }

    public String toString()
    {
        String result = Integer.toString(faceValue);
        return result;
    }
}

Body:
use

 public PairOfDice()
    {
        die1=new Die();
        die2=new Die();
    }

You are trying to declare die1 and die2 in constructor. Thus the local variables were not initializing.


问:
Neo4j stuck when create relation with big data
i'm using this cypher query to create relationship between two nodes in Neo4j

```<code>MATCH (first:FIRSTNODE)
with first
MATCH (second:SECONDNODE)
WHERE first.ID = second.ID
CREATE (first)-[:RELATION]->(second)
</code>```

first has 100.000 of nodes and second has 1.100.000 nodes.

I have imported the csv file and then i've created index of the two tables; but when i try to run the query with the relation neo4j got stuck and stop working.
I noticed that the cpu usage goes at 100% when this happens.

I'm working with an cpu of 8x4.0Ghz and 10Gb of ram and an SSD.

Do you know something that can help me to resolve this problem?

EDIT 1:

Using apoc.periodic.commit it works. But if then i run a second query like this:

```<code>call apoc.periodic.commit("
    MATCH (third:THIRDNODE)
    WHERE NOT (third)-[:RELATION2]->()
    WITH third LIMIT {limit}
    MATCH (second:SECONDNODE)
    WHERE third.ID = second.ID2
    CREATE (third)-[:RELATION2]->(second)
    RETURN count(*)
", {limit:10000})
</code>```

it got stuck again

答:
You can try using apoc.periodic.commit from APOC Procedures. The docs about this procedure says:

apoc.periodic.commit(statement,params) - runs the given statement in
  separate transactions until it returns 0

Install APOC Procedures and try it:

```<code>call apoc.periodic.commit("
    MATCH (first:FIRSTNODE),
    WHERE NOT (first)-[:RELATION]->()
    WITH first LIMIT {limit}
    MATCH (second:SECONDNODE)
    WHERE first.ID = second.ID
    CREATE (first)-[:RELATION]->(second)
    RETURN count(*)
", {limit:10000})
</code>```

Remember to install APOC procedures according the version of Neo4j you are using. Take a look in the version compatibility matrix.

Body:
i'm using this cypher query to create relationship between two nodes in Neo4j

MATCH (first:FIRSTNODE)
with first
MATCH (second:SECONDNODE)
WHERE first.ID = second.ID
CREATE (first)-[:RELATION]->(second)

first has 100.000 of nodes and second has 1.100.000 nodes.

I have imported the csv file and then i've created index of the two tables; but when i try to run the query with the relation neo4j got stuck and stop working.
I noticed that the cpu usage goes at 100% when this happens.

I'm working with an cpu of 8x4.0Ghz and 10Gb of ram and an SSD.

Do you know something that can help me to resolve this problem?

EDIT 1:

Using apoc.periodic.commit it works. But if then i run a second query like this:

call apoc.periodic.commit("
    MATCH (third:THIRDNODE)
    WHERE NOT (third)-[:RELATION2]->()
    WITH third LIMIT {limit}
    MATCH (second:SECONDNODE)
    WHERE third.ID = second.ID2
    CREATE (third)-[:RELATION2]->(second)
    RETURN count(*)
", {limit:10000})

it got stuck again

Body:
You can try using apoc.periodic.commit from APOC Procedures. The docs about this procedure says:

apoc.periodic.commit(statement,params) - runs the given statement in
  separate transactions until it returns 0

Install APOC Procedures and try it:

call apoc.periodic.commit("
    MATCH (first:FIRSTNODE),
    WHERE NOT (first)-[:RELATION]->()
    WITH first LIMIT {limit}
    MATCH (second:SECONDNODE)
    WHERE first.ID = second.ID
    CREATE (first)-[:RELATION]->(second)
    RETURN count(*)
", {limit:10000})

Remember to install APOC procedures according the version of Neo4j you are using. Take a look in the version compatibility matrix.


问:
Is python is a good choice as language used to implementing my first 3D model?
I am C/C  /Java programmer, but lately I have started learn Python.

Moreover I have 3D Graphics on my studies. I have to create 3D model of my apartment, with dynamic camera. I am wondering if this is a good idea to merge this two issues, by writing this 3D model in python.

However as I said, I am a python beginner, so I don't know possibilities, which python can give me in this area. Which libraries/engine will be the best for a start?

答:
If you're solely trying to learn how to do a 3d model go for the language you're the most familiar with. I'd recommend C++ or C# in that case (whichever of the 2 you meant with the second C).

If you also want to learn more about the language Python is the better choice.

But pure language wise I wouldn't say that C++/c#/python beats the other.


问:
Error:(26, 13) Failed to resolve: com.android.support:appcompat-v7:25.+
I am facing gradle error when I build a project (simple helloworld app) in android studio 2.3.3. I have attached here screen shot that describes error messages I am facing. Please help me how to get rid of it?

NOTE -Please tell me which code files are to be added to get rid of this type of error.

My build.gradle:

```<code>buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.1'

       }
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

答:
Looking at your question title, Error:(26, 13) Failed to resolve: com.android.support:appcompat-v7:25.+

Do not use that kind of version that has + sign as AS will keep on checking any new version of the libraries associated with that kind of declaration. Use it the stable one, as of now 25.4.0 as of June 2017.

And if you're not sure what version is stable or not, head up here,
https://developer.android.com/topic/libraries/support-library/revisions.html

Body:
I am facing gradle error when I build a project (simple helloworld app) in android studio 2.3.3. I have attached here screen shot that describes error messages I am facing. Please help me how to get rid of it?

NOTE -Please tell me which code files are to be added to get rid of this type of error.

My build.gradle:

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.1'

       }
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}


问:
Colour Individual Items in a winforms ComboBox?
I have a dilemma whereby I have a form which contains a number of comboboxes that contain information/options/items that may be invalid/out-of-date in certain circumstances.

I can't simply remove the out-of-date information from the items, but I do want to give the user a visual-clue when options are invalid.

I was thinking of colouring in the Items (probably red) to indicate if & when they are invalid.  I don't necessarily need to prevent a user from selecting an invalid option, just make them visually aware that they are doing so.

Can this be done? Can you - dyamically - change the colo(u)r of combobox items?

Thanks,

答:
Changing color of combobox back color

You can use this codes for changing back color of combobox.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Comboboxrenklendir
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void cmbrenkli_DrawItem(object sender, DrawItemEventArgs e)
    {

        Color HighlightColor = Color.Red;

        if (e.Index >=0)
        {

            //int sayi = cmbrenkli.Items.Count;

            string deger = cmbrenkli.Items[e.Index].ToString();

            if (deger == "30"|| deger == "50")
            {
                e.Graphics.FillRectangle(new SolidBrush(HighlightColor), e.Bounds);
            }

            e.Graphics.DrawString(cmbrenkli.Items[e.Index].ToString(), e.Font, new SolidBrush(cmbrenkli.ForeColor), new Point(e.Bounds.X, e.Bounds.Y));

            e.DrawFocusRectangle();

        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cmbrenkli.Items.Add("10");
        cmbrenkli.Items.Add("20");
        cmbrenkli.Items.Add("30");
        cmbrenkli.Items.Add("40");
        cmbrenkli.Items.Add("50");
    }
}
}
</code>```

Body:
Changing color of combobox back color

You can use this codes for changing back color of combobox.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Comboboxrenklendir
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void cmbrenkli_DrawItem(object sender, DrawItemEventArgs e)
    {

        Color HighlightColor = Color.Red;

        if (e.Index >=0)
        {

            //int sayi = cmbrenkli.Items.Count;

            string deger = cmbrenkli.Items[e.Index].ToString();

            if (deger == "30"|| deger == "50")
            {
                e.Graphics.FillRectangle(new SolidBrush(HighlightColor), e.Bounds);
            }

            e.Graphics.DrawString(cmbrenkli.Items[e.Index].ToString(), e.Font, new SolidBrush(cmbrenkli.ForeColor), new Point(e.Bounds.X, e.Bounds.Y));

            e.DrawFocusRectangle();

        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cmbrenkli.Items.Add("10");
        cmbrenkli.Items.Add("20");
        cmbrenkli.Items.Add("30");
        cmbrenkli.Items.Add("40");
        cmbrenkli.Items.Add("50");
    }
}
}


问:
Why doesn't my innerHTML method work to list things in my contact form?
I am making a program, and I'm wondering why all I see on my html page is the form, but only a single . where the bulleted list for an unordered list should be.  I input the user input in the fields, but it doesn't show me the data in the fields, like it's supposed to, when I click submit.  Here's the code.</p>

```<code>function getFormElements() {
    var gather_form_elements = new Array(
        $("#first_name").val(),
        $("#last_name").val(),
        $("email").val(),
        $("#phone_number").val()
    );

    displayValues(gather_form_elements);
}

function displayValues(gather_form_elements) {

    for(i=0; i<gather_form_elements.length; i++)
    {
        document.getElementById("contact_info").innerHTML = "<li>" + gather_form_elements[i] + "</li>";
    }
}
</code>```

答:
Because you are overiding it on every iteration. Try to accumulate the html before using innerHTML like this:

```<code>var html = "";
for(var i = 0; i < gather_form_elements.length; i++) {
    html += "<li>" + gather_form_elements[i] + "</li>";
//       ^^ the += is crucial. If you don't use it, it will just replace the content of html (the innerHTML in your code), we need to use += to append to html instead of overriding it.
}
document.getElementById("contact_info").innerHTML = html;
</code>```

You can acheive the same result using only one line of code:

```<code>document.getElementById("contact_info").innerHTML =
    '<li>' + gather_form_elements.join('</li><li>') + '</li>';
</code>```

Body:
I am making a program, and I'm wondering why all I see on my html page is the form, but only a single . where the bulleted list for an unordered list should be.  I input the user input in the fields, but it doesn't show me the data in the fields, like it's supposed to, when I click submit.  Here's the code.

function getFormElements() {
    var gather_form_elements = new Array(
        $("#first_name").val(),
        $("#last_name").val(),
        $("email").val(),
        $("#phone_number").val()
    );

    displayValues(gather_form_elements);
}

function displayValues(gather_form_elements) {

    for(i=0; i<gather_form_elements.length; i++)
    {
        document.getElementById("contact_info").innerHTML = "
" + gather_form_elements[i] + "
";
    }
}

Body:
Because you are overiding it on every iteration. Try to accumulate the html before using innerHTML like this:

var html = "";
for(var i = 0; i < gather_form_elements.length; i++) {
    html += "<li>" + gather_form_elements[i] + "</li>";
//       ^^ the += is crucial. If you don't use it, it will just replace the content of html (the innerHTML in your code), we need to use += to append to html instead of overriding it.
}
document.getElementById("contact_info").innerHTML = html;

You can acheive the same result using only one line of code:

document.getElementById("contact_info").innerHTML =
    '<li>' + gather_form_elements.join('</li><li>') + '</li>';


问:
NodeJS sync flow
Hello i have been using a library called deasync it allows me to get things done in a cleaner way, i have a method like this,

```<code>syncGetMany: function(model, query){
        var ret;
        setTimeout(function(){

         model.find(query, (error, body) => {
            if(body){
                //Awesome got the data
                ret=  body
            }
            else{

                 //What a cruel world

                // No data, fall back to an empty array
                ret = [];
            }

        });

        },0);
        while(ret === undefined) {
            require('deasync').sleep(0);
        }

        //returns an empty array or the real data
        return ret;
},
</code>```

Then i simply call it like this.

```<code>var data = syncGetMany(MongooseModel, queryObj);
// the rest of my code
</code>```

QUESTION: is there a way to get this done using ES6, or any similar library.

PS: Not duplicate as other questions are not relevant to my context

答:
You can write and execute logic as if it was synchronous using nsynjs:

```<code>function synhronousCode(model, query) {
    function syncGetMany(model, query){
        return model.find(query).data; // data will contain result of resolved promise at this point
    };

    var data = syncGetMany(model, query);
    // do stuff with data
}

var nsynjs = require('nsynjs');
....
nsynjs.run(synhronousCode,{},model, query, function(){
    console.log('synhronousCode done');
});
</code>```

nsynjs will evaluate code in synhronousCode in sequential manner: if some function returns promise (as model.find does), nsynjs will pause execution and wait until promise is resolved, assigns result to data property of returned value, and then continue execution.

Title: NodeJS sync flow

Body:
Hello i have been using a library called deasync it allows me to get things done in a cleaner way, i have a method like this,

syncGetMany: function(model, query){
        var ret;
        setTimeout(function(){

         model.find(query, (error, body) => {
            if(body){
                //Awesome got the data
                ret=  body
            }
            else{

                 //What a cruel world

                // No data, fall back to an empty array
                ret = [];
            }

        });

        },0);
        while(ret === undefined) {
            require('deasync').sleep(0);
        }

        //returns an empty array or the real data
        return ret;
},

Then i simply call it like this.

var data = syncGetMany(MongooseModel, queryObj);
// the rest of my code

QUESTION: is there a way to get this done using ES6, or any similar library.

PS: Not duplicate as other questions are not relevant to my context

Body:
You can write and execute logic as if it was synchronous using nsynjs:

function synhronousCode(model, query) {
    function syncGetMany(model, query){
        return model.find(query).data; // data will contain result of resolved promise at this point
    };

    var data = syncGetMany(model, query);
    // do stuff with data
}

var nsynjs = require('nsynjs');
....
nsynjs.run(synhronousCode,{},model, query, function(){
    console.log('synhronousCode done');
});

nsynjs will evaluate code in synhronousCode in sequential manner: if some function returns promise (as model.find does), nsynjs will pause execution and wait until promise is resolved, assigns result to data property of returned value, and then continue execution.


问:
recover lost C# pages
I had a problem I lost all my source(CS) of web site pages but I had only published pages on server ,so please if there is any way to recover theses published pages to orignal pages with code,bin folder</p>

答:
Use your latest backup copy, or roll back to the previous version of SVN you are working on.

http://www.red-gate.com/products/dotnet-development/reflector/ is a good piece of software for recovering source from a compiled program.

Title: recover lost C# pages


问:
Deleting table view row data from data source
I have a data source which holds different lists like in apples notes app.
When the user taps on one row in the ListViewController (all lists) a second ViewController is presented which holds only the data of this list.
The whole data source is in a plist and the key is the list name:

```<code>    var items = [Items]()
    var showItems = [Items]()

    func loadPlistData() {

    // Connect to plist and get the data
    if let plist = PlistHandler(name: "Items") {
        getPlist = plist.getMutablePlistDict()!

        // Load the items into the table view data source
        for i in 0..<getPlist.count {
            listItems = (getPlist.object(forKey: "Item\(i)") as! NSArray) as! [String]

            if listItems[1] != "" {
                items.append(Items(list: listItems[0], name: listItems[1], shop: listItems[2], price: listItems[3]))

                if listItems[0] == listName  {
                    showItems.append(Items(list: listItems[0], name: listItems[1], shop: listItems[2], price: listItems[3]))
                }
            }
        }
    } else {
        print("Unable to get Plist")
    }
    tableView.reloadData()
}
</code>```

So what I'm doing here is to load the whole data source into the items struct and the data for the table view into the showItems struct.
When I add a new item this will be added to both structs which works fine. But when it comes to deleting I run into a problem:

```<code>    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        showItems.remove(at: indexPath.row)
        // Ho to delete the correct item from items here?
        // Update the plist
        itemPlistUpdate()

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
    }
}
</code>```

So how can I delete the correct item from items here? Or is there a better way where I don't need to create two data sources?

答:
I solved the problem by creating an array of keys and an editKey for the item which will be edited later.

```<code>var items = [Items]()
var showItems = [Items]()
var keyArray = [Int]()
var editKey = Int()
</code>```

While populating the showItems struct every item gets the correct key with the help of the array.

```<code>// Load the data from plist
func loadPlistData() {

    // Connect to plist and get the data
    if let plist = PlistHandler(name: "Items") {
        getPlist = plist.getMutablePlistDict()!

        // Load the items into the table view data source
        for i in 0..<getPlist.count {
            listItems = (getPlist.object(forKey: "Item\(i)") as! NSArray) as! [String]

            if listItems[0] != "" {
                items.append(Items(list: listItems[0], name: listItems[1], shop: listItems[2], price: listItems[3], remark: listItems[4]))

                if listItems[0] == listName  {
                    showItems.append(Items(list: listItems[0], name: listItems[1], shop: listItems[2], price: listItems[3], remark: listItems[4]))

                    keyArray.append(i)
                }
            }
        }
    } else {
        print("Unable to get Plist")
    }
    tableView.reloadData()
}
</code>```

So the table view will be filled with the content of showItems. When it comes to deleting I use the corresponding key to delete the item from the items struct.

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return showItems.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath as IndexPath) as! ItemCell

    let myItems = showItems[indexPath.row] as Items
    cell.myItems = myItems
    return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        showItems.remove(at: indexPath.row)
        let key = keyArray[indexPath.row]
        items.remove(at: key)
        keyArray.remove(at: indexPath.row)
        // Update the plist
        itemPlistUpdate()

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    editKey = keyArray[indexPath.row]
}
</code>```

The editKey will be used in the following segue method:

```<code>@IBAction func editItemDetail(segue: UIStoryboardSegue) {
    if let editItemViewController = segue.source as? EditItemViewController {

        // Save the edited item to the struct and update the plist
        if let changedItem = editItemViewController.editedItem {
            items.remove(at: editKey)
            items.insert(changedItem, at: editKey)
            // Update the plist
            itemPlistUpdate()
        }
    }
}
</code>```

Body:
I have a data source which holds different lists like in apples notes app.
When the user taps on one row in the ListViewController (all lists) a second ViewController is presented which holds only the data of this list.
The whole data source is in a plist and the key is the list name:

    var items = [Items]()
    var showItems = [Items]()

    func loadPlistData() {

    // Connect to plist and get the data
    if let plist = PlistHandler(name: "Items") {
        getPlist = plist.getMutablePlistDict()!

        // Load the items into the table view data source
        for i in 0..<getPlist.count {
            listItems = (getPlist.object(forKey: "Item\(i)") as! NSArray) as! [String]

            if listItems[1] != "" {
                items.append(Items(list: listItems[0], name: listItems[1], shop: listItems[2], price: listItems[3]))

                if listItems[0] == listName  {
                    showItems.append(Items(list: listItems[0], name: listItems[1], shop: listItems[2], price: listItems[3]))
                }
            }
        }
    } else {
        print("Unable to get Plist")
    }
    tableView.reloadData()
}

So what I'm doing here is to load the whole data source into the items struct and the data for the table view into the showItems struct.
When I add a new item this will be added to both structs which works fine. But when it comes to deleting I run into a problem:

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        showItems.remove(at: indexPath.row)
        // Ho to delete the correct item from items here?
        // Update the plist
        itemPlistUpdate()

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
    }
}

So how can I delete the correct item from items here? Or is there a better way where I don't need to create two data sources?

Body:
I solved the problem by creating an array of keys and an editKey for the item which will be edited later.

var items = [Items]()
var showItems = [Items]()
var keyArray = [Int]()
var editKey = Int()

While populating the showItems struct every item gets the correct key with the help of the array.

// Load the data from plist
func loadPlistData() {

    // Connect to plist and get the data
    if let plist = PlistHandler(name: "Items") {
        getPlist = plist.getMutablePlistDict()!

        // Load the items into the table view data source
        for i in 0..<getPlist.count {
            listItems = (getPlist.object(forKey: "Item\(i)") as! NSArray) as! [String]

            if listItems[0] != "" {
                items.append(Items(list: listItems[0], name: listItems[1], shop: listItems[2], price: listItems[3], remark: listItems[4]))

                if listItems[0] == listName  {
                    showItems.append(Items(list: listItems[0], name: listItems[1], shop: listItems[2], price: listItems[3], remark: listItems[4]))

                    keyArray.append(i)
                }
            }
        }
    } else {
        print("Unable to get Plist")
    }
    tableView.reloadData()
}

So the table view will be filled with the content of showItems. When it comes to deleting I use the corresponding key to delete the item from the items struct.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return showItems.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath as IndexPath) as! ItemCell

    let myItems = showItems[indexPath.row] as Items
    cell.myItems = myItems
    return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        showItems.remove(at: indexPath.row)
        let key = keyArray[indexPath.row]
        items.remove(at: key)
        keyArray.remove(at: indexPath.row)
        // Update the plist
        itemPlistUpdate()

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    editKey = keyArray[indexPath.row]
}

The editKey will be used in the following segue method:

@IBAction func editItemDetail(segue: UIStoryboardSegue) {
    if let editItemViewController = segue.source as? EditItemViewController {

        // Save the edited item to the struct and update the plist
        if let changedItem = editItemViewController.editedItem {
            items.remove(at: editKey)
            items.insert(changedItem, at: editKey)
            // Update the plist
            itemPlistUpdate()
        }
    }
}


问:
efficient SQL query to get rows with different conditions in different times
Suppose we have a table users:

user_id, timestamp, condition_a, condition_b

Each user session is a row with same user id, different timestamp and arbitrary conditions a and/or b.

I want to do queries like:

Users who had condition a from t1 to t2 and NOT condition b from t3 to t4.

Users who had condition a before t1 and condition b after t3.

One way to do it is with subqueries:

for the 1st example above:

```<code>SELECT * FROM users WHERE
user_id IN
(SELECT user_id WHERE timestamp BETWEEN t1 AND t2 AND condition_a =1 )
AND user_id NOT IN
(SELECT user_id WHERE timestamp BETWEEN t2 AND t3 AND condition_b =1 )
</code>```

This looks very inefficient to me since it will have to scan the table several times.

Is there a more efficient way to do this that only needs to scan the table once?
(this is for presto eventually, partitions are by time blocks)

答:
I would calls the table sessions, not users.  So, let's start from there.  If you have a table users, then user_id should be the primary key (or natural key in a type-2 dimension).

One method to get theuser_ids is aggregation:

```<code>SELECT s.user_id
FROM sessions s
WHERE (timestamp BETWEEN t1 AND t2 AND condition_a = 1) OR
      (timestamp BETWEEN t2 AND t3 AND condition_b = 1)
GROUP BY s.user_id
HAVING SUM(timestamp BETWEEN t1 AND t2 AND condition_a = 1) > 0 AND
       SUM(timestamp BETWEEN t2 AND t3 AND condition_b = 1) > 0;
</code>```

You can join back to the original data (or use IN or EXISTS) to get the detailed rows, if you like.

Body:
Suppose we have a table users:

user_id, timestamp, condition_a, condition_b

Each user session is a row with same user id, different timestamp and arbitrary conditions a and/or b.

I want to do queries like:

Users who had condition a from t1 to t2 and NOT condition b from t3 to t4.

Users who had condition a before t1 and condition b after t3.

One way to do it is with subqueries:

for the 1st example above:

SELECT * FROM users WHERE
user_id IN
(SELECT user_id WHERE timestamp BETWEEN t1 AND t2 AND condition_a =1 )
AND user_id NOT IN
(SELECT user_id WHERE timestamp BETWEEN t2 AND t3 AND condition_b =1 )

This looks very inefficient to me since it will have to scan the table several times.

Is there a more efficient way to do this that only needs to scan the table once?
(this is for presto eventually, partitions are by time blocks)

Body:
I would calls the table sessions, not users.  So, let's start from there.  If you have a table users, then user_id should be the primary key (or natural key in a type-2 dimension).

One method to get theuser_ids is aggregation:

SELECT s.user_id
FROM sessions s
WHERE (timestamp BETWEEN t1 AND t2 AND condition_a = 1) OR
      (timestamp BETWEEN t2 AND t3 AND condition_b = 1)
GROUP BY s.user_id
HAVING SUM(timestamp BETWEEN t1 AND t2 AND condition_a = 1) > 0 AND
       SUM(timestamp BETWEEN t2 AND t3 AND condition_b = 1) > 0;

You can join back to the original data (or use IN or EXISTS) to get the detailed rows, if you like.


问:
Why am I getting ZERO as the output in Android Calculator Application?
I am making a calculator app in the android studio but I am always getting the result as zero when  I am clicking = operator. Kindly help me resolve the error. The code is as follows:

```<code>public class MainActivity extends AppCompatActivity {

Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0,
        btnAdd, btnSub, btnMul, btnDivide, btnEquals, btnPercentage,
        btnClear, btnErase, btnPoint;
EditText etDisplay;

int num = 0, result = 0;
int operator;
public static final int ADD = 0;
public static final int SUBTRACT = 1;
public static final int MULIPLY = 2;
public static final int DIVIDE = 3;
public static final int PERCENTAGE = 4;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    etDisplay = (EditText) findViewById(R.id.etDisplay);
    btn0 = (Button) findViewById(R.id.btn0);
    btn1 = (Button) findViewById(R.id.btn1);
    btn2 = (Button) findViewById(R.id.btn2);
    btn3 = (Button) findViewById(R.id.btn3);
    btn4 = (Button) findViewById(R.id.btn4);
    btn5 = (Button) findViewById(R.id.btn5);
    btn6 = (Button) findViewById(R.id.btn6);
    btn7 = (Button) findViewById(R.id.btn7);
    btn8 = (Button) findViewById(R.id.btn8);
    btn9 = (Button) findViewById(R.id.btn9);
    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnSub = (Button) findViewById(R.id.btnSub);
    btnMul = (Button) findViewById(R.id.btnMul);
    btnDivide = (Button) findViewById(R.id.btnDivide);
    btnEquals = (Button) findViewById(R.id.btnEquals);
    btnPercentage = (Button) findViewById(R.id.btnPercentage);
    btnClear = (Button) findViewById(R.id.btnClear);

    btnClear.setOnClickListener(new View.OnClickListener() {

    /****btnClear is used to clear the contents of EditText****/

        @Override
        public void onClick(View v) {
            etDisplay.setText("");
            num = 0;
            result = 0;
        }
    });

    btn0.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num = num * 10;
            etDisplay.setText("");
            etDisplay.setText(String.valueOf(num));
        }
    });

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num = (num * 10) + 1;
            etDisplay.setText("");
            etDisplay.setText(String.valueOf(num));
        }
    });
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num = (num * 10) + 2;
            etDisplay.setText("");
            etDisplay.setText(String.valueOf(num));
        }
    });
    btn3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num = (num * 10) + 3;
            etDisplay.setText("");
            etDisplay.setText(String.valueOf(num));
        }
    });
</code>```

/SIMILARLY FOR OTHER BUTTONS/

```<code>    btn4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn7.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn8.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            operator = ADD;
            result = num;
            num = 0;
        }
    });
</code>```

/SIMILARLY FOR btnSub, btnMul, btnDivide, btnPercentage/

```<code>    btnSub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btnMul.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });

    btnDivide.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           /*...*/
        }
    });
    btnPercentage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });

    btnEquals.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (operator){
                case ADD : result = result + num;
                case SUBTRACT : result = result - num;
                case MULIPLY : result = result * num;
                case DIVIDE : result = result / num;
                case PERCENTAGE : result = result / 100;
            }
            try {
                etDisplay.setText(String.valueOf(result));
            }
            catch (ArithmeticException e){
                etDisplay.setText("");
            }
            finally {
                num = 0;
                result = 0;
            }
        }
    });

}
</code>```

}

答:
you need to add break in your switch otherwise all cases will be executed

```<code>case ADD : result = result + num;      break;
case SUBTRACT : result = result - num; break;
case MULIPLY : result = result * num;  break;
case DIVIDE : result = result / num;   break;
case PERCENTAGE : result = result / 100;
</code>```

Seems like you are trying with small numbers where / 100 is giving you value less than 1 and the integer division will give you 0 , truncate the rest of the value

Body:
I am making a calculator app in the android studio but I am always getting the result as zero when  I am clicking = operator. Kindly help me resolve the error. The code is as follows:

public class MainActivity extends AppCompatActivity {

Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0,
        btnAdd, btnSub, btnMul, btnDivide, btnEquals, btnPercentage,
        btnClear, btnErase, btnPoint;
EditText etDisplay;

int num = 0, result = 0;
int operator;
public static final int ADD = 0;
public static final int SUBTRACT = 1;
public static final int MULIPLY = 2;
public static final int DIVIDE = 3;
public static final int PERCENTAGE = 4;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    etDisplay = (EditText) findViewById(R.id.etDisplay);
    btn0 = (Button) findViewById(R.id.btn0);
    btn1 = (Button) findViewById(R.id.btn1);
    btn2 = (Button) findViewById(R.id.btn2);
    btn3 = (Button) findViewById(R.id.btn3);
    btn4 = (Button) findViewById(R.id.btn4);
    btn5 = (Button) findViewById(R.id.btn5);
    btn6 = (Button) findViewById(R.id.btn6);
    btn7 = (Button) findViewById(R.id.btn7);
    btn8 = (Button) findViewById(R.id.btn8);
    btn9 = (Button) findViewById(R.id.btn9);
    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnSub = (Button) findViewById(R.id.btnSub);
    btnMul = (Button) findViewById(R.id.btnMul);
    btnDivide = (Button) findViewById(R.id.btnDivide);
    btnEquals = (Button) findViewById(R.id.btnEquals);
    btnPercentage = (Button) findViewById(R.id.btnPercentage);
    btnClear = (Button) findViewById(R.id.btnClear);

    btnClear.setOnClickListener(new View.OnClickListener() {

    /****btnClear is used to clear the contents of EditText****/

        @Override
        public void onClick(View v) {
            etDisplay.setText("");
            num = 0;
            result = 0;
        }
    });

    btn0.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num = num * 10;
            etDisplay.setText("");
            etDisplay.setText(String.valueOf(num));
        }
    });

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num = (num * 10) + 1;
            etDisplay.setText("");
            etDisplay.setText(String.valueOf(num));
        }
    });
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num = (num * 10) + 2;
            etDisplay.setText("");
            etDisplay.setText(String.valueOf(num));
        }
    });
    btn3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            num = (num * 10) + 3;
            etDisplay.setText("");
            etDisplay.setText(String.valueOf(num));
        }
    });

/SIMILARLY FOR OTHER BUTTONS/

    btn4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn7.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn8.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btn9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            operator = ADD;
            result = num;
            num = 0;
        }
    });

/SIMILARLY FOR btnSub, btnMul, btnDivide, btnPercentage/

    btnSub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });
    btnMul.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });

    btnDivide.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           /*...*/
        }
    });
    btnPercentage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*...*/
        }
    });

    btnEquals.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (operator){
                case ADD : result = result + num;
                case SUBTRACT : result = result - num;
                case MULIPLY : result = result * num;
                case DIVIDE : result = result / num;
                case PERCENTAGE : result = result / 100;
            }
            try {
                etDisplay.setText(String.valueOf(result));
            }
            catch (ArithmeticException e){
                etDisplay.setText("");
            }
            finally {
                num = 0;
                result = 0;
            }
        }
    });

}

}

Body:
you need to add break in your switch otherwise all cases will be executed

case ADD : result = result + num;      break;
case SUBTRACT : result = result - num; break;
case MULIPLY : result = result * num;  break;
case DIVIDE : result = result / num;   break;
case PERCENTAGE : result = result / 100;

Seems like you are trying with small numbers where / 100 is giving you value less than 1 and the integer division will give you 0 , truncate the rest of the value


问:
Regex search for Text then match elements
I would like to install a condition. I have already tried a lot but without success. Would someone be so kind and would help me?

My goal: if SharedKeys true then match elements(A B C D).

SharedKeys = "A","B","C","D"

Regex:  (?!\")[A-Z]*?(?=\")

Match elements: A B C D

Update: (SharedKeys)?(?(1)|(?!\")[A-Z]*?(?=\"))

Match elements: SharedKeys A B C D

Link: https://regex101.com/r/WFxZh4/1

I think i have now what i needed, maybe helps others.

SharedKeys = "A","B","C","D"

BlaBla = "B", "B", "C"

Result: (SharedKeys|BlaBla)?(?(1)|(?!\")[A-Z]*?(?=\"))

Match elements: SharedKeys A B C D BlaBla B B C

Result for c++: [A-Za-z]+|(?!\")[A-Z]*?(?=\") (std::regex)

答:
with std::regex:

```<code>std::string s1( R"(SharedKeys = "A","B","C","D")" );
std::regex rx( "(SharedKeys)?(?(1)|[A-Z](?=\\\"))" );
std::match_results< std::string::const_iterator > mr;

while( std::regex_search( s1, mr, rx ) ){
    std::cout << mr.str() << '\n';
    s1 = mr.suffix().str();
}
</code>```

the output:

```<code>terminate called after throwing an instance of 'std::regex_error'
what():  Invalid special open parenthesis. Aborted (core dumped)
</code>```

with boost::regex:

```<code>std::string s1( R"(SharedKeys = "A","B","C","D")" );
boost::regex rx( "(SharedKeys)?(?(1)|[A-Z](?=\\\"))" );
boost::match_results< std::string::const_iterator > mr;

while( boost::regex_search( s1, mr, rx ) ){
    std::cout << mr.str() << '\n';
    s1 = mr.suffix().str();
}
</code>```

the output:

```<code>SharedKeys
A
B
C
D
</code>```

here you can see the difference between this two flavors:

source of the screenshot

Note. The std::regex is buggy especially with gcc version 6.3.0 and lower versions

Body:
with std::regex:

std::string s1( R"(SharedKeys = "A","B","C","D")" );
std::regex rx( "(SharedKeys)?(?(1)|[A-Z](?=\\\"))" );
std::match_results< std::string::const_iterator > mr;

while( std::regex_search( s1, mr, rx ) ){
    std::cout << mr.str() << '\n';
    s1 = mr.suffix().str();
}

the output:

terminate called after throwing an instance of 'std::regex_error'
what():  Invalid special open parenthesis. Aborted (core dumped)

with boost::regex:

std::string s1( R"(SharedKeys = "A","B","C","D")" );
boost::regex rx( "(SharedKeys)?(?(1)|[A-Z](?=\\\"))" );
boost::match_results< std::string::const_iterator > mr;

while( boost::regex_search( s1, mr, rx ) ){
    std::cout << mr.str() << '\n';
    s1 = mr.suffix().str();
}

the output:

SharedKeys
A
B
C
D

here you can see the difference between this two flavors:

source of the screenshot

Note. The std::regex is buggy especially with gcc version 6.3.0 and lower versions


问:
Identity Server 3 Implicit Flow with angular code to get token
We currently have built and asp.net mvc 5 application using Identity Server 3 to handle authentication and authorization to an Web Api, using Implicit Flow.  All is working well until we started adding some angular calls to the Api.  The MVC startup class handles the retrieval of the token, to get it to work with angular for now we wrote out the token into a javascript variable which angular picks up and sends in it's header to all Api calls.

There are times though where by the time the user clicks a button to invoke the angular call the token has expired.  Is there a way to get another token in angular before each call, possibly check if expired then get a new one?  If so possibly without a page refresh as we don't want to lose the data the user is trying to submit while getting a new token.  Would this possibly lead to the application using a different token for angular and mvc side?  as we are not getting rid of the mvc side just yet.

答:
Send the token to Access token validation endpoint.

Assuming you haven't disabled this endpoint, you can invoke it

```<code>POST /connect/accesstokenvalidation

token=<token>
</code>```

Body:
Send the token to Access token validation endpoint.

Assuming you haven't disabled this endpoint, you can invoke it

POST /connect/accesstokenvalidation

token=<token>


问:
ng-if inside ng-repeat is not filtering my array
Hy evryone, im trying to display tabs with a value inside my types array wchich has

```<code>[{"label":"wlan1","type":"wlan1"},
 {"label":"br-wlan","type":"br-wlan"},
 {"label":"tun_cas","type":"tun_cas"},
 {"label":"nfacct_bytes","type":"nfacct_bytes"},
 {"label":"wlan0","type":"wlan0"},
 {"label":"lte0","type":"lte0"},
 {"label":"nfacct_packets","type":"nfacct_packets"}]
</code>```

In my view I dont want to display the types nfacct_bytes and nfacct_packets and for that I was doing:

```<code><tab ng-if="type.label !== 'nfacct_bytes' || type.label !== 'nfacct_packets'"
     ng-repeat="type in dataGraph.network.types" heading="{{type.label}}"
     select="changeSubTab(type.type)" disable="!tabClick" >
</code>```

Solution:

```<code><tab ng-if="type.label !== 'nfacct_bytes' && type.label !== 'nfacct_packets'"
     ng-repeat="type in dataGraph.network.types" heading="{{type.label}}"
     select="changeSubTab(type.type)" disable="!tabClick" >
</code>```

答:
I think you need to check like this,

```<code><tab ng-if="type.label !== 'nfacct_bytes' && type.label !== 'nfacct_packets' ">
</tab>
</code>```

DEMO

var myApp=angular.module('myApp',[]);
 myApp.controller('thecontroller',function($scope){
       $scope.dataGraph = {};
       $scope.dataGraph.network = {};
         $scope.dataGraph.network.types = [{"label":"wlan1","type":"wlan1"},{"label":"br-wlan","type":"br-wlan"},{"label":"tun_cas","type":"tun_cas"},{"label":"nfacct_bytes","type":"nfacct_bytes"},{"label":"wlan0","type":"wlan0"},{"label":"lte0","type":"lte0"},{"label":"nfacct_packets","type":"nfacct_packets"}];
});
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
    <html>
        <head>
          <title>ng-Messages Service</title>
          <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
            <script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
        </head>
        <body ng-app="myApp">
            <div ng-controller='thecontroller'>
            <div  ng-repeat="type in dataGraph.network.types">
           <div ng-if="type.label !== 'nfacct_bytes' && type.label !== 'nfacct_packets' "> {{type.label}}
            </div>
            </div>
            </div>
        </body>
    </html></code>```

Body:
Hy evryone, im trying to display tabs with a value inside my types array wchich has

[{"label":"wlan1","type":"wlan1"},
 {"label":"br-wlan","type":"br-wlan"},
 {"label":"tun_cas","type":"tun_cas"},
 {"label":"nfacct_bytes","type":"nfacct_bytes"},
 {"label":"wlan0","type":"wlan0"},
 {"label":"lte0","type":"lte0"},
 {"label":"nfacct_packets","type":"nfacct_packets"}]

In my view I dont want to display the types nfacct_bytes and nfacct_packets and for that I was doing:

<tab ng-if="type.label !== 'nfacct_bytes' || type.label !== 'nfacct_packets'"
     ng-repeat="type in dataGraph.network.types" heading="{{type.label}}"
     select="changeSubTab(type.type)" disable="!tabClick" >

Solution:

<tab ng-if="type.label !== 'nfacct_bytes' && type.label !== 'nfacct_packets'"
     ng-repeat="type in dataGraph.network.types" heading="{{type.label}}"
     select="changeSubTab(type.type)" disable="!tabClick" >

Body:
I think you need to check like this,

<tab ng-if="type.label !== 'nfacct_bytes' && type.label !== 'nfacct_packets' ">
</tab>

DEMO

var myApp=angular.module('myApp',[]);
 myApp.controller('thecontroller',function($scope){
       $scope.dataGraph = {};
       $scope.dataGraph.network = {};
         $scope.dataGraph.network.types = [{"label":"wlan1","type":"wlan1"},{"label":"br-wlan","type":"br-wlan"},{"label":"tun_cas","type":"tun_cas"},{"label":"nfacct_bytes","type":"nfacct_bytes"},{"label":"wlan0","type":"wlan0"},{"label":"lte0","type":"lte0"},{"label":"nfacct_packets","type":"nfacct_packets"}];
});

<!DOCTYPE html>
    <html>
        <head>
          <title>ng-Messages Service</title>
          <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
            <script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
        </head>
        <body ng-app="myApp">
            <div ng-controller='thecontroller'>
            <div  ng-repeat="type in dataGraph.network.types">
           <div ng-if="type.label !== 'nfacct_bytes' && type.label !== 'nfacct_packets' "> {{type.label}}
            </div>
            </div>
            </div>
        </body>
    </html>


问:
Find the next word after matching a word in Javascript
Want to get the first word after the number from the string "Apply for 2 insurances".

```<code>var Number = 2;
var text = "Apply for 2 insurances or more";
</code>```

In this case i want to get the string after the Number, So my expected result is "insurances"

答:
var number = 2;
var sentence = "Apply for 2 insurances or more";

var othertext = sentence.substring(sentence.indexOf(number) + 1);
console.log(othertext.split(' ')[1]);

//With two split
console.log(sentence.split(number)[1].split(' ')[1]);```

Body:
Want to get the first word after the number from the string "Apply for 2 insurances".

var Number = 2;
var text = "Apply for 2 insurances or more";

In this case i want to get the string after the Number, So my expected result is "insurances"


问:
How to make my image just appear on my button, and not overlap
I want to just have a button where the image will be the background, instead of loading the button to be the images. For example, no matter what size the image is, I still want the button to stay the same size. I tried to edit my image to be the same size, but the nice rounded corners are now gone and I don't have the software to put corners on an image accurately.

Do I just have a different understanding of what background means? I would think that It would draw the button and then put the image as the background instead of draw the button, then re-draw the button to be the same size as the background image.

Below is the xml code for my button:

```<code><Button
    android:id="@+id/newUser"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:background="@drawable/ButtonSize"
    android:elevation="0dp"
    android:text="New User"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/spinner"
    tools:textColor="@android:color/black" />
</code>```

The line in question is the android:background="@drawable/ButtonSize" and my file ButtonSize.png is a 90x50 pixel image that would fit really nicely onto an Button.

My question is: Is there any other way to set the image purely as a background in a literal sense, where I could also, for example, add curved edges using android:bottomLeftRadius="30dp", ect.

答:
Instead of using Button you can use Image button and set the following property will give the image to Entire Button.

```<code>android:scaleType="centerInside"
android:adjustViewBounds=true
</code>```

For more reference visit the following linkAndroid ImageButton Resolution Problems

Hope It will help you

Body:
I want to just have a button where the image will be the background, instead of loading the button to be the images. For example, no matter what size the image is, I still want the button to stay the same size. I tried to edit my image to be the same size, but the nice rounded corners are now gone and I don't have the software to put corners on an image accurately.

Do I just have a different understanding of what background means? I would think that It would draw the button and then put the image as the background instead of draw the button, then re-draw the button to be the same size as the background image.

Below is the xml code for my button:

<Button
    android:id="@+id/newUser"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:background="@drawable/ButtonSize"
    android:elevation="0dp"
    android:text="New User"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/spinner"
    tools:textColor="@android:color/black" />

The line in question is the android:background="@drawable/ButtonSize" and my file ButtonSize.png is a 90x50 pixel image that would fit really nicely onto an Button.

My question is: Is there any other way to set the image purely as a background in a literal sense, where I could also, for example, add curved edges using android:bottomLeftRadius="30dp", ect.

Body:
Instead of using Button you can use Image button and set the following property will give the image to Entire Button.

android:scaleType="centerInside"
android:adjustViewBounds=true

For more reference visit the following linkAndroid ImageButton Resolution Problems

Hope It will help you


答: If the assemblies haven't been obfuscated, you can use reflector to recover your code from the assemblies.</p>

Title: recover lost C# pages

Body: I had a problem I lost all my source(CS) of web site pages but I had only published pages on server ,so please if there is any way to recover theses published pages to orignal pages with code,bin folder


问:
Where is "Enable Library Loading" Developer Options on Android?
On Release Note of Google VR SDK for Unity v1.40 (April 2017)
https://developers.google.com/vr/unity/release-notes

Note: You must enable dynamic library loading in VrCore to get the
  latest C++ GVR Updates. To do this, go to Settings > Developer Options

Enable Library Loading. If Developer Options are not visible, tap 7 times on Build Version.

I'm looking for on Nexus 5X(7.0), Nexus 6P(O Preview), Pixel XL(7.1),
I cannot find "Enable Library Loading" setting in Developer Options.
What's mean this?

答:
This option is only available from the VR developer options.

To access the option :

Open a VR app, for example the Daydream app for the Pixel XL

Go into the settings menu, either via a regular menu (in the Daydream app for example), or by pressing the small gear in the top right corner if you are in stereo mode

You should see a settings menu with "Build Version" at the bottom of the list : tap on it several time to activate the developer mode

Once the developer mode is activated, you should find the option "Enable GVR SDK Library loading" in it.


问:
‘sign’ is not a valid field or method name for reference class “OAuth” while using twitteR for R
I am trying to scrape tweets on a specific search string using R library twitteR.
I am able to authenticate fine, but whenever I try to use functions like

```<code> 'searchTwitter()' or 'getUser()',
</code>```

I keep getting an error as below

" Error in envRefInferField(x, what, getClass(class(x)), selfEnv) :
    ‘sign’ is not a valid field or method name for reference class “OAuth” "

I am new to R and twitter, so could someone please explain how to resolve this?

My code is:

```<code>load("twitterAuth")
use_oauth_token(cred)
search_string <- "nba"
no_of_tweets <- 100
tweets<-searchTwitteR("srk")
</code>```

答:
The way I use twitteR is

```<code># Credentials
api_key <- "xxxxxxxxxxxxxxxxxxxx"
api_secret <- "xxxxxxxxxxxxxxxxxxxx"
access_token <- "xxxxxxxxxxxxxxxxxxxx"
access_token_secret <- "xxxxxxxxxxxxxxxxxxxx"

setup_twitter_oauth(consumer_key = api_key,
                    consumer_secret = api_secret,
                    access_token = access_token,
                    access_secret = access_token_secret)

tdy <- as.Date("2017-02-11")
mnth <- as.character(seq(from = as.Date("2013-01-31"), to = tdy, by = "month"))
mnth <- c(mnth, as.character(tdy))

for (i in 1:length(mnth) - 1) {
  tmp <- NULL
  i <- 1

  while (any(class(tmp) %in% "error") | is.null(tmp)) {
    tmp <- tryCatch(searchTwitter("#nba", n = 2400, since = "2013-01-31", until = "2013-02-28"),
                    error = function(e) e,
                    warning = function(w) w)
    save(tmp, file = paste(mnth[i], "___", mnth[i+1], ".RData", sep = ""))
  }

  Sys.sleep(1200)
}
</code>```

This works for smallish datasets. If you're trying to do some heavy duty scraping, it will probably be best to save things in a database.

Body:
I am trying to scrape tweets on a specific search string using R library twitteR.
I am able to authenticate fine, but whenever I try to use functions like

 'searchTwitter()' or 'getUser()',

I keep getting an error as below

" Error in envRefInferField(x, what, getClass(class(x)), selfEnv) :
    ‘sign’ is not a valid field or method name for reference class “OAuth” "

I am new to R and twitter, so could someone please explain how to resolve this?

My code is:

load("twitterAuth")
use_oauth_token(cred)
search_string <- "nba"
no_of_tweets <- 100
tweets<-searchTwitteR("srk")

Body:
The way I use twitteR is

# Credentials
api_key <- "xxxxxxxxxxxxxxxxxxxx"
api_secret <- "xxxxxxxxxxxxxxxxxxxx"
access_token <- "xxxxxxxxxxxxxxxxxxxx"
access_token_secret <- "xxxxxxxxxxxxxxxxxxxx"

setup_twitter_oauth(consumer_key = api_key,
                    consumer_secret = api_secret,
                    access_token = access_token,
                    access_secret = access_token_secret)

tdy <- as.Date("2017-02-11")
mnth <- as.character(seq(from = as.Date("2013-01-31"), to = tdy, by = "month"))
mnth <- c(mnth, as.character(tdy))

for (i in 1:length(mnth) - 1) {
  tmp <- NULL
  i <- 1

  while (any(class(tmp) %in% "error") | is.null(tmp)) {
    tmp <- tryCatch(searchTwitter("#nba", n = 2400, since = "2013-01-31", until = "2013-02-28"),
                    error = function(e) e,
                    warning = function(w) w)
    save(tmp, file = paste(mnth[i], "___", mnth[i+1], ".RData", sep = ""))
  }

  Sys.sleep(1200)
}

This works for smallish datasets. If you're trying to do some heavy duty scraping, it will probably be best to save things in a database.