text:
Q: Spring Boot @Scheduled fixedDelay manipulation I am building an application what reads data from the database in every 'n' seconds.. in my @Scheduled method i would like to read data from my database, for configuring my @Scheduled task. It is important to read in every period, because it can change anytime.
So when i readed the data 'period' from my db table, i would like to access it into my @Scheduled(fixedDelay = period). My code not using the readed db value at the moment, but copied my code below.

Code:
@Scheduled(fixedDelay = 60000)
public void startSchedule() throws InterruptedException {

    //read data from db to configure Scheduling
    //equalize fixedDelay = db.getPeriod(); -> i am not able to do that...

    //do other fancy thing..

}

A: You can create a new scheduler inside your @Scheduled method.
ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
executor.scheduleWithFixedDelay(() => {
    // do your stuff
}, 0, delay, TimeUnit.SECONDS);

delay is this you've read from DB.

A: What is the question? Does the scheduling not work? Did you @EnableScheduling? Does it work but not with your variable?
If I understand correctly you would read a variable from the db and then you want to schedule something in the delay of that variable. So you would need to read the data from the database first, set it to a variable delay and then call another method with @Scheduled(fixedDelay = delay).


text:
Q: Checkbox that unchecks other checkboxes – Maya MEL I just recently started learning MEL scripting and I barely scrape the basics. But for now, I am able to write my own script which enables showing/hiding of objects in Maya 2015. The problem I am facing now is that I want a master checkbox that checks/unchecks other checkbox. The method I have now only enables me to change one children checkbox but not the rest.
ETC - None checkbox is on. All other children checkboxes are off. None checkbox is off. All other children are on. Right now I can manage to get one children checkbox to be toggle on and off with the master None checkbox.
Here's my code:
checkBox -label "None" -align "center" -v false -onCommand "OnNoneProcedure" -offCommand "offNoneProcedure" -changeCommand "checkBox -edit -value (!#1) checkboxNurbsCurves";
checkBox -label "NurbsCurves" -align "center" -v true -onCommand "OnNurbsCurvesProcedure" -offCommand "offNurbsCurvesProcedure" checkboxNurbsCurves;

Am I doing the right way with the changecommand method? if yes, how do I get the other children checkbox to on and off? or do I query the master None checkbox -v then use the -v of None to toggle the -v of children checkbox?

A: probably the easiest thing to do would be to create a procedure that sets all the checkboxes you want to the desired state, then specify that procedure as the changeCommand.
In order to get that to work, you'll probably want to name the checkboxes and/or store them into some string array variable that you can loop through to set within your procedure...  Fortunately, that's really easy since the checkbox command returns the full name of the checkbox it creates.

A: okay i got it working! haha my friend mentored me through the last step. basically this is how it works; 1) query current panel state 2)get results and pass into a array 3)use the results from returned array into another procedure into a new array 4)each result if 0 = off that element, if 1 = on that element return this new result 5)create shelf button with new result (result = command).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running time.sleep() on another thread freezes Tkinter program So I am trying to run time.sleep() on another thread, but the my entire program still freezes upon calling the function. I call it using a button. This is to create an error, and then wait a couple seconds to remove the error. Not sure what else to do here.
import threading, time

class Block():
    def createError(self, text):
        background.itemconfig(errorText, text=text, state=NORMAL, font="Neoteric 11 bold")
        background.itemconfig(errorBG, state=NORMAL)

        # Mainly this part to worry about
        t = threading.Thread(target=self.removeError())
        t.start()
        print("Function called") # Only prints AFTER 5 seconds, even though removeError() should be running on another thread

    def removeError(self):
        time.sleep(5)
        background.itemconfig(errorText, text="", state=HIDDEN)
        background.itemconfig(errorBG, state=HIDDEN)

# Tkinter stuff here to create button and run createError()

Any ideas would be awesome!

A: I figured it out. All that I had to do was use a different function inside threading.
Swap out:

t = threading.Thread(target=self.removeError())
t.start()

To:

threading._start_new_thread(self.removeError, ())

And that's it. Works like a charm!

A: You're calling self.removeError and then you're using the result as target.
So instead of:
t = threading.Thread(target=self.removeError())

you have to do this:
t = threading.Thread(target=self.removeError)


text:
Q: How to determine most Important/Informative features using Linear Support Vector Machines (SVM) classifier I am new to python and working on a text classification problem. I am interested in the visualization of the most important features of each class through a linear SVM classifier model. I want to determine which features are contributing towards the classification decision as Class-1 or Class-2 by classification model. This is my code.
df = pd.read_csv('projectdatacor.csv')
df = df[pd.notnull(df['types'])]
my_types = ['Requirement','Non-Requirement']

#converting to lower case
df['description'] = df.description.map(lambda x: x.lower())

#Removing the punctuation
df['description'] = df.description.str.replace('[^\w\s]', '')

#splitting the word into tokens
df['description'] = df['description'].apply(nltk.tokenize.word_tokenize)

## This converts the list of words into space-separated strings
df['description'] = df['description'].apply(lambda x: ' '.join(x))
count_vect = CountVectorizer()
counts = count_vect.fit_transform(df['description'])

#tf-idf
transformer = TfidfTransformer().fit(counts)
counts = transformer.transform(counts)

#splitting the data and training the model
#naives-bayes
X_train, X_test, y_train, y_test = train_test_split(counts, df['types'], test_size=0.3, random_state=39)

#svc classification
from sklearn import svm
svclassifier = svm.SVC(gamma=0.001, C=100., kernel = 'linear')

svclassifier.fit(X_train, y_train)
y_pred = svclassifier.predict(X_test)

#evalutaing the model
print(classification_report(y_test,y_pred))
print(confusion_matrix(y_test,y_pred))
print('accuracy %s' % accuracy_score(y_pred, y_test))
print(classification_report(y_test, y_pred,target_names=my_types))

I have read all related questions available on this platform but I found the following useful code which I added in my code.
import numpy as np
def show_most_informative_features(vectorizer, clf, n=20):
    feature_names = vectorizer.get_feature_names()
    coefs_with_fns = sorted(zip(clf.coef_[0], feature_names))
    top = zip(coefs_with_fns[:n], coefs_with_fns[:-(n + 1):-1])
    for (coef_1, fn_1), (coef_2, fn_2) in top:
        print ("\t%.4f\t%-15s\t\t%.4f\t%-15s")  % (coef_1, fn_1, coef_2, fn_2)
show_most_informative_features(count_vect, svclassifier, 20)

This code works for naive Bayes and logistic regression and it gives the most important features but for SVM it gives me the error.
I am getting this error.
  File "C:\Users\fhassan\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
    execfile(filename, namespace)

  File "C:\Users\fhassan\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "U:/FAHAD UL HASSAN/Python Code/happycsv.py", line 209, in <module>
    show_most_informative_features(count_vect, svclassifier, 20)

  File "U:/FAHAD UL HASSAN/Python Code/happycsv.py", line 208, in show_most_informative_features
    print ("\t%.4f\t%-15s\t\t%.4f\t%-15s" % (coef_1, fn_1, coef_2, fn_2))

TypeError: must be real number, not csr_matrix

Any help shall be highly appreciated.

A: Maybe this will help you:
from sklearn import svm
import pandas as pd
import numpy as np

from sklearn.feature_extraction.text import CountVectorizer
corpus = [
    'This is the first document.',
    'This document is the second document.',
    'And this is the third one.',
    'Is this the first document?']

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)

x=X.toarray()
y=[0,0,0,1]

model=svm.SVC(kernel='linear')

a=model.fit(x,y)
model.score(x,y)

feature_names = vectorizer.get_feature_names()
coefs_with_fns = sorted(zip(model.coef_[0], feature_names))
df=pd.DataFrame(coefs_with_fns)
df.columns='coefficient','word'
df.sort_values(by='coefficient')

You will get:


text:
Q: Angular ngrx/store :Selector return null value As per title when I use my selector in my component I got undefined value. Here is my reducer
export interface State extends AppState.State {
transactions: TransactionState
 }
 export interface TransactionState {
  transactions: Transaction[]
  error: string
   }
   const initialState: TransactionState = {
    transactions: [],
    error: '',
      }

    export const transactionReducer = createReducer<TransactionState>(
     initialState,
     on(TransactionActions.loadTransactions, (state, action) => {
    return { ...state, transactions: action.transactions }
     }),
    on(
       TransactionActions.errorItem,
      (state, action): TransactionState => {
     return {
        ...state,
     error: action.message,
     }
    },
     )   ,
      )
    export const selectFeature = (state: State) => state.transactions
   export const selectTransactions = createSelector(
   selectFeature,
     (state: TransactionState) => state.transactions,
 )

Here my actions
export const getTransactions = createAction('[Transaction] get transactions')

 export const loadTransactions = createAction(
  '[Transaction] load transactions',
 props<{ transactions: Transaction[] }>(),
  )

And here my effect that make a call to backend service
@Injectable()
export class TransactionEffects {
constructor(
  private actions$: Actions,
  private transactionService: TransactionService,
   ) {}

loadTransactions$ = createEffect(() =>
 this.actions$.pipe(
  ofType(getTransactions),
  mergeMap((action) => {
    console.log('inside effect')

    return this.transactionService.getTransactionsByUsername(3).pipe(
      map((data) => {
        console.log('data', data)
        return loadTransactions({ transactions: data })
      }),
      catchError((error) =>
        of({
          type: '[Transaction] error item',
          message: error,
        }),
      ),
    )
  }),
),

)
When I dispactch the getTransactions action in my component adnd select the state I got the console log res undefined

