text:
Q: Optimise a step function in Pandas using data I have two dataframes (df_1 & df_2) and some variables (A,B,C):
df_1 = pd.DataFrame({'O' : [1,2,3], 'M' : [2,8,3]})
df_2 = pd.DataFrame({'O' : [1,1,1, 2,2,2, 3,3,3],
                     'M' : [9,2,4, 6,7,8, 5,3,4],
                     'X' : [2,4,6, 4,8,7, 3,1,9],
                     'Y' : [3,6,1, 4,6,5, 1,0,7],
                     'Z' : [2,4,8, 3,5,4, 7,5,1]})

I have an algorithm, below, that uses A,B,C to calculate a score (S) for each row in df_2. It finds the row in df_2 with the highest score (S). It compares the highest scoring row in df_2 with df_1 and calculates p_hat, a measure of the similarity between them:
M_G = df_1.M
df_1 = df_1.set_index('O')

A = 1
B = 1
C = 1

# Score
df_2['S'] = df_2['X']*A + df_2['Y']*B + df_2['Z']*C

# Top score
df_Sort = df_2.sort_values(['S', 'X', 'M'], ascending=[False, True, True])
df_O    = df_Sort.set_index('O')
M_Top   = df_O[~df_O.index.duplicated(keep='first')].M
M_Top   = M_Top.sort_index()

# Compare the top scoring row for each O to df_1
df_1_M = df_1.M
df_1_M = df_1_M.sort_index()
df_1_R = df_1_M.reindex(M_Top.index)
T_N_T  = M_Top == df_1_R

# Record the results for the given values of A,B,C
df_Res = pd.DataFrame({'it_is':T_N_T}) # is this row of df_1 the same as this row of M_Top?

# p_hat =         TP / (TP + FP)
p_hat = df_Res.sum() / len(df_Res.index)

For the values of A,B,C in the example, it gives p_hat = 0.333. I would like to find the values of A,B,C that give the maximum possible value of p_hat. I would like to use an optimisation algorithm to make sure that I get the maximum value please.
The graph is for C=2:

How can I find the maximum p_hat please?

A: I guess you could use the Optuna package, it's very easy to use. You define an objective function in which you calculate the variable you want to optimize in which ever way you want, create a study object for it and Optuna basically does the rest.
Small example for an easy 2D-function:
import optuna

def optimize_me(trial):
    x = trial.suggest_uniform('x', -10, 10)
    y = trial.suggest_uniform('y', -10, 10)
    return ((y - 1) ** 2) + ((x + 2) ** 2)

study = optuna.create_study()
study.optimize(optimize_me, n_trials = 10)

You can read more about Optuna here
I use this mainly to optimize hyper parameters for RNNs, it's a very capable package.

A: I found a way to do it using global, brute force optimisation:
from scipy.optimize import brute

df_1 = pd.DataFrame({'O' : [1,2,3], 'M' : [2,8,3]})

df_2 = pd.DataFrame({'O' : [1,1,1, 2,2,2, 3,3,3],
                     'M' : [9,2,4, 6,7,8, 5,3,4],
                     'X' : [2,4,6, 4,8,7, 3,1,9],
                     'Y' : [3,6,1, 4,6,5, 1,0,7],
                     'Z' : [2,4,8, 3,5,4, 7,5,1]})

# Range
min_ = -2
max_ = 2
step = .5
ran_ge = slice(min_, max_+step, step)
ranges = (ran_ge,ran_ge,ran_ge)

# Params
params = (df_1, df_2)

# Index
df_1 = df_1.set_index('O')
df_1_M = df_1.M
df_1_M = df_1_M.sort_index()

# Fun
def fun(z, *params):
    A,B,C = z

    # Score
    df_2['S'] = df_2['X']*A + df_2['Y']*B + df_2['Z']*C

    # Top score
    df_Sort = df_2.sort_values(['S', 'X', 'M'], ascending=[False, True, True])
    df_O    = df_Sort.set_index('O')
    M_Top   = df_O[~df_O.index.duplicated(keep='first')].M
    M_Top   = M_Top.sort_index()

    # Compare the top scoring row for each O to df_1
    df_1_R = df_1_M.reindex(M_Top.index) # Nan
    T_N_T  = M_Top == df_1_R

    # Record the results for the given values of A,B,C
    df_Res = pd.DataFrame({'it_is':T_N_T}) # is this row of df_1 the same as this row of M_Top?

    # p_hat =         TP / (TP + FP)
    p_hat = df_Res.sum() / len(df_Res.index)

    return -p_hat

# Brute
resbrute = brute(fun,
                 ranges,
                 args=params,
                 full_output=True,
                 finish=None)

print('Global maximum ',                   resbrute[0])
print('Function value at global maximum ',-resbrute[1])

It gives:
Global maximum  [-2.   0.5  1.5]
Function value at global maximum  0.6666666666666666

A: Or using global, evolutionary optimisation: (code fixed by @Aviv Yaniv)
from scipy.optimize import differential_evolution

df_1 = pd.DataFrame({'O' : [1,2,3], 'M' : [2,8,3]})

df_2 = pd.DataFrame({'O' : [1,1,1, 2,2,2, 3,3,3],
                     'M' : [9,2,4, 6,7,8, 5,3,4],
                     'X' : [2,4,6, 4,8,7, 3,1,9],
                     'Y' : [3,6,1, 4,6,5, 1,0,7],
                     'Z' : [2,4,8, 3,5,4, 7,5,1]})

# Index
df_1 = df_1.set_index('O')
df_1_M = df_1.M
df_1_M = df_1_M.sort_index()

# Fun
def fun(z, *params):
    A,B,C = z

    # Score
    df_2['S'] = df_2['X']*A + df_2['Y']*B + df_2['Z']*C

    # Top score
    df_Sort = df_2.sort_values(['S', 'X', 'M'], ascending=[False, True, True])
    df_O    = df_Sort.set_index('O')
    M_Top   = df_O[~df_O.index.duplicated(keep='first')].M
    M_Top   = M_Top.sort_index()

    # Compare the top scoring row for each O to df_1
    df_1_R = df_1_M.reindex(M_Top.index) # Nan
    T_N_T  = M_Top == df_1_R

    # Record the results for the given values of A,B,C
    df_Res = pd.DataFrame({'it_is':T_N_T}) # is this row of df_1 the same as this row of M_Top?

    # p_hat =         TP / (TP + FP)
    p_hat = df_Res.sum() / len(df_Res.index)

    print(z)
    return -p_hat[0]

# Bounds
min_ = -2
max_ = 2
ran_ge = (min_, max_)
bounds = [ran_ge,ran_ge,ran_ge]

# Params
params = (df_1, df_2)

# DE
DE = differential_evolution(fun, bounds, args=params)

print('Function value at global maximum ',-DE.fun)


text:
Q: What is an efficient method for partitioning and aggregating intervals from timestamped rows in a data frame? From a data frame with timestamped rows (strptime results), what is the best method for aggregating statistics for intervals?
Intervals could be an hour, a day, etc.
There's the aggregate function, but that doesn't help with assigning each row to an interval.  I'm planning on adding a column to the data frame that denotes interval and using that with aggregate, but if there's a better solution it'd be great to hear it.
Thanks for any pointers!

Example Data
Five rows with timestamps divided into 15-minute intervals starting at 03:00.
Interval 1

*

*"2010-01-13 03:02:38 UTC"

*"2010-01-13 03:08:14 UTC"

*"2010-01-13 03:14:52 UTC"

Interval 2

*

*"2010-01-13 03:20:42 UTC"

*"2010-01-13 03:22:19 UTC"

Conclusion
Using a time series package such as xts should be the solution; however I had no success using them and winded up using cut.  As I presently only need to plot histograms, with rows grouped by interval, this was enough.
cut is used liked so:
interv <- function(x, start, period, num.intervals) {
  return(cut(x, as.POSIXlt(start)+0:num.intervals*period))
}

A: Use a time series package. The xts package has functions designed specifically to do that.  Or look at the aggregate and rollapply functions in the zoo package.
The rmetrics ebook has a useful discussion, including a performance comparison of the various packages:  https://www.rmetrics.org/files/freepdf/TimeSeriesFAQ.pdf
Edit: Look at my answer to this question.  Basically you need to truncate every timestamp into a specific interval and then do the aggregation using those new truncated timestamps as your grouping vector.

A: Standard functions to split vectors are cut and findInterval:
v <- as.POSIXct(c(
  "2010-01-13 03:02:38 UTC",
  "2010-01-13 03:08:14 UTC",
  "2010-01-13 03:14:52 UTC",
  "2010-01-13 03:20:42 UTC",
  "2010-01-13 03:22:19 UTC"
))

# Your function return list:
interv(v, as.POSIXlt("2010-01-13 03:00:00 UTC"), 900)
# [[1]]
# [1] "2010-01-13 03:00:00"
# [[2]]
# [1] "2010-01-13 03:00:00"
# [[3]]
# [1] "2010-01-13 03:00:00"
# [[4]]
# [1] "2010-01-13 03:15:00 CET"
# [[5]]
# [1] "2010-01-13 03:15:00 CET"

# cut returns factor, you must provide proper breaks:
cut(v, as.POSIXlt("2010-01-13 03:00:00 UTC")+0:2*900)
# [1] 2010-01-13 03:00:00 2010-01-13 03:00:00 2010-01-13 03:00:00
# [4] 2010-01-13 03:15:00 2010-01-13 03:15:00
# Levels: 2010-01-13 03:00:00 2010-01-13 03:15:00

# findInterval returns vector of interval id (breaks like in cut)
findInterval(v, as.POSIXlt("2010-01-13 03:00:00 UTC")+0:2*900)
# [1] 1 1 1 2 2

For the record: cut has a method for POSIXt type, but unfortunately there is no way to provide start argument, effect is:
cut(v,"15 min")
# [1] 2010-01-13 03:02:00 2010-01-13 03:02:00 2010-01-13 03:02:00
# [4] 2010-01-13 03:17:00 2010-01-13 03:17:00
# Levels: 2010-01-13 03:02:00 2010-01-13 03:17:00

As you see it's start at 03:02:00. You could mess with labels of output factor (convert labels to time, round somehow and convert back to character).

A: This is an interesting question; with the proliferation of the various time series packages and methods, there ought to be an approach for binning irregular time series other than by brute force that the OP suggests.  Here is one "high-level" way to get the intervals that you can then use for aggregate et al, using a version of cut defined for chron objects.
require(chron)
require(timeSeries)

my.times <- "
2010-01-13 03:02:38 UTC
2010-01-13 03:08:14 UTC
2010-01-13 03:14:52 UTC
2010-01-13 03:20:42 UTC
2010-01-13 03:22:19 UTC
"

time.df <- read.delim(textConnection(my.times),header=FALSE,sep="\n",strip.white=FALSE)
time.seq <- seq(trunc(timeDate(time.df[1,1]),units="hours"),by=15*60,length=nrow(time.df))
intervals <- as.numeric(cut(as.chron(as.character(time.df$V1)),breaks=as.chron(as.character(time.seq))))

You get
intervals
[1] 1 1 1 2 2

which you can now append to the data frame and aggregate.
The coersion acrobatics above (from character to timeDate to character to chron) is a little unfortunate, so if there are cleaner solutions for binning irregular time data using xts or any of the other timeSeries packages, I'd love to hear about them as well!..
I am also curious to know what would be the most efficient approach for binning large high-frequency irregular time series, e.g. creating 1-minute volume bars on tick data for a very liquid stock.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Application Version INSTANT_RUN? So, yay, instant run provides a semi-"instant" build (Well... 7 seconds is not "instant" but whatever).

