Q: C# item Drag Fix I move three controls using this code on MouseMove Event :
if (inHareket)
{
    GelenResimcik.Left = e.X + GelenResimcik.Left -MouseDownLocation.X;
    GelenResimcik.Top = e.Y + GelenResimcik.Top - MouseDownLocation.Y;
    GelenResimcik.BackColor = Color.Transparent;
    ResimHareket.Left = e.X + ResimHareket.Left - MouseDownLocation.X;
    ResimHareket.Top = e.Y + ResimHareket.Top - MouseDownLocation.Y;
    Yonlendir.Left = e.X + Yonlendir.Left - MouseDownLocation.X;
    Yonlendir.Top = e.Y + Yonlendir.Top - MouseDownLocation.Y;

    Aktar.Left = e.X + Aktar.Left - MouseDownLocation.X;
    Aktar.Top = e.Y + Aktar.Top - MouseDownLocation.Y;

    Vazgec.Left = e.X + Vazgec.Left - MouseDownLocation.X;
    Vazgec.Top = e.Y + Vazgec.Top - MouseDownLocation.Y;
}

and if I try move them faster the result is :
Notice : When i stop moving, the glow is not visible, it is only moving faster.
What shall I do?
EDIT :
My Controls
this.Yonlendir = new System.Windows.Forms.PictureBox();
this.Vazgec = new System.Windows.Forms.PictureBox();
this.Aktar = new System.Windows.Forms.PictureBox();
this.ResimHareket = new System.Windows.Forms.PictureBox();
this.GelenResimcik = new System.Windows.Forms.PictureBox();

My Init :
        ((System.ComponentModel.ISupportInitialize)(this.Yonlendir)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.Vazgec)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.Aktar)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.ResimHareket)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.GelenResimcik)).BeginInit();
            this.SuspendLayout();
  //
            // Yonlendir
            //
            this.Yonlendir.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
            this.Yonlendir.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.Yonlendir.Image = global::Surface.Properties.Resources.rotate;
            this.Yonlendir.Location = new System.Drawing.Point(26, 74);
            this.Yonlendir.Name = "Yonlendir";
            this.Yonlendir.Padding = new System.Windows.Forms.Padding(5);
            this.Yonlendir.Size = new System.Drawing.Size(30, 30);
            this.Yonlendir.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.Yonlendir.TabIndex = 14;
            this.Yonlendir.TabStop = false;
            this.Yonlendir.Click += new System.EventHandler(this.Yonlendir_Click);
            //
            // Vazgec
            //
            this.Vazgec.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
            this.Vazgec.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.Vazgec.Image = global::Surface.Properties.Resources.iptal;
            this.Vazgec.Location = new System.Drawing.Point(93, 8);
            this.Vazgec.Name = "Vazgec";
            this.Vazgec.Padding = new System.Windows.Forms.Padding(5);
            this.Vazgec.Size = new System.Drawing.Size(30, 30);
            this.Vazgec.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.Vazgec.TabIndex = 13;
            this.Vazgec.TabStop = false;
            this.Vazgec.Click += new System.EventHandler(this.buton1_Click);
            //
            // Aktar
            //
            this.Aktar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
            this.Aktar.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.Aktar.Image = global::Surface.Properties.Resources.kaydet;
            this.Aktar.Location = new System.Drawing.Point(57, 8);
            this.Aktar.Name = "Aktar";
            this.Aktar.Padding = new System.Windows.Forms.Padding(5);
            this.Aktar.Size = new System.Drawing.Size(30, 30);
            this.Aktar.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.Aktar.TabIndex = 12;
            this.Aktar.TabStop = false;
            this.Aktar.Click += new System.EventHandler(this.Onayla_Click);
            //
            // ResimHareket
            //
            this.ResimHareket.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
            this.ResimHareket.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.ResimHareket.Image = global::Surface.Properties.Resources.hareket;
            this.ResimHareket.Location = new System.Drawing.Point(26, 38);
            this.ResimHareket.Name = "ResimHareket";
            this.ResimHareket.Padding = new System.Windows.Forms.Padding(5);
            this.ResimHareket.Size = new System.Drawing.Size(30, 30);
            this.ResimHareket.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.ResimHareket.TabIndex = 11;
            this.ResimHareket.TabStop = false;
            this.ResimHareket.Click += new System.EventHandler(this.ResimHareket_Click);
            this.ResimHareket.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ResmiHareket_MouseDown);
            this.ResimHareket.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ResmiHareket_MouseMove);
            this.ResimHareket.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ResimHareket_MouseUp);
            //
            // GelenResimcik
            //
            this.GelenResimcik.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
            this.GelenResimcik.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            this.GelenResimcik.Location = new System.Drawing.Point(57, 39);
            this.GelenResimcik.Name = "GelenResimcik";
            this.GelenResimcik.Size = new System.Drawing.Size(438, 452);
            this.GelenResimcik.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.GelenResimcik.TabIndex = 2;
            this.GelenResimcik.TabStop = false;

My Timer (Interval 100):
  private void ResimKontrol_Tick(object sender, EventArgs e)
        {
            try
            {
                if (ontanimli.Height != 0)
                {
                    GelenResimcik.Image = ontanimliGelen;
                    GelenResimcik.Parent = cizim;
                    entegreGoster();

                  }
            }
            catch
            {

            }

        }

entegreGoster and entegreGizle
public void entegreGoster() { GelenResimcik.BringToFront();ResimHareket.BringToFront();Aktar.BringToFront();Vazgec.BringToFront(); Yonlendir.BringToFront(); }
        public void entegreGizle() { GelenResimcik.SendToBack(); ResimHareket.SendToBack(); Aktar.SendToBack(); Vazgec.SendToBack(); Yonlendir.SendToBack(); }

My MouseDown event :
 private void ResmiHareket_MouseDown(object sender, MouseEventArgs e)
        {
            MouseDownLocation = e.Location;
            inHareket = true;
        }

I start timer when Open new form
Ontanimlilar ontanimli = new Ontanimlilar();
            ontanimli.Show();
            ResimKontrol.Start();

ontanimliGelen (public static pictureBox)
ontanimli  Class :
Ciz.ontanimliGelen = seciliRes.Image;
this.Close();


Q: Insert Element between each List element Is there a better way to insert an Element between each pair of elements into a List in Java than iterating through it
List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1,2,3,5,8,13,21));

for (int i = 1; i < exampleInts.size(); i++) {
    int delimiter = 0;
    exampleInts.add(i, delimiter);
    i++;
}

A: No, there is no ready utils for this in standard java libraries.
BTW, your loop is incorrect and will work infinitely until memory end. You should increment i variable one more time:
    for (int i = 1; i < exampleInts.size(); i++) {
        int delimiter = 0;
        exampleInts.add(i, delimiter);
        i++;
    }

or change loop conditions to for (int i = 1; i < exampleInts.size(); i+=2) {

A: Try this solution it is working correctly.
List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1, 2, 3, 5,
            8, 13, 21));
    int size = (exampleInts.size()-1)*2;
    for (int i = 0; i < size; i+=2) {
        int delimiter = 0;
        exampleInts.add(i+1, delimiter);
    }
    System.out.println(exampleInts);


Q: Another way to compute $\lim\limits_{x\to+\infty}x^2\log\left(\frac{x^2+1}{x^2+3}\right)$ I need to compute as a title a limit with $x\to+\infty$. The only way I found to obtain a result is to use the L'Hôpital's rule:
$$\lim\limits_{x\to+\infty}x^2\log\bigg(\frac{x^2+1}{x^2+3}\bigg)=\lim\limits_{t\to 0}\frac{1}{t^2}\log\bigg(\frac{1+t^2}{1+3t^2}\bigg)\stackrel{H}{=}\lim\limits_{t\to 0}\frac{1}{2t}\bigg(\frac{2t}{1+t^2}-\frac{6t}{1+3t^2}\bigg)=\lim\limits_{t\to 0}\bigg(\frac{1}{1+t^2}-\frac{3}{1+3t^2}\bigg)=-2$$
It seems the result is the difference between the two functions inside the log, but how this can be possible? Is there another way to compute these type of limits? I mean a calculus way without using theorems.

A: You can write
$$x^2 \ln \left( \frac{x^2+1}{x^2+3} \right) = x^2 \ln \left( 1- \frac{2}{x^2+3} \right) \sim x^2 \times \frac{-2}{x^2+3}$$
So the limit is $-2$.

A: If it is OK for you to calculate directly a derivative then you may proceed as follows:

*

*Set $x^2 = \frac{1}{t}$ and consider $t\to 0^+$
So, you get
\begin{eqnarray*}x^2\log\bigg(\dfrac{x^2+1}{x^2+3}\bigg)
& \stackrel{x^2 = \frac{1}{t}}{=} & \frac{\log \frac{1+t}{1+3t}}{t}\\
& = &\frac{\log (1+t) - 0}{t} - \frac{\log (1+3t) - 0}{t} \\
& \stackrel{t \to 0^+}{\longrightarrow} & \left. \frac{d}{dt}\log(1+t) \right|_{t=0} - \left. \frac{d}{dt}\log(1+3t) \right|_{t=0} \\
& = & \frac{1}{1+0} - \frac{3}{1+3 \cdot 0} = \boxed{-2}
\end{eqnarray*}
Another way is using

*

*$(1-y)^{\frac{1}{y}}\stackrel{y \to 0}{\longrightarrow} e^{-1}$
So,
\begin{eqnarray*}x^2\log\bigg(\dfrac{x^2+1}{x^2+3}\bigg)
& \stackrel{x^2 = \frac{1}{t}}{=} & \frac{\log \frac{1+t}{1+3t}}{t}\\
& = & \log \left(1 - \frac{2t}{1+3t}\right)^{\frac{1}{t}} \\
& = & \log \left( \left(1 - \frac{2t}{1+3t}\right)^{\frac{1+3t}{2t}}\right)^{\frac{2t}{1+3t}\cdot \frac{1}{t}} \\
& \stackrel{t \to 0^+}{\longrightarrow} & \log \left(e^{-1}\right)^2  = \boxed{-2}\\
\end{eqnarray*}

A: Hint
Use $$\lim_{h\to0}\dfrac{\ln(1+h)}h=1$$
for $h=t^2,3t^2$ to get the limit $=1-3$

A: Alternatively:
$$\lim_{x\to+\infty} x^2 \ln \left(\frac{x^2+1}{x^2+3}\right)=\\
\lim_{x\to+\infty} \ln \left(\frac{x^2+1}{x^2+3}\right)^{x^2}=\\
\ln \left[\lim_{x\to+\infty} \left[\left(1+\frac{-2}{x^2+3}\right)^{\frac{x^2+3}{-2}}\right]^{\frac{-2x^2}{x^2+3}}\right]=\\
\ln e^{\lim_\limits{x\to+\infty} \frac{-2x^2}{x^2+3}}=\\
\ln e^{-2}=-2.$$

