text:
Q: Get session variable from on of two places and set as one variable I have this at the top of pages that I don't want people accessing unless they're logged in:
<?php
session_start();
if(!isset($_SESSION['Register'])){
  if(!isset($_SESSION['Login'])){
    header("location:../notLoggedIn.php");
 }
}
$get_id = $_SESSION['Register'];
$get_id = $_SESSION['Login'];
?>

This gets a session variable from the code that adds a new user to the database when a new user registers. It also checks if a session has been set from a user logging in rather than registering. Hence one check for register and one for login.
Then, I'm using the session variable as a regular variable so I can access that data on any other pages I might write for the website. So I can have the users id easily available to me.
This works fine when a user registers but not when a user logs in. So, when a user registers the id they are given in the database is available to me to use as it's set in this code that's at the top of every page which puts their id number into the variable $get_id.
The problem is that this variable is already being used but I want it to contain the users id when the user logs in as well. Is there a way to set the variable to check for either of one session variables?

A: You could make a check:
if(isset($_SESSION['Register'])){
   $get_id = $_SESSION['Register'];
}else if(isset($_SESSION['Login'])){
   $get_id = $_SESSION['Login'];
}

With this, you have the ID of Register if this is set, or the ID of Login if Register is not set but Login is.
You could also switch the Register and Login-Parts in the check, if you want to have Login if it is set and if you only want to have Register if Login is not set.
But if you want both IDs saved to the same variable, you'd have to make an array:
$get_id = array(
   "Register" => $_SESSION['Register'],
   "Login" => $_SESSION['Login']);

Like this you can then access your Register by typing $get_id['Register'];.
If you don't want named values, you can omit them, like this:
$get_id = array($_SESSION['Register'], $_SESSION['Login']);

Like this, you can access your Register by typing $get_id[0]; and your Login respectively by typing $get_id[1];.
But if you want to save both values to one variable (not an array), I'm afraid, that's not possible. The closest you could do is the check mentioned above.
Alternatively you could, if you're desperate enough, format those both SESSION-variables to strings to concat them together to one variable. But believe me, this would be very very painful to manipulate or use this data.
$get_id = $_SESSION['Register']. " ".$_SESSION['Login'];

A: You can update the contents of the session variable at any point really and you can structure the contents to make it more usable - an array or object work well.
$svar='usr';

/* you could further test for the session variable having particular properties using `property_exists` */

if( !isset( $_SESSION[ $svar ] ) ){
    echo "session variable not set ~ redirect non logged in users using `header()` ";
}

/* later you can set the variable after login */
$_SESSION[ $svar ]=new stdClass();

$_SESSION[ $svar ]->username='joe.bloggs';
$_SESSION[ $svar ]->registered=true;

echo '<pre>',print_r( $_SESSION[ $svar ],true ),'</pre>';

$username=$_SESSION[ $svar ]->username;
echo $username;


text:
Q: Do VirtualBox snapshots take up space? When I remove a snapshot, it just says 'Merging differencing image'. I don't know how much room each snapshot is taking. It's certainly not copying everything.

A: When you take a snapshot, VirtualBox stops writing to the .vdi and starts writing to the snapshot file. When you merge, it merges the snapshot file into the original .vdi and you're left with the original .vdi plus the changes.
To answer the question explicitly, yes.

A: Yes, they do, and apparently snapshotting also increases disk space usage compared to just a single logical disk.
Check out this excellent blog post on how to merge snapshots and compact them to reduce disk space used: http://srackham.wordpress.com/2010/06/17/merging-and-compacting-virtualbox-snapshots/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add whitespace to Google Chart Label Recently Google Charts enabled labeling and had this to say about the resulting layout
"If the label is too big to fit entirely inside the bar, it's displayed outside" https://google-developers.appspot.com/chart/interactive/docs/gallery/barchart
However, I am discovering that if the label is a string, and has spaces, it is breaking into two lines if nearing the threshold of being "too big".  See my example below.
Does anyone know of a whitespace solution to make it a solid string?  Or any other idea?
http://jsfiddle.net/gbzLB/32/
var data = new google.visualization.DataTable();

data.addColumn('string', 'Name');
data.addColumn('number', 'Percent');
data.addColumn({type: 'string', role: 'annotation'});
data.addColumn({type: 'string', role: 'style'});
data.addRows([
    ['Greek', 55, '216 Votes - 72%', 'color: #FFCC00'],
    ['Italian', 5, '15 Votes - 5%', 'color: #FF6688'],
    ['Polish', 16, '48 Votes - 16%', 'color: #33CCFF']
]);