 ngOnInit(): void {
this.userService.getBalance().subscribe((bal) => {
  this.currentBalance = bal
})
this.store.subscribe((state) => console.log('debug state store', { state }))
this.store.dispatch(TransactionActions.getTransactions())
this.store
  .select(selectTransactions)
  .subscribe((res) => console.log('res is', res))

Plus when I use the redux dev tool I got a transactionReducer object before my transactions object itself

Could someone explain me what is going on and what  am I missing? Thanks

A: Your first selector is already grabbing transactions
export const selectFeature = (state: State) => state.transactions;

export const selectTransactions = createSelector(
  selectFeature,
  (state: TransactionState) => state // this one already has transactions
                                     // no need of state.transactions
);

So undefined is expected since transactions.transactions doesn't exit


text:
Q: Assigning quantiles in R where quantiles are not unique Let x be a vector of numeric, non-negative data (mostly < 10) and qx <- quantile(x, probs = pq), and where length(pq) is typically > length(x) * (3/4).
I am in need of a vector of indices of qx, call it q_i, where x[i] falls in the quantile qx[q_i[i]].
The catch, as the title indicates, is that there may be non-unique values present in qx, e.g. multiple 0-valued quantiles if x is zero-inflated, and potentially other duplicate values. I would like to handle these cases by either (a) recycling the sequence of indices of these equivalent quantiles, or (b) randomly assigning the indices of equivalent quantiles. I think I would prefer option (a), but a solution for either would be useful.
Here is an edit to provide the rules for determining q_i[i] for a particular  x[i]:
Consider that qx has one or more sequences of duplicate values, i.e. for some j there is (are) sequence(s) qx[j:n] where qx[j] == qx[j + 1] == ... == qx[j + n] < qx[j + n + 1]. Let k = c(j, j + 1,..., j + n). Then q_i[i] <- k[r] where qx[j] <= x[i] <= qx[j + n + 1] if j == 1 or qx[j] < x[i] <= qx[j + n + 1] if j > 1, and where r <- m %% (n + 1) such that x[i] is the m-th occurrence in x where the inequality has been satisfied.
NOTE: based on this rule, I realized I omitted a 4 in my original q_i - this has been changed.
NOTE: @hodgenovice brought up a good point regarding special cases where data values that are strictly smaller than two quantiles may be grouped into the "bin" between two such quantiles. I am not particularly concerned with the special case because, if for example there were no duplicate quantiles but we had the same quantile values, those special cases would correctly be binned together.
I'm thinking there is an efficient way to do this - I have essentially done this using a for loop but I am looking for a vectorized approach.
I started trying to work with cut() which of course doesn't allow non-unique breaks. I found this question here which kind of helped, in that I discovered the .bincode() function, which does allow non-unique breaks. However, it has no rule for "distributing" the indices - it would only use the index of the first of each duplicated quantile value.
Some example code for this problem:
x <- c(5.8,  0.0, 16.1,  5.8,  3.5, 13.8,  6.9,  5.8, 11.5,  9.2, 11.5,
       3.5,  0.0,  8.1,  0.0,  4.6,  5.8,  3.5,  0.0, 10.3,  0.0,  0.0,
       3.5, 6.9, 3.5)
pq <- seq(0, 1, length.out = 20)
qx <- quantile(x, pq)

# quantiles for reference, rounded for readability
round(as.numeric(qx), 2)
[1]  0.00  0.00  0.00  0.00  0.18  3.50  3.50  3.50  3.62  5.04  5.80 5.80  5.97
[14] 6.90  7.72  9.14 10.55 11.50 13.19 16.10

q_i <- .bincode(x, qx, include.lowest = TRUE)
q_i
[1] 10  1 19 10  5 19 13 10 17 16 17  5  1 15  1  9 10  5  1 16  1  1  5 13 5

Here are the results I would be looking for, if .bincode() was magic and I could talk it into doing what I need:
Under scenario (a) above:
(I edited this too, as I was originally missing a value of 4)
q_i
[1] 10 1 19 11 5 19 13 10 17 16 17 6 2 15 3 9 11 7 4 16 1 2 5 13 6

Under scenario (b), it could, with low probability, look the same as directly above. Or something like:
q_i
[1] 10 1 19 10 6 19 13 11 17 16 17 5 3 15 2 9 11 6 2 16 1 4 5 13 7

Note here that the full vectors of "equivalent" qx sequences that get recycled are essentially sampled without replacement.
Thanks!

A: Okay, I've got some code which continues from yours to get to the final q_i under scenario a (recycling). I wish it was a bit prettier, but hope it helps anyway.
Note:
- This assumes length(x) > length(qx) > length(x)/2.
- In the explanation below the code, q_i refers to the value at the end of the question, before any recycling or replacement of values has taken place.
## Start off with the code provided in the question...
#  1. For each distinct q_i, calculate the number of occurrances, and how far we can recycle it
df <- data.frame(lower=sort(unique(q_i)), freq=as.integer(table(q_i)))
df$upper <- c(df$lower[-1] - df$lower[-nrow(df)], 1) + df$lower - 1
df$upper <- df$upper - as.numeric(df$upper > df$lower & qx[df$upper] < qx[df$upper + 1])

#  2. Identify when there's a (single) number we can't recycle, and identify which position it's in
#     e.g. is it the third time q_i == 10?
df$special_case <- rep(NA, nrow(df))
df$special_case[df$lower < df$upper] <- sapply(df$lower[df$lower < df$upper], function(low) {
                                        bin <- x[q_i==low]
                                        if(length(unique(bin)) > 1) {
                                          return(match(min(bin), bin))}
                                        else return(NA)})

# 3. For each row of df, get a vector of (possibly recycled) numbers
recycled <- apply(df, 1, function(x) {
  out <- rep(x["lower"]:x["upper"], length.out=x["freq"])

  # This part modifies the vector created to handle the 'special case'
  if(!is.na(x["special_case"])) {
    out[x["special_case"]] <- x["lower"]
    if(x["special_case"] < x["freq"]) {
      out[(x["special_case"]+1):x["freq"]] <- out[x["special_case"]:(x["freq"]-1)]
    }
  }
  return(out)
})

# 3b. Make this follow the same order as q_i
q_i_final <- unlist(recycled)[order(order(q_i))]

q_i_final
[1] 10  1 19 11  5 19 13 10 17 16 17  6  2 15  3  9 11  7  1 16  2  3  5 13  6

What's the basic idea?
For each value of q_i, we can fairly easily calculate the number we should recycle up to (if we should recycle at all). We can typically recycle up to one less than the next largest value of q_i. We can then use rep to create a recycled vector to replace what's in q_i e.g. to replace the four 10s with 10 11 10 11.
What else is there to consider?
This basic idea assumes that for each value of q_i, the corresponding value(s) of x can either be all recycled or all not. This is usually the case, but you can also have some value of q_i where all bar one can be recycled i.e. one k such that x[k] < qx[q_i[k]+1], but one or more j where q_i[j] = q_i[k] and also x[j] = qx[q_i[j]+1].
Such 'special' cases (although not present in the question data) should be identified, and care must be taken that this value is not also recycled.

Special case in more detail

*

*We can make some simple changes to the question data to create this case (see code below). Note that x[5] > x[12], but q_i[5] = q_i[12] = 4. Now, under the 'basic idea' described above, all values where q_i = 4 would be recycled, so we would have q_i_final[12] = 5. This is a problem because  we want x[12] to be between qx[q_i_final[12]] and qx[q_i_final[12]+1], which isn't the case since it's strictly less than both. It turns out we are fine to recycle all the values where q_i = 4, except for x[12].

New Code:
# Code copied from question, changes as follows:
# x[12] changed from 3.5 to 3.4
# x[13] and x[21] changed from 0.0 to 10.0
x <- c(5.8,  0.0, 16.1,  5.8,  3.5, 13.8,  6.9,  5.8, 11.5,  9.2, 11.5,
       3.4,  10.0,  8.1,  0.0,  4.6,  5.8,  3.5,  0.0, 10.3,  10.0,  0.0,
       3.5, 6.9, 3.5)
pq <- seq(0, 1, length.out = 20)
qx <- quantile(x, pq)
q_i <- .bincode(x, qx, include.lowest = T, right=T)

q_i
[1]  8  1 19  8  4 19 12  8 17 14 17  4 15 13  1  8  8  4  1 16 15  1  4 12  4

A: This code is based off of @hodgenovice's answer, but does not consider the special case.
It has an additional condition that correctly recycles the values for the first sequence of duplicated quantiles. This was an error on my part in the question, I originally omitted a q_i of 4 from my desired answer, but it should be one of the indices recycled for data values assigned a q_i of 1 by .bincode().
df <- data.frame(lower=sort(unique(q_i)), freq=as.integer(table(q_i)))
df$upper <- c(df$lower[-1] - df$lower[-nrow(df)], 1) + df$lower - 1
# want to omit this adjustment if the first quantile is also the first
#   duplicate, to follow rule described in question edit
ub <- df$lower != 1
df$upper[ub] <- df$upper[ub] - as.numeric(df$upper[ub] > df$lower[ub] &
                  qx[df$upper[ub]] < qx[df$upper[ub] + 1])

recycled <- apply(df, 1, function(x) {
  out <- rep(x["lower"]:x["upper"], length.out=x["freq"])

  return(out)
})

q_i_final <- unlist(recycled)[order(order(q_i))]


text:
Q: New 14.04 LTS install fails to boot with purple screen I have just installed Ubuntu 14.04 and it got to the prompt which said it had finished installing and needed to be restarted. When booting it shows a purple screen then the monitor switches off after with no video response. I can boot using recovery mode, so I think it might be graphics card related.
Is it possible to edit the settings to make the normal boot use default video drivers?

A: The section "Black/purple screen after you boot Ubuntu for the first time" from My computer boots to a black screen, what options do I have to fix it? helped. Installed NVIDIA drivers and now working.


text:
Q: NuGet package referencing issues in new Nuget Class Library template in Visual Studio 2015 I've been working with the pre-release version of VS2015 recently which gave the option of a "ASP.NET 5 Class Library" which has since changed in RTM to simply "Class Library (Package)" With the description PREVIEW - A project template for creation a class library as a NuGet package that can target any platform
I recently created one of these new Class Library projects and added in into a solution which also included an ASP.NET 5 project. I used the Package manager console to add in references to Entity Framework 7 to both projects which worked fine, adding the correct text into the project.json files in both projects (the Reference section in VS also updated accordingly). But when trying to add using Microsoft.Data.Entity; to my Class Library project I cannot reference it at all. It works fine in the ASP.NET project.
Intellisense gives me options for 'Microsoft.CSharp' and one other namespace, but not 'Data'. I've tried creating an entirely new solution from scratch but this still hasn't helped.
I also tried adding references to the dnx XUnit stuff to the project as per their website's guidelines but these did not work either.
EDIT: I think the problem lies somewhere with the dotnet Target Framework Moniker(TFM) which looks to have been introduced in DNX SDK 1.0.0-beta5 as there are not issues when using dnx451 in 1.0.0-beta4

A: I just went through the process of adding 2 projects. A class library and an mvc 6 project. I could duplicate your issue. To fix it I edited the class library project.json and changed the property under "frameworks" from
dotnet to the 2 frameworks dnx451 and dnxcore50 as is found in the web project. Hope this helps.

A: Delete all files in %userprofile%\.dnx\packages and then in the VS2015 Package Manager window execute "dnu restore".

A: I've finally found a post on github from the author of xunit, Brad Wilson who states that currently the dotnet TFM doesn't work as you would expect and that the dnx451 and dnxcore50 are better TFM's to target.

Link to comment

A: Try open a command line terminal in the directory containing Class Library's project.json and type
dnu restore


text:
Q: How to redirect www and non www request to https non www version of my website in tomcat 8 at ec2 instance I am using EC2 Instance for my web application. I bought a new SSL and installed it at AWS classic load balancer and my SSL is working fine. But for an SEO point of view, I want to redirect all the requests from www and non-www and HTTP www and HTTP non-www request to https non-www version. I am running my application in tomcat 8 version. I don't have any apache or any other server. I read many articles they mentioned that by doing .htaccess file but I hope its doesn't work in tomcat8.
I create a file in the WEB-INF folder called rewrite.config. and past this code. it's working somehow but not all the above possible case.
# bounce all requests coming in on HTTP to HTTPS
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

A: You can do this URL forwarding in your DNS provider. I hope it is pretty straight forward check it your DNS provider.


text:
Q: Object method as callback function I have the following piece of code:
function Obj() {
    var container = [1, 2, 3];
    this.callback_m = function() {
        if (obj.exists(this)) {
            //...
        };
    }
    this.exists = function(element) {
        return !(container.indexOf(element) == -1);
    }
}

var obj = new Obj();
$(".elem").on('click', obj.callback_m);

I'm using an object's method as a callback function. It is obvious that when this method is called 'this' is set to the element for which the event was triggered. I'm passing 'this' element to the 'exists' method of an object to see if it's present in collection. However, to get to 'exists' method I need to reference 'obj' varible which references my object.
obj.exists(this)

But this is certainly a wrong choice since 'obj' can have different name or be out of scope. And I can't use bind() here either because I need the reference to the element the event was triggered for.
The only solution I came up with is to use closure to remember reference to itself. This is how it looks right now:
function Obj() {
    var container = [1, 2, 3];
    var self = this;
    this.callback_m = function() {
        if (self.exists(this)) {
            //...
        };
    }
    this.exists = function(element) {
        return !(container.indexOf(element) == -1);
    }
}

Is there any other solution to the problem and what are the potential problems with the apporoach I came up with?


text:
Q: Kudo shows extra Process I have a triggered web job, hosted in 1 instance App Service Plan.
In Kudo Process, why do I see two processes? See picture.

A: The process labeled as SCM is for running Kudu, the other one is for the web App

*

*Every Azure Web App includes a "background "service site called Kudu. It is useful for capturing memory dumps, looking at deployment logs, viewing configuration parameters and much more.


text:
Q: lframConvergence of $\sum_{n=2}^\infty \frac1{\log(n!)}$ How do I show that this sum diverges/converges?
 $$\sum_{n=2}^\infty \frac1{\log(n!)}$$

I want to use the comparison test, but I do not know how to approach.
Also, Wolfram says this diverges by the comparison test, but Mathematica gives me a numerical answer using the NSum function.

A: Hint: We have $$\log(n!)=\log n+\log(n-1)+\cdots+\log2<\log n+\log n+\cdots\log n<n\log n.$$ Now apply the comparison test and make use of the integral test.


text:
Q: When APNS tokens fail, is it a must to repeat the remaining push notifications? I'm sending 1-10 notifications at a time, sometimes one of the tokens fail, I'm guessing they fail when a user deletes the app (or other similar reasons), do I need to retry the remaining tokens/notifications for that batch? (I receive a "failed token" warning later on from PyAPNS)
The tokens are all valid tokens, it's stated that malformed tokens require a retry of the remaining push notifications, however I'm wondering whether I need to retry too with non-malformed tokens, it would be pretty stupid If I need to retry in the above scenario, people delete apps all the time, I'm guessing a high percentage of batches would require a retry
(There are many questions related to this issue, however I wasn't able to find a definite answer, from my trials I'm guessing I already have my answer, It seems the notifications aren't delivered in the above scenario)

A: I don't know what causes PyAPNS to return a "failed token" warning. If it refers to a token belonging to a device that uninstalled the app (which I doubt, since such device tokens are only returned by the Feedback Service), you don't have to re-send the remaining notifications.
However, if this failure is caused by an error response of InvalidToken, this means the connection to APNS was closed after the invalid token was processed, and any notifications that were sent after it must be re-sent.


text:
Q: How to chain call hasOne with morphMany? I think the concept relation should easy to understand. just set relations and chain with proper foreign.
I try to chain relation hasOne with morphMany. But hasOne can't access morph relations

Call to undefined method
Illuminate\Database\Eloquent\Relations\HasOne::images()

media model
public function poster(){
  return $this->hasOne(Media::class);
}

poster model
public function images(){
  return $this->morphMany(Image::class, 'imageable');
}

controller
$media = Media::first();

$media->poster()->images()->create();

A: You cannot chain that way, but you can chain this way:
$media->poster->images()->create()

which is short for:
$media->poster()->first()->images()->create()

You first need to have a proper poster object before you can access the images


text:
Q: Split dataframe into multiple dataframes I am learning pandas for a new project and I am relatively new and seeking help. I have the following dataframe.
The DateTime range from "2020-03-27 00:10:02" to 2020-03-27 23:50:01 repeats 18 times across the dataframe capturing different types of data within this timeline.
I would like to split this dataframe into different dataframes each one having its own data related to the range "2020-03-27 00:10:02" to 2020-03-27 23:50:01.
When I try:
df [(df["Date"] > '2020-03-27 00:10:00') & (df ["Date"] < '2020-03-27 23:55:00')],
it selects the almost the entire dataframe across all the repetitive ranges.
Any suggestions? Dataframe attached as an image.
enter image description here
Adding further information that the range repeats like below. (Although the length of the range is not important).
I would like to segregate each range of "12:00:01 AM" to "11:50:01 PM" into a dataframe each.
Row1    : 12:00:01 AM
Row3588 : 11:50:01 PM
Row3589 : 12:00:01 AM
Row3876 : 11:50:01 PM
Row3877 : 12:00:01 AM
Row4020 : 11:50:01 PM
Row4021  : 12:00:01 AM
Row4452  : 11:50:01 PM

A: I think you first need to make sure there is no duplicate and there are 18 different type of data for each DateTime index.
For example, it seems that there is only one row corresponding to 2020-03-27 23:50:01. At this point, you cannot really separate the dataframe yet since the data is not stored in a consistent format. If you can figure out ways to have 18 data types for each time, then you could try
df_type1 = df.loc[[i for i in range(9820) if i % 18 ==0],:]
df_type2 = ...


text:
Q: Calculating unpolarized scattering cross section (Peskin &Schroeder) From Peskin and Schroeder's Introduction to Quantum Field theory, in order to calculate the scattering cross section of, for example, $e^-(p)e^+(p')\rightarrow \mu^-(k)\mu^+(k')$, we first want to average the amplitude $\mathcal{M}$ over all spin states: $\frac{1}{4}\sum_{\text{spins}}|\mathcal{M}|^2$.
The book gives a pretty straightforward explanation of why (in the limit $m_e\rightarrow0$) this turns out to be:
$$
\frac{1}{4}\sum_{\text{spins}}|\mathcal{M}|^2=
\frac{4e^4}{q^4}\biggl(p'^\mu p^\nu+p'^\nu p^\mu-g^{\mu\nu}(p\cdot p')\biggr)\cdot
$$
$$
\cdot\biggl(k_\mu k_\nu'+k_\nu k_\mu'-g_{\mu\nu}(k\cdot k'+m_\mu^2)\biggr)
$$
But then it claims that this comes out to:
$$
\frac{8e^4}{q^4}\left[(p\cdot k)(p'\cdot k')+(p\cdot k')(p'\cdot k)+m_\mu^2(p\cdot p')\right]
$$
With no explanation, but I can't figure out how.
My own calculation gives:
$$
\frac{16e^4}{q^4}\biggl(p'^\mu p^\nu+p'^\nu p^\mu-g^{\mu\nu}(p\cdot p')\biggr)\biggl(k_\mu k_\nu'+k_\nu k_\mu'-g_{\mu\nu}(k\cdot k'+m_\mu^2)\biggr)=
$$
$$
\frac{4e^4}{q^4}\biggl((p'\cdot k) (p\cdot k')+(p'\cdot k')(p\cdot k)-(p'\cdot p)(k\cdot k'+m_\mu^2)+
$$$$
(p'\cdot k')(p\cdot k)+(p'\cdot k)(p\cdot k')-(p'\cdot p)(k\cdot k'+m_\mu^2)-(p\cdot p')(k\cdot k')-(p\cdot p')(k\cdot k')+(p\cdot p')(k\cdot k'+m_\mu^2)\biggr)
$$
Which gives:
$$
\frac{4e^4}{q^4}\biggl(2(p\cdot k')(p'\cdot k)+2(p\cdot k)(p'\cdot k')-3(p\cdot p')(k\cdot k') -p\cdot p' m_\mu^2\biggr)
$$
I probably have some identity related to a minus sign that I missed, but even so, I don't see how the term containing $(p\cdot p')(k\cdot k')$ can vanish, seeing how there is an odd number of such terms, meaning that no change of signs can make it vanish.
What is it I'm missing here?

A: Okay, my problem was not with the sign but rather because $g^{\mu\nu}g_{\mu\nu}=4$ in 4 dimensions, which makes it work.

A: The mistake is in the fact that $g_{\mu \nu}g^{\mu\nu} = 4$ not $1$. Therefore the terms of the form $(p\cdot p')(k\cdot k')$ cancel.


text:
Q: Arguments too long exception to delete 10k files-Python -HDFS I have 15k files with different dates in HDFS folder. I am trying to delete the files older than 10 days in which I have 10k files to be deleted from HDFS. When I was trying to delete these 10k files at a time by passing to a list I'm getting error. Could you please help me in sorting this issue.
I tried to use find and xargs but it is accepting single file but not multiple fils.
delete_cmd = 'hadoop fs -find /test/folder/* -name ' +filepath+ ' | xargs hadoop fs -rm -r -skipTrash'

OSError: [Errno 7] Argument list too long: '/bin/sh'
folder = '/test/folder/*'
no_of_days = 10
now_dt = datetime.now()

def list_files():
  hdfs_cmd = "hdfs dfs -ls -r " + folder  + " | grep / "
  hdfs_output = subprocess.getoutput(hdfs_cmd)
  return hdfs_output

def delete_cmd(filepath):
  delete_cmd = 'hdfs dfs -rm -r -skipTrash '  + filepath
  delete_output = subprocess.getoutput(delete_cmd)
  print(delete_output)

def delete_olderfiles():
  hdfs_outputfun = list_files()
  delete_list = []
  filepath_list = [line.split(' ')[-1] for line in hdfs_outputfun.splitlines()]
  for filepath in filepath_list:
        filename = filepath.split('/')[-1]
        filename_dt = datetime.strptime(filename, '%Y%m%d.csv')
    diff_days = (now_dt - filename_dt).days
    if diff_days > no_of_days:
        delete_list.append(filepath)
 string = " "
 delete_folders = string.join(delete_list)
 delete_cmd(delete_folders)

delete_olderfiles()

output to delete files:
hdfs dfs -rm -r -skipTrash file20210901.csv file20210801.csv file20210903.csv ...10kfiles

A: I think the problem is that the command line can only take so much data as arguments as explained here: https://unix.stackexchange.com/questions/45583/argument-list-too-long-how-do-i-deal-with-it-without-changing-my-command

On Linux, the maximum amount of space for command arguments is 1/4th of the amount of available stack space. So, a solution is to increase the amount of space available for the stack.

Short version: run something like
ulimit -s 65536

Another solution would be to call the rm command once per file:
for item in delete_list:
    delete_cmd(item)

and put this code at the end of your delete_olderfiles() (and do not call delete_cmd() on a contcatinated list of all the files to delete).


text:
Q: How to avoid login with an empty password field in ASP.NET MVC 5? I'm working on an ASP.NET MVC 5 project where I have created a customized login and registration page. The application is working fine, but the problem is I am able to login even when my password field is empty.
Here is the code for controller(I used all Namespaces and reference correctly)
public class UserController : Controller
{
    //
    // GET: /Register/
    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult LogIn()
    {
        return View();
    }

    [HttpPost]
    public ActionResult LogIn(Models.Register userr)
    {
        if (IsValid(userr.Email_Id, userr.Password))
        {
            FormsAuthentication.SetAuthCookie(userr.Email_Id, false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", "Login details are wrong.");
        }

        return View(userr);
    }

    [HttpGet]
    public ActionResult Register()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Register(Models.Register user)
    {
        try
        {
            if (ModelState.IsValid)
            {
                using (var db = new MvcApplication2.Models.OnlineEducationEntities())
                {

                    var newUser = db.Registers.Create();
                    newUser.Email_Id = user.Email_Id;
                    newUser.Password = user.Password;
                    newUser.Student_Name = user.Student_Name;
                    newUser.DOB= DateTime.Now;

                    db.Registers.Add(newUser);
                    db.SaveChanges();
                    return RedirectToAction("LogIn", "User");
                }
            }
            else
            {
                ModelState.AddModelError("", "Data is not correct");
            }
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);

                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }

            throw;
        }

        return View();
    }

    public ActionResult LogOut()
    {
        FormsAuthentication.SignOut();
        return RedirectToAction("LogIn", "User");
    }

    private bool IsValid(string email, string password)
    {
        var crypto = new SimpleCrypto.PBKDF2();
        bool IsValid = false;

        using (var db = new MvcApplication2.Models.OnlineEducationEntities())
        {
            var user = db.Registers.FirstOrDefault(u => u.Email_Id == email);
            if (user != null)
            {
                if (user.Password == crypto.Compute(password, user.Password))
                {
                    IsValid = true;
                }
            }
        }

        return IsValid;
    }
}

And the is my view:
@model MvcApplication2.Models.Register
@{
    ViewBag.Title = "LogIn";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

LogIn

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Register</legend>

            @Html.LabelFor(model => model.Email_Id)

            @Html.EditorFor(model => model.Email_Id)
            @Html.ValidationMessageFor(model => model.Email_Id)

            @Html.LabelFor(model => model.Password)

            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)

            <input type="submit" value="LogIn" />

    </fieldset>
}

        @Html.ActionLink("Register Now", "Register")

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

A: Add this check to your IsValid method:
private bool IsValid(string email, string password)
{
    if (string.IsNullOrWhiteSpace(password) || password.Length < 6)
        return false;

    //... etc.

The problem is, since you are  not using ModelState.IsValid, you'll need an alternative. Your IsValid method seems to be that alternative.


text:
Q: Inverse of a tridiagonal, irreducible, weakly diagonally dominant matrix I have the following matrix:
$\left( \begin{array}{ccc}
1 & -\frac{k-1}{k} & 0 & 0 & 0 & 0 & \cdots\\
-\frac{2}{k} & 1 & -\frac{k-2}{k} & 0 & 0 & 0 & \cdots\\
0 & -\frac{3}{k} & 1 & -\frac{k-3}{k}  & 0 & 0& \cdots\\
0 & 0 & -\frac{4}{k} & 1 & -\frac{k-4}{k}  & 0 & \cdots\\
\cdots& \cdots& \cdots& \cdots& \cdots& \cdots& \cdots\end{array} \right)$
Since it is  tridiagonal, irreducible, weakly diagonally dominant matrix, I know it is invertible. Is there any easy way to find the inverse in terms of the parameters?


text:
Q: LaTeX: Checking if number of occurrences of a character in a string is some number This is a follow-up question to LaTeX count number of occurrences of a character in a string
This works fine for printing the value. Now what I need is to check if this command returns a specific value. I'd like to do something like
if \CountSubStr{~}{This~is a ~test} = 0 then A else B.

Is it doable?

A: Here's a fairly general macro:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\countsubstringtestTF}{mmmmm}
 {% #1 = substring to test for, #2 = string, #3 = test, #4 = true text, #5 = false text
  \seq_set_split:Nnn \l__salys_substring_seq { #1 } { #2 }
  \cs_set:Nn \__salys_substring_test:n
   {
    \int_compare:nTF { #3 } { #4 } { #5 }
   }
  \__salys_substring_test:n { \seq_count:N \l__salys_substring_seq - 1 }
 }
\seq_new:N \l__salys_substring_seq
\ExplSyntaxOff

\begin{document}

\countsubstringtestTF{~}{This is a test}{#1>2}{greater than 2}{not greater than 2}

\countsubstringtestTF{~}{This~is a~test}{#1>2}{greater than 2}{not greater than 2}

\countsubstringtestTF{~}{This~is~a~test}{#1>2}{greater than 2}{not greater than 2}

\countsubstringtestTF{~}{This is a test}{1 <= #1 <= 2}{between 1 and 2}{not between 1 and 2}

\countsubstringtestTF{~}{This~is a~test}{1 <= #1 <= 2}{between 1 and 2}{not between 1 and 2}

\countsubstringtestTF{~}{This~is~a~test}{1 <= #1 <= 2}{between 1 and 2}{not between 1 and 2}

\end{document}

The number of matches is denoted, in the third argument, by #1; you can do several sorts of comparisons, like the ones shown here.

If you want to allow the second argument to be a control sequence, you can define a variant.
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\countsubstringtestTF}{smmmmm}
 {
  \IfBooleanTF { #1 }
   {
    \salys_countsubstringtest:nVnTF #2 { #3 } { #4 } { #5 } { #6 }
   }
   {
    \salys_countsubstringtest:nnnTF { #2 } { #3 } { #4 } { #5 } { #6 }
   }
 }
\cs_new_protected:Nn \salys_countsubstringtest:nnnTF
 {% #1 = substring to test for, #2 = string, #3 = test, #4 = true text, #5 = false text
  \seq_set_split:Nnn \l__salys_substring_seq { #1 } { #2 }
  \cs_set:Nn \__salys_substring_test:n
   {
    \int_compare:nTF { #3 } { #4 } { #5 }
   }
  \__salys_substring_test:n { \seq_count:N \l__salys_substring_seq - 1 }
 }
\seq_new:N \l__salys_substring_seq
\cs_generate_variant:Nn \salys_countsubstringtest:nnnTF { nV }
\ExplSyntaxOff

\newcommand{\mystringA}{This~is a~test}
\newcommand{\mystringB}{This~is~a~test}

\begin{document}

\countsubstringtestTF{~}{This is a test}{#1>2}{greater than 2}{not greater than 2}

\countsubstringtestTF*{~}{\mystringA}{#1>2}{greater than 2}{not greater than 2}

\countsubstringtestTF*{~}{\mystringB}{#1>2}{greater than 2}{not greater than 2}

\countsubstringtestTF{~}{This is a test}{1 <= #1 <= 2}{between 1 and 2}{not between 1 and 2}

\countsubstringtestTF{~}{This~is a~test}{1 <= #1 <= 2}{between 1 and 2}{not between 1 and 2}

\countsubstringtestTF{~}{This~is~a~test}{1 <= #1 <= 2}{between 1 and 2}{not between 1 and 2}

\end{document}

A: I don't really understand expl3, so may be better ways to do this. You can get this to work by adding by adding an \if_int_compare:w test to Werner's code:
\documentclass{article
\usepackage{xparse}

\ExplSyntaxOn
% \IfCountSubStrCompare{<substring>}{<string>}{=, < or >}{<int>}{<iftrue>}[<iffalse>]
\NewDocumentCommand{\IfCountSubStrCompare}{ m m m m m o }{
  \seq_set_split:Nnn \l_tmpa_seq { #1 } { #2 }
  \if_int_compare:w \int_eval:n {(\seq_count:N \l_tmpa_seq) - 1 } #3 #4
    #5 % true code
  \else
    \IfValueT{#6}{#6}
  \fi
}
\ExplSyntaxOff

\begin{document}

\IfCountSubStrCompare{~}{This~is a ~test}=0{Does not appear}[Appears]

\IfCountSubStrCompare{~}{This~is a ~test}=2{Appears twice}[Does not appear twice]

\IfCountSubStrCompare{~}{This~is a ~test}=3{Appears thrice}[Does not appear thrice]

\IfCountSubStrCompare{~}{This~is a ~test}>0{At least once }[Does not appear]

\IfCountSubStrCompare{~}{This~is a ~test}>1{More than once}[Once or less]

\IfCountSubStrCompare{~}{This~is a ~test}<2{Less than twice}[Twice or more]

\IfCountSubStrCompare{~}{This~is a ~test}<3{Less than thrice}[Thgrice or more]

\IfCountSubStrCompare{yes}{a yes b yes c yes deyesfg yehs ij}=4{Exactly four occurrences}

\end{document}

This produces the expected results:

The sytax of the \IfCountSubStrCompare command is:
\IfCountSubStrCompare{<substring>}{<string>}{=, < or >}{<int>}{<iftrue>}[<iffalse>]

So you need to give it a string to search for, a string to search in, a comparison operator (=, > or <), something to do if the comparison holds and, optionally, something to do if it doesn't.


text:
Q: Applet will work in IE, but not firefox So I have created an applet that creates a file on the local hard drive, and eventually uploads it to a CGI that I have created.
When run on IE, the applet works fine, and creates and uploads the file properly.
However, on firefox, I get an error on the Java Console, access denied, showing me that it simply can't create the file. I created the certificate myself, and did not buy one or have it verified through a company.
I need a solution that will work for anybody who potentially uses the applet, meaning the fix can't just be editing my own settings, unless I can do that with every computer that accepts the certificate.

A: Unsigned applets cannot access local disk on all browsers. It worked for you in IE because I believe that you ran it from file system (not via http). So, the right solution is not to create file on disk. Create content in memory and upload it. But remember: you can connect only to server the applet was downloaded from.
If you really have to create local file you have to sign the applet.

A: May be, some setting has to be done. One of the reason could be your Mozilla Firefox is not java enabled.
Check the following links :

*

*A fix for Java applets not loading in Firefox

*Applet loads but hidden in Firefox
To test whether java is enabled or not in a web browser, click [here]

A: This bug may be relevant.
It states that Firefox kills java applets that take too long to load.  I have an example that works fine when loaded from a local resource but fails when it is remote.  Sometimes, reopening the applet can make it work as it appears that it loads more and more of the classes each time.


text:
Q: FoS5 - Twig - How to change input attr_ name of Twig Form I use symfony 5 and Twig and I created a login form with twig but the problem is their input attr_ name. I have some form[username] (by example) but I want _username. How can I change that?
I have :
<input type='text' name='login[username]'> FROM {{ form_widget(login.username) }}

I want :
<input type='text' name='_username'>

Thanks a lot :D
B.

A: You can change the form names directly (either in the twig view or in the LoginType depending on the method used) and retrieve the corresponding names in your Authentificator (file to create or extend)  :
public function getCredentials(Request $request)
{
    $credentials = [
        'email' => $request->request->get('login')['email'], // email, or _email, or username, or _username, etc.
        'password' => $request->request->get('login')['password'],
        'csrf_token' => $request->request->get('login')['_token'],
    ];

    $request->getSession()->set(Security::LAST_USERNAME, $credentials['email']);

    return $credentials;
}

https://symfony.com/doc/current/security/guard_authentication.html


text:
Q: systemctl suspend or suspend doesn't stop computer from running When I run systemctl suspend in the terminal or click suspend via the Power off menu, my monitor sleeps but my computer is still running when it should instead have gone to sleep. This happens about 50% of the time. Does anyone know what's happening here and how to fix?
Here's some information about my computer
Ubuntu 20.04 x86_64
Nvidia driver 450
GNOME Shell 3.36.4


text:
Q: Error Id returned 1 exit status - Having problems with inheritance and classes in different files C++ This is my BankAccount.h file
#ifndef BANKACCOUNT_H_
#define BANKACCOUNT_H_
#include <string>
#include <iostream>

using namespace std;

class BankAccount{
public:
    BankAccount();
    BankAccount(string n, double b);

    string getName();
    double getBalance();

    virtual void deposit(double a);
    virtual bool withdraw(double a);

    void toString();

    bool transfer(BankAccount *a, double b);

protected:
    string name;
    double balance;
};
#endif

this is my BankAccount.cpp file
#include <iostream>
#include "BankAccount.h"
#include <string>
using namespace std;

 BankAccount::BankAccount(string n, double b){
name = n;
balance = b;
 }
 string BankAccount::getName(){
return name;
}
 double BankAccount::getBalance(){
return balance;
}
void BankAccount::deposit(double a){
balance = balance + a;
}

bool BankAccount::withdraw(double a){
if (balance - a < 0){
    return false;
}
else {
    balance = balance - a;
}
}

void BankAccount::toString(){
cout << "Name: " << this->getName() << " Balance:" << this->getBalance();
}
bool BankAccount::transfer(BankAccount *a, double b){
if (this->getBalance() - b < 0){
    return false;
}
else {
    this->withdraw(b);
    a->deposit(b);
}
}

this is my SavingsAccount.h file
#ifndef SAVINGSACCOUNT_H_
#define SAVINGSACCOUNT_H_
#include <iostream>

#include <string>
#include "BankAccount.h"
using namespace std;

class SavingsAccount : public BankAccount {
public:

    SavingsAccount(string n, double b, double i);
    void addInterest();
private:
    double interest;

};
#endif

This is my SavingsAccount.cpp file
#include <iostream>
#include "SavingsAccount.h"
#include <string>
using namespace std;

SavingsAccount::SavingsAccount(string n, double b, double i){
name = n;
balance = b;
interest = i;
}
void SavingsAccount::addInterest(){
balance = balance + (interest * balance * .01);
}

I keep getting an undefined reference to BankAccount error. I'm not really sure why, any help would be greatly appreciated. It keeps opening up a makeFile.win with $(CPP) $(LINKOBJ) -o $(BIN) $(LIBS)
highlighted.

A: You have declared a default constructor (the one with no parameters) for BankAccount, and you are using it in SavingsAccount, but you haven't actually implemented it.


text:
Q: Spring Boot REST API won't convert JSON to object I'm running into a failure, but I can't figure out why. For a simple test, I want to quickly create a RESTful API to accept a JSON and convert it to an object (POJO).
Restcontroller:
@RestController
public class RESTController {

    @Autowired
    AuthorService authorService;

    @RequestMapping(value = "/setsAuthor", headers = "Accept=application/json", method=RequestMethod.POST)
    public void addAuthor(@RequestBody Author author){
        authorService.addAuthor(author);
    }

}

Data object:
@AllArgsConstructor
@Entity
@NoArgsConstructor
public class Author {

    @Id
    private Integer id;
    private String authorName;
}

Service:
@Service
public class AuthorService {

    @Autowired
    AuthorRepository authorRepository;

    public void addAuthor(Author author) {
        try {
            authorRepository.save(author);
        } catch (IllegalAccessError e) {
            System.out.println("cant save Author: " + author + " to Respository");
        }
    }

Repository interface:
public interface AuthorRepository extends CrudRepository<Author, Integer> {
}

Post Request at
http://localhost:8080/setsAuthor

With JSON:
{
    "id": 1,
    "authorName": "SomeAuthor"
}

I also tried to wrap the Items in the JSON in a "Author" :{}
The RestController won't map my JSON to the object. It always says id = null, authorName = null when I debug the program.
What am I doing wrong? I remember it always worked this way.

A: Add @Getter and @Setter to entity
@AllArgsConstructor
@Entity
@NoArgsConstructor
@Getter
@Setter
public class Author {

A: You can also use
@AllArgsConstructor(onConstructor = @__(@JsonCreator))

instead of @Setter


text:
Q: Correctly creating multiple instances of lightbox for website I am seeking to use a jQuery / JS lightbox I found across a 1 page website, I'd like to use it 7 times to hold 7 unique sets of content but I am failing to implement it correctly for the other 6 instances.
$(document).ready(function() {
    var lightBox = $('#lightbox'),
    lightBoxContent = $('#lb-content');

var positionLightbox = function() {
    var veiwWidth = $(window).width(),
        lbContentMargin = (veiwWidth / 2) - 400,
        lbContent = $('#lb-content');

    lbContent.css({
        'left' : lbContentMargin,
        'top' : $(window).scrollTop() - 150 + 'px'
    });
};

$('#search-submit').click(function() {
    lightBox.fadeIn(function() {
        lightBoxContent.show();
    });
    positionLightbox();
});

$('#lb-close').click(function() {
    lightBox.hide();
    lightBoxContent.hide();
    });
});

Mark-Up:

                x

More content here.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam nec commodo justo. Suspendisse vel facilisis enim. Nulla lorem ante, auctor et malesuada ac, porttitor in lectus. Fusce congue pharetra tincidunt. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nullam dapibus nec neque ut accumsan.

Duplicating the code in 6 new instances didn't work either.
$(document).ready(function() {
    var lightBox = $('#lightbox2'),
    lightBoxContent = $('#lb-content2');

var positionLightbox = function() {
    var veiwWidth = $(window).width(),
        lbContentMargin = (veiwWidth / 2) - 400 + 'px',
        lbContent = $('#lb-content2');

    lbContent.css({
        'left' : lbContentMargin,
        'top' : $(window).scrollTop() - 350 + 'px'
    });
};

$('#search-submit2').click(function() {
    lightBox.fadeIn(function() {
        lightBoxContent.show();
    });
    positionLightbox();
});

$('#lb-close2').click(function() {
    lightBox.hide();
    lightBoxContent.hide();
    });
});

A: Not 100% sure where the other content is or supposed to be but, assuming your lightbox code is correct and your html too (for what you need it to do) then you dont need to repeat the jquery code 7xs. Keep the same code and ............. lets assume that you have this html as your content

 content here to be lightboxed

 content here to be lightboxed

 content here to be lightboxed

 content here to be lightboxed

 content here to be lightboxed

 content here to be lightboxed

 content here to be lightboxed

then in your jQuery, you put all these id selectors in your code as follows.
$(document).ready(function() {
    var lightBox = $('#lightbox, #lightbox2,#lightbox3,#lightbox4,#lightbox5,#lightbox6,#lightbox7'),
    lightBoxContent = $('/* same here for the 7 lb-content 1 through 7 */ ');

etc

Essentially, group all your selectors to reuse the same code.


text:
Q: How to prevent GLIBC symbols from being exported from an .so? I am linking GLIBC statically into my .so:

g++ -shared -o morpher.so -static-libstdc++ -static-libgcc -Wl,-L. -Wl,--whole-archive -l:hello.o -l:libmorpher.a -Wl,--no-whole-archive

I do this to make my binary (.so) portable across different Linux distributions and versions.
However, this has an undesirable side effect: all GLIBC symbols, including e.g. malloc() and free(), are exported from my shared library:
$ nm morpher.so | grep free
00000000000ef520 t _ZN12_GLOBAL__N_14pool4freeEPv.constprop.0
000000000008b08c t _ZN12_GLOBAL__N_14pool4freeEPv.constprop.0.cold
00000000000ef710 T _ZN9__gnu_cxx9__freeresEv
00000000000ef860 T __cxa_free_dependent_exception
00000000000ef7b0 T __cxa_free_exception
                 U __freelocale@@GLIBC_2.2.5
                 U free@@GLIBC_2.2.5

Adding -fvisibility=hidden has no effect: it only works on source files at compile time.
Is there a way to prevent GLIBC and libstdc++ symbols from being exported?

A: nm (without the -D option) shows the static symbol table (.symtab), not the dynamic symbol table (.dynsym). Only the dynamic symbol table is relevant to dynamic linking.
In your case, it appears that the symbols are not actually defined in the shared object.  Rather, __freelocale and free are undefined (U) or imported. If you build your shared object on the oldest distribution you want to support, such imports do not impact cross-distribution compatibility because glibc has a compatible ABI across distributions, and later versions support symbols from older versions.
-static-libgcc is about libgcc (not glibc). A lot of libgcc is always statically linked. The shared-by-default part is mostly about the unwinder, and linking that dynamically is recommended, so that the system unwinder is used.


text:
Q: PYTHONHOME and PYTHONPATH for Django in Heroku This is a follow-up question for this.
No module named PIL in heroku though it is installed
I got help from Heroku website here. https://help.heroku.com/BWJ7QYTF/why-am-i-seeing-importerror-no-module-named-site-when-deploying-a-python-app
But from the terminal, when I type heroku config I only get the DATABASE_URL. How do I set these variables?


text:
Q: get the full path of web service's methods from wsdl file I am working with suds library -python 2.7- and I would like to get the full path of all methods from a wsdl file.
I used this code to get the list of methods from a wsdl file :
from suds.client import Client

url = "http://www.webservicex.net/country.asmx?WSDL"
client = Client(url)
list_of_methods = [method for method in client.wsdl.services[0].ports[0].methods]

and I get something like this :
[GetCurrencyCodeByCurrencyName, GetCurrencyByCountry, GetCurrencyCode, GetCountries, GetCurrencies, GetISOCountryCodeByCountyName, GetISD, GetCountryByCurrencyCode, GetGMTbyCountry, GetCountryByCountryCode]

But I want to get something like this :
[http://www.webserviceX.NET/GetCountryByCountryCode, ...]

so, how can I do this ?

A: What about using a qname attribute of a port?
from suds.client import Client
url = "http://www.webservicex.net/country.asmx?WSDL"

client = Client(url)
port = client.wsdl.services[0].ports[0]
list_of_methods = [port.qname[1] + '/' + method for method in port.methods]
print(list_of_methods)


text:
Q: How to help move the image does not exceed the limit on screens I can drag this pictures to right or left,up,down It passed over an screens.I had zoom in and out. I want limit about that. Using windows phone 8.1 app.
After the transformation, brings the image back if it is out of the boundary. You can detect if the image is out of boundary by comparing the values of TranslateX/TranslateY and the width/height of the boundary. The boundary is the parent of the image (it is a Grid?), you need to debug the code to determine the boundary for TranslateX and TranslateY.
XAML
<Grid>
    <Grid Name="container">
        <Image Name="img_container" Source="/papers.co-mb00-baloon-fly-sea-wallpaper-1920x1080.jpg"
               ManipulationDelta="Image_ManipulationDelta"
               ManipulationMode="Scale,TranslateX,TranslateY"
               Stretch="Uniform"
                RenderTransformOrigin="0.5,0.5">
            <Image.RenderTransform>
                <CompositeTransform/>
            </Image.RenderTransform>
        </Image>
    </Grid>
</Grid>

C#
int mincale = 1;
private void Image_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
    Image img = sender as Image;
    CompositeTransform ct = img.RenderTransform as CompositeTransform;
    //zoom
    ct.ScaleX *= e.Delta.Scale;
    ct.ScaleY *= e.Delta.Scale;

    //checking

    if (ct.ScaleX < mincale)
        ct.ScaleX = mincale;
    if (ct.ScaleY < mincale)
        ct.ScaleY = mincale;

    //drag whitle zooming.

    ct.TranslateX += e.Delta.Translation.X;
    ct.TranslateY += e.Delta.Translation.Y;

    //checking drag not passed over a screen.that's fails.

    if (ct.TranslateX < 10 - img.ActualWidth * ct.ScaleX)
        ct.TranslateX = 10 - img.ActualWidth * ct.ScaleX;

    if (ct.TranslateX > container.ActualWidth - 10)
        ct.TranslateX = container.ActualWidth - 10;

    if (ct.TranslateY < 10 - img.ActualHeight * ct.ScaleY)
        ct.TranslateY = 10 - img.ActualHeight * ct.ScaleY;

    if (ct.TranslateY > container.ActualHeight - 10)
        ct.TranslateY = container.ActualHeight - 10;
}

A: you can check for which resolution is there , according to set Image height and width.

var scalfactor = App.Current.Host.Content.ScaleFactor;
switch (scalfactor)
            {
                case 150:
//write code for 720p or other screen Resolution

                    break;
                case 160:
//write code for Wxga screen Resolution

                    break;
                case 100:
//write code for Wvga screen Resolution
              break;
                default:
                    throw new InvalidOperationException("Unknown resolution type");
            }

Plz refer this link for more info
http://msdn.microsoft.com/en-us/library/windows/apps/jj206974%28v=vs.105%29.aspx


text:
Q: Working With/Processing Audio in Java Anyone know of any good tutorials or reference guides for working with Audio in Java? I'm not looking for anything too specific at this point; just would like to get my feet wet working with audio. Thanks in advance!

A: First of all: Multimedia/audio support in Java is not great.
But—if you're set on Java, I suggest taking a look at the Java Sound Trail. It explains most of the basic APIs. Then check out Java Sound Resources to get a better idea of how things work. Even though it's not brand-new anymore, it is very useful and explains a lot about the low level details.
Beyond the raw sound API, Sun came up with JMF, the Java Media Framework. It has been unsupported for years, so I would stay clear of it. You might want to use it for inspiration, but I can't recommend using it for more.
You will also discover that the built-in Java support for audio formats like mp3 or ogg is rather limited. To be able to play such files, you will need third party libraries, like jogg, jflac, mp3spi, or SampledSP. While the first three are pure Java solutions, the last one is basically a thin Java wrapper for a number of native libraries. Especially for FFmpeg there are a many different libraries like that, as FFmpeg supports most available audio formats.
The only way to play an mp3 file from Java without any additional libraries, is to cheat and use the JavaFX class MediaPlayer. You can find more info about how to do that on Stackoverflow.
Good luck!


text:
Q: http://www.engadget.com/rss.xml is not responding to my XMLHttpRequest. No error code in console I am trying to do a RSS reader chrome extension based on an example from lifehacker (http://lifehacker.com/5857721/how-to-build-a-chrome-extension). I did my own based on that. It didn't work. I tried their source code and it worked perfectly fine(for lifehacker), but when I changed the xml source as http://www.engadget.com/rss.xml it only showed an empty square.If anyone can point any mistake or error, I would be truly thankful.My files are :
manifest.json
  {
  "name": "RSS Fetcher",
  "version": "0.1",

  "description": "engadget rss reader.",
  "homepage_url": "http://www.engadget.com/",
    "background_page": "background.html",
    "permissions": [
      "<all_urls>",
      "http://www.engadget.com/*"

],
    "browser_action": {
    "default_title": "engadget reader",
    "default_popup": "popup.html"
  }
}

background.html

popup.html

    <link rel="stylesheet" href="styles/post.css" type="text/css" />

parse.js
function parse_post(element) {
    // console.log(element);
    var post = new Object();
    post.title = $(element).find("title").text();
    post.tag = post.title.split('[')[1].split(']')[0];
    post.title = post.title.split('[')[0];
    post.id = $(element).find("guid").text();
    post.url = $(element).find('link').text();
    post.description = $("
").html($(element).find("description")).text();
    post.img = $('img', post.description)[0].src; //107x60px
    var shorten = 120;
    if (post.title.length > 80) {
        shorten = 70;
    }
    post.description = $.trim($(post.description).text());
    post.description = post.description.substr(0, shorten);
    // console.log(post);
    return post;
}

function open_item(url) {
    chrome.tabs.create({url: url});
    chrome.browserAction.setBadgeText({text:''});
}

I also used jquery-1.6.1.min.js
Anything helps:) Thanks in advance!

A: not sure "all_urls" works in your manifest.json, remove that and give it a try


text:
Q: Validation of ml-model with highly imbalanced labels I'm currently working on a project which is facing highly imbalanced class labels. So let's say we have 1000 good labels and 5 bad labels. At the moment I'm not sure how long i have to collect data to verify the algorithm. Im working in a business environment and we have to ensure that the algorithm is really detecting bad labels. For training we use different Methods to solve the problem of imbalanced data (up/downsampling and semi supervised learning). Nevertheless we are currently not sure how we can validate that the algorithm works. So how should the test set look like :
In Terms of Size
In Terms of label distribution
In minimum amount of label per group (min. good labels & min. bad labels)

I tried to do some calculation for the sample size with random picking for a specific confidence intervall. (Like mentioned here: Sample Size Determination) So the sample should be "representativ" but can we trust the performance validation if the sample set only contains e.g. 5 bad labels.
Example:
Sample Size for an unlimited population with Confidence Intervall 95%, Margin of Error 5% ==> 384
If we take a closer look at this sample these 384 only contain 2 bad labels. So I don't think i can trust the performance metrics of the algorithm. (Which is predicting both bad labels correctly)


text:
Q: how to import a relationship file into Neo4j to create relationship between existing labels? I am new to Neo4j and have been trying to import a relationship file using Cypher to create a relationship between two existing labels. I have a file with relationship
EID,CID
1,1
1,3
2,5
2,7

I also have two existing labels in Neo4j with employee and children.
 Employee file has
 eid, name, salary

 Children file has
 cid, name, age

I am trying to import the relationship file so that I can create a relationship between employee and children using the eid and cid.
So far I have tried
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:/c:/SKR/links.csv' AS row
MATCH(f:Emps{eid: toInt(row.from_Emps_eid)}), (t:Children{cid:
toInt(row.to_Children_cid)})
CREATE (f)-[:CHILD]->(t);

I am getting no rows, no changes. I would really appreciate if anyone could point me in the right direction.

A: You CSV file's header row specifies these names: EID, CID. In your query, use those names (instead of from_Emps_eid and to_Children_cid, respectively):
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM 'file:/c:/SKR/links.csv' AS row
MATCH(f:Emps{eid: toInt(row.EID)}), (t:Children{cid: toInt(row.CID)})
CREATE (f)-[:CHILD]->(t);


text:
Q: getting an error while executing the code In the below code i want to print the lines which are between "first", and on those line searching for "new.txt" line.. when i am running i get an error :
if "first" in lines[i+n]:
IndexError: list index out of range

my code:
def find_path(self):
        f = open("/output",'w')
        for line in self.logs:
            f.write(line)
        f = open('/output','rb')
        lines = f.readlines()
        for i,line in enumerate(lines):
            if "first" in line:
                pattern = line
                for n in range(1,len(lines)):
                    if "first" in lines[i+n]:
                        break
                    else:
                        if "new.txt" in line:
                            print line
                        print lines[i+n]
        f.close()

A: It's because i+n can be and will be greater than length of lines list.
for i,line in enumerate(lines):

That enumeration creates values for i from 0 to len(lines) - 1, so the maximum value of i is len(lines) - 1.
The following lines tell us that values of n can be from 1 to len(lines) - 1, so maximum value of n is len(lines) - 1 again:
for n in range(1,len(lines)):
    if "first" in lines[i+n]:
        break

So, value of i + n can be from 1 to 2 * (len(lines) - 1) - that's why you're getting IndexError.


text:
Q: NGINX throwing 400 whenever the request is having headers key with space In below request, second header is having space which is causing the issue. If we remove it and hit the API it works fine otherwise 400 bad request error.
The same curl was working until 1.17 NGINX version, but after that we are facing the issue.
Please suggest any solution for it
Request:
curl -ks --location --request GET 'https://<hostname>/employees' \
> --header 'emp_id: 110' \
> --header 'abcd xyz: hello'

Response:

<title>400 Bad Request</title>

400 Bad Request

nginx/1.23.2


text:
Q: Evaluate the limit $\lim_{x \to \frac{\pi}{4}} \frac{1-\tan x}{x-\frac{\pi}{4}}$ I am trying to evaluate $$\lim_{x \to \frac{\pi}{4}} \frac{1-\tan x}{x-\frac{\pi}{4}}$$ without using L'hopital's rule. However, I am not sure what to do. The only thing that came to my mind was to change the tan to sin over cos and get a common denominator but I felt that won't get me anywhere. A hint will be greatly appreciated.

A: We're looking for
$$\lim_{x\to{\pi\over 4}}-{\tan{x}-\tan{\pi\over 4}\over x-{\pi\over 4}}$$
And this is $-\tan'{\pi\over 4}=-2$

A: If you substitute $t=x-\pi/4$, then
$$
\tan x=\tan(t+\pi/4)=\frac{\tan t+1}{1-\tan t}
$$
so your limit is
$$
\lim_{t\to0}\frac{1}{t}\left(1-\frac{\tan t+1}{1-\tan t}\right)=
\lim_{t\to0}\frac{\tan t}{t}\frac{-2}{1-\tan t}
$$
Alternatively, recall that
$$
\cos x-\sin x=-\sqrt{2}\sin\left(x-\frac{\pi}{4}\right)
$$
and therefore
$$
1-\tan x=-\sqrt{2}\sin\left(x-\frac{\pi}{4}\right)\frac{1}{\cos x}
$$
Hence the limit can be rewritten as
$$
\lim_{x\to\pi/4}\frac{\sin\left(x-\frac{\pi}{4}\right)}{x-\frac{\pi}{4}}\frac{-\sqrt{2}}{\cos x}
$$

A: $$\lim_{x \to \frac{\pi}{4}} \frac{1-\tan x}{x-\frac{\pi}{4}} =\lim_{x \to \frac{\pi}{4}} \frac{-\tan (x-\frac{\pi}{4})}{x-\frac{\pi}{4}}(1+ \tan x)=-1(2)=-2$$

A: Hint
This kind of problems are rather simple to address if you know Taylor series. Assuming you do, built at $t=a$, you have
$$\tan(x)=\tan (a)+ \left(\tan ^2(a)+1\right)(x-a)+O\left((x-a)^2\right)$$


text:
Q: Replace strings in pandas cell using regex, between two specific strings there were some tipics connected with strings 'between' replacement, but I think I have something wrong in my regex, or maybe I should use different approach.
I need to replace in my Name column word (in this case is , but it will be not always is, sometime different word) with is not.
This specific world is between numbers ending with 'h'directly.
my df:
df=pd.DataFrame({'Name':['Adam is 23.2h is 223h mike is 223h',
'Katie is 13.2h is 22h mike is 223h','Ilam is 2h is 223h mike is 223h',
'Katie','Brody','Brody like mike'],
'B':[20,20,21,21,22,21]})

    B                                Name
0  20  Adam is 23.2h is 223h mike is 223h
1  20  Katie is 13.2h is 22h mike is 223h
2  21     Ilam is 2h is 223h mike is 223h
3  21                               Katie
4  22                               Brody
5  21                     Brody like mike

expected output:
    B                                     Name
0  20   Adam is 23.2h is not 223h mike is 223h
1  20   Katie is 13.2h is not 22h mike is 223h
2  21      Ilam is 2h is not 223h mike is 223h
3  21                                    Katie
4  22                                    Brody
5  21                          Brody like mike

code:
df.Name=df.Name.replace({'([0-9]{1,8}.[0-9]{1,4}h|[0-9]{1,8}h)(.*?)([0-9]{1,8}.[0-9]{1,4}h|[0-9]{1,8}h)':'is not'},regex=True)

A: To use matching group write it :r'\1 is not \3' . And, seems, you can use a little easier regex
   df.Name.replace({'([0-9]{1,8}(?:.[0-9]{1,4})?h)(.*?)([0-9]{1,8}(.[0-9]{1,4})?h)':r'\1 is not \3'}, regex=True)

0    Adam is 23.2h is not 223h mike is 223h
1    Katie is 13.2h is not 22h mike is 223h
2       Ilam is 2h is not 223h mike is 223h
3                                     Katie
4                                     Brody
5                           Brody like mike
Name: Name, dtype: object


text:
Q: SQLAlchemy filter query results based on other table's field I have got a not very common join and filter problem.
Here are my models;
class Order(Base):
    id = Column(Integer, primary_key=True)
    order_id = Column(String(19), nullable=False)
    ... (other fields)

class Discard(Base):
    id = Column(Integer, primary_key=True)
    order_id = Column(String(19), nullable=False)

I want to query all and full instances of Order but just exclude those that have a match in Discard.order_id based on Order.order_id field. As you can see there is no relationship between order_id fields.
I've tried outer left join, notin_ but ended up with no success.

A: With this answer I've achieved desired results.
Here is my code;
orders = (
    session.query(Order)
    .outerjoin(Discard, Order.order_id == Discard.order_id)
    .filter(Discard.order_id == None)  # noqa: E711
    .all()
)

I was paying too much attention to flake8 wrong syntax message at Discard.order_id == None and was using Discard.order_id is None. It appeared out they were rendered differently by sqlalchemy.


text:
Q: How to remotely compile and debug in Linux from within Visual Studio 2010 The source (ideally project) is to be compiled by gcc/g++ under Linux (Ubuntu). The source/project is to be opened/edited in Visual Studio environment. The output binary is to be debugged so that traces to viewed in Visual Studio 2010 and be ran in Linux step by step.
What is required to achieve this goal?

A: I don't know if this will work in VS 2010 but to debug something on Linux you should use GDB in remote mode. There is plugin fo GDB to VS but I'm not sure if it supports remote debuggin.
Here are some links that could be useful

*

*Debug C++ code on Linux from Visual Studio

*http://visualgdb.com/tutorials/linux/import/

*https://sourceware.org/gdb/onlinedocs/gdb/Connecting.html

*Visual studio + remote gdb debugging


text:
Q: Geolocation APIs for Rails I am trying to show map for a location from my rails app.I tried checking YM4R/GM and GeoKit combination but not sure if there is something better for rails 3.

A: Try Ruby GeoCoder. It allows street address lookup, IP address lookup
and geographic coordinates.

A: You could also try RGeo. It looks nice, but I don't have any experience with it.


text:
Q: Как создать ярлык на рабочем столе? Хотелось бы узнать, можно ли средствами Java, создавать ярлыки на рабочем столе?Т.е. нажал кнопку - создался ярлык.

A: Нашёл вариант создания ярлыка, вдруг кому-то тоже пригодится.


text:
Q: Scaling plot sizes with Matplotlib I have taken the display colormap code and made it more generic.  The problem is that the color maps are now all smooshed together so the graphics are basically unreadable.
How do I increase the size of each colormap display?
Current output:

import numpy as np
import matplotlib.pyplot as plt

# Have colormaps separated into categories:
# http://matplotlib.org/examples/color/colormaps_reference.html
cmaps =  [('All Color Maps',
"Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spectral, spectral_r, spring, spring_r, summer, summer_r, terrain, terrain_r, viridis, viridis_r, winter, winter_r".replace(" ", "").split(',')
          )]
nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps)
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))

def plot_color_gradients(cmap_category, cmap_list, nrows):
    fig, axes = plt.subplots(nrows=nrows)
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
    axes[0].set_title(cmap_category + ' colormaps', fontsize=14)

    for ax, name in zip(axes, cmap_list):
        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3]/2.
        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)

    # Turn off *all* ticks & spines, not just the ones with colormaps.
    for ax in axes:
        ax.set_axis_off()

for cmap_category, cmap_list in cmaps:

    plot_color_gradients(cmap_category, cmap_list, nrows)

plt.show()

A: If you insist on having the plot look as close to what you have shown as possible, i.e. one column of 256 subplots with large labels, then the only real solution is to increase the size of the figure as mentioned in the answer by @Diziet Asahi.
That being said, I have 2 proposals for improvement.
Option 1
Split the subplots into 2 columns. This makes the image far easier to read IMO. This only takes a small modification to your plotting function:
def plot_color_gradients(cmap_category, cmap_list, nrows):
    fig, axes = plt.subplots(nrows=int(nrows/2), ncols=2, figsize=(12,11))
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.1, right=0.98, wspace=0.25)
    fig.suptitle(cmap_category + ' colormaps', fontsize=14)

    for ax, name in zip(axes.flatten(), cmap_list):
        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3]/2.
        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)
        ax.set_axis_off() # Don't need a separate loop for this

Which gives:

Option 2
If you want to keep everything in 1 column there may be a work around to at least make the plot look slightly better. That is to put every other label on the right hand side of the axis.
Note: this may not be what be exactly what you are looking for, but unless you make the figure very large (tall) then the image is always going to look cramped
Changing your plotting function like so gives the following graph:
def plot_color_gradients(cmap_category, cmap_list, nrows):
    fig, axes = plt.subplots(nrows=nrows)
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.9)
    axes[0].set_title(cmap_category + ' colormaps', fontsize=14)

    count = 0
    for ax, name in zip(axes, cmap_list):
        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
        pos = list(ax.get_position().bounds)
        ax.set_axis_off()

        if count == 1:
            count = 0
            x_text = pos[0] + 0.71
            y_text = pos[1] + pos[3] / 2.
            fig.text(x_text, y_text, name, va='center', ha='left', fontsize=10)
        else:
            count = 1
            x_text = pos[0] - 0.01
            y_text = pos[1] + pos[3]/2.
            fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)

    # Theres no need to loop through list of axes twice. Do this in the above loop!

    # Turn off *all* ticks & spines, not just the ones with colormaps.
    #for ax in axes:
    #    ax.set_axis_off()

Not as good as the first example, but an improvement nonetheless.

A: As @DavidG commented, you need to increase the size of your figure. In the code below, replace width and height by appropriate values. Since you seem to want a variable number of lines, height should probably be proportional to nrows
def plot_color_gradients(cmap_category, cmap_list, nrows):
    height = some_value * nrows
    fig, axes = plt.subplots(nrows=nrows, figsize=(width, height))
    ...


text:
Q: An identity for Riemann-Stieltjes integral of $ t^p $ w.r.t. $ \alpha(t) = m(\{x:|f(x)|>t\}) $. I am wondering how to proof the following identity:

Let $ f \in L^p(\mathbb{R}^n) $ and $ \alpha(t) = m(\{x:|f(x)|>t\}) $, with $ m $ denoting the Lebesgue measure. Then $$ p \int_{0}^{\infty} t^{p-1} \alpha(t) \: \mathrm{d}t = - \int_{0}^{\infty} t^p \: \mathrm{d}\alpha(t) . $$

I believe one can show that the left integral exists, equalling $ \int_{\mathbb{R}^n} |f(x)|^p $. If we knew that $ \alpha $ is differentiable and its derivative is Riemann integrable, I suppose we could use integration by parts along with the result that $ \int_{a}^{b} \phi \: \mathrm{d}\psi = \int_{a}^{b} \phi \psi' \: \mathrm{d}t $ whenever $ \psi(t) $ is differentiable and $ \phi(t) $, $ \psi'(t) $ are Riemann integrable...
I would be grateful for any answers, suggestions or hints! References to text books for any results used in a proof would be much appreciated (this way I'd have a starting point for self-study)!!! :-)

A: It is not necessary to have $\alpha$ differentiable to proceed.
Let $g(t) = pt^{p-1}$ and $G(t) = \int_0^t g(s) \, ds = t^p.$ Since $G$ is continuous and $\alpha$ is monotone, it is easily shown that $\alpha $ is Riemann-Stieltjes integrable with respect to $G$ and
$$\int_0^b g(t) \alpha(t)\,dt = \int_0^b\alpha \, dG.$$
Integration by parts provides that $G$ is Riemann-Stieltjes integrable with respect to $\alpha$ where
$$\int_0^b\alpha \,dG = G(b)\alpha(b) - G(0)\alpha(0) - \int_0^bG \, d\alpha$$ .
Hence,
$$\int_0^bp t^{p-1} \alpha(t) \, dt  = b^p\alpha(b) - \int_0^bt^p \, d\alpha.$$
Clearly, $\alpha(b) \to 0$ as $b \to \infty$ since $f \in L^p(\mathbb{R}^n)$, but to complete this you need to show that $\alpha(b) = o(b^p)$.


text:
Q: JayData JSON decode error I have JSON objects coming back from ASP.Net oData services which I am reading through JayData oData provider.  On one service, JSON object is read into an array without any problems.  On another service (from same server), the resulting array contains only etag data for all the elements.
I am not sure if there is a format mismatch or JayData is not decoding the JSON format correctly.
Could someone take a look and see where the problem is located?
Here is the header
GET /GCSData.svc/Customers HTTP/1.1
Referer: http://localhost:56786/HTMLClient/
MaxDataServiceVersion: 2.0
DataServiceVersion: 2.0
Accept: application/atomsvc+xml;q=0.8, application/json;odata=verbose;q=0.5, */*;q=0.1
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
DNT: 1
Host: localhost:56786

HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 2051
Content-Type: application/json;odata=verbose;charset=utf-8
Server: Microsoft-IIS/8.0
X-Content-Type-Options: nosniff
DataServiceVersion: 1.0;
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcQ2hpIFJvd1xkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEzXFByb2plY3RzXEdDU2xzXEdDU2xzXGJpblxEZWJ1Z1xHQ1NEYXRhLnN2Y1xDdXN0b21lcnM=?=
X-Powered-By: ASP.NET
Date: Mon, 31 Mar 2014 19:35:09 GMT

and here is the JSON data.
{"d":[{"__metadata":{"id":"http://localhost:56786/GCSData.svc/Customers(1)","uri":"http://localhost:56786/GCSData.svc/Customers(1)","etag":"W/\"'John%20%20%20%20%20%20','Doe%20%20%20%20%20%20%20','1234567890'\"","type":"LightSwitchApplication.Customer"},"Orders":{"__deferred":{"uri":"http://localhost:56786/GCSData.svc/Customers(1)/Orders"}},"CustID":1,"FName":"John      ","LName":"Doe       ","Phone":"1234567890"},{"__metadata":{"id":"http://localhost:56786/GCSData.svc/Customers(2)","uri":"http://localhost:56786/GCSData.svc/Customers(2)","etag":"W/\"'Jane%20%20%20%20%20%20','Smith%20%20%20%20%20','7703211234'\"","type":"LightSwitchApplication.Customer"},"Orders":{"__deferred":{"uri":"http://localhost:56786/GCSData.svc/Customers(2)/Orders"}},"CustID":2,"FName":"Jane      ","LName":"Smith     ","Phone":"7703211234"},{"__metadata":{"id":"http://localhost:56786/GCSData.svc/Customers(3)","uri":"http://localhost:56786/GCSData.svc/Customers(3)","etag":"W/\"'Dan%20%20%20%20%20%20%20','Handy%20%20%20%20%20','6789876543'\"","type":"LightSwitchApplication.Customer"},"Orders":{"__deferred":{"uri":"http://localhost:56786/GCSData.svc/Customers(3)/Orders"}},"CustID":3,"FName":"Dan       ","LName":"Handy     ","Phone":"6789876543"},{"__metadata":{"id":"http://localhost:56786/GCSData.svc/Customers(4)","uri":"http://localhost:56786/GCSData.svc/Customers(4)","etag":"W/\"'Mike%20%20%20%20%20%20','Smith%20%20%20%20%20','4041231234'\"","type":"LightSwitchApplication.Customer"},"Orders":{"__deferred":{"uri":"http://localhost:56786/GCSData.svc/Customers(4)/Orders"}},"CustID":4,"FName":"Mike      ","LName":"Smith     ","Phone":"4041231234"},{"__metadata":{"id":"http://localhost:56786/GCSData.svc/Customers(5)","uri":"http://localhost:56786/GCSData.svc/Customers(5)","etag":"W/\"'Aaron%20%20%20%20%20','Hayes%20%20%20%20%20','2431235678'\"","type":"LightSwitchApplication.Customer"},"Orders":{"__deferred":{"uri":"http://localhost:56786/GCSData.svc/Customers(5)/Orders"}},"CustID":5,"FName":"Aaron     ","LName":"Hayes     ","Phone":"2431235678"}]}

In the resulting array, for each Customer, all the fields (FName, LName, phone) contain the exact data (which equals to the "etag" field).  Here is an example for Customer(1)
{"CustID":1,"FName":"W/\"'John%20%20%20%20%20%20','Doe%20%20%20%20%20%20%20','1234567890'\"","LName":"W/\"'John%20%20%20%20%20%20','Doe%20%20%20%20%20%20%20','1234567890'\"","Phone":"W/\"'John%20%20%20%20%20%20','Doe%20%20%20%20%20%20%20','1234567890'\""}

The JSON data is read through toLiveArray() method.

A: Make sure you use the [TimeStamp] attribute on server-side to publish your ETag in byte array format:
[Timestamp]
public byte[] token { get; set; }


text:
Q: Reset autorotation in Xcode after force landscape orientation in one view controller (swift 4) An app in which I've begun to work supports all device orientations, except on of the views, which is landscape.
To force this orientation, I set the lanscape orientation value via AppDelegate:
AppDelegate.swift
var shouldSupportAllOrientation = true
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if (shouldSupportAllOrientation == true){
       return UIInterfaceOrientationMask.all
    }
    return UIInterfaceOrientationMask.landscape
}

ViewController.swift
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.shouldSupportAllOrientation = false
let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")

But when the app navigates to other view controller, and the device is in portrait orientation (physically), views appear on landscape mode until device is rotated.
Is there a way to detect the 'real device orientation'?
Thank you

A: I faced the similar issue.
After forcing the UIDevice.current.orientation, it seems that device can't update it anymore (which looks expected since it's a get-only property and represents physical orientation)
Try override supportedInterfaceOrientations in ViewController.swift:
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .landscape
}

After that if you open this VC, the interfaceOrientation is landscape, but UIDevice.current.orientation is the real one.
Just a note: you might want to flip width and height of your view if you work with frames and bounds.


text:
Q: Why is aws lambda invocation client incorrectly returning ClientExecutionTimeoutException? We seem to be deterministically encountering this problem and aren't sure where we're misconfigured.  For lambdas running less than ~5 minutes, our invocation succesfully wraps up ~0.5 seconds after the lambda completes. However for anything running longer than that, we can see that the lambda completes in the lambda logs, but our client invocation throws a ClientExecutionTimeoutException after 15 minutes.
After encountering the problem with other (otherwise successful) lambdas, we created a basic test lambda on Node with a sleep function and have been able to deterministically reproduce the issue:
function sleep(s) {
  return new Promise(resolve => setTimeout(resolve, s * 1000));
}
const sleepMinutes = 60 * 5;
exports.handler = async (event) => {
    console.log(`received lambda invocation, sleeping ${sleepMinutes}`);
    const response = {
        statusCode: 200,
        body: JSON.stringify(`finished running, slept for ${sleepMinutes} minutes`),
    };
    await sleep(sleepMinutes);
    console.log('finished sleeping');
    return response;
};

Our lambda invocation client is using these client configs:
clientConfig.setRetryPolicy(PredefinedRetryPolicies.NO_RETRY_POLICY);
clientConfig.setMaxErrorRetry(0);
clientConfig.setSocketTimeout(15 * 60 * 1000);
clientConfig.setRequestTimeout(15 * 60 * 1000);
clientConfig.setClientExecutionTimeout(15 * 60 * 1000);

Is there a ~5 minute timeout config we're missing?

A: Javadocs in aws-sdk-java says:

 For functions with a long timeout, your client might be disconnected during synchronous invocation while it waits for a response. Configure your HTTP client, SDK, firewall, proxy, or operating system to allow for long connections with timeout or keep-alive settings.

On the other hand, previously AWS Lambda was limited up to 5 minutes, later this limit was increased up to 15 minutes.
I would check:

*

*The client sdk version is up to date

*The connection is not closed by your network

*Move to an async invocation via AWSLambdaAsyncClient.invokeAsync() for long running invocations.

A: I've accepted Ezequiel's answer since it was technically a networking / OS issue, but here is a more detailed result:
We had to ensure all relevant clients were configured to keep alive tcp connections. We then had to add these properties to the /etc/sysctl.conf file on our EC2 residing in a private subnet because the NAT gateway is set to kill idle connections beyond 350s:
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 100
net.ipv4.tcp_keepalive_probes = 6

A: I have experienced such errors.
The problem is with the lambda context.
Your function might not return the success but return fail, as you didn't finish the function with context success.
Please check if you have done this when you finish the lamba.
Thanks.


text:
Q: DocBin to_bytes/to_disk gets killed I am dealing with fairly big corpuses and my DocBin object gets killed when I try to save it. Both to_disk and to_bytes are printing "Killed".
I am with limited python knowledge, so it isn't obvious to me right away how I can work around the issue. Can you help?
Here is my code(very straight forward and basic):
    nlp = spacy.blank("en")
    for text, annotations in train_data:
        doc = nlp(text)
        ents = []
        for start, end, label in eval(annotations)['entities']:
            span = doc.char_span(start, end, label=label)
            if (span is None):
                continue
            ents.append(span)
        doc.ents = ents
        db.add(doc)

    db.to_disk("../Spacy/train.spacy")```

A: You are probably running out of RAM. Instead, save your annotation in multiple DocBin files. You can provide a directory to --paths.train with spacy train instead of a single .spacy file if you have multiple .spacy files.


text:
Q: WPF comboboxes only allowing integers as text I have about 10 combo boxes. They are all populated with table adapters using a .xsd file.
I'm using Linq to SQL to grab a specific row and default the combo boxes to certain columns of that row. Here is my combo box code
                cmbCompany.Text = query.intAcctCo.ToString();
                cmbCompanyRec.Text = query.intAcctCoRec.ToString();
                cmbProgramCodes.Text = query.chrPgmCode;
                cmbCarrierCodes.Text = query.intCarrierCode.ToString();
                cmbDealerNumber.Text = query.chrDlrNum;
                cmbCoverageCodes.Text = query.chrCvgCode;
                cmbPayeeType.Text = query.chrPayeeType;
                cmbFeeType.Text = query.chrFeeType;
                cmbPayeeCodes.Text = query.intPayeeCode.ToString();
                cmbTransactionTypes.Text = query.chrTransType;

Here is the query
   var query =
                (from z in dc.tblActgPayeeTransactionAccounts2
                 where z.intActgAcctID == unique
                 select z).FirstOrDefault();

"unique" is just an identifier for the specific row
All of the ones with "ToString()" are working correctly the other are not. I have tried multiple things with no luck. It even shows that they have the value needed as text when i hover over in debug mode, but when the page loads, they are blank. I've tried adding "ToString()" to the others even though they are already strings and no luck. Ideas?
I'm on visual studio 2013, .net framework of 4.5.1. All of the xaml for the combo boxes is the same.

A: You need to structure your data correctly. You said:

I'm using Linq to SQL to grab a specific row

Put that row data into a custom class, that has a public property for each column and then data bind it to your ComboBoxes. You could then add extra properties to reflect the selected item in each ComboBox and data bind those to the ComboBox.SelectedItem properties of each ComboBox:
<ComboBox ItemsSource="{Binding YourCollectionProperty}"
    SelectedItem="{Binding YourSelectedItemProperty, Mode=TwoWay}" />

Then , when you want to select an item from code, you can just do this:
YourSelectedItemProperty = YourCollectionProperty.FirstOrDefault();

Or this:
YourSelectedItemProperty = YourCollectionProperty.ElementAt(10);

I suggest that you have a good, long read of the linked data binding page on MSDN.


text:
Q: How can I get back my router configuration in Ubuntu 16.04 server after shutdown? I shutdown my Ubuntu Server 16.04 after configuring it to the router using.
sudo shutdown now
The next day when I reboot, PC cannot update. My NAT configurations are gone.
When I type sudo apt update, it says
Err:1 http://us.archive.ubuntu.com/ubuntu xenial InRelease

My PC doesn't seem to be able to access internet. Is there anything I can do about it since I am new to Ubuntu?
I have internet plugged in through an ethernet cable. But still, I cannot update.

A: You need to add again you firewall rules, but wait, don't shutdown after that.
There are two programs to save and restore rules: iptables-restore iptables-save . Save rules and check if it will be restored automatically on reboot. If not - run iptables-restore in rc.local or better make it managed by systemd