Q:

What is happening at the various boundaries of a phase diagram?

Hoping to clarify a few questions I have that the textbook doesn't address.
Lets just say I have a piston (at equilibrium) with 100 moles of gaseous compound that looks like this:

And here is the phase diagram for this compound:
Now lets say I start increasing the pressure on the piston so that the gas starts to approach the gas-liquid boundary.
1.) What would start to happen as you approach the boundary? For example: Would a few moles of gas begin to condense to liquid? Is this process exponential as you approach boundary?
2.) What is happening at the boundary? For example: Are the gas and liquid in perfect equilibrium (50 moles of each)? By that logic, at the triple point, are there 33 moles of each?
3.) Now let's say we approach the critical point along the liquid-vapor boundary. I read online that its when the gas and liquid become "indistinguishable." If so, that means it has a uniform density. Does that make it another state of matter? If not, why is it special?

A:

I got that you are trying to visualize what is actually happening. I have not done the compression myself, but this is what I think will be observed. It will be good if someone with real experience can confirm the answer.

At the beginning you are in the region marked 'vapour'. When you are approaching the liquid-vapour boundary from below, before you touch the boundary, you will still observe only vapour, no liquid at all. You are still in the region marked 'vapour'. Nothing will happen.

When you just reached the boundary, you will see some liquid droplets formed. It should look just like some dew formed at the wall. Regarding the relative amount of liquid and vapour at equilibrium, the pressure of vapour present must be equal to pressure exerted by you (or else the piston will move!) and equal to pressure on the boundary (determined by temperature). Say if you try to push the piston further inside, the volume occupied by sample will decrease, and more liquid formed, but you will still stay on the boundary. You will notice that the pressure needed to push piston inside further does not change, because the pressure of vapour does not change (push in, vapour pressure should increase, but some vapour condensed, lower back the pressure). Only when all vapour has been converted into liquid, you can depart from the boundary, move into the region marked 'liquid'. However, before all vapour turned into liquid, if you stop pushing in and hold your piston still, the liquid and vapour amount won't change. So there is no unique relative amount of vapour and liquid at equilibrium as written in your question. Above liquid-vapour boundary you have only liquid and the piston surface is resting on the liquid surface.

That state is known as supercritical fluid.


Q:

Is Mission Control behavior exposed or how would I hack it?

I haven't written a Mac app in 10 years and will get the terms wrong.
I want to change the default names for Mission Control desktops: Desktop 1, Desktop n, etc. Is there any API that would allow me to intercept or override this naming. Failing that, where would I begin to research how to patch this behavior? Does anyone know of any tutorials for patching Mac system behaviors? Who else tries to do something like this?

A:

"Code injection" is where I need to begin researching.


Q:

Oracle, trigger to control link between tables

I need to create a trigger to control a link between tables. I have the following table structure (image below). an item is linked to a budget and a structure, and this structure should be linked to the same budget.
Sometimes the item receive wrong structures, receive structures different from its own budget budget. I need that when you insert a budget item or edit a budget item to be validated if the id_budget are equal, the id_budget of dg_budget_item is equal to the id_budget dg_budget_structure to which it is being linked

I started building this trigger, but do not know how to continue
CREATE TRIGGER T_BUDGETO_STRUCTURE_ITEM_ID_STRUCTURE
  BEFORE INSERT OR UPDATE OF id_budget_structure ON dg_budget_structure_item
  select id_budget from dg_budget_structure where id_budget_structure = new.id_budget_structure
  FOR EACH ROW
     WHEN (new.id_budget <> ???(result of select?))
  pl/sql_block

A:

This should get you close to what you want
CREATE OR REPLACE TRIGGER T_BUDGET_STRUCTURE_ITEM_ID_STRUCTURE
   BEFORE INSERT OR UPDATE OF id_budget_structure ON dg_budget_item
   FOR EACH ROW
DECLARE
   v_id_budget_structure   NUMBER;
   Budgets_do_not_match    EXCEPTION;
   v_code                  NUMBER;
   v_errm                  VARCHAR2(64);
BEGIN
   SELECT id_budget INTO v_id_budget_structure FROM dg_budget_structure WHERE id_budget_structure = :new.id_budget_structure
   IF :new.id_budget <> v_id_budget_structure THEN
      RAISE Budgets_do_not_match;
   END IF;
EXCEPTION
   WHEN Budgets_do_not_match THEN
      Raise_application_error (-20001,
         'Budget '||TO_CHAR(:new.id_budget)||' for structure '
         || :new.id_budget_structure || 'does not match the budget trying to be linked';
   WHEN NO_DATA_FOUND THEN
      Raise_application_error(-20002,
         'Invalid budget structure ' ||:new.id_budget_structure);
   WHEN OTHERS THEN
      v_code := SQLCODE;
      v_errm := SUBSTR(SQLERRM, 1 , 64);
      Raise_application_error(-20000,
         'Unexpected error ' || v_code  ': ' || v_errm;
END;

You cannot ROLLBACK within a trigger so your application will need to deal with that.


Q:

DoCmd.TransferSpreadsheet Export: Let user choose save destination?

I successfully run TransferSpreadsheet to export an Access query to an Excel file at a specified location:
Private Sub cmdExportQuery_Click()
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "trndOTQry", _
"\\company.com\root\share\public\D2S\D2S\D2S_Scorecard\Trend OT.xls"
End Sub

Given that this is a shared file, I want a dialog to open that allows the user to select whatever save destination he chooses.  I found this link with a good solution that references this article.  When I plug this code into my window:
Private Sub cmdExportQuery_Click()
Dim strSaveAsFilter As String
Dim strSaveAsFileName As String
strFilter = ahtAddFilterItem(strSaveAsFilter, "Excel Files (*.xls)", "*.xls")
strSaveAsFileName = ahtCommonFileOpenSave( _
OpenFile:=False, _
Filter:=strSaveAsFilter, _
Flags:=ahtOFN_OVERWRITEPROMPT Or ahtOFN_READONLY)

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "trndOTQry", _
strSaveAsFileName, , "-1", True
End Sub

I get the error Compile Error: Sub or Function not defined, it highlights ahtAddFilterItem in blue, and highlights Private Sub cmdExportQuery_Click() in yellow with a yellow arrow.  I tried making a Public Sub, but nothing happened when I clicked the button.  What must I do to allow the user to choose the save destination when exporting this query to Excel?

A:

There is additional code that should have also been included.  Check here:
http://access.mvps.org/access/api/api0001.htm
I also found this which may be helpful from someone else who had the same error:
"Did you also get the additional code mentioned in the NOTE
Note: This code still requires the GetOpenFileName routine provided by Ken
Getz. Make sure you copy the function from this article.
which sends you to
http://www.mvps.org/access/api/api0001.htm"


Q:

select * from table does not work

I am trying to do select * from my_table in mysql and it always quits after 2000 rows or so. I have about 10,000 rows. Is this a mysql bug?
EDIT : I am using this class to query. Is it the http connection getting timed out.
<?php
   /**
   * <b>Database Connection</b> class.
   * @author Php Object Generator
   * @version POG 2.6.3 / PHP4
   * @see http://www.phpobjectgenerator.com/
   * @copyright Free for personal & commercial use. (Offered under the BSD license)
   */
Class DatabaseConnection
{
var $connection;
var $databaseName;
var $result;

// -------------------------------------------------------------
function DatabaseConnection()
{
    $this->databaseName = $GLOBALS['configuration']['db'];
    $serverName = $GLOBALS['configuration']['host'];
    $databaseUser = $GLOBALS['configuration']['user'];
    $databasePassword = $GLOBALS['configuration']['pass'];
    $databasePort = $GLOBALS['configuration']['port'];

    $this->connection = mysql_connect ($serverName.":".$databasePort, $databaseUser, $databasePassword) or die ('I cannot connect to the database.');
    mysql_select_db ($this->databaseName) or die ('I cannot find the specified database "'.$this->databaseName.'". Please edit configuration.php');
}

// -------------------------------------------------------------
function Close()
{
    mysql_close($this->connection);
}

// -------------------------------------------------------------
function GetConnection() {
    return $this->connection;
}

// -------------------------------------------------------------
function Query($query)
{
    $this->result = mysql_query($query,$this->connection);
    return $this->result;
}

// -------------------------------------------------------------
function Rows()
{
    if ($this->result != false)
    {
        return mysql_num_rows($this->result);
    }
    return null;
}

// -------------------------------------------------------------
function AffectedRows()
{
    return mysql_affected_rows();
}

// -------------------------------------------------------------
function Result($row,$name)
{
    if ($this->Rows() > 0)
    {
        return mysql_result($this->result, $row, $name);
    }
    return null;
}

// -------------------------------------------------------------
function InsertOrUpdate($query)
{
    $this->result = mysql_query($query,$this->connection);
    return ($this->AffectedRows() > 0);
}

/**
* This function will always try to encode $text to base64, except when $text is a number. This allows us to Escape all data before they're inserted in the database, regardless of attribute type.
* @param string $text
* @return string encoded to base64
*/
function Escape($text)
{
    if ($GLOBALS['configuration']['db_encoding'] && !is_numeric($text))
    {
        return base64_encode($text);
    }
    return mysql_escape_string($text);
}

// -------------------------------------------------------------
function Unescape($text)
{
    if ($GLOBALS['configuration']['db_encoding'] && !is_numeric($text))
    {
        return base64_decode($text);
    }
    return stripcslashes($text);
}

// -------------------------------------------------------------
function GetCurrentId()
{
    return intval(mysql_insert_id($this->connection));
}
   }
   ?>

A:

First thing to troubleshoot is "SELECT * FROM tbl" from any db admin application (phpmyadmin, etc).  That application should give you timing information to see how long the query takes.  Usually, just a SELECT ALL of 10,000 records should take just a few ms.
Next thing is to try "SELECT * FROM tbl" from just a blank PHP script using direct mysql_x functions only - no wrapping in other functions or classes.  Just a small script to fetch all rows in a loop and output some incremental count.
Next thing is to not use your Result($row,$name) method.  Even PHP suggests not using mysql_result() on large result sets.  Instead, use mysql_fetch() or similar function to pull an array from the record, then iterate over that.
Also, check your server and PHP error logs closely and make sure PHP error reporting is on full.  You may see a PHP timeout error or a memory limit error.


Q:

saving selected value from listview or checkbox

I was wondering if someone could help me in the right direction.
How could i save what a user has selected from list view items or a checkbox? When views are switched selected values are not saved. Thanks!

A:

Look into the SharedPreference class. It's the standard way to say things like that.


Q:

Making an efficient constant current source

I need help making an efficient constant current driver.
I want to power my home with LED light strips for lighting and decorative purposes. I need to be able to turn each strip on and off individually.
I need 31 small strips in total. Each strip will have 8 LEDs in series. I want to run each strip at 21.04 volts, 55mA.
The best idea I have so far is a 24v constant voltage power supply and having a simple constant current circuit before each light strip as follows:
https://drive.google.com/file/d/1tjypDpxaherSxHHoGxFWdlf8oasYxr5i/view?usp=drivesdk
Or a variation of the constant current circuit as follows:
How can I efficiently drive an LED?
https://www.instructables.com/id/Circuits-for-using-High-Power-LED-s/
https://www.radio-electronics.com/info/circuits/transistor/active-constant-current-source.php
https://www.electronics-notes.com/articles/analogue_circuits/transistor/active-constant-current-source.php
I don't quiet understand the advantage of adding a second transistor or using multiple zener diodes and I need your help to decide on a circuit. I know its got something to do with temperature stability and/or stabilising variation in current. I'll also need help picking out the transistors as I'm not quiet sure how to pick the most efficient one.
Unless there is an alternative way that you guys recommend that would be cheaper or more efficient?
Should I try to arrange my LEDs differently?
I need the constant current circuit to be on the cheap side as I'll need 31 of them so buck convertors/expensive ICs might be out of the question.
Thanks in advance

A:

I suspect you're overthinking your problem. Maybe not, but probably.
There are two questions you need to ask:
1) How stable is your 24 volt supply?
2) How precisely do you need to control your LED current?
You specify 21.04 volts and 55 mA for your LED string. First off, using 4 significant figures for LED voltage shows that you don't really understand the variability of LEDs. Second, since you are looking at using these LEDs for "illumination and decorative purposes", I suggest that controlling current to more than 10% is a big waste of time. You simply won't be able to see smaller differences. For some reason you seem to have settled on a forward voltage of 2.63 volts for your LEDs. This will change with, among other things, LED temperature, and you are assuming a stability which simply won't occur.
So, what I'd do is the simplest possible circuit:

simulate this circuit – Schematic created using CircuitLab
The resistor should be a 1/4 watt unit, with some airflow to cool it. Don't pack all 31 units into a tiny sealed box. If you do, since they dissipate a total of about 5 watts, they'll get hot and either fail or burn something.
You will encounter statements about how switching regulators are preferred for LED control due to their better efficiency. That's true in general, but it's not much of an issue here. A simple resistor in this case will have an efficiency of about 87% (21/24) and that is right up there with switchers. Plus, this circuit is the ultimate in simplicity and low cost, both of which I suspect are good things for a first project. So don't sweat it.
Look - you plan on doing this, right? So you'll need to buy the LEDs no matter what controller you use. Buy the LEDs and a few resistors, then make a preliminary, simple version. Try it. If that is satisfactory, there is no need to get more complicated.


Q:

what are the differences between inventory and products in a POS system?

I'm trying to make the database system point of sale, however I am confused between the entity and product inventory entity. What are the differences between product and inventory?
I know that the inventory should control the amount of product available .... but i have all that in products.
product code
name
description
cost
unit price
Subcategory code
brand code
amount available
Minimum quantity for rehearing
state
tax code
weight
amount wholesales
wholesales price
perishable
due date
creation date
upgrade date

what i should have in inventory? I have researched and according to what I read I need to have the product, the description, the quantity, purchase price, sale price, profit or gain and date of the transactions. But almost everything is in the Products table, what should I do?

A:

I think you can store the inventory in the products table. There will certainly be transaction tables for purchases for the products and sales and even adjusting records (when items get count and the number differs from what's stored in the database), but you can easily work with the stock stored in the production table itself, thus not having to scan the whole database and sum up all purchases and sales and corrections every time (and never being able to delete old transaction data from the database, as that would invalidate the calculations).
However there are reasons to have stock stored in an inventory table instead. For instance if you want to store different statusses, e.g. you have 100 pieces in store plus twenty just arrived and still unchecked. Or you have a store with goods plus a warehouse housing additional stock. Or you have charges (different model numbers for example for a slightly altered product) which you offer as the same product, but still want to know how many old and how many new ones are in stock. And so on.
So make your mind up, if you want to store additional data with product stock, which would result in an 1:n relation instead of 1:1 which you have now.


Q:

Storing user activity in database in JSP/Java

I'm currently working on a project in JSP. How do I store the user login & logout time and the current no. of users online in database? Also I want to check this as an admin and not as a user?

A:

How do I store the user login & logout time and the current no. of users online in database?

Here’s a simple HttpSessionListener example to keep track the total number of active sessions in a web application. If you want to keep monitor your session’s create and remove behavior, then consider this listener.
Sample code:
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionCounterListener implements HttpSessionListener {

  private static int totalActiveSessions;

  public static int getTotalActiveSession(){
    return totalActiveSessions;
  }

  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
    totalActiveSessions++;
    System.out.println("sessionCreated - add one session into counter");
    // database call to log the log in event of the user with current time
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
    totalActiveSessions--;
    System.out.println("sessionDestroyed - deduct one session from counter");
    // database call to log the log out event of the user with current time
  }
}

web.xml
<web-app ...>
    <listener>
        <listener-class>com.x.y.z.SessionCounterListener</listener-class>
    </listener>
</web-app>

How it work?

If a new session is created , e.g request.getSession(); , the listener’s sessionCreated() will be executed.
If a session is destroyed, e.g session’s timeout or session.invalidate(), the listener’s sessionDestroyed() will be executed.

Sample code:
HttpSession session = request.getSession(); //sessionCreated() is executed
...
session.invalidate();  //sessionDestroyed() is executed

For more info visit mkyong.com from where this example is referred.


Q:

Is there a way to post Webhook notification data to Salesforce

Is there a way to post Webhook notification data to Salesforce? If not, and I must post notification data to my own server, how can Salesforce retrieve the data from my server?
Is there a workaround where I don't have to use my own server as a middleman?
Thank you,
AB

A:

Webhook looks like you are talking about JIRA integration with salesforce.
Yes. I worked on this...
There are two part for this integration

Salesforce part.
Jira Part.

You need to create a rest service on salesforce end
https://forceadventure.wordpress.com/2013/01/31/creating-a-custom-rest-api-in-salesforce/
Also You need to create a site so that webservice will be available without login to org..
Once your rest service and your site is ready...
So Now if I want to access that rest service then I need to use url like
https://site-name-here.force.com/services/apexrest/your rest service end point here.
Next Jira webhook part....
You need to use above url in Webhook.. Add url and select events when post methods should called...
And just setup completed.. You will recevice all JSON data from JIRA to salesforce...
Good Luck..


Q:

Two class in a Single File

I'm preparing the OCA Java 8 Certified Exam.
In the book says:

If do you have a public class, it needs to match the filename. public
  class animal2 would not compile in a file name Animal.java. The sample
  code is:

public class Animal{
private String name;
}
class Animal2{

}

But, if I create a Java file called "Animal.java", I put the code inside and compile it, the compiler generates two java class, "animal.class" and "animal2.class".
Is the study guide wrong?

A:

Basically the book is saying that if a file is named Animal the public class must also be called Animal, otherwise, there is an error.
class Animal2 isn´t public that's why it compiles fine.
What you can do is have a public class within a public class:
public class Animal{

    public class Animal2{
        ...
    }

    ...

}

This is not possible:
public class Animal{
      ....
}

public class Animal2{
      ....
}


Q:

Refresh a PHP required file within a specific intervals

I tried these:

<?php require('newses.php'); ?>

But it didn't worked for me.
Please visit these pages:
Reload the content of a div afer regular interval of time
http://devzone.co.in/automatically-refresh-html-page-div-specific-time-interval/

A:

I found the answer my self.
There was a small problem in my code.
I was wanting my page to include newses.php file in my page, and refresh the same file (newses.php) after every 1 seconds. The JavaScript code had a small problem. The refresh page's code name was load.html,so that the browser tries to load load.html page after 1 sec of first web page loading.
When I changed refresh code from  $("#result").load("load.html");// a function which will load data from other file after x seconds to  $("#result").load("newses.php");// a function which will load data from other file after x seconds, my page became totally working correctly.
Here is the edited code.
       function autoRefresh_div() { $("#result").load("newses.php");// a function which will load data from other file after x seconds } setInterval('autoRefresh_div()', 1000); // refresh div after 5 secs


Q:

Associating child to it's parent's parent?

In OpenERP I have 3 models, A, B and C. If you start on the form for A, there is a tree list of children B. when you click on one of those B children that form has a tree list of children C. I need the C children to be associated to both parents A and B but they will only associate themselves with B despite having many2one fields for both A and B. How can I force this association?
I have looked at solutions using active_id and default_get without success. The context object seems useful for this but I see no way of dynamically setting it with ids for both parent objects as I drill down from A to C navigating through the forms. I don't understand why context is not normally used for holding the context in this manner like in various web frameworks.
To clarify, when I edit object A and from it's edit form create an instance of B and from B's edit form create an instance of C how do I make the C associated to A and B?
Should I just execute a simple update with subselect query in C's create method to make this happen or will that break the ORM?
Looking at the transaction data when I save a new C instance (document) I see that everything I need in terms of ids is within the transaction but I don't know how to access and manipulate the values as I need to e.g.
{
   "jsonrpc":"2.0",
   "method":"call",
   "params":{
      "model":"dbe.vendor",
      "method":"write",
      "args":[
         [
            3
         ],
         {
            "application":[
               [
                  4,
                  2,
                  false
               ],
               [
                  1,
                  21,
                  {
                     "documents":[
                        [
                           4,
                           37,
                           false
                        ],
                        [
                           4,
                           35,
                           false
                        ],
                        [
                           4,
                           46,
                           false
                        ],
                        [
                           4,
                           36,
                           false
                        ],
                        [
                           0,
                           false,
                           {
                              "state":"new",
                              "name":"order of precendence test",
                              "description":"TESTING",
                              "type_of":7,
                              "locked":false,
                              "note":false,
                              "datas":false,
                              "datas_fname":false,
                              "type":"binary",
                              "application_id":false,
                              "certification_id":false,
                              "vendor_id":3,
                              "message_follower_ids":false,
                              "message_ids":false
                           }
                        ]
                     ]
                  }
               ]
            ]
         }
      ],
      "kwargs":{
         "context":{
            "lang":"en_US",
            "tz":"EST",
            "uid":7
         }
      },
      "session_id":"303ae4c1bd9d49079c4efc9e06e0184f",
      "context":{
         "lang":"en_US",
         "tz":"EST",
         "uid":7
      }
   },
   "id":"r138"
}

NOTE: I manually inserted vendor_id because it is a required field but it is the field I want to automatically populated.

A:

Perhaps I am not literate enough with OpenERP to make this association happen properly or there isn't enough relevant documentation or the ORM isn't designed for this use (or any combinations of these) but I need this to work as per my requirements and now it does. I apologize if it is offensive in any manner. Criticisms and advice always welcome.
def create(self, cr, uid, vals, context=None):
    """Creates a new dbe.document instance. Called by both internal app and client.
       documents are associated to dbe.vendor, dbe.application and dbe.certification.
    @param vals: All dbe.document field values as a dictionary.
    @return ID of new dbe.document instance.
    """
    if context is None:
        context={}

    doc_id = None
    association_id = None
    # vendor_id is passed with vals when documents are created from the client side.
    new_vendor_id = vals.get('vendor_id',False)
    if new_vendor_id:
        doc_id = super(dbe_document,self).create(cr, uid, vals, context=context)
        _logger.debug("<CREATE> DBE Document (%d) created for vendor #%d by user %d", doc_id, new_vendor_id, uid)
    else: # within OpenERP we cannot get vendor_id from context so we do it caveman style.
        doc_id = super(dbe_document,self).create(cr, uid, vals, context=context)
        association_id = self.read(cr, uid, doc_id, ['application_id', 'certification_id'], context=context)
        if association_id['application_id']:
            application_id = association_id['application_id']
            application_obj = self.pool.get('dbe.application')
            application = application_obj.browse(cr, uid, application_id)
            new_vendor_id = application.vendor_id.id
        elif association_id['certification_id']: # since there is no application maybe its a certification related doc....
            certification_id = association_id['certification_id'][0]
            certification_obj = self.pool.get('dbe.certification')
            certification = certification_obj.browse(cr, uid, certification_id)
            new_vendor_id = certification.vendor_id.id
        else:
            raise osv.except_osv(_('ValidateError'), _('<CREATE> A DBE Document cannot be created without an application or certification - Association Missing!'))

        if new_vendor_id: # brute-force association to dbe.vendor.
            vals.update({'vendor_id': new_vendor_id})
            self.write(cr, uid, doc_id, vals, context)
            _logger.debug("<CREATE> DBE Document (%d) created for vendor #%d by user %d", doc_id, new_vendor_id, uid)
        else: # too bad - no vendor, no doc.
            _logger.debug("<CREATE> DBE Document (%d) removed because vendor_id missing for user %d", doc_id, uid)
            raise osv.except_osv(_('ValidateError'), _('<CREATE> A DBE Document cannot be created without selecting a Vendor - Vendor Id Missing!'))

    return doc_id


Q:

Pandas: How to group (and sum) by category and retain information from subcategory

This is a follow-up question to Pandas: How to subset (and sum) top N observations within subcategories? There it was demonstrated how you could find the sum of the top 3 months for each year in this dataframe:
Example dataframe
    year      month   passengers
0    1949    January         112
1    1949   February         118
2    1949      March         132
3    1949      April         129
4    1949        May         121
5    1949       June         135
.
.
.
137  1960       June         535
138  1960       July         622
139  1960     August         606
140  1960  September         508
141  1960    October         461
142  1960   November         390
143  1960   December         432

So that you'd end up with this:
    year  passengers
0   1949         432
1   1950         498
2   1951         582
3   1952         690
4   1953         779
5   1954         859
6   1955        1026
7   1956        1192
8   1957        1354
9   1958        1431
10  1959        1579
11  1960         176

The number 432 for 1949 is the sum of 148+148+136 for the months July, August and September.
My question now is this:
Is it possible to do the same calculations, and at the same time keep the corresponding subcategories as a list in it's own column?
Desired output
(I've only checked the actual sum for 1949. 1950 is made up):
        year  passengers  months
    0   1949         432  July, August, September
    1   1950         498  August, September, December
    2   1951         582  .
    3   1952         690  .
    4   1953         779  .
    5   1954         859  .
    6   1955        1026  .
    7   1956        1192  .
    8   1957        1354  .
    9   1958        1431  .
    10  1959        1579  .
    11  1960         176  .

Reproducible code and data:
import pandas as pd
import seaborn as sns
df = sns.load_dataset('flights')
print(df.head())

df2 = df.groupby('year')['passengers'].apply(lambda x: x.nlargest(3).sum()).reset_index()
print(df2.head())

df:
   year     month  passengers
0  1949   January         112
1  1949  February         118
2  1949     March         132
3  1949     April         129
4  1949       May         121

df2:
   year  passengers
0  1949         432
1  1950         498
2  1951         582
3  1952         690
4  1953         779

Thank you for any suggestions!

A:

Use  custom function with GroupBy.apply, idea is sorting first by sort_values and then call head for top values per groups:
def f(x):
    x = x.head(3)
    names = ['passengers','months']
    return pd.Series([x['passengers'].sum(), ', '.join(x['month'])], index=names)

df2 = df.sort_values('passengers', ascending=False).groupby('year').apply(f).reset_index()
print(df2.head())
   year  passengers                   months
0  1949         432  July, August, September
1  1950         498  July, August, September
2  1951         582  July, August, September
3  1952         690       August, July, June
4  1953         779       August, July, June

A:

Alternatively - group, then apply using pd.DataFrame.nlargest instead of a custom function/lambda then regroup on the index and apply suitable aggs, eg:
new_df = (
    df.groupby('year').apply(pd.DataFrame.nlargest, 3, 'passengers')
    .groupby(level=0).agg({'passengers': 'sum', 'month': ', '.join})
    # optionally reset index
    # .reset_index()
)

That'll then give you:
      passengers                    month
year
1949         432  July, August, September
1950         498  July, August, September
1951         582  July, August, September
1952         690       August, July, June
1953         779       August, July, June
1954         859       July, August, June
...

Seems that year as an index makes sense in the resultant frame, but apply a .reset_index() if not.


Q:

GIMP: increase transparency with the distance from image's center

I want to apply a transformation on my image which will cause that:

Image will be at zero transparency in its center
With increasing horizontal distance from the center the image will smoothly become more and more transparent
In the edges the image will be fully transparent

Is there any function in GIMP which can do this?

A:

What you want is a gradient. Read more about Gradients in the GIMP User Manual. Below is how you can accomplish what you describe.

Add a layer mask

Do this by right-clicking the layer, then Add Layer Mask. Use "White (full opacity)"

Select the Gradient took (shortcut L)
In the tool options, change the shape to "Radial"
In the tool options, click the <-> button next to "Gradient". If you don't, you'll have a transparent center and gets more solid as you go out.
Click and drag from the center of the image to the edge.


Q:

How do I change my sword in assassin's creed 2

I bought the sword of Altair and want to fight with it but I have the Florentine Falchion equipped.

A:

You need to go to your Villa and go to the armory/weapons room (it's to your left when you enter), you can change your equipment there. The room right after that is where you can switch out armor sets.


Q:

Basic Algorithm for Types of Triangles

Hi there I need to write algorithm which reads the largest angle of a triangle and the three sides from left, right then bottom. Then based on those results it outputs the specific angle/side triangle.
The specific triangles are acute scalene, right scalene, obtuse scalene, acute isosceles, right isosceles, obtuse isosceles and an equilateral triangle.
We have to write a basic algorithm in pseudocode. I honestly have no idea where to start, any help would be appreciated.

A:

You just need to come up with a series of tests to apply to the triangle. Imagine you are designing the layout of a factory, and these triangles are coming down a conveyor belt past a series of workers. Each worker can check something about the triangle, and then put it into a bin based on its type or move it onto another conveyor belt to go past more workers who will do more tests on it.
For example, you can easily test if it is equilateral by checking if all the sides are equal and if so you can just output that and stop there.
If not, then it must be scalene or isoceles.
If the largest angle is smaller than 90 degrees, it's acute. If it's equal to 90 degrees then it's a right angled triangle, if it's greater than 90 degrees then it's obtuse.
If two of the sides are of equal length then it's isoceles, otherwise it's scalene.
Start by sketching out a decision tree or flowchart based on these criteria. Then turn it into pseudocode.


Q:

How to properly pressurize gas pipes?

I am attempting to cycle gases throughout my base but the vent keeps it is saying over pressurized. I have a gas valve connected to my pipe line to reduce the flow as low as possible yet it still says over-pressurized. The same applies when I have the flow set to anywhere up to max. Is there something I am missing?
I have not attempted to mess with rooms by closing them off with rooms that do not allow gas or liquid to flow freely.

A:

Gas vent being overpressurized means the room you're trying to pump the air in (the tile the vent is at to be exact) already has too much gas in it. Currently however the game has a bug where the warning does not go away even when the vent is working fine. For the vent to really stop working due to being overpressurized (you will see the air starting to build up in the pipes and not going out) you need well above 2kg of gas in the room per tile.


Q:

Solving three-variable nonlinear equation systems

A physical problem which I've been studying leads to the following nonlinear equation system to be solved:
$$\alpha\cdot79\cdot A_1 +(1-\alpha)\cdot 1025 \cdot B_1 = C_{11}$$
$$\alpha\cdot145\cdot A_1 +(1-\alpha)\cdot 696 \cdot B_1 = C_{12}$$
$$\alpha\cdot12\cdot A_1 +(1-\alpha)\cdot 1578 \cdot B_1 = C_{13}$$
In these equations, $\alpha$ is an UNKNOWN universal coefficient, $A_1$ and $B_1$ are UNKNOWN variables to be obtained, and $C_{11}, C_{12}, C_{13}$ are KNOWN constants obtained from experiments. In total, we have 9 pairs of $A$ and $B$ to be obtained the corresponding experimental results $C$, for example, the pair of $A_2$ and $B_2$ should hold the following relationship with $C$:
$$\alpha\cdot79\cdot A_2 +(1-\alpha)\cdot 1025 \cdot B_2 = C_{21}$$
$$\alpha\cdot145\cdot A_2 +(1-\alpha)\cdot 696 \cdot B_2 = C_{22}$$
$$\alpha\cdot12\cdot A_2 +(1-\alpha)\cdot 1578 \cdot B_2 = C_{23}$$
and the same for the other $A_n, B_n$ and $C$. But remember, the coefficient $\alpha$ is unknown. Therefore in total there are $2 \times 9 +1 = 19$ coefficients to be obtained from 27 equations.
My question is, what is the best algorithm to obtain the best solution to both the universal coefficient $\alpha$ and the pairs of $A,B$ please? Thank you very much!

A:

The first two equations suffice to determine $\alpha A_1$ and $(1-\alpha) B_1$.
The third equation is either true or false with those values of $\alpha A_1$ and $(1-\alpha) B_1$, so (depending on how $C_{13}$ relates to $C_{11}$ and $C_{12}$) either it makes the system inconsistent or it doesn't add any new information.
Similarly for the other $\alpha A_i$ and $(1-\alpha) B_i$.  If those are all the constraints, you can choose $\alpha$ arbitrarily (as long as it's not  $0$ or $1$), and then find $A_i$ and $B_i$.


Q:

How to make my system delete all the files in a certain directory older than a certain time while keeping the directory structure intact?

I have a directory on my machine, think of it as my own sort of tmp directory, but it's in my ~ directory. And I want to make it so that my system every 3 hours deletes all the files in (though keeping any directory structure intact, but still deleting all the files in all the levels of the directories recursively) that directory which are older than a day.
I am running Ubuntu GNOME 15.10 with GNOME 3.18, can this be done? And if so, how? I would like this to be fully automated with no users interaction needed. This should be something automatically started when I login, so I shouldn't need to run something on every startup.

A:

Using find:
find ~/tmp -type f -mtime +0 -delete

~/tmp is the directory to be searched recursively, change this accordingly
-type f will look for only files
-mtime +0 which will match a file if it was last modified one day or more ago
-delete will just remove the matched file(s)

Here the catch is -mtime +0, most might think of using -mtime +1 but find will ignore any fractional time while calculating days. So, -mtime +1 will match a file if the last modification was made at least 2 days ago.
Quoting man find, -mtime has the same timing convention as -atime:

-atime n
File was last accessed n*24 hours ago.  When find figures out how
  many 24-hour periods ago the file was  last  accessed,  any
            fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago.

Also note that if you want precision, you should look at the -mmin option of find to indicate time in minutes.
To run it periodically after 3 hours, you can add a cron entry.
Run crontab -e and add:
00 */3 * * * /usr/bin/find ~/tmp -type f -mtime +0 -delete

Using zsh to remove the files:
rm ~/tmp/**/*(.-m+0)

Adding to cron:
00 */3 * * * /usr/bin/zsh -c 'rm ~/tmp/**/*(.-m+0)'

A:

You should be able to delete all files older than 1 day in /home/username/directory and all directories below it with:
find /home/username/directory -type f -mtime +1 -delete

And to schedule that command every three hours set it as a cron job:
crontab -e

Then inside the crontab:
0 */3 * * * find /home/username/directory -type f -mtime +1 -delete

Which runs your command every three hours on the hour (i.e. minute 0), so 3:00 am, 6:00am etc.
Go the the cron and crontab manpages for more information on them.


Q:

Android SQLite created database but table can't be found

So I'm trying to fetch data from one of my database tables, could you please check this out for me and see if you can spot the error?
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH, null,
            SQLiteDatabase.OPEN_READONLY);

    Cursor cursor = db.query(TABLE_CLASSES, new String[] { TABLE_C_DAY,
            TABLE_C_NAME, TABLE_C_DAY, TABLE_C_LOCATION, TABLE_C_TIMEHR,
            TABLE_C_TIMEMIN, TABLE_C_DURATION, TABLE_C_ONETIMEEVENT,
            TABLE_C_CTYPE, TABLE_C_OCCURINGWEEK}, TABLE_C_DAY + "=?",
            new String[] { String.valueOf(day) }, null, null, null, null);

Okay so DB_PATH is definitely correct. I tried to close the db connection and it works fine so db works fine and exists.
All of the table column names are correct as these were used in onCreate to create the db and that worked fine. I also tried using
db.rawQuery("SELECT * FROM " + TABLE_CLASSES + " WHERE day = ?", new String[] { String.valueOf(day) });

So when I make the query the app stops and I get a Source code not found message in Eclipse. LogCat says that table 'classes' doesn't exist.
I tried the creation code manually and it worked. Here is the code from onCreate(SQLiteDatabase db);
String CREATE_DB_WITH_INIT_VALUES =
            "CREATE TABLE %1$s (%4$s TEXT);" +
            "INSERT INTO %1$s VALUES('Lecture');" +
            "INSERT INTO %1$s VALUES('Lab');" +
            "INSERT INTO %1$s VALUES('Tutorial');" +
            "INSERT INTO %1$s VALUES('Meeting');" +
            "INSERT INTO %1$s VALUES('Examples Class');" +
            "CREATE TABLE %2$s (%5$s smallint, %6$s varchar(40), %7$s varchar(10), %8$s smallint, %9$s smallint, %10$s smallint, %11$s boolean, %12$s smallint, %13$s smallint);" +
            "INSERT INTO %2$s VALUES(1,'COMP12112 Computation',1.1,9,0,60,'False','Lecture',3);" +
            "INSERT INTO %2$s VALUES(1,'COMP16212 Java OOP 2',1.1,11,0,45,'False','Lecture',3);" +
            "INSERT INTO %2$s VALUES(1,'COMP18111 Distributed Systems','Unix',13,15,60,'False','Lab',3);" +
            "INSERT INTO %2$s VALUES(2,'Tutorial','LF13',15,0,60,'False','Tutorial',3);" +
            "INSERT INTO %2$s VALUES(2,'COMP14111 AI','LF31',10,30,60,'False','Lab',3);" +
            "CREATE TABLE %3$s (%14$s smallint, %15$s smallint, %16$s TEXT, %17$s date);";

    CREATE_DB_WITH_INIT_VALUES = String.format(CREATE_DB_WITH_INIT_VALUES, TABLE_CLASS_TYPES,
            TABLE_CLASSES, TABLE_DEADLINES, TABLE_CT_TYPE,
            TABLE_C_DAY, TABLE_C_NAME, TABLE_C_LOCATION, TABLE_C_TIMEHR, TABLE_C_TIMEMIN, TABLE_C_DURATION,
            TABLE_C_ONETIMEEVENT, TABLE_C_CTYPE, TABLE_C_OCCURINGWEEK,
            TABLE_D_TIMEHR, TABLE_D_TIMEMIN, TABLE_D_DTEXT, TABLE_D_DDATE
            );

    db.execSQL(CREATE_DB_WITH_INIT_VALUES);

This code doesn't crash and all seems fine but then during the query the table can't be found.
Any idea what is wrong?

A:

What you've done is a valid list of SQL statements. The real problem here is that the method execSQL() only allows you the execution of a single sql statement (See documentation here).
If you want to execute multiple statements automatically, I'd write a method that first splits those statements (by the ending semicolon of each one) and then execute each one in a loop, checking for errors in every iteration so that when some sql statement fails, you can throw a SQLException indicating the sql statement that failed. Something like this:
public static void execSQLScript(SQLiteDatabase db, String script) throws SQLException {
    String[] statements = script.split(";");
    db.beginTransaction();
    for(String statement : statements) {
        try {
        db.execSQL(statement); // Seems like this method already throws a decent exception
        }
        catch(SQLException e) {
            db.endTransaction(); // Rolling back the changes done
            throw e;
        }
    }
    db.setTransactionSuccessful(); // Not rolling but commiting changes, since everything went fine.
    db.endTransaction();
}

A:

I'm not a SQL expert but I think your trying to do a little too much when creating the tables. I would suggest creating the table and adding any initial data in 2 different steps.
I don't have any initial data in my database but this is what I'm using to create the table:
createTable = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_ONE + " TEXT," + COLUMN_TWO + " INTEGER," + COLUMN_THREE + " TEXT," +
COLUMN_FOUR + " TEXT," + COLUMN_FIVE + " TEXT)";

db.execSQL(createTable);

Now in your case after creating the table you can then insert the initial data you want. After
db.execSQL(createTable);

use a ContentValues to add the data you need to the database.
contentValues = new ContentValues();
contentValues.putXXX();
// keep adding data
// the insert method will add the data for you.
SQLiteDatabase.insert(TABLE_NAME, null, contentValues);


Q:

Create a table with mysqli prepared statment

`I have the simple this very simple code below:
        $sql = "SELECT * FROM `alerte`";
    $result = $mysqli->query($sql);

if ($result->num_rows > 0) {

    while ($row = $result->fetch_assoc()) {
        echo "
";
        echo "" . $row['nom_alerte'] . "	";
        echo "" . $row['id_priorite'] . "	";
        echo "
";
    }

}

I would like to use a prepared statement but I am not sure how.
$stmt = $mysqli -> prepare("SELECT *
                                FROM `alerte`
                                WHERE `id_alerte` = ?");
$stmt->bind_param('i', $id_membre);
$stmt->execute();

while ($row = $stmt->fetch()) {
    echo "
";
    echo "" . $row['nom_alerte'] . "	";
    echo "" . $row['id_priorite'] . "	";
    echo "
"; }

Can someone point me in the right direction?
solution, thanks for the comment! :
    $id_alerte = '5';
$stmt = $mysqli -> prepare("SELECT  `nom_alerte`,
                                `id_priorite`
                            FROM `alerte`
                            WHERE `id_alerte` < ?");
$stmt->bind_param('i', $id_alerte);
$stmt->execute();

$stmt->bind_result($nom_alerte, $date_debut_alerte, $date_fin_alerte,      $description_alerte, $status, $id_equipe, $id_priorite);

while ($stmt->fetch()) {
echo "
";
    echo "" . $nom_alerte . "	";
    echo "" . $id_priorite . "	";
echo "
";
}

A:

There are two ways, if mysqlnd is installed on your system, you could use ->get_result() method
Or use ->bind_result() if not available to fetch your results from the prepared statement:
->get_result() version:
$stmt = $mysqli->prepare("SELECT * FROM `alerte` WHERE `id_alerte` = ?");
$stmt->bind_param('i', $id_membre);
$stmt->execute();

$results = $stmt->get_result();
while ($row = $stmt->fetch_assoc()) {
    echo "
";
        echo "" . $row['nom_alerte'] . "	";
        echo "" . $row['id_priorite'] . "	";
    echo "
";
}

Or the bind_result() version:
$stmt = $mysqli->prepare("SELECT `nom_alerte`, `id_priorite` FROM `alerte` WHERE `id_alerte` = ?");
$stmt->bind_param('i', $id_membre);
$stmt->execute();

$stmt->bind_result($nom_alerte, $id_priorite);
while ($stmt->fetch()) {
    echo "
";
        echo "" . $nom_alerte . "	";
        echo "" . $id_priorite . "	";
    echo "
";
}


Q:

How to deal with optional arguments when wanting to enable nullable reference types?

I see the great advantage of turning on (non-)nullable reference types, but I have quite a few methods with optional parameters and I am wondering what the right way to correct the warnings yielded by the compiler is.
Making the parameter nullable by annotating the type with ? takes all of the goodness away. Another idea is to turn all methods with optional parameters into separate methods, which is quite a lot of work and yields high complexity (exponential explosion of parameter combinations).
I was thinking about something like this, but I really question if that it a good approach (performance-wise etc.) beyond the first glance:
[Fact]
public void Test()
{
  Assert.Equal("nothing", Helper().ValueOrFallbackTo("nothing"));
  Assert.Equal("foo", Helper("foo").ValueOrFallbackTo("whatever"));
}

public static Optional<string> Helper(Optional<string> x = default)
{
  return x;
}

public readonly ref struct Optional<T>
{
  private readonly bool initialized;
  private readonly T value;

  public Optional(T value)
  {
    initialized = true;
    this.value = value;
  }

  public T ValueOrFallbackTo(T fallbackValue)
  {
    return initialized ? value : fallbackValue;
  }

  public static implicit operator Optional<T>(T value)
  {
    return new Optional<T>(value);
  }
}

A:

This look's like F#'s Option. This can be emulated in C# 8 up to a point with pattern matching expressions. This struct :
readonly struct Option<T>
{
    public readonly T Value {get;}

    public readonly bool IsSome {get;}
    public readonly bool IsNone =>!IsSome;

    public Option(T value)=>(Value,IsSome)=(value,true);

    public void Deconstruct(out T value)=>(value)=(Value);
}

//Convenience methods, similar to F#'s Option module
static class Option
{
    public static Option<T> Some<T>(T value)=>new Option<T>(value);
    public static Option<T> None<T>()=>default;
    ...
}

Should allow code like this :
static string Test(Option<MyClass> opt = default)
{
    return opt switch
    {
            Option<MyClass> { IsNone: true } => "None",
            Option<MyClass> (var v)          => $"Some {v.SomeText}",
    };
}

The first option uses property pattern matching to check for None, while the second one uses positional pattern matching to actually extract the value through the deconstructor.
The nice thing is that the compiler recognizes this as an exhaustive match so we don't need to add a default clause.
Unfortunately, a Roslyn bug prevents this. The linked issue actually tries to create an Option class based on an abstract base class. This was fixed in VS 2019 16.4 Preview 1.
The fixed compiler allows us to omit the parameter or pass a None :
class MyClass
{
    public string SomeText { get; set; } = "";
}

...

Console.WriteLine( Test() );
Console.WriteLine( Test(Option.None<MyClass>()) );

var c = new MyClass { SomeText = "Cheese" };
Console.WriteLine( Test(Option.Some(c)) );

This produces :
None
None
Some Cheese

VS 2019 16.4 should come out at the same time as .NET Core 3.1 in a few weeks.
Until then, an uglier solution could be to return IsSome in the deconstructor and use positional pattern matching in both cases:
public readonly struct Option<T>
{
    public readonly T Value {get;}

    public readonly bool IsSome {get;}
    public readonly bool IsNone =>!IsSome;

    public Option(T value)=>(Value,IsSome)=(value,true);

    public void Deconstruct(out T value,out bool isSome)=>(value,isSome)=(Value,IsSome);
    public void Deconstruct(out T value)=>(value)=(Value);
}

And
    return opt switch {  Option<MyClass> (_    ,false)  =>"None",
                         Option<MyClass> (var v,true)   => $"Some {v.SomeText}" ,                };

Borrowing from F# Options
No matter which technique we use, we can add extension methods to the Option static class that mimic F#'s Option module, eg Bind, perhaps the most useful method, applies a function to an Option if it has a value and returns an Option, or returns None if there's no value :
public static Option<U> Bind<T,U>(this Option<T> inp,Func<T,Option<U>> func)
{
    return inp switch {  Option<T> (_    ,false)  =>Option.None<U>(),
                         Option<T> (var v,true)   => func(v) ,
                       };
}

For example this applies the Format method to an Option to create a Optino :
Option<string> Format(MyClass c)
{
    return Option.Some($"Some {c.SomeText}");
}

var c=new MyClass { SomeText = "Cheese"};
var opt=Option.Some(c);
var message=opt.Bind(Format);

This makes it easy to create other helper functions, or chain functions that produce options


Q:

C# overwrite first few lines of a text file with constant time

I have a text file:
FIRST LINE
SECOND LINE
THIRD LINE
...

I want to overwrite the first line of the file, eg. with "2345"
with the StreamWriter, I can only overwrite the file into:
2345

with
using (StreamWriter newWriter = new StreamWriter(playingFileDirectory, false)){
    newWriter.WriteLine("2345");
}

or
FIRST LINE
SECOND LINE
THIRD LINE
...
2345

with
using (StreamWriter newWriter = new StreamWriter(playingFileDirectory, true)){
    newWriter.WriteLine("2345");
}

However My desired result is:
2345
SECOND LINE
THIRD LINE
...

Is there any quick way (linear time) of doing that?  I have some text that need to be updated whenever the user presses a button.  The database records contains 100,000 lines. I just want to change the first line like in a text editor, but not changing 1 line and rewriting the whole file.

A:

I don't think that is possible out-of-the-box. I would suggest to do the following:

Open the output file for writing;
Write your first few lines;
Open the input file for reading;
Read up to the line you need;
Read the line from input and write it to the output;
Close both.

If you need to, you can first move the input file and write the output file to the original location.
I would advise against the use of File.ReadAllLines if the file is large. It will have an enormous impact on your memory.


Q:

CUPS print file segmentation fault

I am trying to make a CUPS print system. I want to get printer status, how many pages printed sofar etc.
To do that, I am executing example programs given in CUPS examples.
#include <cups/cups.h>
#include <stdio.h>

int main(){

int num_options;
cups_option_t *options;

cups_dest_t *dests;
int num_dests = cupsGetDests(&dests);
cups_dest_t *dest = cupsGetDest("name", NULL, num_dests, dests);
int job_id;

/* Print a single file */
job_id = cupsPrintFile(dest->name, "testfile.txt", "Test Print", num_options, options);

cupsFreeDests(num_dests, dests);

return 0;
}

I compile it using    gcc myfile.c -o myout -lcups
When I try to execute ./myout
I am getting

Segmentation fault

I am using Raspberry-pi 3 board as my CUPS server.
Thanks in advance.

A:

dest is pointing to non-valid address.
cups_dest_t *dest; // declared but not initialized or assigned afterwards

So dereferencing it ( cupsPrintFile(dest->name... ) is UB and can cause SegFault.

This is how you should have used it (taken from here):
#include <cups/cups.h>

cups_dest_t *dests;
int num_dests = cupsGetDests(&dests);
cups_dest_t *dest = cupsGetDest("name", NULL, num_dests, dests);

/* do something with dest */

cupsFreeDests(num_dests, dests);

Update:
Your code doesn't handle some of the variables (i.e. leaves them uninitialized - bad). The first one I see is cups_option_t *options;. Take care of all of your variables, and if that's not working - debug.
int main(){

int num_options;
cups_option_t *options; // add a call to "cupsAddOption("first", "value", num_options, &options);"

cups_dest_t *dests;
int num_dests = cupsGetDests(&dests);
cups_dest_t *dest = cupsGetDest("name", NULL, num_dests, dests);
int job_id;

/* Print a single file */
job_id = cupsPrintFile(dest->name, "testfile.txt", "Test Print", num_options, options); // options is used here but is uninitialized

cupsFreeDests(num_dests, dests);

return 0;
}


Q:

PHP array how to merge

I have this array:
array(9) {
    [0]=>
    string(5) ",103,"
    [1]=>
    string(4) ",12,"
    [2]=>
    string(5) ",123,"
    [3]=>
    string(5) ",135,"
    [4]=>
    string(5) ",148,"
    [5]=>
    string(4) ",27,"
    [6]=>
    string(16) ",30,31,38,39,40,"
    [7]=>
    string(4) ",35,"
    [8]=>
    string(4) ",94,"
}

How can I merge it to an array like this?
$a = array(12, 27, 30, 31, 35, 38, 39, 40, ...)

I tried but got no clue...

A:

The solution using preg_match_all and sort functions:
$arr = [",103,",",12,",",123,",",135,",",148,",",27,",",30,31,38,39,40,",",35,",",94,"];
preg_match_all('/\d+/', implode("", $arr), $m);
$result = $m[0];
sort($result);

print_r($result);

The output:
Array
(
    [0] => 12
    [1] => 27
    [2] => 30
    [3] => 31
    [4] => 35
    [5] => 38
    [6] => 39
    [7] => 40
    [8] => 94
    [9] => 103
    [10] => 123
    [11] => 135
    [12] => 148
)


Q:

Why does this render an empty plot?

I would like to know why this python code:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
x = np.arange(-3,3,100)
y = -(np.arctan(-1/x))
plt.ylim((-1.5,1.5))
plt.plot(x,y)
plt.show()

renders an empty plot, with the axes having my desired limits. Wolfram Alpha assures me that the function should be visible within these limits.
I am completely lost here.

A:

Your range contains only a single point x = [-3], hence you won't plot much.
What you want is to create a linear space using
x = np.linspace(-3,3,100)

Then your function will be visible.
Edit: Explanation of the first sentence:
np.arange(start, stop, step)

This will create a range starting at start, stopping at stop (exclusive) and stepping by step. Thus you start with -3, the next value must be at stride -3 + 100 = 97, but this is not smaller than 3. Thus the range only contains the start number.
np.linspace(start, stop, number) instead will create a range in the interval [start,stop] divided equidistant in number partitions.


Q:

Pen-servo in TOS Assignment: Earth & The Doctor's Sonic Screwdriver

So I just saw Assignment: Earth again and, although I'm not a fan of Doctor Who, Gary Seven's pen-like multi instrument immediately reminded me of the Doctor's Sonic Screwdriver:

Among the things he uses it for:

Disabling the force-field on his cell
Locking / Unlocking doors
Dazing humans so they become compliant
Popping open a panel on the space shuttle

I had dismissed it as coincidence, but then saw this note on Memory Alpha's talk page for the episode:

The device/weapon Seven wields looks awfully like Dr Who's "sonic
  screwdriver". Assignment: Earth aired March 29 1968; the sonic
  screwdriver made its first appearance in an episode of [of the Deep]:
  between March 16th 1968 and April 20th.

So, are the two items related or is it nothing more than a coincidence?
EDIT:

The original teleplay for Assignment: Earth was done on Nov 14, 1966.  This version wasn't connected to Star Trek in any way, and little extra information is given - I have no idea whether or not it contained the pen servo.
The first draft for Assignment: Earth (the Star Trek one) was finished on Dec 20, 1967.
Filming finished on Jan 10, 1968.
I see nothing on when Doctor Who's Fury from the Deep was filmed.

So I'm inclined to say that, if they're related, the Doctor was influenced by one of the two versions of Assignment: Earth.  But that's why I'm asking for sources/quotes.
(Also note that Star Trek's The Squire of Gothos went only 10 days between first draft and filming, so the nearness of the dates isn't necessarily that good an indicator)

A:

Did some research and both devices were introduced within days of each other. But neither team knew of the other or their productions. It's nothing more than an awesome coincidence.

First appearance of the sonic screwdriver in Doctor Who: Fury from the Deep - Part 1 first aired on 16 March 1968
First airing of the Assignment Earth episode: March 29, 1968.

A:

Been doing some extra Googling ever since I posted this, since Thaddeus's answer really didn't satisfy me.  Here's some of the things I'd found:

The original one was either really limited, or just not used very often.  And many of those uses were for the same type of thing (jarring something loose, presumably by sonic waves).  (List of uses)
Only in the early/mid 70s, with the 3rd Doctor, did it gain its myriad of uses.
They do actually look more different than I had first thought.  I had only seen ones like the two in the middle before, but the one on the far left is the version that appeared in Fury of the Deep:

And finally, the thing that actually convinced me - the Sonic Screwdriver most likely came first, if not by name:  "It is possible that the screwdriver had appeared before Fury from the Deep without the Doctor referring to it by that name: the prop used there appears to be one used by the Doctor in many earlier stories, including the First Doctor's sabotage of Dalek equipment as early as the second serial."
This doesn't discard the possibility of later influence, but given how different the Sonic Screwdriver was when it first appeared, the above is what's convinced me that their original conception was unrelated to each other.


Q:

Help me understand when, why and how to edit posts

I recently had an edit rejected and am not exactly sure why this happened. I tried not to change the user's question at all, but just provide a clearer representation of the question for future visitors.
In the past, I've made an edit that corrects spelling and grammar, and it has been accepted.
I've referenced the help section for editing and in my opinion, which can very well be wrong, states a case for my edit that was rejected.

To clarify the meaning of the post (without changing that meaning)

I always try my best to not change the meaning when editing so far, but perhaps I did or went too overboard on the edit. The reason given seems a little abstract to me.

This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer.

I'd very much like not to make the same mistake again and figure out what I did wrong.
Is there an article that explains to newer users, when not to edit? I guess logically it would be if it doesn't fall under the aforementioned reasons, but perhaps an article that goes into details explaining why an edit is bad or good.

A:

A quick glance at the post highlights why one might have rejected it - it changed a lot of stuff.  It's unfortunate that the edit wasn't really perused; you've preserved much of the original intent without any of the jittery English.
Don't let this edit get you down; personally I think you did alright with it.  It makes the question clearer and more concise.
In the future:  persevere.  Things like this will happen, and I don't want to lose someone who's passionate and thorough with their edits because they were senselessly rejected once or twice.  Consider also getting 2K rep so your edits don't have to go through the edit queue.


Q:

Google Cloud Function + Python

Jumping right to it...
I have the following python code in a Google Cloud Function
main.py
import flask, requests

def gce_test(request):
  test = {"data": {}, "meta": {}, "error": {}}

  metadata_server = "http://metadata/computeMetadata/v1/instance/"
  metadata_flavor = {'Metadata-Flavor' : 'Google'}

  gce_id = requests.get(metadata_server + 'id', headers = metadata_flavor).text
  gce_name = requests.get(metadata_server + 'hostname', headers = metadata_flavor).text
  gce_machine_type = requests.get(metadata_server + 'machine-type', headers = metadata_flavor).text

  test["data"]["gce_id"] = gce_id
  test["data"]["gce_name"] = gce_name
  test["data"]["gce_machine_type"] = gce_machine_type

  test["meta"]["metadata_server"] = metadata_server
  test["meta"]["metadata_flavor"] = metadata_flavor
  test["meta"]["metadata_server_full"] = metadata_server + 'id'

  test["meta"]['generator'] = 'google-cloud-function'

  return flask.jsonify(test)

The problem that I am facing is I get a 404 page not found for gce_id, gce_machine_type, gce_name which means the request to the metadata_server is not being made...
My question is how do I make a HTTP Get request to the metadata_server and pass it the instance name as a param...is that doable?

A:

You're currently making requests to the GCE metadata server URL. Cloud Functions run on top of GAE Standard, and as such end up using the http://metadata.google.internal url. I've provided an example that works with the current cloud function to log the project id.
import flask, requests

def gce_test(request):
  test = {"data": {}, "meta": {}, "error": {}}

  metadata_server = "http://metadata.google.internal/computeMetadata/v1/project/project-id"
  metadata_flavor = {'Metadata-Flavor' : 'Google'}

  project = requests.get(metadata_server, headers = metadata_flavor).text
  test["data"]["gce_id"] = project
  return flask.jsonify(test)


Q:

Trying to use CoffeeScript with JQuery, I get a "document is not defined" error

I start like I usually do in javascript, so:
$(document).ready ->

but when I save I get a document is not defined. So far I haven't been able to find how to make it work.
Edit: by save, I meant I was using coffee -w. The error was due to me forgetting to use the -c option.

A:

CoffeeScript is compiled into JavaScript. I'm not sure what you're trying, but in your exact case your CoffeeScript isn't going to look a whole lot different than your JavaScript. Try:
$(document).ready -> alert 'blah'

If that doesn't work, just do a test like
alert document.title

if that doesn't work, I'm going to suggest that you're not running this code inside a browser ;)


Q:

How to install gevent on an updated Ubuntu 14.04

Lately when I try to install gevent 1.0.2 I get the following error:
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DLIBEV_EMBED=1 -DEV_COMMON= -DEV_CLEANUP_ENABLE=0 -DEV_EMBED_ENABLE=0 -DEV_PERIODIC_ENABLE=0 -Ibuild/temp.linux-x86_64-2.7/libev -Ilibev -I/usr/include/python2.7 -c gevent/gevent.corecext.c -o build/temp.linux-x86_64-2.7/gevent/gevent.corecext.o

In file included from gevent/libev.h:2:0,
                 from gevent/gevent.corecext.c:249:
libev/ev.c:45:22: fatal error: config.h: Aucun fichier ou dossier de ce type
 #  include "config.h"
                      ^

compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

What am I missing?  No matter if I install libev-dev or not it keeps stoping at the same error.

A:

Checking the TMPDIR does not have the "noexec" flag.
Alternatively you may run pip with TMPDIR=/home/$USER/tmp pip install gevent.


Q:

Qt - Transform void pointer (raw data) to QImage and display it on label

I access a camera via USB using a library from the manufacturer. I receive the information about an image via a struct:
typedef struct
{
    /*! Buffer handle which contains new data. */
    BUFF_HANDLE hBuffer;

    /* Pointer to the beginning of the image datas (including MetaDatas(1024 bytes) if any) */
    void * pDatas;

    /*! Total Buffer Payload size in bytes (including image, MetaDatas(1024 bytes) and additional bytes required by USB3 protocol */
    size_t iImageSize;

    /*! Width of the image (not including metadata) */
    size_t iImageWidth;

    /*! Height of the image */
    size_t iImageHeight;

    /*! Pixel Type */
    tImagePixelType eImagePixelType;

    /*! Line Pitch: corresponds to the number of bytes between two consecutive lines
      \note if MetaDatas are not activated, Line Pitch is equal to iImageWidth*eImagePixelType
      \note else MetaDatas are located immediately after the number of bytes corresponding to iImageWidth*eImagePixelType
    */
    size_t iLinePitch;

    /*! Buffer BlockId */
    unsigned long long iBlockId;

    ...

} tImageInfos;

All information i have about the image come from tImageInfos struct comments so there are now additional information elsewhere. I know from the tImagePixelType that the image pixel type is 12 bit: Mono12:
/*! Image Pixel Type */
typedef enum
{
    ...
    /*! Pixel Type 12 bit: Mono12 */
    eMono12   = 3
} tImagePixelType;

My goal is to display the image on a QLabel but first i have to use the raw data (pData) and turn it into an image.
With my current approach i just get displayed stripes maybe due wrong processing of the raw data. The procedure happens in a member function of a QMainWindow class:
void TragVisMain::setImageAndShowPicture(QString message, tImageInfos imageInfos)
{
    // Some message
    addMessageLineToLogOutput(message);

    // Create image from raw data
    QImage *img = new QImage(
                (uchar *) imageInfos.pDatas,
                static_cast<int>(imageInfos.iImageWidth),
                static_cast<int>(imageInfos.iImageHeight),
                QImage::Format_Mono
    );

    ui->logOutput->appendPlainText(
        QString("image infos: [ height: %1, width: %2, iLinePitch: %3, adress: %4 ]")
        .arg(
                    // image height
                    QString::number(img->height()),

                    // output width
                    QString::number(img->width()),

                    // iLinePitch
                    QString::number(imageInfos.iLinePitch),

                    // address of pData
                    QString("0x%1").arg((quintptr)imageInfos.pDatas, QT_POINTER_SIZE * 2, 16, QChar('0'))
        )
    );

    this->iv.setImageFromQImage(*img);
    this->iv.show();

    // pixel type is 3 => 12 bit: Mono12
    ui->logOutput->appendPlainText(QString("tImagePixelType: ").append(QString::number(imageInfos.eImagePixelType)));
}

setImageFromQImage:
void ImageViewer::setImageFromQImage(QImage image)
{
    this->ui->imageLabel->setPixmap(QPixmap::fromImage(image));
}

Here is some output I gathered from an image:
image infos: [ height: 1024, width: 1280, iLinePitch: 2560, adress: 0x00000175da5b3040 ]
tImagePixelType: 3

Do you know how to transform the image data from void pointer correctly?
Then please, enlighten me...

A:

Here is a working solution:
cv::Mat openCvImage(1024, 1280, CV_16UC1, imageInfos.pDatas);
openCvImage.convertTo(openCvImage, CV_8UC1, 0.04);
QImage qImage = QImage(
    openCvImage.data,
    1280,
    1024,
    QImage::Format_Grayscale8
);
imageLabel.setPixmap(QPixmap::fromImage(img));
if(!imageLabel.isVisible()) {
    imageLabel.show();
}


Q:

How to use CASE in SQL for different conditions

I am trying to use conditions with case in sql but not getting any proper solution,
Here is my Query :
select users.id
     , friends.user_id
     , friends.friend_id
     , CASE WHEN friends.accept IS NULL THEN  10
             WHEN friends.friend_id = 18 THEN friends.accept = 11
             else friends.accept = Same
END AS friend_status
from users
  left
  join friends
    on users.id = friends.friend_id
 where users.id != 18
 order
    by id asc

I just want that,

WHEN friends.accept IS NULL THEN  10
WHEN friends.friend_id = 18 THEN friends.accept = 11
else friends.accept = Same as in table

Is it possible, If possible Please help me out

A:

Is this what you are trying to do?
select users.id, friends.user_id, friends.friend_id,
CASE
WHEN friends.accept IS NULL THEN 10
WHEN friends.friend_id = 18 THEN 11
ELSE friends.accept
END AS friend_status
from users left join friends on users.id = friends.friend_id where users.id != 18 order by id asc


Q:

How to join strings in a table in kdb?

I would like to join string in kdb but didn't work well. This is the data:
tab:([]service:`CS`CS.US`CS.US_ABC;y:1 2 3)

`CS 1
`CS.US  2
`CS.US_ABC  3

I would like to add :0 and :primary depending on the given parameter. 0 is working now
update service:`$(((string[service],'(":"))),'("C"$string 0)) from tab

If I would like the data to become
`CS:primary 1
`CS.US:primary  2
`CS.US_ABC:primary  3

and the primary is either string or symbol, how could I join?
I am parameterizing the 0 and primary.
Currently, 0 works as follows
update service:`$(((string[service],'(":"))),'( "0")) from tab

but "primary" is not working
update service:`$(((string[service],'(":"))),'( "primary")) from tab

A:

If you want primary to be a parameter rather than a fixed string, the following will work (primary is "no" in this example):
q)update {`$string[y],\:":",x}[primary;]service from tab
service      y
--------------
CS:no        1
CS.US:no     2
CS.US_ABC:no 3

If primary is a fixed string then you can place it inside the lambda in lieu of "x" and replace "y" with "x", yielding the following:
q)update {`$string[x],\:":","primary"}service from tab
service           y
-------------------
CS:primary        1
CS.US:primary     2
CS.US_ABC:primary 3


Q:

18.04 Screen orientation rotates at random after new install

My screen rotation problem seems the same as blimp1899 from Dec 9 which had no answer. My laptop sits on a desk, with 4 cords which make it very difficult to keep picking it up and turning it around to re-orient it. Lap is an HP Pavillion. Has been happening since I finished downloading Ubuntu 18.04 Bionic Beaver.

A:

Please go to Settings -> Devices-> Displays and, as per  https://help.ubuntu.com/stable/ubuntu-help/look-resolution.html
lock the system down into Landscape mode.


Q:

Suggestion: remove "protected" questions from Hot Network Questions list.

I, as a user, got tired of the same situation. I see a question on the Hot Questions list. I know exact answer to it. There is no proper answer to it yet, and sometimes even dangerous advice.
But the question is on some weird SE that I never saw before and it is protected. Basically, about half of all questions that I find on Hot Questions and can answer, are protected against me.
It is very annoying. If I really want to help, I have to walk around that SE, say dumb and obvious things, in hope to get those 10 points quick enough. If whole SE theme is outside my expertise, what I do is basically spamming. So usually I just walk away.
Please remove questions I may not answer from my selection on Hot Questions.

A:

It's not against you. It's to protect the site from answers coming from people with zero experience in the site.
While your answer might be awesome and perfect for the site, more chances that you'll miss the point of that "weird" site, and what you write will, in general, decrease the overall quality of that site.
Bottom line: the system works. Let's not change something that works as intended.

A:

The design intent of HNQ is to provide interesting reading.  The HNQ draws from 170+ sites, so the odds that any given reader will have the expertise to answer a random hot question are very low.
But you're describing a case where the HNQ leads you to a question you can answer, because while you're not an expert on the site's overall topic, you have specific knowledge here.  And when you get there you can't answer because it's protected.  That's frustrating; I've been there too.
HNQ isn't the only path that leads there, though.  I see questions that have been tweeted, questions that are linked from other questions (on other sites), and questions that hit Reddit or other sites.  And if those questions are protected I can't answer them either.
The HNQ is global; there's no per-user filtering (and it would be expensive because of how often the list changes).  The only way to solve your problem would be to bar protected questions from HNQ entirely.  That wouldn't solve the Twitter/Reddit/etc problem, but at least it would stop you from having a bad HNQ experience.  And I should also mention that, as a moderator on a site that often has stuff on HNQ that we'd rather not, I could get behind a "protection blocks HNQ" idea.
Except that the questions that get protected are usually the most popular and active, the ones that -- for better or worse -- will actually draw visitors to the site in question.  I'd like to see changes to HNQ management, including a way (short of closure) for a community to remove a specific question from it, but this proposal seems too heavy-handed.  It's also likely to produce a flurry of anticipatory protections across the network, making it harder for visitors to contribute and help grow our sites and communities.  Maybe that's fine on big sites, but the smaller sites I'm on don't want to pre-emptively drive prospective users away.


Q:

Как правильно составить JOIN запрос MYSQL?

Есть 2 таблицы MySQL: cs_lots и cs_lots_history. Связаны ID->ID_LOT

Нужно написать запрос, который будет выводить ID каждого лота из cs_lots в массив, а так же user_personaname из cs_lots_history если ID=ID_LOT
Запрос, который уже удалось сочинить:
SELECT
    cs_lots_history.*,
    cs_lots.id as csid,
    inv_id,
    inv_assets,
    inv_image,
    inv_color,
    inv_name,
    inv_rarity,
    inv_type,
    inv_price,
    price_ticket,
    places,
    now_places
FROM cs_lots
LEFT JOIN cs_lots_history
  ON cs_lots.id = cs_lots_history.id_lot
WHERE active_lot='1'
  AND user_personaname='@Saundefined'
GROUP BY cs_lots.id;

Но дело в том, что он выводит только 6 лотов, т.к. в таблице cs_lots_history у ника @Saundefined всего 6 покупок (уникальных id_lot). А если их вообще не будет, то результат и вовсе не выведется.
Если же сделать без ника запрос, то выведет все 12 лотов, но тогда смысла от запроса нет, т.к. в массив не попадет купленная вещь этим пользователем.
Как сделать, чтобы выводило все 12 лотов ориентируясь на cs_lots и при этом, если ник не найден в cs_lots_history с id=id_lot, то тогда выводить просто в столбик значение NULL.

A:

Какой-то странный у Вас вопрос. Не до конца понятно, в каком случае такое может понадобиться. Т.е. скорее всего Вы не совсем корректно решаете свою проблему. Более того еще и немного странно запрос пишете =)
Но тем не менее, если Вы хотите вывести все активные лоты с базы, но при этом показать также только историю по нужному нику, тогда что-то вроде этого должно быть:
SELECT l.*, lh.*
FROM cs_lots l
LEFT JOIN cs_lots_history lh ON l.id = lh.id_lot AND
    lh.user_personaname='@Saundefined'
WHERE l.active_lot='1'


Q:

Django - when best to calculate statistics on large amounts of data

I'm working on a Django application that consists of a scraper that scrapes thousands of store items (price, description, seller info) per day and a django-template frontend that allows the user to access the data and view various statistics.
For example: the user is able to click on 'Item A', and gets a detail view that lists various statistics about 'Item A' (Like linegraphs about price over time, a price distribution, etc)
The user is also able to click on reports of the individual 'scrapes' and get details about the number of items scraped, average price. Etc.
All of these statistics are currently calculated in the view itself.
This all works well when working locally, on a small development database with +/100 items. However, when in production this database will eventually consist of 1.000.000+ lines. Which leads me to wonder if calculating the statistics in the view wont lead to massive lag in the future. (Especially as I plan to extend the statistics with more complicated regression-analysis, and perhaps some nearest neighbour ML classification)
The advantage of the view based approach is that the graphs are always up to date. I could offcourse also schedule a CRONJOB to make the calculations every few hours (perhaps even on a different server). This would make accessing the information very fast, but would also mean that the information could be a few hours old.
I've never really worked with data of this scale before, and was wondering what the best practises are.

A:

As with anything performance-related, do some testing and profile your application. Don't get lured into the premature optimization trap.
That said, given the fact that these statistics don't change, you could perform them asynchronously each time you do a scrape. Like the scrape process itself, this calculation process should be done asynchronously, completely separate from your Django application. When the scrape happens it would write to the database directly and set some kind of status field to processing. Then kick off the calculation process which, when completed, will fill in the stats fields and set the status to complete. This way you can show your users how far along the processing chain they are.
People love feedback over immediate results and they'll tolerate considerable delays if they know they'll eventually get a result. Strand a user and they'll get frustrate more quickly than any computer can finish processing; Lead them on a journey and they'll wait for ages to hear how the story ends.


Q:

PowerShell Module Manifest - automatically loading a Required Module

I am creating a module that depends on several other modules that I need loaded into the global environment. I tried creating a script and using ScriptsToProcess to import the modules, but it looks like the check for RequiredModules happens before ScriptstoProcess runs.
Is there a nice, clean way in a Module Manifest to both Require a module and load it automatically if its not already loaded? If the module could not be loaded, then the RequiredModule would throw an error.

A:

PowerShell V3 works somewhat differently. Required modules are now loaded when you load a manifest with that key specified. Also, removing the module does not unload the required module, no matter how that module was loaded. Interestingly, -Force does not seem to show the autoloading of the required module(s).

Edit: If your module is not in one of the default locations, you will need to add the path to that module (or the parent folder under which the module resides) to the $env:PSModulePath variable.

Side note: since PSv3 there is support for the #Requires command in scripts. You can use this to (1) attempt to load a module dependency in your script and (2) terminate if the module is not/cannot be loaded.
#Requires -Modules ModuleName1,ModuleName2

This also needs the modules to be somewhere under $env:PSModulePath, which must be set before running the script.

about_Requires

A:

In PowerShell 3 and up, RequiredModules are automatically loaded
It's also the only way to make sure people using PowerShellGet (i.e. the PowerShell Gallery) install your dependencies, if you're going to distribute the module.
It would still fail if the required modules are missing, but otherwise works exactly the way you'd wish it to.
In PowerShell 2, there's no way to automatically load RequiredModules
In either case, users can manually load the requirements by typing Import-Module RequiredModule, YourModule -- they won't get a second instance if it's already imported ...
You can also specify the module in NestedModules instead. Even in PowerShell 2, those get loaded "inside" your module, but don't seem to negatively affect resources when they're already loaded. However, as @JasonMArcher reminded me, in PowerShell 2, NestedModules get unloaded along with your module if your module gets unloaded (via Remove-Module), and this happens even if they were pre-loaded separately by the user, which can end up producing really weird bug reports since your users won't expect that.
The other option, which works in all versions of PowerShell, is to call Import-Module at the top of your module (in a psm1 script, after checking to make sure the module's not already loaded) with the -ErrorAction Stop set so that the import of your module will fail if the import of the dependent module fails.
if (!(Get-Module Dependency)) { ## Or check for the cmdlets you need
    ## Load it nested, and we'll automatically remove it during clean up
    Import-Module Dependency -ErrorAction Stop
}

Actually, if you wanted to check for versions ...
if (!(Get-Module Dependency | Where { $_.Version -ge "2.5" )) {
    ## Load version 2.5 (or newer), or die
    Import-Module Dependency -Version 2.5 -ErrorAction Stop
}

Just remember that this doesn't serve as documentation, so if you distribute the module, your users will not know about the dependencies.


Q:

How to sort by custom count with postgresql?

I have two tables:
Companies: (id, name)
Workers: (id, name, country)
I would like to get all companies and sort them by numbers of employees from a given country.
For a query looking for companies that have more workers from the USA, the result should give:
#workers from USA | company id | company name
----------------------------------------------
        90              6           foo corp
        45              9           bar corp
        0               3         foobar corp

I tried:
select
    count(w.country='USA') as mycount,
    w.company_id,
    c.company_name
from
    companies c
    left join workers w on
        c.id=w.company_id
group by
    w.company_id,
    c.company_name
order by mycount desc;

But that's counting all workers regardless of their countries.
Any ideas?

A:

You can do that easily with a correlated subquery:
SELECT
  (SELECT count(*) FROM workers w WHERE w.company_id=c.id AND w.country='USA') AS mycount,
  c.id,
  c.company_name
FROM
  companies c
ORDER BY mycount DESC


Q:

Does SpriteKit or SceneKit support multiplayer?

I want to make a multiplayer game with spriteKit or sceneKit with swift
is this possible? if not when will it be and if it is can you give me a good tutorial on it?
Thanks in advance!

A:

Yes it is possible.
But multiplayer doesn't depend on a framework like SpriteKit or SceneKit. You can implement multi-user capabilities in games like you would do it for other things like a chat or something like that.
Simple multi-user frameworks, that apple provides are either the MultipeerConnectivity framework for local multiplayer or, especially for games, GameKit for multiplayer-games over the internet.
There are many tutorials. For GameKit you can check the tutorial on raywenderlich.com. For the MultipeerConnectivity-Framework I'd recommend you to read the documentation.


Q:

Error registering user in Hyperledger fabric v 2.0

I'm trying hyperledger fabric sample(v2.0). My basic network is running fine and i'm able to enroll the admin. however when i tried to register a user, its throwing an error like "Failed to register user "user1": TypeError: gateway.getClient is not a function"
Please find the sample of code below which i'm trying
'use strict';

const { Gateway, Wallets } = require('fabric-network');
const path = require('path');

const ccpPath = path.resolve(__dirname, '..', '..', 'first-network', 'connection-org1.json');

async function main() {
    try {

        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), 'wallet');
        const wallet = await Wallets.newFileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        // Check to see if we've already enrolled the user.
        const userIdentity = await wallet.get('user1');
        if (userIdentity) {
            console.log('An identity for the user "user1" already exists in the wallet');
            return;
        }

        // Check to see if we've already enrolled the admin user.
        const adminIdentity = await wallet.get('admin');
        if (!adminIdentity) {
            console.log('An identity for the admin user "admin" does not exist in the wallet');
            console.log('Run the enrollAdmin.js application before retrying');
            return;
        }

        // Create a new gateway for connecting to our peer node.
        const gateway = new Gateway();

        await gateway.connect(ccpPath, { wallet, identity: 'admin', discovery: { enabled: false, asLocalhost: true } });

        // Get the CA client object from the gateway for interacting with the CA.
        const client = gateway.getClient();
        const ca = client.getCertificateAuthority();
        const adminUser = await client.getUserContext('admin', false);

        // Register the user, enroll the user, and import the new identity into the wallet.
        const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: 'user1', role: 'client' }, adminUser);
        const enrollment = await ca.enroll({ enrollmentID: 'user1', enrollmentSecret: secret });
        const x509Identity = {
            credentials: {
                certificate: enrollment.certificate,
                privateKey: enrollment.key.toBytes(),
            },
            mspId: 'Org1MSP',
            type: 'X.509',
        };
        await wallet.put('user1', x509Identity);
        console.log('Successfully registered and enrolled admin user "user1" and imported it into the wallet');

    } catch (error) {
        console.error(`Failed to register user "user1": ${error}`);
        process.exit(1);
    }
}

main();

Note: I'm able to invoke and query the fabcar samples through cli in container and its working fine. when i tried to achieve the same through SDK its throwing an error " Failed to register user "user1": TypeError: gateway.getClient is not a function ". Any leads would be appreciated.

A:

You need to clone the new copy of registerUser.js file from their offical repository. They have made some modifications to that file in repository. So just take the new copy of the registerUser.js file from their offical repository.


Q:

passing functor to boost::thread failed in visual studio 2010

This simple code won't compile:
#include <cstdio>
#include <boost/thread.hpp>

struct ftor{
   void operator()(){ printf("Hello"); }
};

int main()
{
      boost::thread th( ftor() );

     th.join(); //<--- error C2228: left of '.join' must have class/struct/union
}

But, following code well compiled:
 #include <cstdio>
 #include <boost/thread.hpp>

 struct ftor{
    void operator()(){ printf("Hello"); }
 };

 int main()
 {
     ftor f;
     boost::thread th( f );

     th.join();
 }

Q: What's problem with #1 code ?
I use visual studio 2010 .
Update:
  codepade http://codepad.org/r5Aok406  shows more informative error:
Line 19: error: request for member 'join' in 'th', which is of non-class type 'mythread ()(ftor (*)())'

A:

  boost::thread th( ftor() );

th is declared as a function that returns boost::thread, and takes a function pointer ftor(*)() as input parameter.
To avoid this, either use C++11's new initialization syntax,
  boost::thread th{ ftor() };

Or add a parathesis around the ftor().
  boost::thread th( (ftor()) );

This is actually one of the well-known c++ glitches. The cause of this problem is for C compatibility.
  struct TEST;
  TEST a(); //well defined in c, a is a function that returns TEST

C++ has to be compatible with C, so Test a() must be a function, but not declare a as a TEST instance and call its default constructor!


Q:

Convert Java interface to JSON String using GSON without encapsulating serialization in a JSON object?

Background
I want to serialize an interface into a JSON object. For instance, say I have the following interface:
public interface Person {
    String getName();
    int getAge();
}

Which is implemented by the class PersonImpl:
public class PersonImpl implements Person {
    private String name;
    private int age;

    public PersonImpl(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public int getAge() {
        return age;
    }
}

PersonSerializer.java is used to serialize the interface using GSON:
public class PersonSerializer implements JsonSerializer<Person> {

    @Override
    public JsonElement serialize(Person src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject person = new JsonObject();
        person.addProperty("name", src.getName());
        person.addProperty("age", src.getAge());
        return person; // Breakpoint BP1
    }
}

I then use a GsonBuilder to serialize the interface:
Person person = new PersonImpl("Bob", 42);
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Person.class, new PersonSerializer());
Gson gson = builder.create();
String personAsJsonString = gson.toJson(person); // Breakpoint BP2

Issue
The problem is the Person class is being serialized as follows:
// Not what I want
{
    "person": {
        "name": "Bob",
        "age": 42
    }
}

However, I only want the data within person:
// What I want
{
    "name": "Bob",
    "age": 42
}

Troubleshooting & Debugging
At Breakpoint BP1 (noted via the comment), the String value of person is exactly what I want. However, by Breakpoint BP2, after GSON completes serialization of the interface (i.e. personAsJsonString), it is the undesired result.
How can I get GSON to serialize a custom interface without encapsulating the result in a JSON Object?
Edit (root cause found)
I completely failed to mention that I was using the Decorator Pattern, which happened to be the root cause of the issue.
public abstract class PersonDecorator implements Person {
    protected Person person;

    public PersonDecorator(Person person) {
        this.person = person;
    }

    @Override
    public String getName() {
        return person.getName();
    }

    @Override
    public int getAge() {
        return person.getAge();
    }
}

Below is an example Decorator:
public class MrPersonDecorator extends PersonDecorator {
    public MrPersonDecorator(Person person) {
        super(person);
    }

    @Override
    public String getName() {
        return "Mr. " + person.getName();
    }
}

So the issue happened when creating a Person instance via a decorator:
Person person = new MrPersonDecorator(new PersonImpl("Bob", 42));

In this case, I was not getting a reference to the interface itself, but rather the decorator, which also contains an instance of the interface along with implementing it.

A:

Gson doesn't provide such mechanics (note, that it's not a principal constraint, e.g. Jackson provides it via @JsonUnwrapped annotation or SerializationFeature.UNWRAP_ROOT_VALUE on mapper).
What you can do is to either provide custom serializer for adapter like this:
public class PersonDecoratorSerializer implements JsonSerializer<PersonDecorator> {

    @Override
    public JsonElement serialize(PersonDecorator src, Type typeOfSrc, JsonSerializationContext context) {
        return context.serialize(src.getOriginalPerson());
    }
}

To avoid violating encapsulation you can add package-private getOriginalPerson() method to PersonDecorator and create serializer as inner static class so it can access this method.
Or wrap GSON calls to extract your person value: replace gson.toJson(person) with gson.toJsonTree(person).getAsJsonObject().get("person").toString():
public static String toJson(Person person, Gson gson) {
    JsonObject object = gson.toJsonTree(person).getAsJsonObject();
    // Checks whether Person was PersonDecorator or not
    if (object.has("person")) {
      return object.get("person").toString();
    } else {
      return object.toString();
    }
}


Q:

Number of ways colour $n$ distinct objects with at most $n$ different colours without permutations of colours

Suppose that I have $n$ distinct objects. In how many ways can I colour the $n$ objects with at most $n$ distinct colours up to permutations of colours. For e.g
$1,1,1,1$ is the same thing as $2,2,2,2$
$1,1,2,3$ is the same thing as $4,4,1,2$
but $1,1,2,3$ is different from $2,3,1,1$
My approach is count the number of ways to use exactly $i \leq n$ colours to colour the $n$ objects using the inclusion-exclusion principle then divide by $ \binom{n}{i}$. Then I add everything up. However I'm not sure if the method is correct and I'm also looking for a general solution in terms on $n$.

A:

What you want to count is the number of different partitions of an $n$ element set into $\leq n$ nonempty subsets. The number of these partitions is the Bell number $B_n$. There is a recursive formula for these and an asymptotic formula involving the Lambert $W$-function.