var chart = new google.visualization.BarChart(document.querySelector('#chart_div'));
chart.draw(data, {
    height: 150,
    backgroundColor: {fill: '#F2EFFB'},
    hAxis: {title: "Percentage", maxValue: '100', gridlines: {
            color: 'black'

    },
    width: 480,
    legend: {
        position: 'none'
    }
});


text:
Q: Mounting a single file from an NFS docker volume into a container Example (many options omitted for brevity):
version: "3"
volumes:
  traefik:
    driver: local
    driver_opts:
      type: nfs
      o: "addr=192.168.1.100,soft,rw,nfsvers=4,async"
      device: ":/volume/docker/traefik"
services:
  traefik:
    volumes:
      - traefik/traefik.toml:/traefik.toml

This errors out as there is no volume with the name traefik/traefik.toml meaning that the volume name must be the full path to the file (i.e. you can't append a path to the volume name)?
Trying to set device: ":/volume/docker/traefik/traefik.toml" just returns a not a directory error.
Is there a way to take a single file and mount it into a container?

A: You cannot mount a file or sub-directory within a named volume, the source is either the named volume or a host path. NFS itself, along with most filesystems you'd mount in Linux, require you to mount an entire filesystem, not a single file, and when you get down to the inode level, this is often a really good thing.
The options remaining that I can think of are to mount the entire directory somewhere else inside your container, and symlink to the file you want. Or to NFS mount the directory to the host and do a host mount (bind mount) to a specific file.
However considering the example you presented, using a docker config would be my ideal solution, removing the NFS mount entirely, and getting a read only copy of the file that's automatically distributed to whichever node is running the container.
More details on configs: https://docs.docker.com/engine/swarm/configs/

A: I believe I found the issue!
Wrong:
   volumes:
      - traefik/traefik.toml:/traefik.toml

Correct:
   volumes:
      - /traefik/traefik.toml:/traefik.toml

Start the volume with "/"


text:
Q: urlretrieve generates an http error 404 after a couple of downloads I'm trying to download some images this way:
from bs4 import BeautifulSoup
import requests

url_ds3_part1 = 'https://darksouls3.wiki.fextralife.com'

url_ds3 = {
"daggers":"https://darksouls3.wiki.fextralife.com/Daggers",
"straight_swords":"https://darksouls3.wiki.fextralife.com/Straight+Swords",
"great_swords":"https://darksouls3.wiki.fextralife.com/Greatswords",
"ultra_great_swords":"https://darksouls3.wiki.fextralife.com/Ultra+Greatswords",
"curved_swords":"https://darksouls3.wiki.fextralife.com/Curved+Swords",
"katanas":"https://darksouls3.wiki.fextralife.com/Katanas",
"curved_great_swords":"https://darksouls3.wiki.fextralife.com/Curved+Greatswords",
"piercing_swords":"https://darksouls3.wiki.fextralife.com/Piercing+Swords"
}

for url in url_ds3.values():
    content = requests.get(url).content
    soup = BeautifulSoup(content,'lxml')
    image_tags = soup.findAll('img')
    [urllib.request.urlretrieve(url_ds3_part1+str(image_tag.get('src')), str('images_swords')+str(image_tag.get('src'))) for image_tag in image_tags if (('forum' in str(image_tag.get('src'))) == False)
                                                                                & (('None' in str(image_tag.get('src'))) == False)
                                                                                & (('avatar' in str(image_tag.get('src'))) == False)
                                                                                & (('Damage' in str(image_tag.get('src'))) == False)
                                                                                & (('Resist' in str(image_tag.get('src'))) == False)
                                                                                & (('STR' in str(image_tag.get('src'))) == False)
                                                                                & (('DEX' in str(image_tag.get('src'))) == False)
                                                                                & (('INT' in str(image_tag.get('src'))) == False)
                                                                                & (('FTH' in str(image_tag.get('src'))) == False)
                                                                                & (('attack' in str(image_tag.get('src'))) == False)
                                                                                & (('normal' in str(image_tag.get('src'))) == False)
    ]

You can just copy/paste the code to reproduce the error HHTP 404 Error.
I'm kinda new to this (first time I did scraping) but I suspect he struggles with duplicates or something, kinda struggle decomposing this problem ?
Thanks in advance for your help :)
EDIT: Forgot to add url_ds3_part1
EDIT2: This should give you an idea of the images I'm trying to retrieve:
for url in url_ds3.values():
    content = requests.get(url).content
    soup = BeautifulSoup(content,'lxml')
    image_tags = soup.findAll('img')
    [print(url_ds3_part1+str(image_tag.get('src'))) for image_tag in image_tags if (('forum' in str(image_tag.get('src'))) == False)
                                                                                & (('None' in str(image_tag.get('src'))) == False)
                                                                                & (('avatar' in str(image_tag.get('src'))) == False)
                                                                                & (('Damage' in str(image_tag.get('src'))) == False)
                                                                                & (('Resist' in str(image_tag.get('src'))) == False)
                                                                                & (('STR' in str(image_tag.get('src'))) == False)
                                                                                & (('DEX' in str(image_tag.get('src'))) == False)
                                                                                & (('INT' in str(image_tag.get('src'))) == False)
                                                                                & (('FTH' in str(image_tag.get('src'))) == False)
                                                                                & (('attack' in str(image_tag.get('src'))) == False)
                                                                                & (('normal' in str(image_tag.get('src'))) == False)
    ]

EDIT 3 :
Temporarely bypassed the issue with try
for url in url_ds3.values():
    content = requests.get(url).content
    soup = BeautifulSoup(content,'lxml')
    image_tags = soup.findAll('img')
    try:
        [urllib.request.urlretrieve(url_ds3_part1+str(image_tag.get('src')), str('images_swords')+str(image_tag.get('src'))) for image_tag in image_tags if (('forum' in str(image_tag.get('src'))) == False)
                                                                                & (('None' in str(image_tag.get('src'))) == False)
                                                                                & (('avatar' in str(image_tag.get('src'))) == False)
                                                                                & (('Damage' in str(image_tag.get('src'))) == False)
                                                                                & (('Resist' in str(image_tag.get('src'))) == False)
                                                                                & (('STR' in str(image_tag.get('src'))) == False)
                                                                                & (('DEX' in str(image_tag.get('src'))) == False)
                                                                                & (('INT' in str(image_tag.get('src'))) == False)
                                                                                & (('FTH' in str(image_tag.get('src'))) == False)
                                                                                & (('attack' in str(image_tag.get('src'))) == False)
                                                                                & (('normal' in str(image_tag.get('src'))) == False)
        ]
    except:
        pass

A: Running your code it seems that some URLs are absolute (they start with https://) and some are not. You need to check for that:
import requests
import urllib.request
from bs4 import BeautifulSoup

url_ds3 = {
"daggers":"https://darksouls3.wiki.fextralife.com/Daggers",
"straight_swords":"https://darksouls3.wiki.fextralife.com/Straight+Swords",
"great_swords":"https://darksouls3.wiki.fextralife.com/Greatswords",
"ultra_great_swords":"https://darksouls3.wiki.fextralife.com/Ultra+Greatswords",
"curved_swords":"https://darksouls3.wiki.fextralife.com/Curved+Swords",
"katanas":"https://darksouls3.wiki.fextralife.com/Katanas",
"curved_great_swords":"https://darksouls3.wiki.fextralife.com/Curved+Greatswords",
"piercing_swords":"https://darksouls3.wiki.fextralife.com/Piercing+Swords"
}

url_ds3_part1 = 'https://darksouls3.wiki.fextralife.com'

for url in url_ds3.values():
    print(url)

    content = requests.get(url).content
    soup = BeautifulSoup(content,'lxml')
    image_tags = soup.findAll('img')

    for image_tag in image_tags:
        if ( (('forum' in str(image_tag.get('src'))) == False)
             & (('None' in str(image_tag.get('src'))) == False)
             & (('avatar' in str(image_tag.get('src'))) == False)
             & (('Damage' in str(image_tag.get('src'))) == False)
             & (('Resist' in str(image_tag.get('src'))) == False)
             & (('STR' in str(image_tag.get('src'))) == False)
             & (('DEX' in str(image_tag.get('src'))) == False)
             & (('INT' in str(image_tag.get('src'))) == False)
             & (('FTH' in str(image_tag.get('src'))) == False)
             & (('attack' in str(image_tag.get('src'))) == False)
             & (('normal' in str(image_tag.get('src'))) == False) ):

            if image_tag.get('src').startswith('http'):
                u = image_tag['src']
            else:
                u = url_ds3_part1 + image_tag['src']

            urllib.request.urlretrieve(u, 'images_swords' + image_tag['src'].replace(url_ds3_part1, ''))


text:
Q: How to optimize multi select comparing/join with only one table SQL I must join employee 3 times on 3 conditions. Can I join employee once on 3 conditions?
select
referType = resAffType,

referName = (case when resAffType = 0 then e.empFirstName + ' ' + e.empLastName

when resAffType = 1 then affFirstName + ' ' + affLastName

else NULL end),

bookName = e3.empFirstName + ' ' + e3.empLastName,

AssignToName = e2.empFirstName + ' ' + e2.empLastName,

from

Reservation r

left join ClubTable c on r.TableISN = c.TableISN

left join Affiliate a on r.AffiliateISN = a.AffiliateISN -- r.aff maybe in table aff

left join Employee e on r.AffiliateISN = e.EmployeeISN -- r.aff maybe in table emp

left join Employee e2 on r.EmployeeISN = e2.EmployeeISN -- assignedby emp

inner join Employee e3 on r.EmployeeISN = e3.EmployeeISN -- bookedby emp

A: No.  What you are already doing is correct.


text:
Q: How to Pass List of data from View to Controller I have List like below in .cshtml
@using (Html.BeginForm("About","Home"))
{

@for (int i = 0; i <= @Model.Count()-1;i++ )
{

        @Html.TextBoxFor(x => x[i].DeptId)

        @Html.TextBoxFor(x => x[i].DeptName)

 }

<input type="button" value="HitMe" onclick="Save()" />

}

The Save function will do the ajax method and serialize all the data and pass to controller.
Controller Code:
    [HttpPost]
    public ActionResult About(List<Dept> obj)
    {
        ViewBag.Message = "Your app description page.";

        return View();
    }

When i executed obj is null but if i change the  type="Submit" in obj i am getting the List data. So how to fill obj in ajax call.

A: You need to serialize form not div
@using (Html.BeginForm("About","Home",FormMethod.Post,new {id="frm_Test"}))
{
.....

...

}

In script provide Id of form to serialize


text:
Q: How do I get the id of a textbox that is invoking a javascript function? What I want is to get the id (i.e myHeader, myHeader2, etc.)
This is what I'm trying now,
HTML:
<input type="text" id="myHeader" onblur="getValue(this)" />
<input type="text" id="myHeader2" onblur="getValue(this)" />
<input type="text" id="myHeader3" onblur="getValue(this)" />
<input type="text" id="myHeader4" onblur="getValue(this)" />

Javascript:
function getValue(obj){
    var someVar = document.getElementById(obj).value;
}

But I'm not getting anything, the event is not firing as well, how do I do this?

A: Your obj object already have id and value property:
function getValue(obj){
    alert('id - ' + obj.id);
    alert('value - ' + obj.value);
}

Note that when you pass this context to your function, you pass your DOM element. Not id. And you can operate with it already as with DOM element. No need for document.getElementById.

A: function value(object)
 {
alert('id= ' + object.id);
 }

A: As I see it, you might be firing the function when user loses focus on that input field.
Unless you are doing obj.value.toUpperCase(); why do you want to fire the same function on each input field?
Anyways as @antyrat said this would give you the DOM element and you can pick value from it.
 function getValue(obj){
 obj.value=obj.value.toUpperCase();
 }

this would make all for of your input fields to upper case as user keeps moving ahead.

A:   <script type="text/javascript">
    function getValue(obj) {
        var id = obj.id;
        var value = obj.value;
    }
</script>

A: Also you can get the textbox id
<input type="text" id="myHeader" onblur="getValue(this.id)" /> <!-- instead of getValue(this) -->

<script type="text/javascript">
    function getValue(id) {
        alert(id);  // Display the id of the textbox
    }
</script>

Hope it will help you.


text:
Q: Azure Pipelines YAML source For our project, it is vital to know to understand the behavior of our yaml azure pipelines. So is there ever a situation where the azure pipeline, with ci triggers for branches, would use a different source yaml file other than the yaml file associated with the trigger branch? We believe that the azure pipeline will use the yaml file with the associated branch that the pipeline was triggered on. However we have not found any specific reference in the Microsoft documentation that would confirm this. Any concrete documentation would be appreciated.

A:

*

*For CI triggers, the YAML file that is in the branch you are pushing is evaluated to see if a CI build should be run.

*For PR triggers, the YAML file resulting from merging the source and target branches of the PR is evaluated to see if a PR build should be run.

Source: https://learn.microsoft.com/en-us/azure/devops/pipelines/repos/azure-repos-git?view=azure-devops&tabs=yaml#a-wrong-version-of-the-yaml-file-is-being-used-in-the-pipeline-why-is-that


text:
Q: C# LinkedList<> remove by index Given a:
LinkedList<int> myList;

How would I remove an element at index n?  I can't seem to find any methods, only ones to remove by value which is no good as this particular list can have duplicate values.
EG:
myList.removeAt(n);

A: Linked lists have great advantage in speed if you are adding or removing a node you have a existing reference to, but when you don't have a reference the best you can do is walk the list to the index, grab the node, then delete it.
Here is a extension method that does that process. It returns a reference to the removed node in case you want it later to insert to some other list or you are moving it's position within the list.
public static class ExtensionMethods
{
    public static LinkedListNode<T> RemoveAt<T>(this LinkedList<T> list, int index)
    {
        LinkedListNode<T> currentNode = list.First;
        for (int i = 0; i <= index && currentNode != null; i++)
        {
            if (i != index)
            {
                currentNode = currentNode.Next;
                continue;
            }

            list.Remove(currentNode);
            return currentNode;
        }

        throw new IndexOutOfRangeException();
    }
}


text:
Q: how do you retrieve xml data from nested nodes <CustomerOrders>
  <Customers>
    <CustomerID>ALFKI</CustomerID>
    <Orders>
      <OrderID>10643</OrderID>
      <CustomerID>ALFKI</CustomerID>
      <OrderDate>1997-08-25</OrderDate>
    </Orders>
    <Orders>
      <OrderID>10692</OrderID>
      <CustomerID>ALFKI</CustomerID>
      <OrderDate>1997-10-03</OrderDate>
    </Orders>
    <CompanyName>Alfreds Futterkiste</CompanyName>
  </Customers>
  <Customers>
    <CustomerID>ANATR</CustomerID>
    <Orders>
      <OrderID>10308</OrderID>
      <CustomerID>ANATR</CustomerID>
      <OrderDate>1996-09-18</OrderDate>
    </Orders>
    <CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
  </Customers>
</CustomerOrders>

How do you retrieve OrderID,CustomerID and OrderDate? i have been trying it for hours already. Can someone help me? Thanks!
XmlNodeList xmlnode = doc.GetElementsByTagName("Customers");
HtmlGenericControl div = new HtmlGenericControl("div");
for(int i = 0; i < xmlnode.Count; i++)
{
    Label lbl2 = new Label();
    lbl2.Text = xmlnode[i].ChildNodes[1].Name;
    div.Controls.Add(lbl2);
    RadioButtonList rb1 = new RadioButtonList();
    rb1.Items.Add(xmlnode[i].ChildNodes[1].InnerText+"<br>");
    div.Controls.Add(rb1);
}
div1.Controls.Add(div);

A: You can use the XDocument class and its decendants. You can use XPath expressions to delve deeper into the code:
e.g.
using System.Xml.Linq
using System.Xml.XPath

....
XDocument doc= XDocument.Load("sample.xml");
XElement root= doc.Element("CustomerOrders");
var result= root.XPathSelectElements("Customers/CustomerId");
foreach(var customerid in result)
    {
    .....
    }

Depending on what you want to achieve this should put you at the right track. While I was typing the answer, another answer proposes to use XmlDocument class. That should work as well, but when using XDocument you can use Linq, which adds a lot of flexibilty.

A:   XmlDocument doc = new XmlDocument();
                doc.LoadXml("yourxmldata");

                XmlNodeList customers = doc.DocumentElement.SelectNodes("Customers");

                foreach (XmlNode customer in customers)
                {
                    XmlNodeList customerOrders = customer.SelectNodes("Orders");

                    string customername = customer["CustomerID"].InnerText;

                    foreach (XmlNode customerOrder in customerOrders)
                    {
                        string orderid = customerOrder["OrderID"].InnerText;
                        string orderdate = customerOrder["OrderDate"].InnerText;
                    }

                }

A: Here is everything using Xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication47
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("Customers").Select(x => new
            {
                customerID = (string)x.Element("CustomerID"),
                companyName = (string)x.Element("CompanyName"),
                orders = x.Elements("Orders").Select(y => new {
                   orderID = (int)y.Element("OrderID"),
                   customerID = (string)y.Element("CustomerID"),
                   date =  (DateTime)y.Element("OrderDate")
                }).ToList()
            }).ToList();
        }
    }
}


text:
Q: Replacing a pattern to the end of a file with sed Using sed, if there is a space character on a line in a file, I need to print the output with the space character and anything after it removed. Code example:
sed "s/"something here I think"//g' file

So, let's say a file says this on a line:
 Chuck Norris is the man

I just need it to print:
 Chuck

Multiple lines applicable too:
Chuck Norris is the man
So is Arnold

