text:
Q: Is there a way to avoid from the mouse when moving a user input slider to highlight the html embed element? This is my site now. nothing much there yet. only the google map and a user input slider.  if you will move the slider left/right and while dragging it you drag the mouse up/down you will see that it's like selecting highlighting the map.
https://rhodan.wixsite.com/my-site-1
The problem is when I'm moving the slider to the left or to the right if the mouse is a bit leaving the slider up or down it's highlighting the html element.
it's like when dragging the mouse on the slider to change the slider value sometimes it's also highlighting the html element.

I tried john solution and added to my html embed code in wix the answer part to the bottom:
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google Maps Api</title>

    <input id="slider1" type="range">

You should not be able to select me when you click above slider and drag the mouse around

This is the part of the solution:

        <input id="slider1" type="range">

You should not be able to select me when you click above slider and drag the mouse around

but the problem still remains.

A: On mouse down you need to do something like:
// add event
document.addEventListener('selectstart', dontSelectAnything);

and on mouse up you need to remove it
// remove event
document.removeEventListener('selectstart' dontSelectAnything);

finally... add this function
function dontSelectAnything(evt) {
  evt.preventDefault();
}

the evt.prevenyDefault() prevents the browser from carrying out the default selectstart behavour which prevents any selection from working.
Proof of concept...

function dontSelectAnything(evt) {
   evt.preventDefault();
}

const sliders = document.querySelectorAll("[data-testid='track']");

sliders.forEach( (s) => {
  s.addEventListener('mousedown', (evt) => {
    document.addEventListener('selectstart', dontSelectAnything);
  });

  s.addEventListener('mouseup', (evt) => {
      document.removeEventListener('selectstart', dontSelectAnything);
  });
});
<input data-testid="track" type="range">

You should not be able to select me when you click above slider and drag the mouse around


text:
Q: How to erase an Ubuntu USB Boot Drive I used the Startup Disk Creator to create a USB Boot disk on my thumbdrive, but now I would like to clean the USB stick and re-use it at full capacity.  I don't have permission to erase or format the USB stick.  How can I clean this USB stick of all files?

A: I would plug in the USB, open up gparted, select the correct /dev/sd*, unmount it, and erase the partition. When you open to gparted it will prompt you for your password however.

A: Firstly you need to identify your USB Flash drive, so open up terminal and type sudo fdisk - l. It usually appears as the last one (in my case). BE CAREFUL! YOU MUST BE 100% SURE THAT YOU HAVE FOUND THE CORRECT ONE, OR ELSE YOU MAY LOSE DATA! Secondly, open up gparted and select the CORRECT DEVICE (in my case sda). Then delete all the partitions you find and create a new one, as filesystem I recommend using FAT32, but you can use whaterver you want, fill all the blanks and click OK. Lastly click APPLY and let it do it's job. Good Luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is Matrix A in Metric Learning expected to be PSD? I read that in Metric learning the metric A is supposed to PSD due to the non-negativity constraint on the distance.
My question is how does A being a PSD (positive semi-definite) ensures that the distance(Mahalanobis) will be non-negative?

A: I'm assuming you mean the following distance:
$$
d^2(x, y) = (x - y)^T A (x - y)
.$$
Say $A$ is $n \times n$.
Recall that one definition of a positive definite matrix is that it's a symmetric matrix such that for any nonzero vector $u \in \mathbb R^n$, $u^T A u > 0$.
Now, for $d$ to be a distance metric we require $d(x, y) > 0$ for any $x \ne y$. In that case, $x - y \ne 0$, and since $A$ is positive definite, $d(x, y) = \sqrt{(x - y)^T A (x - y)} > 0$.
If you prefer the definition that all eigenvalues are positive, we can prove that this property also holds from that: letting $v_i$ be the $i$th eigenvector and $\lambda_i$ its corresponding eigenvalue, we can write $u = \sum_{i=1}^n \alpha_i v_i$ since the $v_i$ are an orthonormal basis, so that
\begin{align}
u^T (A u)
&= \left( \sum_{i=1}^n \alpha_i v_i \right)^T \left( \sum_{i=1}^n \alpha_i A v_i \right)
\\&= \left( \sum_{i=1}^n \alpha_i v_i \right)^T \left( \sum_{i=1}^n \alpha_i \lambda_i v_i \right)
\\&= \sum_{i=1}^n \sum_{j=1}^n \alpha_i \alpha_j \lambda_i v_i^T v_j
\\&= \sum_{i=1}^n \alpha_i^2 \lambda_i > 0
\end{align}
since $v_i^T v_j = \begin{cases} 1 & i = j \\ 0 & i \ne j \end{cases}$, $\lambda_i > 0$, and at least one $\alpha_i \ne 0$ since $u \ne 0$.
The other requirements are also always satisfied. The only one that's tricky is the triangle inequality, but note that if $A$ is positive semidefinite (including if it's positive definite), there is some $R$ such that $A = R^T R$. But then $(x - y)^T R^T R (x - y) = (R x - R y)^T (R x - R y)$, so $d$ is the Euclidean distance between the points $R x$ and $R y$ – thus the triangle inequality holds.
This also gives some insight on the difference between psd and pd matrices $A$. If $A$ is pd, then any valid $R$ above is of full rank, and the points $R x$ are in an $n$ dimensional space; $d$, which is the Euclidean metric in that space, is thus a valid metric. If $A$ is psd with $m < n$ nonzero eigenvalues, then $R$ is of rank $m$, and so necessarily some distinct points in $\mathbb R^n$ are mapped to the same point in the $m$-dimensional range of $R$: there are some $x$ and $y$ such that $R x = R y$. But then $d(x, y) = 0$, making it not a valid metric. All the other properties hold, though, so that $d$ is then a pseudometric.


text:
Q: copy spreadsheet to a specific folder and remove viewers from the copy I'm trying to make a copy of the active spreadsheet to a specific folder, then remove all editors from the copied spreadsheet and keep myself as Owner.
Here is my code :
//Save Spreadsheet in selected folder

function freezeSS(vname,option) {

if (vname != ""){

var mainSs =           SpreadsheetApp.getActiveSpreadsheet();
var SSID =             mainSs.getId();
var CopyDate =         Utilities.formatDate(new Date(), "GMT-3", "dd/MM/yy-HH:mm"); // Function Date + Format
var file =             DriveApp.getFileById(SSID);

if (option == "Public") {
    var folder = DriveApp.getFolderById("0B_EpGZ420rEUfk1mZ2Z3RmFKUk9xaGd1bm1CdGhmZ0FCbTdVT2p2MUlJY3NZUTV0MTR0LTQ");
    file.makeCopy(vname + "_" + CopyDate, folder);
}

else {

    var folder =       DriveApp.getFolderById("0B_EpGZ420rEUfk9jTl81NXNVOXNhRDF2N2R4c1FGTW9wQTB5Q3dNS25nd1NEejBTWWd1RFk");
    var backup =       file.makeCopy(vname + "_" + CopyDate, folder);
    var editors =      backup.getEditors().getEmail();
    Logger.log(editors);
    var permision =    backup.removeEditor(editors);

}
} return false;
}

Everything works but I have a problem in removing editors. I always get an error and still have the same editors as in the original spreadsheet.

A: As the documentation states, you have 2 options for removeEditor():
removeEditor(user)

or
removeEditor(emailAddress)

You're using neither, you'll need to make a loop in the getEditors() without the getEmail(), this one will also get into the loop, as so:
var editors =      backup.getEditors();
for( i in editors ){
  var email = editors[i].getEmail();
  var permision = backup.removeEditor(email);
}

or shorter:
var editors = backup.getEditors();
    for( i in editors )
      var permision = backup.removeEditor(editors[i]);

BTW, this was well documented, a ctrl+c ctrl+v from there would almost solve your problem, please take a little more time to fiddle with it.
https://developers.google.com/apps-script/reference/drive/user#getEmail();


text:
Q: Spring boot @OneToMany association saves id with null value
*

*

Hello guys i don't know why but when i tried to define an association
@one to many i get a null in the service_id and question_id.

first entity

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Inheritance(strategy = InheritanceType.JOINED)
public class Services implements Serializable{
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(nullable = false, updatable = false)
    private Long id;
    private String serviceName;
    private String description;
    private String image;

    @OneToMany(cascade = CascadeType.ALL)
    private List<Questions> questions;

Second entity

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Questions implements Serializable {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(nullable = false, updatable = false)
    private Long id;
    private String question;

    @Column(name="service_id")
    private String service_id;

    @OneToMany(cascade = CascadeType.ALL)
    private List<Answers> answers;

third entity

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Answers implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false, updatable = false)
    private Long id;
    private String answer;
    private double cost;

    @Column(name="question_id")
    private String question_id;

you can find the image for the tables bellow

enter image description here

A: All you need to do is remove the following line from Both of your models:
@Column(nullable = false, updatable = false)

After this line: @GeneratedValue(strategy = GenerationType.IDENTITY)
That will solve your problem.


text:
Q: font-not-found error: font "HoeflerText" cannot be found -- LuaLaTex error! I am running this CV/Resume example from here:
Here is a relevant fraction of the code:
\documentclass[10pt]{article}
%!TEX encoding =  UTF-16
% See geometry.pdf to learn the layout options. There are lots.
\usepackage[hmargin=1.25cm, vmargin=1.5cm]{geometry}
%symbols - the ones you see on the left of the email and of the phone
\usepackage{bbding}
\usepackage{amssymb}
\usepackage{eurosym}
%Colors/Graphics
\usepackage{color,graphicx}
\usepackage[usenames,dvipsnames]{xcolor}

%Fonts and Tweaks for XeLaTeX
\usepackage{fontspec,xltxtra,xunicode}
\defaultfontfeatures{Mapping=tex-text}
\setromanfont[Mapping=tex-text]{Hoefler Text}
...

So... when compiling with LuaLaTeX (part of MiKTeX on Windwos XP x64), I am getting the following error:
...
luaotfload | Font names database loaded: C:/Documents and Settings/Ampleforth/L
ocal Settings/Application Data/MiKTeX/2.9/luatex-cache/generic/names/otfl-names
.lua
luaotfload | Updating the font names database:
luaotfload | Scanning TEXMF and OS fonts...
luaotfload | Font names database saved: %s
: C:/Documents and Settings/Ampleforth/Local Settings/Application Data/MiKTeX/2
.9/luatex-cache/generic/names/otfl-names.lua

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! fontspec error: "font-not-found"
!
! The font "HoeflerText" cannot be found.
!
! See the fontspec documentation for further information.
! For immediate help type H <return>.
!...............................................

l.28 \setromanfont[Mapping=tex-text]{Hoefler Text}

What is wrong? How can I install this font so LuaLaTeX is picking it up? Where to download? Any other thoughts about this?

A: Hoefler Text is distributed with Mac OS X; I don't know if it can be used on a Windows system, as it is not an OpenType font. Just change the line
\setromanfont[Mapping=tex-text]{Hoefler Text}

to
\setmainfont[Ligatures=TeX]{Times New Roman}

or any other system font you have.
Notice that \setromanfont is deprecated in favor of \setmainfont, but that's not the problem. Also Mapping=tex-text is to be changed into Ligatures=TeX. because the latter form is compatible with LuaLaTeX (the former isn't).


