text:
Q: 16.04 regularly fails to boot properly The computer will start, but gets stuck on a black/purple screen before reaching the login screen. It is completely unresponsive, and needs a forced restart. This happens maybe half of all boots and has been going on for a couple of months. There's no pattern I can see.
After reboot, either the computer start normally, OR ubuntu runs some sort of diagnostic, black screen white text. It says something about "Recovering journal" and then "Fixing recursive fault but reboot is needed". After rebooting again it starts up normally.
After booting successfully there are no problems whatsoever. The problem also occurs while waking up from hibernation.

*

*fsck from recovery mode, no errors.

*3 passes with memtest86, no errors.

*SMART says disk is OK.


text:
Q: Prevent the loading of subclass table rows in TPT inheritance on Entity Framework I have the following table hierarchy in my database which i map to an Entity Framework model (Database First) using the Table-Per-Type (TPT) inheritance pattern:

The mapping in the EF model is straightforward: AssetContent is a base abstract class while the other 2 are concrete subclasses.
The AssetContent table participates into a many-to-many relationship with another table which, to keep the picture clear, is omitted.
My question is, how do i build a Linq-to-Entities query to load the related AssetContent table using Include() such that the 2 'sub-tables' are not loaded at all? This is especially important for the DatabaseAssetContent table, whose BinaryContent field may be quite large and of no relevance to the issuer of the query i want to build. As far as i observed, Entity Framework automatically loads the entire hierarchy for a table, whether lazy loading is enabled or not, but i am interested in loading only the rows in the AssetContent table.
Is such a query possible using Linq-to-Entities (for Entity Framework 6)?

A: Eventually, i moved the AssetContent table's fields (except the Id) into another, new table, called AssetContentWithMetadata, which has a 1-1 relationship to the AssetContent table. This way, the AssetContent table remains indeed a bit awkward, with a single field (the ID), but now i can load the metadata table alone, without burdening it with the contents as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i Format a column like this? I was wondering is there a way rename a column like this and if so how would you do it?
COLUMN (column1 || ' ' || column2) HEADING "new_name" FORMAT a20;

SELECT (column1 || ' ' || column2)
FROM Table_name

A: Without knowing the use behind this, you could do
SELECT column AS column2 FROM wherever

A: Typically I use column alias on select statement level.
SELECT substr((column1 || ' ' || column2),1,20) as "new_name" FROM Table_name

A: Assuming you are doing this in sqlplus you need to use a column alias:
COLUMN my_col HEADING "new_name" FORMAT a20;

SELECT (column1 || ' ' || column2) as my_col
FROM Table_name


text:
Q: Creating a python formula that subtracts from each array I have created the following in excel that I am trying to replicate.
Column A show the date
Column B has a binary indicator that can take the value 1 or 0
Column H is the running total of Column B
Now the tricky part:
Column C returns the date of when the cumulative total of the indicator is 1 (value of C2), for the start date corresponding to that row.
e.g. In cell C3, the corresponding start date is 01-Jan and for that date the indicator is 1, so it returns 01-Jan.
However for cell C5, we are looking at 03-Jan onwards, and the first date the total of the indicator reaches 1 is 09-Jan, and this value is returned.
Column D returns the date of when the cumulative total of the indicator is 2 (value of D2), for the start date corresponding to that row.
e.g. In cell D3, the corresponding start date is 01-Jan and when we start on that date, the cumulative total of the indicator reaches 2 on 09-Jan.
In cell C24, we are looking at 22 January onwards, and the first date the total of the indicator reaches 2 is 24-Jan.
The same goes for columns E, F, and G.


text:
Q: Transition not showing for animated polarbar plot with plotly (offline) I am trying to make a polar barplot rotate smoothly using plotly in offline mode. Following the examples available in the docs, I do this by creating a button with as method "animate" and setting the transition time to a value >0 ms.
The same problem occurred when using a scatterpolar type plot instead of a barplot, however the animation did work for a non-polar type scatter plot.
import plotly.graph_objs as go
import plotly.offline as offline
import pandas as pd
import numpy as np
offline.init_notebook_mode()

#some data to plot:
df = pd.DataFrame({'artist':['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
                            'birth': pd.to_datetime(pd.Series(['1990-04-01T00:00:00.000000000', '1945-12-01T00:00:00.000000000',
                                      '1955-01-01T00:00:00.000000000', '1956-01-01T00:00:00.000000000',
                                      '1976-12-01T00:00:00.000000000', '1930-05-01T00:00:00.000000000',
                                      '1942-01-01T00:00:00.000000000', '1936-11-01T00:00:00.000000000',
                                      '1971-12-01T00:00:00.000000000', '1952-12-01T00:00:00.000000000'])),
                            'death': pd.to_datetime(pd.Series(['2012-04-01T00:00:00.000000000', '2015-12-01T00:00:00.000000000',
                                      '2010-01-01T00:00:00.000000000', '2017-01-01T00:00:00.000000000',
                                      '2016-12-01T00:00:00.000000000', '2017-05-01T00:00:00.000000000',
                                      '2010-01-01T00:00:00.000000000', '2015-11-01T00:00:00.000000000',
                                      '2014-12-01T00:00:00.000000000', '2013-12-01T00:00:00.000000000']))} )

#creating the barplot:
shift = df['birth'] - pd.datetime(1970, 1 ,1)
trace = {
    'name': "to",
    'r': (df['death']- shift).dt.date,
    'theta': np.linspace(0,360,11),
    'base':df['birth'].dt.date,
    'type': 'barpolar'
}
data = [trace]

nsteps = 20
tracedicts = []
start_thetas = np.linspace(0,360,nsteps)
for i in start_thetas:
    tracedicts.append(trace.copy())
    tracedicts[-1]['theta'] = np.linspace(i,360+i,11)

frames = [{'data': [tracei]} for tracei in tracedicts]

layout = {
    'polar':{
        'angularaxis':{
            'visible': False,
        },
        'radialaxis':{
            'showgrid': True,
            'type': 'date',
            'hoverformat': '%m-%Y',
        }
    },
    'updatemenus': [{
        'type': 'buttons',
        'x': 0.1,
        'y': 0,
        'buttons':[{'label':'Play', 'method':'animate',
                    'args':[None, {'frame':{'duration':600, 'redraw':True},
                                   'transition':{'duration':400},
                                   'fromcurrent':True,
                                   'easing': 'linear'}]}]
    }],
}

fig = go.Figure(data=data, layout=layout, frames = frames)
offline.iplot(fig,auto_play=False)

The animation works as far as showing the different frames, but the transition does not work.
Is this a feature that simply does not exist for all polar and/or bar plots?
(You'll also notice that I set 'redraw':True - this is because otherwise the animation only worked when setting auto_play=True at the end.)


text:
Q: Remove-PublicFolderClientPermission - Output to shell? When i use a Remove-PublicFolderClientPermission command in processing many users to remove permissions from, it does not output to host every line ...it just shows a blank Powershell window until it is done, unless the user to be deleted permissions for does not have rights, then an error is returned.
Is there a way to make Remove-PublicFolderClientPermission output a line for each person it removes?
The code i use for removing is as follows:
#This script imports data from "PFPerm.csv" and Removes permissions for all users in the file.
Write-Host "Removing users...White text = OK ADDED!" -ForegroundColor Green
Write-Host "If a user DOES NOT exist there will be *RED TEXT* stating it was not found.." -ForegroundColor Magenta
Write-Host "If a user is being removed, it will not show any feedback to the screen, just wait for processing to complete.." -ForegroundColor Yellow
"`n"
$Users= Import-CSV -Encoding Unicode H:\Temp\PublicFolder-powershell\PFPerm.csv
#The switch in this line, prevents confirmation popups from requiring user input and supresses them silently [-Confirm:$false]
foreach ($User in $Users){Get-PublicFolder -identity \$($User.Identity) -recurse | Remove-publicfolderclientpermission -Confirm:$false -User $User.User}

If I use $VerbosePreference = "Continue" and the -Verbose parameter, it shows the output i want to caputure and display, but there is too much un-necessary info and I would not want "VERBOSE" to be at the front of the line.

A: Unfortunately, this cannot be done. As the official help suggests, this command has an empty output field.
"If the Output Type field is blank, the cmdlet doesn't return data."

See more:
https://learn.microsoft.com/en-us/exchange/client-developer/management/exchange-management-shell-cmdlet-input-and-output-types


text:
Q: Jupyter Notebook unable to recognize pandas library: Python I use Windows operating system both personally in my home and at office.
The Jupyter Notebook in my personal laptop is able to recognize pandas library. I can read csv file, assign it's content to a numpy array and do many things.
I run the same Jupyter Notebook file in my office. Latest version of pandas is installed and wheel is also installed.
Now, the confusing part is
If I run the code in python console, it looks like this.

Absolutely no error at all.
The same thing in my office's Jupyter Notebook looks like this. It cannot find pandas.

What could be wrong with my Jupyter Notebook in office's computer? I have restarted the kernel, opened in new browser to no avail.
Thanks in Advance

Edit 1

Jupyter Notebook already has pandas and wheel. I can see them when I run !pip list command. I even tried to upgrade if there is any latest version of pandas.

The pandas and wheel in Jupyter Notebook and my local installation has exactly same version installed.

Both are on same directory: D:\Projects\Python\DataVisualization
And the problem still persists. :(

#Edit 2
As suggested by some SO users, I created a virtual environment named VE. On that virtual environment, I installed pandas. Along with pandas other libraries were also installed, i.e. pytz, six, python-dateutil and numpy.

I opened Jupyter Notebook from the virtual environment. Verified that pandas is installed there. And tried to import pandas. Yet the same error.

May be something is just wrong with my Chrome browser. It is controlled by system admins and I just can't uninstall and install it at my own volition. Let's see.

# Edit 3
I tried Jupyter Notebook on Microsoft Edge and it is reporting the same error. So no fault of Chrome.

A: I had a problem with one notebook using pandas and other notebook failing to import it in VS Code. It happened because I've chosen different versions of Python: the global version had it (so pip indicated it's installed), and another had not.

A: You need to install jupyter inside your virtual env, then start it from within the virtual env.  That way it can see all the packages.
Otherwise Jupyter starts outside with a different python interpreter and cannot see the venv packages.
$ pip install --upgrade virtualenv
$ python -m virtualenv venv
$ source venv/bin/activate
(venv) $ pip install jupyter pandas
(venv) $ jupyter notebook

Bob is your Uncle!

A: Pandas is not included with the Jupiter library. You likely have it installed on your local laptop globally. You need to
pip install pandas

on whatever environment/ terminal you are launching jupyter from

A: I could not figure out exactly what caused the issue. But the issue vanished after doing a fresh install of Anaconda.


text:
Q: NodeJS and MongoDB losing the definition of a variable even with module.exports Hello i'm trying to fetch some partner names from my mongodb database and put them into a list of variables. But it for some reason loses it's definition when I try to export it. What's going on?
This is the first file.
///// mongodb.js /////

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const findDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('partners');
  // Find some documents
  collection.find({}).toArray(function(err, docs) {
    assert.equal(err, null);
    callback(docs);
  });
};

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'yarle';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected succesfully to Database");

  const db = client.db(dbName);

  findDocuments(db, function(docs) {
    module.exports = {
      partner1: console.log(docs[0]['partner_name']),
      partner2: console.log(docs[1]['partner_name']),
      partner3: console.log(docs[2]['partner_name']),
    };
    client.close();
  });
});