A: \begin{align}\lim_{x\to\infty}x^2\log\left(\frac{x^2+1}{x^2+3}\right)&=\lim_{x\to\infty}x\log\left(\frac{x+1}{x+3}\right)\\&=\lim_{x\to0}\frac{\log\left(\frac{x+1}{3x+1}\right)}x.\end{align}So, compute $f'(0)$, where $f(x)=\log\left(\frac{x+1}{3x+1}\right)$.

A: Let $z:=x^2+3$ and
$$\lim_{z\to\infty}\left((z-3)\log\frac{z-2}{z}\right)=\lim_{z\to\infty}\left(z\log\left(1-\frac2{z}\right)\right)
=\log\left(\lim_{z\to\infty}\left(1-\frac2{z}\right)^z\right)
\\=\log e^{-2}.$$

The term $-3$ can be ignored because the $\log$ vanishes.

A: Write
$$x^2\log\left(x^2+1\over x^2+3\right)=x^2\int_{x^2+3}^{x^2+1}{dt\over t}=-x^2\int_{x^2+1}^{x^2+3}{dt\over t}$$
and note that, since $1/t$ is strictly decreasing for $t\gt0$, we have
$${(x^2+3)-(x^2+1)\over x^2+3}\lt \int_{x^2+1}^{x^2+3}{dt\over t}\lt {(x^2+3)-(x^2+1)\over x^2+1}$$
Simplifying the numerators and remembering to reverse the directions of inequalities when multiplying by a negative quantity (namely $-x^2$), we have
$${-2x^2\over x^2+3}\gt-x^2\int_{x^2+1}^{x^2+3}{dt\over t}\gt{-2x^2\over x^2+1}$$
and the Squeeze Theorem does the rest.

A: $$x^{2}\ln\left(\frac{x^{2}+1}{x^{2}+3}\right)$$$$=\ln\left(\lim\limits_{x\to+\infty}\left(1+\left(\frac{x^{2}+1}{x^{2}+3}-1\right)\right)^{x^{2}}\right)$$$$=\ln\exp\left(-2\lim\limits_{x\to+\infty}\frac{x^{2}}{x^{2}+3}\right)=-2$$


Q: Displaying XML in JSF I have a method that gives back a formatted XML string. I want to show that on a JSF page in a nicely wrapped, readable way. I used this solution first.

<h:outputText value="myBean.xml"/>

The result is indented, but it doesn't wrap very long lines (with a lot of attributes for e.g.)
RichFaces is also available in my project. What would you suggest?
Thanks in advance,
Daniel

A: Not sure if I understand you right, but if it is a plain vanilla String with XML data which you want to display as-is in the JSF page, then the first logical step would be to escape the HTML entities so that it's not been parsed as HTML. You can use h:outputText for this, it by default escapes HTML entities (which is controllable by the 'escape' attribute by the way):
<h:outputText value="#{bean.xmlString}" />

Or if it is formatted and you want to preserve the formatting, then apply the CSS white-space:pre property on the parent HTML element.
Or if you want to add syntax highlighting (colors and so on), then consider a Javascript library which does the task. Googling "javascript xml syntax highlighting" should yield enough results.


Q: Salesforce1 take picture option in android not available I have a visualforce page on which one button is shown of name upload photo. What i want is, when user clicks on button there should be a pop up of name take picture.
In iOS it works perfectly, it gives two by default options
1) choose from existing
2) click a new picture
In android it gives option of gallery only but i want option of take picture also.
Kindly help.


Q: Understanding the slicing syntax in Numpy? I have an x dimensional matrix in Numpy.  For this example, I will use a 2x2 array.
np.array([[2, 2], [3,3]])

How would I alternate adding a row and column of some value so the result would look like:
array([[2, x, 3, x],
       [x, x, x, x].
       [2, x, 3, x],
       [x, x, x, x]])

This answer gives a helpful start by saying to set rows in a correctly-sized destination matrix b from a matrix a like so a[::2] = b but what does the ::2 do in the slicing syntax and how can I make it work on columns?
In short what do the x y and z parameters do in the following: a[x:y:z]?

A: If I understand what you want correctly, this should work:
import numpy as np
a = np.array([[2,2],[3,3]])
b = np.zeros((len(a)*2,len(a)*2))
b[::2,::2]=a

This 'inserts' the values from your array (here called a) into every 2nd row and every 2nd column
Edit:
based on your recent edits, I hope this addition will help:
x:y:z means you start from element x and go all the way to y (not including y itself) using z as a stride (e.g. 2, so every 2 elements, so x, x+2, x+4 etc up to x+2n that is the closest to y possible)
so ::z would mean ALL elements with stride z (or ::2 for every 2nd element, starting from 0)
You do that for each 'dimension' of your array, so for 2d you'd have [::z1,::z2] for going through your entire data, striding z1 on the rows and z2 on the columns.
If that is still unclear, please specify what is not clear in a comment.
One final clarification - when you type only : you implicitly tell python 0:len(array) and the same holds for ::z which implies 0:len(array):z.
and if you just type :: it appears to imply the same as : (though I haven't delved deep into this specific example)


Q: Is there a easy way to filter mulitfield in django's admin site? The Model:
class Person(Model):
  (...)
   fathers = models.ManyToManyField('Person', related_name="fathers_children",  blank=True)
   mothers = models.ManyToManyField('Person', related_name="fathers_children",  blank=True)
   sex = models.CharField(null=True, blank=True, max_length=1)

admin.py:
class PersonAdmin(admin.ModelAdmin):
  form = PersonAdminForm
  model = Person

  fields = ('last_name', 'birth_date','fathers','mothers')
  ordering = ['last_name','birth_date']

admin.site.register(Person, PersonAdmin)

(maybe I cut to much, but I think it is self descriptive)
Please don't think why person can have more than one father/mother - it is intentional.
And now when I enter to e.g /admin/person/836, got the form with two MultipleChoiceFields containing full list of persons.
I want to reduce both - fathers should contains males, mothers - females. But how to do it?

A: You can simply limit the queryset for those fields by overriding the init method in the PersonAdminForm class:
class PersonAdminForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(PersonAdminForm, self).__init__(*args, **kwargs)
        self.fields['fathers'].queryset = Person.objects.filter(sex='m')
        self.fields['mothers'].queryset = Person.objects.filter(sex='f')


Q: Adjusting of php.ini I know that it is possible to set parameters in php.ini like this:
error_log = "%sprogdir%/userdata/logs/%phpdriver%_error.log"

How can I properly run php using command line and set these parameters? Similarly:
php -c path/to/php/ini [here something like this: %sprogdir%=path1 %phpdriver%=path2]

A: Are you looking to be able to export a parameter to environment variables using PHP? If so, the exec command may be what you're looking for: PHP: exec - Manual.
You'd execute something similar to this I believe:
<?php
    echo exec('export phpdriver=value');
?>

EDIT: Due to misunderstanding of the question.
To correctly answer the question, we are going to create a script to set some environment variables before executing some PHP from the command line.
Here is our example shell - php_runner.sh
#!/bin/bash
export progsdir=$1
export phpdriver=$2
php -c path/to/php/ini

Once this is created (remember to set correct permissions as well), we can execute it from command line as such:
/path/to/php_runner.sh path1 path2


Q: Dismatched image texture with geometry I have created a planegeometry and a texture which is made by ImageUtils with CanvasRenderer,
and then I created a mesh and finished all relative parameters'settings. The result is that a PlaneGeometry with the image
 texture in the space,but  a diagonal line is showed up,what's more, one image are divided into two
parts by this diagonal line,thus images on this two parts become dismatched.How should I resolve it? The key code are as follows:
    var planeGeo=new THREE.PlaneGeometry(2000,3000);
    var map = THREE.ImageUtils.loadTexture( 'images/greenLines.png' );
    map.wrapS=map.wrapT = THREE.RepeatWrapping;
    map.repeat.set(2,2);
    map.anisotropy = 16;
    var planeMaterial=new THREE.MeshBasicMaterial({color:0xFFBBEE,map:map,overdraw:true});
    var planeMesh=new THREE.Mesh(planeGeo,planeMaterial);
    planeMesh.position.set(2000,-2000,5000);
    scene.add(planeMesh);

NOTICE:the images are constructed by green lines.The result displays that lines are cut and one
line has become two lines which are located on two divided triangles .
Now how should I modify my code so that the two parts of  this image looks matched well without displacement!
Can the diagonal line be removed?


Q: Window in tkinter automatically closes I have some code here that I copied from the tkinter tutorials so I am sure it is 100% correct:
import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Hello World\n(click me)"
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",
                              command=self.master.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")

root = tk.Tk()
app = Application(master=root)
app.mainloop()

It is supposed to work but instead, when I run the program it shows the window for about 1 millisecond and then closes immediately. How do I fix this?
I am using Python 3.8.

A: mainloop() should be called on a tk.Tk object but in your code app is a tk.Frame object.  So, try ...
root.mainloop()


Q: Compare two files in two different folders and replace it by the newer With this VBScript code I was able to copy files. If the file exists it does nothing, if not it will copy the files needed.
Dim Photo
SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"
Set ObjPhoto = CreateObject("Scripting.FileSystemObject")

For Each Photo In ObjPhoto.GetFolder( SourceFolder).Files
    If Not ObjPhoto.FileExists(ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))) Then
        photo.Copy ObjPhoto.BuildPath(DistinationFolder, Photo.Name), True
    End If
Next

I want to compare the files if the source files also exists in the destination folder and replace it by the newer.

A: If you want to overwrite based on the last modified date, then the File object has the property you want: DateLastModified. (You can check all properties of the File object here.)
You already have access to the source file objects (your code's Photo variable) so you just need to get the target's file object.
Something like this should work:
Dim Photo
Dim targetFile, bmpTargetFilename, jpgTargetFilename

SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"

Set ObjPhoto = CreateObject("Scripting.FileSystemObject")

For Each Photo In ObjPhoto.GetFolder(SourceFolder).Files
    bmpTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))
    jpgTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Photo.Name)

    If ObjPhoto.FileExists(bmpTargetFilename) Then
        ' Get the target file object
        Set targetFile = ObjPhoto.GetFile(jpgTargetFilename)
        ' Now compare the last modified dates of both files
        If Photo.DateLastModified > targetFile.DateLastModified Then
            Photo.Copy jpgTargetFilename, True
        End If
    Else
        Photo.Copy jpgTargetFilename, True
    End If
Next

A couple of notes:

*

*It seems you are checking for the existence of a .BMP file yet copying a .JPG file, so I made it explicit by using two variables.

*I am also assuming you want to compare the JPG files, since those are the ones being copied.


Q: using cURL to retrieve JSON data for use with jQuery I've been reading this helpful post:
http://techslides.com/hacking-the-google-trends-api
It shows how you can use cURL in command line/terminal to request data from google trends, for example;
curl --data "ajax=1&cid=actors&geo=US&date=201310" http://www.google.com/trends/topcharts/trendingchart