Replaced:
Chuck
So

A: This should do it for you:
sed 's/ .*//g'  file

To remove from the beginning of the line to the first space, use this:
sed 's/^[^ ]* //g'


text:
Q: Arrange my result in select query of postgresql? I have a query:
select c1,q1,c2,q2,c3,q3,c4,q4 from mxm

The result is:
c1    q1   c2     q2    c3     q3    c4      q4
9103  4    9114   3.3   9197   1.9   B9151   3000
9103  15   9107   8.6   9118   8.3   B9100   130.6
9103  3.6  9114   0.6   9197   1.1   B9151   5000

But I want this output like:
9103  4
9114  3.3
9197  1.9
B9151 3000
9103   15
9107   8.6
9118   8.3
B9100  130.6

and so on .... Is this possible in postgresql?

A: If you want them in that order, it is a bit tricky.  Assuming you have no appropriate id in mxm for identifying the rows in order:
with t as (
      select row_number() over (order by ??) as seqnum, mxm.*
      from mxm
)
select c, q
from ((select c1, q1, seqnum, 1 as ordering from t) union all
      (select c2, q2, seqnum, 2 from t) union all
      (select c3, q3, seqnum, 3 from t) union all
      (select c4, q4, seqnum, 4 from t)
     ) cq
order by seqnum, ordering;

The ?? is for the column that specifies the original ordering for the records.


text:
Q: in active_admin, skip_before_filter for authentication is not working I am trying to use activeadmin to make the entire site, not just the admin dashboard.  I have changed the admin_user to facility_user.  For the facility user page, i want to skip authentication so that anyone who comes to the site can register as a facility_user.  Here is my active_admin code:
ActiveAdmin.register FacilityUser do
    permit_params :email, :password, :password_confirmation
    controller do
        skip_before_filter :authenticate_facility_user!
    end
end

And here is the relevant part of the activeadmin initializer:
ActiveAdmin.setup do |config|
    config.default_namespace = :facility_users
    config.authentication_method = :authenticate_facility_user!
end

However, this is not working.  When I go to localhost:3000/facility_users/facility_users/new, i am redirected to the login page for activeadmin and told i need to login.


text:
Q: What is the state of compression support in gRPC for Python? I am attempting to implement a gRPC client and server using the Python gRPC implementation as a reference.
According to the spec document at https://github.com/grpc/grpc/blob/master/doc/compression.md there are several use-cases that should be supported:

Compression MAY be configured by the Client Application by calling the
  appropriate API method. There are two scenarios where compression MAY
  be configured:

*

*At channel creation time, which sets the channel default compression
  and therefore the compression that SHALL be used in the absence of
  per-RPC compression configuration.

*At response time, via: For unary
  RPCs, the {Client,Server}Context instance. For streaming RPCs, the
  {Client,Server}Writer instance. In this case, configuration is reduced
  to disabling compression altogether.

  ...
Compression Method Asymmetry Between Peers
A gRPC peer MAY choose to
  respond using a different compression method to that of the request,
  including not performing any compression, regardless of channel and
  RPC settings (for example, if compression would result in small or
  negative gains).
...
Specific Disabling of Compression
If the user (through the previously
  described mechanisms) requests to disable compression the next message
  MUST be sent uncompressed. This is instrumental in preventing
  BEAST/CRIME attacks. This applies to both the unary and streaming
  cases.

Some of these seem to be possible, and others not. Tackling them one by one, here is what I think is possible:

*

*At channel creation time, which sets the channel default compression
  and therefore the compression that SHALL be used in the absence of
  per-RPC compression configuration.

This works. On the server you can specify:
from grpc._cython.cygrpc import CompressionAlgorithm, CompressionLevel

server_options = [(
     "grpc.default_compression_algorithm", CompressionAlgorithm.gzip
),(
     "grpc.default_compression_level", CompressionLevel.high
)]

server = grpc.server(
    futures.ThreadPoolExecutor(max_workers=10), options=server_options
)

And on the client:
from grpc._cython.cygrpc import CompressionAlgorithm

channel_options = [(
     "grpc.default_compression_algorithm", CompressionAlgorithm.gzip
)]

channel = grpc.insecure_channel(
    "127.0.0.1:{}".format(port), options=channel_options
)

This correctly sets up the default algorithms on both sides.
You can override the compression algorithm for a specific call by setting the grpc-internal-encoding-request metadata key:
stub.MethodName(request, metadata={'grpc-internal-encoding-request': 'gzip'})

This is ultimately sets the grpc-encoding header on the request and the body is encoded appropriately.
So far so good. Next:

Compression Method Asymmetry Between Peers
A gRPC peer MAY choose to
  respond using a different compression method to that of the request,
  including not performing any compression, regardless of channel and
  RPC settings

I found an example of how to do this in this unit test and a referencing stack overflow question. However, when I try do this I see an error in my logs, and the response header is not changed:
prepare_application_metadata: {"created":"@1541795237.323499000","description":"Unallowed duplicate metadata","file":"src/core/lib/transport/metadata_batch.cc","file_line":113,"key":"grpc-internal-encoding-request","value":"gzip"}

The error is raised when the server also has a default compression algorithm set. When there is no default it does seem to work.
Relatedly, the accepted answer to this stackoverflow question suggests that grpc-internal-encoding-request should only be used in the client ( which makes sense given the name)
So I don't know whether there's a bug whereby you can't set a default and an override at the same time, or whether setting grpc-internal-encoding-request is genuinely invalid on the server side (and if so how the response encoding should be changed)
Finally:

Specific Disabling of Compression
If the user (through the previously
  described mechanisms) requests to disable compression the next message
  MUST be sent uncompressed. This is instrumental in preventing
  BEAST/CRIME attacks. This applies to both the unary and streaming
  cases.

This Github issue says that this is supported, but it seems only by the client stubs in the beta package, even though the referenced commit was merged in 2015. Is support for this still on some kind of roadmap, or have I missed something somewhere?
I don't have to use the Python implementation as my reference. Is there a more complete implementation in another language?


text:
Q: TeamCity - SVN and Labelling: How to do it correctly? I've read all the TeamCity, SVN and labeling questions in S.O. but none seams to apply to my specific problem.
Here we have the following structure on the SVN:
svn://server/root
              /projectA
                 /trunk
                 /tags
              /projectB
                 /trunk
                 /tags

On the TeamCity I've configured a SVN root for the project A like this:
svn://server/root/ProjectA/trunk

And the build process works like a charm.
However now I want to add labeling, but even setting the labeling rules as specified in the documentation or any other setting I know of, as for my latest try:
/ProjectA/trunk=>/ProjectA/tags

I get the following error:
jetbrains.buildServer.vcs.VcsException: Labeling the path 'ProjectA/trunk' to 'ProjectA/tags/build-24' has failed with the error: svn: CHECKOUT of '/svn/root/!svn/ver/5792/ProjectA/tags': 403 Forbidden (https://server:8443)
  at jetbrains.buildServer.buildTriggers.vcs.svn.SvnSupport.throwLabelingError(SvnSupport.java:430)
  at jetbrains.buildServer.buildTriggers.vcs.svn.SvnSupport.label(SvnSupport.java:418)
  at jetbrains.buildServer.vcs.impl.VcsLabeler.setLabel(VcsLabeler.java:45)
  at jetbrains.buildServer.vcs.impl.VcsLabeler.access$400(VcsLabeler.java:64)
  at jetbrains.buildServer.vcs.impl.VcsLabeler$3$1.run(VcsLabeler.java:4)
  at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
  at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
  at java.util.concurrent.FutureTask.run(Unknown Source)
  at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
  at java.lang.Thread.run(Unknown Source)
Caused by: org.tmatesoft.svn.core.SVNAuthenticationException: svn: CHECKOUT of '/svn/root/!svn/ver/5792/ProjectA/tags': 403 Forbidden (https://server:8443)
  at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:62)
  at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:51)
  at org.tmatesoft.svn.core.internal.io.dav.http.HTTPConnection.request(HTTPConnection.java:623)
  at org.tmatesoft.svn.core.internal.io.dav.http.HTTPConnection.request(HTTPConnection.java:274)
  at org.tmatesoft.svn.core.internal.io.dav.http.HTTPConnection.request(HTTPConnection.java:262)
  at org.tmatesoft.svn.core.internal.io.dav.DAVConnection.doCheckout(DAVConnection.java:452)
  at org.tmatesoft.svn.core.internal.io.dav.DAVCommitEditor.checkoutResource(DAVCommitEditor.java:468)
  at org.tmatesoft.svn.core.internal.io.dav.DAVCommitEditor.addDir(DAVCommitEditor.java:136)
  at jetbrains.buildServer.buildTriggers.vcs.svn.SvnCopyHelper$CopyCommitPathHandler.handleCommitPath(SvnCopyHelper.java:138)
  at org.tmatesoft.svn.core.internal.wc.SVNCommitUtil.driveCommitEditor(SVNCommitUtil.java:139)
  at jetbrains.buildServer.buildTriggers.vcs.svn.SvnCopyHelper.doCopy(SvnCopyHelper.java:102)
  at jetbrains.buildServer.buildTriggers.vcs.svn.SvnConnection.label(SvnConnection.java:861)
  at jetbrains.buildServer.buildTriggers.vcs.svn.SvnSupport.label(SvnSupport.java:416)

Does anyone has any reason why this happen, or how can I set up this correctly?
In time: The user accessing the SVN does the checkout correctly as the TeamCity is configured to clean the checkout folder before every build.

A: I would set the root like:
      svn://server/root/ProjectA

And have labeling as :
      trunk=>tags

That's how I have my VCS set up. The SVN error issue is kinda addressed here.
Give it a try.


text:
Q: Heroku Node.js app giving errors I'm trying to deploy my first app to heroku, but something is a miss.
I have gone into the logs and this is what is happening. Anyone have any ideas?
it would be much appreciated or is there any other information I can get that will reveal whats happening? It is working on local host fine, even through heroku's local host at 5000.
port is set like this.
var port = process.env.PORT || 3000;
logs below
2017-05-29T16:28:57.730817+00:00 app[web.1]:

2017-05-29T16:28:57.730818+00:00 app[web.1]: ReferenceError: err is not defined

2017-05-29T16:28:57.730819+00:00 app[web.1]:     at NativeConnection.<anonymous> (/app/app.js:19:17)

2017-05-29T16:28:57.730819+00:00 app[web.1]:     at emitOne (events.js:96:13)

2017-05-29T16:28:57.730820+00:00 app[web.1]:     at NativeConnection.emit (events.js:188:7)

2017-05-29T16:28:57.730821+00:00 app[web.1]:     at Immediate.<anonymous> (/app/node_modules/mongoose/lib/connection.js:322:19)

2017-05-29T16:28:57.730822+00:00 app[web.1]:     at runCallback (timers.js:651:20)

2017-05-29T16:28:57.730822+00:00 app[web.1]:     at tryOnImmediate (timers.js:624:5)

2017-05-29T16:28:57.730823+00:00 app[web.1]:     at processImmediate [as _immediateCallback] (timers.js:596:5)