Now, I know everything comes with pros and cons, but I can't seem to fix this bug that my Android App's version is "INSTANT_RUN". Here's my gradle line:
versionName "0.1 Beta"

I tried removing beta but apparently it's not the problem.

Although I'm much of a thug life person, I searched SO and I found a question, and the answer to it was downgrading Gradle Build Tools, which won't help me since I need the latest version to prevent bugs.
I've looked everywhere in Android Studio, but didn't find anything.

A: you haven't posted if your gradle has a versionCode line, like this
versionCode 1

if it doesn't have that line, try adding it..
if it still doesn't work, try disabling instant run.


text:
Q: ¿Cómo usar inner join? tengo esta consulta
    $query=$db->query("select empleado,count(*) as v
                       from empleado
                       inner join oficinas on
                       empleado.numero=oficinas.numero");

pero me da esta salida
¿alguien me dice que estoy haciendo mal? :3
El caso es el siguiente: tengo una tabla de empleados y otra de oficinas. Hay 7 oficinas registradas (en la tabla de oficinas, con diferentes id por supuesto), y hay 12 empleados que pertenecen a una oficina cada uno.
Varios de ellos pertenecen a la misma oficina. Pero por ejemplo, en la tabla oficina está registrada la oficina 8 pero no hay ningún empleado en la oficina 8, ¿me entienden? Entonces como no hay ningún empleado en la oficina 8, no quiero mostrar ese registro. Quiero mostrar solo los empleados que pertenecen a una oficina. En realidad quiero mostrar cuántos empleados tiene cada oficina, pero las oficinas que tengan empleados pues.
Pero esta consulta no me funcionó. :c Alguien écheme una mano please :)

A: Tu error esta en que el query que hiciste esta mal. Nunca lo probaste en la base de datos no??
Voy a tratar de arreglarlo, pero sin mas información se complica:
select oficina,count(empleados) as v
from
    empleado
 inner join
    oficinas on empleado.numero=oficinas.numero
group by oficina

A: Usando la información de tu otra pregunta, parece que la consulta deseada para obtener la cantidad de empleados por oficina, es:
select o.numero, o.ciudad, count(*) as cantidad_empleados
  from oficinas o
  join empleado e
    on e.numero_o = o.numero
 group by o.numero, o.ciudad


text:
Q: Karate- Good way to send custom headers with each request I have a scenario where I am doing a GET call and on my table I have parameters defined. Now for the headers, I want to purposefully send incorrect values to make sure the test fails as expected. Not really sure how to do it though.
I have the following setup:
        * table input
            | machine    | version | osSystem | status |
            | machineName| version | windows  | 401    |

My secondary file that the above calls on, looks like this:
        Given url env
        And path path
        And header Content-Type = 'application/xml; charset=UTF-16'
        And header Accept = '*/xml; charset=UTF-16'
        And header key = key
        When method GET

In above, I want to send bogus values for "key" header. Total of six bogus values (random alpha string, random number string, random alphanumerical value, random guid, etc). I have obviously tried entering the values as a json under "and header key = {}" but how do I make each request run EACH header per request, instead of running them all in one request?
Thank you in advance!

A: Try this example and observe how it works, it will answer all your questions:
Scenario Outline:
* url 'https://httpbin.org/anything'
* header foo = header
* method get

Examples:
| header |
| one    |
| two    |

And for an alternate way to "loop" refer to this answer: https://stackoverflow.com/a/69422451/143475


text:
Q: Put DropShadowEffect below neighboring disabled elements I have several Borders in a Grid, each has a DropShadowEffect. When a Border is disabled (IsEnabled = false), the DropShadowEffect of the neighboring Borders is above it, thus visible and weird looking.

This is even though I explicitely set the Panel.ZIndex such that there shouldn't be. It doesn't even matter how I sort the Borders.
When the buttons are enabled, everything is fine.


text:
Q: Is "her" a possessive or an objective pronoun in "A mother takes care of her children"? I had a sort of debate with my teacher to whether the her in the sentence

A mother takes care of her children.

is a possessive or an objective pronoun.
I told my teacher that it was a possessive pronoun, as the mother had ownership of her children, but she told me it was an objective pronoun as it had preceded a preposition, making it an object of the preposition.
Which one should be correct, or, should both be considered?

A: TL;DR: The word her in "A mother takes care of her children" is neither a possessive pronoun like mine nor an object pronoun like me; it is a possessive determiner like my.

Just because something immediately follows a preposition does not mean that that thing must be an "object" form.  For example:

Give the prize to whoever comes in first without cheating.

That's a subject form not an object form, even though it immediately follows a preposition, because it's its job in the entire clause that matters, and the object of that preposition is the entire clause.
Similarly in your case:

A mother takes care of her children.

There her is a determiner, not a pronoun. For her to be used as the object of the preposition of, you would need something more like this, in which case her really is a pronoun now, not a determiner:

Her father takes care of her.

The object of the preposition is the noun phrase her children, with her a possessive determiner.  This is not a substantive use because it cannot stand in for a noun.  You cannot say:

She'd like to see some of *my.

The reason that is starred as illegal is because my is a possessive determiner, not a possessive pronoun.  Here is an example of a possessive pronoun serving as the object of a preposition:

She'd like to see some of mine.

For your situation, the actual possessive pronoun corresponding to the subject she is hers — not her, which is not a possessive pronoun at all, merely a determiner or object form.
An example of actual possessive pronoun use of hers is:

When Billy wanted to help Sarah with her homework, he would do hers as well as his own.

Tables for Clarity
English pronouns are pretty confusing for several reasons.  One is that some forms serve multiple functions, especially in the third person forms.  Wikipedia offers a simple table of these:

As you see, several forms span multiple columns, meaning that the same spelling works for multiple functions.  Furthermore, the reflexive / emphatic forms ending in self are sometimes derived from possessive determiners and other times derived from object pronouns.  All this can be very confusing to learners.
When you add in archaic, nonstandard, and dialectic forms, which you will nonetheless from time to time encounter, the picture becomes even more confusing.  Wikipedia offers another table immediately below that one, but it is too large to reproduce here.
Instead, let me flip the axes around and fill in the forms that occupy more than one position.  This should make it easier to understand for some people's learning styles, because now you have the various forms corresponding to a particular person lined up in an easy-to-read column.
         (Click on table below to embiggen.)

Note that I include only the forms you are apt to encounter in normal use. I have omitted nonstandard and dialectic forms to simplify matters, as well as the archaic second-person plural pronoun ye, which while originally a subject pronoun came to be used as an object pronoun, too.  I have also omitted the most common impersonal pronoun set: one, one's, oneself.

A: The discussion only arises because English grammar uses the term object not only as sentence part (objects after verbs) but unfortunately also as term for word groups (object after a preposition). In my view, a use of the term object which only leads to confusion.
As to me, "her" in "her children" is a possessive adjective and it is totally irrelant whether "her children" is preceded by a preposition or not. If you choose another term for the noun after a preposition, e.g. preposition complement then the discussion is pointless.
In all my life I haven't found it necessary to have a special term for the noun following a preposition. According to my definition you can place a preposition before a noun to get secondary indications (where, when etc). Of course, there are cases where a preposition is followed by other word classes but in almost all these cases you can insert a noun to get the full formula.

*

*The cat appeared from under the couch ( from her place under the couch).

Added: Actually I find the original question totally confusing because there are several things intermingled.
1 What  word class is "her" + children? Traditionally "her" is a possessive adjective, and not a pronoun. The possessive pronouns are used without noun and are
mine, yours, his, hers etc.
2 What case follows after a preposition? In English there is only one answer: an accusative (direct object). In English this becomes clear only with personal pronouns: for him, to them, about us. But I think it makes no sense to ask which case is "her". You would ask: A mother takes care of whom? Answer: of her children/ of them. So the whole noun group "her children" is an accusative or object case. Subject case would not make sense. But one can't say "her" alone is in object case.
For me this absurd question is a paragon to show how simple structures  can be made a problem.
If one would try to answer this question reasonably the answer should be
1 "of her children" is possessive case
2 After the preposition of follows "her children", which is object case.
3 and "her" belongs to the word class possessive adjectives.

A:
A mother takes care of her children.

The Original Poster is correct. The word her here is a possessive pronoun in determinative function. The complement or object of the preposition of is the noun phrase her children. The head noun in the noun phrase is children and the determinative is her.
The possessive pronoun her and the object pronoun her are homonyms - they look identical. However, it is easy to test if this is the possessive or object pronoun. We can simply substitute father for mother and see whether the corresponding word is the possessive pronoun his, or the object pronoun him:

*

*A father takes care of his children. (possessive pronoun)

**A father takes care of him children. (ungrammatical: object pronoun)

This shows that the determinative in her children must be a possessive pronoun here.
Hope this is helpful!
Note: The term object pronoun is not very helpful. It tends to imply that the pronoun needs to be the object of something to be in this case - which isn't true. Accusative case pronoun is a better term, imo.

A: Note the contextual significance of the pronoun:

A mother takes care of her children

(takes care, phrasal v.) --> (of, prep.) --> (her children, object of v.)
children is the object, not her, which merely qualifies the object
As such, her is the usual possessive pronoun here.
Compare:

Her mother takes care of her

(takes care, phrasal v.) --> (of, prep.) --> (her, object of v.)
her is the object, the objective pronoun, in the oblique/ accusative case.
There may be a reason why the teacher considered it otherwise, the OP could get it clarified.


text:
Q: square-commerce-v1 bring back to window instead of new tab I have the following:
var dataParameter = {
    amount_money: {
        amount:        "10",
        currency_code: "USD"
    },

    // Replace this value with your application's callback URL
    callback_url: "https://website.com",

    // Replace this value with your application's ID
    client_id: "sq0123idp-asd89798asd",

    version: "1.3",
    notes: "notes for the transaction",
    options: {
        supported_tender_types: ["CREDIT_CARD","CASH","OTHER","SQUARE_GIFT_CARD","CARD_ON_FILE"]
    }
};

const url =
"square-commerce-v1://payment/create?data=" +
encodeURIComponent(JSON.stringify(dataParameter));

Everytime I click this link, it takes me to the correct square app. But then it opens up website.com in a new URL.
I'm trying to build a web POS system so that square will just bring me back to the tab it was on originally. Is this possible?

A: I'm not sure what the intended way to use this is, and we ran into the same issue (iOS Safari).
Our work-around -- have the callback go to a new endpoint that saves the event (both in localstorage and to the server DB via XHR) and then closes itself using Javascript. The tab "under" the current one is the tab we started on, which can then act. It had been polling the localstorage and server during the whole transaction to get an update.
We found that even this is fragile though, so ALSO have webhooks registered on the site. For example, in the POS the operator can hit the "X" or similar things to abort the transaction and never trigger the callback. But if something happens upstream we should get the webhook no matter what.
I'd LOVE some insight from Square on better ways to do this. In theory we should be able to use a Universal Link or something.


text:
Q: git alias for a full reset to HEAD I have the following git aliases:
[alias]
        b           = branch
        p           = push
        co          = checkout
        cm          = commit -m
        cmall       = !git add -A && git commit -m
        cob         = checkout -b
        cached      = diff --cached
        addall      = add -A
        editconfig  = config --global -e
        save        = !git add -A && git commit -m SAVEPOINT
        unsave      = reset HEAD~1 --mixed
        amend       = commit -a --amend
        wipe        = !git add -A && git commit -qm 'WIPE SAVEPOINT' && git reset HEAD~1 --hard
        reset       = !git reset --hard HEAD && git clean -qfdx

