text:
Q: Gnuplot: How to plot bash array without dumping it to a file I am trying to plot a bash array using gnuplot without dumping the array to a temporary file.
Let's say:
myarray=$(seq 1 5)

I tried the following:

myarray=$(seq 1 5)
gnuplot -p  <<< "plot $myarray"

I got the following error:
         line 0: warning: Cannot find or open file "1"
         line 0: No data in plot

gnuplot> 2
         ^
         line 0: invalid command

gnuplot> 3
         ^
         line 0: invalid command

gnuplot> 4
         ^
         line 0: invalid command

gnuplot> 5''
         ^
         line 0: invalid command

Why it doesn't interpret the array as a data block?
Any help is appreciated.

A:
bash array
myarray=$(seq 1 5)

The myarray is not a bash array, it is a normal variable.
The easiest is to put the data to stdin and plot <cat.
seq 5 | gnuplot -p -e 'plot "<cat" w l'

Or with your variable and with using a here-string:
<<<"$myarray" gnuplot -p -e 'plot "<cat" w l'

Or with your variable with redirection with echo or printf:
printf "%s\n" "$myarray" | gnuplot -p -e 'plot "<cat" w l'

And if you want to plot an actual array, just print it on separate lines and then pipe to gnuplot
array=($(seq 5))
printf "%s\n" "${array[@]}" | gnuplot -p -e 'plot "<cat" w l'

A: Plot STDIN
gnuplot -p -e 'plot "/dev/stdin"'

Sample:
( seq 5 10; seq 7 12 ) | gnuplot -p -e 'plot "/dev/stdin"'

or
gnuplot -p -e 'plot "/dev/stdin" with steps'  < <( seq 5 10; seq 7 12 )