//console.log(Object.keys(partners[0][0]));

And this is the end file.
///// Endfile.ts /////
import { Request, Response } from 'express';
import { PartnersList } from './data.d';

var partners = require( './mongodb.js');

console.log(partners.partner1);

const titles = [
  partners.partner1,
  partners.partner2,
  partners.partner3,
];

A: Your problem is not with module.exports, it's with asynchronous programming. When you call MongoClient.Connect, the code in your callback does not get executed synchronously. It gets executed some time in the future. You have no control over when that happens.
The same thing is true of the findDocument callback.
Programming asynchronously is a little trickier, but you will have to learn it to write modern javascript. Asynchrony is a central tenet of nodejs. Read on it, learn examples, and your problem will become clear.
Instead of exporting the values of partner1, 2 and 3, export a function with a callback. This new function can call MongoClient.Connect, passing down the callback. Endfile.ts can now call your newly created asynchronous function and assign the titles array in the callback.
Like this:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const findDocuments = function (db, callback) {
  // Get the documents collection
  const collection = db.collection('partners');
  // Find some documents
  collection.find({}).toArray(function (err, docs) {
    assert.equal(err, null);
    callback(docs);
  });
};

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'yarle';

module.exports.getPartners = (callback) {

  // Use connect method to connect to the server
  MongoClient.connect(url, function (err, client) {
    if (err) {
      callback(err);
      return;
    }
    console.log("Connected succesfully to Database");

    const db = client.db(dbName);

    findDocuments(db, function (docs) {
      const partners = {
        partner1: docs[0]['partner_name'],
        partner2: docs[1]['partner_name'],
        partner3: docs[2]['partner_name']
      };
      callback(null, partners);
      client.close();
    });
  });

}

and this
import { Request, Response } from 'express';
import { PartnersList } from './data.d';

var mongoClient = require('./mongodb.js');
mongoClient.getPartners(function (err, partners) {
  assert.equal(null, err);
  const titles = partners;
});


text:
Q: Blackberry Widget: Where is the www folder on the device? Where do the files I put in the "www" directory before building a Blackberry widget end up on the device?
Background: I would like to read the content of some of the files (e.g. "www/index.html") from the www directory in the native Java part of the widget. (I already used FileConnection.list to write the name of all files on the device to System.out - neither index.html nor any other file from the www directory was part of the list.)
The widget is based on PhoneGap 0.9.4 for Blackberry but that shouldn't make a difference.

A: Found the answer: The files are packaged as resources. Therefore it's possible to read them with Class.getResourceAsStream.
Example:
getClass().getResourceAsStream("/index.html");


text:
Q: Replacement for Properties.list I need to convert Properties objects to byte[], I used
byte[] bytes = SerializationUtils.serialize(properties);

But it doesn't seem to be working well as all the data gets corrupted and I see some symbols and special charters. So I used the below approach
StringWriter writer = new StringWriter();
properties.list(new PrintWriter(writer));
String fileContent = writer.getBuffer().toString();
byte[] bytes = fileContent.getBytes();

The above approach seems to work fine, but now calling properties.list is creating some issues as I was getting some text like "-- listing properties --" on the UI side, looks like Properties list method has hardcoded above string via out.println
public void list(PrintWriter out) {
        out.println("-- listing properties --");
        Hashtable h = new Hashtable();
        enumerate(h);
        for (Enumeration e = h.keys() ; e.hasMoreElements() ;) {
            String key = (String)e.nextElement();
            String val = (String)h.get(key);
            if (val.length() > 40) {
                val = val.substring(0, 37) + "...";
            }
            out.println(key + "=" + val);
        }
    }

Is there any other better way achieve it or some replacement for Properties.list?

A: The first approach is fine.
The point is that depending on what you want to do with that binary data, further encoding is required. For example, you could use Base64 encoding to turn your bytes into something that can be "moved" around easily.