reset should actually reset, but as is still leaves untracked files.
based on git reset --hard HEAD leaves untracked files behind, the second part of my reset should work, in fact it does when I do it alone...which makes me thing there's error in my gitconfig syntax. Why isn't reset working? Thank you

A: From the git-config man page: "To avoid confusion and troubles with script usage, aliases that hide existing git commands are ignored."
So your reset alias is being ignored and the original reset command is run. You'll have to name the alias something else.

A: Or maybe there is a way! Mhwuahahaha
http://blogs.atlassian.com/2014/10/advanced-git-aliases/
my_alias = "!f() { 〈your complex command〉 }; f"


text:
Q: the animation is not work i have made the following animation xml file in my android project:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator = "true"
android:interpolator="@android:anim/linear_interpolator">
<scale
 android:fromXScale = "1.0"
 android:toXScale = "0.0"
 android:pivotX="50%"
 android:pivotY="50%"
 android:duration="40000">
 </scale>
 </set>

what this is basically doing is making a view dissappear starting from its center.
Now in my code i am doing the following to start the animation:
overridePendingTransition (0,R.anim,myanimation);

but nothing is happening.
what am i doing wrong?
thank you in advance.

A: try changing the animation to overridePendingTransition(R.anim.myanimation,0); and then set the timing accordingly if it helps. And also check this if it might help : http://developer.android.com/training/animation/cardflip.html

A: try this:
Animation a = AnimationUtils.loadAnimation(this, R.anim.myanimation);
myView.setAnimation(a);
a.start();

A: Create anim folder and paste your xml there let the name of your xml is showview
Reduce your animation duration from 40seconds to see the effect for testing purpose
showview.xml
<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXScale="0.0"
    android:toXScale="1.0"
    android:fromYScale="1.0"
    android:toYScale="1.0"
    android:pivotX="100%"
    android:pivotY="100%"
    android:startOffset="0"
    android:duration="1000"
    android:fillBefore="true" />

In your code where you want to set animation use the following code if mImageView is the view where you want to set animation.
Animation mAnim = AnimationUtils.loadAnimation(this, R.anim.showview);
mAnim.setRepeatMode(Animation.ABSOLUTE);
mImageView.startAnimation(mAnim);

Thanks
Deepak

A: While using animation of XML file , please check some android devices have setting:
GO to Setting --> Display --> Animation --> enable All Animation


text:
Q: Can thrust occur with constant mass? I understand that in the case of a spacecraft, thrust works by releasing fuel with a velocity in one direction, pushing the rocket in the other direction. This is shown by the equality mv=mv.
Now. If let's say I somehow am in space, could I move by simply thrusting my hips/legs back and forth even though there is no exchange of mass (like fuel in rockets)?

A: Short answer to the title of your question: Yes.
Short answer to your actual question: No.
Long answer: You can have thrust without an exchange of mass. What you need is an exchange of momentum. Imagine a battery powered propeller airplane. It would create thrust using the propeller without losing (or gaining) any matter. The exchange of momentum happens between the propeller and the surrounding air here (the air is being pushed in one direction, the plain in the other).
Now in space, there is pretty much nothing there to exchange momentum with. You can do it via gravity (though this is an acceleration you cannot switch on or off or even steer1), radiation (the thrust resulting from shining a flashlight is practically zero, though) or using the residual gas that is still present in space. This residual gas, however, is so thin, that the thrust you can generate using it is very minute (though still interesting for spacecraft because with this they do not need to carry fuel!
Thrusting your hips/legs back and forth (or making swimming movements), however, would most certainly not result in any meaningful exchange of momentum before you died of old age.

1This is not entirely true. As Anders pointed out in his comment, you can exploit the curvature of space-time to "swim" in it by deforming yourself. (This wouldn't technically be thrust, but it is very very cool.) Though I am no expert here, I am fairly confident that this technique would be even less effective in moving you around than swimming in residual gas for typical places "in space" (i.e. typical curvatures and gas densities in the universe).


text:
Q: Can lldb inspect what has been written to a file, or the data in an IPC mechanism it has generated/used, at a breakpoint? Say with this simple code:
#include<stdio.h>
int main(int argc, char** argv){
    printf("Hello World!\n");
    return 0;
}

After stepping printf("Hello World!\n"); perhaps there's a command to print that "Hellow World!\n" has been written to STDOUT.
And after return 0 perhaps there's a command to see the exit codes generated and it will show 0.
Are there such commands or similar in lldb?

A: LLDB prints the exit status when a process exits:
(lldb) run
Process 76186 launched: '/tmp/a.out' (x86_64)
Process 76186 exited with status = 10 (0x0000000a)

and you can also access it with the SB API's:
(lldb) script lldb.process.GetExitStatus()
10

lldb doesn't have any special knowledge about all the ways a program might read or write data to a pipe, file handle, pty, etc...  It also doesn't know how to interpose on file handles and tee-off the output.  There's no particular reason it couldn't, but nobody has added that to date.
So you would have to build this yourself.  If you know the API your code is using to read and write, you could use breakpoints to observe that - though that might get slow if you are observing a program that reads and writes a lot.


text:
Q: Completing decompiled code I have the following section of code. What method is supposed to be in the place of local 36?
   public void Alert()
  {
    AlertDialog.Builder localBuilder1 = new AlertDialog.Builder(this);
    AlertDialog.Builder localBuilder2 = localBuilder1.setMessage("You lost").setCancelable(false);
    36 local36 = new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface paramDialogInterface, int paramInt)
      {
        paramDialogInterface.cancel();
        Pokemon.this.setContentView(2130903046);
        Pokemon.this.mainmenu();
      }
    };
    AlertDialog.Builder localBuilder3 = localBuilder2.setPositiveButton("OK", local36);
    AlertDialog localAlertDialog = localBuilder1.create();
    this.alert = localAlertDialog;
    this.alert.show();
  }

A: I expect that the original code looked something like this:
AlertDialog.Builder localBuilder3 =
  localBuilder2.setPositiveButton
  (
    "OK",
    new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface paramDialogInterface, int paramInt)
      {
        paramDialogInterface.cancel();
        Pokemon.this.setContentView(2130903046);
        Pokemon.this.mainmenu();
      }
    }
  );

rather than having two separate statements. So the 36 wasn't in the original code; it represents the name of the anonymous inner class.


text:
Q: Regular Backup Script for Apache Derby Apache database hosted in a virtual server to be used with a JSF and JPA application.It there any method where regular back ups can be performed, for example once a day? Like an script?

A: Here's a lot of information about making backups of a Derby database: http://db.apache.org/derby/docs/10.9/adminguide/cadminhubbkup98797.html
Choose a backup method that works well for you, then use your operating system's scheduling tools (cron, etc.) to arrange for that backup to be performed regularly.


text:
Q: React Form Dynamic Input Fields I'm trying to create a react form with multiple (dynamic) input fields. Inputs are grouped together as seen in the picture below.

When a user submits the form, I need to get the values selected from each group. The groups are dynamically generated using the map function. I haven't found much on this topic.
My existing code:
<form onSubmit={this.handleSubmit.bind(this)}>

    {this.state.food.options.map((food, i) =>

{food.name}

            {food.options.map((option, k) =>

                  <input type="radio" name={option.name} value={option.id} style={{height: 20}} />

                  {option.name}

              )}

          )}

    </form>

A: You have to use checked attribute instead
And use onChange event for select optionID
<input
type="radio"
name={option.name}
value={option.id}
style={{height: 20}}
checked={this.state.optionId[option.name] === option.id}
onChange(this.handleChange)
/>

handleChange = e => {
    this.setState({
      optionId: e.target.value
      });
}


text:
Q: Storing Undo and Redo information to the database? I've been wondering about this for a while and I haven't yet come up with a solution for it. On MySQL, I'd create a TRIGGER to automate saving revisions when changes happen and persist change values to the database to track revisions.
The question I have now is: how I can implement this in a more generic sense across most of my models in Django? Right now, I have just over 20 models and it's quickly growing. Generating objects to store all of these items will multiply my models by at least 2 and doesn't seem to be too optimal.
Is there a way I can automate this and make it a bit smarter and less cumbersome?

A: Check out django-reversion.


text:
Q: JQuery animate scrollTop strange behaviour I'm making a simple calendar in PHP in the form of a vertical table. When the page loads I want it to scroll automatically to the current day with an animation.
I chose to create it myself because classes available on the internet don't allow to show the content in the way I want.
This is always working correctly in Chrome on Windows PC, but in Edge and Chrome on Android it only works in Incognito mode or 1 single time after clearing the cache.
I tried every solution suggested on the internet, but nothing works.

*

*Removing viewport

*Only animate $('body')

*Remove overflow: hidden

*Set overflow hidden first, then animate and then set overflow again to auto

*Remove height: 100%

*Adding cache headers in HTML

I don't know anymore what to do. What could be the problem?
Please keep in mind that I'm just a beginning developer, doing this in my spare time only.
The current code:
[PS: I know it is better to seperate HTML and CSS, but it is just a test. Also, the variables and their values are simplified in the example.]
<!DOCTYPE html>

        <META charset = "UTF-8">
        <META name = "viewport" content = "width=device-width, initial-scale=1, shrink-to-fit=no">
        <META HTTP-EQUIV = "CACHE-CONTROL" CONTENT = "NO-CACHE">
        <META HTTP-EQUIV = "EXPIRES" CONTENT = "Mon, 22 Jul 2002 00:00:01 GMT">
        <META http-equiv = "pragma" content = "no-cache">
        <LINK rel = "stylesheet" href = "addins/jQueryUI/jquery-ui.min.css">

<?php
    /* Setting PHP vars here. */
?>

<?php
    for ($thisdaynumber = 1; $thisdaynumber <= $numberofdaysinmonth; $thisdaynumber++) {
?>
            <DIV id = "<?php echo "day".$thisdaynumber;?>">
                <TABLE id = "<?php echo "titletable".$thisdaynumber; ?>">

<?php
                    echo "";
                        echo "".$thisweekdayname."";
                        echo "
".$thisdaynumber."";
                    echo "	";
?>

                <TABLE id = "<?php echo "contenttable".$thisdaynumber; ?>">

<?php
    }
?>

Thank you in advance for your time.
Bart

A: The problem was with the hiding and showing of the #pagecontent. jQuery .show() sets the display type back to the initial value (inline by default). I changed it to .css('display', 'block') and now it's working fine. Actually I don't really understand very why this solves my problem.