More tunned plot
gnuplot -p -e "set terminal wxt 0 enhanced;set grid;
    set label \"Test demo with random values\" at 0.5,0 center;
    set yrange [ \"-1\" : \"80\" ] ; set timefmt \"%s\";
    plot \"/dev/stdin\" using 1:2 title \"RND%30+40\" with impulse;"  < <(

          paste <(
                seq 2300 2400
          ) <(
                for ((i=101;i--;)){ echo $[RANDOM%30+40];}
          )
)

Please note that this is still one line, you could Copy'n paste into any terminal console.


text:
Q: jQuery webcam. Add taken photo to upload form field Hello I'm using jQuery AS3 webcam plugin for my project. But can figure out how to get the taken photo and add it to upload form field (if its possible). When I click the capture button it shows the picture in the capture window, but how actually to save it?
           $("#webcam").webcam({
                swffile: "js/sAS3Cam.swf?v=20120613",

                previewWidth: 400,
                previewHeight: 300,

                resolutionWidth: 400,
                resolutionHeight: 300,

                noCameraFound: function () {
                    this.debug('error', 'Kamera negalima');
                },

                swfApiFail: function(e) {
                    this.debug('error', 'Įskiepio klaida');
                },

                cameraDisabled: function () {
                    this.debug('error', 'Prašom suteikti leidimą prisijungti kamrai prie puslapio');
                },

                debug: function(type, string) {
                    if (type == 'error') {
                        alert(string);
                    }
                },

                cameraEnabled:  function () {
                    this.debug('notice', 'Camera enabled');
                    var cameraApi = this;
                    if (cameraApi.isCameraEnabled) {
                        return;
                    } else {
                        cameraApi.isCameraEnabled = true;
                    }

                    setTimeout(function() {
                        $(".capture").slideDown('fast');
                    }, 750);

                    $('.capture_btn').click(function() {
                        $(".capture").slideUp('fast');
                        $(".save_img").slideDown('fast');
                        var result = cameraApi.save();
                        if (result && result.length) {
                            var actualShotResolution = cameraApi.getResolution();
                          $('.reload_camera').click(function() {
                             cameraApi.isCameraEnabled = true;
                          });
                } else {
                    cameraApi.debug('error', 'Bloga kamera');
                }
            });
        }
    });
      <form action="processupload.php" style="display: none" method="post" enctype="multipart/form-data" id="UploadForm">

                    <input name="ImageFile" id="file" type="file" />

                    <input type="submit"  id="SubmitButton" value="Upload" />

        </form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove duplicates from array of dictionaries, Swift 3 Problem
I have an array of dictionaries as follows:
var arrayOfDicts = [
    ["Id":"01", "Name":"Alice", "Age":"15"]
    ["Id":"02", "Name":"Bob", "Age":"53"]
    ["Id":"03", "Name":"Cathy", "Age":"12"]
    ["Id":"04", "Name":"Bob", "Age":"83"]
    ["Id":"05", "Name":"Denise", "Age":"88"]
    ["Id":"06", "Name":"Alice", "Age":"44"]
]

I need to remove all dictionaries where there is a duplicate name. For instance, I need an output of:
var arrayOfDicts = [
    ["Id":"01", "Name":"Alice", "Age":"15"]
    ["Id":"02", "Name":"Bob", "Age":"53"]
    ["Id":"03", "Name":"Cathy", "Age":"12"]
    ["Id":"05", "Name":"Denise", "Age":"88"]
]

Order does not need to be preserved.
Attempted Solution
for i in 0..<arrayOfDicts.count
{
    let name1:String = arrayOfDicts[i]["Name"]

    for j in 0..<arrayOfDicts.count
    {
        let name2:String = arrayOfDicts[j]["Name"]

        if (i != j) && (name1 == name2)
        {
            arrayOfDicts.remove(j)
        }
    }
}

This crashes though, I believe since I am modifying the size of arrayOfDicts, so eventually it j is larger than the size of the array.
If someone could help me out, that would be much appreciated.

A: I definitely recommend having a new copy rather than modifying the initial array. I also create storage for names already used, so you should only need to loop once.
func noDuplicates(_ arrayOfDicts: [[String: String]]) -> [[String: String]] {
    var noDuplicates = [[String: String]]()
    var usedNames = [String]()
    for dict in arrayOfDicts {
        if let name = dict["name"], !usedNames.contains(name) {
            noDuplicates.append(dict)
            usedNames.append(name)
        }
    }
    return noDuplicates
}

A: You can use a set to control which dictionaries to add to the resulting array. The approach it is very similar to the one used in these answer and this
let array: [[String : Any]] = [["Id":"01", "Name":"Alice", "Age":"15"],
                                ["Id":"02", "Name":"Bob", "Age":"53"],
                                ["Id":"03", "Name":"Cathy", "Age":"12"],
                                ["Id":"04", "Name":"Bob", "Age":"83"],
                                ["Id":"05", "Name":"Denise", "Age":"88"],
                                ["Id":"06", "Name":"Alice", "Age":"44"]]

var set = Set<String>()
let arraySet: [[String: Any]] = array.compactMap {
    guard let name = $0["Name"] as? String else { return nil }
    return set.insert(name).inserted ? $0 : nil
}

arraySet   // [["Name": "Alice", "Age": "15", "Id": "01"], ["Name": "Bob", "Age": "53", "Id": "02"], ["Name": "Cathy", "Age": "12", "Id": "03"], ["Name": "Denise", "Age": "88", "Id": "05"]]

A: Please check this answer:
var arrayOfDicts = [
    ["Id":"01", "Name":"Alice", "Age":"15"],
    ["Id":"02", "Name":"Bob", "Age":"53"],
    ["Id":"03", "Name":"Cathy", "Age":"12"],
    ["Id":"04", "Name":"Bob", "Age":"83"],
    ["Id":"05", "Name":"Denise", "Age":"88"],
    ["Id":"06", "Name":"Alice", "Age":"44"]
]

var answerArray = [[String:String]]()

for i in 0..<arrayOfDicts.count
{
    let name1 = arrayOfDicts[i]["Name"]
    if(i == 0){
        answerArray.append(arrayOfDicts[i])
    }else{
        var doesExist = false
        for j in 0..<answerArray.count
        {
            let name2:String = answerArray[j]["Name"]!
            if name1 == name2 {
                doesExist = true
            }
        }
        if(!doesExist){
            answerArray.append(arrayOfDicts[i])
        }
    }
}

A: Several good answers already, but it was a fun exercise, so here's my solution.  I'm assuming you don't care which of the duplicate entries are kept (this will keep the last one of the dupes).
func noDuplicates(arrayOfDicts: [[String:String]]) -> [[String:String]]
{
    var noDuplicates: [String:[String:String]] = [:]
    for dict in arrayOfDicts
    {
        if let name = dict["name"]
        {
            noDuplicates[name] = dict
        }
    }

    // Returns just the values of the dictionary
    return Array(noDuplicates.values.map{ $0 })
}

A: let uniqueArray = Array(Set(yourArrayWithDuplicates))

That should do the trick.
If you want to use just the name for uniqueness then create these as structs.
You shouldn't be doing anything with dictionaries. Much easier to work with data that makes sense.

A: Try this:
var uniqueNames = [String: [String:String] ]()

for air in arrayOfDicts {
    if (uniqueNames[arr["Name"]!] == nil) {
        uniqueNames[arr["Name"]!] = arr
    }
}

result = Array(uniqueNames.values)

A: If you don't mind using an additional list:
var uniqueArray = [[String: String]]()
for item in arrayOfDicts {
    let exists =  uniqueArray.contains{ element in
        return element["Name"]! == item["Name"]!
    }
    if !exists {
      uniqueArray.append(item)
    }
}


text:
Q: Find minimum perimeter of the triangle circumscribing semicircle The following diagram shows triangle circumscribing a semi circle of unit radius. Find minimum perimeter of triangle
My try:
Letting $$AP=AQ=x$$
By power of a point we have:
$$BP^2=OB^2-1$$ where $O$ is center of the circle.
Also $$CQ^2=OC^2-1$$
Let $$OB=y$$
$$OC=z$$
Then $$BP=\sqrt{y^2-1}$$
$$CQ=\sqrt{z^2-1}$$
So the perimeter of triangle is:
$$P=2x+y+z+\sqrt{y^2-1}+\sqrt{z^2-1}$$
Any help from here?

A:
Let us calculate the perimeter from the figure.
$OB = \dfrac{1}{\sin\alpha}, PB=\dfrac{1}{\tan\alpha},AP= \dfrac{1}{\tan(\pi/2 -\dfrac{\alpha+\theta}{2})},AQ= \dfrac{1}{\tan(\pi/2 -\dfrac{\alpha+\theta}{2})},QC=\dfrac{1}{\tan\theta}, OC =\dfrac{1}{\sin\theta}  $
So total perimeter is $ p = \dfrac{1}{\sin\alpha}+\dfrac{1}{\tan\alpha}+2\dfrac{1}{\tan(\pi/2 -\dfrac{\alpha+\theta}{2})}+\dfrac{1}{\tan\theta}+\dfrac{1}{\sin\theta}$
differentiating p wrt alpha and theta and setting them to zero we get.
$-{\csc}^2\alpha +\sec^2\dfrac{\alpha+\theta}{2}- \csc\alpha\cot\alpha = 0$
$-{\csc}^2\theta +\sec^2\dfrac{\alpha+\theta}{2}- \csc\theta\cot\theta = 0$
from above we get
${\csc}^2\alpha + \csc\alpha\cot\alpha ={\csc}^2\theta + \csc\theta\cot\theta$
After squaring both side and simplification/cancelling terms, we get
${(\cos\alpha - \cos\theta)}^2=0$ that gives $\alpha= \theta$,   using this back to
$-{\csc}^2\alpha +\sec^2\dfrac{\alpha+\theta}{2}- \csc\alpha\cot\alpha = 0$
 we get
$\tan^2\alpha = 1 + \cos\alpha$  from which we get
$\cos^3\alpha+2\cos^2\alpha-1=0$ or $\cos^3\alpha+\cos^2\alpha+\cos^2\alpha+\cos^1\alpha-\cos^1\alpha-1=0$
or $(\cos\alpha+1)(\cos^2\alpha+\cos^1\alpha-1) = 0$
the only possible solution from above is $\cos\alpha = \dfrac{(\sqrt 5 -1)}{2}$ or $\alpha=\theta = 51.827$ (approx)

A: The problem with that is that there are only really two degrees of freedom; the variables $x,y,z$ are related in some way. We could try to find what that relation is - or we could find another way to express things, one with easier relations to spot.
I'd go with the angles of the triangle. Labeling $O$ as you did, $OP$ is perpendicular to $AB$ and $OQ$ is perpendicular to $AC$. Therefore, from right triangle $OBP$, $OB=\csc B$ and $BP=\cot B$. Similarly, $OC=\csc C$ and $CQ=\cot C$. At vertex $A$, note that triangles $AOP$ and $AOQ$ are congruent - so $AO$ bisects angle $A$, and $AP=AQ=\cot\frac{A}{2}$.
We now seek to minimize the perimeter $p$ subject to the constraints $A+B+C=\pi$ and $A,B,C > 0$. There's one more thing to note: $\csc \theta + \cot \theta = \cot\frac{\theta}{2}$. Applying this identity,
$$p(A,B,C) = \csc B+\cot B +\csc C+\cot C+2\cot\frac A2 = 2\cot \frac A2+ \cot \frac B2+\cot \frac C2$$
Now, we solve this constrained optimization problem. First, the boundary constraints $A,B,C\ge 0$. Since each of the half-angles $\frac A2, \frac B2, \frac C2$ is in $(0,\pi)$, all of those cotangents are positive. As any of these angles goes to zero, its cotangent goes to $\infty$ and so too does the perimeter. No minimum there.
In the interior triangular region, we apply Lagrange multipliers. Differentiating,
$$\nabla p(A,B,C) = -\frac12\left(2\csc^2\frac A2, \csc^2 \frac B2, \csc^2 \frac C2\right)$$
must be a constant multiple of $(1,1,1)$, the gradient of the constraint. Since $\csc^2$ decreases monotonically on $(0,\frac{\pi}{2})$, we must have $B=C < A$. If the angles summed to $2\pi$, we would have a nice solution $\frac A2=\frac{\pi}{2}, \frac B2=\frac C2 = \frac{\pi}{4}$ - but no, we're not that lucky. Instead, we apply $\frac A2 = \frac{\pi}{2}-B$ to eliminate $A$:
$$1-\cos B=2\sin^2 \frac B2 = \sin^2 \frac A2 = \cos^2 B$$
so $\cos^2 B + \cos B - 1 = 0$ and $\sin \frac A2 = \cos B = \dfrac{\sqrt{5}-1}{2}$. Then
\begin{align*}\cos\frac A2 &= \sqrt{1-\left(\frac{\sqrt{5}-1}{2}\right)^2} = \sqrt{\frac{\sqrt{5}-1}{2}}\\
\sin\frac B2 &= \sqrt{\frac{3-\sqrt{5}}{4}} = \frac1{\sqrt{2}}\cdot \frac{\sqrt{5}-1}{2}\\
\cos\frac B2 &= \sqrt{\frac{1+\sqrt{5}}{4}} = \frac1{\sqrt{2}}\cdot\sqrt{\frac{\sqrt{5}+1}{2}}\\
\cot\frac A2 &= \sqrt{\frac{2}{\sqrt{5}-1}} = \sqrt{\frac{\sqrt{5}+1}{2}}\\
\cot\frac B2 &= \sqrt{\frac{\sqrt{5}+1}{3-\sqrt{5}}} = \sqrt{\sqrt{5}+2}\\
p &= 2\cot\frac A2 + 2\cot\frac B2 = 2\sqrt{\frac{\sqrt{5}+1}{2}}+2\sqrt{\sqrt{5}+2}\approx 6.66\end{align*}
A truly fiendish problem.
Numerically, the minimizing angles are about $76^\circ$ at $A$ and $52^\circ$ at $B$ and $C$.


text:
Q: How Find the diophantine equation $x_{1}x_{2}x_{3}\cdots x_{n}=x_{1}+x_{2}+\cdots +x_{n}$
let $x_{1},x_{2},\cdots,x_{n}$ such
  $$n\ge 3,x_{1}\le x_{2}\le\cdots x_{n}$$
  $$x_{1}x_{2}x_{3}\cdots x_{n}=x_{1}+x_{2}+\cdots +x_{n}$$
let the number of ordered pairs of postive integers $(x_{1},x_{2},\cdots,x_{n})$ is $f(n)$

we can find the $f(n)$  closed form?  I guess we have  $$f(n)\le n?$$
it is clear
$$1+2+3=1\cdot 2\cdot 3$$

A: So far, there are only very large bounds known, i.e., $f(n)\le n^n$. This follows
easily from the fact that for a solution $(x_1,\ldots ,x_n)$ the largest
component can be at most $n$. However, there is an algorithm how o find all solutions to the equal-sum-product Diophantine equation, see
here. The algorithm should give a better bound, though still large, probably. For another discussion of the bound, see here.

A: Observing that, calling $\sigma_i(x_1,\dots,x_n)$ the $i$-th symmetric polynomial then $x_1+\dots+x_n=\sigma_1(x_1,\dots,x_n)$and $x_1x_2\cdots x_n=\sigma_n(x_1,\dots,x_n)$; then looking at the symmetric polynomials properties maybe you can get some informations on what you want.


text:
Q: Array.map() and Array.forEach() return original array app.post('/test', (req, res) => {
    let grid = req.body.dayGrid

    grid.map(week => {
        week.map(day => {
            return day+'!'
        })
    })

    res.json(grid)
})

Why does this code return the original array without the appended '!'?
The same happens with Array.forEach()

A: Because map is not replacing original object, it's returning the new one.
app.post('/test', (req, res) => {
    let grid = req.body.dayGrid

    grid = grid.map(week => week.map(day => day+'!'))

    res.json(grid)
})

A: You're returning the original grid array from the request body.
 Try this
app.post('/test', (req, res) => {
    let grid = req.body.dayGrid

     const result = grid.map(week => {
        return week.map(day => {
            return day+'!'
        })
    })

    res.json(result)
})


text:
Q: If the limit of a function when x goes to infinity is infinity, does that mean the integral from 1 to infinity is also infinity? If the limit of a function when x goes to infinity is infinity, does that mean the integral from 1 to infinity is also infinity?
Can we use the above to show that an unsolvable integral is infinity?
edit: Can we also say that if the limit of a function when x goes to infinity is a number then the integral is not infinity?

A: The answer to your edit question "Can we also say that if the limit of a function when x goes to infinity is a number then the integral is not infinity?" is No.
As an example, take the constant function $f(x)=1$. The its limit when x goes to infinity is 1, but its integral from 1 to infinity is infinity.

A: The integral
$$\int_{1}^\infty f(x)dx$$
is defined as
$$\lim_{b\to\infty} \int_1^b f(x)dx$$
so it should be simple for you to show that if there exist $x_0\geq 1$ and $M>0$ such that $f(x)>M$ for all $x>x_0$ (this is of course true of $\lim_{x\to\infty} f(x)=\infty$), then $$\int_{1}^\infty f(x)dx = \infty.$$

A: If $f(x)\to\infty$ as $x\to\infty$, then we have that $f(x)\ge M$ for some $M>0$ when $x>x_0$. Hence, we have that
$$
\int_1^\infty f(x)\mathrm dx
=\int_1^{x_0}f(x)\mathrm dx+\int_{x_0}^\infty f(x)\mathrm dx
\ge\int_1^{x_0}f(x)\mathrm dx+M\int_{x_0}^\infty \mathrm dx=\infty.
$$


text:
Q: How to use term_group for ordering subcategories in Wordpress? I'm looking to customize the order for subcategories listed in a navigation bar in Wordpress.  The codex makes it clear that there are five ways to do this: http://codex.wordpress.org/Template_Tags/wp_list_categories#Parameters. I am limited to two: 1) prefixing each category with a number and 2) using term_group.  The problem is that the Codex seems to be pretty vague as to how to make use of term_group as it only describes it as a group of terms. I know that a category containing the word, "video," always needs to be placed first, a category containing the word, "roster," always must come second, etc. Is there a way to achieve this without prefixing the slug and possibly using term_group?

A: To do this generically for terms (with custom taxonomies), you can use http://wordpress.org/extend/plugins/term-menu-order

A: There is a plugin that does that:
http://wordpress.org/extend/plugins/order-categories/


text:
Q: Permission denied of file with 777 i'm tring to use php function copy() but appear this error:
 Warning: copy(/home/smartsch/public_html/admin/student/photos/1tt) [function.copy]:
 failed to open stream: Permission denied in
 /home/schoolzs/public_html/admin/student/fileupload.class on line 137

The problem is that folder photos and file inside have all permission 777.I don't understand why happen permission denied!!


text:
Q: Relations to unlimited unknown future tables I'm working on my own genealogy software where I want to be able to add unlimited amount of sources, notes and places to a event. But I have a problem regarding the source tables.
It's not possible to create one table that fits all types of source.
Example of sources
Source: Letter

*

*To

*From

*Date

*Text

Source: Internet

*

*Website

*Date

*Text

Source: Census

*

*Year

*State

*County

*Adress... and so on.

So my solution so far is to create a special table for each source type and link them to a event_vs_source table
ID             INT
eventID        VARCHAR
sourceID       INT
sourceTable    VARCHAR

Data will then be:
ID          453
eventID     67
sourceID    345
sourceTable source_letter

source_letter
ID        INT
To        VARCHAR
From      VARCHAR
Date      DATE
Text      BLOB

But the problem is when I want to fetch all sources connected to a single event.
SELECT * FROM event_vs_source WHERE event_vs_source.eventID = 67;

this is giving me an array with the name of the source table, source_letter, but how do I use it in a JOIN to select the correct table and find the source ID in it?
I can do it if I do separate queries but what if I have multiple sources connected to one event and all of them are on different source tables?
event_vs_source
ID          486
eventID     67
sourceID    23
sourceTable source_website

That will result in even more separate queries.
Or am I designing this database wrong?
Is there a better way to do it?
Bottom line is that I want to be able to add as many sources, places and notes to a single event but also unlimited new and unknown future tables yet have a few database request per person. And remember that a person can hanv unlimited amount of events.....


text:
Q: Apache Spark architecture Trying to find a complete documentation about an internal architecture of Apache Spark, but have no results there.
For example I'm trying to understand next thing:
Assume that we have 1Tb text file on HDFS (3 nodes in a cluster, replication factor is 1). This file will be spitted into 128Mb chunks and each chunk will be stored only on one node. We run Spark Workers on these nodes. I know that Spark is trying to work with data stored in HDFS on the same node (to avoid network I/O). For example I'm trying to do a word count in this 1Tb text file.
Here I have next questions:

*

*Does Spark will load chuck (128Mb) into RAM, count words, and then delete it from memory and do it sequentially? What if there will be no available RAM?

*When does Spark will use not local data on HDFS?

*What if I will need to do more complex task, when a results of each iteration on each Worker need to be transferred to all other Workers (shuffling?), do I need to write them by my self to HDFS and then read them? For example I can't understand how does K-means clustering or Gradient descent works on Spark.

I will appreciate any link to Apache Spark architecture guide.

A: Here are the answers to your questions

*

*Spark will try to load 128Mb chunk into memory and process it in RAM. Keep in mind that that the size in memory can be several times larger than the original size of the raw file due to Java overhead (Java headers, etc). From my experience, it can be 2-4 time larger.
If there is not enough memory (RAM) Spark will spill the data to local disk. You may want to tweak these two parameters to minimize the spill: spark.shuffle.memoryFraction and spark.storage.memoryFraction.

*Spark will always try to use local data from in your HDFS. If the chunk not available locally it will retrieve it from another node in the cluster. more info

*On shuffle, you do not need to manually save intermediate results to HDFS. Spark will write the results to local storage and shuffle only the data needed maximizing reuse of local storage for the next stage.
Here is good video that goes into more detail of Spark architecture, what happens during shuffle and tips for optimizing performance.

A: Adding to other answers, here I would like to include Spark core architecture diagram as it was mentioned in the question.
Master is entry point here.


text:
Q: Cronjob Quartz format in yml I have the application.yml with that entry:
cron:
  scheduler:
     expr: 0 0/60 * * * ?

when I try to inject the property in my Quarkus scheduler I get the message:
IllegalArgumentExpression: Cron expression contains 1 parts but we expect one of [6, 7]

I get this message for each example I try and I am not able to solve the problem.
Even:
expr: "0 0/60 * * * ?"

did not work.
@Scheduled(cron = "{cron.scheduler.expr}")
void cronJobWithExpressionInConfig() {
   counter.incrementAndGet();
   System.out.println("Cron expression configured in application.yml");
}

I am happy for any advice.

A: According to this the value in the annotation is correct, but if you look at the paragraph updating-the-application-configuration-file the guide is using the file application.properties.
Since you are using an YAML file, I suspect you did not include a dependency that is needed (tested both version 1.9.0.Final and 1.9.2.Final):
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-config-yaml</artifactId>
      <version>1.9.2.Final</version>
    </dependency>

On the contrary of Spring, this dependency must be explicitly listed in the pom.xm file.
Moreover, I would change the YAML file in this way:
cron:
  scheduler:
     expr: "0 0/60 * * * ?"

Disclamer: I did not manage to replicate your error. Details provided are not sufficient.
Edited
Please, note that the cron expression itself is fishy... '0/60' does not make sense. That is the part that specify the minute of the hour the cron job will happen, for instance '0/40' says that one wants the job to be executed at minute 0 and minute 40th of each hour, for example at 00:00, 00:40,...,  14:00, 14:40, ... 23:00 and 23:40.
So your expression says to execute the job at XX:00 and XX:60 which does not exists.
If you check in the official docs of Cron Trigger Tutorial in the Minutes line it clearly states that the values accepted are in the range of [0-59]
Example
Please, observe the following (working) java class:
package com.acme.scheduled;

import io.quarkus.scheduler.Scheduled;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class ScheduledActions {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledActions.class);

    private static final int lengthFrame = 120;
    private static final int lengthText = lengthFrame - 4;
    private static final String FRAME = StringUtils.repeat('*', lengthFrame);

    private void printFancyText(final String text) {
        final String centeredText;

        if(text.length() > lengthText ) {
            centeredText = StringUtils.abbreviate(text,"...", lengthText);
        } else if ( text.length() == lengthText) {
            centeredText = text;
        } else {
            centeredText = StringUtils.center(text, lengthText);
        }

        LOGGER.info(FRAME);
        LOGGER.info("* {} *", centeredText);
        LOGGER.info(FRAME);
    }

    @Scheduled(cron = "{cron.scheduler.expr}")
    public void cronExpressionTrigger(){
        this.printFancyText("Firing from statically defined cron expression. Triggering method 'cronExpressionTrigger'.");
    }

    @Scheduled(delay = 5, delayUnit = TimeUnit.SECONDS, every = "PT15S")
    public void delayTrigger() {
        this.printFancyText("Firing from delay express in seconds. Triggering method 'delayTrigger'.");
    }

    @Scheduled(every = "30s")
    public void periodicTrigger(){
        this.printFancyText("Firing from statically defined period. Triggering method 'periodicTrigger'.");
    }

}

