Q:

Juntar Arrays com php

bom galera to fazendo um sistema e preciso retornar valores da sessão e do banco de dados mais queria isso dentro de uma única array, usando a função array_unshift() ele me retorna o seguinte
Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [i_chamada] => 1
                            [i_interacao] => 19
                            [i_tecnico] =>
                            [i_cliente] => 1
                            [descricao] => texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto
                            [status] => N
                            [tecnico] =>
                            [dt_interacao] => 2015-04-02 09:09:25
                            [tempo] =>
                        )

                )

            [__ci_last_regenerate] => 1427979172
            [id_cli] => 1
            [email_cli] => saymon@rodriguesite.net
            [nome_cli] => LM Sistema
            [user_cli] => admin
            [pass_cli] => 123123
            [status_cli] => A
            [dtcad_cli] => 2015-03-31 09:26:38
            [logado_cli] => 1
            [tela] => pergunta
        )

e não consegui achar um forma de mesclar essas duas array, algo como elas ficassem assim:
            Array
        (
            [i_chamada] => 1
            [i_interacao] => 19
            [i_tecnico] =>
            [i_cliente] => 1
            [descricao] => texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto
            [status] => N
            [tecnico] =>
            [dt_interacao] => 2015-04-02 09:09:25
            [tempo] =>
            [__ci_last_regenerate] => 1427979172
            [id_cli] => 1
            [email_cli] => saymon@rodriguesite.net
            [nome_cli] => LM Sistema
            [user_cli] => admin
            [pass_cli] => 123123
            [status_cli] => A
            [dtcad_cli] => 2015-03-31 09:26:38
            [logado_cli] => 1
            [tela] => pergunta
        )

A:

Bom galera consegui resolver da seguinte maneira, na hora que ele retorna a array com os valores do banco tenho algo como
                    [0] => Array
                    (
                        [i_chamada] => 1
                        [i_interacao] => 19
                        [i_tecnico] =>
                        [i_cliente] => 1
                        [descricao] => texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto
                        [status] => N
                        [tecnico] =>
                        [dt_interacao] => 2015-04-02 09:09:25
                        [tempo] =>
                    )

juntei as arrays com array_unshift($array, $array[0]), no segundo parâmetro utilizei o índice.


Q:

RSSI value using MicroPython in NodeMCU ESP8266

How to get the RSSI value of the WLAN device connected to WiFi of my NodeMCU device using MicroPython? Actually I tried the following code but I'm getting an error:
>>> sta_if.ifconfig()
('192.168.1.103', '255.255.255.0', '192.168.1.1', '192.168.1.1')

>>> sta_if.rssi()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'WLAN' object has no attribute 'rssi'

I don't know what I should do to get the RSSI value of the network.

A:

From the WLAN class documentation:

wlan.scan()
Scan for the available wireless networks.
Scanning is only possible on STA interface. Returns list of tuples with the information about WiFi access points:
(ssid, bssid, channel, RSSI, authmode, hidden)


Q:

How to set the number of documents processed in a batch?

With Spark 2.2.0 checkpointing works a little different than the versions. There is a commits folder that gets created and after completion of every batch a file gets written to the folder.
I am facing a scenario where in I have about 10k records and say my streaming job fails at about the middle after it processed 5k records, there is no file written to the  commit folder in the checkpoint directory and hence when I restart the job, it starts from the beginning and there is data duplication of 5k records.
From what I understand, looks like when there is commit file written and when you restart it pick ups from the latest offset otherwise it reprocesses the data in the last successful batch.
How to set the number of documents to be processed in the batch?

A:

Is there a way I could set the number of documents to be processed in the batch?

Use maxFilesPerTrigger for files and maxOffsetsPerTrigger for kafka format.


Q:

can't get frame of collectionViewCell item for transition

I am trying to transition a view into the imageView of a  collectionViewCell of another viewController.  In order to do that I need the frame of the imageView in the collectionViewCell converted to Window.
I am trying to do that using the following in viewWillAppear:
let indexPath = IndexPath(item: 0, section: 0)
let cell = collectionView.cellForItem(at: indexPath) as! ImageCollectionViewCell
let boundingRect = cell.imageView.convert(cell.imageView.bounds, to: nil)

The size of the boundingRect is correct however the origin is at 0,0 for some reason and not where it should be.
I'm wondering if the problem is that the collectionView is not laid out yet and thus the origin is wrong.  If that's the case, how can I force it to layout.  I have tried:
collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()

But that also didn't change the origin.
How could I force the layout of the collectionView and get the frame of a particular cell (or imageView in that cell) prior to viewDidAppear.  I would like to avoid doing it in viewWillLayoutSubviews or viewDidLayoutSubviews to prevent this from constantly being run.

A:

According to https://developer.apple.com/documentation/uikit/uiview/1622498-convert we need:

view (collectionView.superview), where we want to get subview's
location,
subview's frame (cell.imageView.frame)
and subview's superview or superview.superview etc, any view that contains subview's frame (cell)

and we get
let boundingRect = collectionView.superview.convert(cell.imageView.frame, from: cell)


Q:

Is this valid html

<input type="button" class="big" value="Somewhere">

because in IE it doesnt click....any ideas why..all other browsers seem fine

A:

It's invalid HTML — an <input> cannot be as a descendant of an  element:

Source: http://jsbin.com/iyuxeb


Q:

jQuery Mobile get id of clicked item that caused page transition, after page transition has taken place

I have a jquery mobile application with two "pages".  On the first page is a Google map, and on the second page is a listview of buildings, where each list item has an id associated with it.  When the user clicks a building, the map is meant to pan to that building and show a marker.  However, one of the quirks of jquery mobile is that I have to call google.maps.event.trigger(map, 'resize') and map.panTo(somePosition) after the page transition takes place, otherwise the map shows up funky.  I am tapping into the jQuery Mobile pageshow event to do this.  My question is, is there anything either in the pageshow event handler arguments or any way of attaching something to the pageshow event handler arguments that will allow me to identify the id of the list item that was clicked which caused the page transition in the first place, so I can use this to determine where to pan the map to?
At the moment, I'm having to do it in a round about kind of way, where I tap into the click event of the selected list item, store the selected list item id in a global variable and then use that global variable later on when in the pageshow event handler.
So something like:
var selectedBuilding;

$('a.buildingSelect').click(function(e) {
    e.preventDefault();
    selectedBuilding = $(this).attr("data-buildingNum");
});

$('div').live('pageshow',function(event, ui){
    if (ui.prevPage.attr('id') === "buildingSelect") {
        google.maps.event.trigger(map, 'resize');
        map.panTo(selectedBuilding);
    }
});

Apart from being a little messy, one of the problems with this is if the user didn't select a building number at all, such as when they press the 'back' button on the building list page.  In this case, the pageshow event handler still gets executed, though the selected building will be either non existent if the user hasn't selected a building previously, or will cause the map to pan to the last selected building if they have selected a building previously, which isn't actually the intended behaviour.  I am sure I could make some additional global variables available to both event handlers to code around this, but it would be a little messy.  Ideally what I'm looking for is a way to only have to bind to the pageshow event and from within the binded function be able to derive which building id was clicked.
I am still relatively new to jQuery and javascript in general, so please keep this in mind.  Though I've had a bit of a play with the javascript debugging tools in Chrome, I'm still not really sure how I would go about effectively finding what information is made available in the ui argument to the pageshow event handler, which I imagine would be a good start towards solving problems like this.

A:

You could stick the pageshow event handler inside buildingSelect's click handler, and use the syntax that allows you to pass data through event binders: .live( eventType, eventData, handler ) from http://api.jquery.com/live/.
But then you'd have to die the other live pageshow handlers before doing this.  If it was me, I'd just clean up the way you're storing those global variables and call it a day.  Maybe put them in a nice object that sits off a namespace so it's safer.
EDIT:  changed my incorrect colloquial "destroy" to the correct die.  So you would want to die the event handlers as in $('div').die() or any of the other variations explained in the documentation: http://api.jquery.com/die/


Q:

Intersection_inserter was not declared in this scope

I am trying to calculate the overlap area between two ellipses. I am approximating the ellipses with polygons now and I have found an example that apparently used an old version of Boost.Geometry, as per this answer. From the second answer to this question,  I can see that this is an old example as well, since some of the header files are not there in v1.53.
I have replaced those with:
#include <boost/geometry/geometries/adapted/c_array.hpp>
#include <boost/geometry/multi/multi.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/io/wkt/wkt.hpp>
#include <boost/geometry/multi/geometries/multi_polygon.hpp>

and also added this code:
typedef boost::geometry::model::d2::point_xy<double,
boost::geometry::cs::cartesian> point_2d;
typedef boost::geometry::model::polygon<point_2d> polygon_2d;

and almost everything works. The only problem is with this:
polygon_2d poly, poly2;
typedef std::vector<polygon_2d > polygon_list;
polygon_list v;
intersection_inserter<polygon_2d >(poly2, poly, std::back_inserter(v));

I am getting an error:
intersection_inserter was not declared in this scope
expected primary expression before '>' token

The documentation of boost on the matter here is from 2009, so I guess it does not apply anymore... Their example is written the same as mine, as far as I can tell. I have found the place on the header file intersection.hpp where intersection_inserter is defined but I cannot make heads or tails of it...
I am getting the same error both in VS2012 in win7 and Qt 4.7.4 in Linux Mint 14. Any help would be greatly appreciated!

A:

I cannot find any reference to intersection_inserter in the current boost documentation. Perhaps this functionality has been removed?
It seems that the "official" way to calculate intersections in boost::geometry is through the intersection function, as documented (with example) here


Q:

Schedule PHP script to execute via cron