text:
Q: Parsing smv files in eclipse I download nusmv-tools(https://code.google.com/a/eclipselabs.org/p/nusmv-tools/) which is a model checker.
I installed it and its dependencies(such as xtext)on eclipse successfully and restart eclipse.
Now, I expect eclipse recognize the nusmv files (which extensions are '.smv'), however it cannot.
My question is, what should I do in order to make parse nusmv files in eclipse, so that eclipse will recognize and highlight the nusmv file(.smv).
(Should I create an xtext project or java project or general project?
Which libraries or external jars should I add to the project?)
Any help?
Thanks

A: Actually, for nusmv, the problem was: I was using eclipse 64 bit, but it seems the nusmv-tools require to use 32 bits eclipse and xtext 2.5 version...
After downgrading the eclipse and xtext it worked for me...


text:
Q: Tailwind css opacity In my app I've a model. I'm using opacity on a model.
The problem that I have now is that the body of the model
should not have opacity how could I fix this? Only outside the model
should have opacity!

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css" rel="stylesheet">

Model body

A: Checkout 'Changing the opacity' for background color with Tailwind:
https://tailwindcss.com/docs/background-color#changing-the-opacity
For example in this example 'bg-sky-500' will have an opacity of 50:
<button class="bg-sky-500/50 ..."></button>

A: I know it's been almost three years, and I'm not sure if this is what you want in your situation. But using bg-opacity-{n} instead of opacity-{n} did the trick for me.
I wanted to display an overlay element with kind of blackish background, but the overlay element itself should have 100% opacity.
Example code:

        Sample Text

Posting this in case anyone else needs a solution like this.
TL;DR - use bg-opacity-75 in parent div, and bg-opacity-100 in child div. Using opacity-75 and opacity-100 doesn't work for some reason.

A: You could add .opacity-100 to the nested div.
Check the Official Tailwind Documentation about Opacity for further details.

A: When you apply opacity to a container, all its content and children will inherit
the opacity.
You can see this question on Stackoverflow:
Allow opacity on container but not child elements
The solution is to apply opacity value to background-color. In tailwind you
can do it with bg-blue-{opacity} like bg-blue-100

A: You need to play around with relative/absolute, opacity and z-index
Here's a jsfiddle working example.

new Vue({
  el: "#app",
  data: function () {
     return {
        modalOpen: false
     }
  }
})
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"/>

      Open Modal

      Modal

A: Assigning bg-opacity-40 to the outer div solved it for me


text:
Q: Unexpected regex match with grep I am using GNU grep 2.6.3 on Ubuntu 10.10 and am brushing up on my regex skills in preparation for an upcoming training course and am getting an unexpected hit on the following.
I have a file named strings.regex.txt with the following content:
STRING1   Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)
STRING2   Mozilla/4.75 [en](X11;U;Linux2.2.16-22 i586)

This grep command:
grep 'x[0-9A-Z]' strings.regex.txt

Results in:
STRING1   Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)
STRING2   Mozilla/4.75 [en](X11;U;Linux2.2.16-22 i586)

I expected this as the result:
STRING2   Mozilla/4.75 [en](X11;U;Linux2.2.16-22 i586)

Can anyone explain why I am getting the above result?  The first line of the grep output does not contain a match of the regular expression x[0-9A-Z] .  It would have matched on x[0-9a-z] or on x[0-9A-Za-z] or a number of other regular expressions.  The way I learned and understand regular expressions.  It should not have matched.
Here are some additional grep commands and the resulting output:
grep -o 'x[0-9A-Z]' strings.regex.txt
x2

(I expected this and it supports my current understanding of regular expressions.)
grep -oc 'x[0-9A-Z]' strings.regex.txt
2

(I did not expect this.  I expected 1.)
grep -c 'x[0-9A-Z]' strings.regex.txt
2

(I did not expect this.  I expected 1.)

A: Add a LC_ALL=C before the grep command, i.e.
$ grep -c 'x[0-9A-Z]' strings.regex.txt
2

$ LC_ALL=C grep -c 'x[0-9A-Z]' strings.regex.txt
1

From grep man-page
LC_ALL
LC_COLLATE
LANG
    These variables specify the locale for the LC_COLLATE category,
    which determines the collating sequence used to interpret range
    expressions like '[a-z]'.


text:
Q: How to add package jade-handlebars I am just a newbie in meteor and meteorite. I create a new project by mrt create my-app --branch devel. I have install meteorite by $ sudo -H npm install -g meteorite now when I add the package mrt add bootstrap the packages successfully added but on doing mrt add jade-handlers  it wont show anything(either error or sucess) so how can I add the jade-handlerbars packages in my meteor project??
I am using node --version 0.10.11
meteorite --version 0.6.5
release 0.6.4
Thank You in Advance!!!

A: It may be that your smart.json is pointing at the tag on that package, rather than the git repo itself. (The last update to the package did not include a version bump, so the version of the package you get just by mrt adding it is outdated.)
Try putting this in your smart.json:
"jade-handlebars": {
  "git": "https://github.com/SimonDegraeve/meteor-jade-handlebars.git"
}

A: Just a typo I guess?
mrt add jade-handlebars instead of mrt add jade-handlers

A: I also just figure it out that you can add the packages from the atmosphere by
mrt add <package> --repoPort=443


text:
Q: Article before ordinal numbers
That first season wrapped everything up nicely and when I heard that a second season would be made I started to wonder if it would be able to reach the same quality as the first season.

Source: Bridge Season.
I have from time to time problems to decide whether to use the definite or indefinite article before ordinal numbers. As to my sentence: would  usage of the definite article in the first part of my sentence be a grammatical mistake? Why is there "a second season" but "the first season" in it?

A: Please try some peas.
-- Mmmm. These peas are delicious! Do you have a secret recipe?
I'll let you in on the secret: my grandma's recipe calls for a generous dash of arsenic.
-- They're scrumptious. I've already eaten the first helping you have given me.
Well then, have a second helping.  But I doubt you will ask for a third.
Why do we say "the first helping" but "a second helping"?
The first helping is a particular helping: it actually existed, and was of a certain size and taste and color and temperature, and so forth, and it was served to you at a particular time.
A second helping, on the other hand, is only a possibility, a concept, an  abstraction: "a-helping-that-would-come-after-a-first-helping". Its only attributes or properties are its ordinal and its category.
In the same way, "a second season" means only "a season that would follow upon the first season".  Until it acquires some specific properties in addition to its ordinal (2nd) and its category (season), such as plots and stories, new characters or reappearing characters, a number of episodes,  whatever, we cannot speak of "the second season".


text:
Q: how to hide react native change image white effect on android I have list of images and want display one image on view on tap next will be displayed.
when new image url is updated via state it shows a white blur effect only on android not on ios.
<TouchableHighlight
      onPress={() => {
        this.contentClick();
       }
      } >
      <View style={{backgroundColor:'rgba(52, 52, 52, 0.8)'}}>
         <Image
            style={styles.contentImage}
            source={
              this.state.album0data[this.state.currentImageIndex]
            }
            fadeDuration={0}
          />
      </View>
    </TouchableHighlight>

can someone help

A: The first check OS with Platform like this:
import {Platform, StyleSheet} from 'react-native';

const styles = StyleSheet.create({
  height: Platform.OS === 'ios' ? 200 : 100,
});

and can you tell me you want to show list of image in a Flatlist or just a view?


text:
Q: How to check mysql table with python I want to create a license system for my code in Python.
Now I am facing an issue: how can I check if an integer is contained in my MySQL database?
Here are some variables for the database.
'License' Database: license|user
Database name = License
columns = license and user