text:
Q: ConcurrentModificationException, how to avoid? I have a JavaFX project I've been working on for a few days.  I have a database with a few tables that I, on startup of the program, obtain specific fields from and place in objects.  Countries, Customers,etc etc.  I gather all this data in my main() thread with Manager.loadData(); after connecting to my database via JDBC driver.
When attempting to modify a selected object, for instance Customers, I load a seperate fxml where I display current values of the object in textfields where I can modify them.  After modifying, I have a Save button that onAction looks like this
    @FXML
    private void onActionSaveCustomer(ActionEvent event) throws IOException {

        try{
            DBQuery.setStatement(DBConnection.getConnection());
            Statement statement = DBQuery.getStatement();

            String updateStatement = "UPDATE customers SET "
               + "Customer_Name = '" + nameTextField.getText()
                + "', Address = '" + addressTextField.getText()
                + "', Postal_Code = '" + postalTextField.getText()
                + "', Phone = '" + phoneTextField.getText()
                + "' WHERE Customer_ID = '" + customerTextField.getText() + "'";

            statement.execute(updateStatement);
        } catch(SQLException e) {
            System.out.println(e);
        }

        stage = (Stage)((Button)event.getSource()).getScene().getWindow();
        scene = FXMLLoader.load(getClass().getResource("/view/SchedulingHome.fxml"));
        stage.setScene(new Scene(scene));
        stage.show();

    }

The UPDATE SQL statement works just fine, no worries there.   When switching over to /view/SchedulingHome.fxml, I just can't seem to figure out how to/where to run my reloadData() method that will delete all instances of my object and then redownload them from my database WITHOUT incurring a ConcurrentModificationException
private void reloadData() throws SQLException {
        Manager.deleteData();
        Manager.loadData();
    }

My error occurs right on Manager.deleteData() as I attempt to call reloadData() in my SchedulingHomeController initialize() where I am at the same time iterating over my objects and filling a tableview with attributes from these objects.  I'm just not sure where I can delete my data where I'm not also iterating over it?  I iterate over it in my modify screen and I iterate over it on my next screen.  Is there some sort of limbo async area I can run reloadData() where I'm not iterating over the objects it's trying to delete?


text:
Q: Muliple Websphere Application Servers attached to a single Websphere MQ Failing Issue:
Having multiple consumer applications active specification attached to a single MQ on distributed VM servers is causing a null payload in a MQ Message.
Note: See notes at the bottom. No issue with mq.
Details:
I have 3 Websphere applications deployed across 2 VM servers. 1 application is a publisher and the other 2 applications are consumers attached to a single MQ Manager, and MQ.
2 consumer applications are pulling off the messages and processing them. The consumer application on the separate server receives a null payload. I have confirmed that its seems to be an issue having multiple application server instances attached to MQ. Confirmed by deploying the publisher on server 2 with consumer 2, then consumer 1 fails.
Question:
Has anyone tried attaching multiple MDB applications deployed on separate server instances bind to one Queue Manager and one MQ?
Specifications:
Websphere 7, EJB 3.0 MDB's,Transactions turned off,Queue in a queue installed on another machine.
Goal:
Distributed computing, scaling up against large number of messages.
I'm thinking this is a configuration issue but not 100% sure where to look. I had read that you could use MQLink, but I don't see why I would need to use service bus integration.
Supporting Doucmentation:
[MQ Link][1
UPDATE: I fixed the problem and it was a related to a combination of class loader issue with a duplicate classes. See Solution Notes below I added.
EDIT HISTORY:
- Clarified specifications, clarified question and added overall goal.
- reference notes to solution.

A:
Has anyone tried attaching multiple MDB applications deployed on
  separate server instances bind to one Local MQ?

Multiple MDB applications deployed on separate servers, connecting to one Queue Manager(but different queue) is a normal scenario and we have it everywhere and all applications work fine.
But, I suspect what you are doing is: Multiple MDB applications deployed on separate servers, connecting to one Queue Manager and listening to the same queue.
In this case one message will be received by one consumer only.
You need to create separate queue for each application and create subscriptions for each for the topic being published by your publisher.

Addition:

I suspect, for load balancing the problem you may be facing is that, when your first application gets the message, it doesn't issue a commit. So, there will be an uncommited message in the queue, which may be stopping your other application from getting message from the queue. When your first application finishes its processing, it issues a commit, but then again it is ready to pick the message and hence it again issues a get.
In my architecture, we have implemented load balancing using multiple queue managers like below:
You create 3 queue managers, say GatewayQM, App1QM and App2QM.
Keep the three queue managers in the same cluster.
Create an alias queue(shared in cluster) in GatewayQM and ask your putting app to put message in the gateway queue.
Now create one local cluster queue in each of App1QM and App2QM. Read from these queues via your applications App1 and App2 respectively.
This implementation provides you better security and serves a perfect load balancer.

A: This specific problem was caused by a code issue and the combination of class loading being set to "Parent First" in the Websphere console. On one node it would work and the other nodes in a cluster would fail, I think this was caused by the "Parent First" setting.
More important, in terms of my configuration in a cluster binding multiple active specifications to a single MQ to provide distributed computing is a correct solution.
However "points" due go to "nitgeek" solution references above if you are looking for a extremely high volume solution. Its important to understand that a single MQ can have a very high depth and takes a lot to fully utilize one.  My current configuration is a good starting point for quick configuration and distributed processing using Multiple MDB's.


text:
Q: Difference b/w installing docker container using docker vs using marathon mesos When I install a docker tomcat container using docker I can see it is assigned an ip etc. However when I use  marathon/mesos to deploy and run a docker container I see is is not assigned an ip. I ran the docker inspect in both the cases and found this difference. Can someone comment why is this difference?

A: By default Mesos/Marathon use docker's Host networking mode, so that all container ports are directly exposed on the host's ports on the host IP. You can use Bridge networking mode so that the container has its own IP and you have to manually specify which container ports to forward to which host ports. See the "Bridged Networking Mode" section in https://mesosphere.github.io/marathon/docs/native-docker.html


text:
Q: url parameter of ajax for specific function i want to set url parameter of ajax to a function of class and return the value of that function but my problem it seems cant access to function and nothing returns
this is my script:
$('#send').click(function (e) { //event added
    e.preventDefault(); //prevent normal for submit
    $.ajax({
        type:'post',
        url:'localhost/shapeproject/controllers/Square/getArea',
        data:{'edge':edge},
        success:(function (response) {
            alert(response);
        })
    });
});

this is my class:
<?php
class Square extends Shape
{
    private $edge;

    function __construct()
    {
        $this->edge = $_POST['edge'];
    }

    public function getArea()
    {
        return $this->edge * $this->edge;
    }

    public function getPerimeter()
    {
        return $this->edge * 4;
    }
}

A: but you don't set any data... Add data to the jquery function;
$.ajax({
    type:'post',
    url:'localhost/shapeproject/controllers/Square/getArea',
    data: { edge: 'xyz' },
    success:(function (response) {
        alert(response);
    })
});

A: you can add a page and name it ajax_handle.php.
then link to that page in your ajax code like this
$('#send').click(function (e) { //event added
    e.preventDefault(); //prevent normal for submit
    $.ajax({
        type:'post',
        url:'ajax_handle.php',
        data:{'edge':edge, getArea: true},
        success:(function (response) {
            alert(response);
        })
    });
});

now in your ajax_handle.php you can write this code.
if(isset($_POST['getArea']) && $_POST['getArea'] == true)
{
    $obj = new Square();
    $obj->getArea();
}

A: You must have a front controller to manage this process.
For example: create a file called index.php inside shapeproject directory.
Then you can extract controller and function names from $_SERVER['REQUEST_URI'].
You may need to use some .htaccess directives like the example below:
RewriteEngine on
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ /index.php
Read more about front controllers: An Introduction to the Front Controller Pattern


text:
Q: LaunchScreen xib and displaying application version number from plist I have created a LaunchScreen in Xcode and it appears with the default application title and copyright notice. However I would like to display the version number but I would rather pull the version number from the Info.plist rather than having to modify several places whenever the version number changes. Is this possible or do I need to give up on LaunchScreens and create a SplashScreenViewController to achieve this?

A: Although it can now be a xib instead of bitmaps, the app launch screen still cannot execute any kind of application code. It's static, essentially. So it isn't possible to include a version number from a plist in your launch screen. Unless of course you manage to add some sort of build action to edit the launch screen (be it a xib or bitmaps).

A: This is how I have done it with custom build rules. The basic idea is to add a placeholder string that will be replaced during the build process with proper version. The version is then reverted to the placeholder text.

*

*Create a script file $PROJECT_DIR/Scripts/splash-version.sh with contents:

IMPORTANT: Review XIB and PLIST paths match the ones used by your project
#!/bin/bash

xib_file="$PROJECT_DIR/Base.lproj/LaunchScreen.xib" # CHECK this path
plist_file="$PROJECT_DIR/$TARGET_NAME.plist".       # CHECK this path
bundle_ver=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$plist_file")
bundle_short_ver=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "$plist_file")
str_ver="v$bundle_short_ver($bundle_ver)". # You can edit this. Beware this is used by sed as a regex
placeholder_ver="#version#"                # You can edit this

if [ "$1" == "set" ]; then
    if ! grep "$placeholder_ver" "$xib_file" >/dev/null; then
        echo "Version placeholder $placeholder_ver not found in XIB file $xib_file"
        exit 1
    fi
    sed -i -e "s/$placeholder_ver/$str_ver/" "$xib_file"
elif [ "$1" == "reset" ]; then
    sed -i -e "s/$str_ver/$placeholder_ver/" "$xib_file"
else
    echo "syntax: $0 set | reset"
    exit 1
fi

*Add execute permissions

*Add a new label in your XIB file with the text #version#. This is the placeholder string that will be replaced by the script with the proper version

*Add a "New Run Script Phase" and set the command "$PROJECT_DIR/Scripts/splash-version.sh" set

*Move it just before the "Copy Bundle Resources" phase

*Add a "New Run Script Phase" and set the command "$PROJECT_DIR/Scripts/splash-version.sh" reset

*Move it just after the "Copy Bundle Resources" phase. This steps reverts the version string back to the placeholder string.


text:
Q: How to change default markers in scatterplot Python I'm trying to add weather markers instead of basic circles in a scatterplot. More specifically, I'd like to show physical and mental changes depending on weather conditions. For this purpose, I'd like to use some weather icons (.svg files) instead of differently colored circles. However, I obtain the following error:
TypeError: unhashable type: 'Path'
Here's my code:
clear_marker = parse_path("""M 350.04,161.95
           C 350.04,161.95 391.76,120.24 391.76,120.24M 120.24,391.76
           C 120.24,391.76 161.96,350.04 161.96,350.04M 389.00,256.00
           C 389.00,256.00 448.00,256.00 448.00,256.00M 64.00,256.00
           C 64.00,256.00 123.00,256.00 123.00,256.00M 350.04,350.04
           C 350.04,350.04 391.76,391.76 391.76,391.76M 120.24,120.24
           C 120.24,120.24 161.96,161.95 161.96,161.95M 256.00,389.00
           C 256.00,389.00 256.00,447.99 256.00,447.99M 256.00,64.00
           C 256.00,64.00 256.00,123.00 256.00,123.00M 157.56,216.68M 150.90,242.12
           C 150.31,246.60 150.00,251.26 150.00,256.00
             150.00,256.01 150.00,256.02 150.00,256.02
             150.00,314.57 197.46,362.02 256.00,362.02
             314.54,362.02 362.00,314.57 362.00,256.02
             362.00,197.48 314.54,150.02 256.00,150.02
             220.35,150.02 188.80,167.63 169.59,194.62M 276.00,170.00
           C 217.46,170.00 170.01,217.46 170.01,276.00
             170.01,300.17 178.09,322.45 191.71,340.28
             209.54,353.90 231.82,361.99 255.99,361.99
             314.53,361.99 361.99,314.53 361.99,255.99
             361.99,231.83 353.90,209.55 340.29,191.72
             322.52,178.10 300.28,170.00 276.16,170.00
             276.11,170.00 276.05,170.00 276.00,170.00
             276.00,170.00 276.00,170.00 276.00,170.00 Z""")
