text:
Q: Java parallel stream performance While toying with the new Java streams, I have noticed something strange related to the performance of parallel streams. I've used a simple program that reads the words from a text file and counts the words having length > 5 (the test file has 30000 words):
    String contents = new String(Files.readAllBytes(Paths.get("text.txt")));
    List<String> words = Arrays.asList(contents.split("[\\P{L}]+"));
    long startTime;
    for (int i = 0; i < 100; i++) {
        startTime = System.nanoTime();
        words.parallelStream().filter(w -> w.length() > 5).count();
        System.out.println("Time elapsed [PAR]: " + (System.nanoTime() - startTime));
        startTime = System.nanoTime();
        words.stream().filter(w -> w.length() > 5).count();
        System.out.println("Time elapsed [SEQ]: " + (System.nanoTime() - startTime));
        System.out.println("------------------");
    }

This generates the following output on my machine (I mention only the first and the last 5 loop iterations):
Time elapsed [PAR]: 114185196
Time elapsed [SEQ]: 3222664
------------------
Time elapsed [PAR]: 569611
Time elapsed [SEQ]: 797113
------------------
Time elapsed [PAR]: 678231
Time elapsed [SEQ]: 414807
------------------
Time elapsed [PAR]: 755633
Time elapsed [SEQ]: 679085
------------------
Time elapsed [PAR]: 755633
Time elapsed [SEQ]: 393425
------------------
...
Time elapsed [PAR]: 90232
Time elapsed [SEQ]: 163785
------------------
Time elapsed [PAR]: 80396
Time elapsed [SEQ]: 154805
------------------
Time elapsed [PAR]: 83817
Time elapsed [SEQ]: 154377
------------------
Time elapsed [PAR]: 81679
Time elapsed [SEQ]: 186449
------------------
Time elapsed [PAR]: 68849
Time elapsed [SEQ]: 154804
------------------

Why is the first processing 100 times slower than the rest? Why is the parallel stream slower than the sequential one in the first iterations but it is twice as fast in the last iterations? Why do both the sequential and parallel streams become faster over time? Is this related to loop optimization?
Later edit: At Luigi's suggestion, I implemented the benchmark using JUnitBenchmarks:
List<String> words = null;