The value of the cron expression is taken from the application.yml file, defined as following:
cron:
  scheduler:
    expr: "0 0/1 * * * ?"       #   This works like a charm, with or without the '@' - I prefer with.
#    expr: "0 0/60 * * * ?"   >>> This does NOT work. It fails with error: java.lang.IllegalArgumentException: Period 60 not in range [0, 59]


text:
Q: How can I disable the password reset prompt at ssh login for expired password? (RHEL 6.9) Environment:
Red Hat Enterprise Linux Server release 6.9 (Santiago)
LDAP provided by Oracle Directory Server running on Solaris

How do I turn off the automatic change password prompt when a user logs in with an expired password? I want the login to fail with a message that the password is expired.
It would be nice to add a message to contact our help desk also.
Currently when a user's password is found to have expired the system runs a password reset program but that does not work on our system because of our LDAP server.
I have tried changing chpass_provider = ldap to chpass_provider = none in the sssd.conf file [domain] section. But that did not work for me.
Any pointers greatly appreciated.

A: I think the easiest way is to set the account to expire as well as the password. If they occur on the same day then the user will still get the warning and be able to change their password before it expires, but once it does expire they will not be able to login and/or change their password.
This command will list expiration properties about the user:
 $ chage -l <username>
 Last password change                                    : Dec 29, 2017
 Password expires                                        : never
 Password inactive                                       : never
 Account expires                                         : never
 Minimum number of days between password change          : 0
 Maximum number of days between password change          : 99999
 Number of days of warning before password expires       : 7

You are also able to set properties with the chage command.
As for newly created users, you can modify /etc/default/useradd and set the EXPIRE= value which will set when the account expires for users created with useradd.
As far as alerting IT. You could probably pretty easily iterate through the users and run the chage command to see if their account is locked/expired, and generate an email.
This has some info: https://www.techrepublic.com/article/how-to-manage-linux-password-expiry-with-the-chage-command/

A: chage, as already mentioned, is a good start. Also consider /etc/login.defs and the PASS_* options in it.
Further it looks like sssd is involved, in sssd.conf there are also password expiry config options (e.g pwd_expiration_warning or pam_pwd_expiration_warning).


text:
Q: To prove given category is abelian category In my text book, to prove given category is abelian category,
author just checks there exists Ker and Coker.
In general, we omit other axioms to check(and existence of Ker and Coker is most difficult?)
Do we often omit checking other axioms(additive category, coimf→imf is isom is difficult)?
I'm not familiar with category theory, thank you for your comments.


text:
Q: Windows Phone: playing a recorded sound throws exception I am using an AudioVideoCaptureDevice to record some sound from the microphone. I want to give the user feedback on what he recorded so I want to be able to play it.
When putting that sound into a Song and playing it via Microsoft.Xna.Framework.Media.MediaPlayer, I am getting an exception:

{System.InvalidOperationException: Song playback failed.
      Please verify that the song is not DRM protected.
      DRM protected songs are not supported for creator games.
      ---> System.InvalidOperationException: An unexpected error has occurred.
      --- End of inner exception stack trace ---
      at Microsoft.Xna.Framework.Media.MediaQueue.Play(Song song)}

Looking into the details of the song in the watch, the IsProtected() seems to cause issues. (If playback works, I get correctly that the song is not protected.) I am using AAC and ACM codecs, both give same results.
I can play the song after closing and opening the view again, but have not found any related initialization that would explain this.
I also tried copying the file, in case some process was still holding a lock on it, still, there is no improvement, same with isolated storage.
After not closing app but re-entering view the song plays without problems.
How can I directly play the recorded audio without any problems?