plt.plot(x, y, 'o', marker = clear_marker)

(I only tried on the first marker to see if it worked)
THANKS.


text:
Q: Is there a way to filter array of subdocuments in the $match stage? db.col.aggregate([
  {
    $match: {
      field_nest: { $elemMatch: { /* conditions */ } }
    }
  }
])

This is my current set up. In addition to matching the parent document, it needs to also return only the subdocument that matches the $elemMatch.
Otherwise, I would have to $unwind and $match again. But this would no long be able to use the index. The idea is to be able to use the indexes.

A: No the $match stage selects documents to pass along the pipeline, it does not modify the documents being passed along.
You can use $elemMatch in the $match stage to select the documents, and then use $filter in an $addFields stage to filter out the non-matching elements.
Perhaps something like:
db.col.aggregate([
    {$match: {
       field_nest: { $elemMatch: { /* conditions */ } }
    }},
    {$addFields: {
       field_nest: {$filter:{
          input: "$field_nest",
          as: "item",
          cond: { /* conditions */ }
       }}
    }}
])

This may be able to use an index, depending on the exact conditions and available indexes.
For example, if the query were
db.col.aggregate([
  {$match: {
    field_nest:{$elemMatch:{a:1,b:2}}
  }}
])

It could use an  index on {"field_nest.a":1,"field_nest.b":1}, but it could not use an index on {field_nest:1} or {"field_next.c":1, "field_next.a":1}.
If the query were
db.col.aggregate([
  {$match: {
    top_field: "name",
    some_value: {$gte: "never"},
    field_nest:{$elemMatch:{a:1,b:2}}
  }}
])

the query executor would look at all of the available indexes, but may use an index that does not include the array field.
If the query were
  {$match: {
    top_field: "name",
    some_value: {$gte: "never"},
    field_nest:{$elemMatch:{a:{$regex:"unanchored"},b:2}}
  }}
])

it would not be able to use an index for selecting field_nest.a, but might be able to use one for field_nest.b.
The determination of whether or not an index will be used depends greatly on the exact nature of the match conditions and available indexes.


text:
Q: Azure Storage blob using custom domain is not resolving while subdomain worked - how to set up host records? Yesterday I had successfully setup a custom subdomain in Azure storage.
I had set up assets.iprobesolutions.com to point to iprobesolutions.blob.core.windows.net. This is a screenshot of my host records CNAME set up: https://www.dropbox.com/s/ndfmn5dd7m48aqg/Screenshot%202016-05-30%2019.36.11.png?dl=0. As I said, this was working fine.
Today I decided instead to have iprobesolutions.com point to iprobesolutions.blob.core.windows.net and got as far as Azure accepting the domain using the indirect CNAME validation.
However while http://iprobesolutions.blob.core.windows.net/docs/installation-note-en-us-bosch-dicentis-wireless-installation-set-up.pdf is resolving, when I try the following it does not resolve http://iprobesolutions.com/docs/installation-note-en-us-bosch-dicentis-wireless-installation-set-up.pdf and I get error "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable".
These are my host record setups for iprobesolutions.com: https://www.dropbox.com/s/xqw2d9k3gj6mnjs/Screenshot%202016-05-30%2021.30.22.png?dl=0
I've tried many combinations for a few hours and can't get it to work....
Does anyone have an idea what I'm missing ? iprobesolutions.com is hosted in azure app service. Can't I use the same domain for both hosting and blob storage ?

A: You can't map a domain to both a web app (running in the app service) and storage. Also, you can't CNAME the root domain (so you can't map iprobesolutions.com to blob storage).
You should be able to map www.iprobesolutions.com to blob storage, though. But realize if you do this, anybody who types in www.iprobesolutions.com will not be taken to your web app, which is the expected behavior. You might want to reconsider that course of action, and use storage.iprobesolutions.com or something like that instead.

A: I believe your problem is that you must include the subdomain in the CNAME record.
From https://azure.microsoft.com/en-us/documentation/articles/storage-custom-domain-name/:

A CNAME record is a DNS feature that maps a source domain to a
  destination domain. In this case, the source domain is your custom
  domain and subdomain--note that the subdomain is always required.

Can you try your second mapping with a subdomain and see if that works?


text:
Q: My program skips a bunch of code when I include multiple arrays inside the structure I am trying to learn structures in C++. When I run my code like this:
#include<iostream>
using namespace std;

struct person{
    char firstName[50];
    int age;
    float gradYear;
};
int main(){
    person p1;

    cout << "Whats your FIRST name?";
    cin.get(p1.firstName, 50);
    cout << "Whats your AGE?";
    cin >> p1.age;
    cout << "Whats your GRADUATION YEAR?";
    cin >> p1.gradYear;

    cout << "Displaying Your Information . . . " << endl;
    cout << "First Name: " << p1.firstName << endl;
    cout << "Age: " << p1.age << endl;
    cout << "Graduation Year: " << p1.age << endl;

    return 0;
}

the code works as I want it to, but when I run the code like this:
#include<iostream>
using namespace std;

struct person{
    char firstName[50];
    char lastName[50];
    int age;
    char branch[50];
    float gradYear;
};
int main(){
    person p1;

    cout << "Whats your FIRST name?";
    cin.get(p1.firstName, 50);
    cout << "Whats your LAST name?";
    cin.get(p1.lastName, 50);
    cout << "Whats your AGE?";
    cin >> p1.age;
    cout << "Are you Corps or Civilian?";
    cin >> p1.branch;
    cout << "Whats your GRADUATION YEAR?";
    cin >> p1.gradYear;

    cout << "Displaying Your Information . . . " << endl;
    cout << "First Name: " << p1.firstName << endl;
    cout << "Last Name: " << p1.lastName << endl;
    cout << "Age: " << p1.age << endl;
    cout << "Branch: " << p1.branch << endl;
    cout << "Graduation Year: " << p1.age << endl;

    return 0;
}

the code outputs the information after I enter the FIRST name. Why does it do this, and how can I get it to work the second way?

A: This happens because cin.get() method inputs the first name and when you press enter the enter gets inputted into all other inputs. this is an unexpected behaviour ...
you can overcome this by writing getch() between the inputs.
By that I mean..
    cout << "Whats your FIRST name?";
cin.get(p1.firstName, 50);
    getch();
    cout << "Whats your LAST name?";
cin.get(p1.lastName, 50);
    getch();
    cout << "Whats your AGE?";
    cin >> p1.age;
    getch();
    cout << "Are you Corps or Civilian?";
    cin >> p1.branch;
    getch();
    cout << "Whats your GRADUATION YEAR?";
    cin >> p1.gradYear;
    getch();


text:
Q: What's the license for OS X generic icons? Can anyone link me to a document or otherwise provide information about what the license is for the generic icons included in OS X (Lion)? I tried searching at developer.apple.com but nothing relevant came up.
To be specific, I'm wondering about GenericFolderIcon.icns. If I copy it and customize the look, would distribution be restricted somehow?

A: IANAL but I would guess that all the graphical assets in OS X are copyright Apple just like everything else in the OS.
Any assets that you are entitled to use are listed on the developer sites for which typically a licence must be signed.


text:
Q: CSS Fluid/Static Layout I have the following 2 column div layout. The left column needs to have a width of 75px to accommodate the image, but the right column needs should flow into all of its parent container.
This grid is in a user control that is being added to multiple sites/pages, each having a different layout so the parent container varies in width - some can be wider, some can be skinnier, hence I can't use %.  If the % is too high it wraps.  How can I make this flexible without going for the obvious table option?
<telerik:RadGrid
        ID="ArticlesGrid"
        AlternatingItemStyle-BorderStyle="None"
        AlternatingItemStyle-BackColor="Transparent"
        BorderStyle="None"
        PageSize="20"
        runat="server"
        AllowPaging="True"
        GridLines="None"
        >
        <PagerStyle Mode="NumericPages" BackColor="#FFFFFF" AlwaysVisible="false"  ShowPagerText="false" EnableSEOPaging="True"></PagerStyle>
        <MasterTableView AutoGenerateColumns="False" DataKeyNames="Id">

            <HeaderStyle BackColor="#FFFFFF" BorderStyle="None"  />
            <Columns>
                <telerik:GridTemplateColumn>
                    <ItemTemplate>

                                <img runat="server" src='<%# Eval("ThumbnailImagePath")%>'  class="ArticleImage"
                                    alt='<%# Eval("ImageAltText")%>' id="imgArticle" />

                                <asp:HyperLink CssClass="ArticleTitle" ID="lnkHeadline" runat="server" Text='<%# Eval("Headline")%>'></asp:HyperLink>

                            <asp:Label ID="litContent" CssClass="ArticleBody" Text='<%# Eval("PreviewText")%>'
                                runat="server"></asp:Label>

                                <%# Eval("LinkText")%>

                                    Posted
                                        on
                                        <asp:Label ID="lblDatePosted" runat="server" Text='<%# String.Format("{0:MMMM dd yyyy}", Eval("PublicationUTC")) %>'></asp:Label>

                                <asp:Panel ID="pnlCommentsDisabled" Visible="true" runat="server">
                                    Comments Disabled
                                </asp:Panel>

                    </ItemTemplate>

                </telerik:GridTemplateColumn>
            </Columns>
        </MasterTableView>
        <ClientSettings EnableAlternatingItems="false"></ClientSettings>
    </telerik:RadGrid>

A: without providing a ready-to-use solution, I'd like to give you some hints. Usually this problem is solved using a floating Pattern. The trick is to use fixed padding Values for the fixed column (like 75px) and no width at all for the main column, which will use up the existing space.
This quite old and pretty good article from some css pioneers explains how it is done:
http://www.alistapart.com/articles/holygrail
Here is a quick extracted snipped (you'll need to read the article above, though, to be able to use it, i guess)
#container .column {
  position: relative;
  float: left;
}
#center {
  padding: 10px 20px;    /* CC padding */
  width: 100%;
}
#left {
  width: 180px;          /* LC width */
  padding: 0 10px;       /* LC padding */
  right: 240px;          /* LC fullwidth + CC padding */
  margin-left: -100%;
}

This should help you solving your Problem yourself :)
Best regards,
UPDATE: Yes i see that the example will provide a solution for a three-column layout, while only a two-column solution is needed. In fact, a two-column solution is even much easier to achieve. You'll have to work on it a bit, though.


text:
Q: Gitlab can't start postgresql, redis and sidekiq after upgrade from 7.11 to 8.0 I updated from Gitlab 7.11 to 8.0. Due to lack of space on the root partition, I uninstalled Gitlab 7 via
sudo gitlab-ctl uninstall

and installed 8 via
sudo apt-get install gitlab-ce