@Before
public void setup() {
    try {
        String contents = new String(Files.readAllBytes(Paths.get("text.txt")));
        words = Arrays.asList(contents.split("[\\P{L}]+"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@BenchmarkOptions(benchmarkRounds = 100)
@Test
public void parallelTest() {
    words.parallelStream().filter(w -> w.length() > 5).count();
}

@BenchmarkOptions(benchmarkRounds = 100)
@Test
public void sequentialTest() {
    words.stream().filter(w -> w.length() > 5).count();
}

I also bumped up the number of words from the test file to 300000. The new results are:

Benchmark.sequentialTest: [measured 100 out of 105 rounds, threads: 1
  (sequential)]
round: 0.08 [+- 0.04], round.block: 0.00 [+- 0.00], round.gc: 0.00 [+-
  0.00], GC.calls: 62, GC.time: 1.53, time.total: 8.65, time.warmup: 0.81, time.bench: 7.85
Benchmark.parallelTest: [measured 100 out of 105 rounds, threads: 1
  (sequential)]
round: 0.06 [+- 0.02], round.block: 0.00 [+- 0.00], round.gc: 0.00 [+-
  0.00], GC.calls: 32, GC.time: 0.79, time.total: 6.82, time.warmup: 0.39, time.bench: 6.43

So it seems that the initial results were caused by a wrong microbenchmark configuration...

A: The Hotspot JVM starts executing the program in interpreted mode, and compiles frequently used parts to native code after some analysis. The initial iterations of loops are generally slow because of this.


text:
Q: Extracting domain logic from the forms to which they are coupled? Many applications do nothing to separate the interface from domain logic.  I've been programming for a couple decades and have worked at more than a dozen shops and none of them have taken any measure of separating the interface from the domain logic.  That is, they're all using the Autonomous View pattern.   This runs counter to all the wisdom I've read about separating concerns.  When the user needs to choose an item from a set of items, that selection is directly tied to a combo box rather than an abstraction.
A huge drawback with all this coupling is that it makes it impossible to write unit tests.  To run any unit tests the application in its entirety must first be loaded.  In my mind, the use case should be encapsulated within an abstraction that can later have a database and an interface attached to it.  This kind of separation would make implementing unit tests trivial by comparison.
Given that the average shop has its interface and domain logic tightly coupled, how to we refactor to separation?  That is, a complete rewrite is off the table. What I'm talking about is taking a proposal to management about how to go about creating domain objects (whatever these happen to look like) that live in isolation from the database and the interface. In other words, it would be useful to be able to explain how this concept of presenting the user with a choice (something that is now represented by combos on forms) and to see how some methodology/framework/pattern represents that in an abstract sense and how that abstraction is then tied to the interface.  This would make replacing combos with listboxes nothing more than a slight detail.
What are some good ways for extracting abstractions (domain use cases) from forms?  Any good online resources?  My current shop is on .NET, though I am interested in ideas from any development platform.  Ultimately, what I need to provide is a concrete example (code) of how this might be accomplished.

A: There are a variety of presentation patterns whose exact role is to split out the interface from the behaviour.
Since you specifically mention a Microsoft environment, I would recommend you look up MVVM (which is promoted with particular reference to WPF) and MVC (which is promoted re ASP.NET). Microsoft's MVC approach is a physical framework based closely on the generic MVC pattern - it breaks a few abstractions but auto-produces code for you.
A further approach, also promoted by Microsoft until they jumped on the WPF bandwagon, is the MVP pattern.
In theory all three of these patterns, being patterns, are applicable arcoss any platform. But MVVM was definitely developed with WPF in mind, and as I say Microsoft's implementation of MVC deviates from the "pure" a little.
There are more, but as I say they're all broadly aimed at pulling logic out of the UI layer. Martin Fowler's web site is a decent reference here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i search a value in Ruby Hash Table? area_dictionary = {
  "Alabama" => "205",
  "Alaska" => "907",
  "American Samoa" =>"684",
  "Arizona" => "480",
  "Arkansas" => "479",
  "California" => "209",
  "Colorado" => "303",
  "Connecticut" => "203",
  "Delaware" => "302",
  "Florida" => "239",
  "Georgia" => "229",
  "Guam" => "671",
  "Hawaii" => "808"
}

def get_city_name(hash,key)
    hash.each{|k,v|puts k if v==key}
end
    puts"Please enter the code for which you want to find the city?"
    code = gets.chomp
    if area_dictionary.include?(code)#getting trouble from here
      puts "The city for #{code}is#{get_city_name(area_dictionary,code)}"
    end

A: If you are trying to find the key for a value, you can use the following:
area_dictionary.invert['239']
=> "Florida"

If you are simply trying to get the value for a given key, you can use the following:
area_dictionary['Florida']
=> "239"

A: Some self-explanatory examples
area_dictionary["Alaska"]
 => "907"
area_dictionary["Alaskaaaa"]
 => nil
area_dictionary.fetch("Alaska")
 => "907"
area_dictionary.fetch("Alaskaaaa")
 KeyError: key not found: "Alaskaaaa"
    from (irb):5:in `fetch'
    from (irb):5
    from /usr/local/bin/irb:11:in `<main>'
area_dictionary.fetch("Alaskaaaa", 10)
 => 10
area_dictionary.values_at("Alabama", "Alaska")
 => ["205", "907"]


text:
Q: undefined reference to `cJSON_Parse' I am using Azure SDK. In the SDK I have included cJSON functionalities, I know I need to link cJSON.h to my code. But in azure makefile, I am finding it difficult. Do help in linking the cJSON header file.

A: You could add the json library to the makefile to solve this problem.
Add
-ljson   \

to the linkflags in the makefile in the app directory and then was able to successfully compile.
Here is the similar thread.


text:
Q: query a manytomany realted field I have a model like the following:
GRN Model:
class GrnItems(models.Model):
    item = models.ForeignKey(Product, on_delete=models.CASCADE)
    item_quantity = models.IntegerField(default=0)
    item_price = models.IntegerField(default=0)
    label_name = models.CharField(max_length=25, blank=True, null=True)

class Grn(models.Model):

    reference_no = models.CharField(max_length=500, default=0)
    inward_date = models.DateTimeField(blank=True, null=True)
    items = models.ManyToManyField(GrnItems)

How can I query the GrnItems to get item_quantity which has product = 5 and connected to grn = 103?

A: You can filter with:
GrnItems.objects.filter(item_id=5, grn__pk=103)
Here the grn will query the ManyToManyField in reverse.


text:
Q: Type error when use apex.amp O1 in PyTorch When I try to use NVIDIA apex.amp O1 to accelerate my training, it report an error in my code logits = einsum('b x y d, r d -> b x y r', q, rel_k):

RuntimeError: RuntimeErrorRuntimeErrorexpected scalar type Half but found Float: :
expected scalar type Half but found Float

It means that rel_kshould be torch.HalfTensor.
rel_k is defined as follow: self.rel_height = nn.Parameter(torch.randn(height * 2 - 1, dim_head) * scale)
But when I specify the type of rel_kto be torch.HalfTensor, it report an error that I should not specify dtype manually

RuntimeErrorRuntimeError: : Found param encoder.layers.0.blocks.0.attn.rel_pos_emb.rel_height with type torch.cuda.HalfTensor, expected torch.cuda.FloatTensor.
When using amp.initialize, you do not need to call .half() on your model
before passing it, no matter what optimization level you choose.Found param encoder.layers.0.blocks.0.attn.rel_pos_emb.rel_height with type torch.cuda.HalfTensor, expected torch.cuda.FloatTensor.
When using amp.initialize, you do not need to call .half() on your model
before passing it, no matter what optimization level you choose.

How should I do to use amp O1 correctly in my code?


text:
Q: Boto3 - botocore.errorfactory.NotAuthorizedException Using boto3 and warrant in python3. Headless system. Trying to login using a python script using ASWSRP from warrant. With user pool there is the problem of changing the temporary password. So... I have the code trying the temp password first and when the fails it switches over to trying the permanent password. I am running into a couple different issues:
1) After I get the temporary password changed and I run the script again I get the exception:

botocore.errorfactory.NotAuthorizedException

I can't seem to import that exception from boto3 or botocore. How do I capture that exception?
2) I am sometimes getting a too many passwords attempted.

An error occurred (NotAuthorizedException) when calling the
  InitiateAuth operation: Password attempts exceeded

Obviously I need to wait a certain time period. Does anybody know what that is? Is that time period setable in my user pool or account?
Code:
import boto3
from warrant.aws_srp import AWSSRP
from warrant.exceptions import ForceChangePasswordException

userName = 'XXXXXXXX'
tempPassword = 'XXXXXXXX'
poolId = 'us-east-1_XXXXXXXX'
poolRegion = 'us-east-1'
clientId = 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
#clientSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
client = None
finalPassword = "YYYYYYYYY"

try:
    client = boto3.client('cognito-idp')
    aws = AWSSRP(
        userName,
        tempPassword,
        poolId,
        clientId,
        client=None)
    tokens = aws.authenticate_user()
except ForceChangePasswordException:
    aws.set_new_password_challenge(finalPassword, client=None)
    aws = AWSSRP(
        userName,
        finalPassword,
        poolId,
        clientId,
        client=None)
    tokens = aws.authenticate_user()
except Exception as e:
    print(str(e))

Also, i'd rather just try the final password first, if that does not work then use the temp password, change the password and then retry the final password. I'd still have to get past the:

botocore.errorfactory.NotAuthorizedException

A: To answer your first question (how to capture the boto3 exception), you have to call it via the CognitoIdentityProvider Client object:
import boto3
from warrant.aws_srp import AWSSRP

...

try:
    client = boto3.client('cognito-idp')
    aws = AWSSRP(
            userName,
            tempPassword,
            poolId,
            clientId,
            client=None)
    tokens = aws.authenticate_user()
except client.exceptions.NotAuthorizedException as e:
    print("error: {}".format(e))
    ...

For any method within boto3 that you call, you can find the full list of Exceptions in the Cognito Identity Provider API reference, under the 'Errors' section of the method you're using.
For example, NotAuthorizedException is only one of the several errors you could encounter when calling aws.authenticate_user, because warrant is making a call to Initiate_Auth, which has it's errors listed here.
Hope that helps.


text:
Q: On Board Unit communication via RS485 I've heard of On Board Units (OBU) can communicate via RS485.
My question is, how?
For example, I would like to ask the state of some runtime variables from the OBU (what doors are open?, etc.)
Or another example, I would like to send some data to the OBU (outside temperature).
What protocol must I implement to do these? Are the any sample implementations available somewhere?
Thanks,
krisy


text:
Q: Conditional operations with dplyr in R I have the following data frame df
CustID  Mode_Payment Payment      Expiry       Amount
100      ECS         2015-01-01   2015-03-01    1000
200      Online      2015-01-01   2015-05-01    2000
100      ECS         2015-01-01   2015-10-01    3000
300      Cash        2015-01-01   2015-05-01    5000

I want to calculate a new field subscription period which is period<-as.numberic(expiry-payment).
But, when the Mode of payment is ECS then period should be calculated by the following formula :
group_by(CustID)
period<-max(expiry)-min(payment)
ugroup()

So for the above data set output should be
CustID  Mode_Payment       Payment      Expiry      Amount   Period
    100      ECS         2015-01-01   2015-03-01    1000      273
    200      Online      2015-01-01   2015-05-01    2000      120
    100      ECS         2015-01-01   2015-10-01    3000      273
    300      Cash        2015-01-01   2015-05-01    5000      120

Unfortunately, I'm getting all kind of errors.
df<-df %>%
  group_by(custid) %>%
  if(mode_payement=='ECS') {mutate(period=(as.numeric(max(expiry)-min(payement))))
                      } else mutate(period=as.numeric((expiry-payment)))  %>%
  ungroup()

A: I modified your data a bit in case you have ECS and something else for a customer ID. I chose to use subsetting rather an using ifelse in my approach.
You have one operation for data with ECS only and the other for the rest.
DATA & CODE
mydf <- read.table(text = "CustID  Mode_Payment Payment      Expiry       Amount
100      ECS         2015-01-01   2015-03-01    1000
200      Online      2015-01-01   2015-05-01    2000
100      ECS         2015-01-01   2015-10-01    3000
300      Cash        2015-01-01   2015-05-01    5000
100      Online         2015-01-01   2015-07-01    7000", header = T, stringsAsFactors = FALSE)

  CustID Mode_Payment    Payment     Expiry Amount
1    100          ECS 2015-01-01 2015-03-01   1000
2    200       Online 2015-01-01 2015-05-01   2000
3    100          ECS 2015-01-01 2015-10-01   3000
4    300         Cash 2015-01-01 2015-05-01   5000
5    100       Online 2015-01-01 2015-07-01   7000

library(dplyr)
library(data.table)

#Set Payment and Expiry as Date.
setDT(mydf)[, c("Payment", "Expiry") := lapply(.SD, as.IDate), .SDcols = 3:4]

x <- mydf[Mode_Payment == "ECS"][, period := max(Expiry) - min(Payment), by = CustID]

y <- mydf[Mode_Payment != "ECS"][, period := Expiry - Payment, by = CustID]

rbindlist(list(x, y))

#   CustID Mode_Payment    Payment     Expiry Amount   period
#1:    100          ECS 2015-01-01 2015-03-01   1000 273 days
#2:    100          ECS 2015-01-01 2015-10-01   3000 273 days
#3:    200       Online 2015-01-01 2015-05-01   2000 120 days
#4:    300         Cash 2015-01-01 2015-05-01   5000 120 days
#5:    100       Online 2015-01-01 2015-07-01   7000 181 days

### dplyr way

filter(mydf, Mode_Payment == "ECS") %>%
group_by(CustID) %>%
mutate(period = max(Expiry) - min(Payment)) -> x

filter(mydf, Mode_Payment != "ECS") %>%
mutate(period = Expiry - Payment) -> y

bind_rows(x, y)

A: Or dplyr with ifelse:
data %>%
  group_by(CustID) %>%
  mutate_each(funs(as.Date), Expiry, Payment) %>%
  mutate(period =
           (Mode_Payment == "ECS") %>%
           ifelse(
             max(Expiry) - min(Payment),
             Expiry - Payment) )


text:
Q: Why does function call from PS1 require escaping? I'm setting my prompt inside of .bash_profile like this
export PS1="\w\$(getBranchName)\n ---->"

My getBranchName function exists, and this works, fine.
My question is, why do I need to escape the call to getBranchName like this \$(getBranchName).
In other words, why doesn't this code work, instead?
export PS1="\w$(getBranchName)\n ---->"

If curious, this is what the getBranchName function looks like
esc="\033"
redf="${esc}[31m"
green="${esc}[32m"
purple="${esc}[35m"
cyanf="${esc}[36m"
reset="${esc}[0m"

getBranchName() {
  if [[ "$(__git_ps1 '%s')" == "master" ]]
  then
    echo -e "${redf}$(__git_ps1)${reset}";
  else
    echo -e "${cyanf}$(__git_ps1)${reset}";
  fi
}

export PS1="\w\$(getBranchName)\n ---->"

A: You need to escape the dollar because you want to store this exact text in your variable.
Try it by typing echo "$PS1". You should see the exact text : \w$(getBranchName)\n ---->
If you didn't escape it, the function would be evaluated only once, during the allocation.

The bottom line is that PS1 is a special variable : every time you display a new line in the console, the variable is evaluated to extract the display settings.

A: The PS1 variable is basically a template string (which might contain function calls) which is evaluated each time the prompt is shown.
If you want to evaluate a function each time, so that each prompt shows the result of this new execution, you need to escape the call.
If you would embed the function call directly in the string, the function would be called once immediately (i.e. likely during login) and your PS1 will contain the result of this single function call as evaluated during your initial login. Thus, the value won't be updated again since the function is not called anymore (since the PS1 doesn't contain the function call anymore but only the static result of one).

A: It's escaped because you want it to run when the shell evaluates $PS1 each time it's displayed, not just during the assignment.
The other expansions (which should be using tput unless you actually like random control codes all over your non-ANSI terminals) you want to be expanded just once, when you assign to PS1.


text:
Q: Define filters order I'm trying to code some filters for a text processor. I receive from a socket files that I have to process line by line. For each line I need to apply some filters and in an specific order. For example, for one file I'll use filter 1, filter 2, filter 3 and after that filter 2 again.
My question is what is the best way to run this filters in an specific order and how to define them so I can add more filters without have to change a lot of code? What is the best way to ensure a high speed executing this filters line by line?

A: I would use probably chain of responsibility.
I assume a filter says either true (include/accept the line),
or false (do not include i.e. reject this line).
So chain several filters in a chain, if filter 1 returns true,
then pass the line to the next filter 2 (and so on). Otherwise
(if any filter from the chain says false), reject the line and
don't go checking with the next filter from the chain.
chain of responsibility pattern
What is the best way to ensure a high speed
executing this filters line by line?
This depends on too many factors so
it is hard to give a response on it.

A: This is quite similar to Servlet Filters, except that you want to be able to apply the same filter multiple times.
As others have suggested Chain of Responsibility might be appropriate, especially if a filter needs to have the ability to abort further execution of other filters and needs an "around" control, i.e. it wants to do some processing before the rest of the chain does it thing and do some other processing after.
But to me what seems more important is to separate out the notions of individual filter and a chain which is the arrangement of the filters in a chain (or sequence).
I am thinking of unix pipes. Each Filter does its own thing, without knowing where its input comes from and who consumes its output.
A Controller component creates the chains as necessary, I don't know whether a single chain applies to all files, or there are is fixed set of chains one of which is chosen in some way for each file, or a new chain is created for each file.
FilterChain applies the filters. If you are following Chain of Responsibility pattern then it only has to invoke the first (top) filter otherwise it has to iterate through all filters in the chain.


text:
Q: GWT - Datagrid : Keyboard single selection, when multi selection is enabled When I enable keyboard selection policy and multi selection on DataGrid I encountered this problem.
Case 1 : Multi selection through mouse and keyboard
When I want to select more than one row through mouse, I hold Ctrl key or Shift key and this works fine. Through keyboard by default, this action is provided by spacebar. When I want to select serially through keyboard combination of shift key and spacebar does the trick.
Case 2 : Single selection through mouse and keyboard (This is where the problem starts)
When I want to select a single row through mouse, I just do a left click. If I don't hold either of ctrl of shift key and do a left click, even if the multiple rows are selected, it will get deselected and only the current row gets selected. This is the expected behavior and I don't have any issue with it.
But the same thing is not achievable through keyboard. There is no way to select a single row through keyboard. If I press spacebar a row gets selected and if I press the spacebar again on some other row without shift/ctrl key, it gets multi selected and previous selected row doesn't get deselected.
My question is : How to achieve single selection through keyboard similar to that of mouse?
EDIT : I opened this issue in gwt issues. I hope they respond to this.

A: You have to use a custom selection event manager whose translator returns the appropriate value for the behavior you want from clearCurrentSelection.
The default behavior is to always add/remove from selection from the keyboard, and use the control or meta key to toggle whether to clear the current selection when using the mouse.


text:
Q: Calculate rolling price change in a dataframe, based on pairs of dates in another dataframe I am trying to write a function that calculates the daily change of a trade position between an entry and exit date (with corresponding entry and exit prices).
I have two dataframes:
Daily prices of the traded asset:
daily_prices_df:

Date        Close
2014-01-02  885.0
2014-01-03  880.0
2014-01-06  873.0
2014-01-07  871.0
2014-01-08  870.0
2014-01-09  862.0
2014-01-10  861.0
2014-01-13  850.0
2014-01-14  862.0
2014-01-15  859.0

A ordered dataframe of trades, whose records are entry-exit pairs, in the order entry date, entry price, exit date, exit price:
trades_df:
Date            Price
0   2014-11-18  495.7
1   2014-11-24  484.2
2   2014-11-26  474.1
3   2014-12-31  507.9
4   2015-01-05  495.9
5   2015-02-05  456.2
6   2015-02-24  461.5
7   2015-03-06  415.4
8   2015-03-31  368.5
9   2015-04-30  375.6

I need a function that can calculate the daily value of the trade with respect to the current asset price between the trade entry date, and the exit date.
I have tried a brute force method of iterating over each row of each dataframe with df.iterrows() and comparing the dates, but my logic doesn't seem to quite work out currently as I need to iterate in pairs for the trades data, and individually for the curves?
Expected outcome:
A column that shows the difference, for each day, between the trade entry price and the current price:
entry_date_1 = trades_df.loc[0]
exit_date_1 = trades_df.loc[1]

daily_prices_df

Date        Close   Price_Diff
2014-11-18  496.0   1
2014-11-19  484.0   -11
2014-11-20  487.0   8
2014-11-21  495.0   0
2014-11-24  484.0   -11
2014-11-25  470.0   -25

All help gratefully received, thank you


text:
Q: How can I fix this Nested For Loop script (R) to estimate Model Ages I'm new to R (and coding in general). The data itself is taken from lead isotope analysis and are lead isotopes.
I was hoping to create a nested for loop which compared the output of an equation to a vertex of integers calculated from sample data.
I can see two issues but I don't know how to address them:
(1): '1:length(num_intervals))' references an integer but perhaps should be a series or a list (?)
(2): the output of the loop overwrites the ModelAge function.
Any help would be much appreciated.

#Data for Testing. For obvious reasons, I can't include all my data but here are some samples to create a sample file to compile:

47      18.54400       15.590       38.427
48      18.55900       15.580       38.403
49      18.48100       15.600       38.407
50      18.37400       15.614       38.293
51      19.23800       15.673       37.272
52      18.14200       15.649       38.137
53      18.52500       15.590       38.430
54      18.55000       15.597       38.468
55      18.59200       15.662       37.972
56      18.59500       15.662       37.972
57      18.50000       15.594       38.402

#Model Age Estimations
rm(list = ls())
#library(dplyr)

#assumptions

#growth constant assumptions
decay_constant_u238 <- 1.55125E-10
decay_constant_u235 <- 9.8485E-10
decay_constant_th232 <- 4.9475E-11

#time assumptions
age_of_earth_t0 <- 4.57E9
age_of_earth_t1 <- 3.7E9

#Isotopic Assumptions - Stage 1
s1_206PB.204PB <- 9.307
s1_207PB.204PB <- 10.294
s1_208PB.204PB <- 29.476

#Isotopic Assumptions - Stage 2 (Stacey & Kramer 1975)
s2_206PB.204PB <- 11.152
s2_207PB.204PB <- 12.998
s2_208PB.204PB <- 31.230

#Isotopic Proportion Assumptions - Stage 1 (Stacey & Kramer 1975)
s1_u <- 7.19
s1_w <- 32.21
s1_k <- 4.479833102

#Isotopic Proportion Assumptions - Stage 2 (Stacey & Kramer 1975)
s2_u <- 9.74
s2_w <- 37.19
s2_k <- 3.818275154

#µ or 238U/204Pb Estimates
uranium_lead_ratio_estimates <- matrix(6:12, nrow=7, ncol=1)

#slope
slopes <-(values_207.204-s2_207PB.204PB)/(values_206.204-s2_206PB.204PB)*137.88

model_age <- data.frame(A=ingots$X206Pb.204Pb, B=ingots$X207Pb.204Pb, C=ingots$X208Pb.204Pb, Slopes=slopes, ModelAge = 1:length(ingots$X206Pb.204Pb))

#Calculated Ages
Ages_new <- 1:4 *10000000
last <- Ages_new[length(Ages_new)]
add_val <- 10000000
n_adds <- 70
Ages <- cumsum(c(last, rep(add_val, n_adds)))

#Function
ModelAgeFunction <- function(Ages){
  (exp(decay_constant_u235*age_of_earth_t1)-exp(decay_constant_u235*Ages))/(exp(decay_constant_u238*age_of_earth_t1)-exp(decay_constant_u238*Ages))
}

#Iteration
lower_bound <- 0
upper_bound <- 700000000
num_intervals <- 70
interval_width <- (upper_bound - lower_bound) / num_intervals

#Vector of Slopes
slopes <- model_age$Slopes

#Integration
for (i in 1:length(slopes))
{
  for (j in 1:length(num_intervals))
  {
    left_bound <- lower_bound + interval_width*(i-1)
    if (slopes[i] < ModelAgeFunction(left_bound + interval_width / 2))
    {
      model_age$ModelAge[j] <- (left_bound + interval_width / 2)
      break
    }

  }
}


text:
Q: Using Property Setter In __init__ How do I use a Property setter in __init__ without pylint complaining that the attribute has been defined outside __init__?
For example, the following code only produces one exception which is caught in the try clause at the bottom.
class CircleNotUsingSetterInInit(object):

    def __init__(self, radius):
        # Notice underscore in 'self.radius
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, radius):
        if radius < 0:
            raise ValueError("Radius must be non-negative")
        self._radius = radius

class CircleUsingSetterInInit(object):

    def __init__(self, radius):
        # Notice lack of underscore in 'self.radius'
        self.radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, radius):
        if radius < 0:
            raise ValueError("Radius must be non-negative")
        # From pylint:
        # Attribute '_radius' defined outside __init__ (attribute-defined-outside-init)
        self._radius = radius

CircleNotUsingSetterInInit(5)
CircleNotUsingSetterInInit(-1)
CircleUsingSetterInInit(5)
try:
    CircleUsingSetterInInit(-1)
except ValueError:
    print("caught exception")

I'm using Python 2.7.10.

A: The warning is completely safe to ignore in this case. Pylint just doesn't "see" that, it's rather complex to notice without doing syntax parsing.
You can add a comment for pylint to disable this warning locally like this:
class CircleUsingSetterInInit(object):

    # ....

    @radius.setter
    def radius(self, radius):
        if radius < 0:
            raise ValueError("Radius must be non-negative")
        # pylint: disable=W0201
        self._radius = radius

W0201 is the code for attribute-defined-outside-init, which is the warning you receive according to the docs. You should always add such disable comments as close to the source as possible, so that pylint works normally for the rest of the file.


text:
Q: WIX Help Random start in slide deck gallery THE SETUP
On my WIX site I have:

*

*a collection called Ads980x120 with a few entires (ads and links)

*a dataset on the page linked to that collection

*a 980p x 120p slide deck gallery linked to that dataset (image field and link field)

It currently works perfectly rotating those images on the site.
THE PROBLEM
I do not want the same image to show and start the rotation when the page loads. I want the images to be shown in a random order. This could be option #1: A random starting image and then continuing in the same order, or option #2 a random starting image AND random order. Either one would be fine based on difficulty level.
Lastly, there are some pages that have a couple different galleries so ideally I would be able to paste this code multiple times on the page (once for each gallery) and I would like the links to open into new windows.
I hope this makes sense and thank you in advance for any advice or help!

A: This is pretty simple to do if you don't mind a little flicker. Using a dataset you can load the gallery and then randomize the images, but you will see the original order for a short bit.
To do this without that kind of flicker, I think you need to use the wix-data API.
Here's the code I came up with. You will have to modify it to fit your collection name and structure as well as your gallery ID. I am also using the Lodash npm module to randomize the order of the images, but you could write this code yourself. Finally, you need to remove all the default images from the gallery. All that being said, you will still have a flicker, but from a blank gallery to one with a random image.
import {rendering} from 'wix-window';
import wixData from 'wix-data';
import _ from 'lodash';

$w.onReady( async () => {
    if(rendering.env === 'browser') {
        const {items} = await wixData.query('CollectionId').find();
        const images = items.map(item => ({src: item.image, title: item.title}));
        const shuffledImages = _.shuffle(images);
        $w('#galleryId').items = shuffledImages;
    }
} );


text:
Q: luabridge bind C++ member, but not change member value I have a question by using luabridge, it change C++ value fail, for exam:
//c++ files
struct Coor3D_1 {
    int lon;
};
class ETALink{
public:
ETALink()
{

}
Coor3D_1 coor3D_1;
};

bind code is below:
luabridge::getGlobalNamespace(L)
.beginNamespace("test")
.beginClass<Coor3D_1>("Coor3D_1")
.addData("lon", &Coor3D_1::lon)
.endClass()

.beginClass<ETALink>("ETALink")
.addConstructor<void(*) (void)>()
.addData("coor3D_1", &ETALink::coor3D_1)
.endClass()
.endNamespace();

lua files is below:
eta = test.ETALink();
print("---- ", eta.coor3D_1.lon); //this is OK, I can see eta.coor3D_1.lon
eta.coor3D_1.lon = 11 //?? this is not OK, I print  eta.coor3D_1.lon is not 11

now my question is why eta.coor3D_1.lon = 11 not work?
I find that double "." will not work....

A: This happens because your class field member (coor3D_1) is passed to Lua as a copy, so when you change its value you change the copy, and the original object is not affected.
Probably you can solve the issue one on these ways:

*

*Add an ETALink property which directly operates on the lon field.

*Make coor3D_1 a property returning a pointer to the Coor3D_1 structure.


text:
Q: python Save the output of a shell command into a text file I want to save the output of a shell command into a textfile via python. This is my actual, pretty basic python code:
Edit here is the final script, thank you for your help :)
import subprocess

ip_adress_4 = 0
pr = open("pointer_record.txt", "w")

while (ip_adress_4 < 255):
    ip_adress_4 = ip_adress_4 + 1
    ip_adress = '82.198.205.%d' % (ip_adress_4,)
    subprocess.Popen("host %s" % ip_adress, stdout=pr, shell=True)

A: Use subprocess.check_output instead of Popen That will give you a string back containing the output, which you can then write out to the file.

A: Try something like this:
import subprocess
file_ = open("ouput.txt", "w")
subprocess.Popen("ls", stdout=file_)

EDIT: Matching your needs
import subprocess

file_ = open("ouput.txt", "w")
subprocess.Popen(["host", ipAddress], stdout=file_)


text:
Q: SonaType Nexus NuGet proxy 404 when forwarding to another Nexus We have 2 Nexus SSO servers with NuGet proxy repositories. One is in our private network environment (v3.0.0), the other is within the DMZ (v3.0.1) with internet access.
A request first gets sent to the private Nexus server that forwards the request to the Nexus server in the DMZ, which in turn forwards the request to the outside nuget.org repository. So basically:
client -> private proxy -> dmz proxy -> internet.
Using this method, the client get's an error Unable to find package. From the logs on the private proxy, I see that it forwards the request to the dmz proxy as
http://dmzproxy/repository/NuGetRepository/FindPackagesById?id='angularjs'
but receives a 404 not found.
Troubleshooting the issue, I tried to bypass the private proxy by running nuget.exe straight from that server, which would be:
client -> dmz proxy -> internet
This method actually works, and from using nuget.exe with -Verbosity detailed, I can see that nuget.exe sends a slightly different request to the dmz proxy than the private proxy does:
http://dmzproxy/repository/NuGetRepository/FindPackagesById()?id='angularjs'
Compare that with the request sent by Nexus, you can see that the difference is the parentheses () after FindPackagesById. So, for testing, I copy/pasted both request URL's in a browser window and indeed, without parentheses I get a 404, with parentheses I get a package feed page.
So, Nexus does work with parentheses when serving NuGet, but doesn't seem to apply them when forwarding a request to another Nexus server, causing a 404 reponse.

A: After further testing and contact with SonaType support, I've found that Nexus 3.0.0 and 3.0.1 indeed don't support request with FindPackagesById? without the parentheses, even though that is exactly the way Nexus itself forwards requests.
The latest Nexus version (currently 3.2.1), while still forwarding requests without parentheses, does support both ways. So, updating all Nexus servers to the latest version should solve this issue.
Within this particular organization updating is easier said than done. So in the meantime, I have configured a reverse proxy with a rewrite rule, that forwards request from the private Nexus server to the Nexus server in DMZ and rewrites "FindPackagesById?" to "FindPackagesById()?". Not an ideal situation but a working temporary solution until all Nexus servers are updated.


text:
Q: React native first start of app gives a undefined is not an object, state loads too late I'm currently implementing another API call with Axios using redux. I have already the data coming in the view that I want to. But, there is strange behaviour. When I'm loading the data with for example data.userName, the view loads. But when I'm then in another view calling an array, for example data.users.map(....) it gives me every time an undefined is not an object. Also when I console logging the API request it first loads all the views, getting the error and then the data loads (but too late, already getting an error). When I'm removing the data.users.map(...) call, reloading the app that the data loads and then paste the code again in, the app works fine. I'm really stuck here on why I'm loading the data so late.
I'm working with redux and Axios.
Here is the actions file and reducer file:

export const GET_DATA_BEGIN = "GET_DATA_BEGIN"
export const GET_DATA_SUCCESS = "GET_DATA_SUCCESS"
export const GET_DATA_FAILURE = "GET_DATA_FAILURE"

export const getDataBegin = () => ({
    type: GET_DATA_BEGIN
})

export const getDataSuccess = (data) => ({
    type: GET_DATA_SUCCESS,
    payload: {data}
})

export const getDataFailure = (error) => ({
    type: GET_DATA_FAILURE,
    payload: {error}
})

export function getData() {
    return dispatch => {
        dispatch(getDataBegin())
        let ApiUrl = `https://hereissomeurlfordata`
        return axios({
            url: ApiUrl,
            method: 'GET',
            header: {
                Accept: "application/json"
            }
        }).then((response) => {
            if (response.status === 200) {
                dispatch(getDataSuccess(response.data))
                console.log(response)
            } else {
                dispatch(getDataFailure(response.data))
            }
        }).catch((error) => {
            dispatch(getDataFailure(error))
        })
    }
}

const initialState = {
    data: {},
    error: null,
    loading: false
}

const xchReducer = (state = initialState, action) => {
    switch (action.type) {
        case xchActions.GET_DATA_BEGIN:
            return {
                ...state,
                loading: true
            }
        case xchActions.GET_DATA_SUCCESS:
            return {
                ...state,
                data: action.payload.data
            }
        case xchActions.GET_DATA_FAILURE:
            return {
                ...state,
                error: action.payload.error
            }
            default:
            return state
    }
}

export default xchReducer;

And here is the home file

const Home = ({
    getData,
    data
  }) => {
    useFocusEffect(
      React.useCallback(() => {
        getData()
      }, [])
    )

    function renderHeaderContent() {
      return ( <
        View style = {
          {
            flexDirection: 'row',
            justifyContent: 'flex-start',
            ...Platform.select({
              ios: {
                paddingTop: 40
              }
            })
          }
        } >
        <
        View style = {
          {
            marginTop: 10,
            justifyContent: 'center',
            alignItems: 'center',
            alignContent: 'center',
            flex: 1
          }
        } >
        <
        Text > {
          data.userName
        } < /Text> <
        /View> <
        /View>
      )
    }

    // here is the error, so when I'm removing this part, reloading the app and then pasting it again it works.
    const data = {
      datasets: [{
        data: [...data.users.map(d => d.points)],
        strokeWidth: 2 // optional
      }]
    };

    funtion renderChartContent() {
      return ( <
        View >
        <
        LineChart data = {
          data
        }
        width = {
          screenWidth
        }
        height = {
          256
        }
        verticalLabelRotation = {
          30
        }
        chartConfig = {
          chartConfig
        }
        withInnerLines = {
          0
        }
        bezier /
        >
        <
        View >
      )
    }

    return ( <
      View style = {
        {
          flex: 1,
          backgroundColor: COLORS.white
        }
      } >
      {
        renderHeaderContent()
      } {
        renderChartContent()
      } <
      /View>
    )

    function mapStateToProps(state) {
      return {
        data: state.xchReducer.data,
        error: state.xchReducer.error,
        loading: state.xchReducer.loading,
      }
    }

    function mapDispatchToProps(dispatch) {
      return {
        getData: () => {
          return dispatch(
            getData()
          )
        }
      }
    }

    export default connect(mapStateToProps, mapDispatchToProps)(Home);

The API response is an array with nested objects: "users":[{"points":22}] and so on.
Also, pre-adding the data is also not working, after that it doesn't update at all. I don't see where I need to change the loading behavior

A: because the initialState of data is {}, so when fetching api data.users is undefined.
You can use optional chaining to check.
const data = {
  datasets: [{
    data: data.users?.map(d => d.points) || [], // map return new array so don't need spread operator
    strokeWidth: 2 // optional
  }]
};

A: Before fetching showing an activity indicator, once fetching completed then hide indicator and showing your content, using state.


text:
Q: Purely functional stack implementation with scheme I would like to implement a functional stack in scheme.
This is my attempt:
(define make-stack
  (letrec ((do-op
            (lambda (stack op . val)
              (cond ((eq? op 'push)
                     (lambda (op . v)
                       (do-op (cons (car val) stack) op v)))
                    ((eq? op 'pop)
                     (lambda (op . v)
                       (do-op (cdr stack) op v)))
                    ((eq? op 'print)
                     (begin (display stack)
                            (newline)
                            (lambda (op . v)
                              (do-op stack op v))))))))
    (lambda (op . val)
      (do-op '() op val))))

The stack can be used as in this example:
(define s make-stack)
((((((s 'push 1) 'push 2) 'push 3) 'print) 'pop) 'print)

The output of this example is:
((3) (2) (1))
((2) (1))

Not exactly what I wanted, but not too bad.
I wanted to ask the experienced schemers here if there is a way to make the stack behave more naturally, for example like this:
(define s make-stack)
(s 'push 1)
(s 'push 2)
(s 'pop)
...

while keeping it functional (so no mutability, no set!).
The first thing I thought was to keep returning a function with no arguments, but changing every lambda (op . v) with:
(lambda ()
  (lambda (op . v)
    ...

but this does not work as we still need to capture the returned function:
> (define s make-stack)
> ((s) 'push 1)
#<procedure>

A: As Amalloy suggests, functional style has principles that contrast with your goal. It's not impossible to do something similar, however -
(define (run-stack s prgm)
  (foldl (lambda (step s) (apply s step))
         s
         prgm))

(run-stack
  make-stack
 '((push 1)
   (push 2)
   (push 3)
   (print)
   (pop)
   (print)))

To test this, I implemented make-stack as -
(define (dispatch-stack s)
  (lambda payload
    (match payload
      ((list 'pop)
       (dispatch-stack (cdr s)))
      ((list 'push v)
       (dispatch-stack (cons v s)))
      ((list 'print)
       (println (reverse s))
       (dispatch-stack s))
      (_ (error "invalid stack operation" payload)))))

(define make-stack
  (dispatch-stack null))

Output -
'(1 2 3)
'(1 2)

Another thing I think you would like to see is Make a language in one hour: stacker. This will help you to see how languages like Racket are fundamentally different from others you have probably worked with before.

A: Your goals are contradictory. If s is a stack, and your operations purely functional, then (s 'push 1) must return the same thing every time it is called. To capture the notion of change, you must use a different s each time. That's how your functional stack works: it gives you back a new stack, and you must compose function calls with it.


text:
Q: Vertical pane icon in Outlook Web App (OWA) is no more showing I am developing an outlook add-in targeting OWA, Outlook 2016 for Mac & Windows. Few month back when I started and testing the application, the small icon to activate the add-in was showing. But the icon is no more showing with same manifest and all setting same. Please refer the screenshot.
Is this part of any update from Microsoft? How I can fix it?
Thank you in advance.

A: OWA uses the IconUrl in the section above version overrides because it uses the addin icon while Outlook desktop clients use the individual  control icon. It looks like you found this but I just wanted to add this answer so it is more visible.
An additional note here, <IconUrl .../> should be above <HighResolutionIconUrl ../> element otherwise manifest does not pass the validation.


text:
Q: Take only the lines with numbers with egrep i have a file where lines have numbers with characters,only characters and only numbers. I would like to choose the lines with only numbers. I tried egrep '[^[:alpha:]]' filename but i take also lines with chars. Any idea?
AQ
Feb 9, 1999
11:45
45

And i want only
45

A: The regex needs to check that everything on the line is numeric.  So a ^ and $ around the expression is needed to match from the start to the end of each line.  Also the match will need to be explicitly for digits, rather than non-alpha.
E.g.
 egrep '^[[:digit:]]+$' filename

This worked well against the example in the question.

A: I would exclude any line that contains any non-digit character:
grep -v '[^[:digit:]]' file
# ........| negates the character class

A: with awk
only lines with digits and nothing else
$ awk '/^[0-9]+$/' file
45

or, exclude any line which has a not digit char
$ awk '!/[^0-9]/' file
45

A: To match lines containing only numbers, use either "whole line mode" with -x:
grep -xE '[[:digit:]]+' file

or add the line start/end anchors to the regular expression:
grep -E '^[[:digit:]]+$' file

Note that you can replace the character class [:digit:] with the range 0-9 if you are only concerned with matching the ASCII characters from 0 to 9:
grep -xE '[0-9]+' file


text:
Q: C# Convert json to multiple classes I have a problem. I am trying to parse my json to 2 classes. Here is the json:
{
   "user":[
      [
         {
            "Id":"0",
            "Username":"Vreeswijk",
            "ProfilePicture":"media/user/0.png"
         }
      ]
   ],
   "token":[
      [
         {
            "access_token":"myToken1",
            "refresh_token":"myToken2",
            "expires_in":3600,
            "expires_on":1577363756
         }
      ]
   ]
}

And here are my 2 classes:
public class Token
{
    public string access_token { get; set; }
    public string refresh_token { get; set; }
    public int expire_in { get; set; }
    public int expire_on { get; set; }

    public Token() { }
}

And here is the user class:
public class User
{
    [PrimaryKey]
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string ProfilePicture { get; set; }

    public User() { }
    public User(string Username, string Password)
    {
        this.Username = Username;
        this.Password = Password;
    }
}

Now I want to deserialize the json to those 2 classes.
Here is my code now that works for 1 class only:
var jObject = JObject.Parse(json);
var userPropery = jObject["user"] as JArray;
userList= new List<user>();

foreach (var property in userPropery )
{
    var propertyList = JsonConvert.DeserializeObject<List<user>>(property.ToString());

    userList.AddRange(propertyList);
}

How can I make this work for 2 classes in 1 json?

A: You can create a Root class for your json and add two properties in it with User and Token classes as required.
public class Root
{
    public List<List<User>> Users { get; set; }
    public List<List<Token>> Tokens { get; set; }
}

Then pass this class in DeserializeObject function to deserialize the json.

A: If you observe your Json, both user and token are nested Arrays. You can now create Root Class that has both the required properties. For Example
public class Root
{
    public List<List<User>> user { get; set; }
    public List<List<Token>> token { get; set; }
}

Now, instead of using JObject.Parse you could deserialize it directly as
var root = JsonConvert.DeserializeObject<Root>(json);

To get a flattened user and token list, you can use
var userList= root.user.SelectMany(x=>x);
var tokenList= root.token.SelectMany(x=>x);

A: Why don't you create a class include both user and token?
If you don't do this, please parse one by one.


text:
Q: Fetching Public Record From iCloud Using CloudKit I have the following code for uploading my assets to iCloud
func uploadAsset(recordType: String, fileURL: URL) {
    let record = CKRecord(recordType: recordType)
    record["file"] = CKAsset(fileURL: fileURL)

    CKContainer.default().publicCloudDatabase.save(record) { savedRecord, error in
        if let saveError = error {
            print("An error occurred in \(saveError)")
        } else {
            print(savedRecord)
        }
    }
}

It definitely works because I am able to go onto the CloudKit dashboard, and physically see the records as well as download their attached files.
Here is an example of the savedRecord that is output from that function:
Optional(<CKRecord: 0x100f27f60; recordID=F6DF33CB-35DA-483A-A5B5-33542E435689:(_defaultZone:__defaultOwner__), recordChangeTag=izfmgx06, values={
    file = "<CKAsset: 0x1703e6800; path=/private/var/mobile/Containers/Shared/AppGroup/992A6367-11F5-491F-BE37-C9E4BBA865E6/voice/1487611173.95385.m4a, size=33547, UUID=D8F70489-1FF8-4CE8-99BE-390741E8136D, signature=<01a5bd3c fd9b8042 cb52cc23 3681af91 50aacaa5 97>>";
}, recordType=Voice>
{
    creatorUserRecordID -> <CKRecordID: 0x17003ebe0; recordName=__defaultOwner__, zoneID=_defaultZone:__defaultOwner__>
    lastModifiedUserRecordID -> <CKRecordID: 0x17003e740; recordName=__defaultOwner__, zoneID=_defaultZone:__defaultOwner__>
    creationDate -> 2017-02-21 14:24:28 +0000
    modificationDate -> 2017-02-21 14:24:28 +0000
    modifiedByDevice -> 3AB140FD824827C374412EBB6B72307C57DCF1E07A7FE58F13EBF445ACCB0EA3
    file -> <CKAsset: 0x1703e6800; path=/private/var/mobile/Containers/Shared/AppGroup/992A6367-11F5-491F-BE37-C9E4BBA865E6/voice/1487611173.95385.m4a, size=33547, UUID=D8F70489-1FF8-4CE8-99BE-390741E8136D, signature=<01a5bd3c fd9b8042 cb52cc23 3681af91 50aacaa5 97>>]

I thought, due to this being a public record, I'd be able to download this inside another app that shares the same custom iCloud container string.
However, using the RecordIDName (in this case: F6DF33CB-35DA-483A-A5B5-33542E435689), I am unable to fetch the record.
This is my code for downloading it:
    let recordId = CKRecordID(recordName: "F6DF33CB-35DA-483A-A5B5-33542E435689")

    CKContainer.default().publicCloudDatabase.fetch(withRecordID: recordId) { (results, error) -> Void in

        DispatchQueue.main.async {
            if error != nil {

                print(" Error Fetching Record  " + error!.localizedDescription)
            } else {
                if results != nil {
                    print("pulled record")

                    let record = results as CKRecord!

                    print(record)
                }
            }
        }
    }

I simply get the error as follows:
 Error Fetching Record  Error fetching record <CKRecordID: 0x10024c6f0; recordName=6988103A-E795-441B-A115-2D044872AAAC, zoneID=_defaultZone:__defaultOwner__> from server: Record not found

Any help appreciated. Thanks in advance! :)

A: The error was in using
CKContainer.default()

In both the creation and pulling stages. Instead, I should have used a specified custom container inside, i.e.
CKContainer(identifier: "iCloud.tech.jackrobson.myApp")


text:
Q: How to parse xml using JavaScript and identify elements based on attributes I am using xml2js to convert an xml file into a javascript object. I need to identify attributes within element tags in the xml file and manipulate the matching element(s).
For example, I have some a property element in test.xml:
...
<property name="TemporaryPort" type="input" required="true" order="0">
  <object>endpoint</object>
</property>
<property name="TemporaryPort" type="input" required="false" order="1">
  <object>endpoint</object>
</property>
<property name="TemporaryPort" type="output" required="false" order="2">
  <object>endpoint</object>
</property>
...

In my parse.js file that is parsing this xml file, I would like to identify elements based on their attributes:
const xml2js = require('xml2js');
const xml = fs.readFileSync("test.xml");

let output = "";
const parser = new xml2js.Parser();
parser.parseString(xml, function(err,result){
  // I would like to find all elements where:
  // required is set to "true",
  // name is set to "TemporaryPort", and
  // type is set to "input"
  output="";
  console.log(output);
});

A: Maybe with DOMParser() ?
sample code:

const
  DomParser = new DOMParser()
, XMLtext = `
  <data_xml>
    <property name="TemporaryPort" type="input" required="true" order="0">
      <object>endpoint 1</object>
    </property>
    <property name="TemporaryPort" type="input" required="false" order="1">
      <object>endpoint 2</object>
    </property>
    <property name="TemporaryPort" type="output" required="false" order="2">
      <object>endpoint 3</object>
    </property>
  </data_xml>`
  ;
let XMLparsed = DomParser.parseFromString( XMLtext, 'application/xml')
  ;

  //  find all elements where:
// required is set to "true",
// name is set to "TemporaryPort", and
// type is set to "input"

for (let nod of XMLparsed.querySelectorAll('data_xml property[name="TemporaryPort"][type="input"][required="true"]') )
  {
  for(let subChild of nod.children)
    {
    console.log( '---subChild name:', subChild.nodeName )
    console.log( '----------content ->', subChild.textContent )
    }
  }
console.log('\n\n\n')

// otherwise:

for (let nod of XMLparsed.querySelector('data_xml').children )
  {
  console.log( 'nodeName =', nod.nodeName)
  for(let attr of nod.attributes)
    {
    console.log('---> attribute: name=', attr.name, ',  value=', attr.value)
    }
  for(let subChild of nod.children)
    {
      console.log( '---subChild name:', subChild.nodeName )
      console.log( '----------content ->', subChild.textContent )
    }
  }
.as-console-wrapper {max-height: 100%!important;top:0; }

A: I made a slight change to your .xml file, as I can't see the whole thing, but I assume it's enclosed in a parent wrapper, which I've called props.
<props>
    <property name="TemporaryPort" type="input" required="true" order="0">
    <object>endpoint</object>
    </property>
    <property name="TemporaryPort" type="input" required="false" order="1">
    <object>endpoint</object>
    </property>
    <property name="TemporaryPort" type="output" required="false" order="2">
    <object>endpoint</object>
    </property>
</props>

I've also...

*

*Imported fs

*Changed output to an array, as your function parses the xml as an array of objects

*Looped through result (the array of objects), props (my made up parent wrapper) and property the children from the XML file in your example.

*The loop checks for your required conditions and pushes the object to the output array, which it logs at the end.

const xml2js = require('xml2js');
const fs = require('fs');

const xml = fs.readFileSync("test.xml");

const output = []
const parser = new xml2js.Parser();

parser.parseString(xml, function(err,result){
  result.props.property.forEach(prop => {
    prop['$'].required == 'true' &&
    prop['$'].name == 'TemporaryPort' &&
    prop['$'].type == 'input' &&
    output.push(prop)
  })
  console.log(output)
});


text:
Q: No Such File to Load -- rest_client (Rails 3) When I do thin start, this is the error I get:
$ thin start
>> Using rack adapter
/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239:in `require': no such file to load -- rest_client (LoadError)
    from /.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239:in `block in require'
    from /.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225:in `block in load_dependency'
    from /.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:596:in `new_constants_in'
    from /.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225:in `load_dependency'
    from /.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239:in `require'
    from /.rvm/gems/ruby-1.9.2-p0/gems/stripe-1.5.13/lib/stripe.rb:9:in `<top (required)>'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `block (2 levels) in require'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `each'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `block in require'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `each'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `require'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler.rb:112:in `require'
    from /app/config/application.rb:7:in `<top (required)>'
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from /app/config/environment.rb:2:in `<top (required)>'
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from /app/config.ru:3:in `block in <main>'
    from /.rvm/gems/ruby-1.9.2-p0/gems/rack-1.2.3/lib/rack/builder.rb:46:in `instance_eval'
    from /.rvm/gems/ruby-1.9.2-p0/gems/rack-1.2.3/lib/rack/builder.rb:46:in `initialize'
    from /app/config.ru:1:in `new'
    from /app/config.ru:1:in `<main>'
    from /.rvm/gems/ruby-1.9.2-p0/gems/thin-1.2.11/lib/rack/adapter/loader.rb:36:in `eval'
    from /.rvm/gems/ruby-1.9.2-p0/gems/thin-1.2.11/lib/rack/adapter/loader.rb:36:in `load'
    from /.rvm/gems/ruby-1.9.2-p0/gems/thin-1.2.11/lib/rack/adapter/loader.rb:45:in `for'
    from /.rvm/gems/ruby-1.9.2-p0/gems/thin-1.2.11/lib/thin/controllers/controller.rb:169:in `load_adapter'
    from /.rvm/gems/ruby-1.9.2-p0/gems/thin-1.2.11/lib/thin/controllers/controller.rb:73:in `start'
    from /.rvm/gems/ruby-1.9.2-p0/gems/thin-1.2.11/lib/thin/runner.rb:185:in `run_command'
    from /.rvm/gems/ruby-1.9.2-p0/gems/thin-1.2.11/lib/thin/runner.rb:151:in `run!'
    from /.rvm/gems/ruby-1.9.2-p0/gems/thin-1.2.11/bin/thin:6:in `<top (required)>'
    from /.rvm/gems/ruby-1.9.2-p0/bin/thin:19:in `load'
    from /.rvm/gems/ruby-1.9.2-p0/bin/thin:19:in `<main>'

Anyone have any thoughts?
Edit: I tried running sudo gem install rest-client, and even though that gem installed, I am still getting the error when I run thin start.

A: I had to declare gem 'rest-client' explicitly in my Gemfile for it to work.
It was an issue with the Stripe gem, that needs rest-client as a dependency.


text:
Q: Why my iOS app don´t appear on notifications settings? I have a problem with my app. I have a distribution certificate with Push Notifications, I tested the .ipa and it's alright.
But, when I delivered the app to App Store, and the app was accepted and published, after download, my app doesn't appear on Notification Center in Settings.
Can someone help me on this?


text:
Q: Is it possible to set a SharePoint Online list as read only without having to edit permissions? I have a list in SharePoint Online that I would like to make read-only. I would normally remove the edit permission from all roles in the list permissions, but I want to even prevent site-collection administrators from editing the list (of course, if they really needed to, they could just change the setting).
I can't find any property on the list object. Is this possible?

A: This is not possible, site collection administrators will always have full control over lists and libraries in the site collection and therefore be able to edit the list.

A: The SharePoint Site Collection Administrator cannot be locked out of any sub-site, list, library, item, or page on the site. The permissions inheritance for any of these elements can be broken at any time, and permissions can be changed so that even users with Full Control rights have lesser permissions or even no permissions at all.
In all cases the SharePoint Site Collection Administrator will always have full access to all of the elements and all of the data. This is especially handy when a site Owner accidentally deletes their own user account or group when creating custom permissions.
Reference:
What Is a SharePoint Site Collection Administrator?

A: I don't think it's possible to prevent site collection administrator editing the list. Because site collection administrator has full control.


text:
Q: Beginner and Blocks Simple question.
I have a tableViewController that will display a list of search results.
I want to create a block based callback (I think that's what you would call it)
I would present the viewController
[searchResultController showSearchResults //BlockCode here {

//did select this item...

}];

but use a block so that I can detect the selection made from the tableview instead of using a delegate method.
Problem is I have no idea how to implement this. Is there a good tutorial or a simple example on how to do this?

A: Your search results controller needs to have a block property. This block should be defined with no return type, and should take a parameter of whatever object you are going to use to represent the selected item.
Before presenting your search results controller, set the block property to whatever you wish to do for your callback.
Within the search results controller, when a row is selected, execute the block, passing in the selected object. Either this method, or the block itself, should also dismiss your controller.


text:
Q: How do i compare a variable's data with the data in an array? I have an int array:
int[] BankClientNumber = new int[10];

I want the user to input an id number...
findidd = JOptionPane.showInputDialog ("\nEnter ID number:\n\n");
findid = Integer.parseInt(findidd);

...and have the program look through the data of the array, match the id number and print the other details of the client.
How do I compare the variable's data with that of the array?
Any suggestions will be much appreciated.

A: You want to know if the int array contains the number, this is probably the esiest way:
Arrays.asList(BankClientNumber).contains(findidd)

Note: As an advice I would use a Collection as BankClientNumber for instance a Set.

A: You would be better off storing the Bank Client Numbers in a Collection rather than an array. Collections have nice methods for searching, sorting etc.

A: If you don't want to use a collection for whatever reason it's simply:
boolean exists = false;
for(int check: bankClientNumber) {
   if(check == findid) {
      exists = true;
      break;
   }
}
if(exists) {
   //do something
}

FYI Java coding conventions dictate that variables start in lowercase so BankClientNumber should be bankClientNumber.
Method names also start with lowercase and object names start with Uppercase.
It is also recommended to use camel cases (youShouldUseCamelCase or YouShouldUseCamelCase) and avoid underscores in method and object names. IMHO use camel case for variables as well.


text:
Q: If $|x + 1| + |x - 3| = 6$, solve for $x$ $|x + 1| + |x - 3| = 6$. Solve for X.
So I know when you have a problem like this: |x| = 6, you solve by doing x=6 and x=-6. That doesn't help us much in the above example.
You can also solve problems of this fashion by negative the variable portion of the equation. For ex:
$|x+3| = 6. $
You can solve it either by doing:
$x+3 = 6$ or
$x+3 = -6$
$x= 3,-9$
OR
$(x+3) = 6$ so $x=3$
or
$-(x+3) = 6$
$-x -3 =6$
$-x = 9$
$x = -9$
So back to the original problem of $|x + 1| + |x - 3| = 6$
if $X>3$, then $x+1 + x-3 = 6$
$2x=8$
$x=4$
or if $X<3$
$x+1 + x-3 = -6$
$2x=-4$
$x=-2$
Is that correct? Is that all I need to do? I also feel like I got the "critical points" of the equation wrong.

A: First let us do it without algebra. Draw a number line. Then $|x+1|+|x-3|$ is the sum of the distances of $x$ from $-1$ and from $3$. It is clear that if $x$ is between $-1$ and $3$, the sum of the distances is $4$. The sum of the distances will be $6$ if we are $1$ unit to the right of $3$, or $1$ unit to the left of $-1$.
Now with algebra, essentially like you approached it.
If $x\ge 3$, then $|x-3|=x-3$ and $|x+1|=x+1$. So we want $(x-3)+(x+1)=6$. giving $x=4$.
If $x\gt -1$, and $x\lt 3$, then $|x+1|=x+1$ and $|x-3|=-x+3$, so we want $(x+1)+(-x+3)=6$, impossible.
If $x\lt -1$, then $|x+1|=-x-1$ and $|x-3|=-x+3$, so we want $-2x+2=6$, giving $x=-2$.

A: Divide the domain to
(1) $x \le -1$
(2) $-1 \le x \le 3$
(3) $x \ge 3$
solve the equation in each domain

A: $|x+1| = 6 - |x-3|$
$x + 1 = 6 - |x-3|$ or $x+1 = -6 + |x-3|$
For the first equation: $|x-3| = 5 - x$ so
$x-3 = 5 -x$ or $ x-3 = x-5$. Only the first part is valid, it gives you the solution $x=4$.
Second equation: $x+7 = |x-3|$. So
$x+7 = x-3$ or $-x - 7 = x-3$. Only the second equation is valid, that gives you $x=-2$. These are the two solutions.


text:
Q: Let $f(z)=z^2, g(z)=z-1,h(z)=\frac{1}{z}$ be functions defined on $\Bbb{C}$, what is the derivative of their composition?
Let $f\left(z\right)=z^2,\:g\left(z\right)=z-1,\:h\left(z\right)=\frac{1}{z}$ be functiones defined on $\mathbb {C}$, what is the derivative of $\left(f\:\circ h\:\circ \:g\right)$ on $\mathbb{C}\setminus\{1\}$.

I presume the solution would involve some variation of multivariable chain rule for complex-valued functions, but, evidently, I seem to lack the brain power to figure this out all by myself.

A: (f∘h∘g)  = 1/(z−1)^2
\frac{d}{dz}\left(\frac{1}{\left(z-1\right)^2}\right)=-\frac{2}{\left(z-1\right)^3}
Thanks for your advice, guys!


text:
Q: Pop function for stack has unexpected behaviour I was just taking lecture on behalf of my Guide and one student given this code:
#include<stdio.h>

struct stack{
     int top;
     int store[50];
};

void push(int num, struct stack stk)
{
        stk.store[stk.top] = num;
        stk.top = stk.top + 1;
}

int pop(struct stack stk)
{
        int temp = stk.store[stk.top];
        stk.store[stk.top - 1] = 0;
        stk.top = stk.top - 1;
        return temp;
}

int main()
{
        int i;
        struct stack imp, pl;
        imp.top = 0;
        for(i = 0; i<8; i++)
        {
                int choice, val;
                printf("Menu:\n\n");
                printf("1. Push\n");
                printf("2. Pop\n");
                printf("3. Exit\n\n");

                printf("Please enter the choice:");
                scanf("%d", &choice);
                switch(choice)
                {
                        case 1:
                                printf("Please enter the value to be inserted");
                                scanf("%d", &val);
                                push(val, imp);
                                printf("The position:%d\n",imp.top);
                                break;
                        case 2:
                                printf("The poped value is : %d at position:%d\n",pop(imp), imp.top);
                                break;
                        case 3:
                                return 0;
                                break;
                        default:
                                printf("Wrong choice.\n");
                }
        }
}

The value of top is always zero and pop is returning always zero.
Can somebody point out what is wrong with the code or the reason behind this behavior of the code.

A: Your push operator assumes that stk.top is one entry past the top element of the stack. Your pop operator assumes that stk.top is the top element itself. (Sort of; it's actually a bit inconsistent internally.)
I suggest that you draw a diagram and run through some operations by hand, following the code line by line. Watch out for off-by-one problems and fix them as you find them.
[EDITED to add:] Oh, Sourav Ghosh (in comments to the original question) also makes a very important point: you're passing your stack object around by value rather than by pointer, which is also going to break everything -- because the modifications in the store and pop functions are applied to the copy, not to the original. I'm community-wiki-ing this answer since one of the key things in it is now from someone other than me.

A: The pop function returns [top] but resets [top - 1] to 0.

A: Here is an Stack implementation example


text:
Q: Reuse NSPredicate for new variable substitute Can I reuse NSPredicate for new variable substitute? My NSPredicate is rather simple:
NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"id == %@",userID];

The userID is generated at run-time with different value, right now for each userID I need to create a NSPredicate. So is it possible I can reuse my NSPredicate ?

A: Yep, you can do this with a variable:
NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"id == $user"];

Save that predicate somewhere, then do this when you need to actually start filtering stuff:
NSDictionary *sub = [NSDictionary dictionaryWithObject:user forKey:@"user"];
NSPredicate *filter = [userPredicate predicateWithSubstitutionVariables:sub];

This is a much more efficient way to reuse a predicate, because parsing the format string (which can be pretty expensive) only happens once.


text:
Q: Run JavaScripts one after another using WebView (Android) I'm trying to load a web page using WebView in Android and then run several JavaScripts, one after another. To do this I'm trying to use the function onPageFinished to start running a script once the previous one is finished. However, it seems that the function is called only once. Here is my code:
public class MyWebViewClient extends WebViewClient {
    private int state;
    private WebView webView;

    private String[] urls = new String[4];

    public MyWebViewClient(WebView webView, HtmlSelectComponent component) {
        this.webView = webView;

        this.state = 0;
        String option = String.valueOf(component.getOption());
        this.urls[0] = "http://my.web.site/page.aspx";
        this.urls[1] = "javascript:document.getElementById('" + component.getId() + "').value='" + option + "';";
        this.urls[2] = "javascript:(function() {__doPostBack('" + component.getName() + "','');})()";
        this.urls[3] = "javascript:window.HTMLOUT.showHTML(''+document.getElementsByTagName('html')[0].innerHTML+'');"; // Obtain the HTML code
        webView.loadUrl(urls[0]);
    }

    @Override
    public void onPageFinished(WebView view, String url)
    {
        state++;
        if(state == 4)
            return; // End of the scripts
        webView.loadUrl(this.urls[state]);
    }
}

The HtmlSelectComponent is a class that holds the component's (which is a dropdown list) name, id and selected option.
What is happening is that the page is being displayed and the onPageFinished is only called once (the "state" variable stops with value 1).
I'm not sure if this is correct because I don't even know if JavaScripts actually call the onPageFinished function and I would like to know the correct way of doing this.

A: So I found a simple solution. JavaScripts do not call the onPageFinished(); unless they cause a page reload. So, to run several scripts one after another I simply placed them all in a single line, separated by a semi-column like this:
webView.loadUrl("javascript:document.getElementById('" + component.getId() + "').value='" + option + "';(function() {__doPostBack('" + component.getName() + "','');})();javascript:window.HTMLOUT.showHTML(''+document.getElementsByTagName('html')[0].innerHTML+'');");

A: Process 1 : Simply call it from one JavaScript function's last line (if have no return type) to another Function and you only call the first function and it will call itself when one scripting finished.
Process 2: webview.loadData(); use this method more then one time to push your scripting to webpage when onFinish(); executing.


text:
Q: Why cant apt-get install the i386 version of any package? Why cant apt-get install the i386 version of libpcap-dev?
$ sudo apt-get install libpcap-dev:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package libpcap-dev:i386 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'libpcap-dev:i386' has no installation candidate

However, the package clearly exists: https://launchpad.net/ubuntu/trusty/i386/libpcap-dev. I'm on Ubuntu 14.04 x64.

A: This normally is because you don't have enabled multiarch and updated your package lists. This can be achieved easily:
sudo dpkg --add-architecture i386
sudo apt-get update

The first tells dpkg that we like to support the i386 binaries in our system, APT query this and starts downloading not only the amd64 package list but also the i386. I'm not sure why this isn't the default in Ubuntu (in Debian it isn't, but Debian supports way more architectures) but that's why.

A: The package may exist, but this package is an architecture-independent package (see here for the source package info), since this is a transitional package that does nothing but install another package. Such packages don't need to be "built" for each architecture.
The package that it installs is libpcap0.8-dev (don't ask me why they decided to suffix a development package with the version), which is multi-arch.


text:
Q: What's the sum of this series? I would like to know how to find out the sum of this series:
$$1 - \frac{1}{2^2} + \frac{1}{3^2} - \frac{1}{4^2} + \frac{1}{5^2} - \frac{1}{6^2} + \cdots$$
The answer is that it converges to a sum between $\frac 34$ and $1$, but how should we go about estimating this sum?
Thanks!

A: It is well known that $\displaystyle\sum_{n=1}^{\infty}\dfrac{1}{n^2} = \dfrac{\pi^2}{6}$.
Thus, $\displaystyle\sum_{\substack{n=1\\ n \ \text{is even}}}^{\infty}\dfrac{1}{n^2} = \sum_{m=1}^{\infty}\dfrac{1}{(2m)^2} = \dfrac{1}{4}\sum_{m=1}^{\infty}\dfrac{1}{m^2} = \dfrac{1}{4} \cdot \dfrac{\pi^2}{6} = \dfrac{\pi^2}{24}$.
Hence, $\displaystyle\sum_{\substack{n=1\\ n \ \text{is odd}}}^{\infty}\dfrac{1}{n^2} = \sum_{n=1}^{\infty}\dfrac{1}{n^2} - \sum_{\substack{n=1\\ n \ \text{is even}}}^{\infty}\dfrac{1}{n^2} = \dfrac{\pi^2}{6} - \dfrac{\pi^2}{24} = \dfrac{\pi^2}{8}$.
Finally, $\displaystyle\sum_{n=1}^{\infty}\dfrac{(-1)^{n+1}}{n^2} = \displaystyle\sum_{\substack{n=1\\ n \ \text{is odd}}}^{\infty}\dfrac{1}{n^2} - \displaystyle\sum_{\substack{n=1\\ n \ \text{is even}}}^{\infty}\dfrac{1}{n^2} = \dfrac{\pi^2}{8} - \dfrac{\pi^2}{24} = \dfrac{\pi^2}{12}$.

A: If we did not know an exact answer, here is a crude way to estimate the sum of the series.
Our series is an alternating series, with terms that decrease in absolute value and have limit $0$. So the error made by truncating at a particular term has absolute value less than the absolute value of the first "neglected" term.
For example, if we use $1-\frac{1}{2^2}+\frac{1}{3^2}-\frac{1}{4^2}+\frac{1}{5^2}$ as an approximation, then the absolute value of the error is less than $\frac{1}{6^2}$. Furthermore, the error is "negative," that is, our estimate is greater than the true value.

A: The sum of this series is $\frac{\pi^2}{12}$.
Explantion
We already know that:
$$1+ \frac{1}{2^2} + \frac{1}{3^2} + \text{...} = \frac{\pi^2}{6}$$
HINT
Note that:
$$\large \frac{-1}{2^2} = \frac{1}{2^2} - \frac{1}{2^2} - \frac{1}{2^2}$$
Now,
$$1- \frac{1}{2^2} + \frac{1}{3^2} - \text{...} = \left(\frac{1}{1} + \frac{1}{2^2} + \frac{1}{3^2} + \frac{1}{4^2} + ...\right) - 2 * \left(\frac{1}{2^2} + \frac{1}{4^2} + \frac{1}{6^2} + ...\right)$$
$$ = \frac{\pi^2}{6} - \frac{2}{2^2}\left(\frac{1}{1} + \frac{1}{2^2} + \frac{1}{3^2} + \frac{1}{4^2} + ...\right)$$
$$ = \frac{\pi^2}{6} - \frac{1}{2}*\frac{\pi^2}{6}$$
$$= \frac{\pi^2}{12}$$
Comment if you have questions.

A: HINT:
This can be written as $$\sum_{i=1}^{\infty} \frac{(-1)^{i+1}}{i^2}$$
$$$$
Setting $\displaystyle a_i= \frac{(-1)^{i+1}}{i^2}$:
$$\sum_{i=1}^{\infty} a_{2i-1}=\sum_{i=1}^{\infty} \frac{1}{(2i-1)^2}$$
$$\sum_{i=1}^{\infty} a_{2i}=-\frac{1}{4}\sum_{i=1}^{\infty} \frac{1}{i^2}$$
When the series $\displaystyle \sum_{i=1}^{\infty} a_{2i-1}$ and $\displaystyle \sum_{i=1}^{\infty} a_{2i}$ converge then the series $\displaystyle \sum_{i=1}^{\infty} a_{i}$ also converges.
$$\sum_{i=1}^{\infty} a_{i}=\sum_{i=1}^{\infty} a_{2i-1}+\sum_{i=1}^{\infty} a_{2i}$$
Find where the series $\displaystyle \sum_{i=1}^{\infty} a_{2i-1}$ and $\displaystyle \sum_{i=1}^{\infty} a_{2i}$ converge.


text:
Q: Can we have different colors for different markers in folium map? Different colors for different range of frequency signal Sample_csv_data
import pandas as pd

df = pd.read_csv('C:/Nishant/Gtech/folium.csv',sep=',')
subset=df.sample(n=700)
subset.tail()

Plot
import folium from folium.plugins
import FastMarkerCluster

print(df['Lon'].mean())
print(df['Lat'].mean())

m=folium.Map(location=[df['Lat'].mean(),df['Lon'].mean()],zoom_start=25)

def add_marker(row):
    marker = folium.CircleMarker([row['Lat'],row['Lon']],radius=2,color='red',popup=row['RSRP_Signal'])

marker.add_to(m)

subset.apply(add_marker,axis=1)

m.save('C:/Nishant/Gtech/folium.html')

m

A: import folium
from folium.plugins
import FastMarkerCluster

print(df['Lon'].mean() )

print(df['Lat'].mean())

m=folium.Map(location=[df['Lat'].mean(),df['Lon'].mean()],zoom_start=15)
def add_marker(row):
    if row['RSRP_Signal']>-80:

marker=folium.CircleMarker([row['Lat'],row['Lon']],radius=2,color='green',popup=row['RSRP_Signal'])
        marker.add_to(m)

    elif row['RSRP_Signal']>-100:
        marker=folium.CircleMarker([row['Lat'],row['Lon']],radius=2,color='blue',popup=row['RSRP_Signal'])
        marker.add_to(m)

    else:
        marker=folium.CircleMarker([row['Lat'],row['Lon']],radius=2,color='red',popup=row['RSRP_Signal'])
        marker.add_to(m)

subset.apply(add_marker,axis=1)
m.save('C:/Nishant/Gtech/folium.html')
m


text:
Q: python pyplot.quiver: Scaling of two superimposed vector fields I want to plot two vector fields in one quiver plot. This is already working: For each point, there are two vectors in different colors. Now the problem is, that the scaling is not the same: e.g.  vector (1,0) from the first field  (sol) is displayed with another length as the (1,0) from field two (res).
How can I make quiver to plot both fields with the same scale, so that (1,0) from res has the same physical length on my plot as (1,0) from sol?
My code:
import numpy as np
from matplotlib import pyplot as plt

#res and sol are two vector fields with dimension (ny, nx ,2)

step=3 #not all vectors should be plotted. Just every third one (in x and y direction)

X,Y = np.meshgrid(np.arange(0,nx,step), np.arange(0,ny,step))
Q=plt.quiver(X,Y,sol[::step,::step,0], sol[::step,::step,1], color='r')
W=plt.quiver(X,Y,res[::step,::step,0], res[::step,::step,1], color='b')
plt.quiverkey(Q, 0.4, 0.15, 1, r'text1', labelpos='S')
plt.quiverkey(W, 0.6, 0.15, 1, r'text2', labelpos='S')
plt.show()

A: You have two solutions:

*

*Normalize the input data and scale it

*Tell quiver how to scale your data

Solution 2 (fastest):
Q=plt.quiver(X,Y,sol[::step,::step,0], sol[::step,::step,1], color='r', scale=1)
W=plt.quiver(X,Y,res[::step,::step,0], res[::step,::step,1], color='b', scale=1)

You may adjust the scale value, but you have to keep the same values in both quivers in order to get what you expect. This thread helped but in your case I think it's not an overspecification to give the same scale to each quiver.


text:
Q: What does 'itself' refer to in the sentence?
That tidal disruption of a Sun-like star by a black hole 1 million times more massive than itself took place 215 million light-years from Earth.

So that the star is as large as the Sun is clear to me. But I am not sure which one the word 'itself' refers to. Does that mean the black hole is 1 million times more massive than the Sun-like star?
Source article  (in the second paragraph)

A: First of all, the sentence is awkward and rather unusual. So don't use it as a good example of how to express this idea.
The black hole is one million times more massive than the Sun-like star it consumed.
To make it easier to understand, you can add either that was or which was offset by commas:

That tidal disruption of a Sun-like star by a black hole that was one million more times more massive than itself took place 215 million light years from Earth.

That tidal disruption of a Sun-like star by a black hole, which was one million more times more massive than itself, took place 215 million light years from Earth.

Plus, I think it's fairly common knowledge that black holes are among the most massive objects in the universe


text:
Q: Can't forward a port I spend a day searching in how to forward a port from my router to my PC, whihout success. And now I'm out of leads... and frustrated. I've seen many pages with descriptions and possible solutions but somehow I don't see the right answer. So, excusses if this is a repeating question, that is not how I see it.
This is what I try to do:
I want to have access to my PC at home when I'm at work. For this I use a ddns service.
Some scenarios that work, and some that dont:
This is my `standard' configuration.
I have two PC's, a desktop and a laptop. On both I have an SSH server (bitvise) and an SSH client (PuTTY) The desktop is running windows 10 and the laptop is running windows 7. I can make a SSH connection from the desktop to the laptop and the other way around, suggesting to me that port 22 is open on both computer. Right?
ISP
 |
ZyXEL VMG8324-B10A (forward port 22 to 192.168.1.105)
 | .1  (192.168.1.x)
 |
 +- .105 PC (desktop, W10, SSH server on port 22)
 |
 +- .107 PC (laptop, W7, SSH server on port 22)

The service for ddns allows me to connect to my home network. If I try to connect port 80 I just get the login screen for my router, no problems there. I even tried it with a second routeron confifured for port 8080 and the original server forwarding port 8080 to this second server. No problem.
This is what that setup does look like.
ISP
 |
ZyXEL VMG8324-B10A (forward port 8080 to 192.168.1.2)
 | .1  (192.168.1.x)
 |
 | .2
LinkSys E3000 (configuration available on port 8080)
 | .1  (10.233.1.x)

I was successfull in connecting to the configuration for LinkSys (on port 8080) via the ddns provider. No problems there. Right?
As said before, I can establish a connection between 192.168.1.105 SSH client to 192.168.1.107 SSH server and also 192.168.1.107 SSH client to 192.168.1.105 SSH server.
But I can't get a connection via ddns to any SSH server.
Now, I can see the configuration page (port 80) for ZyXEL and for LinkSys E3000 (forwarding port 8080 works). Why does it not work for port 22?
Here are the rules in ZyXEL for the forwarding:
# Status Name      WAN WAN_IP ServerIP      TriggerStart End TranslationStart End Protocol
1 active SSH       wan -      192.168.1.105 22           22   22           22   TCP/UDP
2 active http8080  wan -      192.168.1.105 8080         8080 8080         8080 TCP/UDP

Nothing strange here. And SSH communication between PC and laptop possible, nothing strange there. Where do I have to look for communication from ddns to PC? What do I forget?
Any suggestions are welcome!
Edit: 5 sept 2016.
Problem solved! With the help form the answers below I was able to iron out some configuration issues and a few minutes ago I was able to get a RDC going from my android to my PC. Nice!

A: You wrote you're inside the network and the following happens:

The service for ddns allows me to connect to my home network. If I try to connect port 80 I just get the login screen for my router

That means your router does not support NAT loopback. To properly test your port forwarding, you need to be outside the local network. You could use your phone with mobile broadband to test, for example.
Ping is filtered by default on most consumer-grade routers. That's security through obscurity, of course. It also makes diagnosing issues needlessly difficult, so you can just disable that option.
Also:
Your router's internal software is also not behaving properly. The web interface opens when you browse to your external IP address. This is very dangerous! Without knowing your internal network structure, an attacker can gain control of your router via cross-site scripting or the like.

A:
"I can make a SSH connection from the desktop to the laptop and the other way around, suggesting to me that port 22 is open on both computer. Right?"

Yes.  This indicates that the SSH server is running, and no software-based firewall (on either machine) is blocking that traffic.
Note that this does not mean that you can SSH in from another network.  Windows Firewall can have different rules apply depending on whether a network appears to be "Private", "Public", or "Guest".  So just because the software firewall allows one connection doesn't mean that another connection will work.  I'm not suggesting that this is likely to be the source of your problem, but if it is, it can be very tricky to detect if you don't think about it.
Let me also make sure you have an understanding of what an "open port" is.  We're referring to TCP port numbers and UDP port numbers.  These "ports" are simply numbers.  When a "port" is open, that means that a connection can be made to that port.
So, when someone tries to send an SSH request to your home's IP address, your ISP will dutifully pass that traffic onto the router in your building.  If the result is a successful connection, then the port is open.
Now, there are two ways that the router can handle that traffic in a way that makes the port be open.

*

*One of those ways is for the router to be running a program that responds to that port.  So, for port 22, that would typically mean that the router would be running an SSH server.  (And, for port 80, that would typically mean that the router is running an HTTP server, which we often call a "web server".)

*The other possible approach is for the router to pass along the traffic to another device.  This is typically done by sending traffic to a device on another subnet.  When the device does this, it "routes" the traffic.  That is why we often call these things a "router".
In order for the second approach to work, the router needs to know what system to send the traffic to.  This can be done using a process called "port forwarding".  All "port forwarding" really involves is telling the router what port number the traffic is expected to arrive on, and then what system the traffic goes to.
Now, if you check your router configuration, you might find that your "port forwarding" section is blank.  So, how can SSH be routed in that case?  Well, many routers have a configuration section called a "demilitarized zone", very often abbreviated "DMZ".  The way this DMZ works is really just a rather special rule for port forwarding.  You end up specifying what computer the router will use, and the router will send all ports to that computer, unless there is a more specific rule specified in the "port forwarding" section.  I think most routers don't usually place the DMZ into the port forwarding section, perhaps because the DMZ configuration might cause the router to forward IP traffic other than just those ports.
In general, you can only do one thing with incoming traffic on port 22.  Okay, so I suppose it is possible to do more than one thing, like have traffic from an office in Seattle to go to a laptop while traffic from Tokyo goes to the desktop.  However, such complicated setups are not common.  What would be far more common is to just have port forwarding send a different port (e.g. maybe 2222) to your other machine and have that machine listen on a non-standard port.
(Or have the router do some translation, so incoming traffic on port 2222 gets redirected to the other machine's standard port 22.  But then the machine that receives the traffic doesn't even have to know that port 2222 got used.  Hiding such information can make logs be less useful, and then you'd need to remember that the router is doing such translation.  Instead, of you just listen to port 2222, things are often more clear.)
Note that ICMP (used by ping, and multiple traceroute implementations) does not use a TCP port or a UDP port.  (ICMP sits above IP.  However, even though IP uses "Layer 3" of the OSI networking model, ICMP doesn't really qualify as being a protocol that is on "Layer 4" of the OSI Model, because it does not provide the typical conversation-tracking feature that tends to distinguish a "Layer 4" protocol.)
So now you see that having your port 22 open on the router won't necessarily help both machines to get SSH traffic.
Understand that your ZyXEL likely has two IPv4 addresses (assuming your Internet is using IPv4).  One is the 192.168.1.1.  That address is safe to tell us about, because it is an address listed in RFC 1918.  The other is a public address.  It sounds like that address changes (since you use DynDNS).  Don't tell us that address.  (For conversation, you can pretend like it starts with "203.0.113.", which is actually a set of addresses reserved for examples/documentation, as noted by RFC 5735 page 5.)
You may have an easier time by just not using Dynamic DNS, but getting a static IP from your ISP.  I know of an ISP local where I am (in the USA) that can give out a static IP (to a customer) on request, free of charge.  They might want to charge you (and, if so, you might want also ask what the price is for a /29, which is a block of 8, of which 5 are typically usable by the customer).  This isn't to suggest that your route of Dynamic DNS can't work, but I'm just throwing out another option for consideration.

The service for ddns allows me to connect to my home network. If I try to connect port 80 I just get the login screen for my router, no problems there.

You didn't say what IP address you use when connecting to port 80.  But since you said that right after talking about using DDNS, it sounds like you're talking about using your public IP address.  If that is actually the case, the last paragraph of Daniel B's answer is a quite valid warning.  Consumer grade routers are notorious for not having sufficient security for their web interfaces, so find the option that specifies that your web interface should be accessible only using the wired LAN connection.  (Trust neither connections from the Internet, nor Wi-Fi.)


text:
Q: The Network Adapter could not establish connection Oracle 12c I have an oracle12c database setup on my windows 8 machine & I am trying to access this database through JDBC from ubuntu(Linux) machine present in local area network.
When am trying to establish connection through JDBC, getting the following exception
The network adapter could not establish connection.
I have ensured the following.
1. Disabled the firewalls between both the machines.
2. the URL is proper & I tired using both hostname as well as ip address.
3. listener is up and running on port 1521.(lsnrctl stat shows the listener is READY)
I have done extensive google search about this. Please help.
Thanks in advance. Please let me know if you need more details.

A: make sure you have used proper jdbc driver for that database connection.

A: try to telnet the computer (Windows 8)  that is running DB from client computer (Ubuntu).


text:
Q: Getting 5XX error on product feeds when disabling WP feeds I am getting a 5XX error in Google Search Console after disabling the wordpress feeds. It worked correctly for about 6 months but it is no longer working correctly. I tried to look for solutions and I tried to see if maybe some of the code had been deprecated but I didn't see anything in search to highlight this. The code I added to disable the feed is listed below.
I tried to do a search in google and stack overflow but I did not find a solution to this problem. I did find the initial code in Google search but not a solution to the 5XX xml error message.
function wpb_disable_feed() { wp_die( __('No feed available,please visit our homepage!') );}

add_action('do_feed', 'wpb_disable_feed', 1);
add_action('do_feed_rdf', 'wpb_disable_feed', 1);
add_action('do_feed_rss', 'wpb_disable_feed', 1);
add_action('do_feed_rss2', 'wpb_disable_feed', 1);
add_action('do_feed_atom', 'wpb_disable_feed', 1);
add_action('do_feed_rss2_comments', 'wpb_disable_feed', 1);
add_action('do_feed_atom_comments', 'wpb_disable_feed', 1);

First step: remove the feed links from the section of your site.
add_action('wp_head', 'wpse33072_wp_head', 1);

remove feed links from wp_head
function wpse33072_wp_head (){ remove_action('wp_head', 'feed_links', 2); remove_action('wp_head', 'feed_links_extra', 3);}

The expected results is a simple container that says "no feed available, please visit our homepage" when you visit the feed URL. When you view the source code, you should not be able to see the link to the feed in the header.
The actual results is that the header link to the feed is not there, it has been removed and this is correct, it is also the second part of the code presented above, I expected this but not the xml error that I am getting in the feed when I visit the feed URL. That is coming from the first part of the code I have presented. So the issue seems to be in the function "wpb_disable_feed".
My only other thought is that some other code may be conflicting with this one. I just haven't found it yet but I will, hopefully with a little help from the community.

A: By default wp_die() will return 500 status code and that will affect your GCS report.
Try below code to return 200 status code:
function wpb_disable_feed() {
    wp_die(
        __('No feed available, please visit our homepage!'),
        'No feed available',
        array('response' => 200)
    );
}

A: Did you ever resolve this?
I am also trying to disable these RSS feeds but I don't get a nice HTML page with the boxed content when wp_die() is called, instead I get this nasty: "This XML file does not appear to have any style information associated with it." when I browse to https://website/feed/

Btw, the wp_die() function accepts message + title + arguments, and you can provide the status code as an argument e.g.:
wp_die( 'You Died','Dead',200 );

This will return a HTTP200 instead of the default HTTP500.


text:
Q: В чем тут ошибка ? Нужно вывести нечетное число которое больше 20 в Not Weird Пробовал разные варианты с условиями , но в любом случае выводит Weird в последнем условии. А нужно Not Weird
N = int(input('Ведите целое число..'))
if N % 2 != 0:
    print('Weird')
elif N % 2 == 0 and N >= 2 and N <=5:
    print('Not Weird')
elif N % 2 == 0 and N >= 6 and N <=20:
    print('Weird')
elif N % 2 !=0 and  N > 20:
    print('Not Weird')


text:
Q: python pptx How to change line format in chart based on XL_CHART_TYPE.LINE How to access line format object for series in chart based on XL_CHART_TYPE.LINE?
chart_data = ChartData()
vec2 = [ float(i.value) for i in xl_sheet.col(1)]
chart_data.categories = [ datetime.datetime.fromordinal(int(693594+i.value )) for i in xl_sheet.col(0)]
uu=chart_data.add_series('Model1',    tuple(vec2))

I didn't access to format of series line by
uu.format.line.color.rgb = RGBColor((100,100,100))

A: After the chart is created, you access each line by the series that line represents:
graphic_frame = slide.shapes.add_chart(..chart_data,..)
# ---graphic frame is the shape containing the chart, not the chart itself---
chart = graphic_frame.chart
# ---get the desired series from the chart---
series = chart.series[0]
# ---series.format is a ChartFormat object, which in turn provides access to
#    the LineFormat object for that series---
line = series.format.line
# ---change the line style, color, etc. the same way as for any other line---
line.color.rgb = RGBColor(255, 0, 0)