Gives you a big block of what I think is JSON. Below is an example of what I am doing to use cURL within my PHP to get data like this- however I cannot find anything that would get the data from the above cURL command to work in PHP like below.
<?php
    //initialize session
    $url = "http://www.google.com/trends/hottrends/atom/feed?pn=p1";
    $ch = curl_init();
    //set options
    curl_setopt($ch, CURLOPT_URL, $url);
    //execute session
    $data = curl_exec($ch);
    echo $data;
    //close session
    curl_close($ch);
    ?>

How do I go about getting the data from above?

A: You can do the same with the PHP cURL extension. You just need to set the options through curl_setopt, so you would do something like this
$url = "http://www.google.com/trends/topcharts/trendingchart";
$fields = "ajax=1&cid=actors&geo=US&date=201310";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

Now you have the response of the website in $data and you can do whatever you want with it.
You can find the PHP cURL documentation on http://php.net/curl

A: Try this
// Complete url with paramters
$url = "http://www.google.com/trends/topcharts/trendingchart?ajax=1&cid=actors&geo=US&date=201310";

// Init session
$ch = curl_init();

// Set options
curl_setopt($ch, CURLOPT_URL, $url);

// Set option to return the result instead of echoing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Execute session
$data = curl_exec($ch);

// Close session
curl_close($ch);

// Dump json decoded result
var_dump(json_decode($data, true));


Q: How to prevent a click on the underlying element? How to prevent a click on the underlying element? When I hover the mouse over the board on the website https://08ce2429.my-trello-frontend.pages.dev/ - the label "Delete board" appears, when I click on it, the board is deleted, but the board page also opens. How to prevent this?
My code of the board element:
  return (
    <div key={props.id} className={`board-home id${props.id}`}>
      <Link
        className="board-link"
        to={{ pathname: '/board/' + props.id }}
        state={{ id: props.id }}
      >

{props.title}

 {
              try {
                e.stopPropagation()
                alert('stopPropagation')
              } catch (err) {
                alert(err)
              }
              //  (document.querySelector(`.id${props.id}`) as HTMLElement).style.pointerEvents = "none"
              deleteBoard((e.target as HTMLElement).getAttribute('id')!)
            }}
          >
            Delete board

      </Link>
      <Routes>
        <Route path="/board/:id" element={<Board />} />
      </Routes>

  )

stopPropagation() does not help.

A: Just use e.preventDefault() in onClick


Q: Why is it possible to set a value in a slice using reflection? According to The Laws of Reflection it is not possible to set the value of an element as follows, you need to use its address.
This will not work:
var x float64 = 3.4
v := reflect.ValueOf(x)
v.SetFloat(7.1) // Error: will panic.

This will work:
var x float64 = 3.4
p := reflect.ValueOf(&x) // Note: take the address of x.
p.Elem().SetFloat(7.1)

So why will the following work when using slices?
floats := []float64{3}

v := reflect.ValueOf(floats)
e := v.Index(0)
e.SetFloat(6)
fmt.Println(floats) // prints [6]

http://play.golang.org/p/BWLuq-3m85
Surely v.Index(0) is taking the value instead of address from slice floats, thus meaning it shouldn't be settable like the first example.