A: I used the AudioRecorder sample from http://independentinnovation.net/blogs/independentinnovation/archive/2012/12/11/Windows-Phone-8-Audio-Recording-using-Windows.Phone.Media.Capture.aspx .
(Note: right now this link is not working, domain expired.. anyway, I used someone else's code.)
It turns out, that in the Record() function, a stream is opened, that in the Stop() function is never properly flushed and disposed.
I don't understand how this could have caused the problem, since I did copy the resulting file, just to make sure that all handles are valid.
Still, old handling was definitely wrong and new handling is a lot cleaner, and, btw, works.
    public async void StopRecording()
    {
        try
        {
            if (dev != null)
            {
                await dev.StopRecordingAsync();
                dev = null;
                // these 2 lines I had to add
                await recordingStream.FlushAsync();
                recordingStream.Dispose();
           }
            var length = new System.IO.FileInfo(fileName).Length;
            System.Diagnostics.Debug.WriteLine("Recorded " + fileName + " with length " + length);
        }
        catch (System.Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }
    }

edit: to give credits, I found the answer I used here http://www.postseek.com/meta/9fddd403d0cde523a542be42b7a4b057


text:
Q: Finite second homotopy group I am interested in sufficient conditions for the second homotopy group $\pi_2(X)$ of a compact connected manifold to be finite. Are there familiar classes of manifolds $X$, for which this is the case?

A: You can have for instance a look at the following paper
Manuel Amann and Anand Dessai, MR 2600123 The $\hat A$-genus of $S^1$-manifolds with finite second homotopy group, C. R. Math. Acad. Sci. Paris 348 (2010), no. 5-6, 283--285.
and at the references given therein.


text:
Q: Rails 4 + Omniauth + Devise: Logout link not working I'm using Omniauth as my only method for signing into my Rails application.
The issue is: When a user clicks "Logout", the page reloads and the Logout link is still there (despite if user_signed_in? logic wrapping it). Which leads me to believe that users aren't actually getting logged out
Here's my index.html.erb:
<% if user_signed_in? %>
  <%= link_to "Authenticate with Google", user_omniauth_authorize_path(:google_oauth2) %>
<% else %>
  <%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
<% end %>

And my user.rb
def self.from_omniauth(auth)
  if user = User.find_by_email(auth.info.email)
    user.provider = auth.provider
    user.uid = auth.uid
    user
  else
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.email = auth.info.email # THIS (user.email) value i want to provide to my registration form as default value
   end
  end
end

And my omniauth_callbacks_controller.rb:
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  skip_before_filter :redirect_to_login_if_required
  def google_oauth2
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication
      return
    else
      session["devise.user_attributes"] = @user.attributes
      redirect_to new_user_registration_path
    end
  end
end

And my routes.rb:
devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks" }

Unfortunately it's not bringing me back an error. It's just refreshing the index page as if nothing happened.
Edit: Here's the POST when I click Logout
Started DELETE "/users/sign_out" for ::1 at 2015-07-06 11:00:22 -0400
Processing by Devise::SessionsController#destroy as HTML
  Parameters: {"authenticity_token"=>"7QXScU8eVW6NVedKG5P86rPxkaP8uJdUzyJ712ZrYXtK7QjP/m33eQ2WE/ituUvFQ2GeenXLRBaiVibxEjHG6w=="}
Redirected to http://localhost:3000/
Filter chain halted as :verify_signed_out_user rendered or redirected
Completed 302 Found in 1ms (ActiveRecord: 0.0ms)

Edit 2: I've included this in my application_controller.rb
before_action :authenticate_user!

And now the error message I'm getting in the console is:
Started GET "/users/auth/google_oauth2/callback?state=c92f3f9e0a8db79485e56ec2a1defd91949e8e7d99a02130&code=4/pgl_HZFw113L7VJ-rSaV9-JYngABkfgx7lqRm06Dyqg" for ::1 at 2015-07-06 16:12:14 -0400
I, [2015-07-06T16:12:14.739138 #2442]  INFO -- omniauth: (google_oauth2) Callback phase initiated.
Processing by OmniauthCallbacksController#google_oauth2 as HTML
  Parameters: {"state"=>"c92f3f9e0a8db79485e56ec2a1defd91949e8e7d99a02130", "code"=>"4/pgl_HZFw113L7VJ-rSaV9-JYngABkfgx7lqRm06Dyqg"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = ? LIMIT 1  [["email", "broy@gmail.com"]]
   (0.1ms)  begin transaction
  SQL (0.4ms)  UPDATE "users" SET "last_sign_in_at" = ?, "current_sign_in_at" = ?, "sign_in_count" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["last_sign_in_at", "2015-07-06 20:11:47.636852"], ["current_sign_in_at", "2015-07-06 20:12:15.365770"], ["sign_in_count", 42], ["updated_at", "2015-07-06 20:12:15.366734"], ["id", 4]]
   (1.4ms)  commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 15ms (ActiveRecord: 2.1ms)

Started GET "/" for ::1 at 2015-07-06 16:12:15 -0400
Processing by ProductlinesController#index as HTML
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms)

A: I would recommend switching the if to unless, so it shows the logout link when the user is signed in.
<% unless user_signed_in? %>
  <%= link_to "Authenticate with Google", user_omniauth_authorize_path(:google_oauth2) %>
<% else %>
  <%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
<% end %>

When using devise, an alternative way of displaying the corrects links is:
<%unless current_user.blank? -%>
  <%= link_to "Authenticate with Google", user_omniauth_authorize_path(:google_oauth2) %>
<%else -%>
  <%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
<%end-%>

A: From the logs you posted, you have

Filter chain halted as :verify_signed_out_user rendered or redirected

This is the reason for your problem.
Adding skip_before_filter :verify_signed_out_user to your controller should solve the problem.
Update:
You need to change your code in index.html.erb to the following
<% if user_signed_in? %>
  <%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
<% else %>
  <%= link_to "Authenticate with Google", user_omniauth_authorize_path(:google_oauth2) %>
<% end %>

Source: Devise Wiki


text:
Q: Nginx / libxml error I installed nginx server on my Ubuntu using repos...
When I am starting the server I am getting this error:
    starting nginx: /usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/sbin/nginx)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/sbin/nginx)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)``
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libxslt.so.1)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libexslt.so.0)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libexslt.so.0)
/usr/sbin/nginx: /usr/local/lib/libxml2.so.2: no version information available (required by /usr/lib/i386-linux-gnu/libexslt.so.0)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()

This is what I see using locate
locate libxml2.so.2
    /home/john/Downloads/libxml2-2.7.8/.libs/libxml2.so.2
    /home/john/Downloads/libxml2-2.7.8/.libs/libxml2.so.2.7.8
    /usr/lib/libxml2.so.2
    /usr/lib/libxml2.so.2.9.1
    /usr/local/lib/libxml2.so.2
    /usr/local/lib/libxml2.so.2.7.8

What is the issue and how to fix it ?

A: You have a manually compiled libxml in /usr/local. Perhaps Direct Admin? Either get rid of it or don't use the ubuntu package and compile nginx from source.


text:
Q: Java Slot machine college project I'm making a slot machine for a college project. There are loads and loads of similar projects talked about online however the requirements for my project are slightly different. Here is my task:

*

*The player starts with £1 credit, with each go costing 20 p.

*If the Fruit Machine "rolls" two of the same symbol, the user wins 50 p.

*The player wins £1 for three of the same and £5 for 3 Bells.

*The player loses £1 if two skulls are rolled and all of his/her money if three skulls are rolled.

*The player can choose to quit with the winnings after each roll or keep playing until there is no money left.

What I've come up with so far is this:
for ( int runCount = 1; runCount <= 3; runCount ++ ) {

        int symIndex = r.nextInt(6);

        if (symIndex == 0) {
            symbol = "cherry";
        } else if (symIndex == 1){
            symbol = "orange";
        } else if (symIndex == 2){
            symbol = "lemon";
        } else if (symIndex == 3){
            symbol = "bell";
        } else if (symIndex == 4){
            symbol = "star";
        } else if (symIndex == 5){
            symbol = "skull";
        }

        if (runCount == 1){
            reel1 = symbol;
        } else if ( runCount == 2 ){
            reel2 = symbol;
        } else if ( runCount == 3 ){
            reel3 = symbol;
        }

    }
    System.out.println(reel1 + "  " + reel2 + "  " + reel3);

Which is great and spits out 3 random symbols but what is I need is a way is for it to somehow treat the bell and skull symbols differently. There must be an easier way than write out every possible combination in an if statement. In all the other projects I've seen the prize if statements have looked something like this
if (reel1 == reel2 && reel1 == reel3 && reel2 == reel3)
System.out.println("You have won!");

Or something about that etc etc. But if I do it this way it's not defining the actual symbol but just storing it in one of the reel variables so I can't make if statements for those specific outcomes.
Any help would be greatly, greatly appreciated. Even if you could just tell me how to phrase my question properly so I could search it would be helpful

A: I've changed things a little. Rather than storing 3 unique fields reel1, reel2 and reel3 you can re-use the counter variable you're using to control the for-loop to place the chosen symbols into an array. Note: you need to start the counter at 0, but this makes little/no difference.
    private static final String CHERRY = "cherry";
    private static final String ORANGE = "orange";
    private static final String LEMON = "lemon";
    private static final String BELL = "bell";
    private static final String STAR = "star";
    private static final String SKULL = "skull";
    private static final Random random = new Random();

    public static void main(String[] args) {
        String[] symbols = new String[3];
        pickRandomSymbolsForReels(symbols);
        displayReels(symbols);
        Map<String, Integer> symbolCounts = new HashMap<>();
        checkResults(symbols, symbolCounts);
        displayResults(symbolCounts);
    }

    private static void checkResults(String[] symbols, Map<String, Integer> symbolCounts) {
        // for each symbol
        // if (symbolCounts.get(symbol) != null) {
        //      symbolCounts.put(symbol, 1);
        // } else {
        //      int incrementedValue = symbolCounts.get(symbol) + 1;
        //      symbolCounts.put(symbol, incrementedValue);
        // }
    }

    private static String[] pickRandomSymbolsForReels(String[] symbols) {
        for (int reelIndex = 0; reelIndex < symbols.length; reelIndex++) {
            int choice = random.nextInt(6);
            switch (choice) {
                case 0:
                    symbols[reelIndex] = CHERRY;
                    break;
                case 1:
                    symbols[reelIndex] = ORANGE;
                    break;
                case 2:
                    symbols[reelIndex] = LEMON;
                    break;
                case 3:
                    symbols[reelIndex] = BELL;
                    break;
                case 4:
                    symbols[reelIndex] = STAR;
                    break;
                case 5:
                    symbols[reelIndex] = SKULL;
                    break;
            }
        }
        return symbols;
    }

    private static void displayReels(String[] symbols) {
        for (String symbol : symbols) {
            System.out.print(symbol + " ");
        }
        System.out.println();
    }

    private static void displayResults(Map<String, Integer> symbolCounts) {
        /**
         * Here you'll need to understand the logic of various events.
         * e.g
         * 3 skulls - instantly lose all credit - game over
         * 2 skulls - decreaseBalance(1.00)
         * 3 Bells - increaseBalance(amount)
         * 3 of any other symbol - increaseBalance(amount)
         * 2 of any thing else - increaseBalance(amount)
         * .. etc
         */
        // if (hasThreeSkulls(symbolCounts.get(SKULL)) {
        //   gameOver();
        // } else if (hasTwoSkulls(symbolCounts.get(SKULL)) {
        //   decreaseBalance(100) // note when working with money, store pence amount only and display the value as pounds and pence.. otherwise you'll have issues
        // } etc ..
    }

Next gather the stats from the reels (counts of the symbols of interest). Finally check the stats for winning/losing results. This will be a bunch of if, else-if statements.


text:
Q: How to create a clickable listview I am currently trying to create a clickable list view. I've created the xml file but confused on what to do after to make the items in the list clickable. Below is the xml code.
activities_clubs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ListView
        android:id="@+id/listView1"
        android:layout_width="200dp"
        android:layout_height="600dp"
        android:layout_alignTop="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:entries="@array/activities"
        android:padding="40dp" >
    </ListView>