I had a few other problems that I found solutions for online and have finally managed to get 8 up and running. I have confirmed the data is still there. The problem is I can't start the postgresql, redis and sidekiq services via gitlab-ctl:
administrator@development:/var/opt/gitlab$ sudo gitlab-ctl restart
ok: run: gitlab-git-http-server: (pid 15873) 1s
ok: run: logrotate: (pid 15879) 0s
ok: run: nginx: (pid 15972) 0s
timeout: run: postgresql: (pid 2191) 7089s
timeout: run: redis: (pid 21277) 52584s, got TERM
timeout: run: sidekiq: (pid 5200) 1882s, got TERM
ok: run: unicorn: (pid 16308) 0s

I can however start postgresql via:
sudo su - gitlab-psql -c \
  '/opt/gitlab/embedded/bin/postgres -D /var/opt/gitlab/postgresql/data/'

and redis via:
sudo su -s '/bin/sh' -c \
  '/opt/gitlab/embedded/bin/redis-server /var/opt/gitlab/redis/redis.conf' gitlab-redis

The server is running Ubuntu 14.04. How can I get Gitlab to start/stop postgresql, redis and sidekiq?

A: Your problems are most likely occuring because of the runsvdir service failing using:
ps auxw

The errors or warnings will be pretty blatent, in my case:
runsvdir -P /opt/gitlab/service log: ar/log/gitlab/sidekiq: file does not exist svlogd: pausing: unable to rename c
Ensure your machine has enough space using:
df /

Delete files which maybe taking up space. e.g. Logs, backups, etc... in my case I had 25GB of backups and only a 30GB drive. My / was 100% in use and not allowing my logs to rotate.
Stop gitlab using:
gitlab-ctl stop

Manually kill any left over processes. Use ps auxw to identify the left over processes and kill -9 them.
Restart gitlab using:
gitlab-ctl start

A: I had a very similar issue where i saw errors like

file "current" could not be renamed

finally resolved by killing all the runsv and svlogd processes, then gitlab-ctl restart
root cause for me was the following change:

gitlab-ctl stop && mv /var/log/gitlab{,_BAK} && mount /dev/gitlab-vg/logs-lv /var/log/gitlab && gitlab-ctl start

... effectively replacing path "/var/log/gitlab/" with a mounted volume
so, changing the pointers out from under Gitlab, more specifically runit, did cause that process manager to fail restarting services like sidekiq, workhorse, nginx, etc.  Restarting with gitlab-ctl restart did not resolve it, since runsv,svlogd apparently are not also restarted (restart of the entire system, however, would have fixed this).
I should also say that this issue did not manifest itself until the day after change to /var/log/gitlab/. As i understand it, not until then did svlogd yet try to move/rename the log files (eg: /var/log/gitlab/gitlab-workhorse/current).  I should've noticed this, since the "new" log files in the mounted path were not written to immediately after replacement.
One might encounter the same issue from simply implementing logrotate (anything affecting those file pointers outside svlogd/runit) -- even if you restart gitlab-omnibus.

A: In that situation can help you
systemctl stop gitlab-runsvdir && systemctl start gitlab-runsvdir

A: After a couple of hours of trying and new issues popping up, I ended up downgrading to 7.11 and upgrading to 7.12, 7.13, 7.14 and eventually 8.0 in individual steps. No issues after the upgrade.


text:
Q: Как сделать сайт мультиязычным через php + Mysql? Как сделать сайт мультиязычным через php + Mysqli? Контент слова хранится в БД, как сделать?
ПОСМОТРИТЕ ЗДЕСЬ:

"My <?php echo lang('id слова'); ?>" если я поставлю id 1 "My home" вот так можно? Мне все нужно от и до, я новичок, помогите программисты!

A: Для локализации лучше использовать готовые инструменты, например, gettext.
Но судя по прошлому вопросу вам бы сначала с основами разобраться, а уже потом локализацией заниматься.
Если надо делать срочно, то почитайте что-нить типа "PHP за 21 день" - познакомитесь с основами, двигаться дальше будет уже легче.
А про локализацию через базу можно здесь в вопросах поискать, не так давно их было несколько штук.


text:
Q: Saving a Sharp Promise to a variable returns pending I'm trying to resize an image from a base64 encoded string. I can do this using c in nodejs. Sharp works with Promises, so I know I have to do async methods. After resizing, I need to convert it back to a base64 string. I usually do this by converting an image to a buffer, using the nodejs Buffer, then use the 'toString() method to convert it back to base64.
This is what my code looks like:
async function resizer(base64, width = 224, height = 224) {
  if (!base64) {
    throw console.error("not a base64 string")
  } else {
    const Buffer = require("buffer").Buffer
    let base64buffer = Buffer.from(base64, "base64")
    const image = await sharp(base64buffer)
      .resize({
        width: width,
        height: height,
        fit: sharp.fit.cover,
      })
      .rotate(90)
      .toBuffer()

    const newBase64 = image.toString("base64")

    return newBase64
  }
}
const resizedBase64 = resizer(base64Image).then((result) => {
  console.log(result)
  return result
})
console.log(resizedBase64)

The function takes a base64 string as an argument. It then gets converted to a buffer and I let sharp do it's thing.I then return the the newly generated string. When I store it as a variable, however, it returns a Promise {pending}. When I just console.log inside the .then() callback, it does log the new base64 string.
Anyone know how to fix this? I need to use the new base64 later in the code.
Thank you in advance!

A: You simply need to add an await to get the resolved value from the promise:
const resizedBase64 = await resizer(base64Image);

EDIT: What's important to understand here is that your resizer function contains some asynchronous code (from the Sharp library) which returns a promise. As such, your function will also always return a promise of the value, not the value itself, even if you use await inside it. The caller of your function will receive the promise and will have to await it to get its actual value.
When calling your function resizer, if you are not in an async context and cannot use await there are a couple of solutions available.
Solution 1: use an IIFE
(async() => {
  const resizedBase64 = await resizer(base64Image);
  console.log(resizedBase64);
  // the rest of your code goes here
})();

Solution2: declare an async function (basically the same as previous)
async main() => {
  const resizedBase64 = await resizer(base64Image);
  console.log(resizedBase64);
  // the rest of your code goes here
});

main();

Solution 3: place your code inside the then callback
resizer(base64Image).then((resizedBase64) => {
  console.log(resizedBase64);
  // the rest of your code goes here
});


text:
Q: Change directory problem in ksh I work with Ubuntu 18.04.3
My current directory is /home/hans/bin, The directory /home/hans/.sshz also exist. My shell is "ksh."
The command cd ../.ssh give the output.
ksh cd: /home/hans/ssh:[No such file or directory]

In this command, the . before ssh  disappeared. This problem doesn't occur in the sh and bash shells. This problem also doesn't happen in the "ksh" shell on Centos.
Is this a bug in the ksh shell on Ubuntu?


text: Q: Pronunciation of FEIN as acronym in US According to Wikipedia, FEIN is an abbreviation for Federal Employer Identification Number in the US. Cursory googling shows me that as a name, it could be pronounced fine or like faint, and in german, it should be pronounced fine; however, this doesn't give me a definite answer to whether there is a correct way to pronounce the acronym. I work for an insurance company, and although I've heard both pronunciations from time to time, that doesn't satisfy my curiosity.


text:
Q: arcgis silverlight - how to delete/cut a part of a multipart polygon Say I cloned a single-part lake polygon that had a hole for an island. Then I used the Editor Reshape command to cut a piece off. That incidentally caused a second part to be created where the island was, as seen here.

Now I want to get rid of that bogus island.
I've tried drawing a circle around it with the Cut command, tried the Reshape command again, no joy.
Help a dummy out?
(yeah I know my links are to ArcGIS Desktop editing tools, the better descriptions of the apparently more or less equivalent Silverlight API Editor commands)  ;-)


text:
Q: Close a popup window that has been redirected I'm having an issue getting a popup window to close on my page using JavaScript
I've been able to get other popup windows to close, but I think I'm losing something when I end up redirecting the popup window. For example, on the main window I select a project and the popup appears giving the information. Next I click on edit which does a response redirect to the edit page. Here I do my changes and hit submit. Upon submission I want it to close but I can't seem to get it to do that.
For previous popups I would use
ClientScript.RegisterStartupScript(this.GetType(), "CLOSE", "CloseAndRefresh();", true);

To call the javascript I have sitting in my .aspx file. Which is this:
function CloseAndRefresh() {
    parent.location.reload(true);
    parent.ClosePopup();
}

I generated the popup window with the following code:
editButton.OnClientClick = (popupWindow.GetTargetPopupCode("MYURL"));

This however isn't working anymore. I think that due to my redirection of the original popup window it's throwing everything off. Any idea what I need to fix?
Edit:
I've finally got to the point that the javascript is actually getting called.
I've tried these functions and none have worked:
window.close();
self.close();
parent.ClosePopUp();

ww = window.open(window.location, "_self");
ww.close();

Thanks!

A: Okay, you might be doing things to closely together. Adding a timeout might help. This is code that I use to refresh the parent and close a popup. Adapt this, and see if it helps:
refreshParent = function(){
    window.opener.reload();
    setTimeout(function(){ self.focus(); self.close(); }, 2000);
}

Try using this:
EDIT: Removed true parameter from location.reload method, per W3 specification:
function CloseAndRefresh() {
    parent.location.reload();
    self.close();
    return true;
}

See: http://www.w3schools.com/jsref/met_loc_reload.asp
EDIT: Instead of adding it as a startup script, try just adding it to the ClientOnClick of the submit button, like this:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return CloseAndRefresh();" OnClick="..." />


text:
Q: Never is not provided to BlocBuilder. Context used for Bloc retrieval must be a descendant of BlocProvider I tried to make a social media app and when setup my layout contains bottom Nav bar and screens also my cubit is ok and the code in the main is ok I tried to change bottom Nav to Text and the problem solved I had a problem with getting Bloc from child widget and I have no idea what I'm doing wrong.
how can I got this error any one can help ?
class SocialLayout extends StatelessWidget {
 @override
  Widget build(BuildContext context) {
     return BlocConsumer<SocialCubit , SocialStates>
        (listener: (context,state){},
        builder: (context,state)
        {
          var cubit= SocialCubit.get(context);

          return  Scaffold(
            appBar: AppBar(
              title:   Text('News Feed',),
            ),
            body: cubit.screens[cubit.currentIndex],
            bottomNavigationBar: BottomNavigationBar(
              currentIndex: cubit.currentIndex,
              onTap: (index){
                cubit.changeBottomNav(index);

              },
              items:   [
                BottomNavigationBarItem(icon: Icon(IconBroken.Home,),label: "Home"),
            BottomNavigationBarItem(icon: Icon(IconBroken.Chat,),label: "Chats"),
              BottomNavigationBarItem(icon: Icon(IconBroken.Setting,),label: "Settings"),
        BottomNavigationBarItem(icon: Icon(IconBroken.User,),label: "Users"),

              ],
            ),
          );
    }
    );
}
}
//cubit
class SocialCubit extends Cubit<SocialStates> {
  SocialCubit() : super(SocialInitialState());
static SocialCubit get(context) => BlocProvider.of(context);
 SocialUserModel ? socialUserModel;
void getUserData() {
   uId = CacheHelper.getData(key: 'uId');
    emit(SocialGetUserLoadingState());
    FirebaseFirestore.instance.collection('users').doc(uId).get().then((value) {
      socialUserModel = SocialUserModel.fromJson(value.data());
      print(socialUserModel.toString());

      emit(SocialGetUserSuccessState());
    })
        .catchError((error) {
          print(error.toString());
          emit(SocialGetUserErrorState(error.toString()));
    });
  }
 int currentIndex =0;
 List<Widget>screens =[
    Feeds(),
    Chats(),
    Users(),
    Setting(),
 ];
 void changeBottomNav(int index)
 {
   currentIndex = index;
   emit(SocialChangeBottomNav());
 }
}
//main
void main() async
  SimpleBlocObserver();
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  DioHelper.init();
  await CacheHelper.init();

  bool ? isDarkMode = CacheHelper.getData(key: 'isDarkMode');

  Widget widget;

  uId = CacheHelper.getData(key: 'uId');

