问:
Form is submitted even after using e.preventDefault()
I have a form which checks for the ifsc code of before form submission, The api returns "failure" if wrong ifsc is given. If the response is a failure, the form shouldn't be submitted. I used e.preventDefault(e) but it didn't help.

```<code>$('#corporate-signup').on('submit',function(e){

    var ifsc_code = $('#ifsc-code').val();
    var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
    $.get(api_url, function(data, status){

       if (data.status === "failure") {
           $('.bank-details').addClass('no-ifsc').text(data.message);
           e.preventDefault(e);
       }

       else{
           $('#corporate-signup').submit()
           }

    });

});
</code>```

I don't know what is the mistake here. I have also tried to return false instead of preventDefault() but even it didn't work.

答:
Try this</p>

```<code>$('#corporate-signup').on('submit',function(e){
    e.preventDefault();
    var ifsc_code = $('#ifsc-code').val();
    var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
    $.get(api_url, function(data, status){

       if (data.status === "failure") {
           $('.bank-details').addClass('no-ifsc').text(data.message);
       }
       else{
           $('#corporate-signup')[0].submit() // bypass jQuery bound event
       }
    });
});
</code>```

Body:
I have a form which checks for the ifsc code of before form submission, The api returns "failure" if wrong ifsc is given. If the response is a failure, the form shouldn't be submitted. I used e.preventDefault(e) but it didn't help.

$('#corporate-signup').on('submit',function(e){

    var ifsc_code = $('#ifsc-code').val();
    var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
    $.get(api_url, function(data, status){

       if (data.status === "failure") {
           $('.bank-details').addClass('no-ifsc').text(data.message);
           e.preventDefault(e);
       }

       else{
           $('#corporate-signup').submit()
           }

    });

});

I don't know what is the mistake here. I have also tried to return false instead of preventDefault() but even it didn't work.

Body:
Try this

$('#corporate-signup').on('submit',function(e){
    e.preventDefault();
    var ifsc_code = $('#ifsc-code').val();
    var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
    $.get(api_url, function(data, status){

       if (data.status === "failure") {
           $('.bank-details').addClass('no-ifsc').text(data.message);
       }
       else{
           $('#corporate-signup')[0].submit() // bypass jQuery bound event
       }
    });
});


来源: stackexchange

问:
SQL IF-Statment within funciton
I've been working with SQL lately to make ends meet with my programming. I am trying to create a function which does a select, and if it views any duplicates (>1) of the same Analyte, it will create a string.

For example, If the select statement pulls back apples, oranges, peanuts, grapes, grapes, peaches, oranges, pineapple I will obtain a string of oranges,grapes. However if the there are no duplicates, the system breaks with an error since I'm trying to use a sub-string call on nothing.

How can I use an IF-Statment to make it pass back "NORECS" if result is still empty, and to use the sub-string functionality if it is not empty?

Working code which breaks if select doesn't pull duplicates:

```<code>Declare @result varchar(1000)

set @result = ''

select @result = @result + R.ANALYTE + ','
 FROM results R (NOLOCK)
    left join tests T (NOLOCK) on (T.testcode = R.testcode)

where
T.SHOW='Y' and R.SA='Show'
and R.ID = 3094083
group by R.ANALYTE
having COUNT(*)>1

select substring(@result, 1, len(@result) - 1) AS MissingAnas
</code>```

Attempted IF-Statement which does the "Else" regardless.

```<code>    Declare @result varchar(1000)

    set @result = ''

    select @result = @result + R.ANALYTE + ','
     FROM results R (NOLOCK)
        left join tests T (NOLOCK) on (T.testcode = R.testcode)

    where
    T.SHOW='Y' and R.SA='Show'
    and R.ID = 3094083
    group by R.ANALYTE
    having COUNT(*)>1

    if (Count(@result)>1)
    Begin
    select substring(@result, 1, len(@result) - 1) AS MissingAnas
    End
    Else
    Begin
    set @result = 'NORECS'
    select @result AS MissingAnas
    End
</code>```

答:
```<code>Use RETURN Statement in below format :

Declare @result varchar(1000)

set @result = ''

select @result = @result + R.ANALYTE + ','
 FROM results R (NOLOCK)
    left join tests T (NOLOCK) on (T.testcode = R.testcode)

where
T.SHOW='Y' and R.SA='Show'
and R.ID = 3094083
group by R.ANALYTE
having COUNT(*)>1

if (Count(@result)>1)
Begin
   SET @result = substring(@result, 1, len(@result) - 1)
End
Else
Begin
   SET @result = 'NORECS'
End

SELECT @result
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL IF-Statment within funciton

Body:
I've been working with SQL lately to make ends meet with my programming. I am trying to create a function which does a select, and if it views any duplicates (>1) of the same Analyte, it will create a string.

For example, If the select statement pulls back apples, oranges, peanuts, grapes, grapes, peaches, oranges, pineapple I will obtain a string of oranges,grapes. However if the there are no duplicates, the system breaks with an error since I'm trying to use a sub-string call on nothing.

How can I use an IF-Statment to make it pass back "NORECS" if result is still empty, and to use the sub-string functionality if it is not empty?

Working code which breaks if select doesn't pull duplicates:

Declare @result varchar(1000)

set @result = ''

select @result = @result + R.ANALYTE + ','
 FROM results R (NOLOCK)
    left join tests T (NOLOCK) on (T.testcode = R.testcode)

where
T.SHOW='Y' and R.SA='Show'
and R.ID = 3094083
group by R.ANALYTE
having COUNT(*)>1

select substring(@result, 1, len(@result) - 1) AS MissingAnas

Attempted IF-Statement which does the "Else" regardless.

    Declare @result varchar(1000)

    set @result = ''

    select @result = @result + R.ANALYTE + ','
     FROM results R (NOLOCK)
        left join tests T (NOLOCK) on (T.testcode = R.testcode)

    where
    T.SHOW='Y' and R.SA='Show'
    and R.ID = 3094083
    group by R.ANALYTE
    having COUNT(*)>1

    if (Count(@result)>1)
    Begin
    select substring(@result, 1, len(@result) - 1) AS MissingAnas
    End
    Else
    Begin
    set @result = 'NORECS'
    select @result AS MissingAnas
    End


问:
How does Maven 3 password encryption work?
I'm trying to understand Maven 3's[password encryption feature. I have found that this feature is poorly documented and confusing. For example, the feature documentation and a blog post by the author of the feature contradict each other about several points.

This question is broader than How does maven --encrypt-master-password work and is not covered by Maven encrypt-master-password good practice for choosing password.

Specifically, I am trying to answer the following questions which are not covered by the documentation. I've put what information I have been able to gather so far below each question in italics.

Does the encrypted master password provide security simply by existing in settings-security.xml in a folder that only one user can access (~/.m2)? If so, why bother with encrypting a 'master password' (why not just use some random value)? Isn't the 'master password' really just an entropy input to the cryptographic function? Calling it a password is confusing - I expected Maven to prompt me for this password before de-crypting any encrypted server passwords, but it did not.

My understanding is that yes, this only provides security by existing in an operating-system protected file. I believe Maven allows you to encrypt a master password so that if you loose the settings-security.xml file you can re-generate it. Is this correct?

Do the master password and server passwords use the same encryption process/cipher? The server passwords are based on the master password, so there must be some difference in the algorithm. Where is the source code for this located?

Marcelo Morales' answer on How does maven --encrypt-master-password work links to the plexus-cihper project on GitHub. It isn't clear if that is just the cipher, or the actual Maven plugin that provides the password functionality though.

I have observed that the same master password or server password encrypted multiple times gives different hashes. According to Marcelo Morales' answer on How does maven --encrypt-master-password work, this is because 'a JVM-configuration-specific (usually SHA1PRNG) 64-bit random salt' is added to the password prior to encrypting. Maven decrypts stored passwords when they are used at compile time. Doesn't this mean the salts have to be stored somewhere?

I have no idea.

I have also observed that a regular password encrypted using one encrypted master password will still work if the master password is re-encrypted and stored in the settings-security.xml file, even though the encrypted master password ciphertext is now different. Can someone explain how this works?

I have no idea. This seems to me like Maven is doing something fishy or storing cleartext somewhere.

My understanding is that the encrypted passwords can only be used with <server /> tags in the settings.xml file. is this true? Where can servers defined in settings.xml be used?

My understanding is that <server /> definitions can be used in <repositories /> and <distributionManagement />, but not <scm />. Can someone verify this?

For such a critical feature (build system security) it seems to me that there is a lot of confusion and poor documentation. Can someone point out how the documentation on the Maven 3 website works? Is there a wiki link somewhere that would allow me to try and improve the documentation at all?

I have no idea

Sorry for the wall of text, and thanks for any answers.

答:
I need to know this for bnd(tools) so I can share some deeper analysis.

The 'encrypted' passwords have a syntax of:

```<code>output    ::= '{' base64(packet) '}'
packet    ::= salt[8] padlen[1] encrypted[?] padding[padlen]
salt      ::= <random>
padlen    ::= <length of padding >
padding   ::= <random to make packet length a multiple of 16>
</code>```

The cipher used is AES/CBC/PKCS5Padding. The secret key and initialisation vector is calculated as follows:

```<code>sha = sha256( X + salt[8] )
key = sha[0..16]
iv  = sha[16..32]
</code>```

For the master password X is "security.settings". Since this is a well known constant the master password is not encrypted but only obscured. For the server passwords X is the decoded master password.

Why the resulting packet is padded seems a waste of bytes since the packet format makes it trivial to strip and they are never part of the encryption/decryption.  They just add a few random characters to the base64 string.

The only way this is useful is using the relocation facility. For example, if you mount the settings-security.xml  on a private mount on the build server. You can then you can freely share the settings.xml file in public repos. However, this is also a sucky solution since you need to mount it the same mount point for all your users and CI build servers.

Be aware that any plugin can decode all your server passwords so never use real passwords for the servers. Nexus can create proxy passwords.

Body:
I need to know this for bnd(tools) so I can share some deeper analysis.

The 'encrypted' passwords have a syntax of:

output    ::= '{' base64(packet) '}'
packet    ::= salt[8] padlen[1] encrypted[?] padding[padlen]
salt      ::= <random>
padlen    ::= <length of padding >
padding   ::= <random to make packet length a multiple of 16>

The cipher used is AES/CBC/PKCS5Padding. The secret key and initialisation vector is calculated as follows:

sha = sha256( X + salt[8] )
key = sha[0..16]
iv  = sha[16..32]

For the master password X is "security.settings". Since this is a well known constant the master password is not encrypted but only obscured. For the server passwords X is the decoded master password.

Why the resulting packet is padded seems a waste of bytes since the packet format makes it trivial to strip and they are never part of the encryption/decryption.  They just add a few random characters to the base64 string.

The only way this is useful is using the relocation facility. For example, if you mount the settings-security.xml  on a private mount on the build server. You can then you can freely share the settings.xml file in public repos. However, this is also a sucky solution since you need to mount it the same mount point for all your users and CI build servers.

Be aware that any plugin can decode all your server passwords so never use real passwords for the servers. Nexus can create proxy passwords.

ContentLicense: CC BY-SA 4.0


问:
ajax post to jboss eap 7 without encodeURIComponent occurred messy code
Firstly,the project works well in tomcat(UTF-8) and jboss eap 6,the page encoding is also UTF-8.
Secondly,jboss config has add

<servlet-container name="default" default-buffer-cache="default" stack-trace-on-error="local-only" default-encoding="UTF-8">

Thirdly,when using encodeURIComponent or serialize it works well,however,it failed when using serialize and appending some parameters like follows:

  var params = $("#form_viewOrUpdateSchedule").serialize();
  params += "&recordId=" + recordId;
  params += "&custName=" + custName;
  params += "&startTime=" + startTime;
  params += "&content=" + content;
  params += "&endTime=" + endTime;
  params += "&scheduleDate=" + getScheduleDate();
  bodymask();
  $.ajax({
    url: url,
    type: "POST",
    data: params,
    datatype: "JSON",
 contentType : "application/x-www-form-urlencoded; charset=utf-8",
    success: function(data) {```