2017-05-29T16:28:57.828280+00:00 heroku[web.1]: State changed from starting to crashed

Thanks in advance.

A: So I stupidly followed tutorials. I was still connected to localhost mongoDB. now I have it live with MLAB, thanks all that looked.


text:
Q: any third party providers for getting products information from all eCommerce affiliate api's We are working on application which has product search to get products information of product from all eCommerce websites. We have found that flipkart,amazon,ebay all are having their own affiliate api's to get product information. We are searching for third party api providers who gives information from all eCommerce websites. like price comparison api providers who give info from all eCommerce.

A: I have built up a price comparison api that combines basic data from many sources into one list. It requires that you give it a upc and api keys for the providers that it supports. It will then go and give you back a list of products with their information including price.
The api so far supports Amazon, Ebay, Walmart, and BestBuy. It is written in .net but can be easly used to create a server that returns json data for a specific upc. If you need a differant provider you can just post a issue on the github.
It is called Gobble. Here is the link -  https://github.com/greatjack1/Gobble


text:
Q: Prove that the measure of the image of a continuous, differentiable function is equal to $\int_Eg'(x)$. Problem: Assume that a real-valued function $g$ is continuous and differentiable on an open interval containing $[0,1]$, an assume that there exist constants $c_1$ and $c_2$ such that $0 < c_1 \le g'(x) \le c_2$ for all $x \in [0,1]$. Prove that $\mu(g(E)) = \int_E g'(x)dx$ for every Lebesgue measurable set $E \subset [0,1]$.
My attempt: I've been able to prove the case where $E$ is an open interval, and $g$ is an increasing function. This case is obvious: $\mu(g((a,b))) = g(b)-g(a) = \int_a^bg'(t)dt$. When $E$ is an open set, $E$ can be written as a disjoint union of open intervals, so that case follows as well. However, I can't figure out how to generalize this to Lebesgue measurable sets and to non-increasing functions.
If $g$ is non-increasing, and $E$ is an open interval, we still have that $g(x) = g(a) + \int_a^x g'(t)dt$. But I can't seem to come with with an expression for even $\mu(g((a,b)))$ when $g$ is not continuous. Help would be much appreciated.


text:
Q: Add x in between the number I have list of numbers
1112
1113
1114
1115
1116-1117
1118-1119
1120
1121-1122

Need to show these numbers like following
1x112
1x113
1x114
1x115
1x120

And these number explode with - and show like
1x116
1x117
1x118
1x119
1x121
1x122

A: Cast your numbers to string, and then you can manipulate them :
$a = 1112;
$a = (string) $a;
var_dump(substr($a, 0, 1) . 'x' . substr($a, 1)); /* "1x112" */

A: Try the below code. It's working for you.
<?php
    $numStr = '1112 1113 1114 1115 1116-1117 1118-1119 1120 1121-1122';
    $numStr = explode(' ',str_replace('-',' ',$numStr));

    foreach($numStr as $key => $num) {
        $numStr[$key] = substr($num, 0, 1) . 'x' . substr($num, 1);
    }

    echo $numStr = implode(' ',$numStr);
?>

OUTPUT
1x112 1x113 1x114 1x115 1x116 1x117 1x118 1x119 1x120 1x121 1x122

A: Try with convert into array like this.
<?php
$a = array();
$a[] = 1112;
$a[] = 1113;
$a[] = 1114;
$a[] = 1115;
$a[] = '1116-1117';
$a[] = '1118-1119';
$a[] = 1120;
$a[] = '1121-1122';

$output = array();
foreach($a as $key=>$value){
    if (strpos($value, '-') !== false) {
        $sub_a = explode('-',$value);
        foreach($sub_a as $sub_key=>$sub_value){
            $output[$key][$sub_key] = substr($sub_value, 0, 1).'x'.substr($sub_value, 1);
        }
    }else{
        $output[$key] = substr($value, 0, 1).'x'.substr($value, 1);
    }
}
print_r($output);

Output
Array
(
    [0] => 1x112
    [1] => 1x113
    [2] => 1x114
    [3] => 1x115
    [4] => Array
        (
            [0] => 1x116
            [1] => 1x117
        )

    [5] => Array
        (
            [0] => 1x118
            [1] => 1x119
        )

    [6] => 1x120
    [7] => Array
        (
            [0] => 1x121
            [1] => 1x122
        )

)

A: Split on any non-digit, and then substitute part of the string:
<?php
$list = '1112 1113 1114 1115 1116-1117 1118-1119 1120 1121-1122';
foreach(preg_split('/[^0-9]/', $list) as $number)
    echo substr_replace($number, 'x', 1, 0), "\n";

Output:
1x112
1x113
1x114
1x115
1x116
1x117
1x118
1x119
1x120
1x121
1x122


text:
Q: How do I pass additional info with ? I need to upload files to a servlet running on tomcat.  In addition to the file, I want to allow the user to add a comment associated with the file uploaded. I tried the following but it did not work:
<form action='MyUploadServlet' enctype='multipart/form-data' method='POST'>
    <input type='file' name='filechooser'>

    <textarea name='comment' cols='15' rows='5'></textarea>
    <input type='Submit' value='Upload'>

</form>

Here is a snippet from the server side code:
@WebServlet("/MyUploadServlet")
public class MyUploadServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
            ServletContext sc = request.getServletContext();
            String comment = (String)request.getParameter("comment");
            ....etc}

The omitted part of the server code deals with receiving the contents of uploaded file.
The request.getParameter("comment") line above returns null.
I use several servlets and multiple forms in my app.  In all other places, if I use request.getParameter("form-input-name"), I always get the value of the corresponding input field.  This is the only exception, namely when the form has an input field of type "file".
How do I pass in a comment along with the file upload submit?

A: You need to get the text field value by the same API as you used to get the content of the uploaded file.
You have specified the HTML form to send the data in multipart/form-data encoding instead of the standard application/x-www-form-urlencoded encoding. The multipart/form-data encoding is mandatory in order to send the file's content along with the form submit. However, the getParameter() method works in combination with application/x-www-form-urlencoded only.
A multipart/form-data request is usually to be parsed with a multipart/form-data parser such as the well known Apache Commons FileUpload, which is a de facto standard in this area. However, since Servlet 3.0 (which you seem to be actually using, given the presence of the also in Servlet 3.0 introduced @WebServlet annotation), there's a new getParts() method which allows you to extract the necessary submitted data using the standard methods without the need for Apache Commons FileUpload. It's however still only a bit more verbose than with Apache Commons FileUpload. You can find a concrete example of the both approaches in this answer: How to upload files to server using JSP/Servlet?


text:
Q: How to count the number of account numbers per loan ID entry instead of the total number of entries for that account number? I want my query to count the number of account number entries if the lt.type is 46, per each loan ID entry. It is currently counting the total number of entries overall.
SELECT *
FROM
(
SELECT DISTINCT a.ACCOUNTNUMBER AS [Account Number]
    , CONCAT(n.FIRST, ' ', n.MIDDLE, ' ', n.LAST) AS [Member Name]
    , l.id AS [Loan ID]
    , COUNT(a.ACCOUNTNUMBER)
        OVER(partition by a.ACCOUNTNUMBER) as [Number of
Tracking Records]
    , n.EMAIL AS [Email]
    , n.HOMEPHONE AS [Phone Number]
FROM dbo.account a
INNER JOIN dbo.LOAN l
ON a.ACCOUNTNUMBER = l.PARENTACCOUNT
INNER JOIN dbo.LOANTRACKING lt
ON l.PARENTACCOUNT = lt.PARENTACCOUNT
AND l.ID = lt.ID
INNER JOIN dbo.NAME n
ON a.ACCOUNTNUMBER = n.PARENTACCOUNT
WHERE lt.type = 46
AND l.ProcessDate = CONVERT(VARCHAR(8), dateadd(day,-1, getdate()),
112)
AND lt.ProcessDate = CONVERT(VARCHAR(8), dateadd(day,-1, getdate()),
112)
AND n.ProcessDate = CONVERT(VARCHAR(8), dateadd(day,-1, getdate()),
112)
AND a.ProcessDate = CONVERT(VARCHAR(8), dateadd(day,-1, getdate()),
112)
AND l.CLOSEDATE IS NULL
AND lt.EXPIREDATE IS NULL
AND n.type = 0
AND a.ACCOUNTNUMBER NOT IN (SELECT a.ACCOUNTNUMBER
                                    FROM dbo.ACCOUNT a
                INNER JOIN dbo.LOANTRACKING lt
                ON a.ACCOUNTNUMBER = lt.PARENTACCOUNT
                WHERE lt.type = 36)
) MyQuery
WHERE MyQuery.[Number of Tracking Records] >= 3
ORDER BY [Account Number], MyQuery.[Loan ID]

Right now my code is counting the total amount of entries for the account number each time there is an entry for that account and the lt.type of 46.
I want it to count the number of entries for each account number if there is a type 46, but only for each loan ID.
I am attaching some examples of what it is doing now, and what I'd like it to do, along with some sample data.
This is what my query is doing now
This is what I want my query to do
Here is some sample data

A: You need to partition by two fields, of which the loan Id is one of them:
COUNT(a.ACCOUNTNUMBER) OVER(partition by a.ACCOUNTNUMBER, l.id)


text:
Q: Chart.js How to edit the title label color Im working on a project where I display charts of stocks, everything works fine but I can't find how to change the title color above the chart like here: "AAPL" here
This is my code so far:
  public renderChart(xData, yData, symbol){
    this.chart = new Chart("canvas" + symbol, {
      type: "line",
      data : {
        labels: xData,
        datasets: [{
          label: symbol,
          data: yData,
          backgroundColor: "#fdb44b",
          borderColor: "#00204a",
        }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: {
            ticks: { color: '#f5f5f5'}
          },
          x: {
            ticks: { color: "#f5f5f5" }
          }
        }}
    })
  }

Any help is appreciated!

A: "AAPL" is not the chart title it's the label of the legend.
To change that color, place the following inside your options block.
    options: {
      plugins: {
        legend: {
          labels: {
            color: 'red'
          }
        }
      },
   ...
   }

https://www.chartjs.org/docs/latest/configuration/legend.html


text:
Q: Simple code for create a thread in Python 2.7 I'm new to Python and I'm trying to do a simple thread as follows.
import threading

def func(x):
    print x

t1 = threading.Thread(target=func,args=("Hello",));
t1.start();

