Q: Property list in a Model property couldn't be mapped while trying to migrate I'm setting up a migration in an MVC5 that has a Model that's called "Order" with 3 properties, one of them is a class of PizzaModel. PizzaModel has the code below, what I'm trying to do is to enable multiple instances of pizzas in a single Order, so one Order can have many pizzas.
public class PizzaModel
{
    [Key]
    public int Id { get; set; }
    public List<PizzaSet> Pizzas { get; set; }
    public int Cost { get; set; }

}
public class PizzaSet
{
    public enum Toppings { GreenOlives, BulgarianCheese, Onions, Mushrooms, Peppers, Basil, Sausage, Pepperoni, Ham, Beef }
    public enum Sauces { BBQ, Islands }
    public enum Size { Personal, Medium, Family }

    public Size PizzaSize { get; set; }
    public List<Sauces> PizzaSauces { get; set; }
    public List<Toppings> PizzaToppings { get; set; }
}

Is this a wrong approach for a migration?

A: Your PizzaSet class is using a List of Enums, which will not map to a database schema in EF.
If you want to use an enum for Sauces and Toppings and want to allow multiple selections, you need to use the [Flags] property for the enum, to treat it as a bit field.
public class PizzaSet
{
    [Flags]
    public enum Toppings { GreenOlives = 1, BulgarianCheese = 2, Onions = 4, Mushrooms = 8, Peppers = 16, Basil = 32, Sausage = 64, Pepperoni = 128, Ham = 256, Beef = 512 }

    [Flags]
    public enum Sauces { BBQ = 1, Islands = 2 }

    public enum Size { Personal, Medium, Family }

    public Size PizzaSize { get; set; }
    public Sauces PizzaSauces { get; set; }
    public Toppings PizzaToppings { get; set; }
}

Then Toppings and Sauces become a bit field of possible values (notice the values will need to represent unique bits)
To select multiple toppings:-
PizzaSet ps = new PizzaSet();

ps.Toppings = Toppings.GreenOlives | Toppings.Peppers;

However, given your list of toppings and sauces may change over time, it's probably better to have a separate table that lists toppings, and use a join table (since it's EF Core)

A: You have enums as your list type.
If youre storing this data in a database. The database needs a placeholder to store the enum values.
In general this is done by a table.
So, if you make classes of your enums, these will be translated to tables and the mapping will work.
public class Topping
{
     public string Name {get;set;}
}

Use this class as your list type.
Do note that you need to fill the topping, sauces and etc. tables. The good news is: you can extend them without changing the code :-)

Alternatively,  you can put the
[NotMapped]

attribute on your property.  Do note that this won't help you in your specific case because it would not store the toppings in the database then.


Q: Flutter : stack & Ink overlay I am using a Stack to recreate this effect :

But for some reason, using the Ink widget to be able to get the gradient effect, this is what I have :

This is my code :
Stack(
                        children: [
                          SizedBox(
                            height: 100.0,
                            width: 100.0,
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(20.0),
                              child: CachedNetworkImage(
                                imageUrl:
                                    'https://images.unsplash.com/photo-1570296767266-60ccc88974a5',
                                fit: BoxFit.cover,
                                placeholder: (context, url) => MC_Shimmer(),
                              ),
                            ),
                          ),
                          Positioned(
                            right: -5.0,
                            bottom: -5.0,
                            child: SizedBox(
                              height: 30.0,
                              width: 30.0,
                              child: Ink(
                                decoration: BoxDecoration(
                                  gradient: gradient,
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(5.0)),
                                ),
                                child: Icon(
                                  OMIcons.cameraAlt,
                                  color: Colors.white,
                                  size: 15.0,
                                ),
                              ),
                            ),
                          )
                        ],
                      ),

A: you can use Container instead of Ink and able to use gradient effect.
Positioned(
      right: -5.0,
      bottom: -5.0,
      child: SizedBox(
        height: 30.0,
        width: 30.0,
        child: Container(
          decoration: BoxDecoration(
            gradient: gradient,
            borderRadius:
            BorderRadius.all(Radius.circular(5.0)),
          ),
          child: Icon(
            OMIcons.cameraAlt,
            color: Colors.white,
            size: 15.0,
          ),
        ),
      ),
    )

A: I tried this in dart pad it worked alright.
Positioned(
                    right: -5.0,
                    bottom: -5.0,
                    child: SizedBox(
                      height: 30.0,
                      width: 30.0,
                      child: Material(
                        child: Ink(
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                                colors: [Colors.pink, Colors.yellow]),
                            borderRadius: BorderRadius.all(Radius.circular(5.0)),
                          ),
                          child: Icon(
                            Icons.camera,
                            color: Colors.white,
                            size: 15.0,
                          ),
                        ),
                      ),
                    ),
                  )


Q: Dependencia JAX-RS (com.sun.xml.ws) não empacotar arquivos tipo zip Olá.
O projeto possui essa dependência.
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <version>2.3.3</version>
        <type>pom</type>
    </dependency>

No momento de empacotar tudo esses arquivos vão juntos (não lembro perfeitamente o nome):
samples2.3.3.zip e release-documentation2.3.3.zip
Existe uma regra tola no cliente, um script do Jenkis que não permite arquivos zip que contenha pasta.
Gostaria de remover esses arquivos do empacotamento.
Já tentei esse código mas não funcionou:
  <id>distribution</id>
  ...
  <fileSets>
    <fileSet>
      <outputDirectory>/</outputDirectory>
      <directory>${project.build.outputDirectory}</directory>
      <excludes>
        <exclude>*.zip</exclude>
      </excludes>
    </fileSet>
  </fileSets>

E até abaixo de cada tag outputDirectory coloquei uma exclusão de zip. Também não funcionou. Alguém já precisou fazer isso? Não empacotar certos arquivos de uma dependencia?
  <outputDirectory>/</outputDirectory>
  <excludes>
    <exclude>*.zip</exclude>
  </excludes>

A: Descobri como fazer.
<dependency>
     <groupId>com.sun.xml.ws</groupId>
     <artifactId>jaxws-ri</artifactId>
     <version>2.3.3</version>
     <type>pom</type>
    <exclusions>
        <exclusion>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>samples</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>release-documentation</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Este post em inglês me ajudou.
https://stackoverflow.com/questions/9119055/excluding-maven-dependencies


Q: There is a way to use not operator in regex when ^ inside bracket is not an option? I went through dozen of already answered Q without finding one that can help me.
I have a string like this:
aaa.{foo}-{bar} dftgyh {foo-bar}{bar} .? {.!} -! a}aaa{

and I want to obtain a string like this:
aaa{foo}-{bar}dftgyh{foo-bar}{bar}-aaaa

Essentially I want to keep:

*

*valid word chars and hyphens wrapped in an open and a closed curly bracket, something that will match the regex \{[\w\-]+\}

*all the valid word chars and hyphens outside curly brackets

Using this:
$result = preg_replace( array( "#\{[\w\-]+\}#", '#[\w\-]#' ), "", $string );

I obtain the exact contrary of what I want: I remove the part that I want to keep.
Sure I can use ^ inside the square brackets in the second pattern, but it will not work for the first.
I.e. this will not work (the second pattern in the array is valid, the first not):
$result = preg_replace( array( "#[^\{[\w\-]+\}]#", '#[^\w\-]#' ), "", $string );

So, whis the regex that allow me to obtain the wanted result?

A: You may consider matching what you want instead of replacing the characters you do not want. The following will match word characters and hyphen both inside and outside of curly braces.
$str = 'aaa.{foo}-{bar} dftgyh {foo-bar}{bar} .? {.!} -! a}aaa{';
preg_match_all('/{[\w-]+}|[\w-]+/', $str, $matches);
echo implode('', $matches[0]);

Output as expected:
aaa{foo}-{bar}dftgyh{foo-bar}{bar}-aaaa

A: Also an option to (*SKIP)(*F) the good stuff and do a preg_replace() with the remaining:
$str = preg_replace('~(?:{[-\w]+}|[-\w]+)(*SKIP)(*F)|.~' , "", $str);

test at regex101; eval.in


Q: My table won't show the border i defined in css I'm trying to edit the borders of my table in css but the border's won't show.
Here's the code :

.midden {
  text-align: center;
}
.lijstje {
  list-style: inside;
  text-align: left;
  padding-left: 40%;
}
.naamkolom {
  background-color: lightgreen;
  font-weight: bold;
  border-radius: 25px;
  border-top: 2px chartreuse;
}
table {
  border: 25px green;
}
body {
  background-color: antiquewhite;
}
p {
  font-size: 25px;
  font-family: Georgia;
}

Italiaanse Recepten

    Recepten
    Ingrediënten
    Bereiding

    Spaghetti carbonara met andijvie

300 g spaghetti

250 g champignons

100 g Parmezaanse kaas

300 g gerookte spekreepjes

400 g gesneden andijvie

3 eieren

Kook de spaghetti volgens de aanwijzingen op de verpakking.

Snijd ondertussen de champignons in plakjes. Rasp de Parmezaanse kaas.

Verwarm een ruime hapjespan zonder olie of boter en bak de spekjes 3 min. op middelhoog vuur. Voeg de champignons en de andijvie in delen toe en bak nog 5 min. Schep regelmatig om. Breng op smaak met peper en eventueel zout.

Doe ondertussen de eieren in een kom en klop met 2/3 van de kaas los tot saus.

Giet de spaghetti af en doe terug in de pan. Voeg al roerend de saus toe. Blijf roeren tot de saus iets is ingedikt. Schep het andijviemengsel erdoor. Verdeel over de 4 borden en bestrooi met de rest van de kaas.

    Pangrattato

ciabatta

75 ml olijfolie

2 tl chilivlokken (molentje)

2 tenen knoflook

Maal de ciabatta in de keukenmachine tot broodkruim

Verhit de olijfolie in een grote koekenpan.

Voeg het broodkruim en de chilivlokken, peper en eventueel zout toe en bak in 5 min. op middelhoog vuur krokant.

Schep regelmatig om. Snijd ondertussen de knoflook fijn. Voeg de knoflook aan de pan toe en bak 2 min. mee op laag vuur.

Neem de pan van het vuur en laat de pangrattato afkoelen.

Terug naar startpagina

I really don't understand why the border isn't showing, since i can get the top columns to change color and the title to center, so the css file is working.
I've also tried creating a selective class for the table and assigning that in the html file but that didn't work either.

A: table {
    border: 25px solid green;
}

instead of
table {
    border: 25px green;
}

A: You have to define the type of border, so in your case I guess you want a solid border.
Here you have all css types of borders


Q: PIG Group by avoid Bag This is a basic PIG question.
I have my data something like this
10  | Dog
15 | Cow
20 | Dog
15 | Elephant
15 | Dog
25 | Elephant

I want to find the average weight of each animal and have the output as this :
Dog | 12.5
Elephant | 20
Cow | 15

I am able to use GROUP by and get the result, but the result is a bag, something like this :
 {(Dog), (Dog) } | 12.5
 {(Elephant), (Elephant)} | 20
 {(Cow)} | 15

How can I extract just the individual animal ?
I am using GROUP by like this.
--animal_weight is derived through other means
animal_by = GROUP animal_weight by (animal);
results = FOREACH animal_by GENERATE animal_weight.animal as animal_name, AVG(animal_weight.weight) as kg;
STORE results INTO '$output_4' USING PigStorage('|');

A: Use group instead of animal_weight.animal.Note that from your sample data,Dog should have an average of weight (10+20+15)/3 = 15 kg
results = FOREACH animal_by GENERATE group as animal_name, AVG(animal_weight.weight) as kg;

Output


Q: Unable to get data from child form into selected Parent DataGridView Cell I have been stumped on a programming issue. When I right click on a cell of a DataGridView object, a context menu will show. From that context menu, a user can click an option. That option will show a form. When the user is finished, the resultant of that form will be populated in the selected cell.
Problem: How do I get the result from the child form into the selected cell? There are multiple DataGridView objects on the parent form that use the same functionality.
Code:
    private void commandOperation(Object sender, EventArgs e)
    {
        if (sender == dec2HexToolStripMenuItem)
        {
            frmNumFormatConv form = new frmNumFormatConv();
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // Get data from the form into the selected cell!!!
            }
        }
        else
        {
            throw new Exception("Operational object unknown");
        }
    }

    private void cellMouseDown(Object sender, DataGridViewCellMouseEventArgs e)
    {
        if (sender == dgvCircuit1TestSetup || sender == dgvCircuit2TestSetup)
        {
            if (e.Button == MouseButtons.Right)
            {
                ((DataGridView)sender).CurrentCell = ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex];
                itsGridContextMenu.Show((DataGridView)sender, new Point(e.X, e.Y));
            }
        }
    }