text:
Q: How to create Order By in my SQL statement How can i create a Order By in my sql statement? I already tried in a statement like this but this does not work. It crashes every time i run it. Is it because of my $_GET['email']? What am i doing wrong?
$results = $this->EE->db->query(
"SELECT ct.*, t.*, em.*, cd.*
FROM transactions as t
Inner JOIN exp_channel_titles as ct on (t.restaurant_id = ct.entry_id)
Inner JOIN exp_channel_data as cd on (ct.entry_id = cd.entry_id)
inner join exp_members as em on (t.cardid-10000000 = em.member_id)
WHERE ct.title = '".$_GET['email']."'ORDER BY t.created DESC");

A: shoule be :
$results = $this->EE->db->query(
"SELECT ct.*, t.*, em.*, cd.*
FROM transactions as t
Inner JOIN exp_channel_titles as ct on (t.restaurant_id = ct.entry_id)
Inner JOIN exp_channel_data as cd on (ct.entry_id = cd.entry_id)
inner join exp_members as em on (t.cardid-10000000 = em.member_id)
WHERE ct.title = '".$_GET['email']."' ORDER BY t.created DESC");

There is space missing between $_GET['email'] and ORDER BY .

A: As indicated in the comments, you missed one space before 'ORDER BY'.
From
WHERE ct.title = '".$_GET['email']."'ORDER BY t.created DESC");
                                   ^^^

to
WHERE ct.title = '".$_GET['email']." 'ORDER BY t.created DESC");
                                   ^^^^

All together:
$results = $this->EE->db->query(
"SELECT ct.*, t.*, em.*, cd.*
FROM transactions as t
Inner JOIN exp_channel_titles as ct on (t.restaurant_id = ct.entry_id)
Inner JOIN exp_channel_data as cd on (ct.entry_id = cd.entry_id)
inner join exp_members as em on (t.cardid-10000000 = em.member_id)
WHERE ct.title = '".$_GET['email']." 'ORDER BY t.created DESC");

A: Use seperate variables for readability.
$email  =   $_GET['email'];

$query  =   "SELECT
              ct.*,
              t.*,
              em.*,
              cd.*
            FROM transactions as t
              Inner JOIN exp_channel_titles as ct
                on (t.restaurant_id = ct.entry_id)
              Inner JOIN exp_channel_data as cd
                on (ct.entry_id = cd.entry_id)
              inner join exp_members as em
                on (t.cardid - 10000000 = em.member_id)
            WHERE ct.title = '$email'
            ORDER BY t.created DESC";

$results = $this->EE->db->query($query);


text:
Q: Handle sequential HTTP calls with the same message I would like to make two sequential calls one after the other, but using the same request message for both calls. But as shown in my sample code, the response from the first post call becomes the request of the second call by default. What is the most elegant solution for this pattern in spring integration
 public IntegrationFlow test() {
   return IntegrationFlows
       .from("testChannel")
       .handle(httpConfigurations.postCall1())
       .handle(httpConfigurations.postCall2())
       .get();
 }

A: Before the first .handle add a header enricher with an expression to copy the payload to a header.
Before the second .handle use a .transform() to copy the header back to the payload.


text:
Q: laravel eager loading to minimize queries I am using laravel with DDD Pattern and here is my code to make some analytics report for website...
My code from Repository...
//Abstract Entity
  public function getFirstBy($key, $value, array $with = array())
  {
    return $this->repository->getFirstBy($key, $value, $with);
  }

//Link Entity
$link = parent::getFirstBy('hash', $data['hash'], ['visits']);

//prepare report
          $report = [];

          //get dates difference
          $date1 = new \DateTime($data['from']);
          $date2 = new \DateTime($data['to']);
          $date_diff = $date2->diff($date1)->format("%a");

          $time_visits = $link->visits()->whereRaw('DATE(created_at) BETWEEN ? AND ?', array($date1, $date2))->groupBy('created_at')->orderBy('created_at', 'ASC')->get();

          //Total Visits
          $report['total_visits'] = $time_visits->count();

    //country visits
          $country_visits = $link->visits()->whereRaw('DATE(created_at) BETWEEN ? AND ?', array($date1, $date2))->orderBy('country_iso', 'ASC')->groupBy('country_iso')->get();

    //referrers
          $referer_visits = $link->visits()->whereRaw('DATE(created_at) BETWEEN ? AND ?', array($date1, $date2))->where('source', '!=', '')->orderBy('source', 'ASC')->groupBy('source')->get();

    //browsers
          $browser_visits = $link->visits()->whereRaw('DATE(created_at) BETWEEN ? AND ?', array($date1, $date2))->where('browser', '!=', '')->orderBy('browser', 'ASC')->groupBy('browser')->get();

    //os
          $os_visits = $link->visits()->whereRaw('DATE(created_at) BETWEEN ? AND ?', array($date1, $date2))->where('os', '!=', '')->orderBy('os', 'ASC')->groupBy('os')->get();

The code is working perfectly fine but executing 6 mysql queries which could be a big problem for larger usage...

**sql queries dump...**

    select * from `link_visits` where `link_visits`.`link_id` = '4' and DATE(created_at) BETWEEN '2014-09-15 00:00:00' AND '2014-09-17 00:00:00' group by `created_at` order by `created_at` asc

    select * from `link_visits` where `link_visits`.`link_id` = '4' and DATE(created_at) BETWEEN '2014-09-15 00:00:00' AND '2014-09-17 00:00:00' group by `country_iso` order by `country_iso` asc

    select count(*) as total_visits, medium from `link_visits` where `link_visits`.`link_id` = '4' and DATE(created_at) BETWEEN '2014-09-15 00:00:00' AND '2014-09-17 00:00:00' group by `medium` order by `medium` asc

    select * from `link_visits` where `link_visits`.`link_id` = '4' and DATE(created_at) BETWEEN '2014-09-15 00:00:00' AND '2014-09-17 00:00:00' and `source` != '' group by `source` order by `source` asc

    select * from `link_visits` where `link_visits`.`link_id` = '4' and DATE(created_at) BETWEEN '2014-09-15 00:00:00' AND '2014-09-17 00:00:00' and `browser` != '' group by `browser` order by `browser` asc

    select * from `link_visits` where `link_visits`.`link_id` = '4' and DATE(created_at) BETWEEN '2014-09-15 00:00:00' AND '2014-09-17 00:00:00' and `os` != '' group by `os` order by `os` asc

Please suggest some good ways to optimize it better. thanks, i really need advanced help with this.

A: you can use sub query in the relations for ex.
assuming $link is you model object
$link->with(['Visits'=>function($q){
       $q->whereRaw('DATE(created_at) BETWEEN ? AND ?', array($date1,$date2))->where('browser', '!=', '')->orderBy('browser', 'ASC')->groupBy('browser');
}])->get();

the inner query will filter all your records accordingly and the inner query will apply only in the Visits model
my suggestion is first fetch all the records without any filteration and then filter them in the object of collection with filter() method! so it will use only 1 query for visit to fetch all records then you only rearrange them using filter() method


text:
Q: How does spring construct and auto wire maps I am using spring for quite some time but this morning I came across with some unexpected behavior.
As I could not decide by myself whether that was a desired functionality or a bug I am presenting it here with the hope I will get some good explanations about why would this be happening.
In short I have multiple beans defined in an application context and I create two map beans using utils:map name space with only part of my beans added to those maps. The two maps have exactly the same entries.
Then I auto wire those maps. One auto wire is done using @Autowired annotation and the other one is done using @Resource
To my surprise the bean annotated with @Autowired had got all beans in the context not only the ones I specifically put in the map. The other one auto wired using @Resource annotation had only the expected two entries in it.
I am mainly interested in:
1. Why all the beans declared in my context of that time appear in the @Autowired map and not the ones I added
2. Why @Resource and @Autowired would behave differently
Here is the working code that reproduces the scenario described above.
Some interface here:
package my.testing.pkg;

public interface Foo {
    void doStuff();
}

And its implementation:
package my.testing.pkg;

public class FooImpl implements Foo {
    @Override
    public void doStuff() {}
}

The spring config file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:utils="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="foo_1" class="my.testing.pkg.FooImpl"/>
    <bean id="foo_2" class="my.testing.pkg.FooImpl"/>
    <bean id="foo_3" class="my.testing.pkg.FooImpl"/>
    <bean id="foo_4" class="my.testing.pkg.FooImpl"/>

    <utils:map id="fooMap1" map-class="java.util.HashMap">
        <entry key="foo_1" value-ref="foo_1"/>
        <entry key="foo_2" value-ref="foo_2"/>
    </utils:map>

    <utils:map id="fooMap2" map-class="java.util.HashMap">
        <entry key="foo_1" value-ref="foo_1"/>
        <entry key="foo_2" value-ref="foo_2"/>
    </utils:map>
</beans>

And the test case to reproduce the behavior:
package my.testing.pkg;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.Map;

import static org.junit.Assert.assertEquals;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/test-context.xml")
public class SpringMapCreatingTest {
    @Autowired
    private Map<String, Foo> fooMap1;
    @Resource
    private Map<String, Foo> fooMap2;

    @Test
    public void shouldInjectATwoEntriesMap() throws Exception {
        assertEquals("fooMap1 should have to entries", 2, fooMap1.size());
        assertEquals("fooMap2 map should have to entries", 2, fooMap1.size());
    }
}

Thank you in advance for your clarifications.

A: What is happening there is the following:

*

*The @Autowired dependency will look for beans that match its type, and in this case it will create a map of your beans Foo mapped by their name. The same behavior will happen when you autowire on a list of beans, Spring will inject all the beans that implement the interface.

*The @Resource dependency will look first for a bean that matches the dependency name, e.g fooMap2 and will inject it.

A: Take a look at the documentation http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-autowired-annotation-qualifiers
Maps / List are not handled as "standard" beans injection.
Take a look to those questions on so: Can spring @Autowired Map?
https://stackoverflow.com/a/13914052/1517816
HIH

A: Check the spring docs, the tips section:

beans that are themselves defined as a collection or map type cannot
  be injected through @Autowired, because type matching is not properly
  applicable to them. Use @Resource for such beans

So it is better to use @Resource and not @Autowired for maps


text:
Q: Expression to use when you are not dressed or otherwise ready to meet someone What is the English expression to ask someone if he/she is dressed and "presentable", in the sense that he/she is tidy enough to meet someone else? The word "dressed" does not convince me, because its meaning covers only clothes, and one might think of being not "presentable", for example, if hair are not combed.
Example: imagine someone knocking at the door of your bedroom and asking "X is here to meet you, are you [dressed]?".
Example, from the opposite side: someone knocks at the door of your bedroom and asks "May I come in?", and you answer "No, I'm not [dressed]".

A: You can actually use "presentable" in the way you're describing: "Give me a minute, I'm not presentable." The phrase "are you decent" covers mainly whether you're not naked but also implies that you are presentable.


text:
Q: How to recover a locally only committed branch in git? Somehow my local git got corrupted and I am getting, "fatal: Not a git repository (or any of the parent directories): .git". On one of the branches I have committed locally, but looks like that I have never pushed to the server. When I got a new repo on to a different folder, is there any way to recover that branch? In the new repo, when I try to checkout the branch, I am getting "the branch doesn't exist" message.
Thanks

A: As probably you know. All the info about your braches and commits are inside a folder call .git
I have a problem long time ago like that. If you still have it the folder you should try to clone the repository (diferent folder) again and  copy the folders:

*

*.git/refs (here you can see the list of your branchs)

*.git/objects (you have the branch but you need the files info)
Hope you can recover your work!!!

A: Added the older local repository as a remote of your new local repository, you can get those local branches in your old local repository.

A: Worst case scenario, how about you clone from scratch, create a new branch and then copy the changed files from your corrupt local repository.


text:
Q: Can Newton's second law for rotation be derived from Newton's second law for translation? I am referring to the Newton's second law for rotation:
$\vec{\tau}=I \vec{\alpha}$
Which obviously is the analogue for Newton's second law for translation
$\vec{F}=M \vec{a}$
I wonder whether the rotation law can be derived from transnational one? If yes, how can we do it?

A: Mathematically yes (as shown below), but it is always good to understand Force equations as conservation of linear momentum or angular momentum.
Taking cross-product on either side of linear force balance with $\vec{r}$, we get
\begin{equation}
\vec{F}\times \vec{r} = [M\vec{a}]\times \vec{r}
\end{equation}
we know that,
\begin{equation}
\vec{F}\times \vec{r} = \vec{\tau}; \ \vec{a}= r\vec{\alpha};  \ Mr^2 = I;
\end{equation}
Therefore,
\begin{equation}
\vec{F}\times \vec{r} = \vec{\tau} = [Mr^2\vec{\alpha}] = I\vec{\alpha}
\end{equation}


text:
Q: Making PDF exported from ArcMap have pop-up when clicking on feature? When converting your map into a PDF from ArcView 10.1, is there a way to make the PDF Map to have a pop-up when you click on a tract?

A: there are several companies and products you can use: geoPDF is one of them.
There are much more detailed answers available at Adding interactive map to PDF?


text:
Q: How to append type definition to existing @types package? For example, my project has a dependency on npm package foo-js, and dev-dependency @types/foo-js for type definitions.
// package.json
{
   ...
  "dependencies": {
    "foo-js": "2.0.0"          // latest
  },
  "devDependencies": {
    "@types/foo-js": "1.2.3"   // latest
  }
}

The version of @types/foo-js is outdated (though it is the latest), If I try to use newly added method of foo-js;
import { Foo } from 'foo-js'

Foo.v1_method()     // ok

Foo.v2_new_method() // Property 'v2_new_method' does not exist on type 'typeof import("foo-js")'.ts(2339)

Using type assertion such as (Foo as any).v2_new_method() solves compile-time eror, but I'm trying not to use type assertions as much as possible.
I've tried to add type declaration file as below;
// types.d.ts

declare module 'foo-js' {
  interface Foo {
    v2_new_method: () => any
  }
}

but it didn't work. I think I've missed something.
Is there another way to solve this problem?


text:
Q: Asp.net mvc 3 model usage with database I am working on a project that has a large database with all the data already in it. So now, I don't see the mvc project model being used very much, since the views are being strongly typed to a database model.
I am very new to this stuff, so is database simply taking place of the model "space" ?

A:
since the views are being strongly typed to a database model

That's wrong. You shouldn't pass any domain models to the views. You should be using view models which are classes specifically designed for the requirements of a given view. A controller action should query your data access layer which will return some domain models and then map those domain models to view models and then pass this view model to the view. A view model is a representation of the database for a specific view.


text:
Q: Is there a more pythonic way to find duplicates of folders and return their paths as a list of tuples? I implemented this to find duplicates within a folder where folder names take on the format: "NAME_(ID)". The program finds duplicates, where NAME is identical and ID is different, and puts them into a list of tuples with the full path for later merging.
While the approach works well (folder count is never >1000), I couldn't help but wonder if there is a more pythonic and possibly faster approach.
def getFolderNumber(f_name):
    return f_name.split("_")[-1]

def discoverDuplicates(path):
    '''
    Discovers duplicate folders
    '''
    #Gets the list of folder ID numbers
    folder_nums = [getFolderNumber(f) for f in os.listdir(path)]
    #Gets the list of full folder names
    folders = [f for f in os.listdir(path)]

    #Returns folder ID numbers if there are more than 1
    dupes = [item for item, count in collections.Counter(folder_nums).items() if count > 1]

    #Gets the indices for the duplicates in folder_nums, which is of equal length and ordering to folders
    f_indices = [i for i, x in enumerate(folder_nums) if x in dupes]

    #Gets all items in folders that match the indices from above. Sorts this list using the ID number
    pre_zip = sorted([folders[x] for x in f_indices],key=lambda x: getFolderNumber(x).lstrip("(").rstrip(")"))

    #Packages together duplicates into a list of lists
    iterator = iter(pre_zip)
    pre_join = list(map(list,zip(iterator,iterator)))

    #Lambda for joining paths
    path_builder = lambda x: os.path.join(path,x)

    #Joins the final paths within each sublist within the final lists of lists
    return [final.append(list(map(path_builder,x))) for x in pre_join]

Here is an example of input:
Input: ListOfFolders(List) contains [NAME1_(459),NAME2(459),NameN(ID_N)...]
Output: [('Path/to/NAME1_(459)','Path/to/NAME2_(459'),(DuplicatePair2),...]

A: Would something like this do the job ?
from collections import defaultdict

def group_duplicates(folders_names):
    dups_dict = defaultdict(list)
    for folder_name in folders_names:
        folder_name_prefix = folder_name.split('_')[:-1]
        dups_dicts[folder_name_prefix].append(folder_name)
    return [tuple(dups) for dups in dups_dict.values()]

It can eventually be seen as more 'pythonic' in the sense that it is very simple and straight-forward (simple is better than complex).
One could one-line it with some nested comprehensions, but it would eventually become less readable.
As of the speed, it will perform reasonably fast, so as long as it is not the bottleneck of your program, you should not worry too much about it.


text:
Q: Python 3 NameError when Using variable in 'if' condition I am trying to make a simple program for 'Stone Paper Scissor', it's just a beginner level code, but I am facing NameError for a variable that I defined and using that variable for a condition of if. I am using Python 3.I am posting the program I wrote here:
player1count = 0
player2count = 0
print("Make a Choice: \n1.Stone\n2.Paper\n3.Scissor")
player1 : int(input("Player 1 plays "))
player2 : int(input("Player 2 plays "))
while (True):
    if player1 is 1 and player2 is 3 or player1 is 2 and player2 is 1 or player1 is 3 and player2 is 2:
        player1count += 1
        print(player1+" beats "+player2)
    elif player2 == 1 and player1 == 3 or player2 == 2 and player1 == 1 or player2 == 3 and player1 == 2:
        player2count += 1
        print(player2 + " beats " + player1)
    else:
        continue
    if(player1count == 5):
        print("Player 1 Wins!")
        break
    elif(player2count == 5):
        print("Player 2 Wins!")
    else:
        continue

This is the error I am getting:
Make a Choice:
1.Stone
2.Paper
3.Scissor
Player 1 plays 1
Player 2 plays 3
Traceback (most recent call last):
  File "G:/Study/Python/StonePaperScissor.py", line 7, in <module>
    if player1 is 1 and player2 is 3 or player1 is 2 and player2 is 1 or player1 is 3 and player2 is 2:
NameError: name 'player1' is not defined

Process finished with exit code 1

A: Assuming you're trying to assign the input values to those variables, please use assignment operator.
player1 = int(input("Player 1 plays "))
player2 = int(input("Player 2 plays "))

Brownie points :

*

*As pointed out in another answer there is bug in print statement too, you're trying to concat int and string. Do something like print(str(player1) + " beats " + str(player2))

*And maybe you need to take the inputs inside the loop.
Working code/demo : https://repl.it/repls/QuintessentialWittyAbilities

A: I'm not getting the error you say when I run your code, however I did get other errors:
player1 : int(input("Player 1 plays "))
player2 : int(input("Player 2 plays "))

should be
player1 = int(input("Player 1 plays "))
player2 = int(input("Player 2 plays "))

You also have print(player2 + " beats " + player1). + is used for string concatenation, which is when you stick one string on the end of another. However, player1 and player2 aren't strings. You need to use , instead of + or do str(player1) and str(player2).
Making those changes to the code you supplied, my output just spams x beats y, which is due to an error in your code logic.

A: The player: type is just a type hint. It doesn't actually do anything, it's there to help readability and external tools for code analysis. It also does not declare the variable, as in static language.
In python, to declare the variable, you have to assign a value to it. So
player1: int = int(input("Player 1 plays "))

to use both the type hint and the value assignment.
Note: You want player1==1, instead of player1 is 1. is checks if they are the same object, not if they are equal.

A: Since you got the answer you were looking for, i will give you a tip to shorten the code if you want. If you assign the values 0,1,2 to Rock, Paper, Scissors, then your if statements can be greatly simplified as follows:
You take the value from the computer's choice (ex. Scissors = 2) and from it you subtract the value of your choice (ex. Paper = 1). Now whats left of the subtraction determines the outcome.
Make 2 lists, A=[-1,2] and B=[1,-2]
If outcome=0: draw
If outcome in B: you lose
If outcome in A: you win

This probably works with any series of values you give to the choices, so long as they are linear (ex. 7,8,9)


text:
Q: How do I do a where query on a SQL column against multiple values? This is what my query looks like:
Connection.where("invited_user_id = :user_a_id AND inviter_user_id = :user_b_id", user_a_id: self.inviter.try(:id), user_b_id: self.invited.try(:id)).exists?

What I would like to do is basically check invited_user_id against multiple options, e.g. something like invited_user_id = [:user1, :user2]. But that doesn't work.
How can I check to see if the value in the column invited_user_id is in either of the variables :user1, :user2 or any other of multiple variables.
Is that possible without using an explicit OR approach that's less DRY?

A: The Hash form of where accepts array of values, so:
Connection.where(invited_user_id: [1, 2, 3, 4, 5])

That will find all records where invited_user_id is any of the values listed in the array.

A: Never put values directly in a query, that's not safe. Parameterize your query using the ? operator.
invited_user_ids = [:user1, :user2]
Connection.where("invited_user_id IN (?)", invited_user_ids)


text:
Q: Las funciones de php me trabajan de diferentes formas en distintas hosting Soy un poco nuevo en esto pero les indicare que sucede
1)Tengo un programa de php con javascript, jquery, bootstrap, su respectivo css y los archivos smtp para enviar correo, en mi localhost todo funciona correctamente, envia correos etc.. se complica es al momento de subirlo al hosting
2)Tengo de prueba a 3 hosting.... Godaddy, CaracasHosting y uno gratuito llamado zz.com.ve
3)GoDaddy no tiene por defecto el modo rewrite activado, algo que es de vital importancia para el proyecto por ende no nos sirve, CaracasHosting si tiene activado ese modo pero al momento de querer iniciar sesion etc.. por ejemplo al validar el usuario, simplemente se queda en ese archivo php si hacaer nada, puede registrar y de hecho si vas al lugar como deberia hacer al momento de validar al usuario este lo valida etc.. pero pues no cumple sus funciones como deberia, Este es el error de los log
[03-Mar-2020 01:13:34 UTC] PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/globalli/public_html/directorio/validar.php:8) in /home/globalli/public_html/directorio/validar.php on line 11