</RelativeLayout>

Here is the strings.xml file:
<string-array name="activities">
        <item >American Football</item>
        <item >Archery</item>
        <item >Athletics</item>
        <item >Badminton</item>
        <item >Basketball (Men)</item>
        <item >Basketball (Women)</item>
        <item >Dance</item>
        <item >Fencing</item>
        <item >Football (Men)</item>
</string-array>

What would i need to do next to make the items clickable?

A: You can do it in your java file, do something like this.
ListView list = (ListView) findViewById(R.id.listView1);

list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
        // DO SOMETHING HERE
    }

});

A: Try putting this code
android:clickable="true"

A: Try this
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
        Log.i("ListView", " position:" + position);
            // Then you start a new Activity via Intent
            Intent intent = new Intent();
            intent.setClass(this,ItemDetail.class);

            startActivity(intent);


text:
Q: Spring Doc: swagger-ui.html giving Whitelabel Error Page 404 I am using springdoc-open api for swagger integration in my springboot project.
I have added below property in application.yml
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_mathcher

and added below  dependency in build.gralde file
implementation "org.springdoc:springdoc-openapi-ui:1.6.9"

I am able to access /v3/api-docs , but /swagger-ui/index.html and /swagger-ui.html giving 404 Whitelabel Error Page

A: After googling so many thins, I found a solution to this issue. I had to add an additional configuration class that is OpenApiConfig.java to make it work.
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"org.springdoc"})
@Import({org.springdoc.core.SpringDocConfiguration.class,
org.springdoc.webmvc.core.SpringDocWebMvcConfiguration.class,
org.springdoc.webmvc.ui.SwaggerConfig.class,
org.springdoc.core.SwaggerUiConfigProperties.class,
org.springdoc.core.SwaggerOAuthProperties.class,
org.springframework.autoconfigure.jackson.JacksonAutoConfiguration.class})
class OpenApiConfig implements WebMvcConfigurer {
}


text:
Q: questions in understanding the textbook about fourier transform I am confused about if the text book set $z = x-y$, then why there is no $-$ after variable change? I think it is obvious that $dy = - dz$

A: They have compensated for this negative sign, but it's hidden in their $\int_R$ notation. Substitution affects both the $d$ term and the bounds of an integral, but we can't see that here. Writing it with explicit bounds, and inserting an intermediate calculation, we get
$$
\int_{-\infty}^\infty [\cdots]dy=-\int_\infty^{-\infty}[\cdots]dz\\
=\int_{-\infty}^\infty [\cdots ]dz
$$
Hopefully this is clearer.

A: You are right there is a minus sign but also the boundaries of the integral will change after the change of variables, so the integral will be
$-\int_{+\infty}^{-\infty}=\int_{-\infty}^{+\infty}= \int_{\mathbb R}$


text:
Q: Авторизация для гостей в laravel 5.2 Для авторизации я использую политики laravel. Проблема в том, что они не работают для гостей. Как мне проверить права для гостей?
Мой код:
В контроллере:
class PostController extends Controller
{
    public function index(Post $post)
    {
        $this->authorize($post);
        return $post->all();
    }
}

В политике:
class PostPolicy
{
    // Эта функция выполняется только для аутентифицированных пользователей.
    // Хотелось бы, чтобы она выполнялась и для гостей
    public function index(User $user)
    {
        return $user->can('get-posts');
    }
}

Мне нужна возможность ограничения доступа к методам контроллера для некоторых пользователей. Права будут храниться в БД и их можно будет менять через админку. Мне кажется, что для этого подходит стандартный механизм политик, там я мог проверять доступ к каждому методу контроллера + с помощью модуля entrust в базе хранятся роли и привилегии для пользователей. И при любом запросе я могу проверить права с помощью метода $user->can(). Но всё то не работает для гостей. Я не понимаю, почему так сделано, ведь у пользователей тоже есть права. И непонятно, как теперь проверять, есть ли у пользователей привилегии на какое-либо действие

A: Все зависит конечно от того насколько ваше приложение будет большим. Но могу обратить ваше внимание на middleware такого рода проверки обычно хватает для малых приложений. Если вам нужно привязывать конкретно к каждому пользователю права и его роль в системе можете реализовать это сами обвернув существующий User но если вы не хотите изобретать велосипед то вам сюда, это не единственный пакет и их много ключевое слово laravel access rights user :)


text:
Q: How to prepare testing data for object detection? I have some images with which I will test an object detection classifier.
I'll have the classifier output the coordinates for the rectangles where it believes the target objects are, but I wonder how the results are tested?
I'm guessing I should have a reference file of coordinates of true object positions against which I can compare the classifier's results.
What if the classifier does make a correct classification, just with the coordinates not exactly the same as the ones in the reference file?
How's this usually solved?

A: The answer depends of the method you are going to use. One of them you've proposed, and in that case I would put an fixed possible error rate for bad detecting case which, if the classifier result lays inside the error interval for one of the examples from data test file, is considered as a proper classified example. Of course this fixed error rate should be as small as not to "overdetect" in the data set.
I would suggest trying cross-validation as a technique to test classifier. From data set, it chooses some vectors (images) as a test set and the rest of them as a training set. Repeat few times and average the errors resulting in estimated classificator error. And you don't have to have separate data test set and you don't have to worry about the problem you stated.


text:
Q: Updating items at UI on an ObservableCollection using MVVM Light So I have an ObservableCollection<Term> on a view model, with Term items having some data properties.
Term class:
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Neomilano.Model
{
    public class Term
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public DateTimeOffset TermStart { get; set; }

        public DateTimeOffset TermEnd { get; set; }

        public string DurationText
        {
            get
            {
                return "from " + TermStart.Date.ToString("MMMM d, yyyy") + " to " + TermEnd.Date.ToString("MMMM d, yyyy");
            }
        }

        public Term()
        {
        }
    }
}

This is the ViewModel in question that has the ObservableCollection (ProjectBaseViewModel implements MVVM Light's ViewModelBase and has few properties that I don't think is necessary here):
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using Microsoft.Practices.ServiceLocation;
using Neomilano.Model;
using Neomilano.Services;
using SQLite;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.Foundation;

namespace Neomilano.ViewModel
{
    public partial class TermsViewModel : ProjectBaseViewModel
    {

        public IDialogService DialogService
        {
            get { return ServiceLocator.Current.GetInstance<IDialogService>(); }
        }

#region properties
        private ObservableCollection<Term> _terms;
        public ObservableCollection<Term> Terms {
            get { return this._terms; }
            private set { Set(() => Terms, ref _terms, value); }
        }
#endregion

#region commands

        private RelayCommand<int> _deleteTermCommand;
        public RelayCommand<int> DeleteTermCommand
        {
            get
            {
                return _deleteTermCommand ??
                    (_deleteTermCommand = new RelayCommand<int>(async id => {
                        var t = "Are you sure you want to delete this term?";
                        var c = "This cannot be undone.";
                        var ct = "delete";
                        bool deleteConfirmed = await DialogService.ShowConfirmationDialogAsync(t, c, ct);

                        if (deleteConfirmed == true)
                            await ExecuteDeleteTermAsync(id);
                    }));
            }
        }

#endregion

        public TermsViewModel()
        {
            if (IsInDesignMode)
            {
                List<Term> t = new List<Term>();

                t.Add(new Term() { ID=1, Name = "Sample Term 1", TermStart = DateTimeOffset.Parse("October 1, 2013"), TermEnd = DateTimeOffset.Parse("December 17, 2013") });
                t.Add(new Term() { ID=2, Name="Sample Term 2", TermStart=DateTimeOffset.Parse("January 1, 2014"), TermEnd=DateTimeOffset.Parse("April 30, 2014") });

                Terms = new ObservableCollection<Term>(t);
            }

        }

        /// <summary>
        /// Gets the list of Terms from the database and adds it to the Terms property of the ViewModel.
        /// </summary>
        /// <returns></returns>
        public async Task GetTermsListAsync()
        {
            IsProgressEnabled = true;

            List<Term> list = new List<Term>();
            await Task.Run(() =>
            {
                using (var db = new SQLiteConnection(app.DBFileName))
                {
                    list = db.Table<Term>().ToList<Term>();
                    db.Close();
                }
            });
            Terms = new ObservableCollection<Term>(list);

            IsProgressEnabled = false;
        }

        /// <summary>
        /// Returns the term ID of the selected term from the view.
        /// </summary>
        /// <param name="clickedItem"></param>
        /// <returns></returns>
        public Term ReturnSelectedTerm(object clickedItem)
        {
            return (Term)clickedItem;
        }

        public async Task ExecuteDeleteTermAsync(int termId)
        {
            IsProgressEnabled = true;

            Term t = new Term();
            await Task.Run(() =>
            {
                using (var db = new SQLiteConnection(app.DBFileName))
                {
                    var q = db.Table<Term>().Where(tr => tr.ID.Equals(termId));
                    t = q.First<Term>();

                    db.Delete<Term>(termId);
                    db.Close();
                }
            });

            var target = Terms.Single<Term>(tr => tr.ID.Equals(termId));
            Terms.Remove(target);

            IsProgressEnabled = false;
        }
    }
}

THE ISSUE: Sure, adding and removing terms from another page work well. When the Term items get updated, however, only the title gets updated.
Here's what's on the view:
            <ListView
                x:Name="TermsListView"
                ItemsSource="{Binding Terms}"
                IsItemClickEnabled="True"
                ItemClick="OnTermItemClick">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Holding="OnTermItemHold">
                            <FlyoutBase.AttachedFlyout>
                                <MenuFlyout x:Name="TermItemContextMenu">
                                    <MenuFlyoutItem Text="edit" Command="{Binding TermsViewModel.NavigateToFormCommand, Mode=OneWay, Source={StaticResource Locator}}" CommandParameter="{Binding}" />
                                    <MenuFlyoutItem Text="delete" Command="{Binding TermsViewModel.DeleteTermCommand, Mode=OneWay, Source={StaticResource Locator}}" CommandParameter="{Binding ID}" />
                                </MenuFlyout>
                            </FlyoutBase.AttachedFlyout>
                            <TextBlock Text="{Binding Name}"  Style="{ThemeResource ListViewItemTextBlockStyle}"/>
                            <TextBlock Text="{Binding DurationText}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

Term.DurationText does not update when the two date values have changed. If the edit page is to be seen however, the change is reflected in the DatePickers.
Is there any way that I can make DurationText update accordingly through Binding in such a way that it works with an implementation using MVVM Light?
I have tried this but the error says:

The type 'Neomilano.Model.Term' cannot be used as type parameter 'T'
  in the generic type or method
  'Neomilano.Common.ItemsChangeObservableCollection'. There is no
  implicit reference conversion from 'Neomilano.Model.Term' to
  'System.ComponentModel.INotifyPropertyChanged'.