if(uId != null)
  {
    widget = SocialLayout();
  }
else{
  widget=SocialLoginScreen();
}
  runApp(MyApp(isDarkMode, widget ,token ));
}

// ignore: must_be_immutable
class MyApp extends StatelessWidget {

    bool ? isDarkMode;
    late final Widget startWidget;
    String? token;

  MyApp(this.isDarkMode,this.startWidget, String? token, {Key? key}) : super(key: key) ;

  @override
  Widget build(BuildContext context) {

    return MultiBlocProvider(
      providers: [

        BlocProvider( create: (BuildContext context)  => AppCubit()..changeAppMode(fromShared: isDarkMode,),

        ),

        BlocProvider( create: (BuildContext context)  => SocialCubit()..getUserData(),
        ),

    ],
      child: BlocConsumer<AppCubit, AppStates>(
        listener: (context, state){},
        builder: (context ,state){
          return MaterialApp(
                debugShowCheckedModeBanner: false,
                themeMode:  AppCubit.get(context).isDarkMode ? ThemeMode.light: ThemeMode.dark,
            home: AnimatedSplashScreen(
              splash: SplashScreen(),
              nextScreen: startWidget,
              splashIconSize: 700,

              animationDuration: const Duration(milliseconds: 2000),
              splashTransition: SplashTransition.fadeTransition,
            ),
            theme: MyTheme.lightTheme,
            darkTheme: MyTheme.darkTheme,
                 builder: BotToastInit(),
                 navigatorObservers: [BotToastNavigatorObserver()],

              );
            },

      ),
    );
  }
}

*Invalid argument(s): Never is not provided to BlocBuilder<SocialCubit, SocialStates>. Context used for Bloc retrieval must be a descendant of BlocProvider.

A: Solved by remove unused bloc packages from pubsbec.yaml file


text:
Q: Android - can I fill the inside of an existing bitmap? I have a Bitmap that is the outline of a green curved shape on a while background, and a Canvas derived from the Bitmap.  Is there a "fast" way to fill the inside of the diamond with a particular color in code?
I tried going through each Y-value one by one, and for each Y, find the smallest X where the color is not white, then finding the smallest X > that value where it is white (i.e. the inside left edge), then doing the same thing from the right side (to find the inside right edge), then setting the pixels between the two X-values, but for a 640 x 320 bitmap, that's 204,800 separate operations.
There is also no easy way to express the shape in terms of a Path.


text:
Q: PostgreSQL: A function to add parent & child records I am writing a function to add a parent record and children records.
As far as I am aware, I should create appropriate data types, which I have simplified.
create type parenttype as (
    data varchar            --  data
);

create type childtype as (
    parent integer,         -- foreign key
    details varchar         --  data
);

This is a simplified version, omitting a number fields which add nothing to the question. However, they both also omit the primary key which will be generated.
I think the function would take the following form:
function adddata(parentdata parenttype, childdata childtype[])
--  etc
--  LANGUAGE plpgsql

I think I know what to do what to do with the data inside once it gets there.
The question is, how do I set the data before when I call the function? That is, how do I set values for the the parenttype and the array of childtype?
I have asked asked a related question for MS SQL Server, but I know that this requires a different approach.

A: Depends from what you call that function and where does this data come from.
Example 1
SELECT * FROM adddata(
      row('somedata')::parenttype,
      array[row(1::integer,'somedata'), row(2::integer,'somedata22')]::childtype[]
);

Example 2
SELECT adddata(
         row(parent.column)::parenttype,
         array_agg(row(child.parent_id,child.column)::childtype)
       )
FROM parent
JOIN child ON child.parent_id = parent.id
GROUP BY parent.column;


text:
Q: Prevent multiple user enter by same username at the same time? symfony 1.4 How to prevent multiple users enter by same username at same time? Example: When username is using by me and other guys try to enter with my username at same time it should display error like "Your username is already in use".
I tried saving username in DB that user using it already. But leaving account without logging off is being  problem  now.

A: You would use sfValidatorDoctrineUnique.
http://symfony.com/legacy/doc/forms/1_4/en/B-Validators#chapter_b_sub_sfvalidatordoctrineunique
You should also make your database column unique as well.

A: I would do something like this, inside the form's "configure" function :
$this->validatorSchema->setPostValidator(new sfValidatorDoctrineUnique(
                                            array('model' => 'sfGuardUser', 'column' => array('username')),
                                            array('invalid' => 'Username already in use') )
                                        );

I'm assuming here that you're using the sfGuard plugin, else you'll have to modify the model. And as @Kevin said, the column must be unique


text:
Q: Unity - saving simple data off device First off, I am developing a game for mobile, android and ios. I am currently focusing on android, hence why my main focus on data saving has been with Google Play and not Game Center.
I am not referring to a high score value, but a value that could go up or down. Like if you earn gold in a game and then spend some of the gold in the game, then you would want the latest value, not the highest.
I already have Google Play working in my game and it works fine for achievements, but the leaderboard doesn't work very well, or doesn't work for my need.  An example of this is that the leaderboard seems to be down right now.
I know I could go the route of firebase and setup an account and write info that way, but that seems like a bit of overkill for what I want to store - just one integer value per user, off device, that can be retrieved quickly and written to quickly.
I don't want to use encrypted playprefs for the obvious reasons.
I'm sure this issue has been ran into a million times before. I'm just curious how the unity community has solved this issue. I would love to get it working in some kind of Google Play Leaderboard setup, but it just doesn't seem to work consistently.


text:
Q: Error: Unable to connect to kuzzle server at 127.0.0.1:7512: Connection lost. (ws status=503) i receive lot of :
[kuzzle networkError] :  Error: Unable to connect to kuzzle server at 127.0.0.1:7512: Connection lost. (ws status=503)

since i start using apikey from createApikey, may it be related to a bad usage of the token ?
seems to happen after every successful query


text:
Q: Sort data based on key of a list of multiple dictionaries I have a list like this
li = [
    {1: {'amount': 255, 'date': '25-02-2017'}},
    {2: {'amount': 25, 'date': '2-02-2017'}},
    {3: {'amount': 38, 'date': '20-02-2017'}},
]

I am trying to sort the data in ascending and descending order based on 'amount'.
I tried the following but am unable to get the result I want:
import operator
li.sort(key=operator.itemgetter('amount'))

and
from operator import itemgetter
newlist = sorted(li, key=itemgetter('amount'))

Both raise an exception, KeyError: 'amount'.

A: You have a list of dictionaries with a single key, whose value is another dictionary. It is that nested dictionary that has the key 'amount'.
You'd have to reach in and get that single value:
newlist = sorted(li, key=lambda d: d.values()[0]['amount'])

This only works in Python 2, where d.values() is a list. In Python 3 you'd have to use next(iter(d.values())['amount'] instead.
You'd be much better of not producing the nested structure at all. Move those numbered keys into another key-value pair perhaps:
li = [
    {'id': 1', amount': 255, 'date': '25-02-2017'},
    {'id': 2, 'amount': 25, 'date': '2-02-2017'},
    {'id': 3, 'amount': 38, 'date': '20-02-2017'},
]

at which point your original attempt would work. You can transform your current data structure with [dict(id=d.keys()[0], **d.values()[0]) for d in li] but it'd be better to fix the code that produced the list.

A: Try the following code which uses lambdas,
li=[{1:{'amount':255,'date':'25-02-2017'}},{2:{'amount':25,'date':'2-02-2017'}},{3:{'amount':38,'date':'20-02-2017'}}]
print(li)

li.sort(key=lambda x:list(x.values())[0]['amount']) # ascending
print(li)

li.sort(key=lambda x:list(x.values())[0]['amount'],reverse=True) # descending
print(li)


text:
Q: Vanishing torsion condition preserved when doing a connexion transformation I have a simple question but I can't wrap my head around it.
First let's consider a Riemannian manifold with a metric $g$ with an affin Connection $ \Gamma $
If we want to construct a Levi-Civita Connexion we surely need to impose

*