3)Por ultimo tenemos al servicio web gratuito y que creen? Este si casi por completo sus funciones como lo hace en mi localhost....El envio del correo no funciona en ninguno de los 3 tengo entendido que eso es cuestion de hablar con la empresa a ver como configurarlo
Si alguien puede orientarme seria de mucha ayuda


text:
Q: php read directory and output date modified for folder I have a working code that Reads a directory and outputs the name, total files and size already. What I would like to do is also grab the Date Modified and format it as YYYY-MM-DD.
Code:
if ($handle = opendir('D:/'.$sub.'/')) {

    while (false !== ($entry = readdir($handle))) {
        if ($entry != '$RECYCLE.BIN' && $entry != 'System Volume Information' && $entry != '.' && $entry != '..') {
        $exists = mysql_query('SELECT * FROM comics WHERE arc LIKE "'.$entry.'%"');
        $exists1 = mysql_num_rows($exists);
            if ($exists1 == 0) {
            $directory = $base.$sub."/".$entry;
            $filecount = count(glob($directory."/"."*.*"));
            $size = 0;
            $d = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($directory),
            RecursiveIteratorIterator::SELF_FIRST
            );

            foreach($d as $file){
            $size += $file->getSize();
            }

            $entry = str_replace(" - ", ": ", $entry);
                mysql_query('INSERT INTO comics (arc, files, size) VALUES ("'.$entry.'\n", "'.$filecount.'", "'.$size.'")');
                print "
Inserted ".$entry." With A File Count Of ".$filecount." & A Total Size Of ".$size." Bytes.
";
            }
        }
    }
}

A: if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("Y-m-d", filemtime($filename));
}

http://php.net/manual/en/function.filemtime.php


text:
Q: Can't See ListViewItem.SubItems For some reason, when I write the following code in my Visual Studio 2010 (.NET Framework 4.5):
ListViewItem item = new ListViewItem("item1");
item.SubItems

there is no such field as SubItems.
What could be the reason for that?
Regards,
Vitalii.

A: Yes there is, at least in winforms.
Look a little closer, once you add the dot the usual list of items should come up:

ListViewItem item = new ListViewItem("item1");
item.SubItems.Add("subitem1");

Note: To declare an instance you need to reference the class like this:
ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();

Also note: Sometimes Intellisense stops working; I have to restart VS to bring it back to life..
If however you are targeting WPF, then you are right: There are no SubItems in a WPF ListViewItem. It is a ContentControl, which can contain whatever you put there, I believe. But I'm no WPF expert. A good book may be best..

          System.Windows.Controls.ContentControl
            System.Windows.Controls.ListBoxItem
              System.Windows.Controls.ListViewItem

A: There is a ListViewItem constructor that takes a string array, where the first element is the main item text and the other are the SubItems texts:
var myNewItem = new ListViewItem(new[]
                {
                    "First column",
                    "Second column",
                    "Third column"
                });

myListItem.Items.Add(myNewItem);

Of course, you have to set your ListView Mode to Detail mode, and create the Columns collection accordingly.
EDIT: This is a WinForm tip... I dont know if it applies to WPF unfortunately.


text:
Q: Calculating sum of converging series $\sum_{n=1}^{\infty}\frac{1-n}{9n^3-n}$ I have a trouble with calculating the sum of this series:
$$2+\sum_{n=1}^{\infty}\frac{1-n}{9n^3-n}$$
I tried to split it into three separate series like this:
$$2+\sum_{n=1}^{\infty}\frac{1-n}{9n^3-n} =2+\sum_{n=1}^{\infty}\frac{2}{3n+1}+\sum_{n=1}^{\infty}\frac{1}{3n-1}-\sum_{n=1}^{\infty}\frac{1}{n} $$ but I'm not able to continue, can you give me some tips?

A: For the direct evaluation of the limit, you have received the good solution from J.G.
You could also consider the partial sum using, as you did, partial fraction decomposition
$$\frac{1-n}{9n^3-n}=\frac{1}{3 n-1}+\frac{2}{3 n+1}-\frac{1}{n}$$ which makes
$$S_p=\sum_{n=1}^{p}\frac{1-n}{9n^3-n}=\frac{1}{3} \left(\psi \left(p+\frac{2}{3}\right)-\psi
   \left(\frac{2}{3}\right)\right)+\frac{2}{3} \left(\psi
   \left(p+\frac{4}{3}\right)-\psi \left(\frac{4}{3}\right)\right)-H_p$$ where appear the digamma function and harmonic number.
Now, using asymptotics and Taylor series you should arrive to
$$S_p=-\left(\gamma +\frac{1}{3}\psi\left(\frac{2}{3}\right)+\frac{2}{3} \psi
  \left(\frac{4}{3}\right)\right)+\frac{1}{9 p}-\frac{1}{9
   p^2}+O\left(\frac{1}{p^3}\right)$$ which shows the limit and how it is approached.
Now, the particular values
$$\psi\left(\frac{2}{3}\right)=-\gamma +\frac{\pi }{2 \sqrt{3}}-\frac{3 \log (3)}{2}$$
$$\psi\left(\frac{4}{3}\right)=3-\gamma -\frac{\pi }{2 \sqrt{3}}-\frac{3 \log (3)}{2}$$ make
$$S_p=\left(-2+\frac{\pi }{6 \sqrt{3}}+\frac{3 \log (3)}{2}\right)+\frac{1}{9
   p}-\frac{1}{9 p^2}+O\left(\frac{1}{p^3}\right)$$