Project specs:
* This is a WinRT app
* It's a universal Windows App, but I'm working on Windows Phone first right now. I think this doesn't matter because of the convergence bet. WinRT and WinPRT, but who knows this might be the problem
* As I have mentioned, I'm using MVVM Light(libraries only).
So, in general, how can I update the contents of an item of an ObservableCollection in WinRT using MVVM Light?
Thank you for your help!

A: You don't need anything in the linked article, you simply need Term to impllement INotifyPropertyChanged.  ObservableCollection<T> only notifies the ListView bound to it that the content of the collection has changed, i.e. it notifies add, remove, move, replace, reset etc.  It doesn't monitor the items within the collection for changes.
In this case, you can make Term derive from ViewModelBase, as this contains an implementation of INotifyPropertyChanged.
An example is below.  Note how the setter for TermStart also raises a change event for DurationText, as this property is dependent.
public class Term : ViewModelBase
{
    private int _id;
    private string _name;
    private DateTimeOffset _termStart;
    private DateTimeOffset _termEnd;

    public int Id
    {
        get { return _id; }
        set
        {
            if (value == _id) return;
            _id = value;
            RaisePropertyChanged("Id");
        }
    }

    public string Name
    {
        get { return _name; }
        set
        {
            if (value == _name) return;
            _name = value;
            RaisePropertyChanged("Name");
        }
    }

    public DateTimeOffset TermStart
    {
        get { return _termStart; }
        set
        {
            if (value.Equals(_termStart)) return;
            _termStart = value;
            RaisePropertyChanged("TermStart");
            RaisePropertyChanged("DurationText");
        }
    }

    public DateTimeOffset TermEnd
    {
        get { return _termEnd; }
        set
        {
            if (value.Equals(_termEnd)) return;
            _termEnd = value;
            RaisePropertyChanged("TermEnd");
            RaisePropertyChanged("DurationText");
        }
    }

    public string DurationText
    {
        get { return "from " + TermStart.Date.ToString("MMMM d, yyyy") + " to " + TermEnd.Date.ToString("MMMM d, yyyy"); }
    }
}


text:
Q: onBindViewHolder is giving me a null ArrayList because the data hasn't finished loading from Firebase For RecyclerView my onBindViewHolder is using setText from an ArrayList that I load data in, from firebase.
However for the first onBindViewHolder call, it's giving me a null ArrayList because the data hasn't finished loading. (2nd, 3rd ... etc get the values in time)
How do I call onBindViewHolder, after my ArrayList has finished retrieving all the data?

A: Try to load the data in before seting the adapter. In the adapter, pass the data through the constructor.

A: try to setAdapter after loading all data in List.
and in getItemCount do this
 @Override
    public int getItemCount() {
        if (list == null)
            return 0;
        return list.size();
    }

this is for is your list is null it will return 0 means onBindViewHolder will not get call and its not null then it will return size of list at that time your onBindViewHolder will get called


text:
Q: Write in an existing Excel .xls file which contains macros I want to insert datas an existing Excel (.xls) file with Ruby under Linux. This file has already data, it has some format properties and it contains macros.
I tried to insert data into the file with the spreadsheet gem but when I save modifications, the format and all the macros of the file are lost.
Here's an example of a simple modification where I meet this problem :
book = Spreadsheet.open('myOriginalFile.xls')
sheet = book.worksheet 0
sheet.write('C12','hello')
book.write('myModifiedFile.xls')

I tried lots of things, did research on forums and the web but I didn't find a solution...
Does anyone has an idea?

A: I found a solution :
I use the POI library of Apache which is written in java with the rjb gem (Ruby Java Bridge, which allows to use java libraries with ruby). POI allows to keep macros and formulas of existing xls file and to modify it.
For those who need, here's how to set up rjb to use POI :
    # JVM loading
    apache_poi_path = File.dirname(__FILE__)+'/poi-3.8/poi-3.8-20120326.jar'
    Rjb::load("#{apache_poi_path}", ['-Xmx512M'])

    # Java classes import
    @file_class = Rjb::import('java.io.FileOutputStream')
    @workbook_class = Rjb::import('org.apache.poi.hssf.usermodel.HSSFWorkbook')
    @poifs_class = Rjb::import('org.apache.poi.poifs.filesystem.POIFSFileSystem')
    Rjb::import('org.apache.poi.hssf.usermodel.HSSFCreationHelper')
    Rjb::import('org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator')
    @cell_reference_class = Rjb::import('org.apache.poi.hssf.util.CellReference')
    @cell_class = Rjb::import('org.apache.poi.hssf.usermodel.HSSFCell')
    # You can import all java classes that you need

    # Java classes utilisation :
    @file_input_class = Rjb::import('java.io.FileInputStream')
    @file_input = @file_input_class.new(model_file_path)
    @fs = @poifs_class.new(@file_input)
    @book = @workbook_class.new(@fs)

    @worksheet = @book.getSheet('worksheet')
    # ...
    # You can use your objects like in Java but with a ruby syntax

A: You need to write the modified file to a new file name. Check out this
If you have more than one sheet, you need to rewrite other sheets
XLS with several sheets but only modify one of the sheets (and don't
touch the other data), there is no way, that spreadsheet "remembers"
what is in the other sheets. You will have to write the unmodified
sheets as well or otherwise unexpected things will happen.
Ergo: Write the modified sheet and also write the complete unmodified
sheets again, when modifying an XLS with spreadsheet with several
sheets.

A: Might want to check out Axlsx not sure if it will be able to edit a plain .xls, but I did some work with it a few weeks ago, it worked wonders for the xlsx I was working with.

A: You just need to open existing file, write your changes into file and save it with another name.
For example on server you have template.xls file.
Simple working example ( need to have template.xls near your .rb file ):

#edit_xls.rb
require 'rubygems'
require 'spreadsheet'

book = Spreadsheet.open 'template.xls'
sheet = book.worksheet 0
sheet[0,0] = 'qweqeqw'
book.write 'edited.xls'


text:
Q: Erro ao compilar WEB API NET CORE Eu estou recebendo a mensagem abaixo ao tentar compilar meu projeto. Eu comentei alguns código e cheguei a conlusão que estou implementando a classe de Contexto de dados de maneira erra pois se eu comento ela o erro para de ocorrer.
Segue abaixo o erro.
Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: BLL.People.Person.Searches.Abstractions.IPersonQuery Lifetime: Transient ImplementationType: BLL.People.Person.Searches.Services.PersonQuery': Unable to resolve service for type 'DAL.People.PeopleDbContext' while attempting to activate 'BLL.People.Person.Searches.Services.PersonQuery'.)
---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: BLL.People.Person.Searches.Abstractions.IPersonQuery Lifetime: Transient ImplementationType: BLL.People.Person.Searches.Services.PersonQuery': Unable to resolve service for type 'DAL.People.PeopleDbContext' while attempting to activate 'BLL.People.Person.Searches.Services.PersonQuery'.
---> System.InvalidOperationException: Unable to resolve service for type 'DAL.People.PeopleDbContext' while attempting to activate 'BLL.People.Person.Searches.Services.PersonQuery'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.ValidateService(ServiceDescriptor descriptor)
--- End of inner exception stack trace ---
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.ValidateService(ServiceDescriptor descriptor)
at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable1 serviceDescriptors, ServiceProviderOptions options) --- End of inner exception stack trace --- at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable1 serviceDescriptors, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at LeiriaAPI.Program.Main(String[] args) in D:\Projects.netCore\LeiriaAPI\Program.cs:line 16
Segue abaixo a classe de contexto:
public class PeopleDbContext : DbContext {

    // Constructor
    public PeopleDbContext(DbContextOptions options) : base(options) {}

    // Person
    public DbSet<PersonEntity> Person { get; set; }

    protected override void OnModelCreating(ModelBuilder builder) {

        // Person
        builder.ApplyConfiguration(new PersonConfiguration());
    }
}

Segue abaixo a classe onde eu registro as dependencias
public static class People_IoC {
    public static IServiceCollection AddMapperPeople(this IServiceCollection conteiner) {

        // Person
        conteiner.AddTransient<IPersonQuery, PersonQuery>();

        return conteiner;
    }
}

Eu não estou comseguindo achar o problema.
Desde já agradeço a disposição de vocês. Se precisanrem de mais alguma informação estou a disposição.

A: acabei de achar o problema. Eu havia esquecido de registrar a minha classe de contexto com o AddDbContext.
Até mais, obrigado.


text:
Q: Change Icon of Wine Application in Unity Launcher I frequently run a windows program with wine. When I open this program it shows up in the unity launcher as wine instead of the actual opened program.
I have made a desktop launcher with the right icon but dragging this to the unity launcher reverts the icon back to the wineglass icon. When starting the application it's denominated as Wine Windows Program Loader instead of its actual name.
Screenshot:

A: *

*This is where you will find your icons or place your custom icons in here:
$ cd ~/.local/share/icons/hicolor/256x256/apps/
$ ls
1DF1_PicasaPhotoViewer.0.png
.
.
.
29F5_WINWORD.0.png
850A_EXCEL.0.png
AA79_POWERPNT.0.png

*Go to the following directory:
$ cd ~/.local/share/applications/wine/Programs/Microsoft\ Office
$ ls
Microsoft Excel 2010.desktop\
Microsoft Office 2010 Tools\
Microsoft PowerPoint 2010.desktop\
Microsoft Word 2010.desktop\

*Edit .desktop files:
$ sudo nano Microsoft\ Word\ 2010.desktop
[Desktop Entry]
Name=Microsoft Word 2010
.
.
.
Icon=29F5_WINWORD.0.png (or name of icon as in above folder)

*You are done!

A: Workaround on Ubuntu 12.04 LTS and up

Note
This workaround requires a working launcher for your Wine application. Here's a tutorial on how to create one. The workaround also applies to applications installed with PlayOnLinux scripts. More recent versions of PlayOnLinux automatically add the StartupWMClass line to their launcher.
Instructions
Open your .desktop launcher in your favorite text editor and append this line to the file:
StartupWMClass=application.exe

where application.exe is the base name of the executable you want to launch in Wine.
Don't use the the full path, only the base name. And make sure it's unqoted (a general rule you should follow with desktop files).
Result
Application icons and descriptions should be rendered fine now:

Source: https://bugs.launchpad.net/unity-2d/+bug/702452

A: There are several logged bugs on this issue.
In one of the bugs (post 3), someone has reported a possible workaround.  However two further posts below that note that it doesnt always work.