I have a script that will update some columns on my database. It is written in PHP, I execute it via URL (eg. http://foo.com/xyz/yzx/dbupt8r). I did this using crontab -e then curl on the script URL, because on my mind it is like somehow similar of what I am doing: accessing it via URL. Is there any advisable or better way of doing this? Am I at security or threat flaws?

A:

There are two ways to do this, the way that you're already doing it: (curling a publicly accessible URL); or executing the PHP script directly from your crontab.
Cron Curling
As you mentioned, this is often very convenient and comfortable since you're already developing a web application in PHP and so it's the way you're already working. There are a few risks:

Most importantly, security: You'll want to ensure that input is properly filtered, there are no risks of SQL injection, etc., in case someone discovers the URL and tries to take advantage of it. Hopefully you're covering most of this anyway since you're developing a web application.
Frequency & concurrency: You're scheduling it's execution from cron, so are there any issues if someone else starts calling the URL and making it fire more frequently or at the same time as a scheduled run is occurring?
Relying on curl: It also means you're relying on curl to execute your script, so you're opening yourself up to many points of failure (curl itself, DNS, etc.).

Running PHP from Cron
Alternatively, you may be able to run the script directly from your crontab. There are two ways of doing this:

Passing the PHP script to the PHP interpreter binary, which would look something like this (note the path to your PHP binary varies by platform, but should be specified as an absolute path as cron doesn't have access to many environment variables):
*/15 * * * *    /usr/bin/php -f /path/to/php/script.php

Alternatively, you can add a hashbang/shebang line to the first line of the PHP script as follows:
#!/usr/bin/php

Make it executable, for example:
chmod 755 /path/to/php/script.php

And add it directly to your crontab:
*/15 * * * *    /path/to/php/script.php

The advantages of this method are that you can put the script in a location that's not publicly accessible so you can ensure tighter control over its access & execution. It may also mean you can write lighter code if you don't have to handle the web side of things. That said, if you're using a PHP framework, you may find it difficult to develop a stand-alone script such as this.


Q:

Questions regarding the setting button, action bar and the title changing

I am a noob in android development and I follow the tutoral of the android website.
1. In the part of "Starting Another Activity", I just copied the code and tried to run it, but I found  after the activity is changed (changed to new page), the title of action bar will change to the name of the class of that activity.
2. When it talks about the respond of the action button, the code is written as:
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.action_search:
            openSearch();
            return true;
        case R.id.action_settings:
            openSettings();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

However, in the default code:
 `public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}`

It only return true which contains no method to respond(no openSettings()), but a "setting" word still pop out when I press it.
3. How do I remove the action bar and make it full screen?

A:

The Name of the activity is, in your case, is declared in AndroidManifest.xml. Check the android:label attribute of your activity. You can manipulate it through java code if you want. See this SO question.
Check the menu file under res/menu/your_menu_file.xml. I think it contains something like

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="@string/action_settings"/>

The displayed icon is NOT setting icon, but overflow icon. If the overflow icon is clicked, it lists all menu items. In your case only one (i.e Setting)

To hide the action bar, include these in your onCreate() method
//getWindow().requestWindowFeature(Window.FEATURE_NO_TITLE);
getActionBar().hide();

You can also do it via xml. Look at this SO question.


Q:

Quickly append value to a list

PHP has a really quick way to append a value to an array:
$array[] = 'value';

What is the easiest way to do this in python without needing an index number?
 Also, is there an easy way to do this with a list nested inside a dictionary, like this PHP equivalent..
$array['associative'][] = 'value';

A:

my_list.append(value)

or
my_dict[key].append(value)


Q:

Chrome Extension Notification Buttons not showing on MacOs/OSX

I'm currently working on a Chrome Extension using the Notification Api. On Chrome in Windows and Linux its working ok, but in MacOs / OSX the notification is being shown without the button. I tried to look any information in Chrome Notification API but they doesn't say anything about buttons not working for MacOS users like for other functionality as imageURL or appIconMaskUrl.
This is the declaration of my notification on the extension:
        type: "basic",
        title: message.participant + " has arrived!",
        message: message.description,
        iconUrl: "icon.jpg",
        buttons: [{title:'Go to Project'}]

A:

AFAIK, from the recent update, the action button icons will not be used and the user will need to hover over the notification and select the "More" button to see the available actions.
From this GitHub post,

To enable actions on the notification (the buttons that allow the user to select an option), open System Preferences > Notifications, select terminal-notifer in the sidebar, and select the "Alerts" alert style.


Q:

Load Facebook into an iframe

I can't load facebook into an iframe, in a web page like the following one:
<html>
<head>
<!-- some stuffs here -->
</head>
<body>
<!-- some stuffs here -->
<iframe src="http://www.google.com" frameborder="0">
</iframe>
</body>
</html>

I've tested it with other websites and it seems to load without problems for instance for wired.com, but not for facebook.com...
Can anyone explain me why?
I'm using Google Chrome and Safari, if needed.
It seems to be as if Google blocks iframe loading of its page.

A:

If you use Firebug or Google Chrome's developer console, you can see the following error
Refused to display document because display forbidden by X-Frame-Options.

X-Frame-Options

DENY
  The page cannot be displayed in a frame, regardless of the site attempting to do so.
SAMEORIGIN
  The page can only be displayed in a frame on the same origin as the page itself.

Here is another related stackoverflow question
Overcoming “Display forbidden by X-Frame-Options”

A:

Google and Facebook are using a X-Frame-Options in the HTTP response header to avoid the content being loaded in a iFrame.

The X-Frame-Options HTTP response header can be used to indicate
  whether or not a browser should be allowed to render a page in a
   or  . Sites can use this to avoid clickjacking
  attacks, by ensuring that their content is not embedded into other
  sites.

Source: https://developer.mozilla.org/en/The_X-FRAME-OPTIONS_response_header
I don't think it is possible for you to override this setting.


Q:

Ionic input and select side by side

I have one input and one select that i want to show side by side.
I attempted several way with no avail.
The current code is as follows
<form name="signup">
<ion-list>

<input placeholder="Identificación" name="identificacion" type="text" ng-click="registro.msg = null" ng-model="registro.identificacion" required>

Tipo de Identificación

<select ng-model="registro.tipo_id">
<option ng-repeat="tipo in defaultTipo" value="{{tipo.id}}" ng-selected="{{tipo.selected}}">{{tipo.tipo}}</option>
</select>

</ion-list>
</form>

This outputs the following:

I need to put the input on the left and the select on the right in the same row.
Any ideas?

A:

You can simply use the ionic grid system, but putting them side by side wont leave you a lot a room on a phone. You can read more about it here: http://ionicframework.com/docs/components/#grid-explicit
<form name="signup">
<ion-list>
**
**
**
**

<input placeholder="Identificación" name="identificacion" type="text" ng-click="registro.msg = null" ng-model="registro.identificacion" required>

**
**

Tipo de Identificación

<select ng-model="registro.tipo_id">
<option ng-repeat="tipo in defaultTipo" value="{{tipo.id}}" ng-selected="{{tipo.selected}}">{{tipo.tipo}}</option>
</select>

</ion-list>
</form>

A:

You can try this ::
<ion-grid>
  <ion-row>
   <ion-col width-50>
   <ion-item>
    <ion-label color="primary">Inline Label</ion-label>
    <ion-input placeholder="Text Input"></ion-input>
  </ion-item>
 </ion-col>
 <ion-col width-50>
    <ion-item>
       <ion-label>Minute 2</ion-label>
       <ion-select [(ngModel)]="inr">
       <ion-option value="h1">5</ion-option>
       <ion-option value="h2">6</ion-option>
       <ion-option value="h3" >7</ion-option>
       </ion-select>
    </ion-item>
    </ion-col>
  </ion-row>
  </ion-grid>


Q:

Target a specific table using CSS3 selector

Is it possible to use the nth-child selector to target a specific table within it's parent element?
I'm trying to target the 2nd table in a div but it doesn't seem to be working:
#div table:nth-child(2) {
    color: blue
}

Table 1

Table 2

A:

Your issue could be with the invalid html. You need to wrap the text within td.

Table 1

Table 2

Also make sure you do not have id duplicated.
Here's a working CodePen demo
One more thing to be noted is that this will work only if your table is 2nd child of div, if you want to target 2nd table inside its parent you would need to use nth-of-type(2)


Q:

Entry of a list item in a file

Good afternoon, I have a multiple list of IP and MAC, list of arbitrary length
A = [['10.0.0.1','00:4C:3S:**:**:**', 0], ['10.0.0.2', '00:5C:4S:**:**:**', 0], [....], [....]]

I want to check if this MAC is in the oui file:
E043DB   (base 16)   Shenzhen
2405f5   (base 16)   Integrated
3CD92B   (base 16) Hewlett Packard
...

If the MAC from the list is in the file, write the name of the manufacturer as 3 list items. I'm trying to do so and it turns out to check only the first element, the remaining ones are not checked, how can I do this please tell me?
f = open('oui.txt', 'r')
for values in A:
    for line in f.readlines():
        if values[1][0:8].replace(':','') in line:
            values[2]=(line.split('(base 16)')[1].strip())
f.close()
print (A)

And get an answer:
A = [['10.0.0.1','00:4C:3S:**:**:**', 'Firm Name'], ['10.0.0.2', '00:5C:4S:**:**:**', 0], [....], [....]]

A:

The Problem
Consider the "shape" of your code:
f = open('a file')
for values in [ 'some list' ]:
    for line in f.readlines():

Your two loops are doing this:
Start with first value in list
Read all lines remaining in file object f
Move to next value in list
Read all lines remaining in file object f

Except that the first time you told it to "read all lines remaining" it would do so.
So, unless you have some way to put more lines into f (which can happen with async files like stdin!) you are going to get one "good" pass through the file, and then every subsequent pass the file object will point to the end of the file, so you'll get nothing.
A Solution
When you are dealing with a file, you want to only process it one time. File I/O is expensive compared to other operations. So you can choose to either (a) read the entire file into memory, and do whatever you want since it's not a file any more; or (b) scan through it only one time.
If you choose to scan through it only once, the easy solution is just to invert the two for loops. Instead of doing this:
for item in list:
    for line in file:

Do this instead:
for line in file:
    for item in list:

And presto! You are now only reading the file one time.
Other Considerations
If I look at your code, and your examples, it seems like you are trying for an exact match on a particular key. You trim down the MAC addresses in your list to check them against the manufacturer ids.
This suggests to me that you might well have many, many more list values (source MAC addresses) than you have manufacturers. So perhaps you should consider reading the contents of the tile into memory, rather than processing it one line at a time.
Once you have the file in memory, consider building a proper dictionary. You have a key (MAC prefix) and a value (manufacturer). So build something like:
for line in f:
    mac = line.split('(base 16)')[0].strip()
    mfg = line.split('(base 16)')[1].strip()
    mac_to_mfg[mac] = mfg

Then you can make one pass through the source addresses and use the dict's O(1) lookup to your advantage:
for src in A:
    prefix = src[1][:8].replace(':', '')
    if prefix in mac_to_mfg:
        # etc...


Q:

Postgresql - Sybase concepts correspondence

The following diagram depicts the main PostgreSQL concepts pretty nicely:

I find myself having to work with Sybase ASE 15 and I was wondering what the similar concepts are in Sybase. E.g. from what I've understood so far Sybase lacks the concept of schemas. So some questions are:

does Sybase ASE 15 have the concept of schemas?
what is the boundary for referential integrity constraints? E.g. in PostgreSQL you can have foreign keys across schemas (but not across databases). What is the situation in Sybase ASE 15?

A:

SAP/Sybase ASE uses a slightly different conceptual model than PostgreSQL, Oracle & SQLServer, which all have the concept of a schema.
PostgreSQL  |   SAP ASE
-----------------------
Cluster     |   Database Server or Database Server Cluster
Catalog     |   Database
Schema      |   User
-----------------------

In ASE, a cluster is multiple physical Database Servers working as a single logical Database Server.  There is no separate designation if a Database Server (single or cluster) is running multiple databases, since that is the expected operation.
Database is the collection of related objects (Tables, views, triggers, users, etc).
Schemas: In ASE a user can own objects, and set permissions on those objects independently, which satisfies some of the same use cases for schemas BUT a user can not be dropped from the database if they own any objects.  So for practical purposes, most sites don't use user level objects.
The lowest granularity storage object in ASE is a page (other databases call this a block) the size of which is set when the server is installed, but can be 2k, 4k, 8k or 16k.  This means that the database allocates pages in chunks equivalent to the page size setting.
Referential integrity can cross database (schema) boundaries.
I highly recommend checking out sypron.nl.  Rob Verschoor is an SAP VP & Engineer and his site is packed with good information, tips, tricks and scripts.  His quick reference books are also VERY good, and I would recommend them to anyone needing to work with ASE, Replication Server or IQ.


Q:

Are Easter days normally distributed?

How can Mathematica be used to check if Easter days are normally distributed?
By definition, Easter day is the first Sunday after the first full moon after the spring equinox (so between March 23d and April 25th).
This is a self-answered question but of course the purpose is to discover new ideas/commands/etc. so feel free to post your own answer!

A:

Instead of FindFit[], DistributionFitTest[] is the function to use to test the distribution followed by your data. Using easter[] from this answer, generate the number of days Easter is counted from March 23 of that same year:
data = Table[DayCount[DateObject[{k, 3, 23}], DateObject[easter[k]]], {k, 1700, 2018}];

Then,
hh = DistributionFitTest[data // N, Automatic, "HypothesisTestData"];

See the test results:
hh["TestDataTable", All]

The $p$-values of all except one test are quite tiny. More starkly put,
hh["TestConclusion", All]
   {"The null hypothesis that the data is distributed according to the
     NormalDistribution[x, y] is rejected at the 5 percent level based on
     the Anderson-Darling test.",

    ...

    "The null hypothesis that the data is distributed according to the
     NormalDistribution[x, y] is rejected at the 5 percent level based on
     the Shapiro-Wilk test."}

where I have omitted some of the output.

A:

This is code to compute Easter Sunday for each year (the "Computus"), from Gauss, in the proleptic Gregorian calendar:
computusGauss[year_Integer] :=
  Module[{a, b, c, d, e, f, g, h, i, j, k, month, day},
   a = Mod[year, 19];
   {b, c} = QuotientRemainder[year, 100];
   {d, e} = QuotientRemainder[b, 4];
   f = Quotient[8 b + 13, 25];
   g = Mod[19 a + b - d - f + 15, 30];
   {h, i} = QuotientRemainder[c, 4];
   j = Quotient[a + 11 g, 319];
   k = Mod[2 e + 2 h - i - g + j + 32, 7];
   month = Quotient[g - j + k + 90, 25];
   day = Mod[g - j + k + month + 19, 32];
   {year, month, day}
   ];

The result is periodic with period 5700000 years.
Compute a full period:
data = computusGauss /@ Range[5700000];

Project the results to a common year (it's irrelevant which one you choose):
data[[All, 1]] = 2018;

A date histogram shows this trapezoidal structure, between March 22 and April 25, both included:
DateListStepPlot[Tally[data]]

A:

First, we need to get the data, here from the website tlarsen2.tripod.com:
data = Import["http://tlarsen2.tripod.com/thomaslarsen/easterdates.html", "Table"];
dates = Reverse /@ SortBy[Partition[Flatten@Select[data,
         MemberQ[#, "April"] || MemberQ[#, "March"] &], 3], Last] /.
    "April" -> 4 /. "March" -> 3;
dates = Table[date[[1 ;; 2]]~Join~{ToExpression@
      StringReplace[date[[3]], LetterCharacter -> ""]}, {date, dates}];
(* {{1700, 4, 11}, {1701, 3, 27}, {1702, 4, 16}, ... *)

Then, convert the dates into the number of days from the first possible date (March 23d), and use Tally to count:
monthsDays = dates[[All, {3, 2}]];
days = If[#[[2]] == 4, #[[1]] + 31 - 22., (#[[1]] - 22.)] & /@ monthsDays;
dist = Sort@Tally[days];

That's the date (counted in days after March 23d) as a function of the year (counted from 1700).
ListPlot[days]

Then, we can fit a Gaussian curve on the distribution (note: to see how to do this properly, check J.M.'s answer)
model[x_] = ampl Evaluate[PDF[NormalDistribution[mu, sigma], x]];
fit = FindFit[dist, model[x], {ampl, mu, sigma}, x]
Show[ListPlot[dist],
 Plot[model[x] /. fit, {x, 0, 35}, PlotStyle -> Red]]

The result is not really well approximated by a Gaussian.


Q:

Accessing "protected" part of object

I have the variable $customerData that stores an object. When I execute print_r($customerData) I get something similar to the below.
Balanced\Customer Object(
    [_collection_uris:protected] => Array(
        [reversals] => Array(
            [class] => Balanced\Reversal
            [uri] => /v1/customers/1234123412341234/reversals
        )
    )
    [_member_uris:protected] => Array(
        [source] => Array(
                [class] => Balanced\Card
                [uri] => /v1/customers/1234123412341234/cards/987698769876
            )
    )
    [_type] => customer
    [twitter] => twitterHandle
    [phone] => 5551231234
)

I'm having issues accessing the uri inside _member_uris:protected.
print_r($customerData->_member_uris:protected); #Throws error "unexpected ':'"
print_r($customerData->_member_uris); #Throws error " Undefined property"
print_r($customerData['_member_uris']); #Throws error "Cannot use object of type array"

What is the process of accessing that part of the object?

A:

Members declared protected can be accessed only within the class itself and by inherited and parent classes. You could add a method in your class to get it, using setAccessible(),  like:
//function inside your class
public static function getProtectedProp($class, $propName) {
    $reflClass = new ReflectionClass($class);
    $property = $reflClass->getProperty($propertyName);
    $property->setAccessible(true);
    return $property->getValue($class);
}

and you can do:
getProtectedProp($someClassObject, 'protectedPropertyName');

Source:: Reading Protected Property


Q:

Generalization of Hoeffding Inequality

According to Hoeffding Inequality, if $X_1,\ldots,X_n$ are independent random variables with $\mathbb{P}(X_i \in [a_i,b_i]) = 1 \; \forall i = 1,\ldots,n$ then
$$\mathbb{P}(\bar{X_n} - \mathbb{E}[\bar{X_n}] \geq t) \leqslant \exp\left(-\frac{2t^2n^2}{\sum_{i=1}^{n}(b_i - a_i)^2}\right) \quad \forall t > 0.$$ Does there exist any such bound for the probability of the event $\{\bar{X_n} - c\mathbb{E}[\bar{X_n}] \geqslant t\}$ for any constant $c$. Hoeffding Inequality is just a special case of this event when $c = 1$.

A:

To bound this event, you can just apply Hoeffding's Inequality as usual, replacing $t$ with $t + (c - 1)\mathbb{E}[\bar{X_n}]$.


Q:

Inserting data from one table, then taking the primary key of that insert and put it into another table

I have a quick question. I have a table users
 -----------------------------
| ID | first_name | last_name |
 -----------------------------

and another table like users.login
 ------------------
| users_ID | EMAIL |
 ------------------

My id's in the first table are auto incrementing from a certain point, say 160,000. How do I take the id from the first table, save it to a value, and then put that value into the id of the 2nd table? The id in users.login is foreign key to users.id.
So far i have
INSERT INTO public.users (first_name, last_name)
                VALUEs ($1,$2) RETURNING ID;
INSERT INTO public.users_login(email, ID)
                Values($1, id)

does this work? I'm new to postgres.

A:

Consider using the RETURNING clause on an INSERT or UPDATE statement to insert the foreign key.  From the PostgreSQL docs:
WITH upd AS (
  UPDATE employees
  SET sales_count = sales_count + 1
  WHERE id =
    (
       SELECT sales_person
       FROM accounts
       WHERE name = 'Acme Corporation'
    )
    RETURNING *
)
INSERT INTO employees_log
SELECT *, current_timestamp FROM upd;

So, your statement would need to do the initial insert in common-table-expression, which returns the id to allow it to be inserted into the users_login table:
CREATE TABLE users (
      user_id serial
    , first_name varchar(30)
    , last_name varchar(30)
);

CREATE TABLE users_login (
      user_login_id serial
    , email varchar(30)
    , user_id int
);

WITH ins AS (
    INSERT INTO users (first_name, last_name)
                VALUES ('max', 'vernon')

    RETURNING user_id
)
INSERT INTO users_login(email, user_id)
SELECT 'us@them.com', user_id
FROM ins

Querying the two tables:
SELECT *
FROM users u
    INNER JOIN users_login ul ON u.user_id = ul.user_id;

╔═════════╦════════════╦═══════════╦═══════════════╦═════════════╦═════════╗
║ user_id ║ first_name ║ last_name ║ user_login_id ║    email    ║ user_id ║
╠═════════╬════════════╬═══════════╬═══════════════╬═════════════╬═════════╣
║       1 ║ max        ║ vernon    ║             1 ║ us@them.com ║       1 ║
╚═════════╩════════════╩═══════════╩═══════════════╩═════════════╩═════════╝


Q:

Set default language on a CodeMirror TextArea

How can i set that a CodeMirror TextArea will understand PHP WITHOUT echo the tag?
The Textarea
<textarea id="code" name="code">
  <?php
    echo '<?php';
  ?>
</textarea>

The JS script
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        lineNumbers: false,
        matchBrackets: true,
        mode: "application/x-httpd-php",
        indentUnit: 4,
        indentWithTabs: true,
        enterMode: "keep",
        tabMode: "shift"
    });

A:

I've solved it, you have to change the mode to mode: "text/x-php",


Q:

Delphi Intraweb website crash on IIS

I've made an Intraweb ISAPI application. After building the dll, I've created an Web site on IIS and a pool for the application. On the Inetpub directory the permissions are set for the Internet Guest Account and for the IIS_WPG accounts.
When I'm trying to access the webpage from IE (http://ip.0.0.1/website/application.dll)  it returns me HTTP 500 or

errors. After searching on the Internet it says that is a problem of COM initialization. But in the datamodule of the application there is this code:
initialization
  CoInitialize(nil);

finalization
  CoUninitialize;

Can anybody give any advice?

A:

Do not use your own CoInitliaze calls, but instread use the ServerController and set the ComInitialization property to ciMultiThread for example.
From my IntraWeb Courseware manual: "The ComInitialization property of type TComInitialization (ciNone, ciNormal, ciMultiThread) is needed when the application requires the use of (D)COM. Since IntraWeb executes requests in different threads, each thread must make its own call to CoInitialize.
By default this property is set to ciNone, to indicate that no COM support is required. If you need COM support - for example if you want to connect to a DataSnap server - then you need to set ComInitialization to ciNormal or ciMultiThreaded.
Personally, I’ve found no reason not to set it to ciMultiThreaded when working with COM in one way or another inside an ISAPI DLL, although IIS 6 and higher may handle the required ComInitialization already for you, and you should set it to ciNone (but it looks like it’s ignored when set to some other value, so ciMultiThread won’t hurt either)."


Q:

Otsu thresholding method

Hi All and Happy New Year
I am writing my matlab code for otsu method but I have errors, If someone can look at my code and suggest me some corrections, I will be very grateful.
This is my code:

im1=imread('cameraman.tif');
%im1=rgb2gray(im1);
[n,m]=size(im1);
hst=imhist(im1);
mu=0;
N=0;
for i=1:255
    N=N+hst(i);
end
% The total mean level of the original image
for i=1:255
    mu(i)=mu(i)+((i.*hst(i))./N);
end

for T=1:254
    qb=0;
    muT=0;
    qo=0;
    for i=1:T
        qb=qb+(hst(i)./N); % probability of class occurence (background)
        m=m+((i.*hst(i))./N);% probability of class mean (background)
    end
    for i=T+1:255
        qo=qo+(hst(i)./N);% probability of class occurence (object)
    end
    sigma(T)=((mu-(qb*muT))^2)/(qb*qo)
end
[Y,T] = max(sigma)

[n,m]=size(im1);
for i=1:n
    for j=1:m
        if im1(i,j)>T
            im(i,j)=1;
        else
            im(i,j)=0;
        end
    end
end
figure(1);
subplot(1,3,1);
imshow(im1);
subplot(1,3,2);
imhist(im1);
subplot(1,3,3);
imshow(im);

thanks in advance

A:

Changed two lines that induced errors, please test:
mu=zeros(255,1); instead of mu=0;
sigma(T)=((mu(T)-(qb*muT))^2)/(qb*qo); instead of sigma(T)=((mu-(qb*muT))^2)/(qb*qo);


Q:

Best practice to reset angular 7 form

I am using Angular 7. In my project I've used Template Driven form. I'm resetting form using <input type="reset"> and it works fine. But I'm confused on which is better- <input type="reset" or form reset()?

A:

Better way is to use reset() of form as it resets the states of the form controls so any validation styling and errors reset also to the original pristine condition.


Q:

Use VB.NET DLL in VB.NET

I would like to use a Class Library project in a Windows Forms project. Here's what I did:

Make a Class Library project.
Code it.
Go to BUILD on the menu bar, then do Build.

Now that I've done that, I don't see an option to use the DLL in my other project.

A:

You need a reference to the library project to use it.
In the project where you want to use the library, right click on the "References" node in the solution explorer, and select "Add Reference...".
It will open the reference manager, there you select the "Solution" tab. It will show you the projects in your solution, and you can check the checkbox in front of your library project.


Q:

Change calendar view's layout

I have a calendar list with about 8 views created by filtering on Location. Is it possible to have these views appear differently than the default? I've selected "Week" as the scope for all the views. Here's what I need:

The calendar is shaded to indicate the workweek from Monday - Friday, 8 - 5. Can this be changed? So the workweek would be from Sunday - Thursday, 8 - 5:30 p.m.
Can the full day name appear at the top instead of the one letter abbreviation?
Can we set the display time range for the days of the week? It currently defaults to 7 a.m. - 7 p.m. for the calendar. We'd like it to go from 6 a.m. to 10 p.m.
Can the calendar display area be scrollable vertically? This way, we limit its height to a set value and let the user scroll inside.

The calendar is based on a custom content type, which is based on the Event type. I have access to jQuery so if these changes require it, that's no problem. Thank you :)

A:

You can define your work week and time range by changing your site Regional settings under Site Settings > Site Administration > Regional Settings > Define Your Work Week.
By applying different work week and time range your calendar will render differently (maybe not exactly as you require).
To make other desired changes you will need to use jQuery and/or css.


Q:

win32 message loop - should I break or return?

I'm wondering what the correct return value for a windows message loop is. So far I've used the following:
case WM_LBUTTONDOWN: // left mouse button pressed.
    if (condition == true )
    {
        do_something();
    }
break;

but I've seen also things like:
if (IDC_BUTTON == LOWORD(wParam) && BN_CLICKED == HIWORD(wParam))
{
    do_something();
    return true;
}
break;

which one is correct? Should I return true? or should I break? Does it matter?
EDIT does it depend whether I'm interacting with a button press or a mouse movement?

A:

The return value is documented on MSDN, as part of the documentation for each message. For example, the documentation for WM_LBUTTONDOWN states that

If an application processes this message, it should return zero.

For other messages, the return value might be more meaningful. You should always read the documentation, never guess.


Q:

Valor-software/ngx-bootstrap put a component inside dynamically created content

I'm trying to use valor-software/ngx-bootstrap to create a dynamic tab but I want to put a component's selector inside the dynamically created tab content,
In the documentation example we have:
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'demo-tabs-dynamic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './dynamic.html'
})
export class DemoTabsDynamicComponent {
  tabs: any[] = [
    { title: 'Dynamic Title 1', content: 'Dynamic content 1' },
    { title: 'Dynamic Title 2', content: 'Dynamic content 2', disabled:
true },
    { title: 'Dynamic Title 3', content: 'Dynamic content 3',
removable: true }
  ];

  addNewTab(): void {
    const newTabIndex = this.tabs.length + 1;
    this.tabs.push({
      title: `Dynamic Title ${newTabIndex}`,
      content: `Dynamic content ${newTabIndex}`,
      disabled: false,
      removable: true
    });
  }

}

And I want to be able to do something like this:
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'demo-tabs-dynamic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './dynamic.html'
})
export class DemoTabsDynamicComponent {
  tabs: any[] = [
    { title: 'Dynamic Title 1', content: 'Dynamic content 1' },
    { title: 'Dynamic Title 2', content: 'Dynamic content 2', disabled:
true },
    { title: 'Dynamic Title 3', content: 'Dynamic content 3',
removable: true }
  ];

  addNewTab(): void {
    const newTabIndex = this.tabs.length + 1;
    this.tabs.push({
      title: `Dynamic Title ${newTabIndex}`,
      content: `<my-component></my-component>`, // Here is the change
      disabled: false,
      removable: true
    });
  }
}

Angular sanitizes the component selector to string Is there any workaround?

A:

Actually I took this approach that doesn't need to path any html in the content
 <tabset >
    <tab *ngFor="let tabz of mainMenuTab.tabs"
         [heading]="tabz.title"
         [active]="tabz.active"
         (select)="tabz.active = true"
         (deselect)="tabz.active = false"
         [disabled]="tabz.disabled"
         [removable]="tabz.removable"
         (removed)="removeTabHandler(tabz)"
         [customClass]="tabz.customClass">
            <div [ngSwitch]="tabz?.content">
               <app-employees-menu *ngSwitchCase="'employee'">
               </app-employees-menu>
               <app-inventories-menu *ngSwitchCase="'inventory'">
               </app-inventories-menu>
               <app-customers-menu *ngSwitchCase="'customer'">
               </app-customers-menu>
            </div>
    </tab>
 </tabset>

So basically I already put all the possible tabs that I may have and based on which one I need to be shown I'll pass the content which act as a switch and in the template there is a switchCase that shows the tab that match the switchCase.


Q:

How to call 2 stored procedures using mysqli

Bascially I have a form with 2 select dropdown boxes and I want to populate the selections with 2 stored procedures that returns all the values via php. However, it seems like only the first select box is getting populated while the second one is not.
I have tested both stored procedure and they work fine.

  Name

    <select class="form-control" name="pokemonName" style="width:30%;">
      <?php
        require_once '../database/connection.php';
        $sqlNames = "CALL sp_selectAllPokemonName";
        $names = $con->query($sqlNames);
        while ($name = $names->fetch_assoc()){
          echo "<option value= '".$name['pokemonName']."'>".$name['pokemonName']."</option>";
        }
      //  $names->close();
      //  $con->close();
      ?>
    </select>

  Hour

    <select class="form-control" name="hour" style="width:30%;">
      <?php
        // query doesn't work here
        require_once '../database/connection.php';
        $sqlHours = "CALL sp_selectAllHour";
        $hours = $con->query($sqlHours);
        while ($hour = $hours->fetch_assoc()){
          echo "<option value= '".$hour['Id']."'>".$hour['Id']."</option>";
        }
      ?>
    </select>

connection.php
<?php
    require 'credentials.php';
    include '../ChromePhp.php';
    // Create connection
    //$con = mysqli_connect($servername, $username, $password, $dbname); // Procedural
    $con = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($con->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
        ChromePhp::warn('something went wrong!');
    }
?>

A:

This is an excerpt from my PDO tutorial, but the principle is applicable to any API:

There is one thing about stored procedures any programmer stumbles upon at first: every stored procedure always returns one extra result set: one (or many) results with actual data and one just empty. Which means if you try to call a procedure and then proceed to another query, then "Cannot execute queries while other unbuffered queries are active" error will occur, because you have to clear that extra empty result first.

So you have to advance to that extra result set, using mysqli_next_result
Just a call to $con->next_result() should do the trick. Note that you have to call it only after fetching all the data from result set.


Q:

R: conditional aggregate based on factor level and year

I have a dataset in R which I am trying to aggregate by column level and year which looks like this:
    City  State   Year   Status      Year_repealed   PolicyNo
    Pitt   PA     2001   InForce                        6
    Phil.  PA     2001   Repealed        2004           9
    Pitt   PA     2002   InForce                        7
    Pitt   PA     2005   InForce                        2

What I would like to create is where for each Year, I aggregate the PolicyNo across states taking into account the date the policy was repealed. The results I would then get is:
    Year    State PolicyNo
    2001     PA     15
    2002     PA     22
    2003     PA     22
    2004     PA     12
    2005     PA     14

I am not sure how to go about splitting and aggregating the data conditional on the repeal data and was wondering if there is a way to achieve this is R easily.

A:

It may help you to break this up into two distinct problems.

Get a table that shows the change in PolicyNo in every city-state-year.
Summarize that table to show the PolicyNo in each state-year.

To accomplish (1) we add the missing years with NA PolicyNo, and add repeals as negative PolicyNo observations.
library(dplyr)

df = structure(list(City = c("Pitt", "Phil.", "Pitt", "Pitt"), State = c("PA", "PA", "PA", "PA"), Year = c(2001L, 2001L, 2002L, 2005L), Status = c("InForce", "Repealed", "InForce", "InForce"), Year_repealed = c(NA, 2004L, NA, NA), PolicyNo = c(6L, 9L, 7L, 2L)), .Names = c("City", "State", "Year", "Status", "Year_repealed", "PolicyNo"), class = "data.frame", row.names = c(NA, -4L))

repeals = df %>%
  filter(!is.na(Year_repealed)) %>%
  mutate(Year = Year_repealed, PolicyNo = -1 * PolicyNo)
repeals
#    City State Year   Status Year_repealed PolicyNo
# 1 Phil.    PA 2004 Repealed          2004       -9

all_years = expand.grid(City = unique(df$City), State = unique(df$State),
                        Year = 2001:2005)

df = bind_rows(df, repeals, all_years)
#     City State Year   Status Year_repealed PolicyNo
# 1   Pitt    PA 2001  InForce            NA        6
# 2  Phil.    PA 2001 Repealed          2004        9
# 3   Pitt    PA 2002  InForce            NA        7
# 4   Pitt    PA 2005  InForce            NA        2
# 5  Phil.    PA 2004 Repealed          2004       -9
# 6   Pitt    PA 2001     <NA>            NA       NA
# 7  Phil.    PA 2001     <NA>            NA       NA
# 8   Pitt    PA 2002     <NA>            NA       NA
# 9  Phil.    PA 2002     <NA>            NA       NA
# 10  Pitt    PA 2003     <NA>            NA       NA
# 11 Phil.    PA 2003     <NA>            NA       NA
# 12  Pitt    PA 2004     <NA>            NA       NA
# 13 Phil.    PA 2004     <NA>            NA       NA
# 14  Pitt    PA 2005     <NA>            NA       NA
# 15 Phil.    PA 2005     <NA>            NA       NA

Now the table shows every city-state-year and incorporates repeals. This is a table we can summarize.
df = df %>%
  group_by(Year, State) %>%
  summarize(annual_change = sum(PolicyNo, na.rm = TRUE))
df
# Source: local data frame [5 x 3]
# Groups: Year [?]
#
#    Year State annual_change
#   <int> <chr>         <dbl>
# 1  2001    PA            15
# 2  2002    PA             7
# 3  2003    PA             0
# 4  2004    PA            -9
# 5  2005    PA             2

That gets us PolicyNo change in each state-year. A cumulative sum over the changes gets us levels.
df = df %>%
  ungroup() %>%
  mutate(PolicyNo = cumsum(annual_change))
df
# # A tibble: 5 × 4
#    Year State annual_change PolicyNo
#   <int> <chr>         <dbl>    <dbl>
# 1  2001    PA            15       15
# 2  2002    PA             7       22
# 3  2003    PA             0       22
# 4  2004    PA            -9       13
# 5  2005    PA             2       15


Q:

How to get a snapshot of current drawable with metal on mac?

I found a similar post here and here.
I tried the following codes, it works fine in iOS 12.1.4 but empty on macOS Mojave version 10.14
    id<CAMetalDrawable> lastDrawable = view.currentDrawable;
    [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> commandBuffer) {
        id<MTLTexture> drawableTexture = lastDrawable.texture;
        int width = (int)drawableTexture.width;
        int height = (int)drawableTexture.height;
        int len = width * height * 4;
        uint8_t* image = (uint8_t*)malloc(len);
        [drawableTexture getBytes:image bytesPerRow:width*4 fromRegion:MTLRegionMake2D(0, 0, width, height) mipmapLevel:0];

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef bitmapContext = CGBitmapContextCreate(
                                                           image,
                                                           width,
                                                           height,
                                                           8, // bitsPerComponent
                                                           4*width, // bytesPerRow
                                                           colorSpace,
                                                           kCGImageAlphaNoneSkipLast);

        CFRelease(colorSpace);

        CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
        CFRelease(cgImage);
        CFRelease(bitmapContext);
        free(image);
    }];

Do I need some additional processes to get a correct snapshot of the current screen on mac?

A:

The storage mode of the drawable's texture is managed. You need to use a blit command encoder to encode a -synchronize... command. Otherwise, the data isn't guaranteed to be available to the CPU.


Q:

Delphi Ambiguous Overloaded Call to MkDir

I'm getting the following error message when I attempt to call MkDir

[Error] DBaseReindexer.dpr(22): Ambiguous overloaded call to MkDir

I've tried the following things and they all return the same error.
MkDir('test');

var
  Dir: String;
begin
  Dir := 'test';
  MkDir(Dir);
end;

const
  Dir = 'test';
begin
  MkDir(Dir);
end;

From looking at the source, there's a version that takes a string, and a version that takes a PChar. I'm not sure how my string would be ambiguous between those two types.

Code to reproduce the error (from comments):
program Project1;
{$APPTYPE CONSOLE}
uses SysUtils, System;
begin
  MkDir('Test');
end.

A:

Your code compiles fine in an empty project:
program Project1;

procedure Test;
const
  ConstStr = 'test';
var
  VarStr: string;
begin
  MkDir('Test');
  MkDir(ConstStr);
  MkDir(VarStr);
end;

begin
end.

So your problem is that somewhere else in your code you have defined an incompatible overload for MkDir. For instance this program:
program Project1;

procedure MkDir(const S: string); overload;
begin
end;

procedure Test;
const
  ConstStr = 'test';
var
  VarStr: string;
begin
  MkDir('Test');
  MkDir(ConstStr);
  MkDir(VarStr);
end;

begin
end.

produces the following compiler errors:

[dcc32 Error] Project1.dpr(13): E2251 Ambiguous overloaded call to 'MkDir'
  System.pas(5512): Related method: procedure MkDir(const string);
  Project1.dpr(3): Related method: procedure MkDir(const string);
[dcc32 Error] Project1.dpr(14): E2251 Ambiguous overloaded call to 'MkDir'
  System.pas(5512): Related method: procedure MkDir(const string);
  Project1.dpr(3): Related method: procedure MkDir(const string);
[dcc32 Error] Project1.dpr(15): E2251 Ambiguous overloaded call to 'MkDir'
  System.pas(5512): Related method: procedure MkDir(const string);
  Project1.dpr(3): Related method: procedure MkDir(const string);

Notice how the compiler helpfully tells you which two methods cannot be disambiguated. If you read the full compiler error message then it will take you to the cause of your problem.
Older Delphi versions don't give you the extra information. So if you are in that position, you will have to search your source code for the extra MkDir.
Update
Following the edit to the question that adds code, we can see that the incompatible overload arises from a rather surprising source. Your code is:
program Project1;
{$APPTYPE CONSOLE}
uses SysUtils, System;
begin
  MkDir('Test');
end.

Well, System is automatically included in every unit and it is a compiler defect that the compiler gets past the uses clause. But the erroneous second inclusion of System is what is causing the ambiguity.
Modern versions of Delphi fix this problem and your code results in

[dcc32 Error] E2004 Identifier redeclared: 'System'

Clearly the solution is to remove the spurious use of System.


Q:

how to ignore particular child node when select the root node in xslt?

current coding given in this picture, I want ignore the <bookmeta> content in output how is possible
image

A:

There are several ways to do this. In your situation I would either change the template to match <book> instead of the root (remember - the built-in templates will automatically handle the root for you) and use the except operator or I would write a template to suppress the bookMeta element.
Approach 1
<xsl:template match="book">
    <!-- you probably want to add some sort of output element here! -->
    <xsl:apply-templates select="node() except bookMeta"/>
</xsl:template>

Approach 2
<xsl:template match="/">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="bookMeta"/>

I would suggest using the second approach normally - you have made no changes to the original template and, if you want to handle bookMeta later you have isolated your changes.


Q:

the most efficient way to do aggregation with null value?

I have two tables, and I want to join the two table and do sum operation on their columns.
table 1
id  value
1    100
2    101
3    102
4    103

table 2
id  value
2    201
3    202

I want add the two value column, and if there is null, then it is 0. The return table looks like
id  value
1   100
2   302
3   304
4   103

What is the most simple way to handle that?

A:

SELECT t1.id, t1.value + IFNULL(t2.value, 0) AS value
  FROM table1 t1
  LEFT JOIN table2 t2 on t2.id = t1.id;


Q:

How do I pass the value of an HTML property to a jQuery function?

I would like to pass the value of an HTML tag to a jQuery alert box, but I'm not getting any luck. I basically want to pass either "1" or "2" to the alert box. I keep getting "undefined" in the alert box.
<button class="up" value="1">
<button class="down" value="2">

$(document).ready(function(){
    $(".up,.down").click(function(){
        alert(this.value);
   });
)};

I'm doing this for an ajax function, but I need to make sure I can pass the values first, so the alert box is for debugging.

A:

alert($(this).attr("value"));

A:

That's because the value of a button is what's between the <button></button> tags in IE7, to be safe you can instead you can use for example a data- attribute, like this:
<button class="up" data-value="1">Something</button>

With matching script:
$(document).ready(function(){
    $(".up,.down").click(function(){
        alert($(this).data("value"));
   });
)};

You can test it here.


Q:

Perl Ternary statement with regex as one of its results

I currently have the following code:
my $class = $rs->{'CLS_ID'};
$class =~ s/^C\S{1,3}\s+// if ($transform);

This works fine, but I was wondering if those 2 statements could be combined into a single ternary expression?

A:

The ternary conditional operator lets you specify a test and two values.
E.g.
my $value = somecondition ? value-if-true : value-if-false;

Now, you aren't doing that with your example - you're setting a value, then running a subroutine (regex) if your condition is true.
So I'd suggest whilst you possibly could, you're subverting the notion of what a ternary operator is for. And you'd still have your assignment on both 'sides' of the expression.
E.g:
my $class = ($transform) ? $rs->{'CLS_ID'} : $rs->{'CLS_ID'} =~ s/^C\S{1,3}\s+//r;

The 'r' flag tells your regex to 'return' the modified value, without modifying the original. But I wouldn't do this, because it makes what you're doing less clear.
Note that the r modifier to regex applies to perl 5.14 onwards.


Q:

Same Tree, Iterative Solution, JavaScript

I need to check if two given binary trees are the same. Here's an iterative solution that I wrote:
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */

var isSameTree = function(p, q) {
    const nodePair = [p, q]
    const nodes = []

    if(p && q) nodes.push(nodePair)
    else if (!p && !q) return true
    else return false

    while(nodes.length) {
        const lastNodePair = nodes.pop()

       if(
           (lastNodePair[0].val !== lastNodePair[1].val)
            || (lastNodePair[0].left && !lastNodePair[1].left)
            || (!lastNodePair[0].left && lastNodePair[1].left)
            || (lastNodePair[0].right && !lastNodePair[1].right)
            || (!lastNodePair[0].right && lastNodePair[1].right)
       ) return false

        if(lastNodePair[0].left && lastNodePair[1].left) {
            nodes.push([lastNodePair[0].left, lastNodePair[1].left])
        }
        else if(lastNodePair[0].right && lastNodePair[1].right) {
            nodes.push([lastNodePair[0].right, lastNodePair[1].right])
        }
    }
    return true
};

It passes 56 out of 57 test cases, but not this case, which is supposed to be false:
[390,255,2266,-273,337,1105,3440,-425,4113,null,null,600,1355,3241,4731,-488,-367,16,null,565,780,1311,1755,3075,3392,4725,4817,null,null,null,null,-187,152,395,null,728,977,1270,null,1611,1786,2991,3175,3286,null,164,null,null,4864,-252,-95,82,null,391,469,638,769,862,1045,1138,null,1460,1663,null,1838,2891,null,null,null,null,3296,3670,4381,null,4905,null,null,null,-58,null,null,null,null,null,null,null,null,734,null,843,958,null,null,null,1163,1445,1533,null,null,null,2111,2792,null,null,null,3493,3933,4302,4488,null,null,null,null,null,null,819,null,null,null,null,1216,null,null,1522,null,1889,2238,2558,2832,null,3519,3848,4090,4165,null,4404,4630,null,null,null,null,null,null,1885,2018,2199,null,2364,2678,null,null,null,3618,3751,null,4006,null,null,4246,null,null,4554,null,null,null,1936,null,null,null,null,2444,2642,2732,null,null,null,null,null,null,null,4253,null,null,null,null,2393,2461,null,null,null,null,4250,null,null,null,null,2537]

[390,255,2266,-273,337,1105,3440,-425,4113,null,null,600,1355,3241,4731,-488,-367,16,null,565,780,1311,1755,3075,3392,4725,4817,null,null,null,null,-187,152,395,null,728,977,1270,null,1611,1786,2991,3175,3286,null,164,null,null,4864,-252,-95,82,null,391,469,638,769,862,1045,1138,null,1460,1663,null,1838,2891,null,null,null,null,3296,3670,4381,null,4905,null,null,null,-58,null,null,null,null,null,null,null,null,734,null,843,958,null,null,null,1163,1445,1533,null,null,null,2111,2792,null,null,null,3493,3933,4302,4488,null,null,null,null,null,null,819,null,null,null,null,1216,null,null,1522,null,1889,2238,2558,2832,null,3519,3848,4090,4165,null,4404,4630,null,null,null,null,null,null,1885,2018,2199,null,2364,2678,null,null,null,3618,3751,null,4006,null,null,4246,null,null,4554,null,null,null,1936,null,null,null,null,2444,2642,2732,null,null,null,null,null,null,null,4253,null,null,null,null,2461,2393,null,null,null,null,4250,null,null,null,null,2537]

I'd like to stick with an iterative solution if possible.

A:

You are comparing only the left children of both trees OR the right children of both trees because you have else if there when comparing children. Remove the else. Because, if both this.left and this.right from both trees are not null, the right children will not be compared because you have else there. Only the left children are compared
    if(lastNodePair[0].left && lastNodePair[1].left) {
        nodes.push([lastNodePair[0].left, lastNodePair[1].left])
    }
    if(lastNodePair[0].right && lastNodePair[1].right) {
        nodes.push([lastNodePair[0].right, lastNodePair[1].right])
    }


Q:

DDD: Aggregate Roots

I need help with finding my aggregate root and boundary.
I have 3 Entities: Plan, PlannedRole and PlannedTraining. Each Plan can include many PlannedRoles and PlannedTrainings.
Solution 1: At first I thought Plan is the aggregate root because PlannedRole and PlannedTraining do not make sense out of the context of a Plan. They are always within a plan. Also, we have a business rule that says each Plan can have a maximum of 3 PlannedRoles and 5 PlannedTrainings. So I thought by nominating the Plan as the aggregate root, I can enforce this invariant.
However, we have a Search page where the user searches for Plans. The results shows a few properties of the Plan itself (and none of its PlannedRoles or PlannedTrainings). I thought if I have to load the entire aggregate, it would have a lot of overhead. There are nearly 3000 plans and each may have a few children. Loading all these objects together and then ignoring PlannedRoles and PlannedTrainings in the search page doesn't make sense to me.
Solution 2: I just realized the user wants 2 more search pages where they can search for Planned Roles or Planned Trainings. That made me realize they are trying to access these objects independently and "out of" the context of Plan. So I thought I was wrong about my initial design and that is how I came up with this solution. So, I thought to have 3 aggregates here, 1 for each Entity.
This approach enables me to search for each Entity independently and also resolves the performance issue in solution 1. However, using this approach I cannot enforce the invariant I mentioned earlier.
There is also another invariant that states a Plan can be changed only if it is of a certain status. So, I shouldn't be able to add any PlannedRoles or PlannedTrainings to a Plan that is not in that status. Again, I can't enforce this invariant with the second approach.
Any advice would be greatly appreciated.
Cheers,
Mosh

A:

I was having similar problems with this when designing my model and asked this question which I think might help you, especially regarding your first point.
DDD - How to implement high-performing repositories for searching.
When it comes to searching I don't work with the 'model', instead I have specialised search repositories that return 'Summary' objects... i.e. 'PlanSummary'. These are nothing more than information objects (could be thought of more like reporting) and are not used in a transactional sense - I don't even define them in my model class library. By creating these dedicated repositories and types I can implement high performing search queries that can contain grouped data (such as a PlannedTraining count) without loading all of the associations of the aggregate in memory. Once a user selects one of these summary objects in the UI, I can then use the ID to fetch the actual model object and perform transactional operations and commit changes.
So for your situation I would provide these specialised search repositories for all three entities, and when a user wishes to perform and action against one, you always fetch the Plan aggregate that it belongs to.
This way you have the performant searches whilst still maintaining your single aggregate with the required invariants.
Edit - Example:
OK, so I guess implementation is subjective, but this is how I have handled it in my application, using a 'TeamMember' aggregate as an example. Example written in C#. I have two class libraries:

Model
Reporting

The Model library contains the aggregate class, with all invariants enforced, and the Reporting library contains this simple class:
public class TeamMemberSummary
{
    public string FirstName { get; set; }

    public string Surname { get; set; }

    public DateTime DateOfBirth { get; set; }

    public bool IsAvailable { get; set; }

    public string MainProductExpertise { get; set; }

    public int ExperienceRating { get; set; }
}

The Reporting library also contains the following interface:
public interface ITeamMemberSummaryRepository : IReportRepository<TeamMemberSummary>
{

}

This is the interface that the application layer (which in my case happens to be WCF services) will consume and will resolve the implementation via my IoC container (Unity). The IReportRepository lives in an Infrastructure.Interface library, as does a base ReportRepositoryBase. So I have two different types of repository in my system - Aggregate repositories, and reporting repositories...
Then in another library, Repositories.Sql, I have the implementation:
public class TeamMemberSummaryRepository : ITeamMemberSummaryRepository
{
    public IList<TeamMemberSummary> FindAll<TCriteria>(TCriteria criteria) where TCriteria : ICriteria
    {
        //Write SQL code here

        return new List<TeamMemberSummary>();
    }

    public void Initialise()
    {

    }
}

So then, in my application layer:
    public IList<TeamMemberSummary> FindTeamMembers(TeamMemberCriteria criteria)
    {
        ITeamMemberSummaryRepository repository
            = RepositoryFactory.GetRepository<ITeamMemberSummaryRepository>();

        return repository.FindAll(criteria);

    }

Then in the client, the user can select one of these objects, and perform an action against one in the application layer, for example:
    public void ChangeTeamMembersExperienceRating(Guid teamMemberID, int newExperienceRating)
    {
        ITeamMemberRepository repository
            = RepositoryFactory.GetRepository<ITeamMemberRepository>();

        using(IUnitOfWork unitOfWork = UnitOfWorkFactory.CreateUnitOfWork())
        {
            TeamMember teamMember = repository.GetByID(teamMemberID);

            teamMember.ChangeExperienceRating(newExperienceRating);

            repository.Save(teamMember);
        }
    }

A:

Real problem here is SRP violation. Your input part of app goes in conflict with output.
Stick with first solution (Plan==aggregate root). Artificially promoting entities (or even value objects) to aggregate roots distorts whole domain model and ruins everything.

You might want to check out so called CQRS (command query responsibility segregation) architecture which would fit perfectly to fix this particular issue. Here's an example app by Mark Nijhof. Here's nice 'getting-started' list.

A:

This is the whole point of CQRS architectures: segregate Commands - that modify the domain - from Queries - that simply give a view of domain state, because requirement for Commands and Queries are so different.
you can find a good introductions on these blogs :

Udi Dahan
Greg Young

and on many other blogs (including mine)


Q:

Проблемы с ProGuard при превращении строки в ресурс

Что бы превратить строку с ресурс, использую следующий метод
public static int getResId(String variableName, Class<?> c) {
    try {
        Field idField = c.getDeclaredField(variableName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

При использовании ProGuard этот метод не работает! Что нужно добавить в proguard.cfg?

A:

Добавьте в proguard.cfg метку не обфусцировать класс(ы) которые передаются в качестве параметра в ваш метод int getResId(String variableName, Class<?> c)


Q:

Error Building CSipSimple for Android

I am trying to build CSipSimple application for android. I followed all instructions in https://code.google.com/p/csipsimple/wiki/HowToBuild. I also installed all packages too, but I am getting following error while executing the 'make' command on CSipSimple directory.
Mac-mini:CSipSimple-master sino$ make -no-check-certificate
(make -n -C jni/silk init)
wget --no-check-certificate https://developer.skype.com/silk/SILK_SDK_SRC_v1.0.9.zip; \
    unzip -d  sources -q SILK_SDK_SRC_v1.0.9.zip; \
    rm SILK_SDK_SRC_v1.0.9.zip
# Needed for 1.0.8 // todo test
#@mv sources/SILK_SDK_SRC_v1.0.9/* sources/
# source checkout done
# Init done
(make -n -C jni/opus init)
# old uri : https://git.xiph.org/opus.git
git clone git://git.opus-codec.org/opus.git sources; \
    cd sources; \
    git fetch --tags; \
    git checkout origin; \
    git checkout v1.1
# Init done
(make -n -C jni/zrtp4pj init)
git clone git://github.com/r3gis3r/ZRTP4PJ.git sources; \
    cd sources; \
    git fetch --tags; git checkout origin; git checkout  V3.2.0_4; \
    cd zsrtp; \
    git clone git://github.com/r3gis3r/ZRTPCPP.git zrtp; \
    cd zrtp; \
    git fetch --tags; git checkout origin; git checkout  V3.2.0;
# Init done
(make -n -C jni/openssl init)
git clone https://github.com/android/platform_external_openssl.git sources; \
    cd sources; \
    git fetch --tags; \
    git checkout origin; \
    git checkout fa610339baf67da107ba040930352c974b38256f
# Init done
(make -n -C jni/libvpx init)
git clone https://code.google.com/p/webm.libvpx sources; \
    cd sources; \
    git fetch --tags; \
    git checkout origin; \
    git checkout v1.1.0;
quilt push -a && \
    touch .patched_sources
mkdir -p build/armeabi
cd build/armeabi; \
    if [ "build/armeabi/config.mk" = "build/armeabi/config.mk" ]; then TGT=armv5te-android-gcc; fi; \
    if [ "build/armeabi-v7a/config.mk" = "build/armeabi/config.mk" ]; then TGT=armv7-android-gcc; fi; \
    if [ "build/x86/config.mk" = "build/armeabi/config.mk" ]; then TGT=x86-android-gcc; fi; \
    if [ "build/mips/config.mk" = "build/armeabi/config.mk" ]; then TGT=mips32-android-gcc; fi; \
    BUILD_PFX=jni/libvpx/build/armeabi/ ../../sources/configure --target=$TGT --disable-examples --sdk-path=/Users/sino/Documents/android-ndk-r9d
mkdir -p build/armeabi-v7a
cd build/armeabi-v7a; \
    if [ "build/armeabi/config.mk" = "build/armeabi-v7a/config.mk" ]; then TGT=armv5te-android-gcc; fi; \
    if [ "build/armeabi-v7a/config.mk" = "build/armeabi-v7a/config.mk" ]; then TGT=armv7-android-gcc; fi; \
    if [ "build/x86/config.mk" = "build/armeabi-v7a/config.mk" ]; then TGT=x86-android-gcc; fi; \
    if [ "build/mips/config.mk" = "build/armeabi-v7a/config.mk" ]; then TGT=mips32-android-gcc; fi; \
    BUILD_PFX=jni/libvpx/build/armeabi-v7a/ ../../sources/configure --target=$TGT --disable-examples --sdk-path=/Users/sino/Documents/android-ndk-r9d
mkdir -p build/x86
cd build/x86; \
    if [ "build/armeabi/config.mk" = "build/x86/config.mk" ]; then TGT=armv5te-android-gcc; fi; \
    if [ "build/armeabi-v7a/config.mk" = "build/x86/config.mk" ]; then TGT=armv7-android-gcc; fi; \
    if [ "build/x86/config.mk" = "build/x86/config.mk" ]; then TGT=x86-android-gcc; fi; \
    if [ "build/mips/config.mk" = "build/x86/config.mk" ]; then TGT=mips32-android-gcc; fi; \
    BUILD_PFX=jni/libvpx/build/x86/ ../../sources/configure --target=$TGT --disable-examples --sdk-path=/Users/sino/Documents/android-ndk-r9d
mkdir -p build/mips
cd build/mips; \
    if [ "build/armeabi/config.mk" = "build/mips/config.mk" ]; then TGT=armv5te-android-gcc; fi; \
    if [ "build/armeabi-v7a/config.mk" = "build/mips/config.mk" ]; then TGT=armv7-android-gcc; fi; \
    if [ "build/x86/config.mk" = "build/mips/config.mk" ]; then TGT=x86-android-gcc; fi; \
    if [ "build/mips/config.mk" = "build/mips/config.mk" ]; then TGT=mips32-android-gcc; fi; \
    BUILD_PFX=jni/libvpx/build/mips/ ../../sources/configure --target=$TGT --disable-examples --sdk-path=/Users/sino/Documents/android-ndk-r9d
# Preconfigure for each done
(make -n -C jni/fdk_aac init)
git clone https://android.googlesource.com/platform/external/aac sources; \
    cd sources; \
    git fetch --tags; \
    git checkout origin; \
    git checkout jb-release
# Init done
(make -n -C jni/pjsip patch)
quilt push -a && \
    touch .patched_sources
# Patch done
(make -n -C jni/webrtc patch)
quilt push -a && \
    touch .patched_sources
# Patch done
(make -n -C jni/ffmpeg patch)
quilt push -a && \
    touch .patched_sources
# Patch done
(make -n -C jni/libvpx patch)
quilt push -a && \
    touch .patched_sources
# Patch done
(make -n -C jni/silk patch)
quilt push -a && \
    touch .patched_sources
# Patch done
(make -n -C jni/fdk_aac patch)
git clone https://android.googlesource.com/platform/external/aac sources; \
    cd sources; \
    git fetch --tags; \
    git checkout origin; \
    git checkout jb-release
quilt push -a && \
    touch .patched_sources
# Patch done
# External sources fetched out from external repos/zip
(make -n -C jni/webrtc preprocess)
make[1]: *** No rule to make target `sources/build/generate_asm_header.py', needed by `sources/modules/audio_processing/aecm/aecm_core_neon_offsets.h'.  Stop.
make: *** [webrtc-preprocess] Error 2

A:

This problem is related to the SILK package. The source URL of SILK is moved to a different one. You have to download it from the source and install manually to continue.
Steps to be followed :-

svn checkout http://csipsimple.googlecode.com/svn/trunk/ CSipSimple-trunk (when successful, don't make)
Download  SILK_SDK_SRC_v1.0.9.zip: http://code.google.com/p/bkvoice/downloads/detail?name=SILK_SDK_SRC_v1.0.9.zip&can=2&q=
Create folder sources in /jni/silk/
Unzip and copy to sources
cd CSipSimple-trunk/CSipSimple
make


Q:

Show that $L(x,y)=ax^2+by^2$ is a Lyapunov function for the equilibrium at the origin

I am looking at past paper questions and I'm a little stuck on this one.
I have the following system of ODEs:

$\dot{x}=(\epsilon x+2y)(x+1)$
$\dot{y}=(-x+\epsilon y)(x+1)$
where $\epsilon$ is a parameter.
a) Show that
$L(x,y)=ax^2+by^2$
is a Lyapunov function for the equilibrium at the origin of the system of the ODEs above if $\epsilon \leq 0$ and for suitable $a,b >0$. Give an example of suitable $a,b$.
b) What does the Lyapunov function tell us about the stability of the origin for $\epsilon <0$ and for $ \epsilon =0$?

Okay, so my attempt:
$L(0,0)=a(0)^2+b(0)^2=0$
$L(x,y)>0 $ when $a,b>0$
$\frac{dL}{dt}=\frac{dL}{dx} \frac{dx}{dt} + \frac{dL}{dy} \frac{dy}{dt}$
$=2xa(\epsilon x^2 +2yx +\epsilon x +2y) +2by(-x^2 + \epsilon yx -x + \epsilon y )$
But I'm not sure where to go from there, I feel like I'm overthinking it.
If anyone could help to find a solution to study I'd be really appreciative!

A:

$$
\frac{dL}{dt}= 2ax(\epsilon x+2y)(x+1)+2by(-x+\epsilon y)(x+1)
$$
$$
=2(x+1)(a\epsilon x^2+2axy-bxy+b\epsilon y^2).
$$
If we take $a=1$, $b=2$, $\epsilon<0$ then
$$
\frac{dL}{dt}= 2(x+1)(\epsilon x^2+2\epsilon y^2)
$$
is negative in the set $\{(x,y):\, x>-1\}\setminus (0,0)$, thus, the origin is asymptotically stable.
In the case when $\epsilon=0$ this Lyapunov function can tell us only that the origin is stable because in this case $\frac{dL}{dt}=0$ for all $x$ ,$y$.


Q:

Architecture - Multiple pages in GWT means multiple modules?

This is more a design/architecture question.
I am thinking of a web app and I want to use GWT (I used it long ago and I am back to it, so just assume I am a rookie). Like many apps, it will have many entry points, the obvious being signin, lostpassword, signup, etc. More will be added.
To keep code clear & clean, would you:

Make a separate project for each entry point, or:
Have a global project and try to have multiple  (I don't know if this is feasable), or:
Have a single project, many services and manage "user entry points" via the History / Bookmark mechanism...

I am tempted by the third option, but I admit I have not pushed it yet to production, so...

A:

If the modules don't need to communicate with each other I suggest to go for 1).
It's easier to work on a small modules with GWT. Since incremental compilation isn't available yet, you can save a lot of compile time by breaking your app into modules.
Code splitting is a helpful feature, but its purpose is to break-up the app into small pieces, which is best done after the code is written and more-ore-less stable. If you can have multiple modules from the start, that's easier.
If you need to share common code consider using GWT-compatible libraries instead of merging projects.


Q:

C# class from a SQL database table

Came across this:
http://www.eggheadcafe.com/articles/adonet_source_code_generator.asp
And wondering if this is the right solution as I am not that big of a fan of creating a class for every stored procedure or do I use Enterprise Library for ASP.net 2.0 project.

A:

You definitely shouldn't be creating a class for every stored procedure. There are a number of approaches you can take to handling your database interactions. You should have a good look at the major frameworks out there and decide which one best suits you. The Castle Project solution is great, and relies on nHibernate (nHibernate). LINQ is a similar offering by Mircrosoft (LINQ Project). Both of these solutions are full ORM frameworks (Object Relational Mapping) and will generate dynamic SQL to persist your objects in the database. Each also has it's own quirks and likes you to structure your objects in particular ways. If you don't want to manage the SQL your system uses, I would definitely recommend one of these approaches.
I come from a database background, and prefer a bit more control over my SQL. In particular I like to have my interractions handled by stored procedures. I find this enables me to control both the SQL better for optimisation, but helps me manage database security in a more friendly manner. To accommodate this approach, I recommend something like iBatis (iBatis). iBatis isn't a full ORM, but rather a simple SQL mapper. The downside to my approach is that you need to write a lot more code (SQL), but I don't mind the trade-off.


Q:

Is it safe to share the first six digits of my credit card with an immigration company?

I was contacting with an Immigration company from Canada during the call the took all data which they need to start their evaluation. Then, they requested to know the first 6 digits of my payment card. I they assure to me that they need it to check my international payment method is it work or not, since I am very far and the service fees should be online. I didn’t give them anything, question is: is it safe or not?

A:

The first digit identifies the card type.

4 = Visa
5 = Mastercard
7 = American Express etc.

The top 6 digits (including that first digit) identify your bank, and also whether it is a credit, debit, or prepaid.
I almost said "the next 5 digits identifies the bank", but they are independent.  577777 might be Oahu Credit Union Mastercard, but 477777 might be United Airlines Visa managed by Synchrony.
So the first 6 digits tells them where you bank.  Essentially, they are poaching the "Know Your Customer" due diligence the banks have already done, which is likely to establish you as someone able to bank in that  country.
It's probably one of the lowest-friction ways of asking you to prove that, because it captures the info very easily, it's info you'll disclose anyway if you hire them, it avoids awkwardness like faxing over bank statements (how do you even fax anymore?), and most people do not realize their purpose, so they don't try to manipulate or lie.


Q:

What's the reason for this unusual transmission tower (pylon) design?

I saw this unusual transmission tower (pylon) while cycling recently:

This is in the UK. Specifically, it's just off the A6, between Preston and Lancaster.
The simple hanging attachments are very common, and the ones with a loop of wire are common too. But I've never seen one that is a mix before. There must be some specific reason it was constructed this way - any idea why?

A:

It appears from your photo that the lower lines have been raised to clear the roadway below.

Note that the lower lines require two insulators per phase whereas the upper ones only require one. There is a cost saving to only applying this style to the lines that require it.
The lower lines also require two splices - one at each end of the loop - whereas the upper ones can be clamped by the fixing at the bottom of the insulator. I imagine that for installation all the wires are drawn through pulleys, transferred to clamps and the bottom one clamped by the horizontal insulators before being cut and looped.
Each of the horizontal insulators on the bottom lines are approximately the same length as the ones on the upper lines. This is to be expected to maintain breakdown voltage between the lines and the earthed frame of the pylon.

You may be interested to know that Britain has a Pylon Appreciation Society!

Figure 1. A simple straight-through clamping arrangement. Notice the Stockbridge or tuned-mass dampers each side of the insulator. Source: Wikipedia Commons.

Figure 2. The horizontal insulator arrangement is more commonly seen on turning pylons. Source: Pylons.org.

Figure 3. "CHECK IF THE LIGHTS ARE WORKING NOW!" An insulator in tension.

A:

In the Netherlands we find the same situation. On a specific site concerning highvoltage transmission lines they indicate that it is sloppy work thereby disturbing the image in the landscape.
So there seems not to be any specific reason for this other then that someone on the drawing board did not give the system full attention as might be expected.
Not completely satisfied with my own answer I contacted TENNET the resposible party for this in the Netherlands.
The answer I received was:
If required adjustments are made to the lines, based upon the standard, optimum technology and most safe soluting. In this case it results in the lines being +/- 0,8 m higher.
The contracter is not to blame here because he only executes the work he has been given.


Q:

How can I change label of OK/Cancel buttons of a dialog window?

How can I change/tranlate label of OK/Cancel buttons of a dialog window of XPCOM? You can see a list of such buttons here.
Indeed I want localize Zotero Firefox add-on. A portion of code that display such dialog is here:
var regenerate = promptService.confirmEx(
    window,
    Zotero.getString('integration.revert.title'),
    Zotero.getString('integration.revert.body'),
    promptService.STD_OK_CANCEL_BUTTONS + promptService.BUTTON_POS_1_DEFAULT,
    null, null, null, null, out
);

A:

Well, first, if you want to learn XUL, I would highly recommend getting the XUL Explorer, which is an interactive tool you can use to build snippets and preview what you are designing.
This will come in handy if you've never worked in XUL before, as though it looks a lot like HTML, it's not the same lineup of elements and approaches. It really lives a bit above where HTML does, in that it's used to build desktop apps, which can be used to build things such as:
https://developer.mozilla.org/en-US/docs/tag/tools
The majority of those programs you can download the source for and look through it just like you would a list of documents. You'll also notice several extensions, such as the Firefox Web Developer add-on. Here's the source, and here's some of the XUL files. Which happens to include a dialogs directory, and a message.xul:
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/"?>
<?xml-stylesheet href="chrome://web-developer/content/dialogs/style-sheets/message.css"?>
<!DOCTYPE dialog SYSTEM "chrome://web-developer/locale/dialogs/message.dtd">
<dialog buttons="accept" id="web-developer-message-dialog" onload="WebDeveloper.Message.initialize()" title="&webdeveloper.message.title;" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
    <script src="chrome://web-developer/content/common/common.js"/>
    <script src="chrome://web-developer/content/dialogs/javascript/message.js"/>

    <vbox id="web-developer-message-details">
        <description id="web-developer-message"/>
        <description id="web-developer-more-information" value="&webdeveloper.more.information;" onclick="WebDeveloper.Message.moreInformation()" class="url"/>
    </vbox>
</dialog>

So you can use a Dialog for this, which let's you create different types of prompts. For instance, I made the following going through a tutorial some time ago:
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<dialog id="myDialog" title="My Dialog"
        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
        onload="window.sizeToContent();"
        buttons="accept,cancel"
        buttonlabelaccept="Set Favorite"
        buttonaccesskeyaccept="S"
        ondialogaccept="return doSave();"
        buttonlabelcancel="Cancel"
        buttonaccesskeycancel="n"
        ondialogcancel="return doCancel();">
  <script>
  function doSave(){
      //doSomething()
      return true;
  }
  function doCancel(){
      return true;
  }
  </script>
  <dialogheader title="My dialog" description="Example dialog"/>
  <groupbox flex="1">
    <caption label="Select favorite fruit"/>
    <radiogroup>
      <radio id="1" label="Oranges because they are fruity"/>
      <radio id="2" selected="true" label="Strawberries because of color"/>
      <radio id="3" label="Bananna because it pre packaged"/>
    </radiogroup>
  </groupbox>
</dialog>

Which looks like:

So you really have a lot of options, even, if you want, nsIPromptService...
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);

var check = {value: false};                  // default the checkbox to false

var flags = prompts.BUTTON_POS_0 * prompts.BUTTON_TITLE_SAVE +
            prompts.BUTTON_POS_1 * prompts.BUTTON_TITLE_IS_STRING  +
            prompts.BUTTON_POS_2 * prompts.BUTTON_TITLE_CANCEL;
// This value of flags will create 3 buttons. The first will be "Save", the
// second will be the value of aButtonTitle1, and the third will be "Cancel"

var button = prompts.confirmEx(null, "Title of this Dialog", "What do you want to do?",
                               flags, "", "Button 1", "", null, check);

There's also something called PopupNotifications.jsm. There's a lot there, so I'm sure there's something you can find for what you're looking to do. There's also the Zotero source, too.


Q:

"Wasn't" vs "weren't"

Which one would be correct?

I wish it weren't raining today.
I wish it wasn't raining today.
I wish it were raining today.
I wish it was raining today.

A:

The fact that you wish something was or wasn't true means you should use the indicative. You are stating that something is factually one way or another, and wishing for the situation to be reversed. So "I wish it wasn't raining today" and "I wish it was raining today" are how to express those concepts.
If you were trying to imply something contrary to fact, then were would be the way to go.

If I were you, I wouldn't be wishing it wasn't raining: rain is good for your garden.

Edit: Because Stan Rogers, whose opinion I respect, has weighed in with the polar opposite viewpoint from mine, I feel obliged to elaborate.
Morton S. Freeman, writing in A Treasury for Word Lovers, elaborates on a parallel idea using if clauses:

Some people have a mistaken belief that a clause beginning with if must always be in the subjunctive mood, reflecting doubtful fulfillment of the condition or a condition contrary to fact. This is not so. A clause introduced by if may express a simple condition relating to the past and take the indicative form of the verb. For example, in "If Allan was there, he was drunk," the if clause introduces a supposition, hence a verb in the indicative mood. And so with the sentences "If Curran was absent, he was probably out of town" and "If I was long-winded, I'm sorry." None of the examples imply doubt or suggest circumstance contrary to fact, as in "If I were President, I wouldn't pardon him." [Emphasis added.]

I think you can see the parallel here. Far from indicating a circumstance contrary to fact, the "I wish" construction is lamenting an actual fact. So subjunctive mood is not called for.


Q:

rspec with --tag option runs different test than spring rspec with same --tag option

When I run
spring rspec --tag ~slow

None of my tests are run and I see this unexpected output:
Run options:
  include {:focus=>true}
  exclude {:slow=>true}

All examples were filtered out; ignoring {:focus=>true}

All examples were filtered out

Finished in 0.21728 seconds (files took 0.43359 seconds to load)
0 examples, 0 failures

When I run:
rspec --tag ~slow

I see the following expected set of tests run:
Run options:
  include {:focus=>true}
  exclude {:slow=>true}

All examples were filtered out; ignoring {:focus=>true}

.
. testing output remove for berevity
.

Finished in 6.9 seconds (files took 15.29 seconds to load)
179 examples, 0 failures, 4 pending

Is this a problem I can fix or, if I want to use spring, do I have to give up using --tags ?
TL;DR: Seems I have to pick between saving time using Spring or saving time skipping slow rspec tests.  Can't get both.
ADDENDUM:
Submitted Spring issue here: https://github.com/rails/spring/issues/359

A:

This now works:
  time spring rspec ./spec --tag speed:slow
  time spring rspec ./spec --tag ~speed:slow

Seems adding "./spec" was the necessary change.
Using:
  * spring (1.2.0)
  * spring-commands-rspec (1.0.2)
  * rspec-collection_matchers (1.0.0)
  * rspec-core (3.0.4)
  * rspec-expectations (3.0.4)
  * rspec-mocks (3.0.4)
  * rspec-rails (3.0.2)
  * rspec-support (3.0.4)


Q:

How to call a function on .change()?

Summary: I would like to call an external function upon a status change for a checkbox.
The following code which includes the function to call upon the change works (code available at JSFiddle, commented section)
HTML
<input type="checkbox" id="cb">

JS
$("#cb").change(function () {
        if ($("#cb").prop('checked'))
        {
            alert('checked');
        } else {
            alert('unchecked')
        }
    });

As expected, an alert is raised when checking or unchecking the checkbox.

I now want to move the function part outside the .change() method:
$("#cb").change(alertme());

function alertme () {
        if ($("#cb").prop('checked'))
        {
            alert('checked');
        } else {
            alert('unchecked')
        }
    }

This does not work anymore (no alert on status change). Why is it so?

A:

You just need the function definition, don't execute it:
$("#cb").change(alertme);

A:

You want to just pass the function name to the change event, not actually call the function and pass the return value. Use this instead:
$("#cb").change(alertme);


Q:

Get Storing updated rows and previous rows as well

Let's suppose I have table as :
column_1 | column_2 | column_3 | column_4

  abc        12         23          34

  abc        01         12          45

I am looking for query something like
insert into table(column_1,column_2,column_3,column_4) values(List of updated rows i.e select (do some logic here of changing value of column_1) from where column_1='abc')
Output should be as :-
column_1 | column_2 | column_3 | column_4

  abc        12         23          34

  abc        01         12          45

  xyz        12         23          34

  xyz        01         12          45

A:

You can do it with another select from you insert. it not necessary to use insert into ... (...) values(..). You can use select as well as your value.
insert into table(column1,column2,column3,column4)
select 'xyz' as column1,column2,column3,column4
from table
where column1 = 'abc'


Q:

When a plane flies faster than the speed of sound, does the distance between plane and sound increase?

I had this discussion with my dad about a question he had asked. Basically he said:

If a plane flies faster than the speed of sound, will he be able to overtake his own sound and hear itself?

(let's leave behind the fact that he can run out of fuel or that the sound finishes before he hears it)
I disagreed because it seemed illogical to me, but we never actually found hard evidence to determine if the statement is true or false.
Can a plane actually do this?

A:

I think you are missing some physics knowledge, so let's start from here:

If a plane flies faster than the speed of sound

Sound is a compression wave that travels through air. Given a certain air temperature, the sound will travel at different speeds through the air.
If a plane flies faster than the speed of sound means that the compression waves it is generating will remain behind the aircraft:

image from here

will he be able to overtake his own sound and hear itself?

As you can see on the right picture, if the aircraft is travelling faster that the speed of sound, the compression waves it generated in the past will remain behind. If it would stop/slow down, the waves would then catch up with the plane and a person on board would be theoretically capable of hearing them.

A:

Your father asked:

If a plane flies faster than the speed of sound, will he be able to overtake his own sound and hear itself?

Of course he can!
He can catch up because he is faster. But that does not fully answer this brilliant question. We want to know what would practically happen:
But what does it sound like?
We want to catch up with our own sound, so it needs to get away from us first. That means we fly slower than sound in the beginning. For example, your father shouts

Can you hear me?

in the direction of travel.
Now, we accelerate our aircraft to be faster than sound. With that, we create a shockwave in front of the plane, which can be heard as the sonic boom. Practically, the whole situation is really loud
We hear no difference.
It does get louder, but not noticeable.
But in theory, we can think about what we would hear when it would be quiet, and we could use the air molecules in front of our shockwave as a microphone.
But if we could hear it anyway?
Then, we would actually hear "Can you hear me?", but in very deep voice, so deep that it is to deep to be heard by a human. The words were spoken in some seconds, but we reach the sound waves only slowly over some minutes.
We would hear a very deep voice...
And as we creep up to our sentence from behind, we catch the last syllable first, because that is what we said at the latest time, so it had less time to go away. The direction of the time in the sound is flipped.
Speaking the words backwards!

It's a very deep
¿em raeh uoy naC


Q:

SQL Server: Group by First Character (i.e. Letter)

How do I a query in SQL Server using T-SQL to return the counts of the first letter/character in a column's values?

A:

SELECT SUBSTRING(FileName, 1, 1) as first_letter, COUNT(FileId)
FROM Files
GROUP BY SUBSTRING(FileName,1,1)
ORDER BY first_letter

I modified an example for Oracle that can be found here:
group by first character


Q:

Open help on current word

Example:
Open the vim configuration and move the cursor to shortmess.
Now i would like to open any available help context to the current word.
I could write a function to run that command:
:h shortmess

Is there already a built-in feature to achieve that?

A:

Hi try the following mapping:
nnoremap <your-mapping> :h <c-r><c-w><cr>
it takes the current word under your cursor and searches the help pages.
see :h c_CTRL-R
In order to use K you have to set keywordprg=:help, since the default value is man. see :h K