*A metricity condition $\nabla g=0$
This gives us a way (let's say) to decompose the connection into two parts one symmetric depending on the metric and a second part antisymmetric depending on something we call torsion.

*The second condition is the vanishing torsion $T=0$. The purpose of it is well known and trivial.

My question is on the second condition: if we want to impose it locally on a point, the connection would change to Christoffel symbols. But how do we know that this condition is preserved in all the manifold?
My guess to the answer is in the fact that a connection is decomposable, as I mentioned earlier, into two parts this makes the two parts transform independently from each other. So if the first part (the symmetric part) transform non covariantly the second part transform tensorially, to ensure the fact that a connection transforms non covariantly. And because the torsion is tensorial we can say that the condition is preserved. I still feel that my reasoning is a little bit wrong. Tell me what you think.
EDIT:
Let's consider an affine connection $\Gamma$ in a (pseudo)-Riemannian manifold M of dimension 4 and a point $x\in M$ in a neighbourhood $U \subset M$ and finally a chart.
These considerations will associate to each point a connection $\Gamma$ that will transport vectors of tangent spaces from one point to another neighbourhood $V$.
If we impose the metricity condition on $x$ we will,  as I said, decompose the connection into
$$\Gamma^\mu_{\ \nu\rho}= \widetilde{\Gamma}^\mu_{\ \nu\rho}(g, \partial g)+ K^\mu_{\ \nu\rho}(T)$$
Where $\widetilde{\Gamma}^\mu_{\ \nu\rho}$ are the Christoffel symbols and $K^\mu_{\ \nu\rho}(T)$ is what we call contortion.
So if we impose a torsion-free condition on $x$ and transport a vector from $x$ to $y \in V$. we need to be sure that the condition $T=0$ is still verified. Hence doing a transformation on the equation $T=0$ and noticing that it's tensorial will ensure that it's verfied everywhere in the manifold. And besides that, a transformation on the Christoffel symbols does not generate a part with torsion because first, they depend on $g$ and second the inhomogeneous part of the transformation is symmetric.


text:
Q: invalid character error while executing immediate BEGIN
    exception
         when others then
    sqltext2:='insert into ERROR_TABLE_SHREE select '||str||' from dual;';
    EXECUTE IMMEDIATE sqltext2;
    end;
    COMMIT;

I am getting the below error within Exception block
ORA-00911: invalid character

A: You don't have a string there (I assume str is declared as a character of some description). If you wanted to insert a string you need extra quotes otherwise it'll be interpreted as a column in this instance. Something like:
begin
   ...
exception
   when others then
     sqltext2 := 'insert into error_table_shree select '''||str||''' from dual';
     execute immediate sqltext2;
end;
commit;

Please note that I've removed the semi-colon from the end of your string; this is not required (and is probably the actual cause of your error).
It's also worth noting that this is a bit SQL-injectiony... you should be using bind variables rather than concatenation; this is all described in the documentation:
begin
   ...
exception
   when others then
     execute immediate 'insert into error_table_shree select :1 from dual'
                  using str;
end;
commit;

However, there's no need to use dynamic SQL in this context; you could simply insert the variable value:
begin
   ...
exception
   when others then
     insert into error_table_shree values (str);
end;
commit;

Lastly, I am slightly concerned about your COMMIT; it's unusual to commit after handling an error in this manner. Without more context it's impossible to be certain but it would be more normal for error logging to be performed in an autonomous transaction

A: You don't want a semicolon in the character string you are building and passing to EXECUTE IMMEDIATE.
sqltext2:='insert into ERROR_TABLE_SHREE select '||str||' from dual';

I'm hoping that you're not really starting your block with a WHEN OTHERS exception handler.  And I'm hoping that you have a valid reason for using dynamic SQL here since I'm not seeing one.


text:
Q: Series $\frac{x^{3n}}{(3n)!} $ find sum using differentiation Find sum of the series $$\sum_{n=1}^{\infty}\frac{x^{3n}}{\left(3n\right)!}$$ using differentiation. So far I found that $$S(x)+1=S'''(x)$$ but it does not help. Then I tried different interesting ideas  like $$S(x)+S'(x)+S''(x)=e^x-1\,.$$Maybe if I get the third equation it will allow me to construct a kind of differential equation. Then, by solving it, obtain $S(x)$.

A: Let $\omega=\exp\left(\frac{2\pi i}{3}\right)$. Then $\frac{\omega^n+\omega^{2n}+1}{3}$ equals $1$ iff $3\mid n$, hence:

$$ \sum_{n\geq 1}\frac{x^{3n}}{(3n)!} = \color{red}{-1+\frac{e^{x}+e^{\omega x}+e^{\omega^2 x}}{3}}. \tag{1}$$

A: Define $$y(x)=\sum_{k\geq0}\frac{x^{3k}}{\left(3k\right)!}.
 $$ We observe that $$\sum_{k\geq0}\frac{x^{3k}}{\left(3k\right)!}+\sum_{k\geq0}\frac{x^{3k+1}}{\left(3k+1\right)!}+\sum_{k\geq0}\frac{x^{3k+2}}{\left(3k+2\right)!}=e^{x}
 $$ so we have the second order ODE $$y''\left(x\right)+y'\left(x\right)+y\left(x\right)=e^{x}.\tag{1}
 $$ Let start to solve the characteristic polynomial $$\lambda^{2}+\lambda+1=0\Leftrightarrow\lambda_{1,2}=-\frac{1}{2}\pm i\frac{\sqrt{3}}{2}
 $$ so a solution of the homogeneous equation is $$y_{o}\left(x\right)=c_{1}e^{-x/2}\sin\left(\frac{\sqrt{3}x}{2}\right)+c_{2}e^{-x/2}\cos\left(\frac{\sqrt{3}x}{2}\right),\, c_{1},c_{2}\in\mathbb{R}.
 $$ Now we have to found a particolar solution. Since the known term is $e^{x}
 $ we know that a particular solution will be of the form $$y_{p}\left(x\right)=Ae^{x}\tag{2}
 $$ where $A\in\mathbb{R}
 $. So substituting $(2)$ in $(1)$ and equaling the coefficients, we get $$A=\frac{1}{3}
 $$ so, since $y\left(0\right)=1,\,y'\left(0\right)=0
 $ we have $$y\left(x\right)=y_{o}\left(x\right)+y_{p}\left(x\right)=\frac{2}{3}e^{-x/2}\cos\left(\frac{\sqrt{3}x}{2}\right)+\frac{e^{x}}{3}
 $$ and finally $$\sum_{k\geq1}\frac{x^{3k}}{\left(3k\right)!}=\frac{2}{3}e^{-x/2}\cos\left(\frac{\sqrt{3}x}{2}\right)+\frac{e^{x}}{3}-1.
 $$

A: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Leftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\, #2 \,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}
\color{#f00}{\sum_{n = 1}^{\infty}{x^{3n} \over \pars{3n}!}} & =
-1 + \sum_{n = 0}^{\infty}{x^{n} \over n!}\sum_{k = 0}^{\infty}\delta_{3k,n} =
-1 + \sum_{n = 0}^{\infty}{x^{n} \over n!}\sum_{k = 0}^{\infty}
\oint_{\verts{z} = a}{1 \over z^{n - 3k + 1}}\,{\dd z \over 2\pi\ic}
\quad\mbox{where}\quad 0 < a < 1
\end{align}
Then,
\begin{align}
\color{#f00}{\sum_{n = 1}^{\infty}{x^{3n} \over \pars{3n}!}} & =
-1 + \oint_{\verts{z} = a}\sum_{k = 0}^{\infty}z^{3k - 1}
\sum_{n = 0}^{\infty}{\pars{x/z}^{n} \over n!}\,{\dd z \over 2\pi\ic} =
-1 + \oint_{\verts{z} = a}
{\expo{x/z} \over z\pars{1 - z^{3}}}\,{\dd z \over 2\pi\ic}
\\[3mm] & =
-1 + \oint_{\verts{z} = 1/a}{z^{2}\expo{xz} \over z^{3} - 1}
\,{\dd z \over 2\pi\ic} =
-1 + {1 \over 3}\sum_{r}\expo{xr}\quad\mbox{where}\quad r \in \braces{1,\expo{-2\pi\ic/3},\expo{2\pi\ic/3}}
\end{align}
$r$'s are roots of $z^{3} - 1 = 0$ whith $\verts{r} = 1 < 1/a > 1$:
\begin{align}
\color{#f00}{\sum_{n = 1}^{\infty}{x^{3n} \over \pars{3n}!}} & =
-1 + {1 \over 3}\,\expo{x} + {2 \over 3}\,
\Re\pars{\exp\pars{x\bracks{-\,\half + {\root{3} \over 2}\,\ic}}}
\\[3mm] & = \color{#f00}{%
-1 + {1 \over 3}\,\expo{x} + {2 \over 3}\,
\expo{-x/2}\cos\pars{{\root{3} \over 2}\,x}}
\end{align}


text:
Q: Returning Query from PL/pgSQL I have a list of records which has employee ids for each employee (emp_id), and their manager's employee id (manager_id)
Lets say I wanted to run a query to get all columns for the entire chain of command for Sandrine (emp_id = 63679) (i.e. Sandrine, Sandrine's boss, Sandrine's boss's boss, etc.)
How would I write this query?
I tried the following loop in PL/pgSQL:
CREATE FUNCTION getpersons() RETURNS SETOF person
LANGUAGE plpgsql AS
$$ Declare
counter INTEGER := 63679 ;
Begin
WHILE (Counter is not null) loop
RETURN QUERY EXECUTE (SELECT * FROM employees WHERE employees.emp_id = Counter);
Counter = employees.manager_id;
END LOOP;
END; $$
SELECT * from person;

the db looks like this:

A: Your function has several errors.

*

*you are selecting from a table named employees, so the function should return setof employees, not "person"

*You don't store the result of the select anywhere, so you can't actually assign the "counter" variable (which is a really bad choice for a variable name)

*execute is only needed for dynamic SQL, not if you have static SQL

*you should pass the ID of the employee to start with as a parameter, rather than hard coding it.

So in order to actually use the row you retrieved you need to store it in a variable, which can be defined as the same type as the resulting table.
Putting all of that together, your function should look like this:
CREATE FUNCTION getpersons(p_startid integer)
  RETURNS SETOF employee
LANGUAGE plpgsql AS
$$ Declare
  l_id INTEGER := p_startid;
  l_row employee;
Begin
  WHILE (l_id is not null) loop
    SELECT *
      into l_row
    FROM employee
    WHERE emp_id = l_id;

    l_id := l_row.manager_id;
    return next l_row;
  END LOOP;
END;
$$
;

Then you can use it like this:
select *
from getpersons(63679);

However, it is not needed to write a function to traverse such a hierarchy. This can be done with a single SQL statement using a recursive common table expression
with recursive persons as (
  select *
  from employees
  where id = 63679
  union all
  select ch.*
  from employees ch
    join persons p on p.manager_id = ch.id
)
select *
from persons;


text:
Q: Override in RPG. I have a condition.
I have a CL where I override a table(TabA) with Qtemp version(QTEMP/TabA). Then I call a RPG program.
Now in the RPG program, I do an update to TabA. So the Qtemp version is getting updated but I wanted the actual version to be updated. So basically, just in this update, I dont want my override to work. One way is to delete the override and then , after the update, override it back. Is there a better way?

A: An alternative solution would be to simply create a LF( or Index or View ) over the table.
Add an F-spec for the logical and have your UPDATE use that LF.
Regardless of rather or not the override is in place, the actual PF will be updated.

A: The obvious solution is to leave the CL and RPG alone, and
OVRDBF TABA TOFILE(production_library/TABA)
CALL the_cl_program
This works because overrides work from the outside toward the inside.  OVRSCOPE, activation groups, and the like all add to the complexity of making this a solution to recommend in all circumstances.
Assuming that you've already reached that conclusion, the next obvious solution is to simply run the RPG program 'naked' - outside of the CLP.  I can assume that if that were doable, you'd have done it.  Maybe the CL in question is in a whole string of other CLs called by a larger process.
The next obvious solution is to change the CLP; take out the OVRDBF, run the big process, then put it back.  That works, but has the issues of having to remember to compile a production program twice, set the authorities, etc.  Before I did that, I'd consider one slightly different alteration of that CLP.  Use a switch to turn the OVRDBF on or off, depending on your needs.
It's pretty rare that a change like this needs to happen once.  Maybe there's an issue, and the big process needs to be re-run, only this one program needs to update production, not QTEMP.  Consider using the external indicators - something like if %switch(xxxxxxx1) then (OVRDBF...).  If the switches are already used, consider making a data area that you can retrieve and test.
If all of that sounds like it's too much work, there's my fall-back for re-running Big Processed that fell over.  My golden rule is to never change tested, running, production code.  Make a one-time 're-run' version.
1) Make a copy of big_process_cl.  Call it big_process_rerun or something like that.
2) Make a copy of the_clp_with_ovrdbf.  Same idea.
3) Change and compile big_process_cl_rerun to call all the things you need, but when it tries to CALL clp_with_ovrdbf, change that line to CALL clp_with_ovrdbf_rerun.
4) Change clp_with_ovrdbf to not have the OVRDBF.
5) Compile the 2 xxx_rerun CL's
6) CALL big_process_cl_rerun
This seems like a lot of work, but it's only 2 CLs, and you will have never touched/broken production code.  Again, this is great for a re-run sort of problem, but it might not fit your needs.
What is the business problem that lead to this requirement?
EDIT:
Apparently PGMA reads all of the rows in a very large file, but only needs to process a subset.  As it reads records, it updates them as well.  The idea of redirecting the input to the necessary subset is a good one, but this means the production table doesn't get its updates.  If I had these limitations (must not change PGMA) I would write one more program.  After PGMA runs and updates QTEMP/TABA, this new program would read QTEMP/TABA and propagate the changes to production.