A: I'm not using Unity, so I really don't know if it will work.
You problem could be beacause of the program launcher. I assume your .desktop file contains Exec=wine '/home/user/.wine/dosdevices/c:/Program...' and so on. Try making a bash binary wich contains something like this:
#!/bin/bash
cd '/home/aldomann/.wine/dosdevices/c:/Archivos de programa/Warcraft II BNE'
wine 'Warcraft II BNE.exe'

Name it for instance warcraft2 and move it to /usr/bin (or any PATH variable, wich you can know by typing echo $PATH on the Terminal)
Then in your .desktop file instead of Exec=wine '...' use Exec=warcraft2.
I think Unity will assume this is not a wine program and will use your icon, but it is only conjecture.
Hope it works ;)
By default your Wine apps .desktops are placed on /home/user/.local/share/applications/wine
Instead of modifying an existing .desktop file you can create a new one and place it on /home/user/.local/share/applications.
It should be something like this:
[Desktop Entry]
Name=Application
Comment=Comment
Exec=app-binary
Icon=app-icon
Type=Application
Terminal=false
StartupNotify=true
Categories=GTK;Utility

Tip: If you place your icon on /home/user/.icons/ (i.e app-icon.png) you will only have to put Icon=app-icon.

A: I've written a script to fix this and other problems with MSO in Unity.
https://ubuntulogia.wordpress.com/2015/01/25/fix_mso_unity/
It works for me, but any suggestions are welcome. If someone test it and found any improvements, please share it to me.
To run the script, you must copy the code in a text file (using gedit, for example), and save it. Then, you must run it using "sh". For example, if you save the file in your Home folder as "fixmso.sh", the command for running the script is:
    sh fixmso.sh

A: You can do that really simply over the GUI with a program called alacratz. Here's a pretty simple how-to. Bottom chapter is what your looking for http://develop.alpdesigns.ch/pages/linux/add_exe_program_to_linux.html

A: Use Alacarte (the old menu editor, you might need to install it) to create an old style menu entry with an icon and a executable that launches your program. Than search for this via alt + F2 and pin it to the launcher.

A: You can easily change any installed program in your Ubuntu using "Main Menu" (package name is "alacarte"). You can download it from Software Center by typing "Main Menu" and then:

*

*Run "Main Menu" program.

*From right panel called "Menus" find your program (in this case it is in "Wine" node) and select it in "Items" panel.

*Click on properties button.

*From showed dialogue select icon button that located on top left.

*Finally browse the location of your new icon in your file system.

After doing above steps you will see your new icon in Unity launcher and panel.
Have a nice time.

A: I had the same issue, and I found out it was because I put the shortcut files (that PlayOnLinux places on the Desktop) into a separate folder.  I took them out of the folder and put them on the Desktop and it works fine (the icon is displayed).  Hope this helps!


text:
Q: How are some features in my dataset affecting the other features in my new data frame I have a data frame as below which is used to create a food product

I have a code which gives me the mixture proportion ratio of starches , where one starch could be replaced with another , here the batter viscosity values actually lie between 5.75 and 6.75 but when we happen to test it , we got some results where the values doesn't lie between 5.75 and 6.75 , i'm trying to find if other features are impacting the Batter Viscosity , and how are they impacting , the quantity of starch that we are mixing is for 100g , we have arrived at a formula where we would be able to find the proportion of mixture of starches but as we have add few more features in the formula , i would like someone to help me understand how to add moisture_mu column , viscosity_mu column ranging between 10-14 and 400 to 600 respectively
Below is my code for the same
def mixture_proportion(input_df,starch,total_quant=100,final_viscosity=6):
    #Initializations
    starch_list=input_df['Product_Base']
    viscosity_list=input_df['Batter_Viscosity']
    cluster_list=input_df['label']
    sample_name_list=input_df['Sample_Name']
    starch_viscosity=0
    cluster=0
    subset_df=None
    starch_quant=0
    vs=0
    sample_name=""
    active_sample_name=""
    output_df=pd.DataFrame()
    starch1_list=[]
    product_type1_list=[]
    starch2_list=[]
    product_type2_list=[]
    ratio1_list=[]
    ratio2_list=[]
    clust_list=[]
    vs1_list=[]
    vs2_list=[]
    sample_name1_list=[]
    sample_name2_list=[]

    for index in range(len(starch_list)):
        if starch==starch_list[index]:
            cluster=cluster_list[index]
            input_starch_vs=viscosity_list[index]
            prod_type=input_df['Product_Type'][index]
            sample_name=sample_name_list[index]
            subset_df=input_df[input_df['label']==cluster]
            subset_df=subset_df.reset_index()
            subset_df.drop('index',axis=1,inplace=True)

            break

    if input_starch_vs<=5.75:
        for index in range(len(subset_df)):
            if subset_df['Batter_Viscosity'][index]>6:
                vs=subset_df['Batter_Viscosity'][index]
                active_sample_name=subset_df['Sample_Name'][index]
                active_starch=subset_df['Product_Base'][index]
                starch2_list.append(active_starch)
                product_type2_list.append(subset_df['Product_Type'][index])
                amount_1,amount_2=compute_mixture_ratio(input_starch_vs,vs,total_quant,final_viscosity)
                ratio1_list.append(amount_1)
                ratio2_list.append(amount_2)
                clust_list.append(cluster)
                starch1_list.append(starch)
                product_type1_list.append(prod_type)
                sample_name1_list.append(sample_name)
                sample_name2_list.append(active_sample_name)
                vs1_list.append(input_starch_vs)
                vs2_list.append(vs)

    elif input_starch_vs>=6.75:

        for index in range(len(subset_df)):
            if subset_df['Batter_Viscosity'][index]<6 :
                vs=subset_df['Batter_Viscosity'][index]
                active_starch=subset_df['Product_Base'][index]
                active_sample_name=subset_df['Sample_Name'][index]
                starch2_list.append(active_starch)
                product_type2_list.append(subset_df['Product_Type'][index])
                amount_1,amount_2=compute_mixture_ratio(input_starch_vs,vs,total_quant,final_viscosity)
                ratio1_list.append(amount_1)
                ratio2_list.append(amount_2)
                clust_list.append(cluster)
                starch1_list.append(starch)
                product_type1_list.append(prod_type)
                sample_name1_list.append(sample_name)
                sample_name2_list.append(active_sample_name)
                vs1_list.append(input_starch_vs)
                vs2_list.append(vs)

    else:
        for index in range(len(subset_df)):
            if (subset_df['Batter_Viscosity'][index]<(input_starch_vs-1)):
                vs=subset_df['Batter_Viscosity'][index]
                active_starch=subset_df['Product_Base'][index]
                active_sample_name=subset_df['Sample_Name'][index]
                starch2_list.append(active_starch)
                product_type2_list.append(subset_df['Product_Type'][index])
                amount_1,amount_2=compute_mixture_ratio(input_starch_vs,vs,total_quant,final_viscosity)
                ratio1_list.append(amount_1)
                ratio2_list.append(amount_2)
                clust_list.append(cluster)
                starch1_list.append(starch)
                product_type1_list.append(prod_type)
                sample_name1_list.append(sample_name)
                sample_name2_list.append(active_sample_name)
                vs1_list.append(input_starch_vs)
                vs2_list.append(vs)

    # Updating dataframe
    output_df['Cluster']=clust_list
    output_df['Starch_1']=starch1_list
    output_df['Product_Type_1']=product_type1_list
    output_df['Sample_Name_1']=sample_name1_list
    output_df['Batter1_Viscosity']=vs1_list
    output_df['Starch_2']=starch2_list
    output_df['Product_Type_2']=product_type2_list
    output_df['Sample_Name_2']=sample_name2_list
    output_df['Batter2_Viscosity']=vs2_list
    output_df['Ratio_1']=ratio1_list
    output_df['Ratio_2']=ratio2_list

    return(output_df)

def compute_mixture_ratio(starch_1_vs,starch_2_vs,total_quant,final_viscosity):

    amount_1=(total_quant*final_viscosity-total_quant*starch_2_vs)/(starch_1_vs-starch_2_vs)
    amount_2=total_quant-amount_1
    return(amount_1,amount_2)

The above code is the formulated code for which we are finding the mixing proportion using Batter Viscosity , now we need to include moisture and volume ,need help in finding how
Below is the dataframe and the code for the final dataframe
unique_starches_list=list(set(computed_dist_df.Product_Base))

unique_starches_list=['Tapioca and Waxy Tapioca','Potato','Rice','Waxy Maize/Waxy Wheat']

final_df=pd.DataFrame()

for active_starch in unique_starches_list:
    df=mixture_proportion(computed_dist_df,active_starch,final_viscosity=5.75)
    final_df=pd.concat([final_df,df])

final_df=final_df.reset_index()
final_df.drop('index',inplace=True,axis=1)

final_df_6=final_df.copy()

Similarly we have final_df_5 for final viscosity value 6.75
final_df=pd.DataFrame()

for active_starch in unique_starches_list:
    df=mixture_proportion(computed_dist_df,active_starch,final_viscosity=6.75)
    final_df=pd.concat([final_df,df])

final_df=final_df.reset_index()
final_df.drop('index',inplace=True,axis=1)

final_df_5=final_df.copy()

Now we find the ratio of the same
final_df['Ratio_1_Min']=final_df_5['Ratio_1']
final_df['Ratio_1_Max']=final_df_6['Ratio_1']
final_df['Ratio_2_Min']=final_df_5['Ratio_2']
final_df['Ratio_2_Max']=final_df_6['Ratio_2']

We will drop the columns that are not relevant
final_df.drop(['Ratio_1','Ratio_2'],axis=1,inplace=True)

Final Data frame
final_df


text:
Q: Print history list with ocaml utop Is there a way to print the history list in utop, like calling history from bash?  I haven't found any sort of history ring associated with utop-mode in emacs either.  I'm trying to use the history to hippie-expand against in the REPL.
Utop appears to respond to commands like history-prev and history-next (from utop.el), but that is all I have found.

A: This
μ> #require "lambda-term";;
μ> LTerm_history.contents UTop.history;;

will print out your utop history as an OCaml list of strings with the first element being the latest command you've executed (which is unsurprisingly
 "LTerm_history.contents UTop.history;;").
Note: you can add #require "lambda-term";; into your .ocamlinit file to skip the first command in the above listing.
There is also ~/.utop-history file, if you'd like to use some system utilities to access your utop history.


text:
Q: Customize the djoser create user endpoint I am using djoser for auth purposes. I want to customize the create user end point of djoser. I have a User app. Here is my User model
from django.db import models

class User(models.Model):
    email = models.CharField(max_length=100, blank=False)
    name = models.CharField(max_length=100, blank=False)
    last_name = models.CharField(max_length=100, blank=False)
    account_address = models.CharField(max_length=30, blank=False)
    password = models.CharField(max_length=100, blank=False)