Then I got following error:
Traceback (most recent call last):
  File "ex2.py", line 1, in <module>
    import threading
  File "/Users/treinetic-macbook/Desktop/threading.py", line 2, in <module>

  File "/Library/Python/2.7/site-packages/requests/__init__.py", line 43, in <module>
    import urllib3
  File "/Library/Python/2.7/site-packages/urllib3/__init__.py", line 8, in <module>
    from .connectionpool import (
  File "/Library/Python/2.7/site-packages/urllib3/connectionpool.py", line 3, in <module>
    import logging
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 207, in <module>
    _lock = threading.RLock()
AttributeError: 'module' object has no attribute 'RLock'

can someone help me to understand this error?

A: /Users/treinetic-macbook/Desktop/threading.py is being imported because it's on your path somewhere.  This is most likely not correct, try renaming that file and removing any threading.pyc file in your local dir.


text:
Q: What is the first value in a decoded view state? I was looking at some decoded view state values and I wonder what the first string value represents. e.g.:
Pair
 Pair
  1129781638

It seems that this value doesn't change if the page is refreshed or loaded in a different browser.
Let's take easyjet.com as an example - I tried the /EN and /PL versions of the site - the view state values were different but the string value was still the same for both:
1. /wEPDwUKMTEyOTc4MTYzOGRkWfx6hV2SnqItqR4uWJdw0H18w9fWuVgmqXph3EqMQ98=
2. /wEPDwUKMTEyOTc4MTYzOGRkWFe7DRds5xP9uLhFfkODYnASZhcgHyO0xh6yQ2I6Z0Y=

Online view state decoder:
http://ignatu.co.uk/ViewStateDecoder.aspx
Any ideas ?


text:
Q: reactjs html get request not received by php I have written a webpage that has a single submit button on it when pressed it sends a get request to a PHP script. The PHP script creates a file called asdf.txt. At the moment I have this code on 2 different servers, one of which is Heroku. On Heroku this code works fine: a new file called asdf.txt is created. However, on the other server (the one I want to put this code on), this does not work. No error messages are present on the HTML page, however.
Ideally what I would like is to have some suggestions on how to debug this. If anything specific comes to mind please let me know however I am also interested in broadly any way to go about dealing with this problem. Thanks for your time.
Here is the PHP
<?php
system('echo asdf > asdf.txt', $retval);
?>

Here is the HTML

A: In PHP, sometimes system(), exec() and their friends not giving us any error message. Even we set display_erros to On. As a workaround, I suggest you to create custom helper function like follow:
function my_exec($cmd, $input=''){
    $proc=proc_open($cmd, array(0=>array('pipe', 'r'), 1=>array('pipe', 'w'), 2=>array('pipe', 'w')), $pipes);
    fwrite($pipes[0], $input);fclose($pipes[0]);
    $stdout=stream_get_contents($pipes[1]);fclose($pipes[1]);
    $stderr=stream_get_contents($pipes[2]);fclose($pipes[2]);
    $rtn=proc_close($proc);
    return array('stdout'=>$stdout,
        'stderr'=>$stderr,
        'return'=>$rtn
    );
}

var_export(my_exec('echo asdf > asdf.txt'));

I got those script from: http://php.net/manual/en/function.system.php#94929
Then you can check the result at your browser "Network inspector". But before guide you there, I feel there is something wrong with your handleSubmit() function. I believe it will not properly do preventDefault(). Because we working with React which by default it will have "Synthetic event". To properly do preventDefault() I believe, we should make it as follow:
handleSubmit(event){
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
  }.bind(this)

  xmlHttp.open("GET","test.php",true)
  xmlHttp.send(null)
  event.nativeEvent.preventDefault();//This is how we really preventDefault() the native event, instead synthetic event
}

Then, after clicking "Submit", you should able to inspect the response from your PHP script.

I suggest making my_exec() just as a helper function to debug. Once you feel it works properly, replace it back with system() or exec() or anything you like.


text:
Q: How to fetch nodes (required nodes) associated to a node (criteria) based on a specific property of the node (criteria node) in Neo4j I am very new to Neo4j, I just started working on it. I have been through the basic tutorials about neo4j and have got quite a hang of the Cypher Query Language. However I am stuck at a particular query.
I have a structure as A-[relX]->B-[relY]->C-[relZ]->D where A, B, C, D are all labels. Now I have a requirement where I want to find all the nodes of label A related to the node of label D for specific property of D.
Lets say

*

*D:{name :"Tom"}

*D:{name :"Dick"}

*D:{name :"Harry"}

are my nodes f label D and I want to find all A's connected to D:{name :"Harry"} i.e, where name = "harry" for label D.

A: This should be pretty straightforward.  If you just want the ones related to "Harry":
MATCH (a:A)-[:relX]->(:B)-[:relY]->(:C)-[:relZ]->(:D {name: 'Harry'})
RETURN a

If you want to match a number of names and return all of the as:
MATCH (a:A)-[:relX]->(:B)-[:relY]->(:C)-[:relZ]->(d:D)
WHERE d.name IN ['Tom', 'Dick', 'Harry']
RETURN a

You might also want to know what D name was matched for each a:
MATCH (a:A)-[:relX]->(:B)-[:relY]->(:C)-[:relZ]->(d:D)
WHERE d.name IN ['Tom', 'Dick', 'Harry']
RETURN d.name, a

To return the information a bit more efficiently you could make the set of a nodes found for each name be an array:
MATCH (a:A)-[:relX]->(:B)-[:relY]->(:C)-[:relZ]->(d:D)
WHERE d.name IN ['Tom', 'Dick', 'Harry']
RETURN d.name, collect(a)

Lastly, as a style tip, I generally try to put the "anchor" node (one of the nodes that has a condition on it) at the start.  That would look like:
MATCH (d:D)<-[:relZ]-(:C)<-[:relY]-(:B)<-[:relX]-(a:A)
WHERE d.name IN ['Tom', 'Dick', 'Harry']
RETURN d.name, collect(a)

For more Cypher style tips, see Nigel Small's The Zen of Cypher


text:
Q: Why can't I run this fibonacci sequence? extremely new to python, whenever I try to run this code
def fib(n):
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end = ' ')
        a, b = b, a+b
    print()

I get an error message saying either
print(a, end=' ') SyntaxError: invalid syntax
or
fib() not defined.
how can I solve this?

A: Because you didn't take value of n from the user.
def fib(n):
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end = ' ')
        a, b = b, a+b
    print()
fib(10)

A: Your code has no issue if you were to use Python 3 so consider using that instead.
If you like python2 a lot then modify your code to the following:
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
    print(str(a) + ' ')
    a, b = b, a+b

This is because python2 doesn't allow the use of
print(a, end = ' ')

It is a python3 feature


text:
Q: Linq Expression to Query Two List I have two types of objects. Object A contains a field of id and Object B contains a field of id and a field of datetime. Now I have a list of object A and a list of object B. I want to get a list of object B where the id of object B is equal to the id of object A at the same time that this object B is the first object in the object B list ordered descending by the date field corresponding to one id for both objects. How can I write one single linq query expression to get this list instead of using a loop to loop through to search the target object B? Thanks in advance.

A: Without your code it's hard to tell if this will work but seems like you want something like this
var matchingB = listObjectB.OrderByDescending(b => b.DateTime)
           .Where(b => listObjectA.Any(a => a.Id == b.Id))
           .GroupBy(b => b.Id).ToList();

A: I strongly suggest using joins for comparing two lists by an ID-like field - that's what joins are for and this is generally the most efficient way.
If you can assume, that the first list has only unique IDs (as you can often assume about IDs), this will do the job:
var selected1 = listA
    .Join(
        listB
            .GroupBy(b => b.Id)
            .Select(g => g.OrderBy(b => b.Date).First()),
        a => a.Id,
        b => b.Id,
        (a, b) => b);

The following query would yield better performance, if IDs in listA drastically limit the number of IDs in listB (as the grouping and ordering are applied to this limited list).
var selected2 = listA
    .Join(listB, a => a.Id, b => b.Id, (a, b) => b)
    .GroupBy(b => b.Id)
    .Select(g => g.OrderBy(b => b.Date).First());

The second methods works, when there are repeated IDs in listA. If I had reasons to believe that there may be many many repeated IDs in listA, I would aply Distinct (which would also fix selected1 in case of repeated IDs). For example, without EqualityComparer:
var selected3 = listA
    .Select(a=>a.Id)
    .Distinct()
    .Join(listB, id => id, b => b.Id, (id, b) => b)
    .GroupBy(b => b.Id)
    .Select(g => g.OrderBy(b => b.Date).First());

A: In LINQ, you can have multiple from's if you want to query more than one data source, so for your problem I would do something like this:
internal class Program
{
    private static void Main(string[] args)
    {
        //The below code is just me pulling some data out of the air to work with
        var listOfIds = new List<ObjectA>();
        var data = new List<ObjectB>();

        for (var i = 0; i < 5; i++)
        {
            if (i % 2 == 0)
            {
                listOfIds.Add(new ObjectA(i));
            }

            data.Add(new ObjectB(i, DateTime.Now.AddDays(i)));
        }

        //Now we have two ILists which match the type of data you were talking about, and you simply query them like so
        var datesWhereIdIsInList = (from id in listOfIds
                                    from date in data
                                    where id.Id == date.Id
                                    select date).OrderByDescending(x => x.DateTime).ToList();
    }

    private class ObjectA
    {
        private readonly int _id;

        public ObjectA(int id)
        {
            _id = id;
        }

        public int Id
        {
            get { return _id; }
        }
    }

    private class ObjectB
    {
        private readonly int _id;
        private readonly DateTime _dateTime;

        public ObjectB(int id, DateTime dateTime)
        {
            _id = id;
            _dateTime = dateTime;
        }

        public int Id
        {
            get { return _id; }
        }

        public DateTime DateTime
        {
            get { return _dateTime; }
        }
    }
}


text:
Q: Mean Value Theorem with variable bounds? In the exercise, applying the Mean Value Theorem to the function $f(x)=x^j$ in
the interval $[\frac{k-i}{k},\frac{k-i+1}{k}]$, they obtain:
$ \left ( \frac{k-i}{k}\right )^j-\left ( \frac{k-i+1}{k}\right )^j=
 \left (\frac{k-i}{k}-\frac{k-i+1}{k}\right )j x_i^{j-1}=\frac{j}{k}x_i^{j-1}$.
for some $x_i \in [\frac{k-i}{k},\frac{k-i+1}{k}]$.
My question is how they can make $x_i$ as a sequence like this? Is it simply because the bounds of the interval are depending on $i$? or there exists a version of the MVT such that they get such a sequence when the interval bounds are variable?
Thank you.

A: $x_i \in [\frac{k-i}{k},\frac{k-i+1}{k}]$ can actually be $x_i \in (\frac{k-i}{k},\frac{k-i+1}{k})$


text:
Q: Will it be a good approach to have two separate controllers for the same micro-service? I have a Spring-boot based microservice which is currently being hit from a Mobile-APP. Now we are developing a browser base client for the same microservice. Request & Response parameters between mobile-App and browser are same. Number of users in mobile-APP is around 10000 per second and for browser  is around 20000 per second. Hence, there would be more than 30000 hits to this microservice each second.
We know that "Spring controllers are singletons (there is just one instance of each controller per web application) ".
Will it be a good approach (with respect of performance) to have two separate Controllers for this same microservice, one for mobile-App users and other for browser users ?  Will it improve microservice performance by having two instances running in parallel ?
I am looking the best way to handle increasing number of hits through both the channels ?
Any suggestions would be highly appreciated.

A: When You have the same request and response, retrieved to browser and mobile clients there is no point in creating two diff controllers or services. Keep your app simple with one controller to do the job. With this your service just sees the mobile and web client in same way.
Whenever there is increase in load that has to be handled by the app, you can go for horizontal scaling, using a routing, load balancer service like zuul, nginx.
Just scale up/down the instances behind the load balancer according to the load you need to handle.