A: It sounds, to me, like you have a single F spec in your program for TABA. If this is the case you cannot change the observed behavior without modifying the program, but your modifications can be limited in scope by creating a new logical and a subprocedure like this:
dcl-proc UpdateTABA;
  dcl-pi *n Ind;
    record       LikeRec(TABAREC:*output) const;
  end-pi;

  dcl-f tabanewlf    disk keyed usage(*update);

  chain (key) tabanewlf
  if %found(tabanewlf);
    update tabanewlf record;
    return *On;
  endif;
  return *Off;
end-proc;

Then wherever you have an update opcode, you can call this sub-procedure. Since it is using a different file name, it will be unaffected by the override.
Given that you are using SQL, you could also create an alias and update that. The alias is not affected by the override. It would look like this:
create alias qtemp/taba_alias for taba;

I just tested this in the presence of an override that overrides a file to an empty duplicate in a different library.
select * from taba;

returns an empty data set while :
select * from taba_alias;

returns a dataset with the expected data. Then just drop your alias when you are finished with it. Notice that I created the alias in QTEMP. This way multiple users can run your program without recreating or dropping the alias on each other.
So use a view if you don't mind an extra artifact out there, or an alias if you just want to create a pointer.

A: Rather than use overrides scoped at different levels, I would handle this situation by using a fully qualified file name in either your F-spec or your SQL and not use an override at all.  It sounds like the RPG program should always update the permanent file, not the temp file, so on the F-spec you can use the keyword EXTFILE(LIBNAME/FILENAME).  Similarily if you are using SQL, your can refer to the table as LIBNAME.FILENAME.
I would also use an explicit qualification in the CL program as well, referring to QTEMP/FILENAME so that you can remove the override completely.  As Barbara Morris points out, if you have an override in scope, the EXTFILE keyword will point to the overriding file, even if a library name is qualified.
Overrides have some nice features, especially for printer files, but it sounds like they are not the right fit for you. You actually have two logically separate concerns: do work to the temp file and do work on the permanent file.  They deserve separate treatment. An override is a better technique for the case when you want all references to one object be replaced with references to a different one.

A: Another option is to put RPG program in a different activation group from the CL. Although that wouldn't work if you have OVRSCOPE(*JOB) on the override.

A: Thanks all.
I fixed this issue after creating a Alias and updating it instead of the TabA in program. This worked perfectly and I did not want to create an index as well.


text:
Q: Appcelerator - CodeSign issue since adding new UDIDs to provisioning profile I recently added some new UDIDs to my AdHoc Distribution Provisioning profile. I then downloaded the updated certificate and since then I have been able to publish my iPhone app as I keep getting a 'Codesign' issue.
I've tried everything seen in many other posts on this forum including deleting and recreating my developer and production certificates and deleting and recreating my provisioning certificates (Both Developer and Ad Hoc Distribution).
I now can't even 'run' the app to my iPhone attached to the computer (which wasn't one of the new UDIDs - deployment to this phone has always worked).
I'm at a loss where to turn as

*

*Apple tells me my Provisioning Profiles are 'Active'

*Xcode shows the correct Provisioning profiles

*My Key Chain tells me I have two valid certificates (one iPhone developer, one iPhone Distribution).

*Appcelerator gives me all the ticks when I am choosing which profiles to use in the build

*I have been 'cleaning' my app and restarting Appcelerator like crazy but with no luck
I really need to get this app over to the client, but have no idea what is 'wrong' as everything matches up. Is it possible Xcode has cached old certificates? Has something got corrupted?

A: I have been through this issue in past month, the problem was exactly same as yours, everything was showing correctly.
But from your Keychain screenshot, I think there is no private key (this was my case also) attached with your certificates which is the issue of CodeSign.
If you even install the .cert file, it will still show it as a valid certificate, but you might not be able to sign your code due to missing private key.
So, make sure you get the private key added along with the certificate in your keychain. If it does not works for you then you should create new certificates from same machine you will distribute the app as it will save a lot your headaches :)

A: As is often the case - this was a very simple issue wrapped up as a complex one.
When creating a build (both under 'Run' and 'Package'), you can select which KeyChain to use. Somehow this dropdown had changed from 'System Defaults' to another one... changing this Select KeyChain drop down back to System Defaults was all I had to do!
Thanks to @prashant-saini for getting me thinking about keys and keychains!


text:
Q: MySQL Group_By with attributes as columns? I have the following output from some joins I am doing:
------------------------------------------------
      id             title              date
------------------------------------------------
       1             title1            01/01/03
       1             title3            01/01/05
       2             title2            01/01/02
       2             title3            01/01/01
       2             title1            01/01/06
       3             title1            01/01/07
       3             title2            01/01/09

Im wondering if its possible to set-up my query output so that I have a distinct id per row. This could be achieved by allowing the title attribute to be set as a column like so?
-----------------------------------------------------------
      id             title1       title2        title3
-----------------------------------------------------------
       1             01/01/03      null        01/01/05
       2             01/01/06    01/01/02      01/01/01
       3             01/01/07    01/01/09        null

I'm not sure if this is just crazy talk, but thought something could be setup by using GROUP_BY? I may be well off track here though

A: You just need basic conditional aggregation, assuming that there are exactly three titles:
select id,
       max(case when title = 'title1' then `date` end) as title1,
       max(case when title = 'title2' then `date` end) as title2,
       max(case when title = 'title3' then `date` end) as title3
from table t
group by id;

This method works only when you know the list of columns that you want in the resulting SQL.  If you have a variable number of potential columns, then you have two choices.  The first is to use group_concat() to produce something like this:
id          title1:date; title2:date . . .

The SQL for this is:
select id, group_concat(title, ':', date separator '; ')
from table t
group by id;

The other is to create the necessary SQL in a string and use prepare and exec to run it.


text:
Q: MVVM: Should a ViewModel have a member to another ViewModel? The dependent ViewModel gets injected via the constructor (IoC container).
Example: ProductSelectionViewModel uses ShoppingBasketViewModel.
Is this a common practice or is this THE recommended way? I don´t think so...
How should it be done right?
Should the view use the 2 ViewModels?
Mediator pattern?
Event driven?
Personally I don´t like the last one.

A: There's nothing wrong with a view model having a direct reference to another view model, if it is a required dependency, then injecting it via the constructor is fine.
If you wish for a view model to be able to create new instances of another view model, then injecting a view model factory type would be the way to go.


text:
Q: How to configure a user account with unknown password from an admin account on Windows 7? I have to administrate a Windows 7 computer for which I have an Admin account. The computer is in a Domain (if this is important). Now I need to configure an user account on this computer (also a domain account), so put shortcuts on the desktop etc. But I don't know the password for this account. I am not allowed to change the password on the domain server (SBS 2011), because the user needs to login remotely to his Exchange account with his password (which would not work anymore if I changed it). Asking the user for the password is no option, this would violate all my personal and the companies security guidelines.
So, how can I (with an Admin account) configure a user account on a Windows 7 computer without knowing the password for the user account?
In Linux I just be root or do sudo, but I don't know how to do similar tasks in Windows.

A: You could do one of a couple of things:

*

*Gain access to the users home (Just hit continue on You don't have permission to access this folder),  (\Users\username) and update shortcuts there, get the user to logon and hope that the PC syncs with the server.

*Update shortcuts in \Users\Public\Desktop - This will only apply locally

A: Has the user ever signed into this computer before?
If yes, then all you need to do is drop any files/shortcuts you want directly into the user's profile folder under C:\Users.  If you need to change settings for the user, you can mount their registry hive in Regedit from your account by opening the NTUSER.DAT file in their profile.  You'd need to figure out what keys correspond to what settings, but it's doable with a little work on your part.
If not, then the user does not have a cached profile on the computer for you to work with, and therefore you'll have to pull off some wizardry to make it happen.  Here are a couple ways you could do it:

*

*Use some remote control program like TeamViewer, LogMeIn, GoToMyPC, or whatever -- anything that will allow the user to connect remotely to a login screen -- and have the user sign into this computer from wherever they are.  You can then modify their profile right then and there and they still wouldn't have disclosed their password to you.  This would be my preferred suggestion.

*If the computer in question is going to be assigned to them (i.e. they will be the only person using it), then you can modify the default user profile by dropping files into folders under C:\Users\Default.  You can also make the aforementioned registry changes by mounting C:\Users\Default\NTUSER.DAT in Regedit.  The drawback to this is that it will affect every user that signs into this computer for the first time (users who have previously signed in will not be affected).

*Make the user's domain account a roaming profile.  If they sign into any computer in your organization after you make the change, Windows will sync a copy of their profile to the network.  You can then modify the server copy of their profile and it will be pulled down to any machine they sign into.  Once they've signed into this computer the first time, you can revert it back to a normal profile.  This option has some downsides though.  Actually this option is a terrible idea and you should only do it as a last resort :-)

There may be some others that I haven't thought of, but if they've never signed into this computer before then the bottom line is that you'll need to get creative.

A: You could try and use Windows Easy Transfer - this would create the user profile and copy any files from the host PC that contains the user profile you need.
This can be done over the network and the tools are installed on all Win 7 PC's


text:
Q: How can I initialize a mixin's immutable data in Dart? I am programming in Flutter using Dart 2.1.0, and come across this situation:
mixin Salt {
  final int pinches;  // Immutable, and I want to delay initialization.

  // Cannot declare constructors for mixin
}

class Meat with Salt {
  Meat(int pinches) ... // How to initialize it?
}

Salt has no constructor, so I cannot use initializer list. pinches is final, so I cannot set it in Meat's constructor.
I don't want to make Salt a class because Meat may need to extend from something else.
And I want to keep pinches immutable.
Any way to do it? Thanks in advance.

A: By design it is not possible to declare a final member into a mixin because it is not possible to declare a constructor for initializing the final member,
citing the docs:

However, in this proposal, a mixin may only be extracted from a class that has no declared constructors. This restriction avoids complications that arise due to the need to pass constructor parameters up the inheritance chain.

A compromise may be to declare a private member and implement only a getter.
_pinches is visible only inside the library, it is read-only for library users.
mixin Salt {
  int _pinches;

  get pinches => _pinches;

}

class Meat with Salt {

  Meat(int pinches)  {
   _pinches = pinches;
  }
}

Note: the above pattern, because of the visibility rules, works only if the mixin and the mixed classes reside in the same library.

A: I offer my take on a solution to this.  By marking the variable late you can make it final.  No warning will appear if you fail to initialize it so use with caution.
mixin Salt {
  late final int pinches;
}

class Vegetable with Salt {
  Vegetable(int pinches) {
    this.pinches = pinches;
  }
}

A: You can change the declaration of your mixin to:
mixin Salt {
  int get pitches;
}

And then define the field inside the implementation class
class Meat with Salt {
  final int pitches;
  Meat(this.pitches);
}

A: Similar to attdona's suggestion, but a little bit closer to what you really wanted, you could do it like
mixin Salt {
  int _pinches;
  int get pinches => _pinches;
  void initSalt(int pinches) {
    assert(_pinches == null);
    _pinches = pinches;
  }
}

class Meat with Salt {
  Meat(int pinches) {
    initSalt(pinches);
  }
}

It's still not strictly final, but (so long as the mixin's in a different library so you can't change the private member directly) it's immutable at runtime. Not as good as if it could be properly final, but maybe close enough.

A: The following method allows you to set the data at a later time, and gets rid of the warning:
This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final
mixin Salt {
  final SaltData _saltData = SaltData();

  int get pinches => _saltData.pinches;

  set pinches(int extraData) {
    _saltData.pinches = extraData;
  }
}