A: In your first example, you pass the actual x. This will copy x and give it to reflect.ValueOf. When you try to do v.SetFloat, as it get only a copy, it has no way to change the original x variable.
In your second example, you pass the address of x, so you can access the original variable by dereferencing it.
In the third example, you pass floats to reflect.ValueOf, which is a slice. "Slice hold references to the underlying array" (http://golang.org/doc/effective_go.html#slices). Which mean that through the slice, you actually have a reference to the underlying object. You won't be able to change the slice itself (append & co) but you can change what the slice refers to.


Q: Proxy error: Could not proxy request /send from localhost:3000 to http://localhost:3001/ I'm sending some data from my ReactJS front-end application to my node/express backend, however, whenever I send the data, I get the error message mentioned in the title.
https://ibb.co/KbpwqZv

contact.js

This is my react js code where i declare my react from those who communicate with backend via axios
import React, { useState } from 'react'
import "./Contact.css";
import Axios from 'axios';
import {API} from '../backend';

const Contact = () => {

 const [state,setState]= useState({
     name:'',
     lastname:'',
     email:'',
     message:'',
 })

    const [result,setResult] = useState(null);

    const sendMail = e =>{
        e.preventDefault();
        Axios.post('/send',{...state})
        .then(response => {
            setResult(response.data);
            setState({
                name:'',
                lastname:'',
                email:'',
                message:''
            })
        })
        .catch(()=>{
            setResult({
                success:false,
                message:"Something went wrong. Try again later"
            })
            setState("");
        })
    }

    const onInputChange = e =>{
        const {name,value} = e.target;

    setState({
        ...state,
        [name]: value
    })
}

    console.log("API is",API);
    return (
        <>
        {result && (
            <p className={`${result.success ? 'success' : 'error'}`}>
                {result.message}

        )}

CONTACT US

                    <form  >

                            Name
                            <input type="text"
                                name="name"
                                className="name"
                                placeholder="Your Name..."
                                value={state.name}
                                onChange={onInputChange}
                            />

                        {/*

                            LastName
                            <input type="text"
                                name="LastName"
                                className="LastName"
                                placeholder="Your Last Name..."
                                value={state.lastname}
                                onChange={onInputChange}
                            />

 */}

                            Email
                            <input type="email"
                                name="email"
                                className="email"
                                placeholder="Your Email..."
                                value={state.email}
                                onChange={onInputChange}
                            />

                            Message
                            <textarea name="message"
                                id=""
                                col="30"
                                rows="5"
                                placeholder="Your Message..."
                                value={state.message}
                                onChange={onInputChange}
                            >
                            </textarea>

Message has been Sent

                        <button type="button" className='btn btn-primary' onClick={sendMail}>Submit</button>
                    </form>

        </>
    )
}

export default Contact;


Q: How to mass update in Eloquent given an array of keys and values efficiently I have a very large (millions of rows) database table where I need to add some missing data from a 3rd party to every row.
The data source has a 'reference key' which is my only way to map to the correct item in the table
Each row needs 1 number updated
I can loop through the 3rd party data source and perform an eloquent Update to each row using a unique identifier, but this is very slow from my tests:
Orders
  id,  reference_key,  new_value
  int, string,         double(8,2)

foreach ($xml as $row) {
    Order::where('reference_key', $reference_key)
        ->update('new_value', (float)$row->new_value);
}

Is there a more efficient way I can do this?

A: I would do update statement to do all in once like this :
UPDATE OrderTable
INNER JOIN table_to_fill ON OrderTable.refkey = table_to_fill.refkey
SET OrderTable.value = table_to_fill.value

A: Eloquent is very powerfull to manage complicated relationship, joins, eager loaded models etc... But this abstraction has a performance cost. Each model have to be created, filled and saved, it is packed with tons of features you don't need for this precise use case.
When editing thousand or even millions of records, it is highly inefficient to use Eloquent models. Instead you can either use the laravel Query builder or a raw SQL statement.
I would recommend this approach:
$table = Db::table('orders');
foreach ($xml as $row) {
    $table->where('reference_key', $reference_key)
        ->update('new_value', (float)$row->new_value);
}

But you can also do something like this:
foreach ($xml as $row) {
    DB::statement('UPDATE orders SET new_value=? WHERE reference_key=?',
    [(float)$row->new_value, $reference_key]);
}

It will cut down your execution time significantly but the loop over millions of XML lines will still take a long time.


Q: How can i get the position in the Array list model class in the Observer using Live Data? Observer<ArrayList<ActionModel>> arrayListObserve=new Observer<ArrayList<ActionModel>>() {
            @Override
            public void onChanged(@Nullable ArrayList<ActionModel> actionModels) {
                Action1.setText(actionModels.get(position).getBackground_remarks());
            }
        };

here,i can get the  ActionModel class object but i can't get the position of the arraylist so how can i get the position of arraylist??


Q: Using repeat.vim for keymapping I'm trying to set a custom keymapping to do debug-stepping with gdb and pyclewn, like this:
nnoremap <leader>ds :Cstep<CR>

Now when pressing . I'd like this to be repeated, since stepping is probably something I'm going to do often. I found repeat.vim and a helpful SO answer, so I tried this:
nnoremap <silent> <Plug>CCstep :Cstep <bar> silent! call repeat#set("\<Plug>CCstep", v:count)<CR>
nmap <leader>ds <Plug>CCstep

I also tried using :Cstep<CR>:silent [...] instead of :Cstep <bar> silent to seperate the two commands.
Both variants don't seem to work. I either get a blinking screen (bell) when pressing . or something random happens, like some chars getting deleted.
What am I doing wrong?


Q: Shinydashboard 'topbar' Is it possible to place some items in the horizontal bar next to the dashboardHeader? I know you can place notificationItem on the far right like in this example. But I would like to use the same options as in dashboardSidebar like adding filters etc. I want such a filter on top:

A: Hi You can do something like this:
library(shiny)
library(shinydashboard)

CustomHeader <- dashboardHeader()
CustomHeader$children[[3]]$children <-  div(style="min-width:200px;",tags$input(id="searchbox",placeholder = "  Search...",type="text",class="chooser-input-search",style="width:200px;height:50px;"))

ui <- dashboardPage(
  CustomHeader,
  dashboardSidebar(),
  dashboardBody()
)
server <- function(input, output, session) {}
shinyApp(ui, server)

A: Based on Pork Chop answer, you can simply use selectInput (or other shiny inputs) that you put in a div with float:left to span horizontally:
CustomHeader <- dashboardHeader()
CustomHeader$children[[3]]$children <- list(
  div(style="float:left;height:50px",selectInput("select1", NULL, c("a","b","c"))),
  div(style="float:left;height:50px",selectInput("select2", NULL, c("d","e","f"))))

ui <- dashboardPage(
  CustomHeader,
  dashboardSidebar(),
  dashboardBody(textOutput("text1"),textOutput("text2"))
)

server <- function(input, output, session) {
  output$text1 <- renderText({input$select1})
  output$text2 <- renderText({input$select2})
}

shinyApp(ui, server)


Q: How to find gzip file is empty compressed file How to find gzip file is empty  using perl
a.txt.gz when i uncompress its empty
how to find the compress gz are empty ?

A: You can't directly get the size of the uncompressed file, but you can use seek for it. Create an object from the file and try to seek to the first byte. If you can seek, then your file is at least 1 byte in size, otherwise it is empty.
#!/usr/bin/env perl
use strict;
use warnings;
use IO::Uncompress::Gunzip;
use Fcntl qw(:seek);

my $u = IO::Uncompress::Gunzip->new('readme.gz');
if ( $u->seek(1, SEEK_CUR) ) {
    print "Can seek, file greather than zero\n";
}
else {
    print "Cannot seek, file is zero\n";
}

A: You could use IO::Compress::Gzip which comes with Perl 5.10 and above (or download it via CPAN). And use that to read the file.
However, you could just do a stat on the file and simply see if it contains only 26 bytes since an empty file will consist of just a 26 byte header.
I guess it simply depends what you're attempting to do. Are you merely trying to determine whether a gzipped file is empty or did you plan on reading it and decompress it first? If it's the former, stat would be the easiest. If it's the latter, use the IO::Compress::Gzip module and not a bunch of system commands to call gzip. The IO::Compress::Gzip comes with all Perl distributions 5.10 and greater, so it's the default way of handling Zip.

A: To check the content of a compressed tar-file, use
tar -ztvf file.tgz

To list content of a .gz-file, use
gzip --list file.gz

Wrap that in perl and check the uncompressed field in the output
$ gzip --list fjant.gz
         compressed        uncompressed  ratio uncompressed_name
                 26                   0   0.0% fjant


Q: Where does Authlite store the second factor? Authlite is an Active Directory extention to use second factors. They seem to have their own partition on a domain controller, and use global groups to manage their users.
So the question is where do they store the second factor information for each user? In an attribute of the user, so they manipulate the schema? In their application partition? Or do they have an extra location for that?

A: This is mentioned in the documentation:

AuthLite does not add or change any schema properties on the "user" or other built-in objects in Active Directory. All AuthLite data is stored separately in the AuthLite Application Partition. Adding the AuthLite schema elements will have no performance impact on user object replication since we don't touch those objects at all.


Q: Java Swing Window is Too Tall I am building a small application using Java Swing. The application will be used on several different computers. I am using a GridLayout. The problem is that the window is not adjustable since I show the gui like this:
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addComponentsToPane(getContentPane());
    pack();
    setVisible(true);

I am aware that pack() is causing this. The program works fine on my computer but the window is relatively tall. On some other computers the bottom is cut off so that the user cannot access some features. What is the best solution for this? I have thought of several approaches but none of them seem optimal:

*

*Rearrange the window so that this is not a problem.

*Add a scroll bar.

Unfortunately, I would like to keep the window structured as it is since it looks nice and is intuitive. I already have scroll bars for some selectors so I think adding a scroll bar for the window will look very cluttered and add confusion.
I would appreciate any suggestions. Thanks.

A: If you don't want to add a scroll bar, and you don't want to rearrange the widgets, then the only options left are

*

*Lay the items out on more than one window (two pages for example).

*Change the scaling of the items (shrink them)

There is not an infinite number of approaches.  The more approaches you decide are unsuitable will limit the opportunities to address the key issues.  In your case, you have two dramatically different screen layouts, the obvious solution would be to detect the screen parameters, and select one of two different layouts, each tailored to look good.

A: Too much controls in a window is much boring. So why don't you categorize the controls and add them in different tabs using JTabbedPane ?

A: I think this is more suitable. If this is not desired, then adding a scroll pane would be better. Well shrinking the controls may not be that helpful


Q: How to open iOS app from browser? I have to open my iOS app whenever user open a link of my app in browser. I have already used a like myApp://  but i want to open my app even when user open an http link a from browser. Just like pinterest. Pinterest opens app even if i open a regular http link like this http://www.pinterest.com/pseudoamber/ and using URL scheme as well like this  pinterest://www.pinterest.com/pseudoamber/. My app is opening on myApp://www.myapp.com now i want to open my app when user open an http link like this http://www.myapp.com
Anybody please help

A: Here is an example using jQuery:
$(document).ready(function() {

        var user_agent_header = navigator.userAgent;

        if(user_agent_header.indexOf('iPhone')!=-1 || user_agent_header.indexOf('iPod')!=-1 || user_agent_header.indexOf('iPad')!=-1){
            setTimeout(function() { window.location="myApp://www.myapp.com";}, 25);
        }

    });


Q: Ícones em CSS intermitente ao recarregar página Estou tendo problemas no carregamento de ícones, mas é raro e difícil de reproduzir o problema, pois ocorre de vez em quando na atualização com F5.
Só ocorre em ícones css do bootstrap ou de oura fonte css qualquer como o Ionicons.
Os css estão em arquivo.
Segue alguns exemplos de como está exibindo os ícones quando o problema ocorre.

Exemplo do css do arquivo "ionicons.css"
.ion-edit:before { content: "\f2bf"; }

Utilização da class no html

Inspecionando aqui a tela o css carregou desse jeito:
.ion-edit:before {  content: "ïŠ¿";}

Agradeço quem puder ajudar.
EDIT:
Os arquivos css estão configurados em bundleconfig.json do Asp .NET Core para realizar o minifier e são inseridos em apenas um cshtml de layout.

A: Resolvi aqui.
Alterei duas coisas.
A primeira era que um dos arquivos de css não estava explícito o tipo de charset a ser usado e aí o .net atribui um charset default do windows. Deixei explícito para usar UTF-8.

@charset "UTF-8";

E Segundo é que os arquivos css dos ícones estavam todos configurados para um mesmo arquivo Minifier no bundleconfig.json junto com vários outros css, somente após isolar os arquivos na configuração para serem únicos no minifier o problema parou de ocorrer.


Q: laravel validate conditional image field i have a field that required, and can be 2 value type : String (path) and Image file
how can write validation rule for this ?
if value is string check file_exist and if is file must be image
thanks

A: Maybe there's an easier way to do this. However, I think a custom rule as such should work.
$validator = Validator::make($request->all(), [
    'image' => [
        'required',
        function ($attribute, $value, $fail) {
            if(is_file($value)) {
                if (true !== mb_strpos($value->getMimeType(), "image")) {
                    return $fail($attribute.' is invalid.');
                }
            }
            if (is_string($value)) {
                if(! file_exists($value)) {
                    return $fail($attribute.' is invalid.');
                }
            }
        },
    ],
]);

A: i found my answer with FormRequest
MyTestFormRequest
<?php
use Illuminate\Foundation\Http\FormRequest;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class MyTestFormRequest extends FormRequest
{
    public function rules()
    {
        $rules = [
            "image" => ['required']
        ];
        if(is_string($this->image)) {
            $rules['image'][] = new FileExistsRule;
        } else if($this->image instanceof UploadedFile) {
            $rules['image'][] = 'image';
            $rules['image'][] = 'dimensions:ratio=1/1';
        }

        return $rules;
    }
}

FileExistsRule
<?php

use Illuminate\Contracts\Validation\Rule;

class FileExistsRule implements Rule
{
    public function passes($attribute, $value)
    {
        return file_exists(public_path($value));
    }

    public function message()
    {
        return 'The file not exists';
    }
}


Q: Catch Spotify app events in the background I'm observing changes on the Player model and console.logging the currently played song.
When I switch away from the app it works fine - but only for a minute or so.
Is there a way to keep the app alive?

A: Currently, the app object only lives on for 60 seconds after the context has been deselected.


Q: How to pass id from button to modal

Reply Query

            Name
            Title
            Description
            Photo
            Date
            Actions

            <?php for($i=1;$i<=12;$i++){?>

              'NAME'
              'Title'
              'Description'

              'dd/mm/yyyy'

                <input type="submit" value="   Reply" href="javascript:;" onclick="jQuery('#modal-6').modal('show', {backdrop: 'static'});" style="background-color: #313437;border:1px solid #313437" class="btn btn-primary btn-single btn-sm fa-input">
                <input type="text" hidden="" value="<?php echo $i;?>" name="id">
                </input>

              <?php }?>

This is my code of view data.when user click on reply button, i want to display modal.it displayed it but which button is clicked how i know?
i want to pass id to identified it so please help me how to pass it.

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Reply Query

                        Title
                            <input class="form-control" disabled="" name="question" data-validate="required" data-message-required="Please Enter Title" placeholder="Enter Title" type="text">

                        URL
                        <input class="form-control" name="url" disabled="" data-validate="required" data-message-required="Please Enter URL"  placeholder="Enter URL" type="text">

                            Description
                            <textarea class="form-control autogrow" id="description" placeholder="Describe Description Regarding Query"></textarea>

                        Image Upload

  Select image Change
                                    <input type="file" name="..." accept="image/*">  Remove

                <button type="button" class="btn btn-info">Send</button>
                <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>

This is the code of modal.

A: Will suggest more easy and less complicated approach and bootstrap framework will handle the rest.
replace following

    <input type="submit" value="   Reply" href="javascript:;" onclick="jQuery('#modal-6').modal('show', {backdrop: 'static'});" style="background-color: #313437;border:1px solid #313437" class="btn btn-primary btn-single btn-sm fa-input">
    <input type="text" hidden="" value="<?php echo $i;?>" name="id"></input>

With

    <button type="button" data-toggle="modal" data-target="#modal-6" data-id="This Is Id" class="btn btn-primary btn-single btn-sm fa-input">Reply</button>

Use data-toggle and data-target attributes to open the modal and with additional data-id attribute and show.bs.modal or shown.bs.modal modal events, can pass the value to modal
$(document).ready(function() {
  $('#modal-6').on('show.bs.modal', function(e) {
    var id = $(e.relatedTarget).data('id');
    alert(id);
  });
});

To keep the backdrop: 'static' add it in Modal HTML Markup

A: I have been inspirited by @Shehary but had to use it with little different syntax.
$(document).ready(function() {
  $('#modal-6').on('show.bs.modal', function(e) {
    var id = $(e.relatedTarget.id).selector;
    alert(id);
  });
});


Q: How to automatically setup Google Account in Android Emulator I am trying to do some Android Automation using Python/Appium on GitLab.
I have found the way to create and launch the Android Emulator using the command line options.
But when the emulator opens, it requires the Google Account Setup in order to use Play Store/Gmail etc.
Creating a script through Appium is possible but would be little bit tedious work.
Is there any simpler way using some command line configuration during the initial setup to automatically setup the Google Account
avdmanager create avd --force --name "MyEmulator" --package "system-images;android-31;google_apis_playstore;x86_64" --device "pixel"

A: I've found you just need to pipe echo "no" into avdmanager create then start the emulator.
Something like this:
echo "y" | sdkmanager "system-images;android-31;google_apis_playstore;x86_64"
echo "no" | avdmanager create avd -n MyEmulator -k "system-images;android-31;google_apis_playstore;x86_64"
emulator64-arm -avd MyEmulator -noaudio -no-window -accel on
sleep 300 # wait for avd to start
# or detect when booting is finished

See also: How to create Android Virtual Device with command line and avdmanager?
You'll also need to wait for the avd to start. You can either sleep for a reasonably long period of time or try something more sophisticated like polling adb -e shell getprop init.svc.bootanim to see if the output says "stopped" -- example reference.


Q: Click A button faster We are playing a clicker game on a website where a button will be displayed at a random time, first 7 players to click it will be shown as the winners of that round. I wrote the clicker function bellow and always use it on my Chrome console.
(function () {
  setInterval(() => {
    const button = document.querySelector(“.click-button);
    if (!button) return;
button.click();
   }, 5);
})();

I was playing it with mobile network of 50 - 70 mbps of  speed  and was among the top 5 until when other players started using VPS Machine which have over 4gbps of internet speed. I now have a VPS running Windows server 2022 but cant still perform better. So My question is, Is it that my VPS speed is slower than their own or My Laptop have less specification than their own or I need a better javascript code than the one above?
Running the above code on a VPS server with a download speed of 4.3gbps and upload speed of 4.1gbps through a browser console and click faster

A: Your code can be a little faster by caching the function and the button outside the interval
(function() {
  const button = document.querySelector(".click-button");
  const buttonClick = () => button.click();
  if (button) setInterval(buttonClick, 5);
})();

If the button does not exist at all, then the code above will not work. Then you do need the mutation oberver

A: Instead of polling for the button, you could use a MutationObserver that will notify you when the button changes or is inserted into the document. Unless you can get to the event that triggers the button activation, this is probably the fastest you can do.
Assuming that the button is inserted into a

:
const callback = mutations => {mutations.forEach(m => m.addedNodes.forEach(node => node.tagName === 'BUTTON' && node.click()))}
const observer = new MutationObserver(callback)
const container = document.getElementById('button-container')
observer.observe(container, {childList: true})

Have a look at this codepen
Replacing the forEach() with a for will give you a few additional nanoseconds.


Q: HTable.get(List) results order What is the order of the Result array returned by a call to HTable.get(List<Get>)?
I mean, is correct to assume that is the same order of the input list?

A: The order in the result array will be the same as the order of the input list. Like the batch method, the ordering of execution of the actions is not defined but the result will always be in the same order. Since it will have a null in the results array for gets that failed, it would have been difficult to determine which have failed without looking in each Result instance.


Q: Change colors of solid in drawable selector I have the following drawable:

<item android:state_pressed="true" android:text="texting .....">
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
        <stroke android:width="@dimen/circleStrokeThickness" android:color="@color/earlGreen" />
        <solid
            android:color="@color/lightGrey"/>

        <size
            android:width="100dp"
            android:height="100dp"/>
    </shape>
</item>

<item android:state_pressed="false" android:text="texting .....">
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
        <stroke android:width="4dp" android:color="@color/earlGreen" />
        <solid
            android:color="@android:color/white"/>

        <size
            android:width="100dp"
            android:height="100dp"/>
    </shape>
</item>

However, I need a number of similar one where the solid color is different but the rest is the same.
Is there any easy way to do this or should I just define a number of xml files?
I know it is possible to change the background color at runtime but I can't see how to get to the colour of a specific state.

A: You can define id for shape item <item android:id="@+id/shape_bacground"../> then at runtime you have to get background of your view and cast it to LayerDrawable and use findDrawableByLayerId() for find your shape and set it's color using
setColor(). Here is sample code:
drawable xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="@drawable/float_button_shadow1">
    </item>
    <item
        android:id="@+id/shape_bacground"
        android:bottom="2dp"
        android:left="1dp"
        android:top="1dp"
        android:right="1dp">
        <shape android:shape="oval" >
            <solid android:color="#1E88E5" />
        </shape>
    </item>

</layer-list>

Changing  color
try {
        LayerDrawable layer = (LayerDrawable) view.getBackground();

        GradientDrawable shape = (GradientDrawable) layer
                .findDrawableByLayerId(R.id.shape_bacground);
        shape.setColor(backgroundColor);// set new background color here
        rippleColor = makePressColor();
    } catch (Exception ex) {
        // Without bacground
    }

A:
You can do same thing by programatically, Where you can change any
  color at runtime by making function and passing Color in parameter.

ShapeDrawable sd1 = new ShapeDrawable(new RectShape());
                            sd1.getPaint().setColor(CommonUtilities.color);
                            sd1.getPaint().setStyle(Style.STROKE);
                            sd1.getPaint().setStrokeWidth(CommonUtilities.stroke);
                            sd1.setPadding(15, 10, 15, 10);

                            sd1.getPaint().setPathEffect(
                                    new CornerPathEffect(CommonUtilities.corner));
                            ln_back.setBackgroundDrawable(sd1);

Hope it will help you !


Q: Integrating Robolectric and Cucumber I want to combine both Robolectric and Cucumber (JVM).
Currently I have two classes ActivityStepdefs where two step definitions for activity management are defined.
My second class is RoActivity Where for example an activity is created from it's class name, and where Robolectric will be used.
When I run RoActivityTest using RobolectricTestRunner the test in this class passes, but when I run RunCukesTest (class for running features as junit test) the code from RoActivity is not running as part of Robolectric, i.e. RunCukesTest search for features on my project and match it with a method inside ActivityStepdefs and finally this class will call a method from RoActivity
Is possible to run test with both junit both* runners?
I'm not sure but perhaps it's possible to do something like powermock, using junit rules.
In that case for which one should I have to define the rule?
*Cucumber and Robolectric

A: My small 5 cents.
Cucumber is mostly used for acceptance tests (correct me if you use it for unit testing) and Robolectric is mostly used for unit testing.
As for me, it is overkill to write cucumber during TDD. And Robolectric is still not android and I would run acceptance tests on real device or at least emulator.

A: I'am facing the same problem, after some google work, I got a solution:
@RunWith(ParameterizedRobolectricTestRunner::class)
@CucumberOptions( features = ["src/test/features/test.feature","src/test/features/others.feature"], plugin = ["pretty"])
class RunFeatures(val index: Int, val name:String) {

    companion object {
        @Parameters(name = "{1}")
        @JvmStatic
        fun features(): Collection<Array<Any>> {
            val runner = Cucumber(RunFeatures::class.java)
            Cucumber()
            val children = runner.children
            return children.mapIndexed{index, feature ->
                arrayOf(index,feature.name)
            }
        }
    }

    @Test
    fun runTest() {
        val core = JUnitCore()
        val feature = Cucumber(RunFeatures::class.java).children[index]!!
        core.addListener(object: RunListener() {
            override fun testFailure(failure: Failure?) {
                super.testFailure(failure)
                fail("$name failed:\n"+failure?.exception)
            }
        })
        val runner = Request.runner(feature)
        core.run(runner)
    }
}

but seems not an pretty solution for me, can somebody help me out these problem:

*

*must explicitly list all feature file path. but cannot use pattern such as *.feature

*when failed cannot know which step failed.

*parameter can only pass primitive type data,

I've get into cucumber source , but seems CucumberOptions inline Cucumber , I cannot pass it programmatically but can only use annotation .


Q: What the best way to display html in the recyclerView? In the recyclerView I display comments. Comments are stored as HTML.
I tried to display the comments in webView - all displayed well (with the ability to use custom *.css) but recyclerView significantly retarding while scrolling. And I was not able to make it "transparent" to the touch, because commentView support ripple effect (android:background="?attr/selectableItemBackground") but webView - no.
Also I tried to display the comments in textView as spannable. Everything works fast but much more difficult to customize the appearance.
Help me to choose the best way to display the comments in recyclerView.
As a result I want to get something like this:

A: Here htmlString will is holding you html content.
TextView textView = (TextView)findViewById(R.id.tv_string);
 textView.setText(Html.fromHtml(htmlString));


Q: Inserting Row and getting Id, get error I insert a value / new row and I need the ID, but I get an error...
SQL code:
INSERT INTO [StoneTable] ([StoneName]) VALUES (@StoneName)
SELECT SCOPE_IDENTITY()

Using this code to insert row and getting the ID:
stoneTableTableAdapter = new StoneTableTabelleTableAdapter();
int id = Convert.ToInt32(stoneTableTableAdapter.InsertStoneNameAndReturnId("anything"));
//And on this 2nd Line I got an error

Error message:

There was an error parsing the query. [ Token line number = 2,Token line offset = 1,Token in error = SELECT ]

What's the problem? In my other project I use the same syntax, with no problems. Tried with @@IDENTITY, as well not working....

A: See the answer to this question for a suggestion on how to make your example work:

You should change your INSERT to return that inserted ID to you right away (in an OUTPUT clause)

A: You can only issue a single statement per batch in SQL Server Compact, and you cannot use Scope_identity, but must use @@IDENTITY (remember to keep the connection open betweeen the two calls)


Q: Use div's height to determine another div's padding or margin-top I am using the following jQuery to work out the width of a div (thats in %), to then tell another div to set it's height to that in pixels.
<script>
    $("#top").height($("#left").width());
    $("#bottom").height($("#left").width());
</script>

It's working really well. Now my next problem is, that I want my div called 'wrapper' to have a padding-top or margin-top of the pixel value it returns for the height. I tried changing 'height' to 'padding-top', but that didn't seem to work.
The end result is a web page with a series of 4 black div acting as a border around the edge, it calculates 5% of the with of the window, and that determine's the pixel value for how how the top and bottom black div's are. That way it's exactly even. Now I want my inside wrapper div, to start exactly that far down the web page too.

A: Use the jQuery outerWidth function to retrieve the width inclusive of padding, borders and optionally margin as well (if you send true as the only argument to the outerWidth method).

A: Tested Solution: Find height of a div and use it as margin top of another div.
$('.topmargindiv').css('margin-top', function() {
    return $('.divheight').height();
});


Q: How to divide workers and aggregate results? Given a payload submitted to a parentWorker:

*

*I divide the work amongst otherWorkers and I add the taskId of the parentWorker as an additional property in the payload

*each of the otherWorkers finish what they are responsible for

What I want is to know if 5 or 10 or 20 otherWorkers were queued/kicked off then when do they all finish? Because when all of them are finished, I want to start the next part of my workflow: nextWorker!
So the ideal pipeline is: parentWorker > X # of otherWorkers > everyone done? > nextWorker
How can I make this happen?
Please don't answer with a polling-based solution. I'm not looking for that.
I thought of using a cache:

*

*where the parentWorker would set the total # of otherWorkers that will be created, like: cachekey_<parertTaskId>_workersCreated: 10

*then the otherWorkers would decrement the # atomically by -1 after they finish and eventually the count will reach zero: cachekey_<parertTaskId>_workersCreated: 0 but who is supposed to act on that count?

a) If the idea is to let otherWorkers decrement it then check the value and to see if it is zero and kick off nextWorker ... that is flawed in a situation where:
cachekey_<parertTaskId>_workersCreated: 2
otherWorker9 sends -1
otherWorker10 sends -1
otherWorker9 checks and otherWorker10 checks
both get back 0 and both will kick off nextWorker! We only wanted one instance.