text:
Q: Are the vectors incoherent when they have a small dot product? Assuming the dot product of two vectors $\langle a, b\rangle$ is small but not zero.
I cannot say they are orthogonal, but I want to say they can be considered more dis-similar than similar.
Is there any better term to describe that situation?
Can I say they are incoherent?


text:
Q: PHP Url string to array I'm trying to find out if there's any function that would split a string like:
keyword=flower|type=outdoors|colour=red

to array:
array('keyword' => 'flower', 'type' => 'outdoors', 'colour' => 'red')

At the moment I built a custom function, which uses explode to first split elements with the separator | and then each of those with assignment symbol =, but is there perhaps a native function which would do it out of the box by specifying the string separator?
The function I've written looks like this:
public static function splitStringToArray(
    $string = null,
    $itemDivider = '|',
    $keyValueDivider = '='
) {

    if (empty($string)) {

        return array();

    }

    $items = explode($itemDivider, $string);

    if (empty($items)) {

        return array();

    }

    $out = array();

    foreach($items as $item) {

        $itemArray = explode($keyValueDivider, $item);

        if (
            count($itemArray) > 1 &&
            !empty($itemArray[1])
        ) {

            $out[$itemArray[0]] = $itemArray[1];

        }

    }

    return $out;

}

A: $string = "keyword=flower|type=outdoors|colour=red";
$string = str_replace('|', '&', $string);
parse_str($string, $values);
$values=array_filter($values);   // Remove empty pairs as per your comment
print_r($values);

Output
Array
(
    [keyword] => flower
    [type] => outdoors
    [colour] => red
)

Fiddle

A: Use regexp to solve this problem.
([^=]+)\=([^\|]+)

http://regex101.com/r/eQ9tW8/1

A: The issue is that your chosen format of representing variables in a string is non-standard. If you are able to change the | delimiter to a & character you would have (what looks like) a query string from a URL - and you'll be able to parse that easily:
$string = "keyword=flower&type=outdoors&colour=red";
parse_str( $string, $arr );
var_dump( $arr );

// array(3) { ["keyword"]=> string(6) "flower" ["type"]=> string(8) "outdoors" ["colour"]=> string(3) "red" }

I would recommend changing the delimiter at the source instead of manually replacing it with replace() or something similar (if possible).


text:
Q: How to Remove Retake step in UIImagePicker? I do not want to show Retake step in my iphone application.
how?? subclassing uiimagepicker?

A: Don't subclass UIImagePickerController. It's a bunch of view controllers packaged in a UINavigationController subclass.
I don't think you can skip the Retake step. Use the AV Foundation framework instead.

A: UIImagePickerController calls its delegate's didFinishPickingMediaWithInfo immediately after taking a picture if it has 'showsCameraControls' set to false.


text:
Q: if else in where clause on columns I have a situation where we have added a new column current_owner (createdBy is already there).
Now I want to write a query such that in where clause if current_owner is null then condition applied on createdBy or else on current_owner.
select *
from wns
where (if current_owner==null then createdBy = ? else current_owner = ?)

A: SELECT *
FROM wns
WHERE ? = COALESCE(current_owner, createdBy);

PS. In DBMS with strong datatypes system you must explicitly cast both operands in COALESCE to the same datatype which can be compared with the parameter provided.


text:
Q: Laravel Get Updated_at gives wrong Return I want to return the updated_at field from my database when making a GET Request.
I always get back something like this:
{
    "data": [
        {
            "id": 1,
            "updated_at": {
                "date": "2015-03-08 12:52:28.000000",
                "timezone_type": 3,
                "timezone": "UTC"
            }
        },
        {
            "id": 2,
            "updated_at": {
                "date": "2015-03-19 13:40:39.000000",
                "timezone_type": 3,
                "timezone": "UTC"
            }
        }
    ]
}

But I actually want that updated_at to look like this:
..."updated_at":"2015-03-08 12:52:28"...

I am using a Transformer to return the data like this:
<?php namespace App\Http\Controllers;

use Project;
use League\Fractal\TransformerAbstract;

class ProjectDateTransformer extends TransformerAbstract
{
    public function transform(Project $project)
    {
        return [
            'id'         => (int) $project->id,
            'updated_at' => $project->updated_at,
        ];
    }
}

So what am I doing wrong?
I am using MariaDB as the database encase this has something to with that?

A: Laravel turns updated_at/created_at/deleted_at timestamps into Carbon objects. You can use Carbon's various formatting options to get the particular format you want, or you can use (string)$project->updated_at to cast it as a string, which will use the default format (which matches what you want).


text:
Q: Download excel file with php I need to download an excel file from the external link.
i wrote 2 codes and both went wrong  :
first one :
$url = "www.example.com";
$data = file_get_contents($url);
$destination = "test.xlsx";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);

after running this script, I can't my test.xlsx file,
and got and excel error:
Excel cannot open this file, The file format or file extension is not valid.
Verify that the file has not been corrupted and that the file extension matches the format of the file.

second one :
$ch = curl_init();
$targetFile = fopen( 'test.xlsx', 'w' );
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:
application/vnd.ms-excel"));
curl_setopt($ch, CURLOPT_URL,
www.example.com');
curl_setopt( $ch, CURLOPT_FILE, $targetFile );
curl_exec( $ch );
fclose( $targetFile );

and again I got the same error. when I am trying to open that link from the browser , xlsx file downloads automatically but I cannot download that link from code, plz help

A: my understanding of the question is like
yoursite
www.yoursite.com
site with file
www.sitewithfile.com/path/file.xlxs
l thing you use a link
Download


text:
Q: How to make a TextInputFormatter Mask for IpAddress in flutter I am trying to make a TextInputFormatter Mask for IpAddress in flutter
What I am trying to do :
import 'package:flutter/services.dart';

class IpAddressInputFormatter extends TextInputFormatter {
  String separator = '-';

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.text.length > 0) {
      if (newValue.text.length > oldValue.text.length) {
        String lastEnteredChar = newValue.text.substring(newValue.text.length - 1);
        var value = newValue.text;
        if (lastEnteredChar == separator) {
          if (RegExp(separator).allMatches(newValue.text).length > 3) {
            return oldValue;
          }
          if (newValue.text.length > 9) {
            return oldValue;
          }
          return TextEditingValue(
            text: '$value',
            selection: TextSelection.collapsed(
              offset: value.length,
            ),
          );
        }
        if (!_isNumeric(lastEnteredChar)) return oldValue;
        if (_isNumeric(newValue.text.split(separator).last) && newValue.text.split(separator).last.length == 3) {
          if (newValue.text.length < 16 && newValue.text.split(separator).last.length <= 3) {
            var s = '$separator';
            s = newValue.text.length == 15 ? '' : s;
            s = RegExp(separator).allMatches(newValue.text).length > 2 ? '' : s;
            value = '${newValue.text}$s';
          } else if (RegExp(separator).allMatches(newValue.text).length > 2) {
            return oldValue;
          } else {
            return oldValue;
          }
        } else if (newValue.text.length > 15) {
          return oldValue;
        } else if (RegExp(separator).allMatches(newValue.text).length == 3 &&
            newValue.text.split(separator).last.length > 3) {
          return oldValue;
        }
        return TextEditingValue(
          text: '$value',
          selection: TextSelection.collapsed(
            offset: value.length,
          ),
        );
      }
    }
    return newValue;
  }

  bool _isNumeric(String s) {
    if (s == null) return false;
    return double.tryParse(s) != null;
  }
}

I expect the user to be able to enter 55.55.55.55 | 1.1.1.1 | 1.10.100.4 | etc
Is there a easy way to make an input text fiel for Ip Addresses ?
this code works for some scenarios but not for all ip scenarios, it works well for
10-10-10-10
111-111-111-111
192-168-133-13
1-1-1-1
1-10-10-1
but fails from time to time for
10-100-10-1

A: Surely it can be improved but it works for me like this.
inputFormatters: [
              MyInputFormatters.ipAddressInputFilter(),
              LengthLimitingTextInputFormatter(15),
              IpAddressInputFormatter()
            ],

MyInputFormatters.class
class MyInputFormatters {
    static TextInputFormatter ipAddressInputFilter() {
        return FilteringTextInputFormatter.allow(RegExp("[0-9.]"));
    }
}

IpAddressInputFormatter.class
class IpAddressInputFormatter extends TextInputFormatter {
@override
  TextEditingValue formatEditUpdate(
  TextEditingValue oldValue, TextEditingValue newValue) {
  var text = newValue.text;

  if (newValue.selection.baseOffset == 0) {
    return newValue;
  }

  int dotCounter = 0;
  var buffer = StringBuffer();
  String ipField = "";

  for (int i = 0; i < text.length; i++) {
    if (dotCounter < 4) {
      if (text[i] != ".") {
        ipField += text[i];
        if (ipField.length < 3) {
          buffer.write(text[i]);
        } else if (ipField.length == 3) {
          if (int.parse(ipField) <= 255) {
            buffer.write(text[i]);
          } else {
            if (dotCounter < 3) {
              buffer.write(".");
              dotCounter++;
              buffer.write(text[i]);
              ipField = text[i];
            }
          }
        } else if (ipField.length == 4) {
          if (dotCounter < 3) {
            buffer.write(".");
            dotCounter++;
            buffer.write(text[i]);
            ipField = text[i];
          }
        }
      } else {
        if (dotCounter < 3) {
          buffer.write(".");
          dotCounter++;
          ipField = "";
        }
      }
    }
  }

  var string = buffer.toString();
  return newValue.copyWith(
      text: string,
      selection: TextSelection.collapsed(offset: string.length));
  }
}


text:
Q: arreglo de estructuras dentro de una funcion tengo este codigo de ejemplo que arme de que pasaria llamo a un arreglo de estructuras en una funcion separada del main, estoy aprendiendo onda prueba y error y me surgió esta duda, y me surgio un error, la funcion no detecta la estructura del main y quisiera saber por que, si me lo pueden corregir por favor, e buscado por la web y no e encontrado nada similar asi que ayudarian a muchas personas que quiza se crucen con este mismo obstáculo.
primeramente el codigo en C metido en un solo archivo funciona perfectamente y no tira niun tipo de error;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct personas
{
char nombre[20];
int edad;
float salario;
}datos[5];
////////////////////////////////////////////////////////////////////////
void carga()
{
for(int i=0;i<5;i++)
 {
  printf("ingresar nombre\n");
  gets(datos[i].nombre);
  printf("\ningresar edad\n");
  scanf("%i",&datos[i].edad);
  printf("\ningresar salario\n");
  scanf("%f",&datos[i].salario);
  fflush(stdin);
 }
}
/////////////////////////////////////////////////////////////////
int main()

{
carga();
for(int c=0;c<5;c++)
 {
  printf("\nnombre %i es: ",c); puts(datos[c].nombre);printf("\n");
  printf("\n edad %i es: %i\n",c,datos[c].edad);
  printf("\nsalario %i es: %2.f\n ",c,datos[c].salario);
  fflush(stdin);
 }
system ("pause");

return 0;
}

