问:
BlazeDS and Flash Builder, Inheritance generation problem
I have a server with some simple java objects running. I want to build the client with Flex and connect to the server data with BlazeDS. The problem is the Flash Builder is not generating the Classes correctly. Just the properties are being generated, the inheritance are not being generates.

Is it a limitation or something is wrong in my code?

答: AFAIK inheritance is not supported in Flash Builder / Fiber. We ran into the same problem on a current project and ended up writing a custom code generator ourselves. If time permits, I would suggest to do the same, as you'll have complete control over the generation process.</p>


来源: stackexchange

问:
Enable and disable onkeydown event?
Hi I am trying to start off with the keys enable and then once a button is clicked to disable the event this so far works fine, then once the close button is pressed I want to enable the event again this part doesn't work I'd like to solve this using javascript if possible my close button is in another html (project1.html) file and is loaded via Ajax here is my code:

```<code>var enable_keydown = document.onkeydown;

$(".open-project").click(function(){
document.onkeydown = null;
});

$("#project_close").click(function(){
document.onkeydown = enable_keydown;
});

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
             $.fn.fullpage.moveSectionUp();
            break;
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
             $.fn.fullpage.moveSectionDown();
            break;
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
    }
};
</code>```

Kind Regards

答:
You can use a flag variable or use bind and unbind functions.

Also checkout this question :

bind and unbind event in jquery

ContentLicense: CC BY-SA 3.0

Title: Enable and disable onkeydown event?

Body:
Hi I am trying to start off with the keys enable and then once a button is clicked to disable the event this so far works fine, then once the close button is pressed I want to enable the event again this part doesn't work I'd like to solve this using javascript if possible my close button is in another html (project1.html) file and is loaded via Ajax here is my code:

var enable_keydown = document.onkeydown;

$(".open-project").click(function(){
document.onkeydown = null;
});

$("#project_close").click(function(){
document.onkeydown = enable_keydown;
});

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
             $.fn.fullpage.moveSectionUp();
            break;
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
             $.fn.fullpage.moveSectionDown();
            break;
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
    }
};

Kind Regards


问:
windows directory contents being "." and ".."
I'm trying to search through the contents of a directory. Inside of the directory is other directories, which should always be in the same order. When I make an array of the directory contents, I have to reserve the first two spots for "." and "..". Can anyone tell me why this is?

And is this present on mac as well? My script won't run properly on mac because the array isn't lining up with where the directories should be. I think its because these "." and ".." spots don't exist on mac or something. I'm just looking for some answers. Not sure if it will help, but here is my code.

```<code>print "Enter the SMD day folder to generate summary. (Ex: a folder named 06132017)\n";
chomp($smddirectory = <STDIN>);
print "\n";
print "Output will be in the SGE folder.\n";
opendir ($DIR, $smddirectory) ;
my @directories = readdir $DIR;
closedir $DIR;

@directories = map{$smddirectory . '/' . $_} @directories;

$mydir = @directories[14];
$mydirs = @directories[2];
$mydirb = @directories[3];
$mydirbs = @directories[4];
$mydirc = @directories[5];
$mydircs = @directories[6];
$JSHDirectory = @directories[7];
$JSHsDirectory = @directories[8];
$JSHBDirectory = @directories[9];
$JSHBsDirectory = @directories[10];
$JSHCDirectory = @directories[11];
$JSHCsDirectory = @directories[12];
$SGEDirectory = @directories[13];
</code>```

答:
Linux/Unix systems have the same convention, as do newer Macs (from what I'm aware, I don't use one).

One way to get around this issue on all systems by using grep.

Put the following line right above your map line.

```<code>@directories = grep{$_ !~ /^\.{1,2}$/} @directories;
</code>```

What that will do is rebuild the @directories array after removing all entries that are either . or ...

If you're on a system that doesn't list the . or .. directories, the grep line won't do anything.

After that, you can re-index your array back to 0 and it'll work across all of your platforms.

Body:
I'm trying to search through the contents of a directory. Inside of the directory is other directories, which should always be in the same order. When I make an array of the directory contents, I have to reserve the first two spots for "." and "..". Can anyone tell me why this is?

And is this present on mac as well? My script won't run properly on mac because the array isn't lining up with where the directories should be. I think its because these "." and ".." spots don't exist on mac or something. I'm just looking for some answers. Not sure if it will help, but here is my code.

print "Enter the SMD day folder to generate summary. (Ex: a folder named 06132017)\n";
chomp($smddirectory = <STDIN>);
print "\n";
print "Output will be in the SGE folder.\n";
opendir ($DIR, $smddirectory) ;
my @directories = readdir $DIR;
closedir $DIR;

@directories = map{$smddirectory . '/' . $_} @directories;

$mydir = @directories[14];
$mydirs = @directories[2];
$mydirb = @directories[3];
$mydirbs = @directories[4];
$mydirc = @directories[5];
$mydircs = @directories[6];
$JSHDirectory = @directories[7];
$JSHsDirectory = @directories[8];
$JSHBDirectory = @directories[9];
$JSHBsDirectory = @directories[10];
$JSHCDirectory = @directories[11];
$JSHCsDirectory = @directories[12];
$SGEDirectory = @directories[13];

Body:
Linux/Unix systems have the same convention, as do newer Macs (from what I'm aware, I don't use one).

One way to get around this issue on all systems by using grep.

Put the following line right above your map line.

@directories = grep{$_ !~ /^\.{1,2}$/} @directories;

What that will do is rebuild the @directories array after removing all entries that are either . or ...

If you're on a system that doesn't list the . or .. directories, the grep line won't do anything.

After that, you can re-index your array back to 0 and it'll work across all of your platforms.


问:
Piping output with SBT ProcessCommand
I'm trying to write an SBT task which stops a java application process called wiremock.

```<code>  lazy val `stop-wiremock` = taskKey[Unit]("Stop the wiremock server")
  lazy val stopWireMockTask = `stop-wiremock` in Performance := {
    "kill $(ps ux | grep [w]iremock | awk '{print $2}')".!
  }
</code>```

Unfortunately this results in the output:

```<code>> stop-wiremock
kill: illegal process id: $(ps
kill: illegal process id: ux
kill: illegal process id: |
kill: illegal process id: grep
kill: illegal process id: [w]iremock
kill: illegal process id: |
kill: illegal process id: awk
kill: illegal process id: '{print
kill: illegal process id: $2}')
</code>```

I don't know what the process builder is doing behind the scenes here but this doesn't work and the documentation tells me to use operators when building my command so I tried the following:

```<code>  lazy val `get-wiremock-pid` = taskKey[Unit]("Stop the wiremock server")
  lazy val getWiremockPidTask = `get-wiremock-pid` in Performance := {
    "ps ux" #| "grep [w]iremock" #| "awk '{print $2}'" !
  }
</code>```

Now the error is:

```<code>> get-wiremock-pid
awk: syntax error at source line 1
 context is
     >>> ' <<<
    missing }
awk: bailing out at source line 1
</code>```

I suspect this is because the process builder has split the arguments to awk on the whitespace so it's only receiving awk '{print but I don't know how to rectify this.

Can anyone help me do this using the ProcessBuilder operators or even suggest a way I can just run the full command? Thank you very much.

答:
We can create Process from a sequence of string where first string is the command and remaining strings are parameters. For your case it will be</p>

```<code>("ps ux" #| "grep [w]iremock" #|  Process(Seq("awk", "{print $2}"))) !
</code>```

Title: Piping output with SBT ProcessCommand

Body:
I'm trying to write an SBT task which stops a java application process called wiremock.

  lazy val `stop-wiremock` = taskKey[Unit]("Stop the wiremock server")
  lazy val stopWireMockTask = `stop-wiremock` in Performance := {
    "kill $(ps ux | grep [w]iremock | awk '{print $2}')".!
  }

Unfortunately this results in the output:

> stop-wiremock
kill: illegal process id: $(ps
kill: illegal process id: ux
kill: illegal process id: |
kill: illegal process id: grep
kill: illegal process id: [w]iremock
kill: illegal process id: |
kill: illegal process id: awk
kill: illegal process id: '{print
kill: illegal process id: $2}')

I don't know what the process builder is doing behind the scenes here but this doesn't work and the documentation tells me to use operators when building my command so I tried the following:

  lazy val `get-wiremock-pid` = taskKey[Unit]("Stop the wiremock server")
  lazy val getWiremockPidTask = `get-wiremock-pid` in Performance := {
    "ps ux" #| "grep [w]iremock" #| "awk '{print $2}'" !
  }

Now the error is:

> get-wiremock-pid
awk: syntax error at source line 1
 context is
     >>> ' <<<
    missing }
awk: bailing out at source line 1