For $p=10$, the exact value is $-\frac{477820712081}{12033629407800}\approx -0.039707$ while the above truncated expansion gives $-\frac{199}{100}+\frac{\pi }{6 \sqrt{3}}+\frac{3 \log (3)}{2}\approx -0.039782$.

A: Let's rewrite $\frac{1}{n}$ as $\frac{3}{3n}$, so your sum is $S+2$ with$$S:=\sum_{n\ge 1}\left(\frac{1}{3n-1}-\frac{3}{3n}+\frac{2}{3n+1}\right)\\=\sum_{n\ge 1}\int_0^1 x^{3n-2}\left(1-3x+2x^2\right)\mathrm dx=\int_0^1\frac{x-3x^2+2x^3}{1-x^3}\mathrm dx.$$Thus $$S+2=\int_0^1\frac{2+3x}{1+x+x^2}\mathrm dx=\frac32\int_0^1\frac{1+2x}{1+x+x^2}\mathrm dx+\frac12\int_0^1\frac{\mathrm dx}{1+x+x^2}.$$The rest I'll leave to you.


text:
Q: Realloc allocation in C Hello I try to understand how realloc works so here is my question:
Let's say that first we call malloc in order to allocate enough memory for 1 int.
int *p=malloc(sizeof(int))

then we call realloc like this:
p=realloc(p,sizeof(int)*2);

The pointer p points to memory with available space for 2 or 1+2 ints?

A: As mentioned in the man pages:

void *realloc(void *ptr, size_t size);
[...]
The realloc() function changes the size of the memory block pointed
         to by ptr to size bytes.  The contents will be unchanged in the range
         from the start of the region up to the minimum of the old and new
         sizes.  If the new size is larger than the old size, the added memory
         will not be initialized. [...]

(My emphasis). In other words, the size parameter to realloc asks for how many bytes of memory you'd like allocated in total, not the number of bytes of memory that you'd like to add.
Hope this helps!

A: void* realloc (void* ptr, size_t size);
Changes the size of the memory block pointed to by ptr.
The function may move the memory block to a new location (whose address is returned by the function).
The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved to a new location. If the new size is larger, the value of the newly allocated portion is indeterminate.
In case that ptr is a null pointer, the function behaves like malloc, assigning a new block of size bytes and returning a pointer to its beginning.
In C90 (C++98):
Otherwise, if size is zero, the memory previously allocated at ptr is deallocated as if a call to free was made, and a null pointer is returned.
In C99/C11 (C++11):
If size is zero, the return value depends on the particular library implementation: it may either be a null pointer or some other location that shall not be dereferenced.
Argument ptr:
Pointer to a memory block previously allocated with malloc, calloc or realloc.
Alternatively, this can be a null pointer, in which case a new block is allocated (as if malloc was called).
Argument size:
New size for the memory block, in bytes.
size_t is an unsigned integral type.
Return Value:
A pointer to the reallocated memory block, which may be either the same as ptr or a new location.
The type of this pointer is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
In C90 (C++98):
A null-pointer indicates either that size was zero (an thus ptr was deallocated), or that the function did not allocate storage (and thus the block pointed by ptr was not modified).
In C99/C11 (C++11):
A null-pointer indicates that the function failed to allocate storage, and thus the block pointed by ptr was not modified.

A: From realloc(3)

Synopsis
  void *realloc(void *ptr, size_t size);
Description
  The realloc() function changes the size of the memory block pointed to by ptr to size bytes.


text:
Q: Inherit from QDomNode to create PHP Code Fragments in a QDomDocument I write a program which should output PHP code containing mainly basic HTML code but a few PHP commands. Therefore I wanted to use QDomDocument to write this file in an object oriented style.
I created a class QDomPHPCode inheriting from QDomNode. I've overwritten save() which writes the PHP code including the <?...?> to a QTextStream.
The problem now is that to create such an element, I have to call one of the factory methods QDomDocument::create...(), but of course, there doesn't exist one for my own class.
I thought about subclassing QDomDocument in order to implement such a method for my QDomPHPCode node and therefore watched the source code of QDomDocument. The functions create...() call the functions in QDomDocumentPrivate with the same name, so in order to implement an own create...() function implies the need to create one in QDomDocumentPrivate. The latter requires me to subclass QDomDocumentPrivate which isn't visible to #include <QDomDocument> and therefore can't be subclassed as far as I know.
Is there any possibility to do what I want to do? Or is it definitely the better (or only) way to create a PHP file completely on my own?
Thanks in advance!

A: The problem I see is that a PHP document in not a valid HTML/XML document, so you might have parsing errors. PHP is an interpreter that parses a special (PHP) document that could produce a valid HTML/xHTML/XML document.
So, as a workaround I suggest you place some tags say <-- php-code-start --> and <-- php-code-end --> into the document (using QDomDocument) and then parse/replace it after (post-processing).
Another approach is the replace the php start tag with an HTML start comment but you will still need to post-process.


text:
Q: What came first: git subtree merge strategy or git submodule? What is more recent invention — git subtree merge strategy (not the new git-subtree command) or git submodule command (or maybe underlying mechanism if there was a separate one symmetrical to git subtree command vs. merge strategy).
What was included in Git distribution release first?
Bonus points for links to relevant Git ML posts.
I tried do dig that info from Git commit history, but got lost somewhere in 2007-2008 for both features.

A: Subtree merge seems to be a tad older:
Introduced by Junio Hamano in Feb 2007 68faf68938ee943fc251c702f2027e4dfda354db »Add new merge stragety [sic] 'subtree'« (file git-merge.sh)
Git submodule was introduced in May 2007 by Lars Hjemli in commit 70c7ac22de681a83621bda03e676348170c8d8a2 »Add git-submodule command« (file git-submodule.sh)
To get the releases that first contained a certain feature, run git describe --contains on its commit.
For the above commits this means v1.5.2-rc0 and v1.5.3-rc0, respectively.


text:
Q: Как объединить два массива в один у которых ключи id и user_id с одинаковыми значениями в js? Подскажите пожалуйста как решить.
есть "большой" массив в котором user_id повторяются:
[
 { "user_id": 1, "page_views": 7, "clicks": 5 },
 { "user_id": 5, "page_views": 6, "clicks": 3 },
 { "user_id": 9, "page_views": 4, "clicks": 7 },
 { "user_id": 1, "page_views": 3, "clicks": 5 },
]

есть "маленький" массив все id уникальны:
[
 {"id":9,"first_name":"Barnabas"},
 {"id":1,"first_name":"Emlyn"},
 {"id":5,"first_name":"Ervin"},
]

Нужно слить их в общий массив, при этом отыскать все совпавшие значения id маленького массива c user_id большого
 просуммировать все значения ключей page_views и clicks добавить в объекты маленького массива.
Вид массива должен быть следующий,
итоговый массив:
[
 {"id":9, "first_name":"Barnabas", "page_views": 4 , "clicks": 7 },
 {"id":1, "first_name":"Emlyn", "page_views": 10, "clicks": 10 },
 {"id":5, "first_name":"Ervin", "page_views": 7, "clicks": 5 },
]

A: Например, так:

let large = [{"user_id": 1, "page_views": 7, "clicks": 5},
  {"user_id": 5, "page_views": 6, "clicks": 3},
  {"user_id": 9, "page_views": 4, "clicks": 7},
  {"user_id": 1, "page_views": 3, "clicks": 5}
];

let small = [{"id": 9, "first_name": "Barnabas"},
  {"id": 1, "first_name": "Emlyn"},
  {"id": 5, "first_name": "Ervin"}
]

let result = small.map(item => {
  let { id, first_name } = item;
  let { page_views, clicks } = large.reduce((acc, data) => {
    if (data.user_id == id) {
      acc.page_views += data.page_views;
      acc.clicks += data.clicks;
    }
    return acc;
  }, {page_views: 0, clicks: 0});
  return { id, first_name, page_views, clicks }
});

console.log(result);


text:
Q: Windows route with virtualbox network configuation There are two network cards in my workstation. One for our local network and one for internet access.
The local network card has static ip address 192.168.1.10 with gateway of 192.168.1.1.
The internet network card has static ip 192.168.155.* with gateway of 192.168.155.1.
Now I use the route to make the pc access local network and internte at the sametime.
route ADD     0.0.0.0 MASK 255.255.255.0  192.168.155.1 # default use the internet network card
route ADD 192.168.1.0 MASK 255.255.255.0  192.168.1.1   # for local network

It worked.
However I have VirtualBox installed, and there is  a guest vm with bridge network with static ip 192.168.1.11. I can not access that after I set the route.
Is it possbile to make the host and guest can access each other, also make the guest vm can access both local and internet?

update:
Before I set the route, my virtualbox guest vm works as expected, so  I think there is not problem with the configuration with the vbox.