class SaltData {
  int pinches = 0;
}

So what I did is create a class SaltData. This will store all the variables you need.
The private _saltData variable is final, this will stop the warning.
Then use a getter and setter to retrieve and update the data.
int get pinches => _saltData.pinches;

set pinches(int extraData) {
  _saltData.pinches = extraData;
}

If you want you can could expose the entire saltData object as well:
SaltData get saltData => _saltData;


text:
Q: Looking for group of polynomials with only real roots Assume $P_\mathbb R$ is the set of all polynomials which have only real coefficients and only real roots. Define $0$ as a polynomial with infinitely many real roots and all other constant polynomials as having no roots, thus no complex roots either.
Say we want to find an operation $\star$ such that $(P_\mathbb R,\star)$ is a group.
Let's start looking with some obvious ones. If we select $\star = +,$ ie. addition of polynomials, we immediately see that $(P_\mathbb R,+)$ is not a group. Take as an example $p_1 = 1+x$ and $p_2 = x^2.$ Then clearly $p_i \in P_\mathbb R$ but $p_1+p_2 = 1+ x+ x^2$ has no real roots. However, construction $(P_\mathbb R,+)$ has an identity element $0$ and every member has an inverse, namely inverse of $p$ is $-p$. It also has associativity. Thus $(P_\mathbb R,+)$ is a groupoid.
If we select $\star = \times$, meaning multiplication of polynomials, then clearly $(P_\mathbb R,\times)$ is closed. If $p_1$ has roots $r_1, r_2 \dots r_n$ and $p_2$ has roots $R_1, R_2 \dots R_k$, then $p_1 p_2$ has roots  $r_1, r_2 \dots r_n, R_1, R_2 \dots R_k$. These obviously need not be distinct.
So multiplication seems promising. We also have an identity element, namely constant polynomial $1$. $$1\times p = p \times 1 = p.$$ Multiplication has associativity.
But finding an inverse of $p \in P_\mathbb R$ seems difficult, if not impossible. Lets say we want to invert $1+x$. We need a polynomial $p \in P_\mathbb R$ such that $(1+x)p = 1.$ Solving $p$, we get $p = \frac{1}{x+1},$ which is not a polynomial.
Or is it? We have the Taylor series of $\frac{1}{x+1}$ around $0$ given by $\sum_{k=0}^\infty (-1)^k x^k,$ and, indeed, $$(x+1)\times\sum_{k=0}^\infty (-1)^k x^k = 1$$ as long as $-1<x<1.$ But I have serious doubts that $$\sum_{k=0}^\infty (-1)^k x^k \in P_\mathbb R.$$
Looking at above, it is doubtful $(P_\mathbb R, \times)$ can be a group, no matter how the inverse is defined. If not, we get that $(P_\mathbb R, \times)$ is a monoid.
Is there any way to interpret the inverse of a polynomial in the multiplicative case, that also preserves the group structure? The answer seems to be no, as if we look at the polynomial ring over field of real numbers under multiplication and addition, the only elements with multiplicative inverses are constant polynomials with exception of $0$, which has no multiplicative inverse. As this preserves the properties of multiplication in that ring, multiplication doesn't give a group, even if $0$ is removed.
Does there exists a subring of the polynomial ring under the addition and multiplication defined in the field of real numbers, restricted to some $P^* \subset P_\mathbb R$? In other words, is there a restriction to some subset of polynomials with real coefficients and real roots such that this set forms a group under addition and a monoid under multiplication.

A: Not a complete answer, just some remarks too lengthy for a comment.
A non-zero polynomial with all real roots corresponds uniquely to a finite (possibly empty) set of real numbers (the roots) tagged with positive integers (the order of vanishing), together with a non-zero real number (the leading coefficient). That is,
$$
c\prod_{k=1}^{N} (x - a_{k})^{m_{k}} \leftrightarrow\bigl\{(a_{1}, m_{1}), \dots, (a_{N}, m_{N}), c\bigr\}.
$$
Alternatively, the data on the right may be viewed as a non-zero real number $c$ together with an "order-of-vanishing" function $m$ from the reals to the non-negative integers that is non-zero at only finitely many points. (In the notation of the preceding equation, $m(a_{k}) = m_{k}$ for $k = 1, \dots, N$, and $m(x) = 0$ for all other real $x$.)
The product operation has the pleasant interpretation of multiplying the leading coefficients and adding the order-of-vanishing functions. It should be clear why there are no inverses, however: The identity element has coefficient $c = 1$ and $m \equiv 0$, but $\times$ does not decrease the order of vanishing at any point.
If you're looking for a binary operation that "keeps the root structure somewhat intact", the data $(c, m)$ may be useful for ensuring your set is closed under your operation....


text:
Q: How to replace every comma with a new word from a file I have a log file samplelog.log
 [java] 08 May 2017 21:17:37,508  INFO FoobarTests.testSomething.95e0dc44-c51e-4b2f-a048-eba70eae6d94-60e04794-2fe8-42c6-b8a3-5ea180a20431 aaaa.aaa.test.:170 - Creating account: aaaa.aaaa.test.client.FoobarSpec@4a0e091e[name=<null>,aaaa=33,bbb=<null>,ccc=<null>,ddd=<null>,xxx=XY,eeee=eee,fff=fff,port=8200,

 [java] 08 May 2017 21:17:40,527  INFO FoobarTests.testSomething.95e0dc44-c51e-4b2f-a048-eba70eae6d94-60e04794-2fe8-42c6-b8a3-5ea180a20431 aaa.bbb.test.runner.ClientFactory:400 - Building a client for customer[123] using url-info[test.client.utils.Endpoint@78830d9a[envn=aaa,endPoint=<null>]].

I want to loop through this file colors.cfg
\033[0;31
\033[0;32
\033[0;33
\033[0;34
\033[0;35
\033[0;36
\033[0;37

and replace every comma in the log file with "a comma and a line from the color.cfg". A different line is read everytime.
I want to use this to give text a different color after every comma in the logfile.
so i get output like this in a new file.
 [java] 08 May 2017 21:17:37,508  INFO FoobarTests.testSomething.95e0dc44-c51e-4b2f-a048-eba70eae6d94-60e04794-2fe8-42c6-b8a3-5ea180a20431 aaaa.aaa.test.:170 - Creating account: aaaa.aaaa.test.client.FoobarSpec@4a0e091e[name=<null>,\033[0;31aaaa=33,\033[0;37bbb=<null>,\033[0;36ccc=<null>,\033[0;35ddd=<null>,\033[0;34xxx=XY,\033[0;33eeee=eee,\033[0;32fff=fff,\033[0;31port=8200,

A: COLORS=()
while read -r line; do
  COLORS+=("${line}")
done </path/to/colors_file/colors_file.txt

IFS=','

while read -r logLine; do
  logLineParsed=''
  clrsIndx=0

  for linePart in ${logLine}; do
    if [ "${clrsIndx}" -eq "${#COLORS[@]}" ]; then
      clrsIndx=0
    fi

    logLineParsed+="${linePart},${COLORS[${clrsIndx}]}"
    ((clrsIndx++))
  done

  printf '%s\n\n' "${logLineParsed}" >> new_log_file.txt
done </path/to/log_file/log_file.txt

Output:
[java] 08 May 2017 21:17:37,\033[0;31508  INFO FoobarTests.testSomething.95e0dc44-c51e-4b2f-a048-eba70eae6d94-60e04794-2fe8-42c6-b8a3-5ea180a20431 aaaa.aaa.test.:170 - Creating account: aaaa.aaaa.test.client.FoobarSpec@4a0e091e[name=<null>,\033[0;32aaaa=33,\033[0;33bbb=<null>,\033[0;34ccc=<null>,\033[0;35ddd=<null>,\033[0;36xxx=XY,\033[0;31eeee=eee,\033[0;32fff=fff,\033[0;33port=8200,\033[0;34

[java] 08 May 2017 21:17:40,\033[0;31527  INFO FoobarTests.testSomething.95e0dc44-c51e-4b2f-a048-eba70eae6d94-60e04794-2fe8-42c6-b8a3-5ea180a20431 aaa.bbb.test.runner.ClientFactory:400 - Building a client for customer[123] using url-info[test.client.utils.Endpoint@78830d9a[envn=aaa,\033[0;32endPoint=<null>]].,\033[0;33


text:
Q: Create new tables based on existing tables with different column names I have two tables. One is the raw table and another one is the table that I need to reference from. I am not sure how to join this two tables because the structure is different. I am trying to create two new tables based on the reference table. Below is the sample data and expected output:
#Raw table

Sbjnum
B_01
B_02
C_01
C_02

172009172
100
120
200
240

172009173
200
140
220
250

172009174
300
150
240
260

#Specnorm

tablename
fieldname
destfieldname
sequence

Screener
B_01
Area1
1

Screener
B_02
Area2
2

Product
C_01
ProductID1
3

Product
C_02
ProductID2
4

Expected output
#Screener table

Sbjnum
Area1
Area2

172009172
100
120

172009173
200
140

172009174
300
150

#Harvest table

Sbjnum
ProductID1
ProductID2

172009172
200
240

172009173
220
250

172009174
240
260

A: Try to build on this:
DROP TABLE IF EXISTS #Specnorm;

CREATE TABLE #Specnorm
(
    [tablename] SYSNAME
   ,[fieldname] SYSNAME
   ,[destfieldname] SYSNAME
   ,[sequence] BIGINT
);

INSERT INTO #Specnorm ([tablename], [fieldname], [destfieldname], [sequence])
VALUES ('Screener' ,'B_01', 'Area1' ,   1)
      ,('Screener' ,'B_02', 'Area2' ,   2)
      ,('Product'  ,'C_01', 'ProductID1',   3)
      ,('Product'  ,'C_02', 'ProductID2',   4);

DECLARE @source_data_table_name SYSNAME = '#Raw';
DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

SELECT @DynamicTSQLStatement = STRING_AGG(CAST([table_definiton] AS NVARCHAR(MAX)), ';')
FROM
(
    SELECT 'SELECT ' + STRING_AGG(CAST(QUOTENAME([fieldname]) + ' AS ' + QUOTENAME([destfieldname]) AS NVARCHAR(MAX)), ', ') WITHIN GROUP (ORDER BY [sequence]) + + ' INTO ' + MAX([tablename]) + ' FROM ' + @source_data_table_name
    FROM #Specnorm
    GROUP BY [tablename]
) DS ([table_definiton])

EXEC sp_executesql @DynamicTSQLStatement;


text: Q: The conjugate of the series in complex [power series of functions.] Let $f$ be an analytic function at $z_0(\in\Bbb C)$ . (That is $f(z) = \sum_{n=0}^{\infty}a_n(z-z_0)^n$ ). Then, as far as I've known, $\overline{f(z)} = \sum_{n=0}^\infty\overline{a_n}\cdot\overline{(z-z_0)^n}$. What if we expand this thought in the case including the $n=-\infty$ (e.g. the case for Laurent series)? When considering the $z=z_0$ as the isolated singularities, does $\overline{f(z)} = \sum_{n=-\infty}^{\infty}\overline{a_n}\cdot\overline{(z-z_0)^n}$ for $f(z) = \sum_{n=-\infty}^{\infty}a_n(z-z_0)^n$ ? Intuitively, just in my thought, it seems true, but I can't confidently say "yes".