b) other bad ideas:
cachekey_<parertTaskId>_workersCreated: 2
otherWorker9 checks and otherWorker10 checks
neither one kicks off nextWorker because value!==1
otherWorker9 sends -1
otherWorker10 sends -1
its over and noone is left to act on cachekey_<parertTaskId>_workersCreated: 0

A: There's unfortunately no automated/very simple/built-in way to do this.
Regarding your idea to use a cache, if you use something like Redis, it's increment and decrement operations are atomic so you'd never get a case where both workers got back the same number. One worker and one worker only would get the zero back: http://redis.io/commands/decr


Q: Include all *.bib files in one directory to a bibliography There are several *.bib files in one directory which I want to add to my bibliography.
I don't want to add them one by one like this:
\bibliography{../dir/a,../dir/b,../dir/c}

I tried adding the directory to bibtex like this: (see here)
bibtex --include-directory "../dir/

resulting in
bibtex: unrecognized option '--include-directory=../dir/'

This option seems to be specific to mikTeX BibTeX, but I am using TeXLive.
Is there a way to add all *.bib files in ../dir/ to my bibliography?
I am already using TeX, BibTeX and Make, so a solution using those tools is preferred, although any solution is welcome.

A: By default, in TeX Live bibtex looks for local .bib files in your local texmf/bibtex/bib folder.  So you can put your directory containing the bib files there, or make a symbolic link inside that folder to your directory.  Either one will work.  Then you just use \bibliography{a,b,c} for .bib file a.bib, b.bib etc.