ahora bien, el problema es cuando trato de separarlos de esta manera
primer archivo
archivo main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "datos.c"
struct personas
{
char nombre[20];
int edad;
float salario;
}datos[5];
////////////////////////////////////////////////////////////////////////
void carga();
/////////////////////////////////////////////////////////////////
int main()
{
carga();// funcion cargar datos
for(int c=0;c<5;c++)
 {
  printf("\nnombre %i es: ",c); puts(datos[c].nombre);printf("\n");
  printf("\n edad %i es: %i\n",c,datos[c].edad);
  printf("\nsalario %i es: %2.f\n ",c,datos[c].salario);
  fflush(stdin);
 }
system ("pause");

return 0;
}

en el siguiente archivo me marca el error justo cuando debe guardar un dato en la estructura del main
10  7 [Error] 'datos' undeclared (first use in this function)
segundo archivo
datos.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void carga()
{
for(int i=0;i<5;i++)
 {
  printf("ingresar nombre\n");
  gets(datos[i].nombre);//justo aqui me marca un error
  printf("\ningresar edad\n");
  scanf("%i",&datos[i].edad);
  printf("\ningresar salario\n");
  scanf("%f",&datos[i].salario);
  fflush(stdin);
 }
}

Muchas gracias de antemano

A: Primero estás cargando datos.c y hasta después defines la estructura, es decir, intentas usar la variable antes de definirla. Mueve ese bloque de main.c a datos.c y debería funcionar:
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "datos.c"
////////////////////////////////////////////////////////////////////////
void carga();
/////////////////////////////////////////////////////////////////
int main()
{
carga();// funcion cargar datos
for(int c=0;c<5;c++)
 {
  printf("\nnombre %i es: ",c); puts(datos[c].nombre);printf("\n");
  printf("\n edad %i es: %i\n",c,datos[c].edad);
  printf("\nsalario %i es: %2.f\n ",c,datos[c].salario);
  fflush(stdin);
 }
system ("pause");

return 0;
}

datos.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct personas
{
char nombre[20];
int edad;
float salario;
}datos[5];

void carga()
{
for(int i=0;i<5;i++)
 {
  printf("ingresar nombre\n");
  gets(datos[i].nombre);//justo aqui me marca un error
  printf("\ningresar edad\n");
  scanf("%i",&datos[i].edad);
  printf("\ningresar salario\n");
  scanf("%f",&datos[i].salario);
  fflush(stdin);
 }
}


text:
Q: xmllint problems to output lines I know that my question includes 2 questions...
At first, I want to use xmllint to output "loc" content tags. The sitemap I load has got a xmlns="...".
On xmllint shell, I need to do this:
setrootns
xpath //defaultns:loc

That works... no problem. But I need to do this in a bash script.
(AFAIK) xmllint hasn't got option to tell "let's go, setrootns" so I cannot do this:
xmllint --xpath "//loc" sitemaps.xml
# or
xmllint --xpath "//defaultns:loc" sitemaps.xml

This is the first question, how can I tell to xmllint to load the default ns ?
If I can't, let's take a look on my second solution:
I can remove xmlns attribute and then, there os no ns to use:
xmllint --xpath "//loc" <(sed -r 's/xmlns=".*?"//' sitemaps.xml)

But... now... the whole response of my 500 "loc" content is concatenated in one line !...
I tried this too:
xmllint --shell sitemaps.xml <<EOF
setrootns
xpath //defaultns:loc/text()
EOF

Or again
xmllint --shell sitemaps.xml <<EOF
setrootns
cat //defaultns:loc
EOF

The first gives me (for example)
465  TEXT
    content=http://...

with truncated url
The second gives me "------" every 2 lines... and a "/>" at last line...
And I begin to be very nervous... :)
A big thanks if you find any solution.
The goal is to have every location, one per line.

A: @BrnVrn is right, I only had to append "\n" after  tags
Then I found my answer about namespaces, I can use local-name to not check default namespace
So, I did this:
xmllint  --xpath "//*[local-name()='loc']/text()" <(sed 's/<loc>/<loc>\n/g' sitemaps.xml)

And it works !
Thanks to all

A: I used to do something similar:
clean_xml_message=$(echo "$xml_message" | sed 's/xmlns/ignore/')

Eventually you could try to put back the new lines:
sed 's/></>\n</g'

I guess you only want the URL without the <loc></loc> ?
Then I would select all the loc elements with xmllint:
<loc>...</loc><loc>...</loc><loc>...</loc>

Then add the new lines: sed 's/<loc>/<loc>\n/g' | sed 's#</loc>#\n</loc>#g'
<loc>
...
</loc><loc>
...
</loc><loc>
...
</loc>