text:
Q: How to Conditionally Route Using One Button? (Flutter) I have a scene (collections.dart) that takes an index of several other scenes/files in a PageView.builder. You can swipe between scenes from the collections.dart file.  Also in collections.dart is a button.
I want it to be the case that if you click on the button, and the current scene being shown through collections.dart is, for example, FirstScreen, then I can route to a table I have built specifically for first.dart, with the same being true for all other scenes in the index.
I have tried to accomplish this by a conditional statement in the onPressed argument, but no success yet. There is no error, it just takes no action.  Here is the code in its entirety for collections.dart (including the unsuccessful conditional statement for onPressed):
    import 'package:flutter/material.dart';
    import 'package:circle_indicator/circle_indicator.dart';
    import 'first.dart';
    import 'second.dart';
    import 'third.dart';
    import 'fourth.dart';
    import 'fifth.dart';
    import 'sixth.dart';
    import 'seventh.dart';
    import 'eighth.dart';
    import 'ninth.dart';
    import 'tenth.dart';

    class CollectionsScreen extends StatelessWidget {

      @override
      Widget build(BuildContext context){
        return Collections();
      }
    }

    class Collections extends StatefulWidget {
      @override
      CollectionsState createState() => CollectionsState();
    }

    class CollectionsState extends State<Collections> {

      FirstScreen one;
      SecondScreen two;
      ThirdScreen three;
      FourthScreen four;
      FifthScreen five;
      SixthScreen six;
      SeventhScreen seven;
      EighthScreen eight;
      NinthScreen nine;
      TenthScreen ten;
      List<Widget> pages;

      @override
      void initState() {
        one = FirstScreen();
        two = SecondScreen();
        three = ThirdScreen();
        four = FourthScreen();
        five = FifthScreen();
        six = SixthScreen();
        seven = SeventhScreen();
        eight = EighthScreen();
        nine = NinthScreen();
        ten = TenthScreen();

        pages = [one, two, three, four, five, six, seven, eight, nine, ten];

        super.initState();
      }

      final PageController controller = new PageController();

      @override
      Widget build(BuildContext context){

        return new Stack(
          children: <Widget>[
            new Scaffold(
              body: new Container(
                child: new PageView.builder( //Swipe Between Pages
                  controller: controller,
                  itemCount: 10,
                  itemBuilder: (context, index){
                    return pages[index];
                  }
                ),
              ),
            ),
            new Container( //CircleIndicator
              child: new CircleIndicator(controller, 10, 8.0, Colors.white70, Colors.white,),
              alignment: Alignment(0.0, 0.9),
            ),
            new Container( //Button
              alignment: Alignment(0.0, 0.65),
              child: new Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  new Container(
                    child: new RaisedButton(
                      elevation: 4.0,
                      child: new Text(
                        'SHOW ME',
                        style: new TextStyle(
                          fontWeight: FontWeight.w900,
                          fontSize: 22.0,
                        ),
                      ),
                      color: Color(0xFF70E0EF),
                      shape: new RoundedRectangleBorder(
                        borderRadius: new BorderRadius.circular(7.5)
                      ),
    //This is the conditional statement I'm talking about
                      onPressed: () {
                        new PageView.builder(
                          controller: controller,
                          itemBuilder: (context, index) {
                            if (pages[index] == one){
                              Navigator.push(
                                context,
                                new MaterialPageRoute(builder: (context) => new FirstTable()),
                              );
                            }
                            else if (pages[index] == two){
                              Navigator.push(
                                context,
                                new MaterialPageRoute(builder: (context) => new SecondTable()),
                              );
                            }
                            else {
                              Navigator.push(
                                context,
                                new MaterialPageRoute(builder: (context) => new ThirdTable()),
                              );
                            }
                          }
                        );
                      },
                    ),
                    width: 150.0,
                    height: 60.0,
                  ),
                ],
              ),
            ),
          ],
        );
      }
    }

The "Table" classes I'm referring to in the conditional statement are in the files for first.dart, second.dart, etc. Here is the file for first.dart.  For the moment, the code is identical between all these files (first.dart, second.dart, etc.):
    import 'package:flutter/material.dart';

    class FirstScreen extends StatelessWidget {

      @override
      Widget build(BuildContext context) {
        return new First();
      }
    }

    class First extends StatefulWidget {
      @override
      FirstState createState() => FirstState();
    }

    class FirstState extends State<First>{

      @override
      Widget build(BuildContext context) {

        double fontSize = MediaQuery.of(context).size.height;

        double fontSizeFractional = fontSize * 0.07;

        return Scaffold(
          body: new Stack(
            fit: StackFit.passthrough,
            children: [
              new Container( //Background
                decoration: new BoxDecoration(
                  image: new DecorationImage(
                    image: new AssetImage('assets/FirstBG.png'),
                    fit: BoxFit.cover
                  ),
                ),
              ),
              new Container( //Title
                margin: EdgeInsets.all(40.0),
                alignment: new Alignment(0.0, -0.70),
                child: new Text(
                  'FIRST',
                  style: new TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: fontSizeFractional,
                    color: Colors.white,
                    fontFamily: 'baron neue',
                  ),
                ),
              ),
            ],
          ),
        );
      }
    }

    class FirstTable extends StatelessWidget {

      @override
      Widget build(BuildContext context) {
        return new Table();
      }
    }

    class Table extends StatefulWidget {
      @override
      TableState createState() => TableState();
    }

    class TableState extends State<Table>{
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: new RaisedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: new Text(
                'Go Back',
              ),
            ),
          ),
        );
      }
    }

I have a theory that the reason it isn't working is that collections.dart isn't actually caching any data as to what page of the index it is on (that could be totally wrong, though).  Curious to hear your ideas!

A: Your problem is that you should directly use controller.page inside the onPressed of your button. instead of instantiating a widget.
Although ultimately you should hide an abstract layer between your gallery class and the list of items.
To do that you can create a custom class which will hols all informations about a gallery item :
@immutable
class GalleryItem {
  final Widget content;
  final Widget details;

  GalleryItem({@required this.content, this.details}) : assert(content != null);
}

Your gallery will then take a list of such class as parameter. And do it's job with these.
Ideally you want to use your gallery like this :
Gallery(
  items: [
    GalleryItem(
      content: Container(
        color: Colors.red,
      ),
      details: Text("red"),
    ),
    GalleryItem(
      content: Container(
        color: Colors.blue,
      ),
      details: Text("blue"),
    ),
  ],
),

The code of such gallery would be :
class Gallery extends StatefulWidget {
  final List<GalleryItem> items;

  Gallery({@required this.items, Key key})
      : assert(items != null),
        super(key: key);

  @override
  _GalleryState createState() => _GalleryState();
}

class _GalleryState extends State<Gallery> {
  final PageController pageController = PageController();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: PageView(
            children: widget.items.map((item) => item.content).toList(),
            controller: pageController,
          ),
        ),
        RaisedButton(
          onPressed: showContentDetails,
          child: Text("More info"),
        )
      ],
    );
  }

  void showContentDetails() {
    final index = pageController.page.round();

    if (widget.items[index]?.details != null) {
      showDialog(
        context: context,
        builder: (_) =>
            GalleryItemDetails(details: widget.items[index].details),
      );
    }
  }
}

class GalleryItemDetails extends StatelessWidget {
  final Widget details;

  GalleryItemDetails({@required this.details, Key key})
      : assert(details != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: details,
    );
  }
}


text:
Q: Python paramiko module - doesn't return full terminal output I'm using Python 3.5. I need to execute a command over ssh and the result I'm getting back is often not what I see in terminal if I executed same command. Often it seems to be cutting it short after first '\n' but other times it works fine. Why is it doing this?
def simple_ssh(zone, cmd):

    # get zone ip address
    machine = socket.getaddrinfo(zone, 22, socket.AF_INET)
    ip_address = machine[0][4][0]
    # print(ip_address)

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(ip_address, port=22, username='xxxxxxxxx', password='xxxxxxxxx', look_for_keys=False)

    data = [None, None]
    _, stdout, stderr = client.exec_command(cmd, timeout=10)
    stdout.channel.recv_exit_status()  # wait till finished
    data[0] = stdout.read().decode("utf-8")
    data[1] = stderr.read().decode("utf-8")
    client.close()

    return data

print(simple_ssh('fetish', "cd /usr/fl/log/ws-fsdb_vol_fetish-images ; grep 'first pass' console.txt"))

Output:
['2019-07-18 11:22:58 fsdb (0 sec, 10.00 ms, 139696900073312): main: first pass: started\n', '']

When same run in terminal:
['2019-07-18 11:22:58 fsdb (0 sec, 10.00 ms, 139696900073312): main: first pass: started\n2019-07-18 11:24:11 fsdb (73 sec, 14050.00 ms, 139696900073312): main: first pass status:complete time:73\n', '']


text:
Q: ¿Cómo deshabilitar el boton cuando los input no tengan cambios? Tengo una consulta y es la siguiente:
Tengo un formulario con datos cargados en los respectivos input y lo que quiero es que cuando no existan cambios en los input el boton se mantenga deshabilitado pero si existen cambios se habilite el boton.

$(document).ready(function(){
            metodos.CambioInputValor();
        });

        var metodos = function(){
            return{
                CambioInputValor:function(){
                    var inivalNombre = $("#idNombre").val();
                    $("#idNombre").on('input',function(){
                        if ( $("#idNombre").val() != inivalNombre ) {
                            $("#btnActualizar").attr('disabled',false);
                        }else{
                            $("#btnActualizar").attr('disabled',true);
                        }
                    });

                    var inivalEdad = $("#idEdad").val();
                    $("#idEdad").on('input',function(){
                        if ( $("#idEdad").val() != inivalEdad ) {
                            $("#btnActualizar").attr('disabled',false);
                        }else{
                            $("#btnActualizar").attr('disabled',true);
                        }
                    });
                }
            };
        }();
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

        <form action="" id="idForm">

                    Nombre
                    <input type="text" id="idNombre" value="Darwin" class="form-control">

                    Edad
                    <input type="text" id="idEdad"  value="27" class="form-control">

            <button type="button" class="btn btn-success" id="btnActualizar">Actualizar</button>
        </form>