A: As far as I know, there is no built in way to add all files in one directory, something like \bibliography{*.bib}.
However, you could set the environment variable BIBINPUTS to ./dir:; then you will be able to use \bibliography{a,b,c} to load ./dir/a.bib, ./dir/b.bib and so on. You could also set as many paths as you want, something like ./dirA:./dirB:./dirC:. The colon here is used to separate paths and when used on the beginning or in the end, is used to add the default path.
To set BIBINPUTS you could use env BIBINPUTS='./dir:' pdftex yourfile.tex in your command line or Makefile.
There is also a BSTINPUTS variable to set paths for .bst files.


Q: android list point to position I have 3 items in my listView, problem is that the pointToPosition() method is returning 1 for first item in the list and -1 for third item in the list. The rawx and rawy positions are correct as they match the dX and dY positions given by the device dev tools. I can not therefore work out how to get the correct cursor position for the list item especially the last position as code returns -1 rather than position 2. I can paste further code if required
 int pos = listView.pointToPosition((int) arg1.getRawX(), (int) arg1.getRawY());

Layout
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/x"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.buzz.ContactFragment"
    tools:ignore="MergeRootFrame"
    >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <ListView
        android:id="@+id/contact_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="@null"

        />
...

Fragment
public class ContactFragment extends Fragment implements
        LoaderManager.LoaderCallbacks<Cursor>,
        GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener, View.OnTouchListener {

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        gdc = new GestureDetectorCompat(getActivity().getApplicationContext(), this);
        View rootView = inflater.inflate(
                R.layout.fragment_contact, container, false);
        listView = (ListView) rootView.findViewById(R.id.contact_list);
...
}

...

 @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {

        int pos = listView.pointToPosition((int) arg1.getRawX(), (int) arg1.getRawY());
        Cursor cursor = (Cursor)listView.getItemAtPosition(pos);
...
}
...

A: The issue has been resolved based on suggestions found on the web but sorry can not remember the url.
public int getTouchPosition(MotionEvent motionEvent){
    // Transient properties
    int mDismissAnimationRefCount = 0;
    float mDownX;
    int mDownPosition=-1;
    View mDownView=null;

    //   Find the child view that was touched (perform a hit test)
    Rect rect = new Rect();
    int childCount = mListView.getChildCount();
    int[] listViewCoords = new int[2];
    mListView.getLocationOnScreen(listViewCoords);
    int x = (int) motionEvent.getRawX() - listViewCoords[0];
    int y = (int) motionEvent.getRawY() - listViewCoords[1];
    View child;
    for (int i = 0; i < childCount; i++) {
           child = mListView.getChildAt(i);
           child.getHitRect(rect);
           if (rect.contains(x, y)) {
                  mDownView = child;
                  break;
           }
    }

    if (mDownView != null) {
           mDownX = motionEvent.getRawX();
           mDownPosition = mListView.getPositionForView(mDownView);
    }

    return mDownPosition;

 }

Can use the position to get the cursor position used to populate the view
Cursor cursor = (Cursor)mListView.getItemAtPosition(mDownPosition);


Q: Republish http cloudpages to keep existing ID and introduce SSL We started to use cloudpages before SSL was configured. Since now it's available we would like to republish the pages we have in place but under https. Is there any opportunity to do it in a way that will allow us to keep existing pages IDs (not to changes other assets referencing these cloudpages)

A: When setting up the SSL, normaly the support will ask you some questions amongst which are the questions:

Will you require references made directly to HTTP to be force
  redirected to HTTPS?
...OR...
Would you like for references made directly to HTTP to work as is,
  without redirecting to a secured link?

You simply need to answer YES the first question and NO the second one.
PS: you may need to take in consideration this support's recommendation:

If you elect to enable the Forced Redirect feature, we recommend that
  you consult with your IT/Development teams beforehand to ensure your
  current landing pages and/or link references are equipped to properly
  resolve in the event of a redirect to HTTPS (ie - mixed content
  errors, hard coded HTTP, etc).


Q: Box2d: Place object besides another one precisely? I was wondering about how to place fixtures right beside another one. Btw. I have probably confused myself.
So here is what I want to do:
LIKE THIS ILLUSTRATION
Could I just accomplish this by applying the sum of something like this positionX of leftWall + sizeX/2 of leftWall + sizeX/2 of box, to the box climbing the wall? Or is there some box2d function that automatically calculates the position?
After I have accomplished this, I will add a constant velocity to the box and therefore I need it to be exact plus the fact that it looks better. I have just confused myself too much and I do not know how but can anybody tell me what they would do?
Thanks! Much appreciated!

A: Go with "the sum of something".
I don't see it is a problem.
If you really dislike it, just write your own function to do it.
As you already know, it is not hard.
Detail
Box2D is not an architectural library.
As far as I know, there is no such function.
In 3D Physics and Graphics, I also faced a little inconvenience like this.
There are 2 choices for me :-

*

*hard code "the sum of something"   (I start to love this phrase.)

*encapsulate such library (e.g. Box2D)    / code a utility function

I usually pick one of the choices, depends on situation.
Because it is only little inconvenience, I believe the first is suitable for your situation.
By the way, there are reserved margin between colliding fixtures, so I think you can't set the exact position.

there is always a small margin of space added around the fixture by default.

A: An explanation of what's going on...
For static and kinematic bodies, where you place them is where they'll be. In other words, if you call b2Body::SetTransform with a position of pos and then call b2Body::GetPosition, the returned value should equal pos. This should hold true even if these bodies overlap each other. They won't move unless you tell them to.
Dynamic bodies behave differently however. They behave more like we'd expect solid bodies to behave in the real world. But we can do things to them still that couldn't practically be done to real solid objects. For instance, we can call b2Body::SetTransform on one dynamic body to place it (or part of it) within another body. Now the physics engine works to figure out where to move the dynamic body so that it's not within the other body anymore (and in a way that's intended to appear reasonable enough given what the initial overlap may look like).
More precisely, the 2.3.2 Box2D library will resolve the overlap of two bodies (where one or both are dynamic) as much as b2_maxLinearCorrection for each position iteration until minSeparation >= -3.0f * b2_linearSlop where minSeparation is the distance separating the closest vertices (of both shapes) in the separating plane minus the sum of the vertex radiuses (of both shapes). The "sequential solver" does this via impulses but without influencing the body velocity values so that neither body acts as if it had any additional momentum.
You can take a look at the code involved in the b2ContactSolver::SolvePositionConstraints method of the b2ContactSolver.cpp file.
So in a sense, the Box2D world step "calculates the position" for you. Note however the following caveats:

*

*This position resolution doesn't always complete in one step. I.e. users may watch as the box moves out from the wall till it appears entirely out.

*If you place the box too far into the wall, it will appear on the opposite side of the wall.

*You may want to factor in to your expectations the total of the vertex radiuses - i.e. sum the values of the shapes' m_radius values. This is referred to as the reserved margin of space. For two polygons, this will be 4.0f * b2_linearSlop or 0.02f (2 centimeters).

Insofar as placing an object beside another precisely then:

*

*You can place non-dynamic bodies beside each other as precisely as floating-point values allow.

*You can place a dynamic body beside another body only as close as position resolution allows (and only as precisely as floating-point values allow). Any closer, and the "sequential solver" will move it back out.


Q: Jquery drop down menu strange behavior My Problem (Fiddle)
My problem is that on my jquery animated dropdown menu, when you hover over the "Other" link, the sub menu does not appear. When using firefox to 'Inspect Element', I find height is animated, and the width appears to be alright, yet all I see is the left border.
I noticed that if I have that particular section display as a block, when you animate the first menu it is shown, but upon entering the unordered list, it disappears (ex). I imagine it is somehow related to this, but I can not figure out what is causing this.
Any incite into what I'm probably just overlooking would be great, and of course much appreciated.
Notes:

*

*I have had this problem in Firefox, Chrome, Opera, and IE.

*It's designed such that it could work with only css. The the first .each is overriding default css hover behavior.

*the empty span holds the arrow image.

*only relevant code is posted. However, you may view my site here

*If you have any tips on making something more efficient, always welcome.

A: http://jsfiddle.net/sailorob/4cdTV/5/
I've removed your CSS for simplicity's sake and simplified your functions by utilizing jQuery slideUp and slideDown, which essentially handle many of the css properties you were managing with your functions. From here, I think it would be fairly simple to work back in some of your CSS.
When utilizing javascript/jQuery/animation on menus, I highly suggest using timers (setTimeout) for firing mouseenters and 'leaves. This way, your menu is more forgiving when a user accidentally moves their mouse a few pixels out of the menu and it closes.

A: Well, in debugging the JS and CSS I found that if you remove ALL the JS you have, the drop down menu with sub menus work fine. The Other li opens up the ul below it just fine. Note, it doesn't animate without the JS though.
Here's a forked fiddle.
I tested it in latest Chrome and Firefox.


Q: Как заставить работать v-model? Создаю таблицу чекбоксов
buildTableCheckbox() {
                let checked = this.schedule.limitSchedule.split('');
                let days = ['ПН', 'ВТ', 'СР', 'ЧТ', 'ПТ', 'СБ', 'ВС'];
                let createHeader = document.querySelector(".create-header");
                let createBody = document.querySelector('.create-body');
                let timetableCount = 0;
                createHeader.innerHTML = '	';
                for(let i=0; i<24; i++) {
                    let th = document.createElement('th');

                    th.innerText = i;
                    th.scope = 'col';
                    createHeader.appendChild(th);
                }

                for(let key in days) {
                    let tr = document.createElement('tr');
                    tr.innerHTML = '' + days[key] + '	';
                    createBody.appendChild(tr);
                    for (let i = 0; i < 24; i++) {
                        let isChecked = '';
                        if (checked[timetableCount] === '1') {
                            isChecked = 'checked="checked"';
                        }
                        tr.innerHTML += '<input class="filled-in" type="checkbox" v-model="timetable" name="timetable['+ timetableCount + ']" value="1" id="timetable[' + timetableCount + ']" ' + isChecked + '>	';
                        timetableCount++
                    }
                }
            }

в строке
tr.innerHTML += '<input class="filled-in" type="checkbox" v-model="timetable" name="timetable['+ timetableCount + ']" value="1" id="timetable[' + timetableCount + ']" ' + isChecked + '>	';