Here is my code I got so far:
def check_data():
    license = str(11585728)
    val = f'"18742974","USER"'
    sql = "SELECT * FROM License WHERE license = ''11585728''"

    cursor.execute(sql)
    conn.commit()
    cursor.execute("SHOW DATABASES")```


text:
Q: Render Twig templates in Controller - Slim 4 Framework Like said in the title, I looking to rendering twig template in controller using Slim 4 framework.
I searched on the Internet, but I didn't find a solution that works for me and well-explained.
If someone can explains me how can I make this to work.
Here the code a my files:
index.php
<?php
use App\Controllers\HomeController;
use DI\Container;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

### Container ###
$container = new Container();

### Slim ###
AppFactory::setContainer($container);
$app = AppFactory::create();

### Twig ###
$container = $app->getContainer();
$container['view'] = function ($c) {
    return $c;
};
$container['HomeController'] = function ($c) {
    return new HomeController($c['view']);
};

### Routes ###
$app->get('/',HomeController::class . ":home");
$app->get('/home', HomeController::class . ":home");

### Run ###
$app->run();

HomeController.php
<?php

namespace App\Controllers;

use Psr\Container\ContainerInterface;
use Slim\Psr7\Request;
use Slim\Psr7\Response;

class HomeController
{
    private $app;

    public function __construct(ContainerInterface $app)
    {
        $this->app = $app;
    }

    public function home(Request $request, Response $response)
    {
        $this->app->get('view')->render($response, 'home.twig');
    }
}

composer.json
{
    "require": {
        "slim/slim": "4.*",
        "slim/psr7": "^1.0",
        "slim/twig-view": "^3.0",
        "php-di/php-di": "^6.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
}

project structure

And when I start the server, the console gives me:
PHP 7.3.11-0ubuntu0.19.10.2 Development Server started at Tue Feb 18 16:33:41 2020
Listening on http://localhost:8080
Document root is /home/thomas/Code/2020/S4/prog_web/homelogin/public
Press Ctrl-C to quit.
[Tue Feb 18 16:33:44 2020] PHP Fatal error:  Uncaught Error: Cannot use object of type DI\Container as array in /home/thomas/Code/2020/S4/prog_web/homelogin/public/index.php:17
Stack trace:
#0 {main}
  thrown in /home/thomas/Code/2020/S4/prog_web/homelogin/public/index.php on line 17

Thank in advance.

A: You cannot use DI\Container object as an array. You should use set() method to add a service to the container instead.
Replace these lines:
$container['view'] = function ($c) {
    return $c;
};
$container['HomeController'] = function ($c) {
    return new HomeController($c['view']);
};

with these:
$container->set('view', function () {
    return \Slim\Views\Twig::create('../resources/views', ['cache' => false]);
});
$container->set('HomeController', function () use ($container) {
    return new HomeController($container);
});

And then you should return a response (ResponseInterface) in the home() method of your HomeController class:
public function home(Request $request, Response $response)
{
    return $this->app->get('view')->render($response, 'templates/home.twig');
}

Note that your home.twig file is located in the templates directory.
Read more about Dependency Container and Twig in Slim.


text:
Q: Sub categories Hierarchy I designed a SQL structure to represent categories and their subcategories.
I have 3 tables:
articles
articles_categories
categories

Articles table:
id,title,content

Categories table:
id, title, parent_id

articles_categories:
id,article_id,category_id

No problem with SQL, but now - lets say i'm on article id 5
article id 5 has - 3 categories, that 2 of them has parents, and the main has '0' as parent.
How do I fetch them all efficiently? (lets say for - breadcrumbs).
thanks!

A: Unless the depth of the category hierarchy is fixed, you cannot do this in MySQL with your current model (adjacency list). You'd have to traverse the hierarchy using several SQL statements in a loop.
If the category hierarchy is fairly static, you can "precompute" the tree by using:

*

*Path enumeration

*Nested sets

*Closure table

All of the above, trades write performance for read performance.
Google or search SO for any of the above and you will find examples of how to implement it.
Quite often, I find that storing the data in a adjacency list (because of best matches the data model) and caching a copy of the tree in the application is good enough, but that depends on your requirements of course :)

A: This should do the job:
select * from articles_categories
left join categories on categories.id = articles_categories.category_id
where article_id=1;

+------+------------+-------------+------+--------+-----------+
| id   | article_id | category_id | id   | title  | parent_id |
+------+------------+-------------+------+--------+-----------+
| NULL |          1 |           1 |    1 | first  |         0 |
| NULL |          1 |           2 |    2 | second |         1 |
| NULL |          1 |           3 |    3 | third  |         2 |
+------+------------+-------------+------+--------+-----------+

Additionally, I would remove the "id" column from associative table articles_categories.


text:
Q: Does order of UFW rules matter? When I first initialized my ufw, I did
ufw default allow outgoing
ufw default deny incoming
ufw allow 80/tcp
ufw allow 22/tcp

Over the last week or so, I've been going through my access logs and banning IPs that are making malicious requests on my server
I'd do so using
ufw deny from <ip>

Here's my ufw status verbose

All the IPs pasted here are from sick-filth spammers; take no pity on them

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
80/tcp                     ALLOW IN    Anywhere
22/tcp                     ALLOW IN    Anywhere
Anywhere                   DENY IN     125.39.22.154
Anywhere                   DENY IN     222.124.200.250
Anywhere                   DENY IN     101.60.178.197
Anywhere                   DENY IN     115.184.115.200
Anywhere                   DENY IN     93.174.93.129
... more ips ...
80/tcp (v6)                ALLOW IN    Anywhere (v6)
22/tcp (v6)                ALLOW IN    Anywhere (v6)

Question
What I'm noticing is that the ALLOW actions are before the DENY actions.
Does the order of the rules actually matter? Or can I rest peacefully knowing that my IP block has worked?
Side question: Is there a more effective way to handle spammy requests than manually greping access/error logs for malicious requests and blocking those IPs from making future requests?

A:
Does the order of the rules actually matter?

Yes it does. Denies should be first in this case since they are more specific (more specific rules should go first).  Example

Is there a more effective way to handle spammy requests than manually

fail2ban can scan logs, and add IPs to many types of filtering systems that match defined patterns.

A: You can instruct ufw to insert rules at a given position:
ufw insert 1 deny from <ip> to any

This inserts the deny rule in first position instead of last.


text:
Q: iPhone to use MFMailComposer to send email from app? In my application i am able to send email using MFMailComposer.
suppose if i have gmail account in my iPhone and i am using my app to send the email , i am able to send email to others
but suppose if i have yahoo account in my iPhone and i am using my app to send email,i am not able to send email.
I really don't no what is the problem,does MFMailComposer using gmail account only or something wrong with m code.
please help me out for this.
following is my code:
-(void)SENDEMAIL
{
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
        mailComposer.mailComposeDelegate = self;
        NSArray* arr = [[dictUser valueForKey:@"recipients"] componentsSeparatedByString:@","];
        NSLog(@"mailcomporeci%@",dictUser);
        NSLog(@"arr:%@",arr);
        [mailComposer setToRecipients:arr];

        //[mailComposer setSubject:[NSString stringWithFormat:@"Scheduled Email %@",arr]];
        [mailComposer setSubject:@"Scheduled Email"];
        [mailComposer setMessageBody:[dictUser objectForKey:@"message"] isHTML:NO];
        mailComposer.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self.tabBarController presentModalViewController:mailComposer animated:YES];
        [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(hackMail:) userInfo:mailComposer repeats:NO];
         }
     }

-(void)hackMail:(NSTimer*)theTimer {
    MFMailComposeViewController *mailController = theTimer.userInfo;
    UIBarButtonItem *sendBtn = mailController.navigationBar.topItem.rightBarButtonItem;
    id targ = sendBtn.target;
    [targ performSelector:sendBtn.action withObject:sendBtn];
}

#pragma mark Mail Compose Delegate Methods
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {

    switch (result)
    {
        case MFMailComposeResultCancelled:
        {
            break;
        }
        case MFMailComposeResultSaved:
        {
            break;
        }
        case MFMailComposeResultSent:
        {
            break;
        }
        case MFMailComposeResultFailed: {

            break;
        }

        default:
            break;
    }

    [self.tabBarController dismissModalViewControllerAnimated:YES];
}

A: Try it and check out the result  :
if([MFMailComposeViewController canSendMail]){
[self presentModalViewController:mailController animated:YES];
}
May be your device is not configured to any account to send mail.


text:
Q: Use another file A if file B does not exist I think it is a simple task. I tried a lot of things with no success.
I want to use a file A on a network directory and when I'm offline I want to use file B on my ssd.
file_PATH = "y:/file_A.txt"

if os.path.isfile(file_PATH):
    file_to_use = "y:/file_A.txt"
else:
    file_to_use = "d:/file_B.txt"

It doesn't work with this piece of code.
When I rename file_A for testing, file_B will not be used.
UPDATE
I've found the (very silly) mistake. It was a misspelling of one of the two directories.

A: Use os.path.exists and also think about using os.path.join for building your path.
file_PATH = "y:/file_A.txt"

if os.path.exists(file_PATH):
    file_to_use = "y:/file_A.txt"
else:
    file_to_use = "d:/file_B.txt"

A: import pathlib

file_PATH = pathlib.Path('y:/file_A.txt')

if file_PATH.is_file():
    file_to_use = "y:/file_A.txt"
else:
    file_to_use = "d:/file_B.txt"

EDIT: due to comment about Python 3.4
You can do it with os.path.exists with Python 2:
>>> import os.path
>>> file_path = 'c:/file_false.txt'
>>> os.path.exists(file_path)
False
>>> file_path = 'c:/file_real.txt'
os.path.exists(file_path)
True

So
import os.path
file_PATH = 'y:/file_A.txt'

if os.path.exists(file_path):
    file_to_use = "y:/file_A.txt"
else:
    file_to_use = "d:/file_B.txt"

A: I would suggest that you check for the existence of the file.
In python 3.4 : the pathlib module offers an object-oriented approach-:
from pathlib import Path
if Path(r"/path/to/file_A.txt").is_file():
    file_to_use = "y:/file_A.txt"

elif Path(r"/path/to/file_B.txt").is_file():
    file_to_use = "d:/file_B.txt"
else:
    # Do something if both files don't exist


text:
Q: How can the Steam first time setup be run without starting the game directly afterwards? Since the incredibly fascinating (re-)installation of some DirectX and VC-Redistributable files takes a bit longer than I'm willing to stare at my screen, I'd like to be able to do something else, e.g. watch youtube. But of course when the first time setup is done, the new game starts, usually directly with an intro which now ends up being mixed with some video I've just been watching or whatever.
Can the first time setup be started in such a way that the game that requires it is not automatically started after said setup?

A: Old post, but I came across this while googling for things to deal with an installer for Steam games, just figured I'd throw in an answer for the last question asked.
Running the redistributables won't inform steam that they're installed, because when Steam actually does a "First Launch" install it also writes entries to the registry to inform itself that they have been installed.
So, for instance, with Alan Wake, which has an AppID of 108710, Steam does a first launch and it creates the key (On Windows 7 x64):
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Valve\Steam\Apps\108710

Under this key it creates two values:
DirectX
VCRedistributable

Each with a DWORD value of 1, indicating they've been installed (0 meaning it hasn't). The keys vary for different games as well, sometimes even using a different value name for the same type of redist install, and others (given they do or don't have more redists to install) have a lot more than just those two.
I've actually, in my true nerd form, created an installer with Inno Setup for all of my Steam games that I've backed up. I have the installer let me chose whether I want to install the redist files, and if so it automatically writes these entries to the registry. So that way after installing my backup, I can play the game straight from the get go.
It's dumb, but I miss the days of having a physical disc with an installer, so that's really why I made the installer for my Steam backups.

A: If you look in the Program Files\Steam\steamapps\ directories you may find folders for VCRedist, DirectX and etc. These are the program's run during first time setup. Unfortunately, there is no common folder structure for instance Delve Deeper has everything in a folder redists but Civ 5 has separate folders for DirectX and VCRedist. Also, I don't know if just running these ahead of time will avoid the first time setup step when launched in Steam.

A: It's possible, but it's not pretty.
The first-run tasks are described in a file called installscript.vdf (or runasadmin.vdf) inside the game's folder, in steamapps somewhere. This script file is interpreted by SteamService.exe. A typical call would look like this (example here: Jamestown):
"C:\Program Files\Steam\bin\SteamService.exe" /installscript "C:\Program Files\Steam\steamapps\common\jamestown\installscript.vdf" 94200

As I said, it's not pretty, and it would require you to locate the installation script and look up the game's app ID (in this example, it's 94200). The app ID is not optional, and the Steam service will crash if it's omitted.


text:
Q: Bad Superblock while mounting an ext4 Disk I wanted to migrate my Data to a larger Disk for my secondary Drive for my Synology NAS.
I tried to Mount the Disk on a Rapsberry to do a Filetransfer to the new Disk on the Synology.
But on the way to get the Data from the old Disk I got superblock errors.
Maybe I hit a wrong Command to mount the Disk which was previously used as ext4 Disk in a Disk Pool with only this single Disk. (Last Time I used mdadm to migrate the Single Disk RAID and worked like a charm).
So now I am unable to mount it and have no clue how to continue getting back the Data.
Here are some commands I tried to debug:
pi@pi4:~ $ lsblk
NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda           8:0    0  7.3T  0 disk
├─sda1        8:1    0  2.4G  0 part
├─sda2        8:2    0    2G  0 part
└─sda3        8:3    0  7.3T  0 part
mmcblk0     179:0    0 29.5G  0 disk
├─mmcblk0p1 179:1    0  256M  0 part /boot
└─mmcblk0p2 179:2    0 29.3G  0 part /

pi@pi4:~ $ sudo mount -t ext4 /dev/sda3 /mnt/tmp/
mount: /mnt/tmp: wrong fs type, bad option, bad superblock on /dev/sda3, missing codepage or helper program, or other error.

pi@pi4:~ $ sudo fsck.ext4 /dev/sda3
e2fsck 1.44.5 (15-Dec-2018)
ext2fs_open2: Bad magic number in super-block
fsck.ext4: Superblock invalid, trying backup blocks...
fsck.ext4: Bad magic number in super-block while trying to open /dev/sda3

The superblock could not be read or does not describe a valid ext2/ext3/ext4
filesystem.  If the device is valid and it really contains an ext2/ext3/ext4
filesystem (and not swap or ufs or something else), then the superblock
is corrupt, and you might try running e2fsck with an alternate superblock:
    e2fsck -b 8193 <device>
 or
    e2fsck -b 32768 <device>

pi@pi4:~ $ sudo mke2fs -n /dev/sda3
mke2fs 1.44.5 (15-Dec-2018)
Creating filesystem with 1952301396 4k blocks and 244039680 inodes
Filesystem UUID: c98ad2b3-3e8a-426c-a0f7-b06ed0279fa3
Superblock backups stored on blocks:
        32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
        4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,
        102400000, 214990848, 512000000, 550731776, 644972544, 1934917632

pi@pi4:~ $ sudo mdadm --examine /dev/sda
/dev/sda:
   MBR Magic : aa55
Partition[0] :   4294967295 sectors at            1 (type ee)

I tried to use a superblock stored in the blocks showed in the previous mke2fs command output but without success (and I tried more superblocks then shown in the example).
sudo e2fsck -b 32768 /dev/sda3
e2fsck 1.44.5 (15-Dec-2018)
e2fsck: Bad magic number in super-block while trying to open /dev/sda3

The superblock could not be read or does not describe a valid ext2/ext3/ext4
filesystem.  If the device is valid and it really contains an ext2/ext3/ext4
filesystem (and not swap or ufs or something else), then the superblock
is corrupt, and you might try running e2fsck with an alternate superblock:
    e2fsck -b 8193 <device>
 or
    e2fsck -b 32768 <device>

pi@pi4:~ $ sudo dumpe2fs /dev/sda3 | grep -i superblock
dumpe2fs 1.44.5 (15-Dec-2018)
dumpe2fs: Bad magic number in super-block while trying to open /dev/sda3
Couldn't find valid filesystem superblock.

Maybe you can give me an Advice how to get the Data from the Disk.
Thanks in Advance!
Edit: Add more Information as requested
pi@pi4:~ $ sudo file -s /dev/sda3
/dev/sda3: data

pi@pi4:~ $ sudo fdisk -l /dev/sda
Disk /dev/sda: 7.3 TiB, 8001563222016 bytes, 15628053168 sectors
Disk model:
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 4096 bytes / 33553920 bytes
Disklabel type: gpt
Disk identifier: F6E21726-C437-47C8-BA95-FF84072B6C52

Device Start End Sectors Size Type
/dev/sda1 2048 4982527 4980480 2.4G Linux RAID
/dev/sda2 4982528 9176831 4194304 2G Linux RAID
/dev/sda3 9437184 15627848351 15618411168 7.3T Linux RAID


text:
Q: Why is a button firing the event of a previous element/tag? I'm not sure what's causing the form button to fire the event of turning the page theme back to white after the dark mode has been clicked and enabled.
Not sure if that may be confusing, but for example if you open the page it's automatically on the light mode theme, when you click "dark" to switch the theme to dark and then click the button "search" while the theme is in "dark", the page will switch back to "light". What am I doing wrong or missing out? Please advise. Also, how could I refractor this JS better and simpler?
Thanks!
HTML - left out the head part intentionally

devfinder

          LIGHT

          DARK

        <form autocomplete="off" class="form" id="search">
          <input
            type="text"
            id="search"
            placeholder="Search GitHub username…" />
          <button class="btn">Search</button>
        </form>

JS
const themeBtn = document.querySelectorAll(".theme-toggle-btn");

const toggle = function (e) {
  if (e.currentTarget.classList.contains("light-hidden")) {
    document.documentElement.setAttribute("color-mode", "light");
    localStorage.setItem("color-mode", "light");
    return;
  }
  document.documentElement.setAttribute("color-mode", "dark");
  localStorage.setItem("color-mode", "dark");
};

themeBtn.forEach((btn) => {
  btn.addEventListener("click", toggle);
});

CSS
:root {
  --monoFont: 'Space Mono', monospace;
  --accent-blue: #0079FF;
  --error-red: #F74646;
  --light-hover: #60ABFF;
}

:root[color-mode="light"] {
  --primary-text-color:#697C9A;
  --secondary-text-color: #4B6A9B;
  --accent-color: #2B3442;
  --background-color: #F6F8FF;
  --container-background: #FEFEFE;
  --font-color: #222731;
}

:root[color-mode="dark"] {
  --primary-text-color: #FFFFFF;
  --background-color: #141D2F;
  --container-background: #1E2A47;
}

*,
*::before,
*::after {
  box-sizing: border-box;
}

:root[color-mode="light"] .light-hidden,
:root[color-mode="dark"] .dark-hidden {
  display: none;
}

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  background-color: var(--background-color);
  height: 100vh;
  margin: 0;

  color: var(--primary-text-color);
  font-family: var(--monoFont);
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2em;
}

.header-container, .content-container {
  width: 100%;
  max-width: 730px;
}

/* header title */
.title {
  color: var(--font-color);
  font-size: 1.63rem;
}

/* theme toggle btn */
.theme-toggle-btn {
  background-color: var(--background-color);
  border: none;

  color: var(--primary-text-color);
  font-size: .7rem;
  font-weight: 700;
  letter-spacing: 1.5px;

  cursor: pointer;
}

.theme-toggle-btn img {
  margin: 0 0 -0.45em 0.75em;
  width: 20px;
  height: 20px;
}

/* search form */
.form {
  position: relative;
  display: flex;
  align-items: center;
  height: 69px;
}

.form input {
  background-color: var(--container-background);
  border: none;
  width: 100%;
  padding-left: 1.5em;
  margin-bottom: 2em;

  color: var(--font-color);
  font-size: 1.05rem;
  font-family: inherit;
  font-weight: 400;

  border-radius: 10px;
  box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 12px;;

}

.form input::placeholder {
  color: var(--secondary-text-color);
}

.btn {
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translateY(-80%);

  width: 100%;
  max-width: 106px;
  height: 50px;
  background-color: var(--accent-blue);
  border: none;

  color: #FFFFFF;
  font-size: 1rem;

  border-radius: 10px;
  cursor: pointer;
}

.btn:hover {
  background-color: var(--light-hover);
}

A: I think when you're clicking the "Search" button, it's refreshing the page and reloads the html template. Because you have "color-mode="light" within the html element, it will then load the page in light mode rather than dark mode.

A: I think the problem is: your not consuming the selection from localStorage. To persist the user selection, you should check the preference in localStorage when the page loads.


text:
Q: Prove inequality on quotient of $\Gamma$-functions $$\frac{\Gamma\left(\frac{n}{2}\right)}{\Gamma\left(\frac{n + 1}{2}\right)} > \frac
{\sqrt{2n + 1}}{n}, \space\space\forall{}n\in\Bbb{N}$$

A: By using $\Gamma(\frac{n}{2}+1) = \frac{n}{2}\Gamma(\frac{n}{2})$, the inequality is written as
$$\frac{\Gamma(\frac{n}{2}+1)}{\Gamma(\frac{n+1}{2})} > \sqrt{\frac{n}{2} + \frac{1}{4}}.$$
Recall Kershaw's improvement of Gautschi's inequality [1]: for $x > 0$ and $s \in (0, 1)$,
$$\left(x + \frac{s}{2}\right)^{1-s} < \frac{\Gamma(x+1)}{\Gamma(x+s)} <
\left(x - \frac{1}{2} + \sqrt{s + \frac{1}{4}}\right)^{1-s}.$$
By letting $x = \frac{n}{2}$ and $s = \frac{1}{2}$ in Kershaw's improvement of Gautschi's inequality, we have
$$\sqrt{\frac{n}{2}+\frac{1}{4}} < \frac{\Gamma(1 + \tfrac{n}{2})}{\Gamma(\tfrac{1}{2} + \tfrac{n}{2})} <
\sqrt{\frac{n}{2}+\frac{\sqrt{3}-1}{2}}.$$
We are done.
[1] D. Kershaw, "Some extensions of W. Gautschi's inequalities for the gamma function", Math. Comp. 41 (1983) 607–611.
https://en.wikipedia.org/wiki/Gautschi%27s_inequality

A: With $s = \frac{n}{2}$, by taking reciprocals and using $\Gamma (s + 1) = s\Gamma (s)$, the inequality is equivalent to
$$
\frac{1}{\sqrt {s + \frac{1}{4}} } > \frac{{\Gamma \left( {s + \frac{1}{2}} \right)}}{{\Gamma (s + 1)}}.
$$
We shall show that this holds for all positive $s$. Indeed, by using the Beta integral, the right-hand side is
\begin{align*}
&\frac{{\Gamma \left( {s + \frac{1}{2}} \right)}}{{\Gamma (s + 1)}} = \frac{1}{{\sqrt \pi  }}B\left( {s + \tfrac{1}{2},\tfrac{1}{2}} \right) \\ & = \frac{1}{{\sqrt \pi  }}\int_0^1 {t^{s - 1/2} (1 - t)^{ - 1/2} dt}  = \frac{1}{{\sqrt \pi  }}\int_0^{ + \infty } {e^{ - (s - 1/2)u} (1 - e^{ - u} )^{ - 1/2} e^{ - u} du} \\ & = \frac{1}{{\sqrt \pi  }}\int_0^{ + \infty } {e^{ - (s + 1/4)u} u^{ - 1/2} \left( {\frac{{e^{u/2}  - e^{ - u/2} }}{u}} \right)^{ - 1/2} du} \\ & = \frac{1}{{\sqrt \pi  }}\int_0^{ + \infty } {e^{ - (s + 1/4)u} u^{ - 1/2} \sqrt {\frac{u}{{\sinh u}}} du} \\ & < \frac{1}{{\sqrt \pi  }}\int_0^{ + \infty } {e^{ - (s + 1/4)u} u^{ - 1/2} du}  = \frac{1}{\sqrt {s + \frac{1}{4}} } .
\end{align*}


text:
Q: Adding List View Web part by Powershell and via GUI hasn't same View Following is a part of my Powershell Script which creates a Discussion Board List and tries to add it to a default.aspx page. the problem is when I add default view to the code (marked as *) it generate this exception:"Exception calling "AddWebPart" with "3" argument(s): "The specified view is invalid." If I delete this line of code it works but the discussion board has a different view which contains only the title of the objects. However when I go to edit page and choose to add the list as a web part it works and has the threaded or unthreaded view which is right.
  $listName = "RIR Diskussion Forum"

  $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DiscussionBoard

  $web.Lists.Add($listName, "Riksrevisonens diskussions forum", [int]$listTemplate)

  $webPartManager = $web.GetLimitedWebPartManager($pageUrl,  [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

$ListViewWebPart = New-Object Microsoft.SharePoint.WebPartPages.ListViewWebPart
$ListViewWebPart.Title = "Diskussion Forum"
$ListViewWebPart.ListName = ($list.ID).ToString("B").ToUpper()
$ListViewWebPart.ViewGuid = ($list.DefaultView.ID).ToString("B").ToUpper()  *
$ListViewWebPart.ZoneID = "Left"
$ListViewWebPart.ChromeType = "Default"

$ListViewWebPart.TitleUrl = $list.DefaultViewUrl
$ListViewWebPart.WebId = $list.ParentWeb.ID

$webPartManager.AddWebPart($ListViewWebPart, "Left", "0")

I need to add the List as a web part to the page by Powershell and make it to have same view as when you add it by GUI. thanks

A: Medes,
first of all, in your example when Discussion Board instance is created,
the line that gets instance of newly created Discussion Board is missing, so i believe you need to add it after line
$web.Lists.Add($listName, "Riksrevisonens diskussions forum", [int]$listTemplate)

like this one
$list = $web.Lists[$listName]

And the last one, when you add Discussion Board using GUI, it actually is instantiated using XsltListViewWebPart and not ListViewWebPart.
So if you change the line where web part is created with this one:
$ListViewWebPart = New-Object Microsoft.SharePoint.WebPartPages.XsltListViewWebPart

it would add Discussion Board on page as you expect it to.
Hope this helps,
Vadim


text:
Q: generate thumbnail when image uploaded django i have a website where multiple large size images uploaded everyday after they go live because of heavy size its taking time so i want to generate thumbnail version when image uploaded:
class Image(models.Model):
      license_type = (
    ('Royalty-Free','Royalty-Free'),
    ('Rights-Managed','Rights-Managed')
                         )
      image_number = models.CharField(default=random_image_number,max_length=12,unique=True)
      title = models.CharField(default=random_image_number,max_length = 100)
      image = models.ImageField(upload_to = 'image' , default = 'demo/demo.png')
      thumbnail = models.ImageField(upload_to='thumbs', editable=False)
      category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
      shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE, related_name='Image', null=True,blank=True)
      image_keyword = models.TextField(max_length=1000)
      credit = models.CharField(max_length=150, null=True)
      location = models.CharField(max_length=100, null=True)
      license_type = models.CharField(max_length=20,choices=license_type, default='')
      uploaded_at = models.TimeField(auto_now_add=True)

      def __str__(self):
          return self.title

      def save(self, *args, **kwargs):

          super(Image, self).save(*args, **kwargs)
          if not self.make_thumbnail():
             raise Exception('Could not create thumbnail - is the file type valid?')

      def make_thumbnail(self):
          fh = storage.open(self.Image.name)
          try:
             image = PILImage.open(fh)
          except:
             return False
          image.thumbnail((400,400),PILImage.ANTIALIAS)
          fh.close()
          thumb_name, thumb_extension = os.path.splitext(self.Image.name)
          thumb_extension = thumb_extension.lower()

          thumb_filename = thumb_name + '_thumb' + thumb_extension

          if thumb_extension in ['.jpg', '.jpeg']:
             FTYPE = 'JPEG'
          elif thumb_extension == '.gif':
               FTYPE = 'GIF'
          elif thumb_extension == '.png':
               FTYPE = 'PNG'
          else:
             return False    # Unrecognized file type

    # Save thumbnail to in-memory file as StringIO
         temp_thumb = StringIO()
         image.save(temp_thumb, FTYPE)
         temp_thumb.seek(0)

    # Load a ContentFile into the thumbnail field so it gets saved
         self.thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=True)
         temp_thumb.close()

         return True

admin.py:
@admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
      readonly_fields=['image_number','uploaded_at']
      fields = ['title','image_number','shoot','category',
         'image','image_keyword','credit','license_type','location','uploaded_at']

now this is the error:
string argument expected, got 'bytes'

backtrace:
File "/home/tboss/Desktop/environment/live/backend/venv/lib/python3.7/site-packages/PIL/JpegImagePlugin.py", line 779, in _save
ImageFile._save(im, fp, [("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize)
File "/home/tboss/Desktop/environment/live/backend/venv/lib/python3.7/site-packages/PIL/ImageFile.py", line 513, in _save
fp.write(d)
TypeError: string argument expected, got 'bytes'

when i user BytesIO:
i get this error:
maximum recursion depth exceeded in comparison

backtrace:
 File "/home/tboss/Desktop/environment/live/backend/venv/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 319, in __init__
  if isinstance(value, Fraction):
 File "/home/tboss/Desktop/environment/live/backend/venv/lib/python3.7/abc.py", line 139, in __instancecheck__
 return _abc_instancecheck(cls, instance)

RecursionError: maximum recursion depth exceeded in comparison
i am current uploading image from admin but also going to using drf. currently its not creating thumbnail.............................................................................................................

A: As said in the comment, you can work with base64 encoded image instead. In order to do this, first change the thumbnail field to the following:
thumbnail = models.CharField(max_length=2000, blank=True, null=True)

Then, override the model save method and add the following code:
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    if not self.image:
        self.thumbnail = None
    else:
        thumbnail_size = 50, 50
        data_img = BytesIO()
        tiny_img = Image.open(self.image)
        tiny_img.thumbnail(thumbnail_size)
        tiny_img.save(data_img, format="BMP")
        tiny_img.close()
        try:
            self.thumbnail = "data:image/jpg;base64,{}".format(
                base64.b64encode(data_img.getvalue()).decode("utf-8")
            )
        except UnicodeDecodeError:
            self.blurred_image = None

    super(Image, self).save(force_insert, force_update, using, update_fields)

You can change the thumbnail_size variable to match your needs.
Lastly, add the following to your import section:
import base64
from io import BytesIO

Don't forget to run makemigrations and migrate commands! Let me know if you have any problems.


text:
Q: what's wrong with this if/then stored proc? I'm fuzzy on when I need you use @ to reference vars in mySQL.  I'm coming from MS SQL where you always use it, but apparently that's not correct in mySQL.
So the below stored procedure is always executing the first IF block, even if the session value is expired - in that it's always executing the update statement.  Apparently the only debug tool I could find for mySQL stored procs runs on Windows and Linux.  I'm on a Mac.  Wamp wamp wamp.
So yeah.  Can anyone see what's wrong here?  Thanks!
DELIMITER $$

CREATE DEFINER=`xxx`@`localhost` PROCEDURE `validate_session`(uid INT, token VARCHAR(256))
BEGIN
    DECLARE sessId INT DEFAULT NULL;

    SELECT sessId = id FROM UserSessions
    WHERE userId = uid
    AND sessionToken = token
    AND expires > INTERVAL 2 MINUTE + NOW() ORDER BY expires DESC LIMIT 1;

IF sessId IS NOT NULL THEN
    UPDATE UserSessions
    SET expires = INTERVAL 2 HOUR + NOW()
    WHERE id = sessId;
ELSE
    DELETE FROM UserSessions
    WHERE userId = uid
    AND sessionToken = token;
    SET @sessId = 0;

END IF;

SELECT sessId;
END

For the record what it's supposed to do in pseudo code:
if we have a session for this user, with a matching token which has not expired {
    update the expiration time to 2 hours from now
    return the session id;
}
else {
    delete the (now stale) session
    return 0;
}

Thanks in advance.

A: You're not setting the value of sessId... you're making a comparisson in your query.
I think what you need is something like this:
CREATE DEFINER=`xxx`@`localhost` PROCEDURE `validate_session`(uid INT, token VARCHAR(256))
BEGIN
    DECLARE sessId INT DEFAULT NULL;

    SELECT id
        INTO sessId -- Here is the assignment
    FROM UserSessions
    WHERE userId = uid
      AND sessionToken = token
      AND expires > INTERVAL 2 MINUTE + NOW()
    ORDER BY expires DESC
    LIMIT 1;

    IF sessId IS NOT NULL THEN
        UPDATE UserSessions
            SET expires = INTERVAL 2 HOUR + NOW()
            WHERE id = sessId;
    ELSE
        DELETE FROM UserSessions
            WHERE userId = uid
            AND sessionToken = token;
        SET sessId = 0;
   END IF;

   SELECT sessId;
END

Reference:

*

*MySQL Reference: SELECT ... INTO syntax

*MySQL Reference: Local variable scope and resolution


text:
Q: Metasurface holography as a principle behind volumetric displays? Disclaimer: By no means am I a physicist of any kind so complete inability to grasp complex physical concepts without spending ridiculously unreasonable amounts of time on corresponding research is a given for me. I'm not attempting to understand some underlying principles in question, just would like an evaluation of certain claims found on web from a person competent enough in the respective field.
A while ago, a topic has been raised on some board, concerning this article. In short, it makes an implication of genuine volumetric displays (citation: "like the one R2D2 projected of Princess Leia in Star Wars: A New Hope") being now achievable due to the aforementioned means of metasurface holography. A link to the original article as well as to somewhat obscure video demonstration of what appears to be a functioning prototype was also included. Both look genuine to me. However, as I find the video completely failing at demonstrating if
the imagery produced by the device actually floats mid-air, coupled with the original article referencing some sort of a screen in one of the figures it features, the whole situation fuels a buildup of quite contradictive impressions within myself. This forced me to perform some googling.
Now, first of all I've decided to locate a better, more clear visual depiction of such devices operating and failed, though I've managed to discover that the beginning of active research on the subject dates at least as far back as a decade ago, so the apparent lack of video material of acceptable quality on the matter comes across as rather surprising. Moreover, similar articles I've encountered during my search focused so much on the theoretical basis that I was unable to definitively deduce any relevant properties of an imagery such a device would actually be able to generate. I was able to notice though that a number of articles apparently carried no dependency on any kind of screen while exploring the subject. This even further facilitated the growth of my confusion.
Furthermore, any attempts at logical evaluation of the concept in question would even more incline myself towards thinking that the most scifi-ish properties of the device (the ability to actually fabricate a fully 3D imagery viewable from "almost any angle" of such scale) exist solely within the journalists' fantasies. As per my understanding, the human ability to truly see something comes from photosensitive cells within an eye exciting the optic nerve attached to it which in turn relays the signals to the brain for further processing. In order for an eye to actually catch some light, this light must be directed at its focusing system. And that is exactly where it gets tricky for me: how anything would actually be hit by any light which is projected in almost an opposite direction under the condition of said light not encountering any surface or medium along its path which would be able to alter its initial trajectory (as what is evident to be exactly the case here)?
Ultimately, any statement on truthfulness of the claims of the technology in question being able to facilitate generation of actual 3D imagery mid-air would be most welcomed. Additional gratitude guaranteed for a dumbed-down explanation of how the hell it is actually (if at all, with this particular approach, of course) possible.
P.S: I'm tagging nanoscience since the whole point of a metasurface here, as per my understanding, is to have orifices of sub-wavelength (regarding the visible electromagnetic spectrum) dimensions.

A: Your intuition is correct: a metasurface hologram cannot produce an image that is visible under any circumstances in which the line of sight does not intersect a surface that's part of the projection system.
In order to form a *Princess Leia" projection, something needs to make light change direction in mid-air, or else light needs to be emitted from points in mid-air.  There actually are some prototype displays that can do it.  One uses sound waves to move a tiny pith ball in a 3D pattern while the pith ball is illuminated with an intensity-modulated beam.  Another uses a focused high-energy pulsed laser to cause a spark in the air, and the focal spot is rapidly scanned.


text:
Q: How to manually set IP to Request Object in Laravel for testing I need to set IP address on laravel requests for testing.
I don't want to mock Request.
Please, help.
This is how I'm getting IP in a controller
$request = app(\Illuminate\Http\Request);
$ip      = $request->ip();

A: $request->server->add(['REMOTE_ADDR' => '0.0.0.0']);

A: When inside a phpunit test class, I was able to override the users IP for testing laravel like so:
public function testPathWithInternalIp() {
    $this->serverVariables = ['REMOTE_ADDR' => '192.168.1.1'];

    $response = $this->get('/some-path');
}

'/some-path' will get accessed as if it was a user on 192.168.1.1, so if you have behaviour that is different you can then assert that condition on the $response.


text:
Q: How do i make 2 divs in eachother How do i make a div like this?
https://i.gyazo.com/cc34cdba5d8ef4969212c45935caf165.png
Its 1 div, the image (car) and the background thats black with text on it. And when you hover, the red fade goes away.
This is a complete gyazo of what I´m trying to do.
https://i.gyazo.com/51d360e8f4a6408dbed789f0d702dbc7.png
Here´s the picture of the car: You need atleast 10 rep to post more than 3 links, the link should be in the comments!
What i tried:
Making 1 div named black, taking it like this:

Styled the black div to get bigger than the car itself so it got a black background, but it never worked.

A: Here you go: https://jsfiddle.net/s2moc0gt/1/
Basically just some CSS:
.img-container {
  width: 200px;
  height: 200px;
  background-image: url("https://rocket-league.com/content/media/items/avatar/220px/75e8bb7e5d1473412157.png");
  background-repeat: no-repeat;
  background-position: center;
}

.red-overlay {
  width: 100%;
  height: 100%;
  background: linear-gradient(transparent, red);
}

.red-overlay:hover {
  opacity: 0;
}


text:
Q: Android: Unable to login to a web session and parse XML data using DOM on the same login session Android Development: I'm needing to log into a web session using POST, then make another request of which I parse XML to get Lat/Long, then submit this to a google maps overlay.
My issue is I'm able to log into my system, but when I submit a command to parse XML, it is acting like a completely new session and I basically get an 'incorrect login' reply from the server.
Does anyone have some simple steps to perform this...and to keep a session open for as many commands as I need?  I'm not actually SURE I'm using a session cookie, but believe this is the case.
Some example code may be:

try {
URI loginUri = new URI("http://www.mywebsite.com/ExternalLogin.jsp?user=lee&pwd=bluedog");
URI xmlUri = new URI("http://www.mywebsite.com/getXMLInfo.xml");

// Prepares the request.
HttpClient httpClient = new DefaultHttpClient();
HttpGet loginHttpGet = new HttpGet();
loginHttpGet.setURI(loginUri);

HttpGet xmlHttpGet = new HttpGet();
xmlHttpGet.setURI(xmlUri);

// Sends the request and read the response
HttpResponse loginResponse = httpClient.execute(loginHttpGet);
InputStream loginInputStream = loginResponse.getEntity().getContent();

HttpResponse xmlResponse = httpClient.execute(xmlHttpGet);
InputStream xmlInputStream = xmlResponse.getEntity().getContent();

DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(xmlInputStream.toString()));

doc.getDocumentElement();
// Continue using DOM to parse my XML data
}

A: You don't indicate your how our "web session" is being maintained. I am going to guess it is via a session cookie. If so, use HttpClient and keep using the same HttpClient object for both requests. The session cookies will be handled automatically.


text:
Q: tuples (arrays) as attributes in mongoose.js MongoDB, and mongoose.js specifically, allows tuples as attributes.  For instance, the MongoDB documentation has this example where the attribute comments is itself an array of objects with the attributes [{body: String, date: Date}]. Yay!
var blogSchema = new Schema({
  title:  String,
  author: String,
  body:   String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs:  Number
  }
})

Now when i persist that to MongoDB, not only does each instance of blogSchema get its own value for _id (e.g. 502efea0db22660000000002) but each individual value of comment gets its own _id field.
For the most part I don't care, but in my app the analog to comments may have thousands of values.  Each of which gets its own huge value of _id.
Can I prevent that?  I'll never need to refer to them individually. Or should I learn to stop worrying and love the unique identifier?  I grew up programming the Vic20 and TRS80 as a kid, so may be overly paranoid about wasting memory/storage.

A: The _id can be disabled by setting the noId schema option to true. To pass the option you need to pass an instance of schema instead of using the object literal:
// instead of this...
comments: [{ body: String, date: Date }]

// do this...
var commentSchema = new Schema({ body: String, date: Date }, { noId: true });
var blogSchema = new Schema({
  ..
  comments: [commentSchema]
})


text:
Q: Flask - SQLAlchemy italicizing text imported from db I have a application that I am pulling data from fields in MySQL database.  In some of these fields a some of the text needs to be italicized. For example, in species.html I have a table data "species.Notes" that I am pulling out from the MySQL database.  That will render something like this on the page when the application is rendered:
Example:
Tall three tip sagebrush is associated with gray horsebrush (Tetradymia canescens).
The text in parenthesis (i.e. species name) need to be italicized, and the rest needs to remain normal text.  I have tried storing the information in the MySQL database with html tags around Tetradymia canescens

</htm>

but that did not work, and I have not been able to find other suggestions online.
For reference (if needed?), here is how the information is being pulled into the html page where it will be displayed.
species.html

    Additional Species Information
    {{ species.Notes }}

A: You can use Jinja filters to introduce the italics tag like this:

    {{ species.Notes|replace('(', '(')|replace(')', ')')|safe }}

Ideally you'd preprocess the text with a regex expression and pass it to the template with the tags already there, then you would just need the safe filter alone.


text:
Q: Is there an XEmbed equivalent in Windows? XEmbed is used to embed an X11 window in an other application. This is done by reparenting the target window.
Is there a windows equivalent to be able to embed an external window into an other one? In my case, I have control on both applications/windows so cooperation is possible.

A: OLE Compound Documents provides the ability for one application to implement part of another applications document (eg. embed a spreadsheet inside a word processor).
But COM etc. is a big learning curve.


text:
Q: when I run the program for the second time it doesn't give me correct execution time I have a C code, When I try to calculate the time of small pieces of processing code  for the first execution. It gives me 30 ms, when I turn of the exe file and run it again it gives me 1 ms, and this time is the time for calculation and each time I run the program the calculation values is different from the previous one, if I turn off the PC and turn it, it gives me 30 ms for the first execution and 1 ms for all other executions
How can I get the same time , I free all the used memory and I run another program to overwrite the memory but the problem is not solved until I reboot the PC
any help
start_time=clock();
Encryption();
end_time=clock();
cpu_time_used_totlal_enc +=(double) (end_time-start_time) / CLOCKS_PER_SEC;

A: This problem is called "warmup": When you want to do performance test some code, you need to run the code several times (say, 10 times). Then you run it 100'000 times and measure how long it takes and divide that by 100'000 to get the average. A single measurement of the runtime is useless, unless the runtime is at least one minute.
The reason for warmup problems is that modern OSs and languages do all kind of tricks to make your code execute faster. For example, the call to Encryption() might actually invoke a function in a shared library.
Those libraries are loaded lazily, i.e. it's loaded the first time when your code actually calls the function. When it is loaded, the OS keeps it in a cache since chances are someone will need it again.
That's why the first few runs of an application have a completely different runtime than the next 10'000 runs.


text:
Q: How to send an email when connection to teradata fails? I'm using the standard way of connecting to Teradata from SAS like below:
connect to teradata (user="youruserid" password="yourpassword" server="servername" mode=teradata);

I have multiple such codes which are scheduled one after the other. What I realized is that if Teradata server is down sometime then few codes fail. I want to do is to get an email each time such connection failure happens in SAS.


text:
Q: Trying to understand how to read ∃! I have to find the negation of ∃!x∈U[p(x)]
I believe I need to rewrite the equation in a format not using ∃! so that I can find its negation. There is what I have come up with, but I am not sure if it is correct.
∃x∈U[P(x) ∧ ∀(y) -> (y = x)]
Am I on the right track with this?
Thanks,
Tony

A: You have the right idea, but the expression that you've written doesn't actually make sense: $\forall y$ is not an expression that can imply anything. What you're trying to say, I take it, is that there is an $x$ with the property $P$ and which is such that any $y$ with the property $P$ must be this same $x$; that's
$$\exists x\in U\Big(P(x)\land\forall y\in U\big(P(y)\to y=x\big)\Big)\;.$$
(There are other, equivalent expressions as well, but that seems closest to the idea that you had in mind.)


text:
Q: Checking whether the number is composite Prove that $5^{125}-1$/ ($5^{25} - 1$) is composite
I have written $5^{125}-1$ as $(5^{25}-1)(5^{100}+5^{75}+5^{50}+5^{25}+1)$ but what should I do after this?
Sorry about earlier mistake in question ,

A: Let $x = 5^{25}$.
$\begin{align}
5^{125}-1 &= x^5-1\\
&=(x^4 +x^3 +x^2 + x + 1)(x-1) \\
&= (x^4 + 9x^2 + 1 + 6x^3 + 6x + 2x^2 - 5x^3 - 10x^2 - 5x)(x - 1)\\
&= ((x^2 + 3x + 1)^2 - 5x(x + 1)^2)(x - 1)
\end{align}$
Put $x = 5^{25}$, just in the expression $5x$, you will get
$5^{125}-1=((x^2 + 3x + 1)^2 - (5^{13}(x + 1))^2)(x - 1)$
it is now of the form $(a^2-b^2)(x-1)$ where $a,b$ are integers and hence $(x^5-1)/(x-1)$ is a composite number.


text:
Q: Matrix multiplication as combination of rotation and stretching I'm starting to look at some lectures on the SVD. The lectures start out by saying that in $$\mathbf{y}=A\mathbf{x}$$ the transformation representing $A$ is only doing rotation and stretching.

*

*The matrix for rotation is $$ \begin{bmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{bmatrix}$$

*The matrix for stretching is $$ \begin{bmatrix}\alpha&0\\0&\alpha\end{bmatrix}$$

In the past I've learnt that transformations can be rotations, reflections, scaling, shears, and flattenings. However the idea that any transformation can be decomposed into a rotation and a stretch is new to me. Is there a clear and/or intuitive way of explaining this?

A: One major theme in the study of matrix algebra is that of matrix decompositions. The idea is to take a matrix $A$ (either arbitrary or satisfying some reasonable conditions) and decompose it as the product of two or three matrices of a simpler form. For example, the so-called QR decomposition writes an arbitrary matrix $A$ as
$$A = QR$$
Where $Q$ is orthogonal (a composition of rotations + reflections) and $R$ is upper-triangular. In two-dimensions, $Q$ is either rotation or reflection.
In the subject of SVD, an important matrix decomposition is the aptly-named singular value decomposition. This writes an arbitrary matrix $A$ in the form
$$A = UDV^{H}$$
where $D$ is a nonnegative, diagonal matrix whose entries are called the singular values, $U$ and $V$ are orthogonal (unitary in the complex case), and $V^{H}$ is the transpose of $V$ (or conjugate-transpose if complex entries are allowed). A diagonal matrix can be thought of as stretching a basis by the corresponding singular values, and an orthogonal matrix is a rotation or reflection. Thus, this decomposition sees $A$ as a composition of a sort of rotation (transposed), a stretching, and finally another rotation.
You can read more about the singular value decomposition here.


text:
Q: How to write groovy script in jenkins pipeline for Powershell command I want to run parallel jobs in jenkins using the pipeline groovy scripts for Powershell command.
I have tried putting the powershell command inside Bat and and powershell inside groovy script but its failing.
Copy to Dev CM Server
NET USE \\10.207.24.148\IPC$ /u:nextgen-dev-cm01\Administrator Complete!123
robocopy  d:\nextGenBuild\Dev \\10.207.24.148\d$\wwwroot\cm01.dev.amgen-test.com\ /e
NET USE \\10.206.24.147\IPC$ /D

Copy to Dev CD Server
NET USE \\10.207.24.178\IPC$ /u:nextgen-dev-cd01\Administrator Complete!123
robocopy  d:\nextGenBuild\Dev \\10.207.24.178\d$\wwwroot\cd01.dev.amgen-test.com\ /e
NET USE \\10.207.24.178\IPC$ /D

I want two scrips for CM server and CD server  to be run parallely.


text:
Q: XPath select innertext I have this HTML/XML:
\t\t\t\t\t    \r\n\t\t

    blabla

this is the text I want

  code: 123

\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t

In C#4 I use the HtmlAgilityPack lib to select the Node with XPath and get the InnerText property. This will get all the text inside the node. How can I get only the text "this is the text I want"?
/text() only returns \t\t\t\t\t    \r\n\t\t

A: /div/text()

From the example given, this XPath will get you all text nodes underneath the div element, in this case test2.
If you could elaborate more on the question we might better be able to help you. The Div contains 3 children: a span element, a text node and a b element. The span and b each have a text node child. Using XPath you could select elements only (/div/*), text nodes only (/div/text()) or all node types (/div/node()).
EDIT: /text() will only return you root level text nodes. In this case I would expect it to return a node list containing 3 text nodes:
\t\t\t\t\t    \r\n\t\t
this is the text I want
\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t

Are you perhaps only selecting the first node in the resultant node list?
There are a few issues of well-formedness such as your
 should probably be
.

A:
How can I get only the text "this is
  the text I want"?

text()[preceding-sibling::node()[1][self::br]]
      [following-sibling::node()[1][self::br]]

Meaning: the text node between two br elements.

A: @peter: You should not edit your question so that people don't see how the accepted answer relates to the question!!!
The answer to your new question:
/br[1]/following-sibling::text()[1]

selects the wanted text node (the quotes are mine):
"
this is the text I want
"