A: Prueba lo siguiente:
    var metodos = function(){
        return{
            CambioInputValor:function(){
                var inivalNombre = $("#idNombre").val();
                var inivalEdad = $("#idEdad").val();

                $("#idNombre").on('input',function(){
                    if ( $("#idNombre").val() != inivalNombre || $("#idEdad").val() != inivalEdad) {
                        $("#btnActualizar").attr('disabled',false);
                    }else{
                        $("#btnActualizar").attr('disabled',true);
                    }
                });

                $("#idEdad").on('input',function(){
                    if ( $("#idNombre").val() != inivalNombre || $("#idEdad").val() != inivalEdad) {
                        $("#btnActualizar").attr('disabled',false);
                    }else{
                        $("#btnActualizar").attr('disabled',true);
                    }
                });
            }
        };

<button type="button" class="btn btn-success" disabled = "false" id="btnActualizar">Actualizar</button>


text:
Q: one particular command in bash script doesn't work when run by cron, all other commands do I have a bash script that runs a few commands including rsync and this one below
rm -f $(ls -1t /nas/backups | tail -n +161)

If I execute the script myself on the cli, all commands work. However if run by cron all commands work except the one above.
No idea why. The files in /nas/backups are owned by root, but cron is running as root.
Any ideas? thanks

A: Okay. So I'm a dummy.
My ls command returns a list of file names, not file paths! And cron wasn't running in the correct working directory.


text:
Q: Filter Distinct Values From List of Custom Type F# Given a list of integers, we can do the following to obtain the list of distinct values.
let myList = [ 1; 2; 2; 3; 4; 3 ]
let distinctList = myList |> Seq.distinct |> List.ofSeq

However, in my case I have a list of a custom type defined as follows:
type Listing(fromDate:NSDate, toDate:NSDate, pricePerNight:int, landlordId:String, landlordName:String, listingId:String, pic1url:NSUrl, pic2url:NSUrl, pic3url:NSUrl, pic4url:NSUrl, pic5url:NSUrl, postcode:String, latitude:Double, longitude:Double, location:String, partnername:String,partnerid:String) =
 member this.fromDate : NSDate = fromDate
 member this.toDate : NSDate = toDate
 member this.pricePerNight : int = pricePerNight
 member this.landlordId : String = landlordId
 member this.landlordName : String = landlordName
 member this.listingId : String = listingId
 member this.pic1url : NSUrl = pic1url
 member this.pic2url : NSUrl = pic2url
 member this.pic3url : NSUrl = pic3url
 member this.pic4url : NSUrl = pic4url
 member this.pic5url : NSUrl = pic5url
 member this.postcode : String = postcode
 member this.latitude : Double = latitude
 member this.longitude : Double = longitude
 member this.location : String = location
 member this.partnername : String = partnername
 member this.partnerid : String = partnerid

Next I have a list defined as follows:
let mutable listings : List<Listing> = List.Empty

Now I want to filter this list to obtain only the unique values (a value is unique if it has a unique listingId). I could do this the naive way and add all the listingId to a list of strings, perform the distinct operation on the list of strings and then extract the listings with the ids in the distinct list, but I think there has to be a better approach.

A: You can use Seq.distinctBy with a lambda function to get the value you want for uniqueness:
listings |> Seq.distinctBy (fun l -> l.listingId)


text:
Q: How to run a different query depending on case switch statement? (C#) Here's my code which works up to a point:
var Data = File.ReadAllLines(FilePath).Select(line => line.Split('\t')).ToArray();

int caseSwitch = 0;

if (radioButton1.Checked == true)
{
    caseSwitch = 1;
}
else if (radioButton2.Checked == true)
{
    caseSwitch = 2;
}
else if (radioButton3.Checked == true)
{
    caseSwitch = 3;
}

 var query = from x in Data
             let sw = caseSwitch
             select
                 sw == 1 ? new { Name = x[6], Age = x[2], Date = x[4], Score = x[7]  }
                 : sw == 2 ? new { Name = x[9], Age = x[1], Date = x[0], Score = x[3] }
                 : sw == 3 ? new { Name = x[5], Age = x[8], Date = x[2], Score = x[1] }
                 : null;

It seems the code stops working when I have up to 8 case switch scenarios...the error I seem to get once I have 8 scenarios is "Index was outside the bounds of the array" whilst the ": null;" statement is highlighted in yellow.  What am I doing wrong?

A: "Index was outside the bounds of the array" would indicate that you have a bad index value for x in one (or more) of your cases - the number of switch statements would not cause that error.
Post the line in your select that causes the error.

A: A better way to do this might be to have the query do everything but the select itself. You can then do your switch like this:
IQueryable<whatever> newQuery;
switch (caseSwitch)
{
 case 1: newQuery = query.Select(i => new { Name = i[9], ... }); break;
 case 2: newQuery = query.Select(i => new { Name = i[6], ... }); break;
}

Note that you can't use an anonymous type, but that shouldn't be a problem here. This way, you only send the query you actually want, rather than doing a case on the server.

A: You do not need a conditional statement there at all - since the structure of your query does not change, all you need is a table providing the indexes for Name, Age, Date, and Score columns:
class ColumnIndex {
    int NameIndex {get;set;}
    int AgeIndex {get;set;}
    int DateIndex {get;set;}
    int ScoreIndex {get;set;}
}
private static readonly ColumnIndex[] ColIndex = new[] {
    new ColumnIndex  {NameIndex = 6, AgeIndex = 2, DateIndex = 4, ScoreIndex = 7}
,   new ColumnIndex  {NameIndex = 9, AgeIndex = 1, DateIndex = 0, ScoreIndex = 3}
,   new ColumnIndex  {NameIndex = 5, AgeIndex = 8, DateIndex = 2, ScoreIndex = 1}
,   ...
};
...
int caseSwitch = -1;

if (radioButton1.Checked == true)
{
    caseSwitch = 0;
}
else if (radioButton2.Checked == true)
{
    caseSwitch = 1;
}
else if (radioButton3.Checked == true)
{
    caseSwitch = 2;
}
var query = from x in Data
    select new {
        Name  = x[ColIndex[caseSwitch].NameIndex]
    ,   Age   = x[ColIndex[caseSwitch].AgeIndex]
    ,   Date  = x[ColIndex[caseSwitch].DateIndex]
    ,   Score = x[ColIndex[caseSwitch].ScoreIndex]
    };


text:
Q: kivy, on_enter() does not produce any result, My current function on kivy needs to display json values from a remote url,
when when i click to load the Project Screen, those values needs to be loaded there, however Nothing displays.
here is the screen control function:
import json
import urllib2
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.network.urlrequest import UrlRequest

class MyScreenManager(ScreenManager):
    pass

class IntroScreen(Screen):
    pass

class MainScreen(Screen):
    pass

class MailScreen(Screen):
    pass

class PrjcScreen(Screen):
    def on_enter(self):
        req = urllib2.Request('http://localhost:5000/api/projects')
        response = urllib2.urlopen(req)
        js = json.loads(response.read().decode('utf-8'))
        for k in js:
            layout = GridLayout(cols=2)
            return layout.add_widget(Label(text=js[k]['title']))
class ChatScreen(Screen):
    pass

class GsaMain(BoxLayout):
    pass

class GsamApp(App):
    def build(self):
        return MyScreenManager()

GsamApp().run()

Here is the kv file
<MyScreenManager>:
    IntroScreen:
    MainScreen:
    PrjcScreen:
    MailScreen:
    ChatScreen:

<IntroScreen@Screen>:
    name: 'introscreen'

    canvas:
        Color:
            rgb: 0, 0.267, 0
        Rectangle:
            size: self.size

    GridLayout:
        rows: 1
        size_hint: None, None
        width: self.minimum_width  # combined width of child widgets
        height: self.minimum_height # combined height of child widgets
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}
        spacing: 10

        TextInput:
            id: login
            text: "Login"
            multiline: False
            size_hint: None, None
            height:50
            width: 140
            font_size: 20

        ImgButton:
            size_hint: None, None
            size: 100, 63
            source: 'login.png'
            on_release: root.manager.current = 'main'

<ImgButton@ButtonBehavior+Image>:
    size_hint: None, None

<MainScreen>:
    name: 'main'

    canvas:
        Color:
            rgb: 0, 0.267, 0
        Rectangle:
            size: self.size

    GridLayout:
        rows: 1
        size_hint: None, None
        width: self.minimum_width  # combined width of child widgets
        height: self.minimum_height # combined height of child widgets
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}
        spacing: 70

        ProjButton:
            size_hint: None, None
            size: 100, 63
            source: 'checkl.png'
            on_release: root.manager.current = 'prjct'

        MsgButton:
            size_hint: None, None
            size: 100, 63
            source: 'msgbox.png'
            on_release: root.manager.current = 'main'

        CsCButton:
            size_hint: None, None
            size: 100, 63
            source: 'community.png'
            on_release: root.manager.current = 'main'

        CrCButton:
            size_hint: None, None
            size: 100, 63
            source: 'Checkmark.png'
            on_release: root.manager.current = 'main'

        ExitButton:
            size_hint: None, None
            size: 100, 63
            source: 'exit.png'
            on_release: root.manager.current = 'main'

<ProjButton@ButtonBehavior+Image>:
    size_hint: None, None

<MsgButton@ButtonBehavior+Image>:
    size_hint: None, None

<CrCButton@ButtonBehavior+Image>:
    size_hint: None, None

<CsCButton@ButtonBehavior+Image>:
    size_hint: None, None

<ExitButton@ButtonBehavior+Image>:
    size_hint: None, None

<MailScreen>:
    name: 'mailscreen'
    BoxLayout:
        orientation: "vertical"
        BoxLayout:
            Label:
                text: 'GSAM Mail'
                font_size: 35
        BoxLayout:
            Button:
                text: 'Chat'
                font_size: 25
                on_release: app.root.current = 'chatscreen'

<ChatScreen>:
    name: 'Discussions'
    BoxLayout:
        orientation: "vertical"
        BoxLayout:
            Label:
                text: 'Chat & Discussions'
                font_size: 35
        BoxLayout:
            Button:
                text: 'Home'
                font_size: 25
                on_release: app.root.current = 'main'

<PrjcScreen>:
    name: 'prjct'
    BoxLayout:
        orientation: "vertical"
        BoxLayout:
            size_hint: None, None
            Label:
                text: 'Community Projects'
                font_size: 35
        BoxLayout:
            Button:
                text: 'community Projects'
                font_size: 25
                on_release: app.root.current = 'main'
                GridLayout:
                    id: 'mygrid'
                    cols: 2
                    rows: 4
                    padding: 5
                    spacing: 5
                    Label:
                        text: "Project Title"
                    TextInput:
                        id: ptitle
                    Label:
                        text: "Project Description"
                    TextInput:
                        id: pdescr

Can you please help point out what am I not doing right ?

A: Your on_enter method is returning the layout. You actually need to add the layout to your screen instead (i.e. it doesn't work in the same way as the build method).
However, once you've done that, you would need to be careful that you don't keep adding a new layout each time.
You might be better off having the layout already defined in your KV file and then just use the on_enter method to clear and (re)populate the grid each time the event is triggered.


text:
Q: How to get count of each item in sqlite group by specific column suppose that I have an android sqlite database with person names and place
like :
Names | country | age
Sam  | Canada | 22
Sara | Brazil | 25
Jack | UK     | 20
Anna | Brazil | 29
Jessica | Uk | 20
Steve | UK | 31
Selena | Brazil | 20
Shaki | UK | 27
I want to have each each country with the number of person in it
like this
Uk 4
Brazil 3
Canada 1
how to query this ?!
I queried this
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,KEY_CITY, null, null);

but it's just display the DISTINCT country without the count
thanks

A: try this:
SELECT country, COUNT(*) FROM table WHERE country IN ('UK', 'Brazil', 'Canada') GROUP BY country

A: You can do
Cursor cursor = ourDatabase.query(DATABASE_TABLE, new String[]
                {
                   KEY_CITY
                }, KEY_CITY+ " = 'UK'", null, null, null, null);

int persons = cursor.getCount();

This will give the number of UK occurrences in the KEY_CITY column.


text:
Q: Share session on subdomains in php I have a problem sharing the session between two subdomains, and I've read a lot of threads here and other places.
I have www.xx.com and sub.xx.com and I've set
session_name("PHPSESSXX");
session_set_cookie_params(0, '/', '.xx.com');

and the session.save_path is the same on both domains.
I get a cookie called PHPSESSXX on both domains, and it has the same value.
When I log on to www.xx.com I get a session with some details in it, and it stays that way until I go to sub.xx.com. Then the session on sub.xx.com is empty, and if I refresh www.xx.com, the session there is gone as well. So it does something, but it seems to be overwriting the session data each time I visit a different subdomain.
Any ideas anyone? - Can i debug this somehow?
Btw: I'm using ssl on both domains.
cheers

A: PHP session ids are saved in Cookies. To make a cookie available in all the sub-domains you need to assign it to the root domain. Then all the sub-domains will get the session id from cookie and PHP can find the session using passed session id.
As it turns out, You just need to set the session.cookie_domain to the root domain in php.ini file
session.cookie_domain = ".example.com"
Also check manual for different approaches used to set an ini entry.
Your question is answered here
Sharing SESSION Variables Between Multiple Subdomains