пытаюсь подключить v-model но я так понимаю vue не рендерит подобное, подскажите как обойти данную проблему и записать данные для отправки на сервер

A: созданную HTML-разметку нужно скомпилировать во Vue.
import Vue from 'vue';
Vue.compile(/*Ваша HTML-разметка*/);

A:

Vue.component('my-form', {
  template: `<form>

          {{ daysOfWeek[(row - 1) % 7] }}

            <input v-model="newData[(row - 1) * 24 + idx - 1]" type="checkbox">

  </form>`,
  props: {
    data: { type: Array, default: () => [] },
  },
  data() { return {
    daysOfWeek: Object.freeze('пн,вт,ср,чт,пт,сб,вс'.split(',')),
    newData: [],
  }},
  computed: {
    rowsCount() {
      return Math.ceil(this.data.length / 24);
    },
  },
  mounted() {
    this.newData = [...this.data];
  },
});

new Vue({
  el: '#app',
  data() { return {
    input: '110000000000000000000000010000000000000000000000001000000000000000000000000100100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
  }},
  methods: {
    log(arr) {
      console.clear();
      console.log(arr.map(v => +v).join(''));
    },
  },
  computed: {
    parsed() {
      return this.input.split('').map(v => v === '1');
    },
  },
})
table { border-collapse: collapse; margin-bottom: 2rem; font-family: sans-serif; }
tr:nth-child(odd) { background: #eee; }
th, td { min-width: 2rem; padding: 0.3em 0; }
th { padding-right: 0.5em; }

  <my-form :data="parsed" action="#" @change="log"></my-form>


Q: problem while extracting data from api in react I have created an API to access data from the database. I have fetched the api data using axios and I want to display it. I have mapped the data, but it returns empty array for the first time.
const ExpenseList = () => {

    const [result, setResult] = useState([]);

    const expenseDetails = async () => {
        try {
          let res = await axios.get("http://127.0.0.1:8000/expense");
          let result = res.data;
          setResult(result);
        } catch (e) {
          console.log(e);
        }
      };

      useEffect(() => {
        expenseDetails()
      }, []);

      console.log("result", result)
    return (
        <Container className='list-group'>
            <Row className='title-row'>
                <Col className='title-col-expenses'>Expenses</Col>
            </Row>
            {
            result.map((items)=>{
                <ExpenseItem id={items.id} name={items.name} cost={items.cost} />
            })}

        </Container>
    )
}

I have attached a screenshot of console where I have logged "result"
Click to view image

A: as CevaComic said you are setting the initial value as an empty array.
useEffect will only work after the component has been rendered, so when you will console.log the data stored in result you will get the initial value.
Only after the component will render for the second time, because of the changed made inside setResult, the data from the api will be logged.


Q: string.Format give wrong thousand seperator in html razor C# block string.Format("{0:#,0}",19091507)
string.Format give wrong thousand seperator in html razor C# block
Expected Output : 19,091,507
Current Output : 1,90,91,507
Please help me.

A: You can try following.
        int @value= 19091507;
        Console.WriteLine(@value.ToString("#,#.##", System.Globalization.CultureInfo.CreateSpecificCulture("en-US")));

For me following is also working.
        int @value= 19091507;
        Console.WriteLine(string.Format("{0:#,#.##}", @value));

You can also try.
        int @value= 19091507;
        Console.WriteLine(string.Format(System.Globalization.CultureInfo.CreateSpecificCulture("en-US"),"{0:#,#.##}", @value));

It depends on your culture.


Q: Erro auth laravel com outra model? Pessoal mudei o nome do model padrão do Laravel User.php para Colaboradores.php (claro, setei o $table e a $primaryKey no model), alterei também no config/auth.php a model. mas o login está sempre me retornando false, segue código de login:
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => Siga\Colaboradores::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

public function auth( Request $request )
{

    $username = $request->input("usuario_colaborador");
    $password = $request->input("senha_colaborador");

    if( Auth::check() || Auth::attempt([
        'usuario_colaborador' => $username,
        'senha_colaborador' => $password]) )
    {
        // redirecionando usuário depois de logado
        return redirect(route('farol.meufarol'));
    }
    else
        return redirect(route('login'));
}

A: Quando se utiliza uma outra classe que não segue o mesmo padrão de nomes de campos, existem formas de autenticar o usuário, pela instância dessa classe ou pelo Id do usuário como descrito na documentação.
O código ideal nesse caso seria primeiramente trazer esse instância e conferir se os dados estão corretos, da seguinte forma:
public function auth( Request $request )
{

    $username = $request->input("usuario_colaborador");
    $password = $request->input("senha_colaborador");

    //busca o usuário para ver se o mesmo existe
    $model    = Siga\Colaboradores::where('usuario_colaborador',$username)->first();

    // confere se o usuário é a mesma senha
    if( Auth::check() ||
      ($model && Hash::check($password, $model->senha_colaborador)) )
    {
        // redirecionando usuário depois de logado
        Auth::login($model); // autenticando ...
        return redirect(route('farol.meufarol'));
    }
    else
        return redirect(route('login'));
}

Basicamente seria essas as alterações, ou seja, como o método attempt deve seguir a mesma nomenclatura de nomes que são email e password na sua tabela é diferente do seu model de autenticação sempre vai retornar false.
Uma dica: se não for necessário, não mude o modelo padrão, porque o mesmo pode até ser adicionado novos campos e relacionamentos, e isso garante que todos os métodos proposto na documentação funcione como deveria.
Referencias:

*

*Documentação

*Hashing


Q: Find the position of equal elements in a matrix using Matlab Suppose I have:
m = [1,2,3;1,4,5;6,4,7]

I want to get a list containing the positions of the elements in the matrix m so that the positions of equal elements are grouped together. The output for matrix m must be:
{{1,1},{2,1}},{{2,2},{3,2}},{1,2},{1,3},{2,3},{3,1},{3,3}
%     1             2         3     4     5     6     7

We can see here that the positions for the elements that are all equal to each other are grouped together.

A: The simplest way would be to loop through every unique value and determine the row and column positions that match each value.  Something like this could work:
val = unique(m);
pos = cell(1, numel(val));
for ii = 1 : numel(val)
    [r,c] = find(m == val(ii));
    pos{ii} = [r,c];
end

pos would be a cell array containing all of the positions for each unique value.  We can show what these positions are by:
>> format compact; celldisp(pos)
pos{1} =
     1     1
     2     1
pos{2} =
     1     2
pos{3} =
     1     3
pos{4} =
     2     2
     3     2
pos{5} =
     2     3
pos{6} =
     3     1
pos{7} =
     3     3

This of course is not meaningful unless you specifically show each unique value per group of positions.  Therefore, we can try something like this instead where we can loop through each element in the cell array as well as display the corresponding element that each set of positions belongs to:
 for ii = 1 : numel(val)
     fprintf('Value: %f\n', val(ii));
     fprintf('Positions:\n');
     disp(pos{ii});
 end

What I get is now:
Value: 1.000000
Positions:
     1     1
     2     1
Value: 2.000000
Positions:
     1     2
Value: 3.000000
Positions:
     1     3
Value: 4.000000
Positions:
     2     2
     3     2
Value: 5.000000
Positions:
     2     3
Value: 6.000000
Positions:
     3     1
Value: 7.000000
Positions:
     3     3

A: This gives you what you want, except for the fact that indices of unique elements are also wrapped in cell twice, just like the indices of repeating elements:
m = [1,2,3;1,4,5;6,4,7];

[~, idx] = ismember(m(:), unique(m(:)));
linInd = 1:numel(m);
[i,j] = ind2sub(size(m), linInd);
res = accumarray(idx, linInd, [], @(x) {num2cell([i(x);j(x)]',2)});

Result:
>> celldisp(res)

res{1}{1} =
     2     1
res{1}{2} =
     1     1
res{2}{1} =
     1     2
res{3}{1} =
     1     3
res{4}{1} =
     2     2
res{4}{2} =
     3     2
res{5}{1} =
     2     3
res{6}{1} =
     3     1
res{7}{1} =
     3     3


Q: JAVA a reliable equivalent for php's MCRYPT_RIJNDAEL_256 I need to access some data that used PHP encryption. The PHP encryption is like this.
base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($cipher), $text, MCRYPT_MODE_ECB));
As value of $text they pass the time() function value which will be different each time that the method is called in.  I have implemented this in Java. Like this,
public static String md5(String string) {
    byte[] hash;

    try {
        hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Huh, MD5 should be supported?", e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Huh, UTF-8 should be supported?", e);
    }

    StringBuilder hex = new StringBuilder(hash.length * 2);

    for (byte b : hash) {
        int i = (b & 0xFF);
        if (i < 0x10) hex.append('0');
        hex.append(Integer.toHexString(i));
    }

    return hex.toString();
}

public static byte[] rijndael_256(String text, byte[] givenKey) throws DataLengthException, IllegalStateException, InvalidCipherTextException, IOException{
    final int keysize;

    if (givenKey.length <= 192 / Byte.SIZE) {
        keysize = 192;
    } else {
        keysize = 256;
    }

    byte[] keyData = new byte[keysize / Byte.SIZE];
    System.arraycopy(givenKey, 0, keyData, 0, Math.min(givenKey.length, keyData.length));
    KeyParameter key = new KeyParameter(keyData);
    BlockCipher rijndael = new RijndaelEngine(256);
    ZeroBytePadding c = new ZeroBytePadding();
    PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(rijndael, c);
    pbbc.init(true, key);

    byte[] plaintext = text.getBytes(Charset.forName("UTF8"));
    byte[] ciphertext = new byte[pbbc.getOutputSize(plaintext.length)];
    int offset = 0;
    offset += pbbc.processBytes(plaintext, 0, plaintext.length, ciphertext, offset);
    offset += pbbc.doFinal(ciphertext, offset);
    return ciphertext;
}

public static String encrypt(String text, String secretKey) throws Exception {

    byte[] givenKey = String.valueOf(md5(secretKey)).getBytes(Charset.forName("ASCII"));

    byte[] encrypted = rijndael_256(text,givenKey);

    return new String(Base64.encodeBase64(encrypted));
}

I have referred this answer when creating MCRYPT_RIJNDAEL_256 method."
Encryption in Android equivalent to php's MCRYPT_RIJNDAEL_256
"I have used apache codec for Base64.Here's how I call the encryption function,
long time= System.currentTimeMillis()/1000;
String encryptedTime = EncryptionUtils.encrypt(String.valueOf(time), secretkey);
The problem is sometimes the output is not similar to PHP but sometimes it works fine.
I think that my MCRYPT_RIJNDAEL_256 method is unreliable.
I want to know where I went wrong and find a reliable method so that I can always get similar encrypted string as to PHP.

A: The problem is likely to be the ZeroBytePadding. The one of Bouncy always adds/removes at least one byte with value zero (a la PKCS5Padding, 1 to 16 bytes of padding) but the one of PHP only pads until the first block boundary is encountered (0 to 15 bytes of padding). I've discussed this with David of the legion of Bouncy Castle, but the PHP zero byte padding is an extremely ill fit for the way Bouncy does padding, so currently you'll have to do this yourself, and use the cipher without padding.
Of course, as a real solution, rewrite the PHP part to use AES (MCRYPT_RIJNDAEL_128), CBC mode encryption, HMAC authentication, a real Password Based Key Derivation Function (PBKDF, e.g. PBKDF2 or bcrypt) and PKCS#7 compatible padding instead of this insecure, incompatible code. Alternatively, go for OpenSSL compatibility or a known secure container format.


Q: Moving back to the the previous fragment tab (KEYCODE_BACK) Moving back to the previous fragment tab (KEYCODE_BACK)
I have something like
TAB
       FA – FB –FC - FD
How can I implement something that when the back button is pressed it moves to the previous fragment i.e. from FD-->FC and from FC-->FB and from FB-->FA (TAB)
With the code below it moves from FD-->FB and from FC-->FA how can I correct this.
Thank you
    View.setFocusableInTouchMode(true);//Called in Fragment D
    View.requestFocus();
    View.setOnKeyListener(new View.OnKeyListener() {

        @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_BACK) {

                    Bundle bundle = new Bundle();
                    FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                    Fragment fragment = new FragmentC(); //move to previous fragment (FC)
                    fragment.setArguments(bundle);
                    fragmentTransaction.replace(R.id.my_container, fragment)
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();

                    return true;
                }

                else {

                    return false;
                }
            }
    });