</div>
</div>
</p>

<p>Fourthly,it works well if using serialize or like follows:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  var recordId = $("#schedule_list_id").val();
  var custName = $("#schedule_list_custName option:selected").val();
  var startTime = $("#schedule_list_startTime").val();
  var endTime = $("#schedule_list_endTime").val();
  var content = $("#schedule_list_content").val();
  var startIndex = $("#schedule_list_startTime").get(0).selectedIndex;
  var endIndex = $("#schedule_list_endTime").get(0).selectedIndex;
  if (startIndex > endIndex) {
    alertInfo("提示", "结束时间不能早于开始时间");
    return;
  }
  var params = {}
  params.recordId = recordId;
  params.custName = custName;
  params.startTime = startTime;
  params.content = content;
  params.endTime = endTime;
  params.scheduleDate = getScheduleDate();
  $.ajax({
    url: url,
    type: "POST",
    data: params,</code>```

Fifthly,jboss eap 7(actually renamed to WildFly,version is 10) is based on undertow instead of tomcat.

Sixly,the similar question is asked in https://developer.jboss.org/thread/221662,and the problem that could not set default charactor encoding is solved in WildFly 8.0,mentioned in https://javaarm.com/faces/display.xhtml;jsessionid=bPtpE2lS35rYKscI0laAyYbp?tid=3341&page=1&print=true

Lastly,I wonder why it works well in tomcat with the above "thirdly" js and works failed in jboss eap 7 ? How to solve the problem if I don't change the js code ?

答:
You need to set uri encoding on http-listener (and any other)

for example:

```<code><http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true" url-charset="UTF-8"/>
</code>```

or cli:

```<code>/subsystem=undertow/server=default:server/http-listener=default:write-attribute(name="uri-charset", value="UTF-8")
</code>```

and similarly for all other listeners you might be using.

Line of note, system properties named org.apache.catalina.* are tomcat related properties. Since WildFly 8+ and EAP7+ web server used is undertow and no longer jbossweb which was based on tomcat.
As such this properties won't have any effect at all.

Body:
Firstly,the project works well in tomcat(UTF-8) and jboss eap 6,the page encoding is also UTF-8.
Secondly,jboss config has add

<servlet-container name="default" default-buffer-cache="default" stack-trace-on-error="local-only" default-encoding="UTF-8">

Thirdly,when using encodeURIComponent or serialize it works well,however,it failed when using serialize and appending some parameters like follows:

  var params = $("#form_viewOrUpdateSchedule").serialize();
  params += "&recordId=" + recordId;
  params += "&custName=" + custName;
  params += "&startTime=" + startTime;
  params += "&content=" + content;
  params += "&endTime=" + endTime;
  params += "&scheduleDate=" + getScheduleDate();
  bodymask();
  $.ajax({
    url: url,
    type: "POST",
    data: params,
    datatype: "JSON",
 contentType : "application/x-www-form-urlencoded; charset=utf-8",
    success: function(data) {

Fourthly,it works well if using serialize or like follows:

  var recordId = $("#schedule_list_id").val();
  var custName = $("#schedule_list_custName option:selected").val();
  var startTime = $("#schedule_list_startTime").val();
  var endTime = $("#schedule_list_endTime").val();
  var content = $("#schedule_list_content").val();
  var startIndex = $("#schedule_list_startTime").get(0).selectedIndex;
  var endIndex = $("#schedule_list_endTime").get(0).selectedIndex;
  if (startIndex > endIndex) {
    alertInfo("提示", "结束时间不能早于开始时间");
    return;
  }
  var params = {}
  params.recordId = recordId;
  params.custName = custName;
  params.startTime = startTime;
  params.content = content;
  params.endTime = endTime;
  params.scheduleDate = getScheduleDate();
  $.ajax({
    url: url,
    type: "POST",
    data: params,

Fifthly,jboss eap 7(actually renamed to WildFly,version is 10) is based on undertow instead of tomcat.

Sixly,the similar question is asked in https://developer.jboss.org/thread/221662,and the problem that could not set default charactor encoding is solved in WildFly 8.0,mentioned in https://javaarm.com/faces/display.xhtml;jsessionid=bPtpE2lS35rYKscI0laAyYbp?tid=3341&page=1&print=true

Lastly,I wonder why it works well in tomcat with the above "thirdly" js and works failed in jboss eap 7 ? How to solve the problem if I don't change the js code ?

Body:
You need to set uri encoding on http-listener (and any other)

for example:

<http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true" url-charset="UTF-8"/>

or cli:

/subsystem=undertow/server=default:server/http-listener=default:write-attribute(name="uri-charset", value="UTF-8")

and similarly for all other listeners you might be using.

Line of note, system properties named org.apache.catalina.* are tomcat related properties. Since WildFly 8+ and EAP7+ web server used is undertow and no longer jbossweb which was based on tomcat.
As such this properties won't have any effect at all.


答:
You are going through all of this trouble to remove the last comma, and there are a couple of ways around that.

One is using a different concatenation with the stuff() with select ... for xml path ('') method of string concatenation.

```<code>select @result = stuff((
  select ',' + r.analyte
  from results R (nolock)
    left join tests T (nolock)
      on T.testcode = R.testcode
  where T.show='Y'
    and R.sa='show'
    and R.id = 3094083
  group by R.analyte
  having count(*)>1
  for xml path (''), type).value('.','nvarchar(max)')
  ,1,1,'')
</code>```

Then if @result is still an empty string (since you set it as one in the beginning), change the value to 'NORECS' using coalesce() and nullif()

```<code>set @result = coalesce(nullif(@result,''),'NORECS');
</code>```

When using the for xml path('') version, you do not need to set @result = '' before concatenating. So if @result is null instead of '' to start iwth, the final coalesce can be simplified to:

```<code>set @result = coalesce(@result,'NORECS');
</code>```

Regarding your use of nolock everywhere, you might want to reconsider your reasons behind doing that.

Bad Habits: Putting NOLOCK everywhere - Aaron Bertrand

Title: SQL IF-Statment within funciton

Body:
You are going through all of this trouble to remove the last comma, and there are a couple of ways around that.

One is using a different concatenation with the stuff() with select ... for xml path ('') method of string concatenation.

select @result = stuff((
  select ',' + r.analyte
  from results R (nolock)
    left join tests T (nolock)
      on T.testcode = R.testcode
  where T.show='Y'
    and R.sa='show'
    and R.id = 3094083
  group by R.analyte
  having count(*)>1
  for xml path (''), type).value('.','nvarchar(max)')
  ,1,1,'')

Then if @result is still an empty string (since you set it as one in the beginning), change the value to 'NORECS' using coalesce() and nullif()

set @result = coalesce(nullif(@result,''),'NORECS');

When using the for xml path('') version, you do not need to set @result = '' before concatenating. So if @result is null instead of '' to start iwth, the final coalesce can be simplified to:

set @result = coalesce(@result,'NORECS');

Regarding your use of nolock everywhere, you might want to reconsider your reasons behind doing that.

Bad Habits: Putting NOLOCK everywhere - Aaron Bertrand


问:
Hide all warnings in IPython
I need to produce a screencast of an IPython session, and to avoid confusing viewers, I want to disable all warnings emitted by warnings.warn calls from different packages. Is there a way to configure the ipythonrc file to automatically disable all such warnings?

答:
I hide the warnings in the pink boxes by running the following code in a cell:</p>

```<code>from IPython.display import HTML
HTML('''<script>
code_show_err=false;
function code_toggle_err() {
 if (code_show_err){
 $('div.output_stderr').hide();
 } else {
 $('div.output_stderr').show();
 }
 code_show_err = !code_show_err
}
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')
</code>```

Title: Hide all warnings in IPython

Body:
I hide the warnings in the pink boxes by running the following code in a cell:

from IPython.display import HTML
HTML('''<script>
code_show_err=false;
function code_toggle_err() {
 if (code_show_err){
 $('div.output_stderr').hide();
 } else {
 $('div.output_stderr').show();
 }
 code_show_err = !code_show_err
}
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')


问:
How do I identify language of a text document in Java?
Is there an existing Java library that could tell me whether a String contains English language text or not (e.g. I need to be able to distinguish French or Italian text -- the function needs to return false for French and Italian, and true for English)?</p>

答:
There's no "good" way of doing this imo. All answers can be very complicated on this topic. The obvious part is to check for characters that is in french + italian and not in english and then return false.

However, what if the word is french but has no special characters? Play with the thought you have a whole sentance. You could match each word from dictionaries and if the sentance has more french points than english points, it's not english. This will prevent the common words that french, italian and english have.

Good Luck.

OwnerDisplayName: anonymous coward

LastEditorDisplayName: Neil Coffey

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Filip Ekberg


问:
Booting Debian Wheezy on a BeagleCore ? (Kernel panic - not syncing: Attempted to kill init!)
I'm trying to boot a Debian Wheezy Image, Ker 3.8 on my BeagleCore (a smaller version of BeagleBone) with TI AM335x Cortex-A8 processor.
I took the Debian Image from beagleboard site.
When I try to boot, on a serial interface for debug, I get this messages:

```<code>U-Boot SPL 2016.01-00001-g4eb802e (Jan 13 2016 - 11:14:31)
Trying to boot from MMC
bad magic

U-Boot 2016.01-00001-g4eb802e (Jan 13 2016 - 11:14:31 -0600), Build: jenkins-github_Bootloader-Builder-313

    Watchdog enabled
I2C:   ready
DRAM:  512 MiB
Reset Source: Power-on reset has occurred.
MMC:   OMAP SD/MMC: 0, OMAP SD/MMC: 1
Using default environment

Net:   <ethaddr> not set. Validating first E-fuse MAC
Could not get PHY for cpsw: addr 0
cpsw, usb_ether
Press SPACE to abort autoboot in 2 seconds
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
gpio: pin 56 (gpio 56) value is 0
gpio: pin 55 (gpio 55) value is 0
gpio: pin 54 (gpio 54) value is 0
gpio: pin 53 (gpio 53) value is 1
switch to partitions #0, OK
mmc0 is current device
gpio: pin 54 (gpio 54) value is 1
Checking for: /uEnv.txt ...
Checking for: /boot.scr ...
Checking for: /boot/boot.scr ...
Checking for: /boot/uEnv.txt ...
gpio: pin 55 (gpio 55) value is 1
2181 bytes read in 16 ms (132.8 KiB/s)
Loaded environment from /boot/uEnv.txt
Checking if uname_r is set in /boot/uEnv.txt...
gpio: pin 56 (gpio 56) value is 1
Running uname_boot ...
loading /boot/vmlinuz-3.8.13-bone79 ...
5644336 bytes read in 333 ms (16.2 MiB/s)
loading /boot/dtbs/3.8.13-bone79/am335x-boneblack.dtb ...
26118 bytes read in 24 ms (1 MiB/s)
loading /boot/initrd.img-3.8.13-bone79 ...
2905600 bytes read in 179 ms (15.5 MiB/s)
debug: [console=ttyO0,115200n8 capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4,BB-UART5 capemgr.disable_partno=BB-BONELT-HDMI,BB-BONELT-HDMIN root=UUID=4d8c9d4c-a16d-47ac-a32c-43d0155df072 ro rootfstype=ext4 rootwait coherent_pool=1M quiet init=/lib/systemd/systemd cape_universal=enable] ...
debug: [bootz 0x82000000 0x88080000:2c5600 0x88000000] ...
Kernel image @ 0x82000000 [ 0x000000 - 0x562030 ]
## Flattened Device Tree blob at 88000000
   Booting using the fdt blob at 0x88000000
   Loading Ramdisk to 8fd3a000, end 8ffff600 ... OK
   Loading Device Tree to 8fd30000, end 8fd39605 ... OK

Starting kernel ...

Uncompressing Linux... done, booting the kernel.
[    0.384810] omap2_mbox_probe: platform not supported
[    0.540541] tps65217-bl tps65217-bl: no platform data provided
[    0.604330] bone-capemgr bone_capemgr.9: slot #0: No cape found
[    0.641437] bone-capemgr bone_capemgr.9: slot #1: No cape found
[    0.678546] bone-capemgr bone_capemgr.9: slot #2: No cape found
[    0.715656] bone-capemgr bone_capemgr.9: slot #3: No cape found
[    0.741854] omap_hsmmc mmc.5: of_parse_phandle_with_args of 'reset' failed
[    0.803809] pinctrl-single 44e10800.pinmux: pin 44e10854 already requested by 44e10800.pinmux; cannot claim for gpio-leds.8
[    0.815463] pinctrl-single 44e10800.pinmux: pin-21 (gpio-leds.8) status -22
[    0.822748] pinctrl-single 44e10800.pinmux: could not request pin 21 on device pinctrl-single
[    0.893233] Unhandled fault: external abort on non-linefetch (0x1008) at 0xe0858c20
[    0.901225] Internal error: : 1008 [#1] SMP THUMB2
[    0.906217] Modules linked in:
[    0.909405] CPU: 0    Not tainted  (3.8.13-bone79 #1)
[    0.914691] PC is at cpts_fifo_read.constprop.1+0x18/0xc4
[    0.920317] LR is at cpts_systim_read+0x11/0x7c
[    0.925040] pc : [<c0326468>]    lr : [<c0326761>]    psr: 000001b3
[    0.925040] sp : df071db8  ip : 00000000  fp : de231664
[    0.936993] r10: de231000  r9 : de231758  r8 : c084e0c0
[    0.942440] r7 : 00000001  r6 : ffffffff  r5 : 00000010  r4 : de231670
[    0.949241] r3 : e0858c00  r2 : 00000001  r1 : de2316d0  r0 : de231670
[    0.956039] Flags: nzcv  IRQs off  FIQs on  Mode SVC_32  ISA Thumb  Segment kernel
[    0.963925] Control: 50c5387d  Table: 80004019  DAC: 00000015
[    0.969907] Process swapper/0 (pid: 1, stack limit = 0xdf070240)
[    0.976163] Stack: (0xdf071db8 to 0xdf072000)
[    0.980699] 1da0:                                                       e0858c00 de2316d0
[    0.989219] 1dc0: de2316bc 35318bf5 00000000 0000001d c052e7a8 c0326761 de2316e8 de2316bc
[    0.997740] 1de0: 35318bf5 c00611f1 de231670 20000113 de2316e8 c0326927 35318bf5 00000000
[    1.006259] 1e00: 00000000 00000004 df0d5410 de231000 df0d5400 c0325bab df0d8ac0 de231540
[    1.014775] 1e20: c0893bb8 0000002b de231540 df0d5400 df0d5410 00000005 00000000 df0d5410
[    1.023298] 1e40: e0858800 e0858a00 e0858a20 e0858a40 e0858a60 e08588c0 e08588e0 00000008
[    1.031813] 1e60: 00000001 0000003c 4a102000 4a102000 00002000 00000010 00000001 de231298
[    1.040338] 1e80: e0858d00 0000000a 00000400 00000002 00000020 00000008 df0d5410 c094362c
[    1.048868] 1ea0: df0d5410 c08b2c40 00000000 c0829039 00000102 c0846d70 00000000 c02c82b1
[    1.057381] 1ec0: c02c82a1 c02c7753 00000000 df0d5410 c08b2c40 df0d5444 00000000 c02c78b3
[    1.065896] 1ee0: c08b2c40 c02c7869 00000000 c02c6887 df049478 df0c6180 c08b2c40 c08a8090
[    1.074421] 1f00: de23d140 c02c7247 c0753554 c08b2c40 c08b2c40 df070000 c08d4180 00000000
[    1.082937] 1f20: c0829039 c02c7bb5 00000000 c0833968 df070000 c08d4180 00000000 c0829039
[    1.091461] 1f40: 00000102 c000867f 00000007 00000007 c088bc98 c0833964 c0833968 00000007
[    1.099978] 1f60: c0833948 c08d4180 c080d1c9 c0846d70 00000000 c080d6a3 00000007 00000007
[    1.108503] 1f80: c080d1c9 c0d60fc0 00000000 c04ccfb1 00000000 00000000 00000000 00000000
[    1.117013] 1fa0: 00000000 c04ccfb7 00000000 c000c8fd 00000000 00000000 00000000 00000000
[    1.125537] 1fc0: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
[    1.134055] 1fe0: 00000000 00000000 00000000 00000000 00000013 00000000 00000000 00000000
[    1.142587] [<c0326468>] (cpts_fifo_read.constprop.1+0x18/0xc4) from [<c0326761>] (cpts_systim_read+0x11/0x7c)
[    1.153018] [<c0326761>] (cpts_systim_read+0x11/0x7c) from [<c00611f1>] (timecounter_init+0x11/0x1c)
[    1.162545] [<c00611f1>] (timecounter_init+0x11/0x1c) from [<c0326927>] (cpts_register+0xf3/0x1b8)
[    1.171894] [<c0326927>] (cpts_register+0xf3/0x1b8) from [<c0325bab>] (cpsw_probe+0x823/0x960)
[    1.180877] [<c0325bab>] (cpsw_probe+0x823/0x960) from [<c02c82b1>] (platform_drv_probe+0x11/0x14)
[    1.190222] [<c02c82b1>] (platform_drv_probe+0x11/0x14) from [<c02c7753>] (driver_probe_device+0x53/0x168)
[    1.200282] [<c02c7753>] (driver_probe_device+0x53/0x168) from [<c02c78b3>] (__driver_attach+0x4b/0x4c)
[    1.210093] [<c02c78b3>] (__driver_attach+0x4b/0x4c) from [<c02c6887>] (bus_for_each_dev+0x27/0x48)
[    1.219521] [<c02c6887>] (bus_for_each_dev+0x27/0x48) from [<c02c7247>] (bus_add_driver+0xe3/0x168)
[    1.228949] [<c02c7247>] (bus_add_driver+0xe3/0x168) from [<c02c7bb5>] (driver_register+0x3d/0xc4)
[    1.238289] [<c02c7bb5>] (driver_register+0x3d/0xc4) from [<c000867f>] (do_one_initcall+0x1f/0xf4)
[    1.247630] [<c000867f>] (do_one_initcall+0x1f/0xf4) from [<c080d6a3>] (kernel_init_freeable+0xc3/0x158)
[    1.257516] [<c080d6a3>] (kernel_init_freeable+0xc3/0x158) from [<c04ccfb7>] (kernel_init+0x7/0x98)
[    1.266951] [<c04ccfb7>] (kernel_init+0x7/0x98) from [<c000c8fd>] (ret_from_fork+0x11/0x34)
[    1.275659] Code: 2701 f100 09e8 6823 (6a1a) 07d3
[    1.280655] ---[ end trace b2036333b4d03ad2 ]---
[    1.285687] Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000b
</code>```

With a Debian Jessie image, Ker 4.4, board is booting normally.

Any idea how to solve this, is kindly appreciated.
Thank you.

答: As per my knowledge there was some issue with CTPS driver in kernel V3.13 (forget the exact kernel version). So it was an open issue. May be with newer kernel version they have fixed it. If you have the source code then try by disabling the CTPS driver CONFIG_TI_CPTS=n.

Body:
I'm trying to boot a Debian Wheezy Image, Ker 3.8 on my BeagleCore (a smaller version of BeagleBone) with TI AM335x Cortex-A8 processor.
I took the Debian Image from beagleboard site.
When I try to boot, on a serial interface for debug, I get this messages:

U-Boot SPL 2016.01-00001-g4eb802e (Jan 13 2016 - 11:14:31)
Trying to boot from MMC
bad magic

U-Boot 2016.01-00001-g4eb802e (Jan 13 2016 - 11:14:31 -0600), Build: jenkins-github_Bootloader-Builder-313

    Watchdog enabled
I2C:   ready
DRAM:  512 MiB
Reset Source: Power-on reset has occurred.
MMC:   OMAP SD/MMC: 0, OMAP SD/MMC: 1
Using default environment

Net:   <ethaddr> not set. Validating first E-fuse MAC
Could not get PHY for cpsw: addr 0
cpsw, usb_ether
Press SPACE to abort autoboot in 2 seconds
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
gpio: pin 56 (gpio 56) value is 0
gpio: pin 55 (gpio 55) value is 0
gpio: pin 54 (gpio 54) value is 0
gpio: pin 53 (gpio 53) value is 1
switch to partitions #0, OK
mmc0 is current device
gpio: pin 54 (gpio 54) value is 1
Checking for: /uEnv.txt ...
Checking for: /boot.scr ...
Checking for: /boot/boot.scr ...
Checking for: /boot/uEnv.txt ...
gpio: pin 55 (gpio 55) value is 1
2181 bytes read in 16 ms (132.8 KiB/s)
Loaded environment from /boot/uEnv.txt
Checking if uname_r is set in /boot/uEnv.txt...
gpio: pin 56 (gpio 56) value is 1
Running uname_boot ...
loading /boot/vmlinuz-3.8.13-bone79 ...
5644336 bytes read in 333 ms (16.2 MiB/s)
loading /boot/dtbs/3.8.13-bone79/am335x-boneblack.dtb ...
26118 bytes read in 24 ms (1 MiB/s)
loading /boot/initrd.img-3.8.13-bone79 ...
2905600 bytes read in 179 ms (15.5 MiB/s)
debug: [console=ttyO0,115200n8 capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4,BB-UART5 capemgr.disable_partno=BB-BONELT-HDMI,BB-BONELT-HDMIN root=UUID=4d8c9d4c-a16d-47ac-a32c-43d0155df072 ro rootfstype=ext4 rootwait coherent_pool=1M quiet init=/lib/systemd/systemd cape_universal=enable] ...
debug: [bootz 0x82000000 0x88080000:2c5600 0x88000000] ...
Kernel image @ 0x82000000 [ 0x000000 - 0x562030 ]
## Flattened Device Tree blob at 88000000
   Booting using the fdt blob at 0x88000000
   Loading Ramdisk to 8fd3a000, end 8ffff600 ... OK
   Loading Device Tree to 8fd30000, end 8fd39605 ... OK

Starting kernel ...

Uncompressing Linux... done, booting the kernel.
[    0.384810] omap2_mbox_probe: platform not supported
[    0.540541] tps65217-bl tps65217-bl: no platform data provided
[    0.604330] bone-capemgr bone_capemgr.9: slot #0: No cape found
[    0.641437] bone-capemgr bone_capemgr.9: slot #1: No cape found
[    0.678546] bone-capemgr bone_capemgr.9: slot #2: No cape found
[    0.715656] bone-capemgr bone_capemgr.9: slot #3: No cape found
[    0.741854] omap_hsmmc mmc.5: of_parse_phandle_with_args of 'reset' failed
[    0.803809] pinctrl-single 44e10800.pinmux: pin 44e10854 already requested by 44e10800.pinmux; cannot claim for gpio-leds.8
[    0.815463] pinctrl-single 44e10800.pinmux: pin-21 (gpio-leds.8) status -22
[    0.822748] pinctrl-single 44e10800.pinmux: could not request pin 21 on device pinctrl-single
[    0.893233] Unhandled fault: external abort on non-linefetch (0x1008) at 0xe0858c20
[    0.901225] Internal error: : 1008 [#1] SMP THUMB2
[    0.906217] Modules linked in:
[    0.909405] CPU: 0    Not tainted  (3.8.13-bone79 #1)
[    0.914691] PC is at cpts_fifo_read.constprop.1+0x18/0xc4
[    0.920317] LR is at cpts_systim_read+0x11/0x7c
[    0.925040] pc : [<c0326468>]    lr : [<c0326761>]    psr: 000001b3
[    0.925040] sp : df071db8  ip : 00000000  fp : de231664
[    0.936993] r10: de231000  r9 : de231758  r8 : c084e0c0
[    0.942440] r7 : 00000001  r6 : ffffffff  r5 : 00000010  r4 : de231670
[    0.949241] r3 : e0858c00  r2 : 00000001  r1 : de2316d0  r0 : de231670
[    0.956039] Flags: nzcv  IRQs off  FIQs on  Mode SVC_32  ISA Thumb  Segment kernel
[    0.963925] Control: 50c5387d  Table: 80004019  DAC: 00000015
[    0.969907] Process swapper/0 (pid: 1, stack limit = 0xdf070240)
[    0.976163] Stack: (0xdf071db8 to 0xdf072000)
[    0.980699] 1da0:                                                       e0858c00 de2316d0
[    0.989219] 1dc0: de2316bc 35318bf5 00000000 0000001d c052e7a8 c0326761 de2316e8 de2316bc
[    0.997740] 1de0: 35318bf5 c00611f1 de231670 20000113 de2316e8 c0326927 35318bf5 00000000
[    1.006259] 1e00: 00000000 00000004 df0d5410 de231000 df0d5400 c0325bab df0d8ac0 de231540
[    1.014775] 1e20: c0893bb8 0000002b de231540 df0d5400 df0d5410 00000005 00000000 df0d5410
[    1.023298] 1e40: e0858800 e0858a00 e0858a20 e0858a40 e0858a60 e08588c0 e08588e0 00000008
[    1.031813] 1e60: 00000001 0000003c 4a102000 4a102000 00002000 00000010 00000001 de231298
[    1.040338] 1e80: e0858d00 0000000a 00000400 00000002 00000020 00000008 df0d5410 c094362c
[    1.048868] 1ea0: df0d5410 c08b2c40 00000000 c0829039 00000102 c0846d70 00000000 c02c82b1
[    1.057381] 1ec0: c02c82a1 c02c7753 00000000 df0d5410 c08b2c40 df0d5444 00000000 c02c78b3
[    1.065896] 1ee0: c08b2c40 c02c7869 00000000 c02c6887 df049478 df0c6180 c08b2c40 c08a8090
[    1.074421] 1f00: de23d140 c02c7247 c0753554 c08b2c40 c08b2c40 df070000 c08d4180 00000000
[    1.082937] 1f20: c0829039 c02c7bb5 00000000 c0833968 df070000 c08d4180 00000000 c0829039
[    1.091461] 1f40: 00000102 c000867f 00000007 00000007 c088bc98 c0833964 c0833968 00000007
[    1.099978] 1f60: c0833948 c08d4180 c080d1c9 c0846d70 00000000 c080d6a3 00000007 00000007
[    1.108503] 1f80: c080d1c9 c0d60fc0 00000000 c04ccfb1 00000000 00000000 00000000 00000000
[    1.117013] 1fa0: 00000000 c04ccfb7 00000000 c000c8fd 00000000 00000000 00000000 00000000
[    1.125537] 1fc0: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
[    1.134055] 1fe0: 00000000 00000000 00000000 00000000 00000013 00000000 00000000 00000000
[    1.142587] [<c0326468>] (cpts_fifo_read.constprop.1+0x18/0xc4) from [<c0326761>] (cpts_systim_read+0x11/0x7c)
[    1.153018] [<c0326761>] (cpts_systim_read+0x11/0x7c) from [<c00611f1>] (timecounter_init+0x11/0x1c)
[    1.162545] [<c00611f1>] (timecounter_init+0x11/0x1c) from [<c0326927>] (cpts_register+0xf3/0x1b8)
[    1.171894] [<c0326927>] (cpts_register+0xf3/0x1b8) from [<c0325bab>] (cpsw_probe+0x823/0x960)
[    1.180877] [<c0325bab>] (cpsw_probe+0x823/0x960) from [<c02c82b1>] (platform_drv_probe+0x11/0x14)
[    1.190222] [<c02c82b1>] (platform_drv_probe+0x11/0x14) from [<c02c7753>] (driver_probe_device+0x53/0x168)
[    1.200282] [<c02c7753>] (driver_probe_device+0x53/0x168) from [<c02c78b3>] (__driver_attach+0x4b/0x4c)
[    1.210093] [<c02c78b3>] (__driver_attach+0x4b/0x4c) from [<c02c6887>] (bus_for_each_dev+0x27/0x48)
[    1.219521] [<c02c6887>] (bus_for_each_dev+0x27/0x48) from [<c02c7247>] (bus_add_driver+0xe3/0x168)
[    1.228949] [<c02c7247>] (bus_add_driver+0xe3/0x168) from [<c02c7bb5>] (driver_register+0x3d/0xc4)
[    1.238289] [<c02c7bb5>] (driver_register+0x3d/0xc4) from [<c000867f>] (do_one_initcall+0x1f/0xf4)
[    1.247630] [<c000867f>] (do_one_initcall+0x1f/0xf4) from [<c080d6a3>] (kernel_init_freeable+0xc3/0x158)
[    1.257516] [<c080d6a3>] (kernel_init_freeable+0xc3/0x158) from [<c04ccfb7>] (kernel_init+0x7/0x98)
[    1.266951] [<c04ccfb7>] (kernel_init+0x7/0x98) from [<c000c8fd>] (ret_from_fork+0x11/0x34)
[    1.275659] Code: 2701 f100 09e8 6823 (6a1a) 07d3
[    1.280655] ---[ end trace b2036333b4d03ad2 ]---
[    1.285687] Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000b

With a Debian Jessie image, Ker 4.4, board is booting normally.

Any idea how to solve this, is kindly appreciated.
Thank you.


问:
Pythonic way to switch object "behind the scenes"
I know about the nature of python object names being nothing but "labels" that can be attached to any object and that variables are always passed by reference. But what if I need a different behavior?

To illustrate this, I made a Short example:

```<code>class car:
    def __init__(self, brand):
        self.brand = brand

subaru = car("subaru")
toyota = car("toyota")

current_car = subaru
current_brand = current_car.brand

print (current_brand)

current_car = toyota

print (current_brand)
</code>```

The Output I get is:

```<code>subaru
subaru
</code>```

This doesn't surprise me. However in the project I'm working on right now, I would like to express a selection by making current_car the selected car. Also I would like the object current_brand to always hold the brand of the current car without explicitly doing:

```<code>current_brand = current_car.brand
</code>```

every time I switch the current car. I thought about using a property decorator for this, but I am not shure, that that's the right way. Is there a pythonic way to do this or am I thinking in the wrong direction all-together?

答:
Well, it turns out, that I had a weird knot in my brain, which was keeping me from understanding even the simplest basics of programming. For the unlikely chance someone else goes down the same dead end road of thinking (and happens to find this post) here is what I meant to do:

```<code>class car:
    def __init__(self, brand):
        self.brand = brand

subaru = car("subaru")
toyota = car("toyota")

current_car = subaru

def current_brand():
    return current_car.brand

print (current_brand())

current_car = toyota

print (current_brand())
</code>```

I didn't get that all I tried to do was to have a function that gives me the current_car's brand.

Well, maybe I should take a break and go outside for a while...

Body:
I know about the nature of python object names being nothing but "labels" that can be attached to any object and that variables are always passed by reference. But what if I need a different behavior?

To illustrate this, I made a Short example:

class car:
    def __init__(self, brand):
        self.brand = brand

subaru = car("subaru")
toyota = car("toyota")

current_car = subaru
current_brand = current_car.brand

print (current_brand)

current_car = toyota

print (current_brand)

The Output I get is:

subaru
subaru

This doesn't surprise me. However in the project I'm working on right now, I would like to express a selection by making current_car the selected car. Also I would like the object current_brand to always hold the brand of the current car without explicitly doing:

current_brand = current_car.brand

every time I switch the current car. I thought about using a property decorator for this, but I am not shure, that that's the right way. Is there a pythonic way to do this or am I thinking in the wrong direction all-together?

Body:
Well, it turns out, that I had a weird knot in my brain, which was keeping me from understanding even the simplest basics of programming. For the unlikely chance someone else goes down the same dead end road of thinking (and happens to find this post) here is what I meant to do:

class car:
    def __init__(self, brand):
        self.brand = brand

subaru = car("subaru")
toyota = car("toyota")

current_car = subaru

def current_brand():
    return current_car.brand

print (current_brand())

current_car = toyota

print (current_brand())

I didn't get that all I tried to do was to have a function that gives me the current_car's brand.

Well, maybe I should take a break and go outside for a while...


问:
Regex to check pattern with numbers
I want to create a regex that does the following

<\numberMAX8>[space or not]<\symbol(-)>[space or not]<\numberMAX8> and max 10 times of all of this - I don't care about end spaces, also numbers must be between 5-8.

To explain it a bit more I'll give a few examples

ex:

5-6 7-6 8-8 6-7 ok

4-7 not ok //because of 4

7    -   6 ok

7-6-6-6 not ok because of the - in the middle

Below is what I have so far without having included the mid spaces.

```<code>^([5-8](?:-|\s)[5-8][\s]){1,10}
          ->  <-//didnt work.
</code>```

答:
Here you go:

```<code>^([5-8]\s*-\s*[5-8]\s*){1,10}$
</code>```

So the explanation is:

The regex matches a starting number from 5-8 ^[5-8], then an arbitrary number of spaces \s*, then dash -, then arbitrary number of spaces \s*, then a number from 5 to 8 [5-8], then an arbitrary number of spaces \s*, and that pattern from 1 to 10 times {1,10}, and nothing after the pattern $.

Title: Regex to check pattern with numbers

Body:
I want to create a regex that does the following

<\numberMAX8>[space or not]<\symbol(-)>[space or not]<\numberMAX8> and max 10 times of all of this - I don't care about end spaces, also numbers must be between 5-8.

To explain it a bit more I'll give a few examples

ex:

5-6 7-6 8-8 6-7 ok

4-7 not ok //because of 4

7    -   6 ok

7-6-6-6 not ok because of the - in the middle

Below is what I have so far without having included the mid spaces.

^([5-8](?:-|\s)[5-8][\s]){1,10}
          ->  <-//didnt work.

Body:
Here you go:

^([5-8]\s*-\s*[5-8]\s*){1,10}$

So the explanation is:

The regex matches a starting number from 5-8 ^[5-8], then an arbitrary number of spaces \s*, then dash -, then arbitrary number of spaces \s*, then a number from 5 to 8 [5-8], then an arbitrary number of spaces \s*, and that pattern from 1 to 10 times {1,10}, and nothing after the pattern $.


问:
How can I make certain parts of my html not selectable?
How can I make certain parts of my html not selectable?

I have some absolutely positioned divs that keep getting selected if a user tries to select the content of my page.

Is there a way to make it so certain elements (such as those divs) aren't selectable?

EDIT: The main issue is when someone copies these absolute div's and then pastes them into the rich text editor on my site, the rich text editor breaks on IE.

答:
jQuery Solution:

```<code>$(".unselectable").disableSelection();
</code>```

Body:
jQuery Solution:

$(".unselectable").disableSelection();


问:
nodejs - Parameters I am sending via POST are undefined
server.js:

```<code>    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    loggedIn = {};

    app.use('/',express.static('www')); // static files
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    app.listen(8080, function () {
      console.log('Port 8080!');
    });

    app.get('/user', function(req, res) {
        if (typeof req.query.user != 'undefined') {
            user = req.query.user;
            res.status(200).send('Works');
        }
    });

    app.post('/user', function(req, res) {
            user = req.body.user;
            if (typeof users[user] != 'undefined') {
                return res.status(405).send('Access Forbidden');
            } else {
                   loggedIn.push(user);
                   res.status(201).send('New User');
            }
        }
    });
</code>```

client.js requests:

```<code>    $.ajax({
        method: "GET",
        url: "/user",
        data: {"user" : user},
        dataType: "application/json",
        success: function(data) {
            // success
        },
        error: function() {
            // error case
        }
    });

    $.ajax({
        method: "POST",
        url: "/user",
        data: {"user" : user},
        dataType: "application/json",
        success: function(data) {
            // success
        },
        error: function() {
            // error case
        }
    });
</code>```

Even though the GET request works exactly as expected but POST doesn't. Whenever I try to pass a POST request through, it hangs in limbo, even though all the parameters show up in Firebug. When I try to force ContentType to application/json, I get an "Unexpected token u" error an 400 Bad Request, meaning what I am sending through is undefined, even though there are clearly parameters with values visible in Firebug when I check the POST request there and I know for a fact I am passing something given the fact that in Firebug, the variables I am passing have values as seen in the DOM section and those same values pop up in the POST request under Firebug (parameters - user = "some text here").

答:
when you use Content-Type = application/json

Then all the body will parse into JSON and you not need to parse it

if(typeof req.body == "string"){
   var body = JSON.parse(req.body)
}

Body:
server.js:

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    loggedIn = {};

    app.use('/',express.static('www')); // static files
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    app.listen(8080, function () {
      console.log('Port 8080!');
    });

    app.get('/user', function(req, res) {
        if (typeof req.query.user != 'undefined') {
            user = req.query.user;
            res.status(200).send('Works');
        }
    });

    app.post('/user', function(req, res) {
            user = req.body.user;
            if (typeof users[user] != 'undefined') {
                return res.status(405).send('Access Forbidden');
            } else {
                   loggedIn.push(user);
                   res.status(201).send('New User');
            }
        }
    });

client.js requests:

    $.ajax({
        method: "GET",
        url: "/user",
        data: {"user" : user},
        dataType: "application/json",
        success: function(data) {
            // success
        },
        error: function() {
            // error case
        }
    });

    $.ajax({
        method: "POST",
        url: "/user",
        data: {"user" : user},
        dataType: "application/json",
        success: function(data) {
            // success
        },
        error: function() {
            // error case
        }
    });

Even though the GET request works exactly as expected but POST doesn't. Whenever I try to pass a POST request through, it hangs in limbo, even though all the parameters show up in Firebug. When I try to force ContentType to application/json, I get an "Unexpected token u" error an 400 Bad Request, meaning what I am sending through is undefined, even though there are clearly parameters with values visible in Firebug when I check the POST request there and I know for a fact I am passing something given the fact that in Firebug, the variables I am passing have values as seen in the DOM section and those same values pop up in the POST request under Firebug (parameters - user = "some text here").


问:
Swift: Get all subviews of a specific type and add to an array
I have a custom class of buttons in a UIView that I'd like to add to an array so that they're easily accessible. Is there a way to get all subviews of a specific class and add it to an array in Swift?</p>

答:
If you want to update/access those specific subviews then use this,</p>

```<code>for (index,button) in (view.subviews.filter{$0 is UIButton}).enumerated(){
    button.isHidden = false
}
</code>```

Body:
If you want to update/access those specific subviews then use this,

for (index,button) in (view.subviews.filter{$0 is UIButton}).enumerated(){
    button.isHidden = false
}


问:
Xcode quits unexpectedly every time I open my project
After opening xcode, when I open my current project, it's showing a warning like "xcode quit unexpectedly" with 3 options: "Ignore", "Report" and "Reopen". When I click "Reopen", it will open the xcode window and again automatically it will close and show the same warning.

Why this is happening? If I open any other projects, then it opens with no issues; the issue is with my current app.

versions:

xcode is 4.3.1

mac OS X version is 10.7.3

Please tell me why it's happening like this.

答: If you're using CocoaPods, just follow Rob's instruction but on the .xcworkspace file instead and do not delete the .xcworkspacedata file.


问:
Solr - Can't search when term ends with "y"
This problem seems really ridiculous.
I always get 0 results when searching for entries that end with "y". I know they exist.

0 Results:

Barthy

Tony

Maxy

x Results:

Barth

Ton

Max

With any of the last three I get the desired results (Barthy B, Tony Banderas, Maxy Doe, ...)

Words that contain but don't end with "y" are totally fine (Rayman, ...)

What is happening? Could something like this be achieved with the schema (if yes, how? So that I can search for it)

Any other idea where to start looking?

答: In my config, it was SnowballPorterFilterFactory and not lowercase snowballporterfilterfactory</p>


问:
How to create ManyToOne relationship using JPA Hibernate annotation?
I had two POJO class named Task and Team.A team can have many tasks correspondingly but each task can be mapped only one team.

```<code>// Task POJO
@Entity
@Table(name = "Task")
public class Task extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long taskId;

//Mapping To Team
@ManyToOne
@JoinColumn(name="teamId")
private Team teamId;
</code>```

Team POJO

```<code>@Entity
@Table(name = "Team")
public class Team extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long teamId;
@Column(nullable = false)

@OneToMany(mappedBy="teamId")
private List<Task> task = new ArrayList<Task>();
</code>```

The issue is I couldn't  Map/Save/Update and which is not affecting my Team Pojo.

```<code>  //Task Table
  +-----------------+--------------+------+-----+---------+----------------+
  | Field           | Type         | Null | Key | Default | Extra          |
  +-----------------+--------------+------+-----+---------+----------------+
  | taskId          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
  | taskName        | varchar(255) | NO   |     | NULL    |                |
  | teamId          | bigint(20)   | YES  | MUL | NULL    |                |
  +-----------------+--------------+------+-----+---------+----------------+
</code>```

The Team Table

```<code> +----------+--------------+------+-----+---------+----------------+
 | Field    | Type         | Null | Key | Default | Extra          |
 +----------+--------------+------+-----+---------+----------------+
 | teamId   | bigint(20)   | NO   | PRI | NULL    | auto_increment |
 | teamName | varchar(255) | NO   |     | NULL    |                |
 +----------+--------------+------+-----+---------+----------------+
</code>```

So How do I map these two Pojo classes and affect when saving/deletion of data in the tables.

Thanks in Advance.

答: @OneToMany(mappedBy="teamId", cascade=CascadeType.ALL), try to add this annotation above the member(attribute) task of the class Team</p>

Body:
I had two POJO class named Task and Team.A team can have many tasks correspondingly but each task can be mapped only one team.

// Task POJO
@Entity
@Table(name = "Task")
public class Task extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long taskId;

//Mapping To Team
@ManyToOne
@JoinColumn(name="teamId")
private Team teamId;

Team POJO

@Entity
@Table(name = "Team")
public class Team extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long teamId;
@Column(nullable = false)

@OneToMany(mappedBy="teamId")
private List<Task> task = new ArrayList<Task>();

The issue is I couldn't  Map/Save/Update and which is not affecting my Team Pojo.

  //Task Table
  +-----------------+--------------+------+-----+---------+----------------+
  | Field           | Type         | Null | Key | Default | Extra          |
  +-----------------+--------------+------+-----+---------+----------------+
  | taskId          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
  | taskName        | varchar(255) | NO   |     | NULL    |                |
  | teamId          | bigint(20)   | YES  | MUL | NULL    |                |
  +-----------------+--------------+------+-----+---------+----------------+

The Team Table

 +----------+--------------+------+-----+---------+----------------+
 | Field    | Type         | Null | Key | Default | Extra          |
 +----------+--------------+------+-----+---------+----------------+
 | teamId   | bigint(20)   | NO   | PRI | NULL    | auto_increment |
 | teamName | varchar(255) | NO   |     | NULL    |                |
 +----------+--------------+------+-----+---------+----------------+

So How do I map these two Pojo classes and affect when saving/deletion of data in the tables.

Thanks in Advance.


问:
OpenGL blending with source and destination alpha
I'm trying to render a texture with alpha to a frame buffer with alpha. I need the texture's transparency to be controlled by a combination of its own alpha, and the alpha already rendered to the frame buffer.

ie:

Normal transparency:

(src_colour * src_alpha) + (dst_colour * 1-src_alpha)

Required transparency:

(src_colour * src_alpha * dst_alphe) + (dst_colour * 1-(src_alpha * dst_alpha))

Can anyone figure out how to do this?

I've been working on it for 9 hours now :-)

I'm using OpenGL 1.0 with GL11ExtensionPack on Android, so I have access to glBlendFunc and glBlendFuncSeparate. I would prefer not to go the GLES20 route with shaders as that would require a lot of code to be rewritten.

Thanks,
Andrew

答:
This is the solution I've used:

enable colour and alpha writes

glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA)

render foreground objects

disabe alpha writes

render shadows

render objects that are casting shadows

glBlendFunc(GL10.GL_ONE_MINUS_DST_ALPHA, GL10.GL_DST_ALPHA)

render background objects

This produces the desired effect of shadows appearing only on foreground objects. Effectively the alpha buffer becomes a stencil buffer with variable opacity.

It's fortunate that my background objects don't have transparency, as if they did I don't think there would be any way to achieve this effect without using shaders.


问:
how to change jquery.mmenu width
I have a problem. I want to change the width jquery.mmenu.
When I change the width, a white space appears between the navbar and the enter image description heresidebar.
How can I change the width so that this space does not appear</p>

答:
```<code>$("target").css("width", "10px");
</code>```

But i don't understand what you changed

Title: how to change jquery.mmenu width

Body:
$("target").css("width", "10px");

But i don't understand what you changed


问:
How to present view controller behind another view controller?
I am trying to present two view controllers. I'm trying to avoid presenting one after the other as this doesn't give a good user experience.

I'm using storyboards / segues to present the view controllers, each embedded in navigation controllers.

The behaviour should be:

View Controller 1 presents view controller 2 - but when view controller 2 dismisses I'd like view controller 3 to be the one showing to the user. And ideally an ability to also dismiss to view controller 1.

I understand I can accomplish this with child views. But I'd ideally like to learn how it can be done by manipulating the navigation stack.

答:
As best to my understanding about your question, try out below method:

Present VC 3 from VC 1 and from VC 3 present VC 2 immediately(This can be done by putting the viewController present code in the ViewDidLoad() of VC 3).

So when you dismiss VC 2, VC 3 will be shown and on dismissing VC 3 , you will be redirected to VC 1.

VC means ViewController.


问:
Improving pandas performance with apply method
I'm working on pandas for high performance calculations, the below function gives 1 loop, best of 5: 7.24 s per loop for 50,000 rows.

I have to scale it to 1 million rows.

How to vectorise the function and apply to all rows. So that overall performance can be improved?

```<code>def weightedFlowAmt(startDate,endDate,tradeDate,tradeAmt):
  startInDays = datetime.strptime(startDate, "%Y-%m-%d")
  endInDays = datetime.strptime(endDate, "%Y-%m-%d")
  tradeInDays = datetime.strptime(tradeDate, "%Y-%m-%d")
  differenceTradeAndEnd=abs((endInDays - tradeInDays).days)
  differenceStartAndEnd=abs((endInDays - startInDays).days)
  weighted_FlowAmt = (tradeAmt * differenceTradeAndEnd)/differenceStartAndEnd

mutatedCashFlow['flow'] = mutatedCashFlow.apply(lambda row:
        weightedFlowAmt(row['startDate'], row['EndDate'], row['tradeDate'],
                        row['tradeAmount']),
    axis=1)
</code>```

答:
I think you can remove apply and use vectorized functions:

```<code>mutatedCashFlow['startDate'] = pd.to_datetime(mutatedCashFlow['startDate'])
mutatedCashFlow['EndDate'] = pd.to_datetime(mutatedCashFlow['EndDate'])
mutatedCashFlow['tradeDate'] = pd.to_datetime(mutatedCashFlow['tradeDate'])

diffTradeAndEnd=((mutatedCashFlow['EndDate']-mutatedCashFlow['tradeDate']).dt.days).abs()
diffStartAndEnd=((mutatedCashFlow['EndDate']-mutatedCashFlow['startDate']).dt.days).abs()

mutatedCashFlow['flow'] = (mutatedCashFlow['tradeAmount']*diffTradeAndEnd)/diffStartAndEnd
</code>```

Alternative:

```<code>mutatedCashFlow['startDate'] = pd.to_datetime(mutatedCashFlow['startDate'])
mutatedCashFlow['EndDate'] = pd.to_datetime(mutatedCashFlow['EndDate'])
mutatedCashFlow['tradeDate'] = pd.to_datetime(mutatedCashFlow['tradeDate'])

diffTradeAndEnd=mutatedCashFlow['EndDate'].sub(mutatedCashFlow['tradeDate']).dt.days.abs()
diffStartAndEnd=mutatedCashFlow['EndDate'].sub(mutatedCashFlow['startDate']).dt.days.abs()

mutatedCashFlow['flow'] = mutatedCashFlow['tradeAmount'].mul(diffTradeAndEnd)
                                                        .div(diffStartAndEnd)
print (mutatedCashFlow)
</code>```

Body:
I'm working on pandas for high performance calculations, the below function gives 1 loop, best of 5: 7.24 s per loop for 50,000 rows.

I have to scale it to 1 million rows.

How to vectorise the function and apply to all rows. So that overall performance can be improved?

def weightedFlowAmt(startDate,endDate,tradeDate,tradeAmt):
  startInDays = datetime.strptime(startDate, "%Y-%m-%d")
  endInDays = datetime.strptime(endDate, "%Y-%m-%d")
  tradeInDays = datetime.strptime(tradeDate, "%Y-%m-%d")
  differenceTradeAndEnd=abs((endInDays - tradeInDays).days)
  differenceStartAndEnd=abs((endInDays - startInDays).days)
  weighted_FlowAmt = (tradeAmt * differenceTradeAndEnd)/differenceStartAndEnd

mutatedCashFlow['flow'] = mutatedCashFlow.apply(lambda row:
        weightedFlowAmt(row['startDate'], row['EndDate'], row['tradeDate'],
                        row['tradeAmount']),
    axis=1)

Body:
I think you can remove apply and use vectorized functions:

mutatedCashFlow['startDate'] = pd.to_datetime(mutatedCashFlow['startDate'])
mutatedCashFlow['EndDate'] = pd.to_datetime(mutatedCashFlow['EndDate'])
mutatedCashFlow['tradeDate'] = pd.to_datetime(mutatedCashFlow['tradeDate'])

diffTradeAndEnd=((mutatedCashFlow['EndDate']-mutatedCashFlow['tradeDate']).dt.days).abs()
diffStartAndEnd=((mutatedCashFlow['EndDate']-mutatedCashFlow['startDate']).dt.days).abs()

mutatedCashFlow['flow'] = (mutatedCashFlow['tradeAmount']*diffTradeAndEnd)/diffStartAndEnd

Alternative:

mutatedCashFlow['startDate'] = pd.to_datetime(mutatedCashFlow['startDate'])
mutatedCashFlow['EndDate'] = pd.to_datetime(mutatedCashFlow['EndDate'])
mutatedCashFlow['tradeDate'] = pd.to_datetime(mutatedCashFlow['tradeDate'])

diffTradeAndEnd=mutatedCashFlow['EndDate'].sub(mutatedCashFlow['tradeDate']).dt.days.abs()
diffStartAndEnd=mutatedCashFlow['EndDate'].sub(mutatedCashFlow['startDate']).dt.days.abs()

mutatedCashFlow['flow'] = mutatedCashFlow['tradeAmount'].mul(diffTradeAndEnd)
                                                        .div(diffStartAndEnd)
print (mutatedCashFlow)


问:
ContentEditable doesn't allow to send php strings
I have a problem with contenteditable .

Before i used textarea for sending posts for text. I want to change it now to use contenteditable.

So contenteditable doesn't allow to send php strings from data. For example

DEMO

In this demo i will show you my html and ajax codes. That is working perfectly, if user send normal text. But if user want to share php codes from his friends like (<?php echo 'Hi There.';?>) then problem will be come here. If user write normal text like (Hi There.) then not have any problem.

Normaly we are using val(); if we use textarea like this

var updateText = $('#post-text-area').val();

I think problem will be come here but i am not sure.

答:
use with encodeURIComponent() .it will prevent the tag's passing from html to php .And retrieve the data from php use with decodeURIComponent()

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

      $("body").on("click", ".sendPost", function() {
        var updateText = $('#post-text-area').html();
        var dataString = 'update=' +  encodeURIComponent(updateText);
        $.ajax({
          type: 'POST',
          url: '/posttext.php',
          data: dataString,
          beforeSend: function() {},
          success: function(html) {
           decodeURIComponent(html);
          }
        });
      });
</code>```

Body:
use with encodeURIComponent() .it will prevent the tag's passing from html to php .And retrieve the data from php use with decodeURIComponent()

$(document).ready(function() {

      $("body").on("click", ".sendPost", function() {
        var updateText = $('#post-text-area').html();
        var dataString = 'update=' +  encodeURIComponent(updateText);
        $.ajax({
          type: 'POST',
          url: '/posttext.php',
          data: dataString,
          beforeSend: function() {},
          success: function(html) {
           decodeURIComponent(html);
          }
        });
      });


问:
GCM cannot receive message
My app use GCM that send notification message, my question is :

My app can receive notification message when app is foreground, but when app is background or killed my app can't receive notification message .

i want to custom a notification view, i do't want that gcm send notification.

答:
It is better you shift to Firebase Cloud Messaging (FCM). It handles both foreground and background cases of your app.

In contrast to GCM where a broadcast receiver also had to be implemented to receive messages, in FCM we use a service that extends FirebaseMessagingService. Your service should override the onMessageReceived and onDeletedMessages callbacks.

onMessageReceived is provided for most message types, with the following exceptions:

Notifications delivered when your app is in the background. In this
case, the notification is delivered to the device’s system tray. A
user tap on a notification opens the app launcher by default.

Messages with both notification and data payload, both background and
foreground. In this case, the notification is delivered to the
device’s system tray, and the data payload is delivered in the extras
of the intent of your launcher Activity.

For more information read FCM Notification for Android

Title: GCM cannot receive message


问:
How can i distinguish which UIAlertView's button was clicked from multiple alertview
In my appln I m using multiple UIAlertView and to determine which between was clicked in alertview i use the method

```<code>- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex{
</code>```

}

but i need only for the one alertview but it was responding for all alertviews. how to restrict to only to one alertview or to alertview to which i need determine the button action

答:
If you can afford to run on 4.x only, you can use blocks and forget about delegates and tags:

```<code>LambdaAlert *alert = [[LambdaAlert alloc]
    initWithTitle:@"Test Alert"
    message:@"See if the thing works."];
[alert addButtonWithTitle:@"Foo" block:^{ NSLog(@"Foo"); }];
[alert addButtonWithTitle:@"Bar" block:^{ NSLog(@"Bar"); }];
[alert addButtonWithTitle:@"Cancel" block:NULL];
[alert show];
[alert release];
</code>```

See LambdaAlert on GitHub.

Body:
In my appln I m using multiple UIAlertView and to determine which between was clicked in alertview i use the method

- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex{

}

but i need only for the one alertview but it was responding for all alertviews. how to restrict to only to one alertview or to alertview to which i need determine the button action

Body:
If you can afford to run on 4.x only, you can use blocks and forget about delegates and tags:

LambdaAlert *alert = [[LambdaAlert alloc]
    initWithTitle:@"Test Alert"
    message:@"See if the thing works."];
[alert addButtonWithTitle:@"Foo" block:^{ NSLog(@"Foo"); }];
[alert addButtonWithTitle:@"Bar" block:^{ NSLog(@"Bar"); }];
[alert addButtonWithTitle:@"Cancel" block:NULL];
[alert show];
[alert release];

See LambdaAlert on GitHub.


问:
Using OR in XSLT
I am having issues using the or operator in XSLT. I need to test if a variable does not equal 00 or 09.

The current value being entered into the XSLT for Timecodehour is 09. I am using the test below to confirm that the value must be 00 or 09.

```<code><xsl:template match="/">

<xsl:if test="$TimecodeHour!='00' or $TimecodeHour!='09'">
    <xsl:message terminate="yes">Timecode is not supported</xsl:message>
</xsl:if>
</xsl:template>
</code>```

The test completes correctly if I removed "$TimecodeHour!='00' or" but submitted message Timecode is not supported when I add it back in again. Could someone please help me understand what I am doing wrong?

答:
You need to use and not or here. or will be true if either of the conditions are true.

So, for example, if $TimecodeHour equals 09 then the expression $TimecodeHour!='00' returns true, and so the result of the or expression is true.

Using and will only return true if both conditions are true.

```<code><xsl:if test="$TimecodeHour!='00' and $TimecodeHour!='09'">
</code>```

Title: Using OR in XSLT

Body:
I am having issues using the or operator in XSLT. I need to test if a variable does not equal 00 or 09.

The current value being entered into the XSLT for Timecodehour is 09. I am using the test below to confirm that the value must be 00 or 09.

<xsl:template match="/">

<xsl:if test="$TimecodeHour!='00' or $TimecodeHour!='09'">
    <xsl:message terminate="yes">Timecode is not supported</xsl:message>
</xsl:if>
</xsl:template>

The test completes correctly if I removed "$TimecodeHour!='00' or" but submitted message Timecode is not supported when I add it back in again. Could someone please help me understand what I am doing wrong?

Body:
You need to use and not or here. or will be true if either of the conditions are true.

So, for example, if $TimecodeHour equals 09 then the expression $TimecodeHour!='00' returns true, and so the result of the or expression is true.

Using and will only return true if both conditions are true.

<xsl:if test="$TimecodeHour!='00' and $TimecodeHour!='09'">


问:
"extern string-literal declaration" within function scope
from [dcl.link]#2 :

extern string-literal declaration

the paragraph does not specify any special cases for declaration within a function scope, but following does not compile also :

```<code>void foo () { extern "C" int boo () ; }
</code>```

from g++ output :

error: expected unqualified-id before string constant

so is it a g++'s bug or i have missed something.?

答:
The linkage-specification is part of declaration which is part of declaration-seq which can be part of a namespace-body or a translation-unit.

Nowhere in the grammar is it allowed in a function, which uses block-declaration, which is almost the same as declaration but is notable missing linkage-specification.

Body:
from [dcl.link]#2 :

extern string-literal declaration

the paragraph does not specify any special cases for declaration within a function scope, but following does not compile also :

void foo () { extern "C" int boo () ; }

from g++ output :

error: expected unqualified-id before string constant

so is it a g++'s bug or i have missed something.?


问:
Easy way to export multiple data.frame to multiple Excel worksheets
I am surprised to find that there is no easy way to export multiple data.frame to multiple worksheets of an Excel file? I tried xlsx package, seems it can only write to one sheet (override old sheet); I also tried WriteXLS package, but it gives me error all the time...

My code structure is like this: by design, for each iteration, the output dataframe (tempTable) and the sheetName (sn) got updated and exported into one tab.

```<code>for (i in 2 : ncol(code)){
        ...
        tempTable <- ...
        sn <- ...
        WriteXLS("tempTable", ExcelFileName = "C:/R_code/../file.xlsx",
              SheetNames = sn);
}
</code>```

I can export to several cvs files, but there has to be an easy way to do that in Excel, right?

答:
Incase data size is small, R has many packages and functions which can be utilized as per your requirement.

write.xlsx, write.xlsx2, XLconnect also do the work but these are sometimes slow as compare to openxlsx.

So, if you are dealing with the large data sets and came across java errors. I would suggest to have a look of "openxlsx" which is really awesome and reduce the time to 1/12th.

I've tested all and finally i was really impressed with the performance of openxlsx capabilities.

Here are the steps for writing multiple datasets into multiple sheets.

```<code> install.packages("openxlsx")
 library("openxlsx")

    start.time <- Sys.time()

    # Creating large data frame
    x <- as.data.frame(matrix(1:4000000,200000,20))
    y <- as.data.frame(matrix(1:4000000,200000,20))
    z <- as.data.frame(matrix(1:4000000,200000,20))

    # Creating a workbook
    wb <- createWorkbook("Example.xlsx")
    Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") ## path to zip.exe
</code>```

Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") has to be static as it takes reference of some utility from Rtools.

Note: Incase Rtools is not installed on your system, please install it first for smooth experience. here is the link for your reference: (choose appropriate version)

https://cran.r-project.org/bin/windows/Rtools/
check the options as per link below (need to select all the check box while installation)

https://cloud.githubusercontent.com/assets/7400673/12230758/99fb2202-b8a6-11e5-82e6-836159440831.png

```<code>    # Adding a worksheets : parameters for addWorksheet are 1. Workbook Name 2. Sheet Name

    addWorksheet(wb, "Sheet 1")
    addWorksheet(wb, "Sheet 2")
    addWorksheet(wb, "Sheet 3")

    # Writing data in to respetive sheets: parameters for writeData are 1. Workbook Name 2. Sheet index/ sheet name 3. dataframe name

    writeData(wb, 1, x)

    # incase you would like to write sheet with filter available for ease of access you can pass the parameter withFilter = TRUE in writeData function.
    writeData(wb, 2, x = y, withFilter = TRUE)

    ## Similarly writeDataTable is another way for representing your data with table formatting:

    writeDataTable(wb, 3, z)

    saveWorkbook(wb, file = "Example.xlsx", overwrite = TRUE)

    end.time <- Sys.time()
    time.taken <- end.time - start.time
    time.taken
</code>```

openxlsx package is really good for reading and writing huge data from/ in excel files and has lots of options for custom formatting within excel.

The interesting fact is that we dont have to bother about java heap memory here.

Body:
I am surprised to find that there is no easy way to export multiple data.frame to multiple worksheets of an Excel file? I tried xlsx package, seems it can only write to one sheet (override old sheet); I also tried WriteXLS package, but it gives me error all the time...

My code structure is like this: by design, for each iteration, the output dataframe (tempTable) and the sheetName (sn) got updated and exported into one tab.

for (i in 2 : ncol(code)){
        ...
        tempTable <- ...
        sn <- ...
        WriteXLS("tempTable", ExcelFileName = "C:/R_code/../file.xlsx",
              SheetNames = sn);
}

I can export to several cvs files, but there has to be an easy way to do that in Excel, right?

Body:
Incase data size is small, R has many packages and functions which can be utilized as per your requirement.

write.xlsx, write.xlsx2, XLconnect also do the work but these are sometimes slow as compare to openxlsx.

So, if you are dealing with the large data sets and came across java errors. I would suggest to have a look of "openxlsx" which is really awesome and reduce the time to 1/12th.

I've tested all and finally i was really impressed with the performance of openxlsx capabilities.

Here are the steps for writing multiple datasets into multiple sheets.

 install.packages("openxlsx")
 library("openxlsx")

    start.time <- Sys.time()

    # Creating large data frame
    x <- as.data.frame(matrix(1:4000000,200000,20))
    y <- as.data.frame(matrix(1:4000000,200000,20))
    z <- as.data.frame(matrix(1:4000000,200000,20))

    # Creating a workbook
    wb <- createWorkbook("Example.xlsx")
    Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") ## path to zip.exe

Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") has to be static as it takes reference of some utility from Rtools.

Note: Incase Rtools is not installed on your system, please install it first for smooth experience. here is the link for your reference: (choose appropriate version)

https://cran.r-project.org/bin/windows/Rtools/
check the options as per link below (need to select all the check box while installation)

https://cloud.githubusercontent.com/assets/7400673/12230758/99fb2202-b8a6-11e5-82e6-836159440831.png

    # Adding a worksheets : parameters for addWorksheet are 1. Workbook Name 2. Sheet Name

    addWorksheet(wb, "Sheet 1")
    addWorksheet(wb, "Sheet 2")
    addWorksheet(wb, "Sheet 3")

    # Writing data in to respetive sheets: parameters for writeData are 1. Workbook Name 2. Sheet index/ sheet name 3. dataframe name

    writeData(wb, 1, x)

    # incase you would like to write sheet with filter available for ease of access you can pass the parameter withFilter = TRUE in writeData function.
    writeData(wb, 2, x = y, withFilter = TRUE)

    ## Similarly writeDataTable is another way for representing your data with table formatting:

    writeDataTable(wb, 3, z)

    saveWorkbook(wb, file = "Example.xlsx", overwrite = TRUE)

    end.time <- Sys.time()
    time.taken <- end.time - start.time
    time.taken

openxlsx package is really good for reading and writing huge data from/ in excel files and has lots of options for custom formatting within excel.

The interesting fact is that we dont have to bother about java heap memory here.


问:
List attributes of an object
Is there a way to grab a list of attributes that exist on instances of a class?

```<code>class new_class():
    def __init__(self, number):
        self.multi = int(number) * 2
        self.str = str(number)

a = new_class(2)
print(', '.join(a.SOMETHING))
</code>```

The desired result is that "multi, str" will be output.  I want this to see the current attributes from various parts of a script.

答:
Please see the python shell script which has been executed in sequence, here you will get the attributes of a class in string format separated by comma.

```<code>>>> class new_class():
...     def __init__(self, number):
...         self.multi = int(number)*2
...         self.str = str(number)
...
>>> a = new_class(4)
>>> ",".join(a.__dict__.keys())
'str,multi'<br/>
</code>```

I am using python 3.4

Title: List attributes of an object

Body:
Is there a way to grab a list of attributes that exist on instances of a class?

class new_class():
    def __init__(self, number):
        self.multi = int(number) * 2
        self.str = str(number)

a = new_class(2)
print(', '.join(a.SOMETHING))

The desired result is that "multi, str" will be output.  I want this to see the current attributes from various parts of a script.

LastEditorDisplayName: Roger Pate

Body:
Please see the python shell script which has been executed in sequence, here you will get the attributes of a class in string format separated by comma.

>>> class new_class():
...     def __init__(self, number):
...         self.multi = int(number)*2
...         self.str = str(number)
...
>>> a = new_class(4)
>>> ",".join(a.__dict__.keys())
'str,multi'<br/>

I am using python 3.4


问:
SSIS issue trying to change Flat File Source Error Output Column
I am having a problem trying to load data from a .CSV file to a SQL table using SSIS. In the Flat File Source, because my SQL columns in the table are data types nvarchar(max) I set all the DATA TYPES of my file source columns in the output columns to UNICODE text stream (DT_NTEXT) and after I did that I got the attached errors.  When I tried to change the Flat File Source Error Output Column I got this error:

Error at Data Flow Task [Flat File Source [1155]]: The data type for
  "Flat File Source.Outputs[Flat File Source Error Output]" cannot be
  modified in the error "Flat File Source.Outputs[Flat File Source Error
  Output].Columns[Flat File Source Error Output Column]".

Error at Data Flow Task [Flat File Source [1155]]: Attempt to set the
  data type properties on "Flat File Source" failed with error code
  0xC020400B. The error occurred while attempting to set one or more of
  the data type properties of the output column.

How do I fix this?  Any help/direction would be appreciated.

答: Instead of editing the datatype in the flat file source component, edit them in the flat file connection manager.  Go to the advanced tab, as shown below.  Once you have modified this, it would be easiest to recreate the flat file source component so it can pick up the new metadata.


问:
Extract particular value from column
How to better extract following:

I have following values in column:

```<code>\\v8pip1\90PI-200009-10.PV
</code>```

I need to get just below, \\v8pip1\ is the same for all rows:

```<code> 90PI-200009-10.PV
</code>```

thanks,
S

答:
For a more general solution using just standard string functions:

```<code>select substr(input_string, instr(input_string, '\', -1) + 1) as new_string
from   ...
</code>```

Stating the obvious, input_string is the input string. INSTR finds the position of the LAST occurrence of '\' in the input string (that is what the minus sign means in the last argument, -1). Then SUBSTR reads from that position + 1 to the end of the string.

Title: Extract particular value from column

Body:
How to better extract following:

I have following values in column:

\\v8pip1\90PI-200009-10.PV

I need to get just below, \\v8pip1\ is the same for all rows:

 90PI-200009-10.PV

thanks,
S

Body:
For a more general solution using just standard string functions:

select substr(input_string, instr(input_string, '\', -1) + 1) as new_string
from   ...

Stating the obvious, input_string is the input string. INSTR finds the position of the LAST occurrence of '\' in the input string (that is what the minus sign means in the last argument, -1). Then SUBSTR reads from that position + 1 to the end of the string.


问:
VBA Remove duplicates taking 30 minutes to run with no idea why
So the code below copies data from two columns in one sheet. Pastes these so that values are displayed in another sheet (because one column is a formula =Left(Column+1,4)) and then attempts to run a remove duplicates across the two columns that are pasted.

This takes roughly 30 minutes to run on what is essentially 100k cells (2 columns of 50k rows each).

This is what I've been using

```<code>Sub ProjTrending1()

Dim s1 As Worksheet, s2 As Worksheet
Dim St As Date, Et As Date
Dim Tt As Double

St = Time

Application.ScreenUpdating = False

'Defines S1 as a Worksheet
Set s1 = Sheets("All Data")

'Defines S2 as WorkSheet
Set s2 = Sheets("Workings")

'Defines LastR1
Dim LR1 As Long
Dim LR2 As Long

'Finds last row cell working sheet

LR2 = s1.Cells(Rows.Count, 10).End(xlUp).Row

'Takes Data from Order Column of defined data Sheet and copy & pastes it to Working Sheet Column B
s1.Range("J1:J" & LR2).Copy s2.Range("A1")

s1.Range("e1:e" & LR2).Copy

s2.Range("b1").PasteSpecial Paste:=xlPasteValues

LR1 = s2.Range("A1").CurrentRegion.Rows.Count

'Removes Duplicates from Column B Working sheet
s2.Range("A2:B" & LR1).RemoveDuplicates Columns:=Array(1, 2), Header:=xlNo

'Copies the formula from C2 and applies it to all cells in column C where column A has values (simple concatenate + countifs(B$2:B2,B2)
s2.Range("C2").Copy s2.Range("C2:C" & LR1)

Et = Time

Tt = (Et - St) * 24 * 60 * 60

MsgBox Timetaken

End Sub
</code>```

I've also tried using a dictionary to do this but I'm new to dictionaries so whilst the code looks good compared to my usual attempts its because its taken from a couple of different sources. (Copied and Pasted the data to sheet2 incase this overwrote the source data)

```<code>Sub M_delete_duplicates()
sn = Sheets("Sheet2").Cells(1).CurrentRegion.Resize(, 5)

With CreateObject("scripting.dictionary")
For j = 1 To UBound(sn)
.Item(sn(j, 1)) = Application.Index(sn, j, 0)
Next

Sheets("Sheet2").Cells(1, 4).Resize(.Count, UBound(sn, 2)) = Application.Index(.Items, 0, 0)
End With
</code>```

End Sub

This is as slow to run and it only does remove duplicates based on single column and I need it to operate on two columns. The potential way around this is to concatenate the two columns of data and run the remove duplicates once and then break the data using =right(Value,X)

If wanted to do it manually it takes 30 seconds max. It makes no sense to me as to why it takes so long to run.

Can anyone help with why this might be taking so long to run? and how I might modify the dictionary code to remove duplicates over two columns?

Thanks in advance

答:
Updated from my comment. This uses a dictionary to track which rows have been added and then copies unique rows across to the destination sheet. You may want to modify it a bit for your use (e.g. update sheet names) Always test this first on a copy of your data set or make a back up before running code

```<code>Option Explicit
Public Sub ExampleRemoveDuplicates()
    Dim dict As Object
    Dim temp As String
    Dim calc As String
    Dim headers As Variant
    Dim NoCol As Long, NoRow As Long, i As Long, j As Long
    Dim c, key

    With Application
        .ScreenUpdating = False
        calc = .Calculation
        .Calculation = xlCalculationManual
    End With

    Set dict = CreateObject("Scripting.Dictionary")
    ' Change this to the sheet that is applicable
    With Sheet1
        NoCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        ' Assumes first row of sheet is headers
        headers = .Range(.Cells(1, 1), .Cells(1, NoCol)).Value2
        ' Change this to destination sheet
        With Sheet2
            .Cells.Clear
            .Range(.Cells(1, 1), .Cells(1, NoCol)).Value2 = headers
        End With
        For Each c In .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
            ReDim arr(1 To NoCol)
            j = 1
            Do
                arr(j) = c.Offset(0, j - 1).Value2
                j = j + 1
            Loop Until j = NoCol + 1
            temp = Join(arr, "//")
            If Not dict.exists(temp) And Not temp = vbNullString Then
                dict.Add key:=temp, Item:=arr
                ' Change this to destination sheet
                With Sheet2
                    NoRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
                    .Range(.Cells(NoRow, 1), .Cells(NoRow, NoCol)).Value2 = arr
                End With
            End If
        Next c
    End With
    i = 1

    ReDim Results(1 To dict.Count, 1 To NoCol)
    For Each key In dict.keys
        For j = 1 To NoCol
            Results(i, j) = dict(key)(j)
        Next j
        i = i + 1
    Next key

    ' Change this to destination sheet
    With Sheet2.Cells(1, 1)
        .Range(.Offset(1, 0), .Offset(dict.Count, NoCol - 1)) = Results
    End With

    With Application
        .Calculation = calc
        .ScreenUpdating = True
    End With
End Sub
</code>```

Body:
So the code below copies data from two columns in one sheet. Pastes these so that values are displayed in another sheet (because one column is a formula =Left(Column+1,4)) and then attempts to run a remove duplicates across the two columns that are pasted.

This takes roughly 30 minutes to run on what is essentially 100k cells (2 columns of 50k rows each).

This is what I've been using

Sub ProjTrending1()

Dim s1 As Worksheet, s2 As Worksheet
Dim St As Date, Et As Date
Dim Tt As Double

St = Time

Application.ScreenUpdating = False

'Defines S1 as a Worksheet
Set s1 = Sheets("All Data")

'Defines S2 as WorkSheet
Set s2 = Sheets("Workings")

'Defines LastR1
Dim LR1 As Long
Dim LR2 As Long

'Finds last row cell working sheet

LR2 = s1.Cells(Rows.Count, 10).End(xlUp).Row

'Takes Data from Order Column of defined data Sheet and copy & pastes it to Working Sheet Column B
s1.Range("J1:J" & LR2).Copy s2.Range("A1")

s1.Range("e1:e" & LR2).Copy

s2.Range("b1").PasteSpecial Paste:=xlPasteValues

LR1 = s2.Range("A1").CurrentRegion.Rows.Count

'Removes Duplicates from Column B Working sheet
s2.Range("A2:B" & LR1).RemoveDuplicates Columns:=Array(1, 2), Header:=xlNo

'Copies the formula from C2 and applies it to all cells in column C where column A has values (simple concatenate + countifs(B$2:B2,B2)
s2.Range("C2").Copy s2.Range("C2:C" & LR1)

Et = Time

Tt = (Et - St) * 24 * 60 * 60

MsgBox Timetaken

End Sub

I've also tried using a dictionary to do this but I'm new to dictionaries so whilst the code looks good compared to my usual attempts its because its taken from a couple of different sources. (Copied and Pasted the data to sheet2 incase this overwrote the source data)

Sub M_delete_duplicates()
sn = Sheets("Sheet2").Cells(1).CurrentRegion.Resize(, 5)

With CreateObject("scripting.dictionary")
For j = 1 To UBound(sn)
.Item(sn(j, 1)) = Application.Index(sn, j, 0)
Next

Sheets("Sheet2").Cells(1, 4).Resize(.Count, UBound(sn, 2)) = Application.Index(.Items, 0, 0)
End With

End Sub

This is as slow to run and it only does remove duplicates based on single column and I need it to operate on two columns. The potential way around this is to concatenate the two columns of data and run the remove duplicates once and then break the data using =right(Value,X)

If wanted to do it manually it takes 30 seconds max. It makes no sense to me as to why it takes so long to run.

Can anyone help with why this might be taking so long to run? and how I might modify the dictionary code to remove duplicates over two columns?

Thanks in advance

Body:
Updated from my comment. This uses a dictionary to track which rows have been added and then copies unique rows across to the destination sheet. You may want to modify it a bit for your use (e.g. update sheet names) Always test this first on a copy of your data set or make a back up before running code

Option Explicit
Public Sub ExampleRemoveDuplicates()
    Dim dict As Object
    Dim temp As String
    Dim calc As String
    Dim headers As Variant
    Dim NoCol As Long, NoRow As Long, i As Long, j As Long
    Dim c, key

    With Application
        .ScreenUpdating = False
        calc = .Calculation
        .Calculation = xlCalculationManual
    End With

    Set dict = CreateObject("Scripting.Dictionary")
    ' Change this to the sheet that is applicable
    With Sheet1
        NoCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        ' Assumes first row of sheet is headers
        headers = .Range(.Cells(1, 1), .Cells(1, NoCol)).Value2
        ' Change this to destination sheet
        With Sheet2
            .Cells.Clear
            .Range(.Cells(1, 1), .Cells(1, NoCol)).Value2 = headers
        End With
        For Each c In .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
            ReDim arr(1 To NoCol)
            j = 1
            Do
                arr(j) = c.Offset(0, j - 1).Value2
                j = j + 1
            Loop Until j = NoCol + 1
            temp = Join(arr, "//")
            If Not dict.exists(temp) And Not temp = vbNullString Then
                dict.Add key:=temp, Item:=arr
                ' Change this to destination sheet
                With Sheet2
                    NoRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
                    .Range(.Cells(NoRow, 1), .Cells(NoRow, NoCol)).Value2 = arr
                End With
            End If
        Next c
    End With
    i = 1

    ReDim Results(1 To dict.Count, 1 To NoCol)
    For Each key In dict.keys
        For j = 1 To NoCol
            Results(i, j) = dict(key)(j)
        Next j
        i = i + 1
    Next key

    ' Change this to destination sheet
    With Sheet2.Cells(1, 1)
        .Range(.Offset(1, 0), .Offset(dict.Count, NoCol - 1)) = Results
    End With

    With Application
        .Calculation = calc
        .ScreenUpdating = True
    End With
End Sub


问:
How to set up Automapper in ASP.NET Core
I'm relatively new at .NET, and I decided to tackle .NET Core instead of learning the "old ways". I found a detailed article about setting up AutoMapper for .NET Core here, but is there a more simple walkthrough for a newbie?</p>

答:
theutz' answer here is very good, I just want to add this:

If you let your mapping profile inherit from MapperConfigurationExpression instead of Profile, you can very simply add a test to verify your mapping setup, which is always handy:

```<code>[Fact]
public void MappingProfile_VerifyMappings()
{
    var mappingProfile = new MappingProfile();

    var config = new MapperConfiguration(mappingProfile);
    var mapper = new Mapper(config);

    (mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}
</code>```

Body:
theutz' answer here is very good, I just want to add this:

If you let your mapping profile inherit from MapperConfigurationExpression instead of Profile, you can very simply add a test to verify your mapping setup, which is always handy:

[Fact]
public void MappingProfile_VerifyMappings()
{
    var mappingProfile = new MappingProfile();

    var config = new MapperConfiguration(mappingProfile);
    var mapper = new Mapper(config);

    (mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}


问:
How to hide/disable only the first uinavigationbar?
I've been wandering how to hide / remove / disable only the main or first navigation bar in the navigation controller so that I could put an image as a whole background screen but I couldn't find any solution.

Did try hide the titleview in viewdidLoad of the main navigation controller but didn't work. Tried using navigationBarHidden but it hides the whole navigation bar for the next stack of controller.

So, I'm not sure how to do this. To give you an example, I would like to have something like this app - The Masters Golf Tournament - http://appshopper.com/sports/the-masters-golf-tournament.

If you look at Screen 1, it doesn't have any nav bar at the top but when you touch any options it will push to a new view controller and have the nav bar appear as in Screen 3,4 and 5.

Hope anyone could help me with this.Thanks a lot!

答:
You can hide navigation bar by using bellow code. Below code will hide navigationbar at the time of viewWillAppear.

Objective C

```<code>-(void)viewWillAppear:(BOOL)animated
 {
        [[self navigationController] setNavigationBarHidden:YES animated:NO];
 }
</code>```

Swift

```<code>self.navigationController?.setNavigationBarHidden(true, animated: animated)
</code>```

Body:
You can hide navigation bar by using bellow code. Below code will hide navigationbar at the time of viewWillAppear.

Objective C

-(void)viewWillAppear:(BOOL)animated
 {
        [[self navigationController] setNavigationBarHidden:YES animated:NO];
 }

Swift

self.navigationController?.setNavigationBarHidden(true, animated: animated)