A: A very easy way is to put a public property in the popup form that will return the values you want (Say RtnValue).  Then
This is an example for popup form:
    public string RtnValue
    {
        set { textBox1.Text = value; }
    }

This is your current code:
frmNumFormatConv form = new frmNumFormatConv();
        if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            dgvalue = form.RtnValue;
            // Get data from the form into the selected cell!!!
        }


Q: Why when I merge 2 pdf files with `gs` (ghostscript) the identify command cannot get the page count? This my gs command than merges 2 one-page pdf file:
gs -dNOPAUSE -dSAFER -sDEVICE=pdfwrite -sOUTPUTFILE=/tmp/blahblahblah.pdf -dBATCH page1.pdf page2.pdf

And this is the output:
GPL Ghostscript 8.70 (2009-07-31)
Copyright (C) 2009 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
Processing pages 1 through 1.
Page 1
Can't find (or can't open) font file /usr/share/ghostscript/8.70/Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Can't find (or can't open) font file /usr/share/ghostscript/8.70/Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Querying operating system for font files...
Can't find (or can't open) font file /usr/share/ghostscript/8.70/Resource/Font/ArialMT.
Can't find (or can't open) font file ArialMT.
Didn't find this font on the system!
Substituting font Helvetica for ArialMT.
Loading NimbusSanL-Regu font from /usr/share/fonts/default/Type1/n019003l.pfb... 3397696 1943901 17192756 15861178 3 done.

The font ArialMT is not found and Helvetica is substituted with it. I got the merged file from server by scp and opened it in my local system. The file is properly merged including 2 pages. So file has no problem. Now I use the below command in order to get the PDF page count:
identify -format %n '/tmp/blahblahblah.pdf'