A: If you use addToBackstack to open new Fragments, it should work without the keyback listener.  The fragmentTransaction manages this for you.


Q: Fixing homebrew path I'm learning Python and most tutorials recommend to install Python using homebrew so I installed homebrew then I typed:
brew install python

which should overwrite OS X Python 2.7.10 with 2.7.11 but I think it didn't and when I enter:
brew doctor

I get:

Homebrew's sbin was not found in your PATH but you have installed
  formulae that put executables in /usr/local/sbin.
  Consider setting the PATH for example like so
      echo 'export PATH="/usr/local/sbin:$PATH"' >> ~/.bash_profile

What should I do? Should I uninstall everything and start over?

A: It might be unrelated to the problem with Python, but at this moment, you should do exactly what the message says, i.e. type the following command:
echo 'export PATH="/usr/local/sbin:$PATH"' >> ~/.bash_profile

After that reopen terminal session or run . ~/.bash_profile command.
It just says that some of the programs you installed with homebrew are placed in /usr/local/sbin directory, but your shell "does not know" about them.
For a reference you can check which programs (formulae) are there by listing the contents:
ls /usr/local/sbin

As for checking Python, type:
ls -l `which python`

It will give you the path to the current executable. You want it the output to look this way:
lrwxrwxr-x  1 root  admin  34 Dec 14 21:12 /usr/local/bin/python@ -> ../Cellar/python/2.7.11/bin/python


Q: Problems with RTL8822BE Bluetooth on Ubuntu 18.04 So my bluetooth was working fine until last week where a new update came along. I'm guessing this included a kernel update. Then, my bluetooth was disabled and I can't turn it on again.
The service is running but in the switch in gnome-control-center does nothing when hit.

Through lshw I figured out, that I have a RTL8822BE Bluetooth and Wifi device. Wifi is working fine btw.
*-network
       Beschreibung: Kabellose Verbindung
       Produkt: RTL8822BE 802.11a/b/g/n/ac WiFi adapter
       Hersteller: Realtek Semiconductor Co., Ltd.
       Physische ID: 0
       Bus-Informationen: pci@0000:03:00.0
       Logischer Name: wlp3s0
       Version: 00
       Seriennummer: 80:2b:f9:bd:d1:8d
       Breite: 64 bits
       Takt: 33MHz
       Fähigkeiten: pm msi pciexpress bus_master cap_list ethernet physical wireless
       Konfiguration: broadcast=yes driver=r8822be driverversion=4.18.0-18-generic firmware=N/A ip=192.168.0.158 latency=0 link=yes multicast=yes wireless=IEEE 802.11
       Ressourcen: irq:143 ioport:d000(Größe=256) memory:df200000-df20ffff

Suspicious about the info firmware=N/A I checked if there are the appropriate firmware files. I read that I should look for rtl8822b_config.bin and rtl8822b_fw.bin under /lib/firmware/rtl_bt/ and they are there.
$ ll /lib/firmware/rtl_bt/rtl8822b*

-rw-r--r-- 1 root root  14 Apr 28 14:58 /lib/firmware/rtl_bt/rtl8822b_config.bin
-rw-r--r-- 1 root root 50K Apr 28 14:59 /lib/firmware/rtl_bt/rtl8822b_fw.bin

Replacing them like suggested in this thread did not help eather.
https://askubuntu.com/questions/1003818/rtl8822be-bluetooth-device#=
One last hope that I had was that it was simply blocked. Investigating this I found that this can be seen with rfkill list but no luck there eather ...
$ sudo rfkill list
0: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no
1: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no

Here is the output of dmesg | egrep -i 'blue|firm'.
dmesg | egrep -i 'blue|firm'
[    0.028000] Spectre V2 : Enabling Restricted Speculation for firmware calls
[    0.143301] ACPI: [Firmware Bug]: BIOS _OSI(Linux) query ignored
[    2.153415] usb 1-14: Product: Bluetooth Radio
[   15.614394] Bluetooth: Core ver 2.22
[   15.614404] Bluetooth: HCI device and connection manager initialized
[   15.614406] Bluetooth: HCI socket layer initialized
[   15.614407] Bluetooth: L2CAP socket layer initialized
[   15.614410] Bluetooth: SCO socket layer initialized
[   15.618901] Bluetooth: hci0: rtl: examining hci_ver=08 hci_rev=627a lmp_ver=08 lmp_subver=b29b
[   15.618902] Bluetooth: hci0: rtl: assuming no firmware upload needed
[   16.046087] r8822be: Using firmware rtlwifi/rtl8822befw.bin
[   20.774984] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[   20.774985] Bluetooth: BNEP filters: protocol multicast
[   20.774988] Bluetooth: BNEP socket layer initialized

And dmesg | egrep -i 'r8822be'.
dmesg | egrep -i 'r8822be'
[   15.884569] r8822be: module is from the staging directory, the quality is unknown, you have been warned.
[   15.885992] r8822be 0000:03:00.0: enabling device (0000 -> 0003)
[   16.046087] r8822be: Using firmware rtlwifi/rtl8822befw.bin
[   16.188308] r8822be: rtlwifi: wireless switch is on
[   16.191197] r8822be 0000:03:00.0 wlp3s0: renamed from wlan0

I realy hope that some one can help me with this issue because it drives me crazy that it was working already but isn't now ...
PS: I also tried to go to a previous kernel but with no luck :/
Update: I also checked that AutoEnable=ture is set in /etc/bluetooth/main.conf.
Thank you all in advance! :)

A: This isn't much of an answer, but I was running into a very similar issue to yours after updating my kernel to 4.18.0-18. When I switched back to 4.18.0-15, Bluetooth seemed to be working again. I ran some diagnostics (lshw, lspci, hdiconfig dev, etc.), but didn't do much else.
When next I switched back to 4.18.0-18, for some unknown reason the issue magically fixed itself. I am unable to reproduce the breakage that I was seeing earlier, which is very spooky but at least it is fixed now.
So maybe, try switching back to an older version of the Kernel and see if Bluetooth comes back? If so then you might be able to figure out what part of the kernel update broke Bluetooth for you, and maybe you'll get lucky like me and the problem will fix itself.


Q: I can not install Entity Framework Power Tools Beta 4 on VS 2013 express Desktop Edition This is my first post and I hope that it meets all of the requirements!
System:
 Windows 10

 VS 2013 Desktop Express

I am attempting to install Entity Framework Power Tools Beta 4 but when I search through "Extensions and Updates" -> "Online" for "Entity Framework Power Tools Beta 4," it can not locate the package.
I thought to myself, perhaps it is only in vs 2015 that you can find this or perhaps it is only in non-express editions. Thus, I turned to the Intergoogles! I found the following site:
https://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d
And there is support for vs2013 on this download! Yet, it says that it cannot locate any application on my machine that would use this if installed.
Can someone give me some guidance? Am I SOL if I am using VS 2013 but want access to the Entity Framework Power Tools Beta 4? I am using EF6 if that helps.
Thank you!

A: The Express edition do not support extensions, use Community edition 2013 instead. Julie Lerman has an updated version, that has been fixed to work with VS 2015 http://thedatafarm.com/data-access/installing-ef-power-tools-into-vs2015/


Q: Maximization of the product of two inner products I have an optimization problem of the form
$\max_\gamma \langle f\circ\gamma,w_f\rangle\langle g\circ\gamma,w_g\rangle$
where $f\circ\gamma$ is the composition of $f$ and $\gamma$ and the inner product is defined as
$\langle f\circ\gamma,w_f\rangle = \int (f\circ\gamma)(t) w_f(t)\,dt$
In other words I am trying to find a $\gamma$ that maximizes the product of the two inner products above. I know one could pursue a gradient approach, which would be slow. Is there a more direct optimization method?

A: If $f$ and $g$ are differentiable, you could do something like the following.
Define $J(\gamma)$ as your objective function. Then, the variation of $J$ in direction $h$ is given by
\begin{align*}J'(\gamma; h)
&= \int f'(\gamma(t)) \, h(t) \, w_f(t) \, \mathrm d t \, \int g(\gamma(t)) \, w_g(t) \, \mathrm d t + \int f(\gamma(t)) \, w_f(t) \, \mathrm d t \, \int g'(\gamma(t)) \, h(t) \, w_g(t) \, \mathrm d t\\
&= \int \Bigg\{\Big( \int g(\gamma(s)) \, w_g(s) \, \mathrm d s \Big) f'(\gamma(t)) \, w_f(t) + \Big(\int f(\gamma(s)) \, w_f(s) \, \mathrm d s\Big) \, g'(\gamma(t)) \, w_g(t) \, \Bigg\} \, h(t) \mathrm d t\\
\end{align*}
Now, this has to be zero for all $h$. Hence, for all $t$, you get the equation
$$\Big( \int g(\gamma(s)) \, w_g(s) \, \mathrm d s \Big) f'(\gamma(t)) \, w_f(t) + \Big(\int f(\gamma(s)) \, w_f(s) \, \mathrm d s\Big) \, g'(\gamma(t)) \, w_g(t) = 0$$
Now, it depends on the functions how this equation could be solved.
Maybe, this is of some use.


Q: Is there strict type check in TypeScript? I'm codding some library with TypeScript, and I want to protect calls my methods from incorrect meaning data. Let's see next example:

type BookId = number;
type AuthorId = number;

BooksService.getById(bookId: BookId): Book {
    // ...
};

let authorId: AuthorId;

// I need to get some type error in next lene, because getById() expect receive BookId, not AuthorId:
book = BooksService.getById(authorId);

Is it possible to get this error? How to upgrade my example to get it?