A: My solution was to set a flag in .htaccess like this:
php_flag "suhosin.session.cryptdocroot" 0

And it now works perfectly ;o)
The problem was that Suhosin was installed on the system, and the ini variable
suhosin.session.cryptdocroot = On

encrypted the session files in such a way, that when a different subdomain tried to change the session, it deleted everything for security reasons.
It didn't work for me to set the variable to Off or [nothing] in the ini-file, though maybe I didn't find the right file.
I also tried setting it in PHP without any luck. Like this:
ini_set('suhosin.session.cryptdocroot', 0)

cheers


text:
Q: Severity of exception codes I am trying to sort out error and exception handlers. With a fatal error, I send myself a text message, and with other errors I get an email. (I added the arrays at the end in case they may be useful.)
For errors there is https://php.net/manual/en/errorfunc.constants.php I but cannot find anything similar for exceptions.
I believe I can set my own exception values but are there agreed severity levels for general exceptions, PDOExceptions etc. The only place I find severity mentioned is in ErrorException. (I only use PDOExceptions at the moment but am trying to catch other "general" ones.)
Is a severity helper chart available somewhere? I freely admit I am struggling with exceptions.
PS I had a look at https://www.php.net/manual/en/errorexception.getseverity.php but that looks like it is for errors being sent as exceptions. I am quite confused now.

Error code arrays in case they are useful.
$phpErrorCodes = array (
1   => "E_ERROR",
2   => "E_WARNING",
4   => "E_PARSE",
8   => "E_NOTICE",
16  => "E_CORE_ERROR",
32  => "E_CORE_WARNING",
64  => "E_COMPILE_ERROR",
128 => "E_COMPILE_WARNING",
256 => "E_USER_ERROR",
512 => "E_USER_WARNING",
1024 => "E_USER_NOTICE",
2048 => "E_STRICT  E_ALL",
4096 => "E_RECOVERABLE_ERROR",
8192 => "E_DEPRECATED",
16384=> "E_USER_DEPRECATED",
32767=> "E_ALL");

$phpErrorCodesFatal = array (
1   => "E_ERROR",
16  => "E_CORE_ERROR",
64  => "E_COMPILE_ERROR",
4096 => "E_RECOVERABLE_ERROR");

$phpErrorCodesFatalNumberOnly = array (
    1   ,
    16  ,
    64  ,
    4096);

//4096 recoverable but dangerous so treated as fatal

A: Exceptions
Let me try to clarify some misconceptions here.

Are there severity codes for exceptions?

No. All exceptions are severe.
An exception will stop the execution of your script. They are used to prevent the execution of the code which follows if the preceding code could not be executed.

How do I know if they are important?

All exceptions are important. When an exception is triggered it tells you as a developer that something unexpected has happened in the code. The code which you have written simply did not anticipate this happening and to prevent undefined behaviour it should stop processing immediately.

Unhandled exceptions would show up as PHP Warning. - mario

That is not true. Any unhandled exception will be converted to PHP Fatal error. If your application doesn't know how to handle an exceptional situation then PHP must immediately stop! It is not a warning you can ignore or silence; it's a fatal error.

As a rule of thumb I should treat exceptions as fatal errors?

Not necessarily. In rare cases a developer might expect a particular piece of code to throw an exception, which is possible to recover from or work around. The code logic anticipates something going wrong and has a way around the problem. If the exception is caught and handled this will not result in a fatal error.
The difference between an exception and a fatal error is that you can catch and recover from an exception, but not from a fatal error.

So if I don't do anything then exceptions turn to errors.

If you have not caught the exception and you do not have your own error handled implemented then PHP will default to the built-in error handler. The logic is that it will stop the script and throw an error with the exception as a message. This error will then, based on your configuration settings, either be logged on the server or displayed to the user.
Errors
PHP has a bad history. One of the problems with early PHP versions was that it was very lenient when it comes to badly written code. It would either try to guess what the correct action should be or merely warn the user about some serious problem. The outcome of this was that a lot of developers learned to simply ignore the warnings, notices and sometimes even errors.
With PHP 7 few things have changed.
PHP 7 changes how most errors are reported by PHP. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, most errors are now reported by throwing Error exceptions. An error is still not an exception, but it behaves like one. You can catch the error and if you don't you will still see "Fatal error: Uncaught Error: ...".
Modern PHP functionalities will now use exceptions. This means that userland code should also try to follow the same approach. Throw an exception when your code should stop the execution (don't use die/exit for this) and only catch them when when you know how to recover.
With future PHP releases the notices and warnings might be changed to Error exceptions. Don't ignore them now. Treat all of them as severe problems in your code and fix them now.

A: As per the comments, the general advice with exceptions is that you should catch them all - in that sense, all unhandled exceptions are severe.
However, you could still classify exceptions in your system in the way that you want. Let's say that at the top level of your app you have a call that enters the main app:
try
{
    $this->mainApp();
}
catch (SeriousRuntimeException $e)
{
    $this->handleSeriousError($e);
}
catch (TrivialRuntimeException $e)
{
    $this->handleTrivialError($e);
}

Then in your code you can throw a SeriousRuntimeException or a TrivialRuntimeException as you see fit. In some cases you will have external exceptions to deal with, and you will need to convert them like so:
try
{
    $this->databaseOperation();
}
catch (PDOException $e)
{
    // Copy the exception properties that are important to you.
    // Throw the appropriate severity based on what handler you
    // want to run.
    throw new SeriousRuntimeException($e->getMessage());
}

In this example I assume that both exception types are fatal, but they are handled differently. It is conceivable that you could have an exception type that is so trivial that the app keeps running (e.g. in a listener loop - it logs the fault and then carries on).


text:
Q: find difference of values between 2 array of objects in python I have 2 array of objects:
a = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
b = [{'a': 1, 'b': 2}, {'g': 3, 'h': 4}, {'f': 6, 'e': 5}]

Output:
a - b = [{'c': 3, 'd': 4}] ("-" symbol is only for representation, showing difference. Not mathematical minus.)
b - a = [{'g': 3, 'h': 4}]

In every array, the order of key may be different. I can try following and check for that:
for i in range(len(a)):
   current_val = a[i]
   for x, y in current_val.items:
      //search x keyword in array b and compare it with b

but this approach doesn't feel right. Is there simpler way to do this or any utility library which can do this similar to fnc or pydash?

A: You can use lambda:
g = lambda a,b : [x for x in a if x not in b]

g(a,b) # a-b

[{'c': 3, 'd': 4}]

g(b,a) # b-a

[{'g': 3, 'h': 4}]

A: Just test if all elements are in the other array
a = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
b = [{'a': 1, 'b': 2}, {'g': 3, 'h': 4}, {'f': 6, 'e': 5}]

def find_diff(array_a, array_b):
    diff = []
    for e in array_a:
        if e not in array_b:
            diff.append(e)
    return diff

print(find_diff(a, b))
print(find_diff(b, a))

the same with list comprehension
def find_diff(array_a, array_b):
    return [e for e in array_a if e not in array_b]

A: here is the code for subtracting list of dictionaries
a = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 6, 'f': 6}]
b = [{'a': 1, 'b': 2}, {'g': 3, 'h': 4}, {'f': 6, 'e': 6}]
a_b = []
b_a = []
for element in a:
    if element not in b:
        a_b.append( element )
for element in b:
    if element not in a:
        b_a.append( element )
print("a-b =",a_b)
print("b-a =",b_a)


text:
Q: Hide Column with NULL Value on Report (Oracle Spool) I have data like this :
Name            Birthday             Telephone              Remarks
-------------   --------------       ---------------        ---------------
Andrew          8-Jun-1989           97827197               (null)
John            19-Sep-1988          87920187               (null)

I just wanna show the column that doesn't null on the report. Something like this:
Name            Birthday             Telephone
-------------   --------------       ---------------
Andrew          8-Jun-1989           97827197
John            19-Sep-1988          87920187

How to do that on Oracle Spool? Already tried with NVL and CASE WHEN IS NULL on SELECT statement after or before spool, but that didn't work. Any other way to hide the column with NULL value? Thanks in advance.

A: You can use SET NULL command to fix this.
SQL> set null (null)
SQL> select * from dob;

NAME             BIRTHDAY  TELEPHONE  REMARKS
-------------------- --------- ---------- ----------
john             11-APR-16 984563732  no rem
john             11-APR-16 984563732  (null)

SQL> set null ""
SQL> select * from dob;

NAME             BIRTHDAY  TELEPHONE  REMARKS
-------------------- --------- ---------- ----------
john             11-APR-16 984563732  no rem
john             11-APR-16 984563732

Or if you want to exclude column you can just select columns from tbl.

A: use noprint in column definition.
like,
COLUMN remarks
col remarks noprint
;


text:
Q: Replace Element After 3 Clicks With Cookie Logging [.load] I coded simple jquery code to replace a specific element with urls code after 3 clicks. After it has exceeded 3 clicks it replaces the element with urls code. Using .load(""). But after, I refresh the page the element returns back to its default state, unreplaced. How could, I make webserver remember the change. Whether in the database or in Cookie, sessionStorage, localStorage.
var count = 0;

$(document).ready( function () {
    $("#id-2").on("click", function(){
    count++;
    if(count == 3)
        $("#id-2").load("yoinkexecutor2.html");
    });
});

All, I want is the element to stay replaced with urls code after clicking on it 3 times and not changing back after refreshing the page.

A: You could use localStorage or Cookies.
var count = parseInt(localStorage.getItem("count"), 10) || 0;
function loadMyPage() {
    if (count >= 3)
        $("#id-2").load("yoinkexecutor2.html");
    }
}

$(document).ready( function () {
    loadMyPage();
    $("#id-2").on("click", function() {
        localStorage.setItem("count", count += 1);
        loadMyPage();
    });
});

Remember localStorage (and Cookies) only store values as string, hence parseInt.
Also it will keep loading your .html page after subsequent clicks, you might want to remove the click handler, or remove the #id-2 element.


text:
Q: Implement licensing in SpFx? I have created 4 web parts using SPFX. Now I want implement licensing.
If the user has purchase license then can access web part else user is redirected to license.

*

*What is the best approach to fulfilling this requirement?

*Should I create license component in each web part?

Thanks

A: I won't recommend you to keep your license on the client side. Since the SPFx is completely client side module, anyone can easily go through the code and find all the details, how you are using licensing in you web part.
To your problem, I can recommend using Azure Functions. They are very powerful when it's come to serverless computing (as quoted my Microsoft).
Follow the URL to know more about them. https://docs.microsoft.com/en-us/azure/azure-functions/