Finally remove the tags grep -v "<loc>" |grep -v "</loc>" or a single grep -v "$<" could do it. (-v is the invert selection: http://unixhelp.ed.ac.uk/CGI/man-cgi?grep)

A: For the newline problem you can have a look at this repo:
https://gitlab.gnome.org/cykerway/libxml2
And its merge request:
https://gitlab.gnome.org/GNOME/libxml2/merge_requests/8
Basically it gives you a choice of separator in a xpath nodeset result. So with this example.xml:
<?xml version="1.0" encoding="UTF-8"?>
<menu>
    <food>
        <name>Hot Chocolate</name>
        <price>$1.99</price>
    </food>
    <food>
        <name>Iced Tea</name>
        <price>$2.99</price>
    </food>
</menu>

You can do:
# xmllint --xpath "//name/text()" --xpath-separator "\n" example.xml

Output:
Hot Chocolate
Iced Tea


text:
Q: Default template argument in method hidden behind class default template argument #include <iostream>

template< typename T = char >
struct Foo {
        void bar();
};

template< typename T = int >
void Foo< T >::bar() {
    std::cout << typeid( T ).name() << std::endl;
}

int main() {
    Foo<> x1;
    Foo< double > x2;
    x1.bar();
    x2.bar();
}

Output:
char
double

char is hiding the int here, why is that?
Is it even possible to have multiple different template arguments for the same class?
(Guess not)But why doesn't yell the compiler then?

http://connect.microsoft.com/VisualStudio/feedback/details/892125/ill-formed-default-template-argument-not-throwing-error

A: ill-formed snippet
The code provided in your post is ill-formed as stated by the C++ Standard (n3337):

14.1p9 Template parameters [temp.param]

A default template-argument is a template-argument (14.3) specified after = in a template-paraemter. A default template-argument may be specified for any kind of template-parameter (type, non-type, template) that is not a template parameter pack (14.5.3). A default template-argument may be specified in a template declaration. [ Note: >>] A default template-argument shall not be specified in the template-parameter-lists of the definition of a member of a class template that appears outside of the member's class. [ << :Note ]

Conclusion
With the above quotation in mind we can draw the conclusion that the compiler you are using is faulty; it's not conformant to the rules set out by the Standard, the snippet should not be accepted.

What are the reason behind the Standard disallowing such construct?
Honestly this most probably boils down to "well, it doesn't make sense to allow it".
Since the type of x1 (and with that the type of T) is known at the type of declaration (Foo<> => F<char>), a potential default template-argument when defining a member of the class is useless; it will never be required, nor will it be used.


text:
Q: Automatically populate GravityForms field with rotating values I'm using gravity forms to send sales inquiries to a CRM.
We have 3 salespeople who each need to receive inquiries in a rotation.
For example:

*

*Entry 1 - Tom

*Entry 2 - Richard

*Entry 3 - Harry

*Entry 4 - Tom

*Entry 5 - Richard

*Entry 6 - Harry

Each time there's a new entry on the contact form I need to include a hidden field containing the name of the next sales person in the rotation to pass to our CRM.
I have some experience in PHP but not familiar with Gravity. Hopefully, someone can point me in the right direction to find a solution.

A: Here's an example of how to accomplish this:
/**
 * Gravity Wiz // Gravity Forms // Rotating Values
 * http://gravitywiz.com/
 */
add_filter( 'gform_entry_post_save', function( $entry ) {

    // Specify an array of values that will be rotated through.
    $rotation = array( 'Tom', 'Richard', 'Harry' );

    // Specify the form ID for which this functioanlity applies.
    $form_id = 1722;

    // Specify the field ID in which the current rotation value will be saved.
    $field_id = 1;

    /* DON'T EDIT BELOW THIS LINE */

    // Bail out of this is not our designated form.
    if( $entry['form_id'] != $form_id ) {
        return $entry;
    }

    // Get the last submitted entry.
    $last_entry = rgar( GFAPI::get_entries( $entry['form_id'], array( 'status' => 'active' ), array( 'direction' => 'desc' ), array( 'offset' => 1, 'page_size' => 1 ) ), 0 );

    // Get the value submitted for our designated field in the last entry.
    $last_value = rgar( $last_entry, $field_id );

    // Determine the next index at which to fetch our value.
    $next_index = empty( $last_value ) ? 0 : array_search( $last_value, $rotation ) + 1;
    if( $next_index > count( $rotation ) - 1 ) {
        $next_index = 0;
    }

    // Get the next value based on our rotation.
    $next_value = $rotation[ $next_index ];

    // Update the value of our designated field in the database.
    GFAPI::update_entry_field( $entry['id'], $field_id, $next_value );

    // Update the value of our designated field in the $entry object that will be used to continuing processing the current submission.
    $entry[ $field_id ] = $next_value;

    return $entry;
} );

Also available as a gist for posterity: https://gist.github.com/spivurno/8908a589aa6ceaf6ff0a874324bfbf93


text:
Q: Display archive posts in Wordpress I am looking to display archives pages as a normal posts page...
So, a posts page with a secondary navigation showing:
LATEST POSTS / LAST MONTH / LAST YEAR / OLDER
On each of those pages, I would like to display a summary of each post just like the standard latest news page. When you click through you get to the full post.
For each of menu items I have created seperate page templates such as archives_month.php, Then in the template instead of using <?php wp_get_archives I have been using <?php query_posts and adding some time params but unfortunately I have no found the best / correct way to get these yet.
I have one script that works:
<?php if (have_posts()) : ?>
<?php $current_month = date('m');?>
<?php $current_year = date('Y');?>
<?php $current_year = $current_year - 24;?>
<?php query_posts("cat=5&year=$current_year&monthnum=$current_month");?>

For the LAST MONTH page. But I now cannot use this for LAST YEAR and OLDER posts.
Can anyone help me? I've looked into a number of different ways to do it but on some blogs it's not clear and most people just retrieve a list of archives rather than displaying the posts.
Thanks in advance.
Mel

A: You should be able to put something together using query_posts() as described here.
An example from the linked page for building a query fetching all posts in March 2009:
<?php
//based on Austin Matzko's code from wp-hackers email list
  function filter_where($where = '') {
    //posts for March 1 to March 15, 2009
    $where .= " AND post_date >= '2009-03-01' AND post_date < '2009-03-16'";
    return $where;
  }
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>

you will find it easy to adjust.
The output can then be done using The Loop:
// the Loop
while (have_posts()) : the_post();
  // the content of the post
  the_content('Read the full post »');
endwhile;

For more info on how to customize the stuff displayed in The Loop (to show the summary you talk about) see here.


text:
Q: "public://public://user-pictures does not exist" when trying to change user profile photo path I'm trying to change the path for the user profile pictures in a Drupal 7 installation and I'm getting the following error:

The directory public://public://user-pictures does not exist or is not
  writable.

The path that I'm entering is simply "user-profiles".
I tried resetting the variable stored in the database by using the value from a new installation:
 UPDATE variable
 SET value=0x733A313A2231223B
 WHERE name = 'user_pictures';

The update was successful but the problem remained.
Does anybody know how to correct this or where this value is stored in the database?
Thanks

A: user_pictures is a boolean variable, you're probably looking for user_picture_path.
Since variable values are stored in serialised PHP arrays it'll be much easier to update that path using the API:
variable_set('user_picture_path', 'user-profiles');

A: Similar to Clive answer, you can use drush from the command line :
drush vset user_picture_path your_path

A: I got the same error and am able to solve the issue.
"public://public://user-pictures does not exist" when trying to change user profile photo path."
What is did: Navigated to mysite.com/admin/config/people/accounts
 in 'Picture directory' field default value was 'pictures', i have changed the directory name to my custom directory name 'prof_images' and now when i try to save the settings, i started getting the above error. I have cross checked the Directory name and permission but everything was fine.
How i solved the issue:
Navigated to Drupal core modules folder /modules/user and commented the following lines:

Blockquote

if (!file_prepare_directory($picture_path, FILE_CREATE_DIRECTORY)) {
      form_set_error('user_picture_path', t('The directory %directory does not exist or is not writable.', array('%directory' => $picture_path)));
      watchdog('file system', 'The directory %directory does not exist or is not writable.', array('%directory' => $picture_path), WATCHDOG_ERROR);
    }

Blockquote

After clearing the cache, everything went cool.
Navigated to mysite.com/admin/config/people/accounts and set 'prof_images' as my user image directory and saved the settings. This time my settings are saved without any problem.
Then uncommented the above lines in the user module and everything worked as usual.
Hope this will help someone.
Thanks


text:
Q: Basic hypothesis testing question: how to find the c.r. for a variance test? Let's suppose that we have two normal distributions, and a sample is taken from each (of sizes $n_X$ and $n_Y$ respectively).
$X \rightarrow N(\mu_X, \sigma_X ^2), Y \rightarrow N(\mu_Y, \sigma_Y ^2)$.
We want to test: $H_0$: "$\sigma_X ^2= \sigma_Y ^2$" against $H_1$: "$\sigma_X ^2 \neq \sigma_Y ^2$".
Depending on whether $S_X ^2 > S_Y ^2$ or otherwise, we take the decision variable as (supposing the former case):
$$F = \frac{S_X ^2}{S_Y ^2} \rightarrow \operatorname{Fischer}(\nu_1 = n_X -1, \nu_2 = n_Y - 1)$$
Everything is fine until here (though I'm not quite sure if this is the correct formula). Anyhow, how would I find the critical region? Supposing that the risk is $\alpha$.

A: By "risk", I take it you mean what I would refer to as "significance level".
The right-half of the critical region is the values greater than $F_{R}=F_{n_{X}-1,n_{Y}-1,\alpha/2}$, where $F_{R}$ is defined to be the value such that $P(X>F_{R})=\alpha/2$ if $X \sim \text{Fischer}(n_{X}-1,n_{Y}-1)$. This can usually be looked up in tables.
What usually cannot be looked up in tables is the corresponding value $F_{L}$ such that $P(X<F_{L})=\alpha/2$. Fortunately, this can be found by the formula $$F_{L} = \frac{1}{F_{n_{Y}-1,n_{X}-1,\alpha/2}},$$ taking care to note that we have swapped the degrees of freedom in the denominator.


text:
Q: Missing required parameter - public_id, and what to assign to imageId for Cloudinary I'm building a website that users can upload insights and comments on reading novels,
and users are free to fetch images of the novel or not.
If an image is chosen, the post schema has image & imageId attribute for Cloudinary uploads and future manipulation such as changing(update route) or deleting(destroy route) it from the Cloudinary library.
If no image is chosen, then a default image takes place.
Problem is, I managed to make default image function work, however I don't want multiple same default images uploaded to Cloudinary library, so I put default_image.jpg in local server folder (/public/images) to be exact), and this default_image.jpg shouldn't be in Cloudinary library and this should save a lot of capacity.
However, for these posts without a chosen image, I dunno what I should assign for their imageId property.
I tried undefined and null, and of course, they didn't work, cuz' this way it won't be able to find certain novel.imageId if they're all undefined or null.
// Schema for data
var fictionSchema = new mongoose.Schema({
    ...
    ...
    image: String,
    // for cloudinary API to track which image to delete or update
    imageId: String,
    ...
    ...
});

// CREATE route
router.post("/", middleware.isLoggedIn, upload.single('image'), (req, res) => {
    if (req.file){
        // req.file.path comes from multer npm
        cloudinary.v2.uploader.upload(req.file.path, function (err, result) {
            if (err) {
                ...
            }
            // add cloudinary url for the image to the novel object under image property
            req.body.novel.image = result.secure_url;
            req.body.novel.imageId = result.public_id;
        });
    } else {
        // setup default image for new novels
        req.body.novel.image = "/images/noimage.jpg";

        // imageId here should be ... empty? Undefined? Null? A fixed ID but may be delete when accessing Destroy route?
        req.body.novel.imageId = undefined;
    }
    ...
    ...
    Novel.create(req.body.novel, function (err, newlyAddedNovel) {
        if (err) {
            req.flash('error', err.message);
            ...
        } else {
            req.flash("success", "Novel added successfully.");
            ...
        }
    });
});

// DESTROY route
router.delete("/:id", middleware.checkNovelOwnership, (req, res) => {
    // find and delete the correct novel along with the image on cloudinary
    Novel.findById(req.params.id, async (err, novel) => {
        if (err) {
            req.flash("error", err.message);
            return res.redirect("back");
        }
        try {
            await cloudinary.v2.uploader.destroy(novel.imageId);
            // delete the novel found
            novel.remove();
            // delete the image from cloudinary
            req.flash("success", "Novel deleted successfully.");
            ...
            ...
        } catch (err) {
            ..
        }
    });
});

A: Good news, I solved the problem! Her-ray! Took me around 2 hrs though...
So, in the end everything worked just as I wanted, such finesse.
Codes are as below:
• CREATE route
For new posts, I set up every new novel with the default image first, then if there's an image (req.file) given, change it and upload.
Afterwards, remember to create that novel data in mongo database. (Novel.create() in my case.)
router.post("/", middleware.isLoggedIn, upload.single('image'), async function (req, res) {
    // set every new novel with default image first
    req.body.novel.image = "https://res.cloudinary.com/dvfkbz6la/image/upload/v1565434656/noimage_ew1uri.jpg";
    req.body.novel.imageId = "noimage_ew1uri";
    req.body.novel.user = {
        id: req.user._id,
        username: req.user.username
    };

    if (req.file) {
        // req.file.path comes from multer npm
        await cloudinary.v2.uploader.upload(req.file.path, function (err, result) {
            if (err) {
                req.flash('error', err.message);
                return res.redirect('back');
            }
            // add cloudinary url for the image to the novel object under image property
            // add image's public_id (imageId in novel model) to novel object
            req.body.novel.image = result.secure_url;
            req.body.novel.imageId = result.public_id;
        });
    }
    Novel.create(req.body.novel, function (err, newlyAddedNovel) {
        if (err) {
            ...
        } else {
            ...
        }
    });
});

• UPDATE route
In try block, if (novel.imageId = "DEFAULT_IMAGEID") { } else { } is added.
// UPDATE route
router.put("/:id", middleware.checkNovelOwnership, upload.single('image'), (req, res) => {
    // find the correct novel
    Novel.findById(req.params.id, async (err, novel) => {
        if (err) {
            ...
        } else {
            // if there's a req.file, we know user is trying to upload a new image
            if (req.file) {
                try {
                    // if imageId is default, await the result to be uploaded
                    if (novel.imageId = "noimage_ew1uri") {
                        var result = await cloudinary.v2.uploader.upload(req.file.path);
                    } else {
                        //  if not default, find the old image using imageId and delete
                        await cloudinary.v2.uploader.destroy(novel.imageId);
                        var result = await cloudinary.v2.uploader.upload(req.file.path);
                    }
                    novel.imageId = result.public_id;
                    novel.image = result.secure_url;
                } catch (err) {
                    ...
                }
            }
            novel.title = req.body.title;
            novel.author = req.body.author;
            novel.price = req.body.price;
            novel.description = req.body.description;

            // remember to save the changed novel
            novel.save();
            req.flash("success", "Successfully Updated!");
            res.redirect("/novels/" + novel._id);
        }
    });
});

• DESTROY route
In try block, if (novel.imageId != "DEFAULT_IMAGEID") { } else { } is added.
// DESTROY route
router.delete("/:id", middleware.checkNovelOwnership, (req, res) => {
    // find and delete the correct novel along with the image on cloudinary
    Novel.findById(req.params.id, async (err, novel) => {
        if (err) {
            req.flash("error", err.message);
            return res.redirect("back");
        }
        try {
            // if novel.imageId isn't default, destroy it from Cloudinary
            if (novel.imageId != "noimage_ew1uri") {
                await cloudinary.v2.uploader.destroy(novel.imageId);
            }
            // delete the novel found
            novel.remove();
            ...
        } catch (err) {
            ...
        }
    });
});

Only problem left is, I dunno why but when hitting UPDATE route,
and when the imageId isn't the default one and the user changed the image,
the old image will NOT be destroyed and stayed in Cloudinary library. Such oddness.
I sure have this code set up
Novel.findById(req.params.id, async (err, novel) => {
        if (err) {
            ...
        } else {
            if (req.file) {
                try {
                    // if imageId is default, await the result to be uploaded
                    if (novel.imageId = "noimage_ew1uri") {
                        ...
                    } else {
                        //  if not default, find the old image using imageId and delete
                        await cloudinary.v2.uploader.destroy(novel.imageId);
                        var result = await cloudinary.v2.uploader.upload(req.file.path);
                    }
...
...

Dunno why await cloudinary.v2.uploader.destroy(novel.imageId); isn't working as expected. Hmmm...

A: Images that were already available in your site, are cached in one or more CDN edges. Therefore, even if you delete the image from your Cloudinary account, cached copies might still be available. In default, all delivered images are cached for 30 days.
When using the destroy API with the invalidate parameter set to true, the image will be deleted and purged from the CDN, allowing for the new image to be displayed.
Alternatively, when updating, you can accomplish the same result by setting the overwrite and invalidate parameters to true when uploading the new file (without the need to call the destroy method).


text:
Q: Does autodesk forge support downloading as an ascii fbx Does Autodesk Forge support downloading an fbx in ascii format? Is there a list somewhere of currently supported derivative formats?

A: You can find the list of supported output formats here:
https://developer.autodesk.com/en/docs/model-derivative/v2/overview/supported-translations/
As of now fbx output is not supported yet.