I suspect this is because the process builder has split the arguments to awk on the whitespace so it's only receiving awk '{print but I don't know how to rectify this.

Can anyone help me do this using the ProcessBuilder operators or even suggest a way I can just run the full command? Thank you very much.

Body:
We can create Process from a sequence of string where first string is the command and remaining strings are parameters. For your case it will be

("ps ux" #| "grep [w]iremock" #|  Process(Seq("awk", "{print $2}"))) !


问:
Braintree for rails
I want to show the price of a plan I created in Braintree. I'm trying to retrieve the details via the the Braintree api by using this: Braintree::Plan.price

```<code><%= form_tag transactions_path do%>
  <div id="dropin"></div>
  <%=submit_tag "Pay #{Braintree::Plan.price}$", class: "button mt1" %>
</code>```

But I'm getting this error:
undefined method price' for Braintree::Plan:Class

Does someone know how to implement this?

答:
One way would be to find the Braintree::Subscription by the subscription_id (if you have one) and then get price from there.

```<code>Braintree::Subscription.find("a_subscription_id").price
</code>```

Or, you can search for Braintree::Subscription by a plan_id and then get the price.

```<code>Braintree::Subscription.search do |search|
  search.plan_id.is "the_plan_id"
end.first.price
</code>```

Both of these examples are taken from Braintree API Documentation for Subscription

It would be nice to retrieve a plan using something like: Braintree::Plan.retrieve(plan_id) and then get the price of the plan directly from there. But, unfortunately, I don't see that option in their API Documentation for Plan.

To get the price of the latest plan:

```<code>Braintree::Plan.last.price
</code>```

Title: Braintree for rails

Body:
I want to show the price of a plan I created in Braintree. I'm trying to retrieve the details via the the Braintree api by using this: Braintree::Plan.price

<%= form_tag transactions_path do%>

  <%=submit_tag "Pay #{Braintree::Plan.price}$", class: "button mt1" %>

But I'm getting this error:
undefined method price' for Braintree::Plan:Class

Does someone know how to implement this?

Body:
One way would be to find the Braintree::Subscription by the subscription_id (if you have one) and then get price from there.

Braintree::Subscription.find("a_subscription_id").price

Or, you can search for Braintree::Subscription by a plan_id and then get the price.

Braintree::Subscription.search do |search|
  search.plan_id.is "the_plan_id"
end.first.price

Both of these examples are taken from Braintree API Documentation for Subscription

It would be nice to retrieve a plan using something like: Braintree::Plan.retrieve(plan_id) and then get the price of the plan directly from there. But, unfortunately, I don't see that option in their API Documentation for Plan.

To get the price of the latest plan:

Braintree::Plan.last.price


问:
Trouble backing up Outlook .OST Files
I need to copy .ost file when Outlook is open.

I found here:

https://support.jungledisk.com/hc/en-us/articles/200812964-Trouble-backing-up-Outlook-OST-Files

Microsoft explanation of this design decision:
Maintaining changes to .ost files within shadow copies is expensive in terms of space and I/O activity. The performance impact doesn’t occur during the image backup itself--the only extra work at backup time is backing up the .ost file as part of the image. Instead, the performance impact occurs during the ongoing, everyday I/O to the .ost file when Outlook is running. If the .ost changes were kept in shadow copies, then every time Outlook writes to the .ost file, the result is a copy-on-write I/O hit (2 writes, 1 read). Although we have worked to reduce the impact of copy-on-writes on shadow copies,  a heavily churned file like an .ost file could still cause problems. For these reasons, and the fact that .ost files can be regenerated, we chose to delete .ost files from the shadow copy before the image is created.
Even if the performance issues didn’t exist, there are situations where Exchange will, after an .ost is restored, detect a “future” version of the .ost file and force you to delete and then regenerate the local .ost file. Therefore, it’s still preferable to regenerate an .ost file instead of restoring it.

So, I can't create shadow copy of .OST file and I can't copy it. What should I do?

答: That really depends on why you need to create a copy of an OST file. It can never be used standalone - it is only useable in the profile used to create it. It cannot be copied to another machine, and it cannot be used in a differ profile on the same machine. MSEMS provider recreates the OST file if it is missing. This is by design.

Title: Trouble backing up Outlook .OST Files


问:
How to convert the results from a query in to a JSON in oracle 12c?
Trying to update a new column with JSON,
i need to convert the selected data in to JSON first.

Here is my code (updated from comment):

```<code>SELECT a.col1 a.col2 b.col3 b.col4
from table AS JSON
</code>```

and I want my output to look like:

[{"col1": "value1", "col2": 2}, {"col3": "value3", "col4": "value4"}]

答:
Working solution for Oracle 12.2.0.1.0 is shown here

https://livesql.oracle.com/apex/livesql/file/content_E8F0DRCAGJJFKAMGK4AB6T2PG.html

Body:
Trying to update a new column with JSON,
i need to convert the selected data in to JSON first.

Here is my code (updated from comment):

SELECT a.col1 a.col2 b.col3 b.col4
from table AS JSON

and I want my output to look like:

[{"col1": "value1", "col2": 2}, {"col3": "value3", "col4": "value4"}]


问:
Max31865 on Raspberry Pi setup
I'm pretty new to coding.  I'm trying to read a PT100 rtd via my Raspberry Pi 3.  I read that I needed the Max31865 RTD amplifier to properly read the data because the resistances are so small.  I am fairly certain I have it plugged in correctly.
 I'm using this code, only slightly editted.
 https://github.com/steve71/MAX31865

I'm getting two different outputs so far but it doesn't seem to correlate with anything I'm changing (The byte associated with the readTemp mostly) since I've run the same code twice and gotten both outputs.  The outputs are as follows:

```<code>config register byte: ff
RTD ADC Code: 32767
PT100 Resistance: 429.986877 ohms
Straight Line Approx. Temp: 767.968750 degC
Callendar-Van Dusen Temp (degC > 0): 988.792111 degC
high fault threshold: 32767
low fault threshold: 32767
</code>```

and

```<code>config register byte: 08
RTD ADC Code: 0
PT100 Resistance: 0.000000 ohms
Straight Line Approx. Temp: -256.000000 degC
Callendar-Van Dusen Temp (degC > 0): -246.861024 degC
high fault threshold: 0
low fault threshold: 0
</code>```

Any help would be appreciated.

答:
I'am dealing exactly with the same issue right now. Do you use your Pt100 with 3- or 4-wires?

I fixed the problem by setting the correct configuration status register in Line 78 of the original code (https://github.com/steve71/MAX31865) to 0xA2

```<code>self.writeRegister(0, 0xA2)
</code>```

I am using 4-wires, so i had to change bit4 from 1 (3-wires) to 0 (2- or 4-wires)

```<code>0xb10100010
</code>```

After this, i've got this as output

```<code>config register byte: 80
RTD ADC Code: 8333
PT100 Resistance: 101.721191 ohms
Straight Line Approx. Temp: 4.406250 degC
Callendar-Van Dusen Temp (degC > 0): 4.406808 degC
high fault threshold: 32767
low fault threshold: 0
</code>```

Brrr... it's very cold in my room, isn't it? To fix this, i had to change the reference resistance in Line 170 to 430 Ohm

```<code>R_REF = 430.0 # Reference Resistor
</code>```

It's curious, because i red a lot of times, there is a 400 Ohm resistance mounted on this devices as the reference. Indeed, on the SMD resistor is a 3-digit Code "431" which means 430 Ohm. Humm...

But now i have it nice and warm in here

```<code>Callendar-Van Dusen Temp (degC > 0): 25.091629 degC
</code>```

Best regards

Title: Max31865 on Raspberry Pi setup

Body:
I'm pretty new to coding.  I'm trying to read a PT100 rtd via my Raspberry Pi 3.  I read that I needed the Max31865 RTD amplifier to properly read the data because the resistances are so small.  I am fairly certain I have it plugged in correctly.
 I'm using this code, only slightly editted.
 https://github.com/steve71/MAX31865

I'm getting two different outputs so far but it doesn't seem to correlate with anything I'm changing (The byte associated with the readTemp mostly) since I've run the same code twice and gotten both outputs.  The outputs are as follows:

config register byte: ff
RTD ADC Code: 32767
PT100 Resistance: 429.986877 ohms
Straight Line Approx. Temp: 767.968750 degC
Callendar-Van Dusen Temp (degC > 0): 988.792111 degC
high fault threshold: 32767
low fault threshold: 32767

and

config register byte: 08
RTD ADC Code: 0
PT100 Resistance: 0.000000 ohms
Straight Line Approx. Temp: -256.000000 degC
Callendar-Van Dusen Temp (degC > 0): -246.861024 degC
high fault threshold: 0
low fault threshold: 0

Any help would be appreciated.

Body:
I'am dealing exactly with the same issue right now. Do you use your Pt100 with 3- or 4-wires?

I fixed the problem by setting the correct configuration status register in Line 78 of the original code (https://github.com/steve71/MAX31865) to 0xA2

self.writeRegister(0, 0xA2)

I am using 4-wires, so i had to change bit4 from 1 (3-wires) to 0 (2- or 4-wires)

0xb10100010

After this, i've got this as output

config register byte: 80
RTD ADC Code: 8333
PT100 Resistance: 101.721191 ohms
Straight Line Approx. Temp: 4.406250 degC
Callendar-Van Dusen Temp (degC > 0): 4.406808 degC
high fault threshold: 32767
low fault threshold: 0

Brrr... it's very cold in my room, isn't it? To fix this, i had to change the reference resistance in Line 170 to 430 Ohm

R_REF = 430.0 # Reference Resistor

It's curious, because i red a lot of times, there is a 400 Ohm resistance mounted on this devices as the reference. Indeed, on the SMD resistor is a 3-digit Code "431" which means 430 Ohm. Humm...

But now i have it nice and warm in here

Callendar-Van Dusen Temp (degC > 0): 25.091629 degC

Best regards


问:
Read-only Django object manager?
I am doing agressive caching and I'd like to make sure that nobody accidentally writes code that updates the database directly. I would imagine that the way to solve this would be to rename the normal object manager .rw_objects for the caches use, and replace .objects with a manager that logs a warning on a non-updating access and throws an exception if someone tries to do an update from it.

I've written an object manager and a query set but I'm not sure how to go about checking whether a query is updating the database.

Any suggestions?

答:
I'm thinking about two approaches here.

Create a custom Manager, override _insert(), _update() to raise exception / log the query, and get_query_set() to return custom QuerySet that overrides create(), get_or_create(), and update().

If you're using django 1.2, Create another database connection in settings.py call it "READ_ONLY", and create a custom manager that returns QuerSet using that connection (like def get_query_set() return super(ReadOnlyManager, self).get_query_set().using("READ_ONLY"), and mark the connection read-only. (One way to do it is create read-only user for the database connection "READ_ONLY".... If you're using Postgres, you can do stuff like How do you create a read-only user in PostgreSQL?)

ContentLicense: CC BY-SA 2.5

Title: Read-only Django object manager?


问:
Efficient VBA code for conditionally deleting rows in big excel sheet
My excel sheet has 40 columns and more than 1,00,000 rows. I want to delete all the rows which contain cell with a string "NA" in any of the columns. I am struggling to find an efficient VB code for this, which doesn't cause excel to crash.
My current VBA code (explained below) takes forever to run (>5 mins on Intel Xenon and 16 GB RAM) and crashes on slower machines (i5, 4 GB RAM). Any suggestions to streamline and make it faster?

P.S. Exact number of rows and columns are not known apriori. And, I'm new to VBA, any help would be greatly appreciated.

Link to the concerned file - https://drive.google.com/file/d/0Bzl56SYDK-iRdTE1LTlYZGsxSE0/view?usp=sharing

My VBA code:

```<code>Sub DeleteRowWithContents()

'Finds the last non-blank cell on a sheet/range.

Dim lRow As Long
Dim lCol As Long

    lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

    lCol = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Column

        'MsgBox "Last Row: " & lRow
        'MsgBox "Last Column: " & lCol

     For j = lCol To 1 Step -1
     For i = lRow To 1 Step -1
        If (Cells(i, j).Value) = "NA" Then
            Cells(i, "A").EntireRow.Delete
        End If
    Next i
    lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row
    Next j

End Sub
</code>```

答: My suggestion would be to 1. create an additional column and get the macro to write an "NA" into it, whenever "NA" is found wihthin the row and the line number else. 2. Sort the table using that column and delete all "NA" rows as block. 3. Resort the table using the row numbers and 4. delete the extra column.</p>

Body:
My excel sheet has 40 columns and more than 1,00,000 rows. I want to delete all the rows which contain cell with a string "NA" in any of the columns. I am struggling to find an efficient VB code for this, which doesn't cause excel to crash.
My current VBA code (explained below) takes forever to run (>5 mins on Intel Xenon and 16 GB RAM) and crashes on slower machines (i5, 4 GB RAM). Any suggestions to streamline and make it faster?

P.S. Exact number of rows and columns are not known apriori. And, I'm new to VBA, any help would be greatly appreciated.

Link to the concerned file - https://drive.google.com/file/d/0Bzl56SYDK-iRdTE1LTlYZGsxSE0/view?usp=sharing

My VBA code:

Sub DeleteRowWithContents()

'Finds the last non-blank cell on a sheet/range.

Dim lRow As Long
Dim lCol As Long

    lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

    lCol = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Column

        'MsgBox "Last Row: " & lRow
        'MsgBox "Last Column: " & lCol

     For j = lCol To 1 Step -1
     For i = lRow To 1 Step -1
        If (Cells(i, j).Value) = "NA" Then
            Cells(i, "A").EntireRow.Delete
        End If
    Next i
    lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row
    Next j

End Sub


问:
Create ETL process in SSIS
Suppose I've data from different sources. For example, MS SQL and Oracle. And these data are connected. And data from different sources should be loaded into 1 table. What are the ways in the SSIS to do this?</p>

答:
One way to do it is to use the Merge Join.

It allows to access data from two or more heterogeneous sources and join them by a common column/field (one or more of them).

The Merge Join will form a unified data stream which will be possible to direct to a single point of destination as a database table.

Good Luck!

Title: Create ETL process in SSIS


问:
Javascript nested array and setting the variable
```<code>for (i = 0; i < length1; i++) {
  for (j = 0; j < length2; j++) {
    for (k = j; k < length2; k++) {}
  }
}
</code>```

I just wondered... in the last loop where I initialize k to be equal to j, would it cause problems for me later on?

I'm assuming every time j increments by 1, k is set to the new value of j and then increments up to length2

答: You are correct that for each iteration of the j-for-loop, the innermost loop will begin at J's current value and iterate up to length2-1.  If this is what you want, shouldn't be a problem.</p>

Body:
for (i = 0; i < length1; i++) {
  for (j = 0; j < length2; j++) {
    for (k = j; k < length2; k++) {}
  }
}

I just wondered... in the last loop where I initialize k to be equal to j, would it cause problems for me later on?

I'm assuming every time j increments by 1, k is set to the new value of j and then increments up to length2


问:
org.xml.sax.SAXParseException: Open quote is expected for attribute "component" associated with an element type "Route"
I am developing a React.js +Spring boot app and I am getting this error -

"org.xml.sax.SAXParseException: Open quote is expected for attribute
component" associated with an  element type  "Route".

here is the piece of code which is giving me problem -

```<code>ReactDOM.render(
  <Router>
        <Route path="/" component={App}>
            <IndexRoute component={Home}/>
            <Route path="stuff" component={Stuff} />
             <Route path="contact" component={Contact} />
        </Route>
 </Router>,  Destination
);
</code>```

答:
You have full description of error. You use SAX parser to parse react code. component={App} this is not valid XML . All attributes should be in quotes in XML.

To help you need to know what you whant at the end of the day.

Body:
I am developing a React.js +Spring boot app and I am getting this error -

"org.xml.sax.SAXParseException: Open quote is expected for attribute
component" associated with an  element type  "Route".

here is the piece of code which is giving me problem -

ReactDOM.render(
  <Router>
        <Route path="/" component={App}>
            <IndexRoute component={Home}/>
            <Route path="stuff" component={Stuff} />
             <Route path="contact" component={Contact} />
        </Route>
 </Router>,  Destination
);


问:
How would you separate a list into sublists of all the duplicates in the original?
```<code>l = [a, a, a, b, b, c]

desired1 = [a, a, a]

desired2 = [b, b]

desired3 = [c]
</code>```

desired could also be a list of all the lists above.

答:
an easy way is to use a dict

```<code>dict = {}
for thing in list:
  dict[thing] += 1

list = []
for key in dict:
  curr_list = []
  for i in range(dict[key]):
    curr_list.append(key)
  list.append(curr_list)
</code>```

Body:
l = [a, a, a, b, b, c]

desired1 = [a, a, a]

desired2 = [b, b]

desired3 = [c]

desired could also be a list of all the lists above.

Body:
an easy way is to use a dict

dict = {}
for thing in list:
  dict[thing] += 1

list = []
for key in dict:
  curr_list = []
  for i in range(dict[key]):
    curr_list.append(key)
  list.append(curr_list)


问:
Yahoo web mail is stripping out certain inline email styles
Yahoo web mail (mail.yahoo.com) is stripping out these inline styles, but keeping things like color and padding.

```<code>text-decoration
font-size
border-radius
text-align
font-family
</code>```

Any idea why these are purposely being removed?

Example:

```<code><span style="font-size:30px;">Hello</span>
</code>```

becomes:

```<code><span style>Hello</span>
</code>```

答:
What can be done?

This is the difficult part because options are few. Even with free market choices well established corporate entities have little to no business reasons to improve their products unless competition comes along. You could always attempt to file a bug report (like, where if even any where though...) and as usual wait decades for a(n intelligent) response (*cough* Mozilla *cough*). You could attempt to work around the issue (replace width with min-width in example). I've noticed that font-size: 120%; works just fine so consider what unit values you're using for testing.

You can make a different though, even if it's relatively small. I was wronged by a motherboard manufacturer in the mid-2000s and since then they've lost tens of thousands of dollars of sales because of me directly and who knows how much more based on the video I posted back then and that is just in the past ten years. The issue with Yahoo is different, at best all you can do is write a blog entry and link to other people talking about the issue to raise awareness. You could go so far as to disallow registrations from users with Yahoo accounts or greatly discourage users from using Yahoo accounts though that could lead to a loss of members so I wouldn't do something like that unless you've got something people really want. The state of HTML email in general is exceptionally sad at this point though most (at least technical users) typically have multiple email addresses.

You could always use  even though scoped CSS is not widely supported in 2017 except for Gecko/Firefox though it did seem to fix some of the issues for me that you mentioned you were having.

Lastly you can always provide a "view this email on our website" option; I see it all the time because HTML email is still a disaster (2017). I've even seen nonsense with developers sending email with html element (uh, it's not an entire page, it will be embedded, but you know, whatever...).

So try utilizing different unit values and even the contexts themselves. Inline-styling is the way to go and if that fails provide a website version of the email (with security considerations for email with sensitive data).

Body:
Yahoo web mail (mail.yahoo.com) is stripping out these inline styles, but keeping things like color and padding.

text-decoration
font-size
border-radius
text-align
font-family

Any idea why these are purposely being removed?

Example:

Hello

becomes:

Hello

Body:
What can be done?

This is the difficult part because options are few. Even with free market choices well established corporate entities have little to no business reasons to improve their products unless competition comes along. You could always attempt to file a bug report (like, where if even any where though...) and as usual wait decades for a(n intelligent) response (*cough* Mozilla *cough*). You could attempt to work around the issue (replace width with min-width in example). I've noticed that font-size: 120%; works just fine so consider what unit values you're using for testing.

You can make a different though, even if it's relatively small. I was wronged by a motherboard manufacturer in the mid-2000s and since then they've lost tens of thousands of dollars of sales because of me directly and who knows how much more based on the video I posted back then and that is just in the past ten years. The issue with Yahoo is different, at best all you can do is write a blog entry and link to other people talking about the issue to raise awareness. You could go so far as to disallow registrations from users with Yahoo accounts or greatly discourage users from using Yahoo accounts though that could lead to a loss of members so I wouldn't do something like that unless you've got something people really want. The state of HTML email in general is exceptionally sad at this point though most (at least technical users) typically have multiple email addresses.

You could always use <style type="text/css"></style> even though scoped CSS is not widely supported in 2017 except for Gecko/Firefox though it did seem to fix some of the issues for me that you mentioned you were having.

Lastly you can always provide a "view this email on our website" option; I see it all the time because HTML email is still a disaster (2017). I've even seen nonsense with developers sending email with html element (uh, it's not an entire page, it will be embedded, but you know, whatever...).

So try utilizing different unit values and even the contexts themselves. Inline-styling is the way to go and if that fails provide a website version of the email (with security considerations for email with sensitive data).

ContentLicense: CC BY-SA 4.0


问:
SQL Server query using a cursor
The query below calculates the percentage of a product between FY2009 vs. FY2010 for California. I am assigned to calculate the remaining states (Please see STATES table). Is there a way in SQL Server that could calculate the states percentages? I am currently manually calculate each state at a time.

(Please note, I must use the states table separately due to data integrity. I was thinking if a cursor would do it, but I am not there yet.)

```<code>DECLARE @LOCATION VARCHAR(2)
SET  @state = 'CA'

SELECT NUMBER1/CAST(NUMBER2 as FLOAT) as PERCENTAGE
FROM
(
    SELECT COUNT (PRODUCT) as NUMBER1
    FROM SOMETABLE1
    WHERE LOCATION = @state
    AND DATE >='10/1/2008'
    AND DATE  <' 10/1/2009'
)X,

(
    SELECT COUNT (PRODUCT) as NUMBER2
    FROM SOMETABLE2
    WHERE LOCATION = @state
    AND DATE >='10/1/2009'
    AND DATE  <' 10/1/2010'
)Y

PERCENTAGE
1.400742

SELECT state
FROM STATES

STATE
CA
AZ
TX
NV
NM
UT
OR
CO
WA
</code>```

答:
You can join on the STATES table. Something along these lines:</p>

```<code>SELECT X.STATE, X.NUMBER1/CAST(Y.NUMBER2 as FLOAT) as PERCENTAGE
FROM
(
    SELECT S.STATE, COUNT(*) as NUMBER1
    FROM SOMETABLE1 AS S1
    INNER JOIN STATES AS S ON S1.LOCATION = S.STATE
    AND S1.DATE >='10/1/2008'
    AND S1.DATE < '10/1/2009'
    GROUP BY S.STATE
)X,

(
    SELECT S.STATE, COUNT (*) as NUMBER2
    FROM SOMETABLE2 AS S2
    INNER JOIN STATES AS S ON S2.LOCATION = S.STATE
    AND S2.DATE >='10/1/2009'
    AND S2.DATE < '10/1/2010'
    GROUP BY S.STATE
)Y
WHERE X.STATE = Y.STATE
</code>```

Title: SQL Server query using a cursor

Body:
The query below calculates the percentage of a product between FY2009 vs. FY2010 for California. I am assigned to calculate the remaining states (Please see STATES table). Is there a way in SQL Server that could calculate the states percentages? I am currently manually calculate each state at a time.

(Please note, I must use the states table separately due to data integrity. I was thinking if a cursor would do it, but I am not there yet.)

DECLARE @LOCATION VARCHAR(2)
SET  @state = 'CA'

SELECT NUMBER1/CAST(NUMBER2 as FLOAT) as PERCENTAGE
FROM
(
    SELECT COUNT (PRODUCT) as NUMBER1
    FROM SOMETABLE1
    WHERE LOCATION = @state
    AND DATE >='10/1/2008'
    AND DATE  <' 10/1/2009'
)X,

(
    SELECT COUNT (PRODUCT) as NUMBER2
    FROM SOMETABLE2
    WHERE LOCATION = @state
    AND DATE >='10/1/2009'
    AND DATE  <' 10/1/2010'
)Y

PERCENTAGE
1.400742

SELECT state
FROM STATES

STATE
CA
AZ
TX
NV
NM
UT
OR
CO
WA

Body:
You can join on the STATES table. Something along these lines:

SELECT X.STATE, X.NUMBER1/CAST(Y.NUMBER2 as FLOAT) as PERCENTAGE
FROM
(
    SELECT S.STATE, COUNT(*) as NUMBER1
    FROM SOMETABLE1 AS S1
    INNER JOIN STATES AS S ON S1.LOCATION = S.STATE
    AND S1.DATE >='10/1/2008'
    AND S1.DATE < '10/1/2009'
    GROUP BY S.STATE
)X,

(
    SELECT S.STATE, COUNT (*) as NUMBER2
    FROM SOMETABLE2 AS S2
    INNER JOIN STATES AS S ON S2.LOCATION = S.STATE
    AND S2.DATE >='10/1/2009'
    AND S2.DATE < '10/1/2010'
    GROUP BY S.STATE
)Y
WHERE X.STATE = Y.STATE


问:
Create a constantly running background task to fetch realtime data
I'm developing a realtime chat/messenger app, sort of like Telegram or Discord. In my app, I need to fetch messages in realtime as they come in. Other apps (Discord is built on React Native) are able to show push notifications in realtime as messages come in. I'm wondering how I can do this as most packages for background tasks only allow it to run every few minutes at the least. I'd like to have a constant task running, using socket.io to get new messages. I would prefer to have Android and iOS support.

Thank you!

答:
For Push Notifications, you can take a look at this package: https://github.com/zo0r/react-native-push-notification.

For any other background tasks, take a look at Headless JS and workers such as https://facebook.github.io/react-native/docs/headless-js-android.html and https://github.com/devfd/react-native-workers.


问:
Why must accessor functions be const? Where is the vulnerability?
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

```<code>#include <iostream>
#include <string>

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}
</code>```

答:
It's actually very simple: If the method is not const, you would not be able to use it on const objects - but you do want to be able to use it. With your class, you can't implement

```<code>void print_brand(const Cheese& cheese);
</code>```

(unless you const-cast, which you shouldn't do).

Also, if you do make it const, instead of returning a copy of your string - which may or may not get optimized away, you could implement:

```<code>const std::string& getBrand() const { return brand_; }
</code>```

which returns a reference, or perhaps

```<code>std::string_view getBrand() const { return brand_; }
</code>```

that does not "commit" your API to the string class (read about string_view here; it was only officially added to the language in C++17, but is available as std::experimental::string_view with recent compilers).

Body:
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

#include <iostream>
#include <string>

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}

Body:
It's actually very simple: If the method is not const, you would not be able to use it on const objects - but you do want to be able to use it. With your class, you can't implement

void print_brand(const Cheese& cheese);

(unless you const-cast, which you shouldn't do).

Also, if you do make it const, instead of returning a copy of your string - which may or may not get optimized away, you could implement:

const std::string& getBrand() const { return brand_; }

which returns a reference, or perhaps

std::string_view getBrand() const { return brand_; }

that does not "commit" your API to the string class (read about string_view here; it was only officially added to the language in C++17, but is available as std::experimental::string_view with recent compilers).


问:
Route [events.store] not defined
Every time it keeps on saying that the Route events.store is defined but in fact it is ,I don't know where I'm going wrong with my code .

This is is my calendar.blade.php class:

```<code><!doctype html>
<html lang="{{ config('calendar.locale') }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Full Calendar</title>

    {!!Html::style('vendor2/seguce92/fullcalendar/fullcalendar.min.css')!!}
    {{Html::style('css/app.css')}}

</head>

<div class='container'></div>

{{ Form::open(['route' => 'events.store', 'method' => 'post', 'role' => 'form']) }}
</code>```

And this is my web.php:

```<code> Route::get('/calendar',function () { return view('calendar');});

    Route::resource('events', 'EventsController',['only' => ['index', 'store']]);
</code>```

And when I take out {{ Form::open(['route' => 'events.store', 'method' => 'post', 'role' => 'form']) } the page loads fine again ,but I will need that line of code in the future

php artisan route list

答:
```<code>{{ Form::open(['route' => 'user.events.store', 'method' => 'post', 'role' => 'form']) }}
</code>```

According to your route:list you should have user.events.store in your from route

Title: Route [events.store] not defined

Body:
Every time it keeps on saying that the Route events.store is defined but in fact it is ,I don't know where I'm going wrong with my code .

This is is my calendar.blade.php class:

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Full Calendar</title>

    {!!Html::style('vendor2/seguce92/fullcalendar/fullcalendar.min.css')!!}
    {{Html::style('css/app.css')}}

{{ Form::open(['route' => 'events.store', 'method' => 'post', 'role' => 'form']) }}

And this is my web.php:

 Route::get('/calendar',function () { return view('calendar');});

    Route::resource('events', 'EventsController',['only' => ['index', 'store']]);

And when I take out {{ Form::open(['route' => 'events.store', 'method' => 'post', 'role' => 'form']) } the page loads fine again ,but I will need that line of code in the future

php artisan route list

Body:
{{ Form::open(['route' => 'user.events.store', 'method' => 'post', 'role' => 'form']) }}

According to your route:list you should have user.events.store in your from route


问:
Beautifulsoup sibling structure with br tags
I'm trying to parse a HTML document using the BeautifulSoup Python library, but the structure is getting distorted by
 tags. Let me just give you an example.

Input HTML:

```<code><div>
  some text <br>
  <span> some more text </span> <br>
  <span> and more text </span>
</div>
</code>```

HTML that BeautifulSoup interprets:

```<code><div>
  some text
  <br>
    <span> some more text </span>
    <br>
      <span> and more text </span>
    </br>
  </br>
</div>
</code>```

In the source, the spans could be considered siblings. After parsing (using the default parser), the spans are suddenly no longer siblings, as the br tags became part of the structure.

The solution I can think of to solve this is to strip the
 tags altogether, before pouring the html into Beautifulsoup, but that doesn't seem very elegant, as it requires me to change the input. What's a better way to solve this?

答:
This is a super old question but I just had a similar problem because my document contained closong
tags. Because of this, massive chunks of document were simply ignored by beatifulsoup ( bs trying to deal with a closing tag, I assume.) soup.find_all('br') didn't actually find anything because there was no opening br tag, so I couldn't use the extract() method.

After bashing my head for an hour I found that using lxml parser instead of the default html fixed the problem.

soup = BeautifulSoup(page, 'lxml')

Body:
I'm trying to parse a HTML document using the BeautifulSoup Python library, but the structure is getting distorted by
 tags. Let me just give you an example.

Input HTML:

  some text

   some more text

   and more text

HTML that BeautifulSoup interprets:

  some text

     some more text

       and more text

In the source, the spans could be considered siblings. After parsing (using the default parser), the spans are suddenly no longer siblings, as the br tags became part of the structure.

The solution I can think of to solve this is to strip the
 tags altogether, before pouring the html into Beautifulsoup, but that doesn't seem very elegant, as it requires me to change the input. What's a better way to solve this?

Body:
This is a super old question but I just had a similar problem because my document contained closong </br>tags. Because of this, massive chunks of document were simply ignored by beatifulsoup ( bs trying to deal with a closing tag, I assume.) soup.find_all('br') didn't actually find anything because there was no opening br tag, so I couldn't use the extract() method.

After bashing my head for an hour I found that using lxml parser instead of the default html fixed the problem.

soup = BeautifulSoup(page, 'lxml')


问:
sending flash success message to parent tab
I'm attempting to trigger a refresh of a parent window and have a flash success message appear on that window.

To clarify, a user works from an admin page, which then opens another tab with an article.   I currently have it set to submit and close, and then have the original page reload ( through window.opener.location.reload();

I can generate a flash success message on the current page, but of course, that's not helpful, as that page closes immediately on submit.

Is it possible to get this to show on the original tab/window using a similar process like below?

```<code>function refreshParent() {
    window.opener.location.reload();
    window.opener.location.$('header > .alerts').append( $('<div>Article sent to editor.</div>').addClass('alert alert-success'));
}
</code>```

There's currently an empty  tag on the twig for the original window.  I'm not sure if I have the above syntax correct.

答:
you can do something like

```<code><script>
    window.onunload = refreshParent;triggerAlertOnParent;
    function refreshParenttriggerAlertOnParent() {
        window.opener.location.hash = "showAlert";
        window.opener.location.reload();
    }
</script>
</code>```

in the child window to
 1. add a #showAlert hash to the URL of window.opener
 2. ask window.opener to refresh (with the new hash in URL) to retrieve new data from server

in the parent window, always have the HTML for the alert box ready, but hide it using css

```<code><div class="alert alert-success is-hidden">Article sent to editor.</div>
</code>```

CSS:

```<code>.is-hidden {
    display: none;
}
</code>```

when your parent page is loaded, in your javascript code, see if there is a hash in the URL that is set to "showAlert", if so, remove the is-hidden class, so that the alert box is displayed.

```<code>$( document ).ready(function() {
    if (document.location.hash === "#showAlert")
        $(".alert.is-hidden").removeClass("is-hidden");
}
</code>```

Body:
I'm attempting to trigger a refresh of a parent window and have a flash success message appear on that window.

To clarify, a user works from an admin page, which then opens another tab with an article.   I currently have it set to submit and close, and then have the original page reload ( through window.opener.location.reload();

I can generate a flash success message on the current page, but of course, that's not helpful, as that page closes immediately on submit.

Is it possible to get this to show on the original tab/window using a similar process like below?

function refreshParent() {
    window.opener.location.reload();
    window.opener.location.$('header > .alerts').append( $('
Article sent to editor.
').addClass('alert alert-success'));
}

There's currently an empty  tag on the twig for the original window.  I'm not sure if I have the above syntax correct.

Body:
you can do something like

<script>
    window.onunload = refreshParent;triggerAlertOnParent;
    function refreshParenttriggerAlertOnParent() {
        window.opener.location.hash = "showAlert";
        window.opener.location.reload();
    }
</script>

in the child window to
 1. add a #showAlert hash to the URL of window.opener
 2. ask window.opener to refresh (with the new hash in URL) to retrieve new data from server

in the parent window, always have the HTML for the alert box ready, but hide it using css

<div class="alert alert-success is-hidden">Article sent to editor.</div>

CSS:

.is-hidden {
    display: none;
}

when your parent page is loaded, in your javascript code, see if there is a hash in the URL that is set to "showAlert", if so, remove the is-hidden class, so that the alert box is displayed.

$( document ).ready(function() {
    if (document.location.hash === "#showAlert")
        $(".alert.is-hidden").removeClass("is-hidden");
}


问:
Sed Extract between two patterns first matching
(Xubuntu 16.04.2 x86_64)
I am trying to parse an html file and grab values from it. I need all the code extracted between this

```<code><tr style="text-align: center; background:#FFF">
</code>```

and this

```<code></td></tr>
</code>```

The problem, is I'm running this through a loop to grab 800 of these sections but the first time it runs it finds the first string correctly but it uses the last match in the file instead of the next one from the first string.

I'm outputting each find into a text file and the first one combines every single entry which is not what I need, I need individual files for each entry.

Instead of using that complicated string, let's say I have this html

```<code><div>
  Index
  Index
  Index
</div>
<div>
  Index
  Index
  Index
</div>
<div>
  Index
  Index
  Index
</div>
</code>```

I am using this code

```<code>sed 1,/<div>/,/<\/div>/!d' sourcefile > output
</code>```

But that command with give the entire file instead of picking the first match of
.

I would much rather use sed than awk, grep, or perl if possible.

答:
If you insist on sed, this should do the trick (if I understand your question correctly):

```<code>sed -n '/<div>/,/<\/div>/ { /<\/*div>/d; p }' file
</code>```

Since POSIX ERE (extended regex) is always greedy, the address range /
/,/<\/div>/ will always catch consecutive divs. The command that we run on those blocks just deletes the (outer)
 and
; printing out everything else.

For input file:

```<code>a
<div>
    1
</div>
b
<div>
    2
</div>
c
<div>
    3
</div>
d
</code>```

output is:

```<code>    1
    2
    3
</code>```

Body:
(Xubuntu 16.04.2 x86_64)
I am trying to parse an html file and grab values from it. I need all the code extracted between this

and this

The problem, is I'm running this through a loop to grab 800 of these sections but the first time it runs it finds the first string correctly but it uses the last match in the file instead of the next one from the first string.

I'm outputting each find into a text file and the first one combines every single entry which is not what I need, I need individual files for each entry.

Instead of using that complicated string, let's say I have this html

  Index
  Index
  Index

  Index
  Index
  Index

  Index
  Index
  Index

I am using this code

sed 1,/
/,/<\/div>/!d' sourcefile > output

But that command with give the entire file instead of picking the first match of
.

I would much rather use sed than awk, grep, or perl if possible.

Body:
If you insist on sed, this should do the trick (if I understand your question correctly):

sed -n '/<div>/,/<\/div>/ { /<\/*div>/d; p }' file

Since POSIX ERE (extended regex) is always greedy, the address range /<div>/,/<\/div>/ will always catch consecutive divs. The command that we run on those blocks just deletes the (outer) <div> and </div>; printing out everything else.

For input file:

a
<div>
    1
</div>
b
<div>
    2
</div>
c
<div>
    3
</div>
d

output is:

    1
    2
    3


问:
In "SemVer.org" what does mean "It MAY include patch level changes" in item 7?
In http://semver.org/spec/v2.0.0.html we have a "formal description" about how to manage software versioning in a way to create a standard and avoid some dependencies management problems. In the item-spec-7 we have as follows:

Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. It MUST be incremented if any public API functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.

1) What does the bold sentences exactly mean?

1.1) Means that I could choose any value for the patch that I want? But I could not just change the patch level from the current value?

Item 1.1 makes senses for me, but the sentences order confused me. After all, the Minor value had just been incremented and the patch was reset to 0(zero).

Did I get it right?

Thanks in advance!

答:
As far as I could understand in the iten-spec 7 of sermver.org (2.0.0), that descibes how to increment Minor version value:

Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. It MUST be incremented if any public API functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.

It MAY include patch level changes into the code in this new version with Minor incremented. But only patch level changes could not lead us to a Minor increment. In the other hand, it is expressed in item-spec 6:

Patch version Z (x.y.Z | x > 0) MUST be incremented if only backwards compatible bug fixes are introduced. A bug fix is defined as an internal change that fixes incorrect behavior.


问:
TypeError: list indices must be integers or slices, not str - get from json
I try to get all lattitudes and longtitudes from this json.

Code:

```<code>import urllib.parse
import requests

raw_json = 'http://live.ksmobile.net/live/getreplayvideos?userid='
print()

userid = 735890904669618176
#userid = input('UserID: ')

url = raw_json + urllib.parse.urlencode({'userid=': userid}) + '&page_size=1000'
print(url)

json_data = requests.get(url).json()
print()

for coordinates in json_data['data']['video_info']:
    print(coordinates['lat'], coordinates['lnt'])
    print()
</code>```

Error:

```<code>/usr/bin/python3.6 /media/anon/3D0B8DD536C9574F/PythonProjects/getLocation/getCoordinates

http://live.ksmobile.net/live/getreplayvideos?userid=userid%3D=735890904669618176&page_size=1000

Traceback (most recent call last):
  File "/media/anon/3D0B8DD536C9574F/PythonProjects/getLocation/getCoordinates", line 17, in <module>
    for coordinates in json_data['data']['video_info']:
TypeError: list indices must be integers or slices, not str

Process finished with exit code 1
</code>```

Where do I go wrong?

In advance, thanks for your help and time.

I just post some of the json to show what it looks like.
The json looks like this:

```<code>{
  "status": "200",
  "msg": "",
  "data": {
    "time": "1499275646",
    "video_info": [
      {
        "vid": "14992026438883533757",
        "watchnumber": "38",
        "topicid": "0",
        "topic": "",
        "vtime": "1499202678",
        "title": "happy 4th of july",
        "userid": "735890904669618176",
        "online": "0",
        "addr": "",
        "isaddr": "2",
        "lnt": "-80.1282576",
        "lat": "26.2810628",
        "area": "A_US",
        "countryCode": "US",
        "chatSystem": "1",
        },
</code>```

Full json: https://pastebin.com/qJywTqa1

答:
Your URL construction is incorrect. The URL you have built (as shown in the output of your script) is:

```<code>http://live.ksmobile.net/live/getreplayvideos?userid=userid%3D=735890904669618176&page_size=1000
</code>```

Where you actually want this:

```<code>http://live.ksmobile.net/live/getreplayvideos?userid=735890904669618176&page_size=1000
</code>```

So your were actually getting this JSON in your response:

```<code>{
  "status": "200",
  "msg": "",
  "data": []
}
</code>```

Which is why you were seeing that error.

Here is the corrected script:

```<code>import urllib.parse
import requests

raw_json = 'http://live.ksmobile.net/live/getreplayvideos?'
print()

userid = 735890904669618176
#userid = input('UserID: ')

url = raw_json + urllib.parse.urlencode({'userid': userid}) + '&page_size=1000'
print(url)

json_data = requests.get(url).json()
print()

for coordinates in json_data['data']['video_info']:
    print(coordinates['lat'], coordinates['lnt'])
    print()
</code>```

Body:
I try to get all lattitudes and longtitudes from this json.

Code:

import urllib.parse
import requests

raw_json = 'http://live.ksmobile.net/live/getreplayvideos?userid='
print()

userid = 735890904669618176
#userid = input('UserID: ')

url = raw_json + urllib.parse.urlencode({'userid=': userid}) + '&page_size=1000'
print(url)

json_data = requests.get(url).json()
print()

for coordinates in json_data['data']['video_info']:
    print(coordinates['lat'], coordinates['lnt'])
    print()

Error:

/usr/bin/python3.6 /media/anon/3D0B8DD536C9574F/PythonProjects/getLocation/getCoordinates

http://live.ksmobile.net/live/getreplayvideos?userid=userid%3D=735890904669618176&page_size=1000

Traceback (most recent call last):
  File "/media/anon/3D0B8DD536C9574F/PythonProjects/getLocation/getCoordinates", line 17, in <module>
    for coordinates in json_data['data']['video_info']:
TypeError: list indices must be integers or slices, not str

Process finished with exit code 1

Where do I go wrong?

In advance, thanks for your help and time.

I just post some of the json to show what it looks like.
The json looks like this:

{
  "status": "200",
  "msg": "",
  "data": {
    "time": "1499275646",
    "video_info": [
      {
        "vid": "14992026438883533757",
        "watchnumber": "38",
        "topicid": "0",
        "topic": "",
        "vtime": "1499202678",
        "title": "happy 4th of july",
        "userid": "735890904669618176",
        "online": "0",
        "addr": "",
        "isaddr": "2",
        "lnt": "-80.1282576",
        "lat": "26.2810628",
        "area": "A_US",
        "countryCode": "US",
        "chatSystem": "1",
        },

Full json: https://pastebin.com/qJywTqa1

Body:
Your URL construction is incorrect. The URL you have built (as shown in the output of your script) is:

http://live.ksmobile.net/live/getreplayvideos?userid=userid%3D=735890904669618176&page_size=1000

Where you actually want this:

http://live.ksmobile.net/live/getreplayvideos?userid=735890904669618176&page_size=1000

So your were actually getting this JSON in your response:

{
  "status": "200",
  "msg": "",
  "data": []
}

Which is why you were seeing that error.

Here is the corrected script:

import urllib.parse
import requests

raw_json = 'http://live.ksmobile.net/live/getreplayvideos?'
print()

userid = 735890904669618176
#userid = input('UserID: ')

url = raw_json + urllib.parse.urlencode({'userid': userid}) + '&page_size=1000'
print(url)

json_data = requests.get(url).json()
print()

for coordinates in json_data['data']['video_info']:
    print(coordinates['lat'], coordinates['lnt'])
    print()


问:
How to Automate selecting values in a iOS PickerWheel with Ruby
I have been automating an application with Ruby and the Cucumber Framework. I'm utilizing XCUITest for my iOS automation within this framework.

From what research I've done it appears as though I have to send text to the picker wheel for it to adjust to the wanted value. This is the code I've tried to use:

```<code>Then(/^I click on month"([^"]*)"$/) do |month_number|
  find_element(xpath: "//XCUIElementTypePickerWheel[1]").adjustToPickerWheelValue("#{month_number}")
end
</code>```

With this code my Cucumber framework calls the find_element method for that element and attempts to send the "month_number" value to a "adjustToPickerWheelValue" method.

The error I receive when I attempt to use this method is a standard noMethod error:

```<code>undefined method `adjustToPickerWheelValue' for #<Selenium::WebDriver::Element:0x007f802cda98d8> (NoMethodError)
</code>```

Is there something special I need to do to call this method in my env.rb file? Right now I just have "appium_lib" as required. Is there an XCUITest library I need to be utilizing as well?

Any and all help would be greatly appreciated. I'm very new to automating iOS. Thanks for reading and I hope to hear from you soon.

答:
The method  for xcuitest is </p>

```<code>select_picker_wheel(element:, order:, offset: nil)
</code>```

Body:
I have been automating an application with Ruby and the Cucumber Framework. I'm utilizing XCUITest for my iOS automation within this framework.

From what research I've done it appears as though I have to send text to the picker wheel for it to adjust to the wanted value. This is the code I've tried to use:

Then(/^I click on month"([^"]*)"$/) do |month_number|
  find_element(xpath: "//XCUIElementTypePickerWheel[1]").adjustToPickerWheelValue("#{month_number}")
end

With this code my Cucumber framework calls the find_element method for that element and attempts to send the "month_number" value to a "adjustToPickerWheelValue" method.

The error I receive when I attempt to use this method is a standard noMethod error:

undefined method `adjustToPickerWheelValue' for #<Selenium::WebDriver::Element:0x007f802cda98d8> (NoMethodError)

Is there something special I need to do to call this method in my env.rb file? Right now I just have "appium_lib" as required. Is there an XCUITest library I need to be utilizing as well?

Any and all help would be greatly appreciated. I'm very new to automating iOS. Thanks for reading and I hope to hear from you soon.

Body:
The method  for xcuitest is

select_picker_wheel(element:, order:, offset: nil)


问:
Laravel: Save Base64 .png file to public folder from controller
I send a png image file to controller in base64 via Ajax. I've already test and sure that controller has received id but still can't save it to public folder.

Here is my controller

```<code>public function postTest() {
        $data = Input::all();

        //get the base-64 from data
        $base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);

        //decode base64 string
        $image = base64_decode($base64_str);
        $png_url = "product-".time().".png";
        $path = public_path('img/designs/' . $png_url);

        Image::make($image->getRealPath())->save($path);
        // I've tried using
        // $result = file_put_contents($path, $image);
        // too but still not working

        $response = array(
            'status' => 'success',
        );
        return Response::json( $response  );
}
</code>```

答:
My solution is:</p>

```<code>public function postTest() {
        $data = Input::all();

        //get the base-64 from data
        $base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);

        //decode base64 string
        $image = base64_decode($base64_str);
        Storage::disk('local')->put('imgage.png', $image);
        $storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
        echo $storagePath.'imgage.png';
        $response = array(
            'status' => 'success',
        );
        return Response::json( $response  );
}
</code>```

Body:
I send a png image file to controller in base64 via Ajax. I've already test and sure that controller has received id but still can't save it to public folder.

Here is my controller

public function postTest() {
        $data = Input::all();

        //get the base-64 from data
        $base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);

        //decode base64 string
        $image = base64_decode($base64_str);
        $png_url = "product-".time().".png";
        $path = public_path('img/designs/' . $png_url);

        Image::make($image->getRealPath())->save($path);
        // I've tried using
        // $result = file_put_contents($path, $image);
        // too but still not working

        $response = array(
            'status' => 'success',
        );
        return Response::json( $response  );
}

Body:
My solution is:

public function postTest() {
        $data = Input::all();

        //get the base-64 from data
        $base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);

        //decode base64 string
        $image = base64_decode($base64_str);
        Storage::disk('local')->put('imgage.png', $image);
        $storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
        echo $storagePath.'imgage.png';
        $response = array(
            'status' => 'success',
        );
        return Response::json( $response  );
}


问:
Having problems outputting proper CGI, Python script?
So I am trying to keep my project as simple as possible, therefore I have decided to use a CGI with my Python scripts in order to run a program that does something.

So here is my current setup:

In CMD, I run:
python -m http.server --cgi 8000

This start a server for me. I can access it via localhost:8000.

Next, I am trying to find my directory with the script by typing in the actual address where it is located: localhost:8000/test/cgi-bin/test.py

This is giving me the output of the actual file, not actually reading it properly. I have tried 2 different ways to output data on the Python file, for example:

```<code>import sys
sys.stdout.write("Content-type: text\html \r\n\r\n")
sys.stdout.write("<html><title>Hi</title><body><p>This is a test</p></body></html>")
</code>```

and

```<code>print("Content-Type: text/html\n")
print("<!doctype html><title>Hello</title><h2>hello world</h2>")
</code>```

Both of which result in the actual code being displayed in my browser.

A few questions:

How do I get my server to automatically take me to the location of the file I am trying to run?

How do I get the python script to output the proper stuff?

Am I setting this up correctly?

I am trying to avoid installing any new dependencies and keep it as minimal as possible.

I am running on Python3, Windows7. I am trying to avoid downloading more pip packages and dependencies because my work is very tech precautious.

Any help is greatly appreciated.

答:
First, I want to say that writing plain CGI-scripts in 2017 is a way of a brave person. Your life will be much easier if you would use bottle or flask.

But if you want, here is the way you can start.

python -m http.server --cgi assumes that the cgi-bin is in the current directory. That is you should go to the test directory and start the command from there. And then call http://localhost:8000/cgi-bin/test.py.

Your cgi-script is not correct. The script should be executable. I am not sure if it needs a shebang line in Windows when you run the http.server, but is is required when you run CGI-scripts with Apache web server under Windows. The shebang line starts with #! and then contains the full path to python3 interpreter, and the line should end with \n and not \r\n, otherwise it won't work.

After that you should output all the HTTP-headers, print a blank line, and output your content. All HTTP-headers should be separated by '\r\n' and not '\n'.

Here is an example CGI-script that works on OS X:

```<code>#!/usr/bin/env python3
import sys
sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: text/html;charset="utf-8"\r\n\r\n')

print('<h1>Hello, world!</h1>')
</code>```

Body:
So I am trying to keep my project as simple as possible, therefore I have decided to use a CGI with my Python scripts in order to run a program that does something.

So here is my current setup:

In CMD, I run:
python -m http.server --cgi 8000

This start a server for me. I can access it via localhost:8000.

Next, I am trying to find my directory with the script by typing in the actual address where it is located: localhost:8000/test/cgi-bin/test.py

This is giving me the output of the actual file, not actually reading it properly. I have tried 2 different ways to output data on the Python file, for example:

import sys
sys.stdout.write("Content-type: text\html \r\n\r\n")
sys.stdout.write("<title>Hi</title>
This is a test
")

and

print("Content-Type: text/html\n")
print("<!doctype html><title>Hello</title>
hello world
")

Both of which result in the actual code being displayed in my browser.

A few questions:

How do I get my server to automatically take me to the location of the file I am trying to run?

How do I get the python script to output the proper stuff?

Am I setting this up correctly?

I am trying to avoid installing any new dependencies and keep it as minimal as possible.

I am running on Python3, Windows7. I am trying to avoid downloading more pip packages and dependencies because my work is very tech precautious.

Any help is greatly appreciated.

Body:
First, I want to say that writing plain CGI-scripts in 2017 is a way of a brave person. Your life will be much easier if you would use bottle or flask.

But if you want, here is the way you can start.

python -m http.server --cgi assumes that the cgi-bin is in the current directory. That is you should go to the test directory and start the command from there. And then call http://localhost:8000/cgi-bin/test.py.

Your cgi-script is not correct. The script should be executable. I am not sure if it needs a shebang line in Windows when you run the http.server, but is is required when you run CGI-scripts with Apache web server under Windows. The shebang line starts with #! and then contains the full path to python3 interpreter, and the line should end with \n and not \r\n, otherwise it won't work.

After that you should output all the HTTP-headers, print a blank line, and output your content. All HTTP-headers should be separated by '\r\n' and not '\n'.

Here is an example CGI-script that works on OS X:

#!/usr/bin/env python3
import sys
sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: text/html;charset="utf-8"\r\n\r\n')

print('<h1>Hello, world!</h1>')


问:
Challenge JavaScript grab image URL from HTML class
This question differs from other questions before, in that here we have a
 STYLE inside a CLASS name. That made it a little more complicated to me.

I want to alert() ONLY the url of a image showing in the website, that is accessible with its class name:

```<code>    <div  class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div>
</code>```

I tried by doing:

```<code>alert( (document.querySelector('.image-container-image').textContent) );
</code>```

Tried other different ways, but still no luck.

My output should be an alert showing the following url:
  "https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg"

Your guidance is very much appreciated.

Body:
This question differs from other questions before, in that here we have a
 STYLE inside a CLASS name. That made it a little more complicated to me.

I want to alert() ONLY the url of a image showing in the website, that is accessible with its class name:

I tried by doing:

alert( (document.querySelector('.image-container-image').textContent) );

Tried other different ways, but still no luck.

My output should be an alert showing the following url:
  "https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg"

Your guidance is very much appreciated.

Body:
alert(document.querySelector('.image-container-image').style.backgroundImage.toString().replace(/(url|\(|\)|")/g, ''))

<div  class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div>


问:
MS Access Append Query too big
I have a database with a large table of pricing data = EB. I want to append 45 days of pricing data to that table so I have written the query below. The query doesn't seem to run though as I get 2 GB warning and also memory warning. The EB table has 716,580 records in it and I have indexed on Symbol and Date.

Please help as I'm new to this.
Thanks

```<code>INSERT INTO EB ( Symbol, Description, [Currency], UNITS, [Date], LOW, HIGH, [CLOSE], INDEX_MIDPOINT, VOLUME, BID, ASK, [OPEN], MEAN )
SELECT EB_hist.Symbol, EB_hist.Description, EB_hist.Currency, EB_hist.UOM,
EB_hist.Date, EB_hist.[Low(l)], EB_hist.[High(h)], EB_hist.[Close(c)],
EB_hist.[Index(u)], EB_hist.[Volume(v)], EB_hist.[Bid(b)], EB_hist.[Ask(a)],
EB_hist.[Open(o)], EB_hist.[Mean(m)]
FROM EB, EB_hist
WHERE (((EB_hist.Date)>(select MAX([Date]) from EB)));
</code>```

答:
There is no JOIN clause in the SELECT between EB and EB_hist. This results in a Cartesian relationship (every record of each table is associated with each record of other table) which is probably why the query hits 2GB limit. This is the limit for an entire Access db. Try removing EB from the SELECT (not the SELECT Max() subquery).

Advise no spaces or punctuation/special characters (underscore only exception) in names. Also, date, close, currency are reserved words, should not use reserved words as names.

Title: MS Access Append Query too big

Body:
I have a database with a large table of pricing data = EB. I want to append 45 days of pricing data to that table so I have written the query below. The query doesn't seem to run though as I get 2 GB warning and also memory warning. The EB table has 716,580 records in it and I have indexed on Symbol and Date.

Please help as I'm new to this.
Thanks

INSERT INTO EB ( Symbol, Description, [Currency], UNITS, [Date], LOW, HIGH, [CLOSE], INDEX_MIDPOINT, VOLUME, BID, ASK, [OPEN], MEAN )
SELECT EB_hist.Symbol, EB_hist.Description, EB_hist.Currency, EB_hist.UOM,
EB_hist.Date, EB_hist.[Low(l)], EB_hist.[High(h)], EB_hist.[Close(c)],
EB_hist.[Index(u)], EB_hist.[Volume(v)], EB_hist.[Bid(b)], EB_hist.[Ask(a)],
EB_hist.[Open(o)], EB_hist.[Mean(m)]
FROM EB, EB_hist
WHERE (((EB_hist.Date)>(select MAX([Date]) from EB)));


问:
Savon using built in request builder instead of raw xml
If i use savon with raw xml everything works fine, this is the raw xml example:

```<code>request = client.call(:authenticate, xml:'<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="xxxx/">
  <SOAP-ENV:Body>
    <ns1:authenticate>
      <ns1:username>user</ns1:username>
      <ns1:password>pwd</ns1:password>
      <ns1:cultureInfo>it</ns1:cultureInfo>
    </ns1:authenticate>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>')
</code>```

If I use the builtin method to call the method I got an error, this is the code:

```<code>credentials={ username: 'user', password: 'pwd!!', cultureInfo: "it" }
response     = client.call(:authenticate, message: credentials)
</code>```

This is the xml produced by the above code:

```<code><?xml version="1.0" encoding="UTF-8"?>
  <env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:wsdl="http://tempuri.org/"
                xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <wsdl:authenticate>
      <username>user</username>
      <password>pwd</password>
      <cultureInfo>it</cultureInfo>
    </wsdl:authenticate>
  </env:Body>
</env:Envelope>
</code>```

Any Idea?

答:
I usually do just this (untested). It's not pretty but it works.

```<code>credentials = { 'ns1:username' => 'user',
                'ns1:password' => 'pwd!!',
                'ns1:cultureInfo' => "it" }
response = client.call(:authenticate, message: credentials)
</code>```

You might want to adapt the use of ns1 to the actually used namespace in your case.

Body:
If i use savon with raw xml everything works fine, this is the raw xml example:

request = client.call(:authenticate, xml:'<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="xxxx/">
  <SOAP-ENV:Body>
    <ns1:authenticate>
      <ns1:username>user</ns1:username>
      <ns1:password>pwd</ns1:password>
      <ns1:cultureInfo>it</ns1:cultureInfo>
    </ns1:authenticate>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>')

If I use the builtin method to call the method I got an error, this is the code:

credentials={ username: 'user', password: 'pwd!!', cultureInfo: "it" }
response     = client.call(:authenticate, message: credentials)

This is the xml produced by the above code:

<?xml version="1.0" encoding="UTF-8"?>
  <env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:wsdl="http://tempuri.org/"
                xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <wsdl:authenticate>
      <username>user</username>
      <password>pwd</password>
      <cultureInfo>it</cultureInfo>
    </wsdl:authenticate>
  </env:Body>
</env:Envelope>

Any Idea?

Body:
I usually do just this (untested). It's not pretty but it works.

credentials = { 'ns1:username' => 'user',
                'ns1:password' => 'pwd!!',
                'ns1:cultureInfo' => "it" }
response = client.call(:authenticate, message: credentials)

You might want to adapt the use of ns1 to the actually used namespace in your case.


问:
How to display text on multiple lines?
I am using RadPhp to build a PHP application. I want to display several independent lines of text in an Edit control (using $this->edit->text property ) but it seems to be impossible. If I use \n it just displays it instead of braking this line in two.

PS: can anybody add 'RadPHP' as tag for this question?

答: Also don't know RadPHP as well but does it use nl2br or something similar to that and you forgot to insert it?

Title: How to display text on multiple lines?


问:
Running Selenium Tests through Linux Server
This is a general question, but I want to run my Selenium tests on a cloud Linux Server. I am accessing this server using PuTTY, which is just a terminal.

I was wondering how I could get my Selenium scripts to run on this VM.

Currently I have a Selenium Grid set up with physical machines, I just do not know how to set one up through a server where the only communication I have with it is through PuTTY and a terminal.

答:
To run Selenium from a Linux server that is "terminal only", as you put it, is to install a GUI inside of the server.

The most common GUI to use, is Xvfb.  There are plenty of tutorials out there on how to run GUI programs like Google Chrome and Mozilla Firefox through Xvfb.


问:
How to subclass int and make it mutable
Is it possible to subclass int and make it mutable?

Consider the following class:

```<code>class CustomBitVector(int):

    # bit 7
    @property
    def seventh_property(self):
        return bool(self & (1 << 7))

    @seventh_property.setter
    def seventh_property(self, val):
        self |= bool(val) << 7

    # bit 6
    @property
    def sixth_property(self):
        return bool(self & (1 << 6))

    @sixth_property.setter
    def sixth_property(self, val):
        self |= bool(val) << 6

    # ... a few more of these ...

    # bit 0
    @property
    def zeroth_property(self):
        return bool(self & (1 << 0))

    @zeroth_property.setter
    def zeroth_property(self, val):
        self |= bool(val) << 0
</code>```

I trying to make a nice interface to a bit vector. I'm reading a proprietary protocol off of a socket and I've made classes to represent the messages I'm sending/receiving. Often these messages include bit vectors and it would be nice to deal with them like this.

This already works great for reading the bit vector values, but setting them doesn't work because int is immutable.

If I rewrite one of the setters like:

```<code>@sixth_property.setter
def sixth_property(self, val):
    print 'before:', self
    self |= bool(val) << 6
    print 'after:', self
</code>```

Then I get this behavior:

```<code>In [2]: c = CustomBitVector()

In [3]: c.sixth_property
Out[3]: False

In [4]: c.sixth_property = True
before: 0
after: 64

In [5]: c
Out[5]: 0

In [6]: c.sixth_property
Out[6]: False
</code>```

I can see my folly ... I'm assigning to self instead of modifying it. How can I modify self in this case?

Any crazy hack to make this happen? Maybe using a metaclass or something?

UPDATE

I forgot to mention a requirement:

Instances of CustomBitVector must behave like int. In particular, I need to be able to pass them to struct.pack

答:
Is it possible to subclass int and make it mutable?

Sort of. You can add all the mutable parts you want, but you can't touch the int parts, so the degree of mutability you can add won't help you.

Instead, don't use an int subclass. Use a regular object that stores an int. If you want to be able to pass it to struct.pack like an int, implement an __index__ method to define how to interpret your object as an int:

```<code>class IntLike(object): # not IntLike(int):
    def __init__(self, value=0):
        self.value = value
    def __index__(self):
        return self.value
    ...
</code>```

You can implement additional methods like __or__ for | and __ior__ for in-place, mutative |=. Don't try to push too hard for complete interoperability with ints, though; for example, don't try to make your objects usable as dict keys. They're mutable, after all.

If it's really important to you that your class is an int subclass, you're going to have to sacrifice the c.sixth_property = True syntax you want. You'll have to pick an alternative like c = c.with_sixth_property(True), and implement things non-mutatively.

Title: How to subclass int and make it mutable

Body:
Is it possible to subclass int and make it mutable?

Consider the following class:

class CustomBitVector(int):

    # bit 7
    @property
    def seventh_property(self):
        return bool(self & (1 << 7))

    @seventh_property.setter
    def seventh_property(self, val):
        self |= bool(val) << 7

    # bit 6
    @property
    def sixth_property(self):
        return bool(self & (1 << 6))

    @sixth_property.setter
    def sixth_property(self, val):
        self |= bool(val) << 6

    # ... a few more of these ...

    # bit 0
    @property
    def zeroth_property(self):
        return bool(self & (1 << 0))

    @zeroth_property.setter
    def zeroth_property(self, val):
        self |= bool(val) << 0

I trying to make a nice interface to a bit vector. I'm reading a proprietary protocol off of a socket and I've made classes to represent the messages I'm sending/receiving. Often these messages include bit vectors and it would be nice to deal with them like this.

This already works great for reading the bit vector values, but setting them doesn't work because int is immutable.

If I rewrite one of the setters like:

@sixth_property.setter
def sixth_property(self, val):
    print 'before:', self
    self |= bool(val) << 6
    print 'after:', self

Then I get this behavior:

In [2]: c = CustomBitVector()

In [3]: c.sixth_property
Out[3]: False

In [4]: c.sixth_property = True
before: 0
after: 64

In [5]: c
Out[5]: 0

In [6]: c.sixth_property
Out[6]: False

I can see my folly ... I'm assigning to self instead of modifying it. How can I modify self in this case?

Any crazy hack to make this happen? Maybe using a metaclass or something?

UPDATE

I forgot to mention a requirement:

Instances of CustomBitVector must behave like int. In particular, I need to be able to pass them to struct.pack

Body:
Is it possible to subclass int and make it mutable?

Sort of. You can add all the mutable parts you want, but you can't touch the int parts, so the degree of mutability you can add won't help you.

Instead, don't use an int subclass. Use a regular object that stores an int. If you want to be able to pass it to struct.pack like an int, implement an __index__ method to define how to interpret your object as an int:

class IntLike(object): # not IntLike(int):
    def __init__(self, value=0):
        self.value = value
    def __index__(self):
        return self.value
    ...

You can implement additional methods like __or__ for | and __ior__ for in-place, mutative |=. Don't try to push too hard for complete interoperability with ints, though; for example, don't try to make your objects usable as dict keys. They're mutable, after all.

If it's really important to you that your class is an int subclass, you're going to have to sacrifice the c.sixth_property = True syntax you want. You'll have to pick an alternative like c = c.with_sixth_property(True), and implement things non-mutatively.


问:
How can i download file inside app folder ?[ after packaging ]
This is my current folder structurebefore packaging
WRM_80.. is my downloaded folder.

I have these two lines of code inside index.js  to download and show html in my electron window

```<code>fs.createReadStream('./Report.zip').pipe(unzip.Extract({ path: './'+folderName }));
LoginWindow.loadURL(`file://${__dirname}./`+folderName+`/t01s01q01.html`);
</code>```

in development mode its working fine, file downloaded inside the same folder where my index.js exists. But after packaging the app file is downloading outside app folder. Packaged folder structure is given below  WRM_80.. is my downloaded folder.
after packaging

That's why I can not load that downloaded file into window. How can  I download file inside app folder? If that is not possible, how can I load external file from resources\app location ?

答:
By referencing the directory as ./folder_name you are essentially telling the application to download to the working directory. In this case, the working directory is the folder that the program is contained in. While developing and using the electron command, the working directory is the root of your application. However once installed and running as a .exe, the working directory changes to the location of the executable.

To solve this problem, do not use the current working directory. Instead use the user / application data folder to store this information. It is not only a consistent location across development and deployment, but it is also the semantically correct place to store application data.

In Electron you can get the path to the application data folder for your app with:

```<code>const {app} = require('electron');
app.getPath('userData')
</code>```

So your code should look something like this:

```<code>var userData = app.getPath('userData');
fs.createReadStream(`${userData}/Report.zip`).pipe(unzip.Extract({ path: `${userData}/${folderName}` }));
LoginWindow.loadURL(`file://${userData}/${folderName}/t01s01q01.html`);
</code>```

Body:
This is my current folder structurebefore packaging
WRM_80.. is my downloaded folder.

I have these two lines of code inside index.js  to download and show html in my electron window

fs.createReadStream('./Report.zip').pipe(unzip.Extract({ path: './'+folderName }));
LoginWindow.loadURL(`file://${__dirname}./`+folderName+`/t01s01q01.html`);

in development mode its working fine, file downloaded inside the same folder where my index.js exists. But after packaging the app file is downloading outside app folder. Packaged folder structure is given below  WRM_80.. is my downloaded folder.
after packaging

That's why I can not load that downloaded file into window. How can  I download file inside app folder? If that is not possible, how can I load external file from resources\app location ?

Body:
By referencing the directory as ./folder_name you are essentially telling the application to download to the working directory. In this case, the working directory is the folder that the program is contained in. While developing and using the electron command, the working directory is the root of your application. However once installed and running as a .exe, the working directory changes to the location of the executable.

To solve this problem, do not use the current working directory. Instead use the user / application data folder to store this information. It is not only a consistent location across development and deployment, but it is also the semantically correct place to store application data.

In Electron you can get the path to the application data folder for your app with:

const {app} = require('electron');
app.getPath('userData')

So your code should look something like this:

var userData = app.getPath('userData');
fs.createReadStream(`${userData}/Report.zip`).pipe(unzip.Extract({ path: `${userData}/${folderName}` }));
LoginWindow.loadURL(`file://${userData}/${folderName}/t01s01q01.html`);


问:
IntelliJ Not Working With Java
I've been working in Eclipse for a while now, and I decided to check out IntelliJ Idea 2017.1.5. I've been having trouble getting the program to run. Maybe you can help me? Error:C:\Users\christine\Downloads (Access is denied) I get this error message. This is where I store my projects for Java. If any of you can help me please write a reply.

答:
Right click on InelliJ icon and choose run as administrator.  This will probably solve the issue.

If this didn't work you can also move your projects to another drive of your pc and set there as your workspace.

Title: IntelliJ Not Working With Java


问:
Python convert txt file to JSON stripping and element ordering
I have a txt file that contains data split by spaces such as:

```<code>2017-05-16 00:44:36.151724381 +43.8187 -104.7669 -004.4 00.6 00.2 00.2 090 C
2017-05-16 00:44:36.246672534 +41.6321 -104.7834 +004.3 00.6 00.3 00.2 130 C
2017-05-16 00:44:36.356132768 +46.4559 -104.5989 -004.2 01.1 00.4 00.2 034 C
</code>```

and I would like to convert it into JSON data to something like:

```{"dataset": "Lightning","observation_date": "20170516004436151", "location": { "type": "point", "coordinates": [43.8187, -104.7669]}}
{"dataset": "Lightning","observation_date": "20170516004436246", "location": { "type": "point", "coordinates": [41.6321, -104.7834]}}
{"dataset": "Lightning","observation_date": "20170516004436356", "location": { "type": "point", "coordinates": [46.4559, -104.5989]}}```

where I have to append a 'dataset':'lightning' key/val pair, combine and strip the date and time, and combine the lat/lng into a dict before doing any json conversion.

But right now I still get the date and time elements without being stripped of the "-" and ":" characters like:

```{"observation_date": "2017-05-1600:44:36.151724381", "location": {"type": "point", "coordinates": ["+43.8187", "-104.7669"]}, "dataset": "Lightning"}
{"observation_date": "2017-05-1600:44:36.246672534", "location": {"type": "point", "coordinates": ["+41.6321", "-104.7834"]}, "dataset": "Lightning"}
{"observation_date": "2017-05-1600:44:36.356132768", "location": {"type": "point", "coordinates": ["+46.4559", "-104.5989"]}, "dataset": "Lightning"}```

What I coded so far:

```<code>import json
import sys
def convert(filename):
    dataDict = {}
    txtFile = filename[0]
    print "Opening TXT file: ",txtFile
    infile = open(txtFile, "r")
    for line in infile:
        lineStrip = line.strip()
        parts = [p.strip() for p in lineStrip.split()]
        date = parts[0].strip("-") #trying to get rid of "-" but not working
        time = parts[1].strip(":") #trying to get rid of ":" and "." but not working
        dataDict.update({"dataset":"Lightning"})
        dataDict.update({"observation_date": date + time})
        dataDict.update({"location": {"type":"point", "coordinates": [parts[2], parts[3]]}})
        json_filename = txtFile.split(".")[0]+".json"
        jsonf = open(json_filename,'a')
        data = json.dumps(dataDict)
        jsonf.write(data + "\n")
        print dataDict
    infile.close()
    jsonf.close()
if __name__=="__main__":
    convert(sys.argv[1:])
</code>```

But I'm not sure how to strip the "-", ".", and ":" as well as place the "dataset":"lightning" element in the front.

答:
You should do:

date = parts[0].replace('-', '')
   time = parts[1].replace(':' '')

To get the dataset up front in JSON, the only option you have is sort the keys:

```<code>data = json.dumps(dataDict, sort_keys=True)
</code>```

You should also consider doing

```<code>dataDict["dataset"] = "Lightning"
</code>```

instead of the .update.

Body:
I have a txt file that contains data split by spaces such as:

2017-05-16 00:44:36.151724381 +43.8187 -104.7669 -004.4 00.6 00.2 00.2 090 C
2017-05-16 00:44:36.246672534 +41.6321 -104.7834 +004.3 00.6 00.3 00.2 130 C
2017-05-16 00:44:36.356132768 +46.4559 -104.5989 -004.2 01.1 00.4 00.2 034 C

and I would like to convert it into JSON data to something like:

{"dataset": "Lightning","observation_date": "20170516004436151", "location": { "type": "point", "coordinates": [43.8187, -104.7669]}}
{"dataset": "Lightning","observation_date": "20170516004436246", "location": { "type": "point", "coordinates": [41.6321, -104.7834]}}
{"dataset": "Lightning","observation_date": "20170516004436356", "location": { "type": "point", "coordinates": [46.4559, -104.5989]}}

where I have to append a 'dataset':'lightning' key/val pair, combine and strip the date and time, and combine the lat/lng into a dict before doing any json conversion.

But right now I still get the date and time elements without being stripped of the "-" and ":" characters like:

{"observation_date": "2017-05-1600:44:36.151724381", "location": {"type": "point", "coordinates": ["+43.8187", "-104.7669"]}, "dataset": "Lightning"}
{"observation_date": "2017-05-1600:44:36.246672534", "location": {"type": "point", "coordinates": ["+41.6321", "-104.7834"]}, "dataset": "Lightning"}
{"observation_date": "2017-05-1600:44:36.356132768", "location": {"type": "point", "coordinates": ["+46.4559", "-104.5989"]}, "dataset": "Lightning"}

What I coded so far:

import json
import sys
def convert(filename):
    dataDict = {}
    txtFile = filename[0]
    print "Opening TXT file: ",txtFile
    infile = open(txtFile, "r")
    for line in infile:
        lineStrip = line.strip()
        parts = [p.strip() for p in lineStrip.split()]
        date = parts[0].strip("-") #trying to get rid of "-" but not working
        time = parts[1].strip(":") #trying to get rid of ":" and "." but not working
        dataDict.update({"dataset":"Lightning"})
        dataDict.update({"observation_date": date + time})
        dataDict.update({"location": {"type":"point", "coordinates": [parts[2], parts[3]]}})
        json_filename = txtFile.split(".")[0]+".json"
        jsonf = open(json_filename,'a')
        data = json.dumps(dataDict)
        jsonf.write(data + "\n")
        print dataDict
    infile.close()
    jsonf.close()
if __name__=="__main__":
    convert(sys.argv[1:])

But I'm not sure how to strip the "-", ".", and ":" as well as place the "dataset":"lightning" element in the front.

Body:
You should do:

date = parts[0].replace('-', '')
   time = parts[1].replace(':' '')

To get the dataset up front in JSON, the only option you have is sort the keys:

data = json.dumps(dataDict, sort_keys=True)

You should also consider doing

dataDict["dataset"] = "Lightning"

instead of the .update.