and here is my serializer
from rest_framework import serializers
from User.models import User

class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ('url', 'id', 'email', 'name', 'last_name', 'account_address', 'password')

and my User.urls.py looks like following
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter

from .views import UserViewSet

router = DefaultRouter()

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^account/', include('djoser.urls')),
]

and project's url.py is follwing
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^users/', include('User.urls')),
    url(r'^advertisements', include('advertisements.urls')),
    url(r'^account', include('wallet.urls')),
]

but i am unable to create user with customized model instead when i go to user/account/create i see djoser's default create user view. Anybody please tell where I am doing wrong. Thanks :)

A: For me, I wanted to write a custom create method and it worked when I override user_create_password_retype and used mine since this is internally using the UserCreateSerializer from djoser
DJOSER = {
      ...
    "SERIALIZERS": {
        "user_create": "account.serializers.user_serializer.CustomUserCreateSerializer",
        "user": "account.serializers.user_serializer.CustomUserSerializer",
        "user_create_password_retype": "account.serializers.user_serializer.UserCreatePasswordRetypeSerializer",
    }
      ...
}

Other settings -
AUTH_USER_MODEL to your custom User model.

A: Having in mind that you have set the AUTH_USER_MODEL to your User model.
Just import the Djoser User Registration Serializer And override it.
from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer

class UserRegistrationSerializer(BaseUserRegistrationSerializer):
    class Meta(BaseUserRegistrationSerializer.Meta):
        fields = ('url', 'id', 'email', 'name', 'last_name', 'account_address', 'password', )

You can also override other things in the serializer like create and update methods in case if you want to customize it.
And in settings.py
DJOSER = {
    ...
    'SERIALIZERS': {
         'user_create': 'yourapp.serializer.UserRegistrationSerializer'
    }
    ...
}


text:
Q: Error trying change font in Android Studio I'm starting in Android development and I got myself stocked in a problem...
I am trying to change the font of a Button in Android Studio, I've followed some tutorials closely but it didn't work.
Tutorials I followed:
Error trying to change font android studio
How to change the font on the TextView?
I don't receive any error message, it just doesn't work. Does anyone have any idea what I could be doing wrong?
Code:
    Typeface font = Typeface.createFromAsset(getAssets(), "fonts/jua.ttf");

    Button Button = (Button) findViewById(R.id.Button)
    Button.setTypeface(font);

XML:
    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@drawable/my_button_bg"
        android:text="Button"
        android:textColor="@android:color/white"
        android:textSize="15sp" />

Image of structure of folders:
Structure of folder - image

A: Have you tried inserting your font in res/font directory and loading it as @font/myfont or R.font.myfont.
API 26 introduced this feature and you can find complete guide here:
https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml


text:
Q: column "e" of relation "analysis_result" does not exist connection to postgresql database has been connected successfully.but while executing below query i am getting some kind of error which looks like :
column "e" of relation "analysis_result" does not exist
LINE 1: INSERT INTO analysis_result(user_id,E,A,C,N,O,total) VALUES ...
        cursor = connection.cursor()
        print("inside execution ")
        cursor.execute("INSERT INTO analysis_result(user_id,E,A,C,N,O,total) VALUES (%s,%s,%s,%s,%s,%s,%s)",Result_lst)

i understand what is the error .i have to put each of E A C N O in quotes but while quoting them my sql query becomes invalid .Please give me a solution i am scraching my head for quite sometime now.
and Result_lst=[1,20,14,14,38,8]. Result_lst will be dyanamic values in integer forms.

A: If the column name contains upper case characters, you must surround it with double quotes, otherwise PostgreSQL will fold it to lower case (note the error message).
But you cannot simply use double quotes because that's what you used for the Python string.
Either use single quotes with the Python string:
cursor.execute('INSERT INTO analysis_result(user_id,"E","A","C","N","O",total) ...', Result_lst)

or escape the double quotes:
cursor.execute("INSERT INTO analysis_result(user_id,\"E\",\"A\",\"C\",\"N\",\"O\",total) ...", Result_lst)


text:
Q: A generic trait in Java In my project I have multiple strictly ordered types and I need them all to support a range operation - given two boundary values, return the list of all intermediary values.
To not repeat myself, I though I would create a "trait" like the following, which would declare the corresponding primitive operations and build a range method on top.
public interface Navigable {

    public Navigable previous() throws UnsupportedOperationException;

    public boolean isFirst();

    public Navigable next() throws UnsupportedOperationException;

    public boolean isLast();

    public boolean precedes(Navigable other);

    public default List<Navigable> range(Navigable to) {

        Navigable from = this;

        boolean invert = to.precedes(from);
        if (invert) {
            Navigable tmp = from;
            from = to;
            to = tmp;
        }

        List<Navigable> result = new LinkedList<>();

        while (from.precedes(to)) {
            result.add(from);
            from = from.next();
        }

        result.add(to);

        if (invert) {
            reverse(result);
        }

        return result;
    }
}

However, with such an interface, I need to implement the operations like this:
public class Item implements Navigable {
    ...
    @Override
    public boolean precedes(Navigable other) {
        ...
    }
    ...
}

Which is, of course, incorrect. What I need is the following.
public class Item implements Navigable {
    ...
    @Override
    public boolean precedes(Item other) {
        ...
    }
    ...
}

Hopefully what I'm trying to achieve is clear. What is the correct way to do this?

A: You have to make your interface generic and change a bit the abstract methods.
For example:
public interface Navigable<T extends Navigable> {
    ...
    public boolean preceeds(T other);
    ..
}

Then, when you implement the interface, you will be able to do (without any compilation errors):
public class Item implements Navigable<Item> {
    ...
    @Override
    public boolean preceeds(Item other) {
        ...
    }
    ...
}


text:
Q: When to fetch data from API via Vuex again to keep the data up to date I'm fetching data from an API and want to achieve it via Vuex. So my users store module is holding and managing all users.
To fetch all users I have a fetch action which calls the API via Axios and passes the users array from the response to the mutation.
I have a view component at /users which renders a list of users. Within that component I call
async mounted() {
  await this.fetch();
}

to initialize the store. After that, the store getter will return the users array and the list gets rendered. I know that I can also fetch one item by id via getter
getById: state => id => state.users.find(user => user.id === id)
When navigating to a user detail page /users/:id I can make use of it, extract the userId via this.$router.currentRoute.params.id and render the user details. But what if I load that route directly? Then the store initialized with an empty users array and it won't find a single user.
So should I fetch all users again in the mounted hook of that user details view? I think calling the axios service directly would be an anti pattern because the resources say I should use Vuex as an interface between the component and the API.
Is there a best practise when to fetch all users from the api? Because let's image you navigate to another page which loads all users in a select component, should I fetch them from the getter? Maybe it will load a user that doesn't exist anymore. But polling all users every X seconds would be bad too...
What is the correct way to update the store data to make it accessible for all components in the entire application?

A: I don't agree that Vuex should be used to store an entire tables worth of user data in the manner you described. This sounds like a security concern to me. Remember that Vuex is a client-side store; meaning all your user data would be visible to any client using your application. You should never store sensitive data client-side.
Type this into your browser console, and you'll see what I mean.
document.getElementsByTagName('a')[0].__vue__.$store.state

Vuex should be used for storing non-sensitive data of an individual user required to drive their session.
If you are storing all user data for the purpose of listing accounts so that they can be managed by an admin or something, then I would instead, make that API call on demand when you load whatever view you have which lists your user accounts. This way you will always have the most up-to-date data, without the need for constantly polling your API.
I would paginate that data, loading only the first 5 records (to keep the API call initially light), then provide your admins the ability to search for accounts; that searching should be done server side, through your API.
Example:
methods: {
    fetchUsers(limit, page, search) {
        const thisIns = this;
        if (search) {
            this.userQuery = `/users/find?search=${search}`
        } else {
            this.userQuery = `/users/find?limit=${limit}&page=${page}`
        }
        thisIns.$http.get(this.userQuery)
            .then(async (response) => {
                console.log(response.data)
            })
            .catch(function (error) {
                console.log(error)
            });
    }
},
created() {
    this.fetchUsers(5, 1)
},

You can then call your fetchUsers() method as needed, such as when performing a search for user(s).
Since you are using Axios, you can also consider implementing a caching mechanism, axios-cache-adapter, so that your API calls are cached for some period of time you define. This would reduce the number of API calls hitting your server.
I also don't consider this to be scaleable. Remember that an application user will have to wait for this payload when they first load your app. This also has performance implications; as your user data grows over time, you'll be consuming more and more of the devices RAM.


text:
Q: Is WPF the best solution for C# GUIs? I was working with Windows Forms for a while now, and due to certain limitations on Forms, I want to work my way up to a better way of making GUIs. I found WPF, which looks pretty promising, but I'm asking you guys, if there are any better ways for doing nice GUIs for Windows with C#?
Thanks in advance!

A: I would look for MS roadmaps and instructions where they plan to drive the platform. For example:
.NET Technology Guide for Business Applications
This is since nov 2013 but still valid to a large degree. Among other things it states that (emphasis mine):

.NET Windows Presentation Foundation
    This is the preferred technology for Windows-based desktop applications that require UI complexity, styles
  customization, and graphics-intensive scenarios for the desktop. WPF also takes advantage of XAML views.
  And WPF development skills are similar to Windows Store development skills, so migration from WPF to
  Windows Store apps is easier than migration from Windows Forms.

HTML5&JS-based apps is an alternate route but I consider it inferior for development efficiency and maintainability reasons. If you are a scripting fella, then it's worth a look.
By my experience WPF is definitely the way to go for desktop development.

A: There is definitely a learning curve migrating from Forms development to WPF, but in my opinion the effort is well worth it, and not simply because WPF is aesthetically different to Windows Forms.
WPF encourages you along the MVVM ("Model-View-View model") path and a separation of concerns between UI, logic and data elements. As an aside, MVVM is one of a number of MV* architectural patterns - there's some debate about what constitutes the difference between the different patterns, but consensus that separation of concerns is absolutely a good thing.  For example:
http://www.infoworld.com/article/2926003/microsoft-net/exploring-the-mvc-mvp-and-mvvm-design-patterns.html
https://nirajrules.wordpress.com/2009/07/18/mvc-vs-mvp-vs-mvvm/
What is difference between MVC, MVP & MVVM design pattern in terms of coding c#
In terms of specific advantages over Forms, there's a lot of stuff you get out-of-the-box with WPF, like two-way data-binding and UI threading for instance.  But I found that the change in thinking about problems is equally valuable; when I started thinking in MVVM, things like asynchronous programming (e.g. calling web services from windows-based client applications) just became much easier to conceptualise and reason about.
MV* is all the rage in web development, too, so the skills (and, in an ideal world, some of the code) are transferable  to the web.