This command cannot get the page count and gives the below error:
identify: Postscript delegate failed `/tmp/blahblahblah.pdf': No such file or directory @ error/pdf.c/ReadPDFImage/664.

NB: I should note that file exist in /tmp/blahblahblah.pdf path!
Why I cannot get page count via identify?
Sample files are attached in link below:
2 PDF sample file


Q: Verify that every cylinder set is clopen
Let $X := Σ^{\mathbb N}$ be the set of all configurations over an alphabet $Σ$. Every word $w = w_1w_2 · · · w_n ∈ Σ^∗$ defines a subset of $X$ by
$C(w) :=$ {$x ∈ X : x_1x_2 · · · x_n = w_1w_2 · · · w_n$} .
This is called the cylinder set with base $w$ in $X$. Observe that $C(λ) = X$.

(a) Verify that the cylinder sets in $X$ form a basis for a topology on $X$.

(b) Let us equip $X$ with the topology generated by the cylinder sets.
Verify that every cylinder set is clopen (i.e., both open and closed) in $X$.

My attempts:
(a) I have to prove the 2 properties of a basis for a topology.

*

*Every $\lambda$ in $X$ is some base element because $X=C(\lambda)$, so one base element suffices.

*For any two elements $B_1 = C(w_1)$ and $B_2 = C(w_2)$ and any $x \in B_1 \cap B_2$, we must find some $B_3$ containing $x$ sitting inside this intersection. We know that $x=x_1=w_1=x_2=w_2$. And I don't know how to continue from there to find such a $B_3$.

(b) I don't know how to prove this. Any help please? Thank you

A: In the second part of (a) you have to prove:

if $v,w\in\Sigma^*$, and $x\in B(v)\cap B(w)$, then there is a $u\in\Sigma^*$ such that $x\in B(u)\subseteq B(v)\cap B(w)$.

Let $v=v_1 v_2\ldots v_m$ and $w=w_1 w_2\ldots w_n$. Then $x_k=v_k$ for $k=1,\ldots,m$, and $x_k=w_k$ for $k=1\ldots n$. Without loss of generality we may assume that $m\le n$, so that $v_k=x_k=w_k$ for $k=1,\ldots,m$. I claim that $B(w)\subseteq B(v)$.
Suppose that $y\in B(w)$; then $y_k=w_k$ for $k=1,\ldots,n$, so in particular $y_k=w_k=v_k$ for $k=1,\ldots,m$, and therefore $y\in B(v)$. Thus, $B(w)\subseteq B(v)$, and therefore $x\in B(w)\subseteq B(v)\cap B(w)$. That is, you can take $u=w$.
For (b) you know that the cylinder sets are open by definition, so you need only prove that they are also closed. Let $w=w_1\ldots w_n\in\Sigma^*$. The most straightforward way to show that $B(w)$ is closed is to show that $X\setminus B(w)$ is open, which you can do by showing that it is a union of cylinder sets.

*

*Show that $x\in X\setminus B(w)$ if and only if there is a $k\in\{1,\ldots,n\}$ such that $x_k\ne w_k$.

*Show that there is a $k\in\{1,\ldots,n\}$ such that $x_k\ne w_k$ if and only if $$x\in\bigcup_{\sigma\in\Sigma\setminus\{w_k\}}B(\sigma)\,.$$

*Conclude that $$X\setminus B(w)=\bigcup_{k=1}^n\bigcup_{\sigma\in\Sigma\setminus\{w_k\}}B(\sigma)\,,$$ which is a union of cylinder sets.

A: Give $\Sigma$ the discrete topology, which has a base $\mathcal{B}= \{\{\sigma\}\mid \sigma \in \Sigma\}$.
Then the cilinder sets are the basic sets in the product topology on $\Sigma^{\Bbb N}$ derived from this component base $\mathcal{B}$, namely of the form $\prod_n U_n$ where we have some $N \in \Bbb N$ such that $U_n \in \mathcal{B}$ for $n \ge N$ and $U_n = \Sigma$ for $n > N$. So we have a base because we recognise it as a the standard topology on $\Sigma^{\Bbb N}$, topologically.
As all sets in $\mathcal{B}$ are clopen (as $\Sigma$ has the discrete topology) the same holds for the product base derived from them. This is quite clear if you know about product topologies; e.g $\overline{\prod_n U_n} = \prod_n \overline{U_n}$ is classical.


Q: How to block ip Ranges using http modules? How to block Ip ranges using http modules with c# . I have a simple solution but its for single Ip and How can I read IPs from  xml file in http modules so that if an IP is there in that file it will be blocked  .Here is my code
public class MyHandler :IHttpModule
{
 public MyHandler(){}

    public bool IsReusable
    {
        get { return false; }
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Application_BeginRequest);
    }
    private void Application_BeginRequest(object source, EventArgs e)
    {
        HttpContext context = (source as HttpApplication).Context;
        List<string> BlackListIp = new List<string>();
        BlackListIp.Add("127.0.0.1");

        if (BlackListIp.Contains(context.Request.UserHostAddress))
        {
            context.Response.Write("
Your IP is Blocked
");
        }
    }

    public void Dispose()
    {
    }
}

A: Just add the xml file inside app_data folder and read it using XDocument.
You can event use Cache with FileDependency to improve performance.


Q: Disable other checkboxes in a GroupBox when two are checked  Private Sub AllBoxes_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged, CheckBox4.CheckedChanged, CheckBox5.CheckedChanged, CheckBox6.CheckedChanged

    Dim qty As Int16 = 0
    Dim cb As CheckBox

    For Each cb In GroupBox8.Controls.OfType(Of CheckBox)
        If cb.Checked Then
            qty += 1
        End If
    Next

    If qty = 2 Then

        For Each cb In GroupBox8.Controls.OfType(Of CheckBox)
            If Not cb.Checked Then
                cb.Enabled = False
            End If
        Next
    Else

        For Each cb In GroupBox8.Controls.OfType(Of CheckBox)
            cb.Enabled = True
        Next
    End If
End Sub

it just doesn't work. The groupbox's name is groupbox8 and it has 6 checkboxes on it. I need to select two checkboxes.

A: You can simplify a lot your CheckedChanged event handler using a bit of Linq
Private Sub AllBoxes_CheckedChanged(sender As Object, e As EventArgs)

    ' Get all checkboxes in the groupBox8
    Dim checks = groupBox8.Controls.OfType(Of CheckBox)()
    ' Count how many are checked
    Dim cnt = checks.Where(Function(x) x.Checked).Count()

    If cnt < 2 Then
        ' Enable all, avoid an if and don't care if already enabled
        For Each c In checks
            c.Enabled = True
        Next
    Else
        ' Disable all except the two checked...
        For Each k In checks.Where(Function(x)  Not x.Checked)
            k.Enabled = False
        Next
    End If
End Sub


Q: Cannot access XML Document using simplexml_load_file() I NEED HELP! I'm trying to generate XML document from my website database in hosting provider and accessing it from my home PC, right now I'm doing it in localhost environment. I use these codes and I got error message in browser. Please take a look at  my codes...
data.php for generating XML document
<?php
include ("koneksi-database.php");

header('Content-Type: text/xml');
echo "<?xml version='1.0'?>";
echo "<outbox>";

$query = "SELECT * FROM `tbstatus` WHERE `status` = '$status' ORDER BY `ID`";
$result = mysql_query($query);

while ($data = mysql_fetch_array($result))
{
echo "<data>";

    echo "<trx>".$data['trx']."</trx>";
    echo "<status>".$data['status']."</status>";
    echo "<signature>".$data['signature']."</signature>";
    echo "<time>".$data['time']."</time>";

echo "</data>";
}

echo "</outbox>";
?>

read.php for reading the XML document in localhost
print_r($dataxml = simplexml_load_file('data.php'));

I also create index.php for running the script every 5 seconds.

Server is Running...

finally this the error messages that i get from browser when I open read.php.
Warning: simplexml_load_file() [function.simplexml-load-file]: data.php:9: parser error : Start tag expected, '<' not found in C:\xampplite\htdocs\simpul\baca.php on line 9

Warning: simplexml_load_file() [function.simplexml-load-file]: echo "<?xml version='1.0'?>"; in C:\xampplite\htdocs\simpul\baca.php on line 9

Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in C:\xampplite\htdocs\simpul\baca.php on line 9

A: Your print_r($dataxml = simplexml_load_file('data.php')); is reading you raw PHP file, not the script execution result!
data.php file have a PHP code that outputs a XML file, not a really XML file.
You should use print_r($dataxml = simplexml_load_file('http://localhost/data.php')); for example. (Assuming that http://localhost/data.php is the url to access your file.)
using only 'data.php' as parameter will get the raw file from server, not processed by PHP.


Q: Referencing the current jQuery object in a chain? At DevDays in SF last year (before jQuery 1.4 was released), I thought they mentioned an upcoming feature in 1.4 that would allow you to reference the current jQuery object while in a chain. I've read through all of the 1.4 improvements and wasn't able to find it. Does anyone know how this can be done?
Example
Being able to access the current jQuery object would be helpful when working with methods that are in relation to the current object like .next():
// Current way
var items = $(this).closest('tr');
items = items.add(items.next(':not([id])'));

// Magical 1.4 way? Is there a "chain"-like object?
var items = $(this).closest('tr')
    .add(chain.next(':not([id])'));

A: I think this is the closest available, using .andSelf():
var items = $(this).closest('tr').next(':not([id])').andSelf();

This goes to the .next() call, but then adds the tr back to it.  Everything is in the context of where the chain occurs, so either jumping around to add elements, or storing the original reference as you have it is as close as is currently available.  These are the helpful functions for jumping around: http://api.jquery.com/category/traversing/miscellaneous-traversal/
John Resig posted this concept a while back, but to my knowledge, nothing closer to that has made it into jQuery core.  You can however use the code posted on the blog there if you want.

A: Possibly andSelf() http://api.jquery.com/andSelf/
This returns the previous selection, but you would then have to use :not([id]) on everything..


Q: Android Image Upload Fails I'm trying to upload an image from my phone to a server. So I get the image uri and create a NameValuePair with it. I then use the following Android code to get a connection and upload the pic. This was taken from previous stackoverflow question(I would link but can't find it even with Google...)
public void post(String url, List<NameValuePair> nameValuePairs) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
           MultipartEntity entity = new
                       MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

             entity.addPart(nameValuePairs.get(0).getName(), new FileBody(new File(nameValuePairs.get(0).getValue())));
        Log.v("Uploading file",nameValuePairs.get(0).getValue());
        httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
           Log.v("Response", response.toString());
        } catch (IOException e) {
          e.printStackTrace();
        }
   }

On the server side I have the following code. This is PHP, which I am a complete novice at. I know there is no validation in the code, but I want to get the upload working before I start worrying about everything else.
      <?php

     if($_FILES){
           $name = $_FILES['image']['name'];
           move_uploaded_file($_FILES['image']['temp'],$name);

           echo "success!";
     }
    else {

  echo "Nothing uploaded";
   }
 ?>

Here the name of the NameValuePair is 'image', which is used as the file name.
Nothing gets uploaded, but a connection is made. Please help.
Following the request I put print_r($Files) in the code. The respons from the server was:
09-05 23:23:35.745: VERBOSE/Response(13849): Array

09-05 23:23:35.745: VERBOSE/Response(13849): (

09-05 23:23:35.745: VERBOSE/Response(13849):     [image] => Array

09-05 23:23:35.745: VERBOSE/Response(13849):         (

09-05 23:23:35.745: VERBOSE/Response(13849):             [name] => DSC_0100.jpg

09-05 23:23:35.745: VERBOSE/Response(13849):             [type] =>

09-05 23:23:35.745: VERBOSE/Response(13849):             [tmp_name] => /tmp/phpXcY8L1

09-05 23:23:35.745: VERBOSE/Response(13849):             [error] => 0

09-05 23:23:35.745: VERBOSE/Response(13849):             [size] => 806873

09-05 23:23:35.745: VERBOSE/Response(13849):         ) 09-05 23:23:35.745: VERBOSE/Response(13849): )

09-05 23:23:35.745: VERBOSE/Response(13849):**

A: On server side please add this code ,
print_r($_FILES);

then check for array parameter 'error' then check error code from here
  http://php.net/manual/en/features.file-upload.errors.php
if you want the file upload code for android then please tell me i can post here
i hope this will help you.
Thank you.

A: move_uploaded_file($_FILES['image']['temp'],$name); replace this line with
move_uploaded_file($_FILES['image']['tmp_name'],$name);
The file's temporary file name is in "tmp_name", as i can see from your log output.


Q: RPN stacking method not working with converted string arrays I'm trying to make a program that processes a line of rpn expression through a stack method. The input is a string array that is converted from a string input.
String[] collect = "8 6 + 2 /"; //the
String line; //the inputed line
collect = line.split(" "); //the conversion
System.out.println(stackem(collect)); // calling the stack method for an output method

The problem is that the output is always the operator ate the end of the line, so when I put in the code that checks for malformed expressions it always turns into the error. Basically my input would be like this:
input: 8 6 + 2 /
output: Error: "Expression is malformed"
output (without the error code): /
output (what's supposed to be the output): 7
This is the code for the stack method:
public String stackem(String[] input)
{
Stack<String> stack = new Stack<String>();
int x, y;
String result = "";
int get = 0;
String choice;
int value = 0;
String p = "";
int output;

try
{
for (int i = 0; i < input.length; i++)
{
if (input[i] == "+" || input[i] == "-" || input[i] == "*" || input[i] == "/" || input[i] == "^")
{
choice = input[i];
}
else
{
stack.push(input[i]);
continue;
}

switch (choice)
{
case "+":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x + y;
result = p + value;
stack.push(result);
break;

case "-":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y - x;
result = p + value;
stack.push(result);
break;

case "*":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x * y;
result = p + value;
stack.push(result);
break;

case "/":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y / x;
result = p + value;
stack.push(result);
break;

case "^":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = (int)Math.pow(y,x);
result = p + value;
stack.push(result);
break;

default:
continue;
}
}

output = Integer.parseInt(stack.pop());
}
catch (Exception ex)
{
return "Error: Expression is malformed";
}
return "Result: " + output;
}

Is there any way to fix this issue?


Q: Paypal recurring payment IPN usage I successfully create a listener and it is working well if I am using the IPN simulator. However, when I am doing the payment request in the process of payment, I set the same listener url for the notify_url, nothing happens even the process working properly. How can I know if someone cancel his recurring payment directly from the Paypal or how do I setup up the listener whenever a recurring payment is made? Is it something wrong with my notify_url? This is what my notify_url look like:

http://example.com/paypal_notification/ipn_callback

No extra parameters. Is it correct? Thank you in advance.

A: You should be getting an IPN when the profile is created, each time the recurring profile bills, and when the profile is cancelled.  Check your IPN history in your account to make sure the IPN's are being sent out, and check to see if there is any type of error being returned to PayPal.  Check your server access logs to see PayPal is calling your script and check your error logs to see if anything is being triggered.  Try adding www. to your URL, and the ext to the end of your URL for the type of file it is.  Also, there are some IPN troubleshooting tips I posted for IPN on this forum POST.

A: The IPN will only be sent to the account on which the profile was created.
Here's how I would do it.

*

*Store the Paypal ProfileID and e-mail address in a database.

*Receive all of the IPN notifications yourself, and in the case of a failure, send an e-mail to the specific user based on their ProfileID, or perform other actions.


Q: Installing USB Wi-Fi driver on Zorin I installed Zorin 10 (after trying Mint and Ubuntu).
My problem is I have a TP LINK Archer T2UH USB Wi-Fi adapter. Their website has the Linux driver for it(http://www.tp-link.com/res/down/soft/Archer_T2UH_V1_150909.zip), but I have no idea how to install it: it has a PDF file explaining the installation process, but I don't have a Ph.D in Linux. Even though it is in English, I have no clue what it is saying.
I have tried multiple ways to get it to work:

*

*terminal commands from YouTube videos,

*windows wireless drivers,

*etc...

Nothing seems to work. Any help would be appreciated.


Q: Python: How can I find the heading of the road using Google Maps API? I wrote a program in python that takes in a starting point and end point and then uses google maps API to create a gif of the route using google street view. Everything works perfectly I just can't find a way to get the bearing/heading of the car. The resulting gifs is the correct path but the camera doesn't point at the road.
https://www.dropbox.com/s/b17el2lmiyna7m6/finalproduct8fps.gif?dl=0
here is sample to show you what I mean, the camera isn't pointing at the road at all times, how can I get the heading of the vehicle?


Q: Android lint custom check UCallExpression type of method receiver I'm writing custom lint check to ban some methods. So if someone calls banned method foo on instance of class A, lint should report error.
I achieved this for static methods like this (inside visitCallExpression(UCallExpression):
node.receiver as UReferenceExpression).getQualifiedName()

From qualified name I can get the Class object and run my check but I can't get the qualified name for methods called on instantiated object. I can get the name of the class to which the objects belongs but not the qualified name.
How do I get qualified name of class of method that is called on instance of that class? If I'm being unclear, here is an example.
import android.view.Button;

class ButtonSetTextIntClass {
       private Button button;

       public void bannedSetText (){
            button.setText(123);
       }
}

And I need in visitCallExpression (UCallExpression) get qualified name/class of button.

A: UCallExpression.receiverType does what you want:
public class CustomDetector extends Detector implements SourceCodeScanner {

    @Nullable
    @Override
    public List<Class<? extends UElement>> getApplicableUastTypes() {
        return Collections.singletonList(UCallExpression.class);
    }

    @Nullable
    @Override
    public UElementHandler createUastHandler(@NotNull JavaContext context) {
        return new UElementHandler() {

            @Override
            public void visitCallExpression(@NotNull UCallExpression node) {
                node.getReceiverType(); // PsiType:Button
            }
        };
    }
}

To extract qualified name you can use the following method:
((PsiClassType) node.getReceiverType()).resolve().getQualifiedName() // android.widget.Button

A: I found a solution which works for both static and non-static methods and for Kotlin top level functions. Not sure if it is the best way to do it but at least it works.
override fun visitCallExpression(node: UCallExpression) {
     (node.resolve()?.parent as? ClsClassImpl)?.stub?.qualifiedName
}

A:     /**
     * eg: android.util.Log
     * ps. imports was initialized in visitImportStatement
     */
    private fun getClassNameWithPackage(node: UCallExpression): String {
        var className = node.resolve()?.containingClass?.qualifiedName
        if (className != null) {
            return className
        }

        className = getClassName(node) ?: return ""
        for (import in imports) {
            if (import.contains(className)) {
                return import
            }
        }
        return "$packageName.$className"
    }

    /**
     * eg: Log
     */
    private fun getClassName(node: UCallExpression): String? {
        return node.receiver?.javaPsi?.text ?: when (val uExpression = (node.methodIdentifier?.uastParent as UCallExpression?)?.receiver) {
            is JavaUSimpleNameReferenceExpression -> {
                uExpression.identifier
            }
            is KotlinUSimpleReferenceExpression -> {
                uExpression.identifier
            }
            is UReferenceExpression -> {
                uExpression.getQualifiedName()
            }
            else -> null
        }
    }


Q: sphinxsearch-0.9 in mediawiki-1.32.0 error 2019/01/14 12:04:51 [error] 21549#21549: *3558 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Class SphinxMWSearch contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (SearchDatabase::doSearchTextInDB, SearchDatabase::doSearchTitleInDB) in /var/opt/www/extensions/SphinxSearch/SphinxMWSearch.php on line 15" while reading response header from upstream, client: 192.168.122.1, server: wiki.yuyizhi.org, request: "GET /index.php?title=Special:%E6%90%9C%E7%B4%A2&search=sphinx HTTP/1.0", upstream: "fastcgi://unix:/var/run/php-fpm/php5-fpm.sock:", host: "wiki.yuyizhi.org"

FastCGI sent in stderr: "PHP message: PHP Fatal error:  Class SphinxMWSearch contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (SearchDatabase::doSearchTextInDB, SearchDatabase::doSearchTitleInDB) in /var/opt/www/extensions/SphinxSearch/SphinxMWSearch.php on line 15", client: 192.168.122.1, server: wiki.abc.com, request: "GET /api.php?action=opensearch&search=bai&namespace=0 HTTP/1.0", host: "wiki.abc.com"

A: The SearchDatabase class that SphinxSearch extends was changed from REL1_31 to REL1_32. It now requires you to define doSearchTextInDB and doSearchTitleInDB methods.
See REL1_31 https://doc.wikimedia.org/mediawiki-core/REL1_31/php/classSearchDatabase.html
vs REL1_32 https://doc.wikimedia.org/mediawiki-core/REL1_32/php/classSearchDatabase.html
This is sortof mentioned in the patch notes if you search for Search under deprecation (note this is a Backwards compatibility break instead) https://www.mediawiki.org/wiki/Release_notes/1.32#Compatibility:

Overriding SearchEngine::{searchText,searchTitle,searchArchiveTitle} in extending classes is deprecated. Extend related doSearch* methods instead.

If you are like me and not comfortable fixing the extension yourself, you will have to wait for one of the extension contributors to update the extension to work with REL1_32. Until then you will have to stay on REL1_31 if you wish to use the extension.

A: Just adding these two empty functions to SphinxMWSearch.php under the definition of SphinxMWSearch class seems to do the trick. It makes it stop complaining and - as far as I can tell - search function is working fine.
function doSearchTextInDB($term) {
}
function doSearchTitleInDB($term) {
}

Hopefully developers of this extension will come up with a proper fix soon.


Q: Android App actions issues when English Articles are used as a part of speech We have implemented android shortcuts. Testing of App actions on physical devices was fine, except for an issue with English Articles.
When English Articles appear as a part of a statement, the statement is not recognized as an action, and Assistant does not redirected to the app. For example, 'add note to Express Scheduler' is recognized, while 'add a note to Express Scheduler' is not.
My question is whether anybody have experienced similar issues?
Please, see capabilities segment extracted from shortcuts.xml. I am  using actions.intent.CREATE_THING and actions.intent.GET_THING BIIs. I've listed one example above: 'add note to Express Scheduler' is recognized, while 'add a note to Express Scheduler' is not.
<capability android:name="actions.intent.CREATE_THING">
    <intent>
        <url-template android:value="https://vijac.ca/schedule{?name,description}" />
        <parameter
            android:name="thing.name"
            android:key="name"
            android:required="false" />
        <parameter
            android:name="thing.description"
            android:key="description"
            android:required="false" />
    </intent>
</capability>

<capability android:name="actions.intent.GET_THING">
    <intent>
        <url-template android:value="https://vijac.ca/search{?name}" />
        <parameter
            android:name="thing.name"
            android:key="name" />
    </intent>
</capability>enter code here

Thank you!

A: I think what may be happening is that you have a very generic name of the thing ("a note"), when it is expecting to handle specific names which normally don't need an article ("Pixel 4", "Stairway to Heaven").
You may want to try one of these to address the problem:

*

*The thing.name parameter for that BII allows for an inline inventory which is a way of setting allowable values and alises for those values. You can create an inventory item for note that has aliases such as "a note" and "note".

*Consider using the actions.intent.CREATE_DIGITAL_DOCUMENT BII which indicates that it supports phrases such as "Create a note".


Q: htaccess redirect .PDF for Prevent Direct Access but visible in internal viewer I'm developing with a small web-based project with WordPress which contains a lot of PDF files. What I'm looking for is to close the direct access to PDF files, like in https://sciami.com/scm-content/uploads/2018/06/myfile.pdf and redirect the request to the attachment page in https://sciami.com/myfile.
To do this, I wrote a code in .htaccess as below:
RewriteCond %{REQUEST_URI} \.pdf$ [NC]
RewriteRule ^scm-content/uploads/([0-9]+)/([0-9]+)/(.+)\.pdf$ /$3 [R=301,L]

In this way all PDFs are redirected to related attachment page (and it works!). Inside the attachment page, there is a PDF viewer that shows related PDF file. But because of the rule written in the .htaccess, the PDF viewer doesn't show anything because the https://sciami.com/scm-content/uploads/2018/06/myfile.pdf URL necessary for show PDF is rewritten.
My question is how to close the direct access to PDFs, while allowing them to be loaded within the viewer?
The condition
RewriteCond %{HTTP_REFERER} !^https://(www.)?sciami.com/ [NC]

allows operation within the site, but prevents redirect from within the site.
Every help is welcome.


Q: Filter custom post types by Post Object Custom Field I have post types named "tour" and "country".
"tour" post type has some custom fields and type of one of them is Post Object and filtered by Post Type "country".
Now I want to show tours filtered by a specific country, for example:
$located_tours = get_posts(array(
    'numberposts'   => 3,
    'post_type'     => 'tour',
    'meta_key'      => 'country',
    'meta_value'    => 'turkey'
));

But the result for this query shows nothing.
I know "country" I have used as meta_key is an object, but how can I use it correctly in my query?
Anyone has any idea?
Thanks


Q: Laravel Controller beforeFilter not working as expected My controllers constructor looks like
function __construct(MessageRepository $message)
{
    $this->beforeFilter('canViewThisMessage', array('only', 'show'));
    $this->message = $message;
    $this->pagesize = 8;
    $this->pageTitle = 'messages';
}

and I expect the filter to be applied on show action. Which looks like
public function show($id)
{
    $message = Message::findOrFail($id);

    return View::make('messages.show', compact('message'));
}

But the filter is applied on all actions, not just on show method! Why is this happening?

A: I think instead of:
$this->beforeFilter('canViewThisMessage', array('only', 'show'));

you should use:
$this->beforeFilter('canViewThisMessage', array('only' =>  ['show']));

or
$this->beforeFilter('canViewThisMessage', array('only' =>  'show'));

looking at documentation


Q: html5shiv.js and respond.js without Bootstrap 3

 <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

Whenever I search for these scripts on the internet they are always connected with Bootstrap 3. Should I use them in any responsive website using HTML5?


Q: setColorFilter not working with resource color If I use setColorFilter like this, it works and paint my image with the chosen color:
int color = Color.parseColor("#FF0000");
viewHolder.Icon.setColorFilter(color);

But if I try to use a resource color, it does nothing:
viewHolder.Icon.setColorFilter(R.color.colorPrimary);

where the resource is defined like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#FF5722</color>
</resources>

A: try this
int actionBarBackground = getResources().getColor(R.color.actionBarBackground);

and you set actionBarBackground in the method setColorFilter thats all

A: Answer marked as "right" use getColor() method which is deprecated.
That's why here is up-to-date answer:
int color = ResourcesCompat.getColor(getResources(), R.color.my_color, null);

A: please add   PorterDuff.Mode.MULTIPLY  See below example
viewHolder.Icon.getDrawable().setColorFilter(getResources().getColor(R.color.blue), PorterDuff.Mode.MULTIPLY );


Q: Joss eap 6.4 upgrade to 7.2 :javax.persistence.spi.PersistenceProvider: Provider org.eclipse.persistence.jpa.PersistenceProvider not a subtype Jboss eap 6.4 upgrade to 7.2 deploy ear error
{"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WLS_DOM_SPS.ear\".FIRST_MODULE_USE" => "WFLYSRV0153: Failed to process phase FIRST_MODULE_USE of deployment \"WLS_DOM_SPS.ear\"
    Caused by: java.util.ServiceConfigurationError: javax.persistence.spi.PersistenceProvider: Provider org.eclipse.persistence.jpa.PersistenceProvider not a subtype"}}

eclipse link module config :
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.eclipse.persistence">
    <resources>
        <resource-root path="javax.persistence_1.1.0.0_2-0.jar"/>
        <resource-root path="eclipselink-2.1.2_TMSModified1.jar">
            <filter>
                <exclude path="javax/**" />
            </filter>
        </resource-root>
    </resources>

    <dependencies>
        <module name="asm.asm"/>
        <module name="javax.api"/>
        <module name="javax.annotation.api"/>
        <module name="javax.enterprise.api"/>
        <module name="javax.persistence.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.validation.api"/>
        <module name="javax.xml.bind.api"/>
        <module name="org.antlr"/>
        <module name="org.apache.commons.collections"/>
        <module name="org.dom4j"/>
        <module name="org.javassist"/>
        <module name="org.jboss.as.jpa.spi"/>
        <module name="org.jboss.logging"/>
        <module name="org.jboss.vfs"/>
    </dependencies>
</module>

jboss eap 6.4 can deploy success. Don't know where the problem is.
javax.persistence.jar-javax.persistence.spi.PersistenceProvider
package javax.persistence.spi;

import java.util.Map;
import javax.persistence.EntityManagerFactory;

public interface PersistenceProvider {
    EntityManagerFactory createEntityManagerFactory(String var1, Map var2);

    EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo var1, Map var2);

    ProviderUtil getProviderUtil();
}

eclipselink-org.eclipse.persistence.jpa.PersistenceProvider
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.eclipse.persistence.jpa;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.LoadState;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.ProviderUtil;
import org.eclipse.persistence.exceptions.PersistenceUnitLoadingException;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider;
import org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl;
import org.eclipse.persistence.internal.jpa.deployment.JPAInitializer;
import org.eclipse.persistence.internal.jpa.deployment.PersistenceInitializationHelper;
import org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor;
import org.eclipse.persistence.internal.jpa.deployment.SEPersistenceUnitInfo;
import org.eclipse.persistence.internal.weaving.PersistenceWeaved;

public class PersistenceProvider implements javax.persistence.spi.PersistenceProvider, ProviderUtil {
    protected PersistenceInitializationHelper initializationHelper = null;

    public PersistenceProvider() {
        this.initializationHelper = new PersistenceInitializationHelper();
    }

    public EntityManagerFactory createEntityManagerFactory(String emName, Map properties) {
        ClassLoader classloader = this.initializationHelper.getClassLoader(emName, properties);
        return this.createEntityManagerFactory(emName, properties, classloader);
    }

    protected EntityManagerFactory createEntityManagerFactory(String emName, Map properties, ClassLoader classLoader) {
        Map nonNullProperties = properties == null ? new HashMap() : properties;
        String name = emName;
        if (emName == null) {
            name = "";
        }

        JPAInitializer initializer = this.initializationHelper.getInitializer(classLoader, (Map)nonNullProperties);
        EntityManagerSetupImpl emSetupImpl = null;
        boolean isNew = false;

        String uniqueName;
        String sessionName;
        SEPersistenceUnitInfo factory;
        try {
            factory = initializer.findPersistenceUnitInfo(name, (Map)nonNullProperties, this.initializationHelper);
            if (factory == null) {
                return null;
            }

            if (initializer.isPersistenceUnitUniquelyDefinedByName()) {
                uniqueName = name;
            } else {
                uniqueName = initializer.createUniquePersistenceUnitName(factory);
            }

            sessionName = EntityManagerSetupImpl.getOrBuildSessionName((Map)nonNullProperties, factory, uniqueName);
            synchronized(EntityManagerFactoryProvider.emSetupImpls) {
                emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(sessionName);
                if (emSetupImpl == null) {
                    if (EntityManagerFactoryProvider.initialEmSetupImpls != null) {
                        emSetupImpl = (EntityManagerSetupImpl)EntityManagerFactoryProvider.initialEmSetupImpls.remove(uniqueName);
                        if (emSetupImpl != null) {
                            emSetupImpl.changeSessionName(sessionName);
                            factory.setClassLoader(classLoader);
                        }
                    }

                    if (emSetupImpl == null) {
                        emSetupImpl = initializer.callPredeploy(factory, (Map)nonNullProperties, this.initializationHelper, uniqueName, sessionName);
                    }

                    emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties);
                    EntityManagerFactoryProvider.addEntityManagerSetupImpl(sessionName, emSetupImpl);
                    isNew = true;
                }
            }
        } catch (Exception var18) {
            throw PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(classLoader, var18);
        }

        if (!isNew) {
            if (!uniqueName.equals(emSetupImpl.getPersistenceUnitUniqueName())) {
                throw PersistenceUnitLoadingException.sessionNameAlreadyInUse(sessionName, uniqueName, emSetupImpl.getPersistenceUnitUniqueName());
            }

            boolean undeployed = false;
            synchronized(emSetupImpl) {
                if (emSetupImpl.isUndeployed()) {
                    undeployed = true;
                }

                emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties);
            }

            if (undeployed) {
                return this.createEntityManagerFactory(emName, properties, classLoader);
            }
        }

        factory = null;

        try {
            EntityManagerFactoryImpl factory = new EntityManagerFactoryImpl(emSetupImpl, (Map)nonNullProperties);
            if (emSetupImpl.shouldGetSessionOnCreateFactory((Map)nonNullProperties)) {
                factory.getServerSession();
            }

            return factory;
        } catch (RuntimeException var15) {
            if (factory != null) {
                factory.close();
            } else {
                emSetupImpl.undeploy();
            }

            throw var15;
        }
    }

    public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
        Map nonNullProperties = properties == null ? new HashMap() : properties;
        EntityManagerSetupImpl emSetupImpl = null;
        boolean isNew = false;
        ClassTransformer transformer = null;
        String uniqueName = PersistenceUnitProcessor.buildPersistenceUnitName(info.getPersistenceUnitRootUrl(), info.getPersistenceUnitName());
        String sessionName = EntityManagerSetupImpl.getOrBuildSessionName((Map)nonNullProperties, info, uniqueName);
        synchronized(EntityManagerFactoryProvider.emSetupImpls) {
            emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(sessionName);
            if (emSetupImpl == null) {
                emSetupImpl = new EntityManagerSetupImpl(uniqueName, sessionName);
                isNew = true;
                emSetupImpl.setIsInContainerMode(true);
                transformer = emSetupImpl.predeploy(info, (Map)nonNullProperties);
                EntityManagerFactoryProvider.addEntityManagerSetupImpl(sessionName, emSetupImpl);
            }
        }

        if (!isNew) {
            if (!uniqueName.equals(emSetupImpl.getPersistenceUnitUniqueName())) {
                throw PersistenceUnitLoadingException.sessionNameAlreadyInUse(sessionName, uniqueName, emSetupImpl.getPersistenceUnitUniqueName());
            }

            boolean undeployed = false;
            synchronized(emSetupImpl) {
                if (emSetupImpl.isUndeployed()) {
                    undeployed = true;
                }

                transformer = emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), (Map)nonNullProperties);
            }

            if (undeployed) {
                return this.createContainerEntityManagerFactory(info, properties);
            }
        }

        if (transformer != null) {
            info.addTransformer(transformer);
        }

        EntityManagerFactoryImpl factory = new EntityManagerFactoryImpl(emSetupImpl, (Map)nonNullProperties);
        if (emSetupImpl.shouldGetSessionOnCreateFactory((Map)nonNullProperties)) {
            factory.getServerSession();
        }

        return factory;
    }

    public ProviderUtil getProviderUtil() {
        return this;
    }

    public LoadState isLoadedWithoutReference(Object entity, String attributeName) {
        return entity instanceof PersistenceWeaved ? this.isLoadedWithReference(entity, attributeName) : LoadState.UNKNOWN;
    }

    public LoadState isLoadedWithReference(Object entity, String attributeName) {
        Iterator setups = EntityManagerFactoryProvider.getEmSetupImpls().values().iterator();

        while(setups.hasNext()) {
            EntityManagerSetupImpl setup = (EntityManagerSetupImpl)setups.next();
            if (setup.isDeployed()) {
                Boolean isLoaded = EntityManagerFactoryImpl.isLoaded(entity, setup.getSession());
                if (isLoaded != null) {
                    if (isLoaded && attributeName != null) {
                        isLoaded = EntityManagerFactoryImpl.isLoaded(entity, attributeName, setup.getSession());
                    }

                    if (isLoaded != null) {
                        return isLoaded ? LoadState.LOADED : LoadState.NOT_LOADED;
                    }
                }
            }
        }

        return LoadState.UNKNOWN;
    }

    public LoadState isLoaded(Object entity) {
        return entity instanceof PersistenceWeaved ? this.isLoadedWithReference(entity, (String)null) : LoadState.UNKNOWN;
    }
}

The above is the interface and implementation of PersistenceProvider.
Can't see any mismatch


Q: Facebook SDK (Require "Like" for access) I only want people that like'd our Facebook page to access a specific section of the site. But i'm relatively new with the Facebook SDK. Is there a way to check whether someone liked our page? If not possible with SDK are there other reliable ways to do so?

A: Like-gating is not allowed by the Facebook platform policies (chapter 4.5).
See

*

*https://developers.facebook.com/policy/#properuse

Only incentivize a person to log into your app, enter a promotion on your app’s Page, or check-in at a place. Don’t incentivize other actions.


Q: How to produce and consume JSON messages between Django services using Redis as a message queue? I am trying to find a way to enable communication between two Django services using Redis as a message queue.
One service would produces JSON data, publish it to the queue and the other one would consume the message.
Something similar to what I want to achieve is described here using Spring Boot and RabbitMQ: https://www.javainuse.com/spring/spring-boot-rabbitmq-consume
Any articles or suggestions would mean a lot.

A: I think there are two things to you think about:

*

*if you want to use redis with django celery (Celery beat).

*if you want to use just redis as M.Q with django.

Below are the references to help you with each case:
For Case 1: check out the link below

*

*https://enlear.academy/hands-on-with-redis-and-django-ed7df9104343
For Case 2: check out the link below

*How can I publish a message in Redis channel asynchronously with python?
(I recommand this one best : https://stackabuse.com/working-with-redis-in-python-with-django/) -- it covers all you need about using redis for caching


Q: xsl 1.0 Group by with comma separated items I have a XML similar to this
<profiles>
<profile>
  <customer>customer a </customer>
  <collateral>
    summary a
   <related>
     <solutions>sol1,sol2</solutions>
   </related>
  <collateral>
</profile>
<profile>
  <customer>customer b </customer>
  <collateral>
    summary b
   <related>
     <solutions>sol1</solutions>
   </related>
  <collateral>
</profile>

<profile>
  <customer>customer c </customer>
  <collateral>
    summary c
   <related>
     <solutions>sol2,sol3</solutions>
   </related>
  <collateral>
</profile>
</profiles>

Desired output

  customer a,summary a
 customer b, summary b

  customer a,summary a
  customer c,summary c

..............
Iam aware of Muenchian way of grouping, but not sure how I can accomplish, if I have comma separated groub-by element values. Any help will be appreciated.

A: While this is straight-forward in XSLT 2.0, in XSLT a two-pass transformation can produce the wanted results:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="kSolByVal" match="solution" use="."/>

 <xsl:template match="node()|@*" name="identity">
         <xsl:copy>
           <xsl:apply-templates select="node()|@*"/>
         </xsl:copy>
 </xsl:template>

 <xsl:template match="/">
  <xsl:variable name="vrtfPass1">
   <xsl:apply-templates/>
  </xsl:variable>

  <xsl:apply-templates select=
  "ext:node-set($vrtfPass1)
                /*/*/*/*
                   /solutions/solution
                    [generate-id()
                    =
                    generate-id(key('kSolByVal', .)[1])
                    ]"
   mode="pass2"/>
 </xsl:template>

 <xsl:template mode="pass2" match="solution">

    <xsl:apply-templates mode="pass2"
       select="key('kSolByVal', .)/../../../.."/>

 </xsl:template>

 <xsl:template match="profile" mode="pass2">
  <xsl:if test="position() = 1">
   <xsl:text>
</xsl:text>
  </xsl:if>
  <xsl:value-of select=
      "concat(customer, ', ', */summary, '
')"/>
 </xsl:template>

 <xsl:template match="solutions">
   <solutions>
     <xsl:apply-templates select="." mode="split"/>
   </solutions>
 </xsl:template>

  <xsl:template match="solutions" name="split" mode="split">
   <xsl:param name="pText" select="."/>

   <xsl:if test="string-length($pText)">
    <xsl:variable name="vText1"
         select="concat($pText, ',')"/>
    <xsl:variable name="vPart" select=
       "substring-before($vText1, ',')"/>

     <solution>
      <xsl:value-of select="$vPart"/>
     </solution>

     <xsl:call-template name="split">
      <xsl:with-param name="pText"
           select="substring($pText, string-length($vPart)+2)"/>
     </xsl:call-template>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document (corrected for well-formedness):
<profiles>
    <profile>
        <customer>customer a </customer>
        <collateral>
            summary a
            <related>
                <solutions>sol1,sol2</solutions>
            </related>
        </collateral>
    </profile>
    <profile>
        <customer>customer b </customer>
        <collateral>
            summary b
            <related>
                <solutions>sol1</solutions>
            </related>
        </collateral>
    </profile>
    <profile>
        <customer>customer c </customer>
        <collateral>
            summary c
            <related>
                <solutions>sol2,sol3</solutions>
            </related>
        </collateral>
    </profile>
</profiles>

the wanted, correct result is produced:

customer a , summary a
customer b , summary b

customer a , summary a
customer c , summary c

customer c , summary c

Explanation:

*

*We carry out the transformation in two passes. Pass2 is applied on the result of applying Pass1 on the provided XML document.

*Pass 1 is essentially the identity rule overriden for any solutions element. The processing of a solutions element consists in recursive splitting of its string value. The final result of Pass1 is the following:
--
<profiles>
   <profile>
      <customer>customer a </customer>
      <collateral>
         summary a
         <related>
            <solutions>
               <solution>sol1</solution>
               <solution>sol2</solution>
            </solutions>
         </related>
      </collateral>
   </profile>
   <profile>
      <customer>customer b </customer>
      <collateral>
         summary b
         <related>
            <solutions>
               <solution>sol1</solution>
            </solutions>
         </related>
      </collateral>
   </profile>
   <profile>
      <customer>customer c </customer>
      <collateral>
         summary c
         <related>
            <solutions>
               <solution>sol2</solution>
               <solution>sol3</solution>
            </solutions>
         </related>
      </collateral>
   </profile>
</profiles>

.3. We then apply templates (in mode="pass2") on the result of Pass1. This is a typical and traditional Muenchian grouping.


Q: How to determine which tmpfs ran out of space overnight I have a process that is using tmpfs and I need to know, out of many tmpfs, which one is getting full.
Is there a way to do that after a nightly process has failed due to 'out of memory' errors?
Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                   4G     0    4G   0% /dev
tmpfs                      4G     0    4G   0% /dev/shm
tmpfs                      4G     0    4G   0% /run
tmpfs                      4G     0    4G   0% /run/user/677

A: After getting more physical memory, changed the following variable in the /etc/systemd/logind.conf file to the value below:
RuntimeDirectorySize=50%

Rebooted and issue resolved.
Prior to this, my RuntimeDirectorySize variable was commented out, therefore it defaulted to 10%.


Q: Is there a way to unload dynamic text once its loaded in Actionscript 3? I'm enlisting your help on how to unload text that dynamically loaded through a text file in Actionscript 3.0.
I have managed to load the data to my stage, but I  want that when the user hits the back button to go home, the data vanishes. At the moment, the data is still appearing even when you hit the back button (whose instance is page3home in the code below.)
Below is my code:
import flash.display.Loader;

var myTextLoader:URLLoader = new URLLoader();
var myTextField_txt:TextField = new TextField();
var myTextUnloader:Loader=new Loader();
var textStyle:TextFormat = new TextFormat();
textStyle.font = "Verdana";
textStyle.size = 14;
myTextField_txt.wordWrap=true;
myTextField_txt.autoSize=TextFieldAutoSize.LEFT;
myTextField_txt.multiline = true;
myTextField_txt.width = 480;
myTextField_txt.height = 300;
myTextField_txt.x = 50;
myTextField_txt.y = 80;

myTextLoader.addEventListener(Event.COMPLETE, onLoaded);

function onLoaded(e:Event):void {
myTextField_txt.text = e.target.data;
addChild(myTextField_txt);
     myTextField_txt.setTextFormat(textStyle);
}

myTextLoader.load(new URLRequest("myText.txt"));

up_btn.addEventListener(MouseEvent.CLICK, scrollUp);

function scrollUp(e:MouseEvent):void
{
     myTextField_txt.scrollV--;
}

down_btn.addEventListener(MouseEvent.CLICK, scrollDown);

function scrollDown(e:MouseEvent):void
{
     myTextField_txt.scrollV++;
}

page3home.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_11);

function fl_ClickToGoToAndStopAtFrame_11(event:MouseEvent):void
{
    gotoAndStop(1);

}

A: To remove a DisplayObject ( the text field in your case ) from its parent DisplayObjectContainer, you can use the removeChild() method :
myTextField_txt.parent.removeChild(myTextField_txt);

Then to free the associated memory, you can add :
myTextField_txt = null;

You can also remove all event listeners added to your URLLoader object like this :
myTextLoader.removeEventListener(Event.COMPLETE, onLoaded);

Hope that can help.


Q: Can Tensorflow/Deep Learning be used for Gradient Boosted Trees, Logistic regression? Tensorflow and deep learning has mostly been used for Image Processing (Classification, Identification), NLP, Voice and text processing. I have used Spark MLLIB and Mahout in the past? Tensorflow has examples of Deep Neural Network - https://www.tensorflow.org/tutorials/wide_and_deep. Can logistic regression, Gradient Boosted Trees etc, be modeled in Tensorflow or a DL Framework?

A: Yes, of course. In fact you can find a lot of examples:
There are some ready implementations like tf.contrib.learn.LinearClassifier in https://www.tensorflow.org/tutorials/wide
Or something like this: https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/logistic_regression.py where you use tf.matmul and appropriate activations.
There is even something with gradient boosting: https://arogozhnikov.github.io/2016/07/05/gradient_boosting_playground.html


Q: How can I enable non-standard characters such as blanks or german Umlaute (ä,ö,ü) for hyperref labels? I am trying to write a small package that (as a minor sub-feature) incorporates some usage of hyperref to get internal cross-references. To be precise, I want to do provide functionality like the following:
\mytarget{Äö üß} % prints "Äö üß" in a section-like style

some text goes here

\mylink{Äö üß} % clickable reference to the above

It is important that the user need not specify a label, this should be handled automagically.
This is an minimal (non)-working example of what I'm thinking about so far:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{hyperref}

\makeatletter
\newcounter{@hash@id}
\newcommand\hashstring[1]{%
  \ifcsname #1\endcsname%
  \typeout{#1 already defined}%
  \else
    \expandafter\xdef\csname #1\endcsname{\the@hash@id}%
    \stepcounter{@hash@id}%
    \typeout{defining #1 now}%
    \fi
  \csname #1\endcsname%
}
\makeatother

\newcommand\mytarget[1]{\hypertarget{\hashstring{#1}}{\section{#1}}}
\newcommand\mylink[1]{\hyperlink{\hashstring{#1}}{\textit{#1}}}

\begin{document}
\mytarget{Äö üß}
some text goes here
\newpage
\mylink{Äö üß}
\end{document}

As you can see, I am trying to auto-generate a label simply by enumerating the distinct "targets" in a global counter, the resulting number being the label. This might not be the most clever way to do it, but I hoped it would be simple to implement. (In the final version, I would of course add some package-specific prefix to the label in order to not interfere with user-defined labels).
However, it doesnt work due to a "missing \endcsname" error, which I do not fully understand - but from browsing the documentation, I can guess that it has something to do with the expansion order of the arguments for hyperlink and hypertarget.
Any help and/or suggestions how to achieve this functionality by other means would be appreciated.

A: There were actually two problems/errors in your approach:

*

*The \hyper… macros expect a fully expandable first parameter.
Your \hashstring macro isn’t one. (\typeout? \stepcounter?)
But your \csname #1\endcsname is one (it only holds the counter).
My solution: Your \my… macros process #1 outside of the \hyper… macros (i.e. creating \csname #1\endcsname if necessary) and the \hyper… use \csname #1\endcsname directly.

*The umlaut problem. How TeX/inputenc deals with characters outside the ASCII range is tricky and I guess those characters are not as expandable as \csname needs them to be.
My solution: \detokenize the parameter.
Code
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{hyperref}

\makeatletter
\newcounter{@hash@id}
\newcommand\hashstring[1]{%
  \ifcsname\detokenize{#1}\endcsname%
    \typeout{#1 already defined}%
  \else
    \expandafter\xdef\csname\detokenize{#1}\endcsname{\the@hash@id}%
    \stepcounter{@hash@id}%
    \typeout{defining #1 now}%
  \fi
}
\makeatother

\newcommand\mytarget[1]{%
  \hashstring{#1}\hypertarget{\csname\detokenize{#1}\endcsname}{\section{#1}}}
\newcommand\mylink[1]{%
  \hashstring{#1}\hyperlink{\csname\detokenize{#1}\endcsname}{\textit{#1}}}

\begin{document}
\mytarget{Äö üß}
some text goes here
\newpage
\mylink{Äö üß}
\end{document}


Q: Join one array with multiple index php How to join 2 arrays with multiple index into 1 array ?
I have array like this
Array
(
    [0] => Array
        (
            [wd[wd5][amount]] => 1.00
            [wd[wd5][address]] => 1BitcoinAddress
            [wd[wd5][currency]] => BTC

        )

    [1] => Array
        (
            [wd[wd7][amount]] => 1.00
            [wd[wd7][address]] => 1BitcoinAddress
            [wd[wd7][currency]] => BTC

        )

)

I want to convert/change/merge that array into something exactly like this
array(
        'wd[wd5][amount]' => 1.00,
        'wd[wd5][address]' => '1BitcoinAddress',
        'wd[wd5][currency]' => 'BTC',
        'wd[wd7][amount]' => 0.0001,
        'wd[wd7][address]' => '1BitcoinAddress',
        'wd[wd7][currency]' => 'BTC'

);

how do I do that ?

A: Using call_user_func_array and array_merge
<?php

$array = [

    [
        "[wd[wd5][amount]]" => 1.00,
        "[wd[wd5][address]]" => "1BitcoinAddress",
        "[wd[wd5][currency]]" => "BTC"
    ],
    [
        "[wd[wd7][amount]]" => 1.00,
        "[wd[wd7][address]]" => "1BitcoinAddress",
        "[wd[wd7][currency]]" => "BTC"
    ]
];

$result = call_user_func_array('array_merge', $array);

echo "<pre>";
print_r($result);

A: Loop the array using foreach and create an new array.
$new_array = array();
foreach($array as $value){
    foreach($value as $k=>$v){
        $new_array[$k] = $v;
    }
}
print_r($new_array);

Output:
Array
(
    [wd[wd5][amount]] => 1.00
    [wd[wd5][address]] => 1BitcoinAddress
    [wd[wd5][currency]] => BTC
    [wd[wd7][amount]] => 1.00
    [wd[wd7][address]] => 1BitcoinAddress
    [wd[wd7][currency]] => BTC
)

A: you can do this like:
$result = array();
foreach($array as $item) {
    $result = array_merge($result, $item);
}

here $result is a new blank array, and $array is the array to merge.

A: You can do it using RecursiveIteratorIterator and RecursiveArrayIterator.
Though I'm liking @BilalAkbar's answer abit more now for the simplicity.
<?php
$array = [
    [
        'wd[wd5][amount]' => 1.00,
        'wd[wd5][address]' => '1BitcoinAddress',
        'wd[wd5][currency]' => 'BTC',
    ],
        [
        'wd[wd7][amount]' => 1.00,
        'wd[wd7][address]' => '1BitcoinAddress',
        'wd[wd7][currency]' => 'BTC'
    ],

];

$result = [];
foreach (new RecursiveIteratorIterator(
         new RecursiveArrayIterator($array)
) as $key => $value) {
  $result[$key] = $value;
}

print_r($result);
/*
Array
(
    [wd[wd5][amount]] => 1
    [wd[wd5][address]] => 1BitcoinAddress
    [wd[wd5][currency]] => BTC
    [wd[wd7][amount]] => 1
    [wd[wd7][address]] => 1BitcoinAddress
    [wd[wd7][currency]] => BTC
)
*/

https://3v4l.org/0fCKj

A: Use array_merge to merge combine the arrays.
http://php.net/manual/en/function.array-merge.php
<?php

$arrayWithSubarrays = array(
    array(
        "[wd[wd5][amount]]" => 1.00,
        "[wd[wd5][address]]" => "1BitcoinAddress",
        "[wd[wd5][currency]]" => "BTC"
    ),
    array(
        "[wd[wd7][amount]]" => 1.00,
        "[wd[wd7][address]]" => "1BitcoinAddress",
        "[wd[wd7][currency]]" => "BTC"
    )
);

// merge each array explicitly:
$mergedArray1 = array_merge($arrayWithSubarrays[0],$arrayWithSubarrays[1]);

// or merge as many as you have in the array:
$mergedArray2 = array();
foreach($arrayWithSubarrays as $array) {
    $mergedArray2 = array_merge($mergedArray2, $array);
}

// (mergedArray1 contains the same data as mergedArray2)

A: Here answer, but you have 2 solution one different key then below answer.
otherwise only save array last values beacause every time  3 keys same.
hope you understand.
<?php

$a = array
(
     array
        (
            'wd[wd[amount]]' => '1.00',
            '[wd[wd5][address]]' => '1BitcoinAddress',
            '[wd[wd5][currency]]' => 'BTC'

        ),

    array
        (
            'wd[wd[amount1]]' => '1.00',
            '[wd[wd5][address1]]' => '1BitcoinAddress',
            '[wd[wd5][currency1]]' => 'BTC'
        )

);
$total = count($a);
$p = array();
$q = array();
$pq = array();
for($i=0;$i<$total;$i++){
    $tarray = $a[$i];
    foreach($tarray as $k=>$v){
        array_push($p,$k);
        array_push($q,$v);

    }
}
$pq = array_combine($p,$q);
print_r($pq);

?>


Q: How can I sync my maven artifacts to jcenter? I have deploy my fist version to the maven central repository. Now I want sync this to JCenter / Bintray. Is this possible and how can I do this?

A: Yes, all you need to do is just download your artifacts from JCenter.
On a related note, I'd suggest doing it the other way around - publish to JCenter and sync to Central. It should be easier for you.

I am with JFrog, the company behind Bintray and [artifactory], see my profile for details and links.


Q: ICE Faces fileInput file path and file name properties I'd like to utilize an ICE Faces fileInput control to fill in the file path & file name for the input to an input field on a web page based on file that the user selects. How can I capture these properties without actually performing any file transfer operations?

A: I believe that the real answer is that you can't.  The file path won't be sent by the browser for security reasons.  The file name will be sent, however I don't believe it gets sent without an actual upload.
The closest you could come, afaik, would be to forcibly kill the connection just when the upload starts.  That would net you the filename with little actual transferred data, but it doesn't sound like it would be useful to you.
Alternatively, a signed Java applet might get you closer to a solution that you'd want.


Q: How to download a file from a VDI (citrix workspace) Artifactory through Python I have a question regarding VDI, Artifactory, and Python.
I wanted to download an artifact that I have tested inside the VDI with the command:
curl https://artifactory-aaaa.company.com/artifactory/artifacts/browse/tree/General/thedirectory/results/filename.xml --output filename.xml

It outputs an XML file, just what I wanted.
I tried doing the same with the Python requests module on my computer (download.py):
import requests

r = requests.get('https://artifactory-aaaa.company.com/artifactory/artifacts/browse/tree/General/thedirectory/results/filename.xml')
with open("filename.xml", "wb") as file:
    file.write(r.content)

and it returns an error :
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x03A4CA50>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

then
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='artifactory-scanner.asml.com', port=443): Max retries exceeded with url: /artifactory/artifacts/browse/tree/General/thedirectory/results/filename.xml (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x03A4CA50>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

To access these file I am required to connect to a VPN. I am connected to the VPN and are able to get the data inside the VDI. But during my Python run, it does not connect. Anybody know what seems to be the problem here?

A: Based on the error snippet shared during the artifact download from the Artifactory application, it looks like there is a connectivity issue from the client(your computer) to Artifactory. You can validate the connectivity using the telnet from your computer to connect to the Artifactory IP/port.
Also, you can validate the Artifactory request logs to check whether the request is reaching the application or not.


Q: Data selection/Row selection I have a scenario where I have to write a SQL query where I consider only the negative values for selected date.
how to achieve the output

what i want is to convert all non negative numbers to zero for a particular date. In this case 2021.

A: You seem to be looking for a conditional sum. The logic is to put a case expression within the aggregate function, like so:
select
    sum(case when "2020" < 0 then "2020" else 0 end)  result_2020,
    sum(case when "2021" < 0 then "2021" else 0 end)  result_2021
from mytable

It is quite unusal to have columns with all-digits names such as 2020, so I wonder whether what you are showing is your actual sample data or the results of an intermediate query (in which case, further optimizations may be possible).

Edit
The above answers the original version of the question. This answers the edited question:
You can use a case expression to turn positive numbers for date 2021 to 0:
select
    fab,
    date,
    case when output > 0 and date = 2021
         then 0
         else output
    end output
from mytbale

A: Say if you have a table like below

I think you are looking for something like this
SELECT id,
    year,
    (case when (a>0 and year = 2021) then 0 else a end) as a_filtered,
    (case when (b>0 and year = 2021) then 0 else b end) as b_filtered
FROM `table_name`
WHERE 1

The output will be the following.


Q: PHP batch extract DB row BLOBs to files We are in the midst of a data migration , and the project needs from one particular table BLOB data saved to files, and sent to the vendor, due to their structure
I am able to achieve this one at a time, but needed to create a batch process, as there are 50,000 rows/potential files.
my current code is
 $sql = "SELECT a.guid  AS file_name, a.attachment AS file_blob"
     ." FROM attachment a";

 $squery = oci_parse($link, $sql);
 oci_execute($squery);

 while ($row = oci_fetch_array($squery, OCI_ASSOC | OCI_RETURN_LOBS)) {
    header('Content-type: octet-stream;');
    header('Content-disposition: attachment;filename='.$row['FILE_NAME']);
    print $row['FILE_BLOB'];
    }

oci_free_statement($squery);

I do understand that I would rather be saving the data rather than streaming it to the browser, I just am not wrapping my head around how to achieve this, should i be looking at php file I/O fputs()?
End result is I would like the process to batch write binary files based on the query to a folder
EDIT
Thank you for your direction and help, based on that I ended up coming up with two separate ways to achieve this
first i did the following getcwd() to verify where the server was pointing to, and did an absolute path if needed
 $basedir = '/path/to/host/www/blobdoc/';

set permissions on the blobdoc folder then used either of the following scripts in the while loop
 $filename='';
 $filename=$basedir.$row['FILE_NAME'];
 file_put_contents( $filename, $row['FILE_BLOB']);

 $filename='';
 $filename=$basedir.$row['FILE_NAME'];
 $File = @fopen( $filename, 'w' );
 if( $File ) {
      if( FALSE === fwrite( $File, $row['FILE_BLOB'] ))
      return FALSE;
 fclose( $File );
 return TRUE;
 }

A: Instead of:
print $row['FILE_BLOB'];
Use something like:
file_put_contents( $filename, $row['FILE_BLOB']); //save locally
You need to write the blob to a file.
If you want to force a download of that file then you need to make use of the correct headers in combinarion with readfile, like so:
$file = '/var/www/html/file-to-download.zip';
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Length: ' . filesize($filename));
header('Content-Disposition: attachment; filename=' . basename($file));
readfile($file);


Q: Efficient way to get median in a unindexed table I am trying to find median salary in this table.
Is there an aggregate function like AVG() to find a median in an unindexed table efficiently? Thanks.
id | Salary
-----------
1    300
2    250
7    180
8    150
9    150
10   160
11   180
15   140

A: There is no MEDIAN() function in MySQL but there is a somewhat simple way to calculate it as demonstrated on this website:
https://www.eversql.com/how-to-calculate-median-value-in-mysql-using-a-simple-sql-query/
Assuming your table is named salaries:
SET @rowindex := -1;

SELECT
   AVG(salary)
FROM
   (SELECT @rowindex:=@rowindex + 1 AS rowindex,
           salaries.salary AS salary
    FROM salaries
    ORDER BY salaries.salary) AS s
WHERE
s.rowindex IN (FLOOR(@rowindex / 2) , CEIL(@rowindex / 2));

Explanation:

*

*Let's start with the internal subquery - the subselect assigns @rowindex as an incremental index for each salary that is selected, and sorts the salaries.

*Once we have the sorted list of salaries, the outer query will fetch the middle items in the array. If the array contains an odd number of items, both values will be the single middle value.

*Then, the SELECT clause of the outer query returns the average of those two values as the median value.

A: select avg(Salary)
from
(
select *,
         ROW_NUMBER() over (order by Salary desc) as desc_salary,
         ROW_NUMBER() over (order by Salary asc) as asc_salary
from Table_Name
) as a
where asc_salary in (desc_salary,desc_salary+1, desc_salary-1)


Q: How to install .Net 4.6.2 on windows 2012r2 We have hundreds of IIS web servers with .Net 3.x and 4.0 installed using using dism.exe on windows 2012r2 (via chef)
powershell command
dism.exe /online /enable-feature /featurename:NetFX4

chef resource
windows_feature 'NetFx4' do
  action :install
end

This only installs up to 4.6.0
gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | gp -name Version,Release -EA 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select PSChileName, Version, Release

PSChildName                      Version        Release
-----------                      -------        -------
v2.0.50727                       2.0.50727.4927
v3.0                             3.0.30729.4926
Windows Communication Foundation 3.0.4506.4926
Windows Presentation Foundation  3.0.6920.4902
v3.5                             3.5.30729.4926
Client                           4.6.01055      394271
Full                             4.6.01055      394271
Client                           4.0.0.0

How can I install .net 4.6.2 though dism on Windows 2012r2?
Update
Those voting to close, please explain why. This question clearly fits the description of questions that can be asked

managing the hardware or software of servers, workstations, storage or networks tools used for administering, monitoring, or automating these deployment to and management of third-party provided information
  technology platforms

A: Your DISM command is just enabling the .Net feature already installed on the OS. DISM can install update packages, but .Net is an .exe installer. So I don't think you can do install it with DISM. You would be best off grabbing the offline installer and using the /q and /norestart flags.


Q: Google Analytics API - Integration With Symfony2 I am trying to gain access to Google Analytics API through OAuth2.
What i did:

*

*Open developers console > APIs and Auth > Credentials

*Create a new Client ID

*Generate p12 key

*Copy the key on the server

*Open google analytics page > admin > Account > User Management

*Add the email from generated Client ID, something like:    xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com

*Give to this email Read and Analyze permissions

*Then when I go back to developers console > permission.    The new email is added on Service accounts with Edit permissions

*Recheck if Google Analytics is enabled and data is going in.
Now I had installed widop/google-analytics-bundle and configure the bundle:
widop_google_analytics:
    client_id:        "xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com"
    profile_id:       "ga:12345678"
    private_key_file: "mykey.p12"
    http_adapter:     "widop_http_adapter.curl"

And the query I try to create is:
        $profileId = 'ga:12345678';
        $query = new Query($profileId);

        $query->setStartDate(new \DateTime('-2months'));
        $query->setEndDate(new \DateTime());

        $query->setMetrics(array('ga:visits' ,'ga:bounces'));
        $query->setDimensions(array('ga:browser', 'ga:city'));

        $query->setSorts(array('ga:country', 'ga:browser'));

        $query->setFilters(array('ga:browser=~^Firefox'));

        $query->setSegment('gaid::10');

        $query->setStartIndex(1);
        $query->setMaxResults(10000);
        $query->setPrettyPrint(false);
        $query->setCallback(null);

        $clientId = 'xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com';
        $privateKeyFile = 'mykey.p12';
        $httpAdapter = new CurlHttpAdapter();

        $client = new Client($clientId, $privateKeyFile, $httpAdapter);
        $token = $client->getAccessToken();

        $service = new Service($client);
        $response = $service->query($query);

        return $response;

As a response I get this error:
User does not have sufficient permissions for this profile.

When I open developers console > overview > 1 hour (tab)
I had notice that requests are going in.
From all that - I assume that authentication and query is OK but the user has no permissions to get any kind of data which is weird because I had granted Read and Analyze permissions to
xxxxxxxx-xxxxxxxxxxxxxxx@developer.gserviceaccount.com
What could by the reason for that exception?

A: I do not know if you already solved this issue.
The solution for me was use the view ID instead of account ID on the analytics account.
The view ID is on the third column in settings, on Google Analytics administration panel.
Sorry for my english.


Q: Merge two directories keeping larger files Consider for example
mkdir dir1
mkdir dir2

cd dir1
echo "This file contains something" > a
touch b
echo "This file contains something" > c
echo "This file contains something" > d
touch e

cd ../dir2
touch a
echo "This file contains something" > b
echo "This file contains something" > c
echo "This file contains more data than the other file that has the same name but is in the other directory.  BlaBlaBlaBlaBlaBlaBlaBlaBla BlaBlaBlaBlaBlaBlaBlaBlaBla BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla. bla!" > d

I would like to merge dir1 and dir2. If two files have the same name, then only the one which size is the largest must be kept. Here is the expected content of the merged directory
a # Comes from `dir1`
b # Comes from `dir2`
c # Comes from either `dir1` or `dir2`
d # Comes from `dir2`
e # Comes from `dir1`(is empty)

A: Assuming that no file name a newline:
find . -type f -printf '%s %p\n' \
  | sort -nr \
  | while read -r size file; do
    if ! [ -e "dest/${file#./*/}" ]; then
      cp "$file" "dest/${file#./*/}";
    fi;
   done

The output of find is a list of "filesize path":
221 ./dir1/a
1002 ./dir1/b
11 ./dir2/a

Then we sort the list numeric:
1002 ./dir1/b
221 ./dir1/a
11 ./dir2/a

And fianlly we reach the while read -r size filename loop, where each file is copied over to the destination dest/${file#./*/} if they don't already exists.
${file#./*/} expands to the value of the parameter file with the leading directory removed:
./abc/def/foo/bar.txt -> def/foo/bar.txt, which means you might need to create the directory def/foo in the dest directory:
  | while read -r size file; do
    dest=dest/${file#./*/}
    destdir=${dest%/*}
    [ -e "$dest" ] && continue
    [ -e "$destdir" ] || mkdir -p -- "$destdir"
    cp -- "$file" "$dest"
   done

A: I cannot comment on the other answer due to not enough reputation, but I was getting a syntax error due to missing fi. I also got an error where the target directory needed to be created before copying. So:
find . -type f -printf '%s %p\n' | sort -nr | while read -r size file; do if ! [ -e "dest/${file#./*/}" ]; then mkdir -p "$(dirname "dest/${file#./*/}")" && cp "$file" "dest/${file#./*/}"; fi; done


Q: What is the best way to instruct user to capture a clear or better image of a document.? I am working on an app where user needs to click an image of a document and upload and server will do the further processing of doing OCR and extracting specific data from it. OCR and data extraction completely depends on the image quality. So what is the best way, i can instruct user to take a near to perfect image of document at run-time.
Factors i am considering.
1) Light available while capturing image
(Can't use the light sensor because it is present on front side of phone whereas document will be on bottom side)
2) Document angle.
(Tried edge detection using openCV but not properly works on white document with light color background surface. Any Edge detection tutorial for run-time document detection over custom camera surface will also be a  great help)
3) Distance from document.
Processing the image after capturing (Transforming the document to a rectangle using openCV) is not always giving a great result with OCR because of character distortion.
So please suggest some way to instruct the user to take a better image of straight document from a perfect distance and better lightening conditions. And also after capturing best way to judge the image quality.

A: If proportions of document is known, you can draw appropriate inner (for min document size) and outer (for max document size) bounding rectangles on preview (as shown on pict)  and control that user positioned document within outer and over inner bounding rect. That is also helps to control right document angle. Also You can control tilt and orientation of smartphone as described in answers for this questions.
Then process preview image (or even its small copy) on-the-fly with lightweight quality estimation algorithms and inform user about low quality and its reason (e.g. low brightness, you can estimate brightness of outer rectangle region, for example, as described in this question) and, may be, block "take snapshot" control.

A: You can use classifier (Machine Learning techniques) to reject low quality images using various features which can differentiate between low and good quality or images captured from long distance by detecting the document in the image.


Q: Help me parse this sentence I and my friend have started examining sentences to recognise parts of speech in them. In our discourse, we could not agree on the point that "naming" in the below sentence is a verb.

The White House website, without naming China, promises “to use every tool at the federal government’s disposal” to end trade abuses.

Can you please help in explaining if "naming" is used as a verb or if it is a different part of speech?

A: Verbs often take Direct Objects. Nouns never do. Instead, the semantically comparable string must appear within a preposition phrase, usually one using the preposition of:

*

*they massacre [the civilians] (verb massacre taking direct object)

*the massacre [of the civilians] (noun massacre taking an of preposition phrase)

Verbs can be premodified by adverbs. Nouns never can. Nouns can be premodified by adjectives. Verbs never can:

*

*the gentle sway

**the gently sway (adverb premodifying noun - ungrammatical)

*gently swayed

**gentle swayed (adjective premodifying verb - ungrammatical)

The Original Poster's example

The White House website, without naming China, promises to ...

Here we see China appearing as the Direct Object of the verb naming. Notice that we cannot put China within an of-preposition phrase here:

*

**The White House website, without naming of China, promises to ... (ungrammatical)

We can further see that if we want to premodify the word naming we must use an adverb. We cannot use an adjective:

*

*without directly naming China (adverb directly)

**without direct naming China (adjective direct - ungrammatical)

This data shows that the word naming is a verb in the Original Poster's example, not an adjective.


Q: How do I change the data type in an HDF5 file from MATLAB? I have a HDF5 datafile that has an array of int32 data values. I wish to change the data stored in that array to different values which are of a different format (double).
for example I can query the data type with the following:
 finf=h5info('file.hdf5');
 finf.Datasets(1).Datatype

 ans =

      Name: ''
      Class: 'H5T_INTEGER'
      Type: 'H5T_STD_I32LE'
      Size: 4
      Attributes: []

If I try to recreate the data in the same node location it gives me the following error that the data set already exists:
t=double(h5read([filepath filename],'/t'));

% more t calculations here....

h5create('file.hdf5','/t',size(t),'DataType','double');

Error using h5create>create_dataset (line 159)
The dataset '/t' already exists.

Error in h5create (line 69)
create_dataset(options);

I've looked in the Matlab docs for a function for deleting a data set in an hdf5 file but can't find any references.  Any one have any ideas?

A: It is not possible to either delete a dataset or change its datatype. From section 5.3.2 of the HDF5 manual:
The datatype is set when the dataset is created and can never be changed.

This is due to how space is assigned in an HDF5 file. While it's not possible to delete a dataset (for the same reasons), it can be "unlinked" and be made inaccessible, but this does not reclaim the used space.
If you really need to change the datatype, you have two choices: the first is to unlink the old dataset and create a new one in its place. The new dataset can have the same name as the old one. However, if space is a concern, you may prefer to just create an entirely new HDF5 file, and copy the old data into the new one.

A: According to This post which is a similar problem there is no mechanism for deleting a dataset in an HDF5 file. It also indicates that it is possible to Modify in place.


Q: Plotting multiple probability distributions in a single graph in R I tried to plot probability distributions from different sources in a single plot. I used the following codes.
require(ggplot2)
require(ggfortify)
p<- ggdistribution(dbeta, seq(0,1,0.01), shape1 = 1.777409 , shape2 = 2.7947, fill ='blue')
p<- ggdistribution(dbeta, seq(0,1,0.01), shape1 = 1.934973 , shape2 = 2.553981, fill ='red', p=p)
ggdistribution(dbeta, seq(0,1,0.01), shape1 = 0.93427 , shape2 = 1.777248, fill ='green', p=p)

Is it possible to use point values (min, max, median and interquartile range) instead of shape1 and shape 2 to plot the distributions?