Q:

Dosen't Reflection API break the very purpose of Data encapsulation?

Very recently I came across the Reflection API and to my surprise we can access and even alter the private variables.I tried the following code
import java.lang.reflect.Field;

public class SomeClass{
    private String name = "John";
}

public class Test{
    public static void main(String args[]) throws Exception {
        SomeClass myClass = new SomeClass();

        Field fs = myClass.getClass().getDeclaredField("name");
        fs.setAccessible(true);

        System.out.println("Variable is " + fs.getName() + " and value is "
                + fs.get(myClass));

        fs.set(myClass, "Sam");
        System.out.println("Variable is " + fs.getName() + " and value is "
                + fs.get(myClass));
    }
}

and I got the following output.
Variable is name and value is John
Variable is name and value is Sam

We say Java is an Object oriented language and it's main features are Data Encapsulation, Inheritance, Polymorphism.. etc. Isn't the reflection API changing the very purpose of Data Encapsulation? Why do we have to use Reflection API? I read in some sites that it can be used for testing purpose but according to me modules are tested and that can be done easily using JUnit test cases. So can anyone explain why do we have such a hack?

A:

Isn't the reflection API changing the very purpose of Data Encapsulation?

Yes and no.

Yes, some uses of the reflection API can break data encapsulation.
No, not all uses of the reflection API do break data encapsulation.  Indeed, a wise programmer only breaks encapsulation via the reflection API when there is a good reason to do so.
No, reflection API does not change the purpose of data encapsulation.  The purpose of data encapsulation remains the same ... even if it someone wilfully breaks it.

Why do we have to use Reflection API?

There are many uses of reflection that DO NOT break encapsulation; e.g. using reflection to find out what super types a class has, what annotations it has, what members it has, to invoke accessible methods and constructors, read and update accessible fields and so on.
And there are situations where is is acceptable (to varying degrees) to use the encapsulation breaking varieties of reflection:

You might need to look inside an encapsulated type (e.g. access / modify private fields) as the simplest way (or only way) to implement certain unit tests.
Some forms of Dependency Injection (aka IoC), Serialization and Persistence entail accessing and/or updating private fields.
Very occasionally, you need to break encapsulation to work around a bug in some class that you cannot fix.

I read in some sites that it can be used for testing purpose but according to me modules are tested and that can be done easily using JUnit test cases. So can anyone explain why do we have such a hack?

That depends on the design of your class.  A class that is designed to be testable will either be testable without the need to access "private" state, or will expose that state (e.g. protected getters) to allow testing.  If the class doesn't do this, then a JUnit test may need to use reflection to look inside the abstraction.
This is not desirable (IMO), but if you are writing unit tests for a class that someone wrote, and you can't "tweak" the APIs to improve testability, then you may have to choose between using reflection or not testing at all.

The bottom line is that data encapsulation is an ideal that we strive to achieve (in Java), but there are situations where the pragmatically correct thing to do is to break it or ignore it.
Note that not all OO languages support strong data encapsulation like Java does.  For example, Python and Javascript are both unarguably OO languages, yet both make it easy for one class to access and modify the state of objects of another class ... or even change the other classes behaviour.  Strong data abstraction is not central to everyone's view of what Object-Oriented means.


Q:

npm failed to install time with make not found error

When i try to install time on nodejs server i get the below error:
time@0.8.4 install /var/www/track/node_modules/time
node-gyp rebuild
gyp ERR! build error
gyp ERR! stack Error: not found: make
gyp ERR! stack     at F (/usr/lib/nodejs/npm/node_modules/which/which.js:43:28)
gyp ERR! stack     at E (/usr/lib/nodejs/npm/node_modules/which/which.js:46:29)
gyp ERR! stack     at /usr/lib/nodejs/npm/node_modules/which/which.js:57:16
gyp ERR! stack     at Object.oncomplete (fs.js:297:15)
gyp ERR! System Linux 3.2.0-31-virtual
gyp ERR! command "node" "/usr/lib/nodejs/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /var/www/track/node_modules/time
gyp ERR! node -v v0.8.15
gyp ERR! node-gyp -v v0.7.1
gyp ERR! not ok
npm ERR! time@0.8.4 install: `node-gyp rebuild`
npm ERR! `sh "-c" "node-gyp rebuild"` failed with 1
npm ERR!
npm ERR! Failed at the time@0.8.4 install script.
npm ERR! This is most likely a problem with the time package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls time
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.2.0-31-virtual
npm ERR! command "nodejs" "/usr/bin/npm" "install" "time"
npm ERR! cwd /var/www/track
npm ERR! node -v v0.8.15
npm ERR! npm -v 1.1.66
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /var/www/track/npm-debug.log
npm ERR! not ok code 0

A:

Which OS are you using?
If it's Ubuntu you'll need to install the build-essential package:
$ sudo apt-get install build-essential

Then try to install the package again.

A:

Simple Solution:
sudo apt-get install build-essential

and try again

A:

I had the same problem using Docker, both on CENTOS 7 and RHEL 7 base images... do the following:
RUN yum install -y make gcc*

Worked perfectly for me!


Q:

Qu'est-ce qu'on entend par « Une couille dans le potage, c’est une erreur, deux, c’est une recette » ?

Que veut dire Franz Bartelt dans cette phrase, citée dans le livre Et Puis Paulette :

Une couille dans le potage, c’est une erreur, deux, c’est une recette.

Et est-ce que ça a un sens vulgaire ?

A:

Le mot "couille" est vulgaire, mais l'expression "dans le potage" montre que la "couille" n'est pas à sa place, donc cela indique qu'une erreur ou une faute a été commise.
De fait, l'usage du mot "couille" pour désigner une erreur vient du monde de l'imprimerie, où l'on appelait toute erreur typographique "une couille du typographe", parce que la plus mémorable de ces "couilles" avait été l'omission de la lettre "q" dans le mot "coquille", ce qui produit effectivement une regrettable erreur...
Ajoutons que, dans l'imprimerie toujours, beaucoup rechignaient à employer le mot "couille" en raison de sa vulgarité, aussi l'erreur typographique prit plutôt le nom de "coquille".

A:

Je n'ai pas lu le livre et je ne connais pas le contexte dans lequel la phrase a été dite, donc difficile d'interpréter la phrase avec certitude, mais je pense que c'est un jeu de mot basé sur l'expression suivante:
Il y a une couille dans le potage signifie qu'il y a un problème qu'on n'a pas identifié:

L'expression viendrait de la Vendée où la touille est une cuillère à
  soupe, qui serait restée dans le potage. Par extension, l'expression
  est devenue familière, et trouver une couille dans son potage est un
  problème qui n'est pas identifié.

Si il y en a deux, alors on sort de cette expression et on passe au sens littéral, qui peut être considéré comme étant une recette de cuisine.
Le sens n'est pas vulgaire, mais le niveau de langue l'est.


Q:

MongoDb search on date field

I have a Mongo collection with 'DateAdded' in ISODate format
{
"_id" : 4098199,
"DateAdded" : ISODate("2018-08-31T05:06:13.150Z")
}

so it is 1hour off then local datetime
LocalDatetime is 2018-08-31 06:06:13 +01:00
UTC is 2018-08-31T05:06:13.150Z

Using following query when i try to get records added after 2018-08-31 06:00:00 i m not getting this records as it is in UTC
 db.getCollection('User').find({"DateAdded":{$gte: new ISODate('2018-08-31T6:00:00Z')}})

How to convert UTC date while doing search on date field in MongoDB?

A:

First of all ISODate('2018-08-31T6:00:00Z') has a typo - it should be 06:00:00Z. Without leading 0 ISODate helper returns '2018-08-31T00:00:00Z' 0am UTC and the query actually returns the document.
Secondly, there is nothing about local time. ISODate is in UTC, so
ISODate("2018-08-31T05:06:13.150Z") is 5am UTC and ISODate("2018-08-31T06:06:13.150Z") is 6am UTC. 5 < 6, so the $gte condition doesn't meet and the document is not returned.
Lastly, if you want to use local time - use Date instead:
db.getCollection('User').find({"DateAdded":{$gte: new Date('2018-08-31T6:00:00')}})

Will return all documents created after 5am UTC, 6am local time. Note, there is no Z at the end, which specifies UTC timezone.
As a recommendation - don't mess up with local time. Convert it to UTC as soon as possible and always work with UTC.


Q:

Break or split up code in Script Editor

I hope I'm not asking too many questions here. But this one is pretty simple I think. From this javascript site it says we can break up code to make it neater.
http://www.w3schools.com/js/js_statements.asp
But when I try it in Apps Script it says the "\" is an illegal character.
So basically I have a really long string and it makes my code look horrendous when it is allowed to go fully horizontal.
DocsList.getFolder('ABCDE' + someStringVariable + '/FGHIJKLMNOPQRSTUV' + someOtherStringVariable + 'WXYZ');

This would look better like this (IMHO):
DocsList.getFolder('ABCDE' + someStringVariable \
                         + '/FGHIJKLMNOPQRSTUV' \
                      + someOtherStringVariable \
                                        + 'WXYZ');

Anyways, that was my question.
Thanks in advance!

A:

Just use the + sign to break across lines.
DocsList.getFolder('ABCDE' + someStringVariable +
                           '/FGHIJKLMNOPQRSTUV' +
                        someOtherStringVariable +
                                        'WXYZ');


Q:

500 Internal Server Error with Wamp and Magento

I am stuck at accessing the installation page, can't seem to get it to work, it always gives me a 500 Internal Server Error error.
I have looked into some of the similar question solutions but they didn't work.

A:

Following error you have given in your post's comment should lead you to the solution after a little search.
The problem is Magento's .htaccess file consists <IfVersion> command.
In order to use this feature mod_version module should have enabled on your Apache web server. Otherwise it will give 500 error.
In Wamp it is disabled by default.
To enable it in Wamp you can do following steps:

Find your apache config file (httpd.conf) : It usually is under /wamp/bin/apache/apache(version)/conf/httpd.conf
Open the configuration file with your favourite text editor: You can simply use Notepad. But I suggest any other one since notepad sometimes doesn't show line breaks. It will be more readable if you do (e.g. Notepad++)
Search the following text: "mod_version"
You will see following line: #LoadModule version_module modules/mod_version.so
Uncomment it, so it will become enabled: Simply delete # sign to uncomment it
Left Click on Wamp and press Restart All Services: Since you have made changes in the configuration file in order to let Apache server know about the changes you should restart at least Apache server.

Now you can check if Magento is working. If it isn't check the error log again. There might be another issue.
Following 6 steps should easily solve the error that you have provided in the comment. Also, please edit your post and add more details e.g. error log.


Q:

Get Random Color

Do you know any method to generate a random Color (not a random Color Name!)?
I've already got one, but this one is'nt doing it correctly:
This only returns Green:
Random r = new Random();
BackColor = Color.FromArgb(r.Next(0, 256), r.Next(0, 256), 0);

This only returns Red:
Random r = new Random();
BackColor = Color.FromArgb(r.Next(0, 256), 0, 0);

This only returns Blue:
Random r = new Random();
BackColor = Color.FromArgb(0, 0, r.Next(0, 256));

I want my Code to return one, random Color, not only green/red/blue every time, as the above ones do.
How to solve this?
Any suggestion will be approved with joy!

A:

Here's the answer I started posting before you deleted and then un-deleted your question:
public partial class Form1 : Form
{
    private Random rnd = new Random();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));

        BackColor = randomColor;
    }
}

A:

The original version of your last method (pre-Edit) will return all different sorts of colors.   I would be sure to use a single Random object rather than create a new one each time:
Random r = new Random();
private void button6_Click(object sender, EventArgs e)
{
    pictureBox1.BackColor = Color.FromArgb(r.Next(0, 256),
         r.Next(0, 256), r.Next(0, 256));

    Console.WriteLine(pictureBox1.BackColor.ToString());
}

It produces all sorts of different colors:

Color [A=255, R=241, G=10, B=200]
  Color [A=255, R=41, G=125, B=132]
  Color [A=255, R=221, G=169, B=109]
  Color [A=255, R=228, G=152, B=197]
  Color [A=255, R=50, G=153, B=103]
  Color [A=255, R=92, G=236, B=162]
  Color [A=255, R=52, G=103, B=204]
  Color [A=255, R=197, G=126, B=133]


Q:

How to compile C++ mongo project

I need help! How to compile c++ mongo project in linux?
I'm doing this:
 1) Install boost
 2) Compile mongodb driver
 3) Try to compile example (fail)
My compile mongodb drivers exist in /home/developer/documents/drivers/mongo-cxx-driver-v2.4/build
I'm trying to compile this file
#include <cstdlib>
#include <iostream>
#include "mongo/client/dbclient.h"

void run() {
  mongo::DBClientConnection c;
  c.connect("localhost");
}

int main() {
  try {
    run();
    std::cout << "connected ok" << std::endl;
  } catch( const mongo::DBException &e ) {
    std::cout << "caught " << e.what() << std::endl;
  }
  return EXIT_SUCCESS;
}

And execute this command: g++ tutorial.cpp -pthread -lmongoclient -lboost_thread-mt -lboost_filesystem -lboost_program_options -lboost_system -o tutorial
This command fail. Error message - "mongo/client/dbclient.h" not found. How to compile this example? Help me, please!

A:

You need to use -I and -L to specify where you have installed your mongo header(s) and library(ies):
g++ tutorial.cpp -I/path/to/mongo/include/ -pthread -L/path/to/libmongoclient
                 -lboost_thread-mt -lboost_filesystem -lboost_program_options
                 -lboost_system -o tutorial


Q:

Is there a way to temporarily pause iCloud sync of photos?

Is there a way to temporarily pause the syncing of photos over iCloud on an iOS device? Sometimes I'm on a 3G connection and don't want to waste my quota syncing photos or sometimes I want to speed up the download of other files by pausing iCloud. Is it possible?

A:

There is no way to pause it, but you can disable it temporarily. The only downside is that you will have to redownload all the pictures when it is re-enabled. To disable cell data for photo stream, you can go into Settings>Cellular and find the Photos app. Simply turn it off.


Q:

In Ruby On Rails, how can I remove views related to a specific controller

For example, I created this post_controller earlier in the project but I decide to destroy it later.
Then I use
rails destroy controller post_controller

to remove the controller. But I also want to remove the views that attach to this controller.
In this case, they are the erb files in the app/views/post folder. How can I remove those erb files?

A:

You can run rails d scaffold post but be warned this will destroy the rest of the scaffolded elements including any models/routes/assets etc.  Here is the full list of what it will destroy:
⌘ ~/testapp/ rails d scaffold post
  invoke  active_record
  remove    migration.rb
  remove    app/models/post_controller.rb
  invoke    test_unit
  remove      test/unit/post_controller_test.rb
  remove      test/fixtures/post_controllers.yml
  invoke  resource_route
   route    resources :post_controllers
  invoke  scaffold_controller
  remove    app/controllers/post_controllers_controller.rb
  invoke    erb
  remove      app/views/post_controllers
  remove      app/views/post_controllers/index.html.erb
  remove      app/views/post_controllers/edit.html.erb
  remove      app/views/post_controllers/show.html.erb
  remove      app/views/post_controllers/new.html.erb
  remove      app/views/post_controllers/_form.html.erb
  invoke    test_unit
  remove      test/functional/post_controllers_controller_test.rb
  invoke    helper
  remove      app/helpers/post_controllers_helper.rb
  invoke      test_unit
  remove        test/unit/helpers/post_controllers_helper_test.rb
  invoke  assets
  invoke    coffee
  remove      app/assets/javascripts/post_controllers.js.coffee
  invoke    scss
  remove      app/assets/stylesheets/post_controllers.css.scss
  invoke  scss

Edit:
To clarify, rails d is just shorthand for rails destroy. It can also be used as rails generate/ rails g.


Q:

Can I connect to two networks simultaneously with two Ethernet cards?

I have a LAN in my building that uses the 10.10.19.* IP range. In addition, I have an ADSL connection at home that uses the 192.168.1.* IP range internally. I also have two Ethernet cards.
Is there any way by which I can access the two networks at the same time? I need a rule that routes all 10.10.19.* traffic through eth0 and everything else through eth1. Is this possible?
I need to do this on Ubuntu 9.10 as well as Windows 7.

A:

Absolutely possible.  You need to configure your routes properly to do this.  You want your default route to go through your eth1, so your routing table should look like this:
$ /sbin/route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
10.10.19.0      *               255.255.255.0   U     0      0        0 eth0
192.168.1.0     *               255.255.255.0   U     0      0        0 eth1
default         192.168.1.1     0.0.0.0         UG    0      0        0 eth1

Windows will look somewhat similar (with formatting variations of course) using the route print command.
You can set up the routes dynamically with the route commands on either platform.  I'm not sure what configuration options you need to set one as default (and the other as not-default, obviously)... will edit with that info.
Edit:  If you're working with the GNOME or KDE GUI network managers, look for a "set this interface as default" option in the configuration for your eth1 device.
If you're configuring /etc/network/interfaces by hand, take a look at the examples in this HOWTO.  In particular, the up option allows you to run commands after an interface comes up.  In your case, you may need to use that to run a route-delete command on an extra default route, or to run a route-add if neither of your interfaces set themselves as a default route:
# example /etc/network/interfaces
# replace the IP addresses in the route-del and route-add commands below
# with those appropriate to your network

auto eth0
iface eth0 inet dhcp
    up route del default gw 10.10.19.1
    # runs a route-delete if dhcp adds a default gateway for this interface

auto eth1
iface eth1 inet dhcp
    up route add default gw 192.168.1.1
    # runs a route-add if dhcp neglects to add a default gateway for this interface


Q:

Replace a substring in C#

I have the following string, "Last Run: 2011-10-03 13:58:54 (7m 30s  ago) [status]" and I would like to replace "7m 30s" (it is not a fixed string) with another string I have generated. How can I do that with string manipulation in C#?

A:

string str = "Last Run : (3m 4s ago) [status]";
str = str.Replace("3m 4s", "yournewstring");

UPDATE :
Ref : Kash's answer.
If time is not fixed, it might be in hour,day, minute and second then regular expression is best choice as it's done by Kash. You can do it like below :
string str = "Last Run: 2011-10-03 13:58:54 (7m 30s  ago) [status]";
string replacement = "test";
string pattern = @"\((.+?)\s+ago\)";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(str, "(" + replacement + " ago)");
MessageBox.Show(result);

A:

You should consider using String.Format instead for this
string result = String.Format("Last Run : ({0} ago) [status]", theTime);

This is only if you have control over the string in question.

A:

For the most convenient way to resolve this, use a combination of RegEx and String.Replace like the below code. I am assuming you do not have access to the generation of this input string (Last Run: 2011-10-03 13:58:54 (7m 30s  ago) [status]).
It basically has 3 stages:
Locate the pattern:
I am using the braces in the input string and "ago" as the pattern to locate the duration that you need to replace. "((.+?)\s+ago)" is the pattern used.
It uses the lazy quantifier "?" to ensure it does minimal matching instead of a greedy match. May not be applicable to your example here but helps if the method will be reused in other scenarios.
Create the backreference group to get the exact substring 7m 30s
Regex.Match uses the pattern and creates the group that will contain "7m 30s". Please note the 1st group is the entire match. The 2nd group is what will be in the braces specified in the pattern which in this case is "7m 30s". This should be good even if later you get a duration that looks like: "Last Run: 2011-10-03 13:58:54 (1d 3h 20m 5s ago) [status]"
Replace the occurence
Then String.Replace is used to replace this substring with your replacement string.
To make it more generic, the method Replace below will accept the inputstring, the replacement string, the pattern and the group number of the backreference (in this case only one group) so that you can reuse this method for different scenarios.
    private void button1_Click(object sender, EventArgs e)
    {
        string inputString = "Last Run: 2011-10-03 13:58:54 (7m 30s  ago) [status]";
        string replacementString = "Blah";
        string pattern = @"\((.+?)\s+ago\)";
        int backreferenceGroupNumber = 1;
        string outputString = Replace(inputString, replacementString, pattern, backreferenceGroupNumber);
        MessageBox.Show(outputString);
    }

    private string Replace(string inputString, string replacementString, string pattern, int backreferenceGroupNumber)
    {
        return inputString.Replace(Regex.Match(inputString, pattern).Groups[backreferenceGroupNumber].Value, replacementString);
    }

This has been tested and it outputs "Last Run: 2011-10-03 13:58:54 (Blah  ago) [status]".
Notes:

You can modify the Replace method appropriately for IsNullOrEmpty
checks and/or null checks.
The button1_Click was my sample    eventhandler that I used to test
it. You can extract part of this in your core code.
If you do have access to the generation of the input string, then you can control the duration part while you are generating the string itself instead of using this code to replace anything.


Q:

Docker port binding doesn't seem to work

I am running an example from Docker tutorial:
docker run -d -P nginx

This starts correctly as docker ps outputs the following:
CONTAINER ID   IMAGE   COMMAND                  CREATED             STATUS              PORTS                                           NAMES
a5838f701c8f   nginx   "nginx -g 'daemon off"   3 minutes ago       Up 2 minutes        0.0.0.0:32773->80/tcp, 0.0.0.0:32772->443/tcp   compassionate_stallman

When I run docker inspect a5838f701c8f, I can see the IP of the container is 172.17.0.2.
However, for some reason going to localhost:32772 or 127.0.0.1:32772 or 0.0.0.0:32772 gives me ERR_CONNECTION_REFUSED. Going to 172.17.0.2:32772 just seems to endlessly load and load and never loads anything...
Could this be something with my host? I am using OSX 10.9.5 and docker 1.10.3, build 20f81dd.

A:

You should test with URL 192.168.99.104:32772 If you are using Docker Machine.
Please take a look with https://docs.docker.com/machine/reference/ip/ to know how to get IP address with Docker Machine


Q:

How can I insert data into a table when I need to know the value of the foreign key from another table?

I have two tables:
Customer with the field ID which is auto increment and the Primary Key and
address with the field customer_ID which is a foreign key .
I have a form which asks for all of the customer info and their addresses ( can be more than 1)
I run the following two query's to update the database however I am currently inputting the value for Customer_ID manually to test it.
mysql_query("INSERT INTO customer(First_Name, Surname, Company_Name, Telephone, Alt_Telephone)VALUES('$fName', '$lName', '$cName', '$tel', '$altTel')") ;
mysql_query("INSERT INTO address(line_1, line2, town, postcode, customer_ID)VALUES('$line1', '$line2', '$town', '$post_code', '2')") ;

The customer_ID field should be the same as the current ID field from the customer table how can I make sure that when the address table is filled in it is doing this automatically?

A:

Using PHP
The easiest solution to your problem would be to call mysql_insert_id in your php-code after your first call to mysql_query (inserting data into your table customer).
This function will return the last id inserted, though you'll have to make sure that the id of customer is a primary key which is auto-incremented.
The value returned by mysql_insert_id is local to the given connection/session, even if another connection inserts a record after you did you'll get the id inserted by you.

Using MySQL
You could use the SQL-function LAST_INSERT_ID() as the below, just make sure that the previous sql-query ran was the insert into customer (as well as checking so that the id is indeed a key and auto-incremented).
-- first insert into `customer`

INSERT INTO address
  address(line_1, line2, town, postcode, customer_ID)
VALUES
  ('$line1', '$line2', '$town', '$post_code', LAST_INSERT_ID());

Same thing here as with the php-version, LAST_INSERT_ID() will retrieve the last inserted ID by you.

You could also use a SQL feature which could be described as SELECT INTO, see the below snippet:
INSERT INTO address
 address(line_1, line2, town, postcode, customer_ID)
SELECT
  '$line1', '$line2', '$town', '$post_code', customer.id
FROM customer
WHERE <some_constraint>


Q:

Validation prints whole regex - change this?

I have some validation in a view model:
[Required(
    AllowEmptyStrings = false,
    ErrorMessageResourceType = typeof(Resources.ValidationMessages),
    ErrorMessageResourceName = "invalid_cellphoneNumber")]
    [RegularExpression(@"^[1-9]{1}[0-9]{7}$")]
public string CellphoneNumber { get; set; }

And this works, regex and error message.
In my markup, I have this:
@Html.TextBoxFor(m => m.CellphoneNumber, new { id = "mobile", type = "tel"})

This will generate an input element. I have also included the right javascripts so that it runs client side as well as server side. The trouble is; when I write something invalid, mvc seems to have created its own error message;
The field CellphoneNumber must match the regular expression '^[1-9]{1}[0-9]{7}$'., instead of using the one I defined. The only way it displays my error message is if the fields are empty and try to submit the form or erase whats write in it, then it changes to my message.
The generated input element looks like this:
<input data-val="true" data-val-regex="The field CellphoneNumber must match the regular expression '^[1-9]{1}[0-9]{7}$'." data-val-regex-pattern="^[1-9]{1}[0-9]{7}$" data-val-required="Cellphone number not valid" id="mobile" name="CellphoneNumber" type="tel" value="" class="input-validation-error">.
Can anyone help?

A:

The ErrorMessageResource... properties are per Validation Attribute. I am afraid you have to specify it again for the RegularExpression validation attribute as well.


Q:

Angular 4 'this' is undefined

I try to know the value of an input within the function, but when I try to call the next line in the function "validateAllFormFields()":
 if (this.txtImporteMaximoVC==="0")

"this" is "undefined"
what I want is to retrieve the control value of "txtImporteMaximoVC", but if I try to recover the value from the formcontrol with control.value, it always returns empty and the input really has values, I think that control.value ="" because de formControl is using a directive.
the component.ts:
        import { Component, HostBinding, OnDestroy, OnInit, Input, Output, EventEmitter, ElementRef, NgModule, ViewChild, ChangeDetectorRef  } from '@angular/core';
import { Validators, FormBuilder, FormControl, FormGroup, AbstractControl,  ValidatorFn } from '@angular/forms';
import { AfterViewChecked } from '@angular/core/src/metadata/lifecycle_hooks';
import { CustomValidators } from '../../../shared/customValidators/custom.validators';
import { CurrencyPipe } from "../../../shared/pipes/pipeFormatCurrency/currency.pipe";
import { FieldErrorDisplayComponent } from '../../../shared/comun/fieldErrorDisplay/field-error-display.component'
import { FocusDirective } from '../../../shared/directives/focus.directive';

@Component({
    selector: 'app-formulario-contrato',
    templateUrl: './contrato.component.html',
    styleUrls: ['./contrato.component.css'],
    providers: [CurrencyPipe],

})
export class FormularioContratoComponent  {

    @Output() pressPointDecimal: boolean;
    @Output() setFormat: boolean;
    @ViewChild('txtImporteMaximo') txtImporteMaximoVC;
    //__________________________________________________ Validaciones formulario:

    constructor(private elRef: ElementRef, private formBuilder: FormBuilder, private cdRef: ChangeDetectorRef, private formatcurrencypipe: CurrencyPipe) {

        this.createForm();
    }

    public txtImporteMaximo = new FormControl('', [this.lessThanZeroValidator]);

    createForm() {
        this.contratoForm = this.formBuilder.group({
            txtImporteMaximo: this.txtImporteMaximo,
        });
    }

    lessThanZeroValidator(fieldControl: FormControl) {
        if (fieldControl && fieldControl.value != null && !isNaN(parseInt(fieldControl.value)) && fieldControl.value <= 0) {
            return { lessThanZeroErr: true };
        }
        else {
            return null;
        }
    }

    isFieldInvalid(field: string) {
        if (this.contratoForm && this.contratoForm.get(field)) {
            return !this.contratoForm.get(field).valid && this.contratoForm.get(field).touched;

        } else {
            if (this.contratoForm && this.contratoForm.controls["fechas2"].get(field)) {
                return !this.contratoForm.controls["fechas2"].get(field).valid && this.contratoForm.controls["fechas2"].get(field).touched;
            }
        } // if (this.contratoForm && this.contratoForm.get(field)) {

        return null;
    }

    ngAfterViewChecked() {
        this.cdRef.detectChanges();
    }

    limpiar() {
        this.contratoForm.reset();
    }

    onClick() {
        this.validateAllFormFields(this.contratoForm);
    }

    onCloseLink() {
        if (this.closeFunction) {
            this.closeFunction();
        }
    }

    validateAllFormFields(formGroup: FormGroup) {
        Object.keys(formGroup.controls).forEach(field => {
            const control = formGroup.get(field);
            if (control instanceof FormControl)
            {
                if (field == "txtImporteMaximo") {

                    if (this.txtImporteMaximoVC === "0") {
                        control.setErrors({ lessThanZeroErr: true });
                    }
                }
                control.markAsTouched({ onlySelf: true });
            } else if (control instanceof FormGroup) {
                this.validateAllFormFields(control);
            }
        });
    }

}

component.html:

    <form [formGroup]="contratoForm" #form="ngForm">

                    Importe Máximo
                    <input autocomplete="off" [formControl]="txtImporteMaximo" type="text" id="txtImporteMaximo" name="txtImporteMaximo" class="cajaTexto ancho80" currencyFormatterDirective [pressPointDecimal]="true" [setFormat]="true" />

                    <app-field-error-display [displayError]="'true'" [errorMsg]="'El importe debe ser mayor que cero'"></app-field-error-display>

                    <app-field-error-display [displayError]="'true'" [errorMsg]="'Por favor, informe el campo importe máximo'"></app-field-error-display>

                <button class="btn btn-primary boton" type="button" style="float:right;" (click)="onCloseLink()">
                     Cancelar
                </button>

                <button class="btn btn-primary boton" type="button" style="float:right;" (click)="limpiar()">
                     Limpiar
                </button>
                <button type="submit" [disabled]="!contratoForm.valid" class="btn btn-primary boton" style="float:right;" (click)="onClick()">
                     Guardar
                </button>

    </form>

Any idea?

A:

Who calls validateAllFormFields method? There may be cases where execution context may not be defined... You may try to bind Component's this to that method explicitly on the Component's constructor:
this.validateAllFormFields = this.validateAllFormFields.bind(this);


Q:

Imperative form - 'a matar'. How to negate it? How to build on reflexives?

I know you can say in the imperative way the following:

a matar
a matarlo

Questions:

Can you use the negative form? Example: "A no matar"?
How do you use apply this construction to reflexive verbs? For example, should it be "A ducharte", "a ducharse"?

A:

I could not find any official sources for this, so this answer is about the way I am used to hearing it in Spain.
The use of "a+infinitive" as an imperative transmits a sense of urgency, as in "do it now". The typical example "¡A comer!" means that the food is ready and it is time to eat. Therefore, this construction is seldom used in negative, as negative imperatives do not usually require immediate action*.
Regarding pronouns, there is a poem by Pablo Neruda with the title "A callarse", so at least Pablo Neruda seems to prefer the infinitive pronoun "se" to the person-related pronouns "te", "os". This is consistent with what I am used to hearing.
*That said, I have been known to say "A no preocuparse", which would answer both your questions but is only one data point.

A:

This is a partial answer, to supplement the answer by @wimi.
Your options for the duchar example are

A duchar
A ducharse

with the latter preferred.  You wouldn't say "A ducharte" because in this construction the verb is expressed for a general person, not for a particular person.  (Note this is consistent with what wimi said about Neruda's work.)
I would generally prefer the latter option, "A ducharse," because the shorter one could sound abrupt and a bit like a drill sergeant barking an order.  However, sometimes in family life one needs to minimize the number of syllables and so one might say "A duchar."
My personal opinion about the negative is that since this construction is a call to immediate action, in general the negative doesn't work.  That's what makes "A no preocuparse" charming.  It is a breaking of a grammatical rule, and the irony helps the worry wart laugh.  As a parent of a child with OCD, I've seen that the laughter distraction is one of the best ways of coping with worrying.
As a more common example, consider the command to not pay taxes.  There are no slogans or posters saying "A no pagar impuestos."  Instead, the imperative form "No pagar impuestos" is used.


Q:

What does stub.callsArg(index) from Sinon.JS do?

Seriously, I can't figure this out. The documentation gives us:
stub.callsArg(index) - Causes the stub to call the argument at the provided index as a callback function. stub.callsArg(0); causes the stub to call the first argument as a callback.
However, I've got no idea where this list of arguments to be indexed into is. Maybe I just don't understand what a stub is...

A:

A stub is a noop function with programmable behavior. In your case callsArg(index) will program the stub to expect a function at index and immediately invoke it.
function sayHi() {
  console.log('hi');
}
var stub = sinon.stub().callsArg(2);
stub('abc', 42, sayHi); // prints "hi"


Q:

How to check Redshift COPY command performance from AWS S3?

I'm working on an application wherein I'll be loading data into Redshift.
I want to upload the files to S3 and use the COPY command to load the data into multiple tables.
For every such iteration, I need to load the data into around 20 tables.
I'm now creating 20 CSV files for loading data into 20 tables wherein for every iteration, the 20 created files will be loaded into 20 tables. And for next iteration, new 20 CSV files will be created and dumped into Redshift.
With the current system that I have, each CSV file may contain a maximum of 1000 rows which should be dumped into tables. Maximum of 20000 rows for every iteration for 20 tables.
I wanted to improve the performance even more. I've gone through https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-S3.html
At this point, I'm not sure how long it's gonna take for 1 file to load into 1 Redshift table. Is it really worthy to split every file into multiple files and load them parallelly?
Is there any source or calculator to give an approximate performance metrics of data loading into Redshift tables based on number of columns and rows so that I can decide whether to go ahead with splitting files even before moving to Redshift.

A:

You should also read through the recommendations in the Load Data - Best Practices guide: https://docs.aws.amazon.com/redshift/latest/dg/c_loading-data-best-practices.html
Regarding the number of files and loading data in parallel, the recommendations are:

Loading data from a single file forces Redshift to perform a
serialized load, which is much slower than a parallel load.
Load data files should be split so that the files are about equal size,
between 1 MB and 1 GB after compression. For optimum parallelism, the ideal size is between 1 MB and 125 MB after compression.
The number of files should be a multiple of the number of slices in your
cluster.

That last point is significant for achieving maximum throughput - if you have 8 nodes then you want n*8 files e.g. 16, 32, 64 ... this is so all nodes are doing maximum work in parallel.
That said, 20,000 rows is such a small amount of data in Redshift terms I'm not sure any further optimisations would make much significant difference to the speed of your process as it stands currently.


Q:

How do I refer to an Excel sheet by name to import Excel data into a Notes app using LotusScript?

I am trying to look up some data in an excel sheet to populate a field in a Lotus Notes app on demand. I am using an Action button with LotusScript like so:
Dim v As String
Dim v2 As String
'Open XL sheet for access to data
Set oExcel = CreateObject ( "Excel.Application" )
v="\\msp2\mi\CSD\Confidential\IT and PPST budget.xlsm"
Msgbox("opening " & v)
Set oWorkbook = oExcel.workbooks.open(v)
Set oWorkSheet= oWorkbook.worksheets (4)
v2=Cstr(oWorkSheet.Cells(1,1).value)
Messagebox(v2)

This code does work in that it pulls data from cell A1 - but which sheet?
The sheet containing the data I want is "Sheet4" renamed as "Logic-Detail" but if I use 4 as a parameter as above I get data from the 4th sheet from the left.  I need to be able to cope with sheets being hidden as well. I spent 20 minutes on MSDN's excel object model "help" getting nowhere  :-(
I feel sure it must be dead easy when you know the answer !

A:

Guessing at the correct syntax is frustrating, isn't it? When referring to sheets in Excel-VBA there are several options:

You can list them by index-number, as you already did in the code-sample in your question
You can refer to it by its name, in your case this would probably be oWorkbook.Worksheets("Logic-Detail")
You can refer to it by its codename, in your case this would probably be oWorkbook.Sheet4. The codename can be changed when you view the properties of the worksheet in the VBA editor.

There may be even more ways to refer to the sheet, but these are the ones which come to mind at the moment. As we know from the question and comments, at least the two first options also work in LotusScript.


Q:

Friends-of-friends algorithm written in Python need to be in Fortran 90/95

I'm trying to write my own code for a 'friends-of-friends' algorithm. This algorithm acts on a set of 3d data points and returns the number of 'halos' in the dataset. Each halo is a collection of point whose distance is less than the linking length, b, the only parameter of the program.
Algorithmic Description:
 The FOF algorithm has a single free parameter called the linking length. Any two  particles that are separated by a distance less than or equal to the linking length are called "friends". The FOF group is then defined by the set of particles for which each particle within the set is connected to every other particle in the set through a network of friends.
Set FOF group counter j=1.

For each particle, n, not yet associated with any group:
Assign n to group j, initialize a new member list, mlist, for group j with particle n as first entry,
Recursively, for each new particle p in mlist:
Find neighbors of p lying within a distance less than or equal to the linking length, add to mlist those not already assigned to group j,
Record mlist for group j, set j=j+1.

This is my attempt to code the algorithm. The only language I'm comfortable in doing this is Python. However, I need this code to be written in Fortran or make it faster. I really hope someone would help me.
First I generate a set of points that should mimic the presence of 3 halos:
import random
from random import *
import math
from math import *
import numpy
from numpy import *
import time

points = 1000

halos=[0,100.,150.]

x=[]
y=[]
z=[]
id=[]
for i in arange(0,points,1):
   x.append(halos[0]+random())
   y.append(halos[0]+random())
   z.append(halos[0]+random())
   id.append(i)

for i in arange(points,points*2,1):
   x.append(halos[1]+random())
   y.append(halos[1]+random())
   z.append(halos[1]+random())
   id.append(i)

for i in arange(points*2,points*3,1):
   x.append(halos[2]+random())
   y.append(halos[2]+random())
   z.append(halos[2]+random())
   id.append(i)

Then I coded the FOF algorithm:
  x=array(x)
  y=array(y)
  z=array(z)
  id=array(id)

  t0 = time.time()

  id_grp=[]
  groups=zeros((len(x),1)).tolist()
  particles=id
  b=1 # linking length
  while len(particles)>0:
  index = particles[0]
  # remove the particle from the particles list
  particles.remove(index)
  groups[index]=[index]
  print "#N ", index
  dx=x-x[index]
  dy=y-y[index]
  dz=z-z[index]
  dr=sqrt(dx**2.+dy**2.+dz**2.)
  id_to_look = where(dr<b)[0].tolist()
  id_to_look.remove(index)
  nlist = id_to_look
  # remove all the neighbors from the particles list
  for i in nlist:
        if (i in particles):
           particles.remove(i)
  print "--> neighbors", nlist
  groups[index]=groups[index]+nlist
  new_nlist = nlist
  while len(new_nlist)>0:
          index_n = new_nlist[0]
          new_nlist.remove(index_n)
          print "----> neigh", index_n
          dx=x-x[index_n]
          dy=y-y[index_n]
          dz=z-z[index_n]
          dr=sqrt(dx**2.+dy**2.+dz**2.)
          id_to_look = where(dr<b)[0].tolist()
          id_to_look = list(set(id_to_look) & set(particles))
          nlist = id_to_look
          if (len(nlist)==0):
             print "No new neighbors found"
          else:
             groups[index]=groups[index]+nlist
             new_nlist=new_nlist+nlist
             print "------> neigh-neigh", new_nlist
             for k in nlist:
               particles.remove(k)

At the end one ends up with a list of the halos in the list groups
This part of the code is a bit off topic but I thought it would be nice to show it to you. I am basically deleting all the groups with no particles, sorting them according to the number of particles and showing some properties.
  def select(test,list):
  selected = []
  for item in list:
    if test(item) == True:
      selected.append(item)
  return selected

  groups=select(lambda x: sum(x)>0.,groups)
  # sorting groups
  groups.sort(lambda x,y: cmp(len(x),len(y)))
  groups.reverse()

  print time.time() - t0, "seconds"

  mass=x
  for i in arange(0,len(groups),1):
    total_mass=sum([mass[j] for j in groups[i]])
    x_cm = sum([mass[j]*x[j] for j in groups[i]])/total_mass
    y_cm = sum([mass[j]*y[j] for j in groups[i]])/total_mass
    z_cm = sum([mass[j]*z[j] for j in groups[i]])/total_mass
    dummy_x_cm = [x[j]-x_cm for j in groups[i]]
    dummy_y_cm = [y[j]-y_cm for j in groups[i]]
    dummy_z_cm = [z[j]-z_cm for j in groups[i]]
    dummy_x_cm = array(dummy_x_cm)
    dummy_y_cm = array(dummy_y_cm)
    dummy_z_cm = array(dummy_z_cm)
    dr = max(sqrt(dummy_x_cm**2.+dummy_y_cm**2.+dummy_z_cm**2.))
    dummy_x_cm = max(dummy_x_cm)
    dummy_y_cm = max(dummy_y_cm)
    dummy_z_cm = max(dummy_z_cm)
    print i, len(groups[i]), x_cm, y_cm, z_cm,dummy_x_cm,dummy_y_cm,dummy_z_cm

A:

I think that you would be ill-advised to start off learning Fortran in the hope that the resulting code will be faster than your current implementation.  It may, eventually, be, but I think you would be better advised to make your Python implementation as fast as you can before thinking of implementing in another language, especially a foreign language.
I write Fortran, and personally I think its performance pisses all over Python, but people who know about these things provide compelling arguments that Python+SciPy+Numpy can, if carefully crafted, match Fortran for speed in the computational kernels of many scientific/engineering programs.  Don't forget that you haven't optimised your Python until all the cores on your computer are running red hot.
So:
1st - get a working implementation in Python.
2nd - make your implementation as fast as possible.
IF (capital letters because it's a big 'if') the code is still not fast enough and the cost/benefit of translating it to a compiled language is favourable THEN consider which compiled language to translate it in to.  If you are in a field where Fortran is widely used, then learn Fortran by all means, but it is something of a niche language and it may benefit your career more to learn C++ or one of its relatives.
EDIT (too long to fit in the comment box)
Why mislead us in your question ?  You state that the only language you are comfortable with is Python, now you say that you know Fortran.  I guess you must be uncomfortable with it. And, from your comment, it seems that maybe the help you really need is in making your Python implementation faster; Sideshow Bob has offered some advice. Take that into consideration, then parallelise.


Q:

Linking Policies of copied Usecase in different space of IBM Blueworks Live?

I have created one Usecase and linked policies like BR and Error Msg to that Usecase. Then I copied that Usecase to another space.
My trouble is that the copied Usecase is linked to the policies of a different space.  How can I use policies in the same space and link to those?

A:

When you say "Usecase" I assume you are talking about a Process Blueprint.
If you copy a Process Blueprint, only the process is copied. None of the linked assets like Policies are going to be copied with it, so the copy will point to the same Policy as the original.
If instead you want to create copies of everything, you can copy the space instead of just copying the process.  Assuming all the linked assets (i.e. Policies) are in the same space as your process, this will create copies of everything and the copy of your process will be correctly linked to the copy of the policies.
If all the assets are not in the same space, one workaround is to temporarily move the items you are wanting to copy into a temp space, copy that temp space and then move everything back to the original location.


Q:

curl multi exec и нагрузка на сервер

В коде есть следующий фрагмент:
    do {
        curl_multi_exec($curlMultiHandle, $running);
    } while($running > 0);

На сколько я понимаю, это цикл, который выполняется пока не будут получены ответы от всех источников.
Собственно, вопрос - как сильно он будет грузить процессор в случае, если долго не будет ответа?
Если нагрузка таки будет большой, то можно ли использовать usleep? Помню, в Си, или Паскале, при использовании такой функции ОС могла на заданное время переключится на выполнение другого процесса, соответственно, МОЙ процесс не будет нагружать процессор. В PHP такое можно провернуть?

A:

Такой вызов будет утилизировать одно ядро процессора практически полностью. При том только одно лишь потому что PHP однопоточный.
Да, воткнуть usleep можно и это исправит положение с утилизацией CPU. Но лучше бы дёргать специальную функцию ожидания curl_multi_select. Вот только в комментариях к ней ссылаются как на уже заведённые баги в поведении так и просто на особенности реализации в libcurl. В общем, оптимально использовать и usleep и curl_multi_select.
    // отправляем запросы
    $active = null;
    do {
        $mrc = curl_multi_exec($multi, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);

    while ($active && $mrc == CURLM_OK) {
        // ждём какую-нибудь активность от потоков
        if (curl_multi_select($multi) == -1) {
            usleep(100);
        }

        // опрашиваем curl_multi_exec на предмет, есть ли ещё активные потоки
        do {
            $mrc = curl_multi_exec($multi, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }

Величину usleep здесь можно подбирать под конкретный проект. Документация к libcurl рекомендует начинать со 100 миллисекунд, затем можно протестировать в своём окружении со своими задачами и уменьшать-увеличивать значение.


Q:

Error ReportViewer 14.0.0.0 Window.$RSjQuery

Ao clicar no botão para expandir grupos no reportview, ele fica carregando eternamente e dá erro na linha abaixo:
// error Uncaught TypeError: window.$RSjQuery is not a function

if ($) {
     window.$RSjQuery(window).on("resize", function () {
         self.ResizeToolbarIcons();
     });
}

A:

Isso está ocorrendo porque o ReportViewer depende do $RSjQuery no momento de exibir a ToolBar.
Adicione a seguinte linha de código no evento Page_Load ou Pre_Render
    If Not Page.IsPostBack Then
        Me.Page.Controls.OfType(Of HtmlForm).First().Controls.Add(New ReportViewer With {.ID = "rdlcRSQuery", .Width = 0, .Height = 0)
    End If

Isso fará com que os Scripts que o ReportViewer depende estejam registrados na Página no momento de sua exibição.
Lembre de chamar
Imports Microsoft.Reporting.WebForms

E adicione o seguinte CSS
<style type="text/css">
    #rdlcRSQuery_ReportViewer { display:none;}
</style>


Q:

Defining a default class property in Python?

Not sure if this is possible in Python, but I'd like to have an instance of a class as a module-level global variable that, when called, returns a default property.
The idea comes from this question that overrides __call__ to have a class mimic a function.
Quick (untested) example of the idea:
class _foo(object):
    __slots__ = ("_foo",)
    _init = False

    def __init__(self):
        if not _init:
            self._foo = ["bar", "baz", "zog"]

    def __call__(self, item=None):
        if itme is not None:
            return self._foo[item]
        else:
            return self._foo

    def __getitem__(self, item):
        return self._foo[item]

# Module level
FOO = _foo()

Assume the above code is in a module (foo.py).  Using the interpreter, I cal get the callable form to work how I want, but not the non-callable form.
>>> import foo

# callable forms
>>> foo.FOO(0)
"bar"
>>> foo.FOO()
["bar", "baz", "zog"]

# attribute forms
>>> foo.FOO[2]
"zog"

# doesn't work
>>> foo.FOO
<foo._foo object at 0xdeadbeef>

# desired output
>>> foo.FOO
["bar", "baz", "zog"]

My thinking is that I need to define a default property somehow so that when calling the instance directly, I get the internal list/dict of my choosing.  I could cheat and do this via overriding repr, but that kinda breaks Python's own API and I want to avoid that.  Passing no value in square brackets (>>> foo.FOO[]) yields a syntax error instead.
I'd like any potential solutions to be compatible with Python 2.4 at minimum and 2.7 at maximum.  If this isn't possible, then I guess I'll just stick to using the callable format.

A:

This is impossible, sorry. You can't have foo.FOO be both a callable (a _foo instance) and an unadulterated list object.
Of course, I did say "unadulterated". If you're feeling sneaky...
class _foo(list):
    _init = False
    def __init__(self):
        if self._init:
            list.__init__(self)
        else:
            list.__init__(self, ['bar', 'baz', 'zog'])

    def __call__(self, item=None):
        if item is None:
            return self
        return self[item]

FOO = _foo()

Usage:
>>> FOO()
['bar', 'baz', 'zog']
>>> FOO(0)
'bar'
>>> FOO
['bar', 'baz', 'zog']


Q:

ARC packaged Android application: run JavaScript API command

I have an ARC packaged ChromeOS application and since there are some behavioral differences between ChromeOS and Android I want it to make some JavaScript API call: chrome.power.requestKeepAwake.
After the obvious step of adding "power" permission, what I've tried to do is to change contents of app_main.html:

<!DOCTYPE html>

But this lead to no changes.
I'm sure, that the request is not applied as I've tried to run the same query from Chrome console and it did the thing.
How should I manage to embed this code?

A:

Actually, I've managed to solve this issue.
The reason for it to happen is not that the code is applied in the wrong moment or something like this, but that the code you use in the app_main.html can't contain inline JavaScript, which is insecure.
That said, the code should look like:
/app_main.html:

<!DOCTYPE html>

/power_request.js:

chrome.power.requestKeepAwake("display");


Q:

Bindings throwing exception

Busy with a school project, and NetBeans is frustrating me to death. Please help me resolve the below error and please show me what I have done wrong.
I'm busy with bindings and Apache Derby. What I'm doing is I'm binding data from the database to text fields. I have a JFrame Form with two tabbed panels. One has a table on it 1, and another one shows individual records 2.

This is an extract of the coding for the binding on the single record view:
1    package UserManager;

    import java.util.*;

5    /**
     *
     * @author Johan Brink
     */
    public class Data extends javax.swing.JFrame {
10       Users users = new Users();
         ListIterator<Users>iterator;

         public Users getUsers() {
              return users;
15       }

         public void setUsers(Users users) {
              Users oldUsers = this.users;
              this.users = users;
20            firePropertyChange("users", oldUsers, users);
         }

         /**
          * Creates new form Data
25        */
         public Data() {
              initComponents();
              setLocationRelativeTo(rootPane);
              iterator = usersList.listIterator(0);
30            setUsers(iterator.next());
         }

The problem lies on lines 29 and 30. This have worked in the past, but now I get an error. I have an automatically-created entity class, etc. Without lines 29 and 30, everything works except the individual records information isn't listed. When lines 29 and 30 is inserted, the following error is displayed when run:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: Cannot cast java.util.Date to java.lang.String
    at java.lang.Class.cast(Class.java:3084)
    at org.jdesktop.beansbinding.Binding.convertForward(Binding.java:1312)
    at org.jdesktop.beansbinding.Binding.getSourceValueForTarget(Binding.java:844)
    at org.jdesktop.beansbinding.Binding.refreshUnmanaged(Binding.java:1222)
    at org.jdesktop.beansbinding.Binding.refresh(Binding.java:1207)
    at org.jdesktop.beansbinding.AutoBinding.tryRefreshThenSave(AutoBinding.java:162)
    at org.jdesktop.beansbinding.AutoBinding.sourceChangedImpl(AutoBinding.java:227)
    at org.jdesktop.beansbinding.Binding.sourceChanged(Binding.java:1411)
    at org.jdesktop.beansbinding.Binding.access$1200(Binding.java:38)
    at org.jdesktop.beansbinding.Binding$PSL.propertyStateChanged(Binding.java:1618)
    at org.jdesktop.beansbinding.PropertyHelper.firePropertyStateChange(PropertyHelper.java:212)
    at org.jdesktop.beansbinding.ELProperty.notifyListeners(ELProperty.java:688)
    at org.jdesktop.beansbinding.ELProperty.access$800(ELProperty.java:155)
    at org.jdesktop.beansbinding.ELProperty$SourceEntry.processSourceChanged(ELProperty.java:312)
    at org.jdesktop.beansbinding.ELProperty$SourceEntry.sourceChanged(ELProperty.java:326)
    at org.jdesktop.beansbinding.ELProperty$SourceEntry.propertyChange(ELProperty.java:333)
    at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:335)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:327)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:263)
    at java.awt.Component.firePropertyChange(Component.java:8382)
    at UserManager.Data.setUsers(Data.java:24)
    at UserManager.Data.<init>(Data.java:34)
    at UserManager.Data$7.run(Data.java:419)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

A:

You have not included the code that is the root problem, but the exception says that the binding code is attempting to cast a String to a Date ... and that's a big no-no in Java!
I suspect the problem is that you have a date-of-birth field in the User object that has type Date and the binding object is attempting to reflectively assign a String to it.
If this is the problem, then you need to add a custom Converter to the relevant Binding object to convert between String and Date objects.  It looks like you will need to write a custom converter to do the job.
References:

Adding a Converter - https://netbeans.org/kb/docs/java/gui-binding.html?print=yes
An example of a custom Converter - https://weblogs.java.net/blog/pkeegan/archive/2007/11/beans_binding_c.html


Q:

Unity3d: Adding gameobject to List from an array

Thanks for help in advance. Here is a short snippet of the code that I am having an issue with.
GameObject[] allMotor_array;
public List<GameObject> BrokenMotor_list = new List<GameObject>();
void Start()
{
   allMotor_array = GameObject.FindGameObjectsWithTag ("Motors");
}

void Update()
{
    foreach (GameObject motor in allMotor_array)
    {
        if(motor.GetComponent<Pump_event>().damaged)
        {
            BrokenMotor_list.Add(motor);
        }
    }

}

I have an array of Gameobjects that is created on Start, each of the gameobjects in the array have a script called Pump_event. What I want to do is add the gameobject with a true boolean (damaged) to the list so that I can create a GUI list of all the motors that are damaged (and then take further action on those motors).
With the current code it instantiates the array fine, but when One of the motors boolean changes to true the list tends to continuously add the motor gameobject to the list on each update cycle. So what I want is to figure out a way of adding the gameobject to the list ONCE.
Having it in the update() is probably not the best method but I really am stuck on how to approach this.
G

The Solution to my problem

Thanks for your answers, you all had well thought out responses. I appreciate it. I didn't go with 1 persons method but instead adapted logical approaches found here to work with my script/s.
Here is what I did.
In my pump_event script the events are sorted in a Case and switch as damage increased on the pump the event would escalate. So I added in a section to that script to include "reporting" the damage.
public class Pump_event : MonoBehaviour
//The damage has taken place and event_category=0\\
switch (event_category)
    {
    case 0:
        Master_script.GetComponent<Control_room>().AddtoList (gameObject);
        event_category = 1;
        break;

I took advice not to insert these types of programing and placed it into its separate class which works out well.
public class Master_script: MonoBehaviour
public void AddtoList(GameObject motor_tobadded)
{
    BrokenMotor_list.Add(motor_tobadded);
}

This also eliminated the need on having an array holding all of the pump event controllers as well.
Now the script all works fine. It may not be most efficient but it is doing its job.
Thank you again to all that helped.

A:

In your Pump_event Script you can have a event Action which you register in this snippet and whenever damaged is set true you need to fire the event.
Example:
// in Pump_event Class
public static event Action<GameObject> OnDamagedValueChanged;
private bool _damaged;
public bool Damaged
{
    get { return _damaged;}
    set
    {
        _damaged = value;
        if(_damaged)
        {
              if(OnDamagedValueChanged != null)
                  OnDamagedValueChanged(gameObject);
        }
    }
}

In your Current Class where you have array of GameObjects:
void OnEnable()
{
    Pump_event.OnDamagedValueChanged += HandleOnDamagedValueChanged;
}
void OnDisable()
{
    Pump_event.OnDamagedValueChanged -= HandleOnDamagedValueChanged;
}
void HandleOnDamagedValueChanged(GameObject obj)
{
    if (!BrokenMotor_list.Contains (obj))
    {
        BrokenMotor_list.Add (obj);
    }
}

Using Actions is a better approach than doing it in Update Method. It is not good for performance to keep checking for a bool in iteration in update method. and try to avoid GetComponent and Find/FindObjectWithTag Methods in Update. It is not good practice. I hope this is helpful.


Q:

Most popular open-source, free, well-documented game engine for research application

My company is getting ready to propose a stroke and brain-injury rehabilitation tool and we need to know what free, open-source, and well-documented game engine are out there.

We will be constructing a 3D environment.
We will need to have good control over characters fine motions (for instance even finger motions).
We need a good physics engine including collision detection and inverse kinematics if possible.
It would be very useful if there are already some hooks in the code for providing haptic feedback, but that's not necessary.
Graphics do not need to be phenomenal.
It must be relatively easy to throw together a proof of concept.

I'm predisposed toward Jake2 because Java's dead easy to program in, but I need more options to consider from you folks who have experience.

A:

I would consider looking at ioquake3 which is an opensource port of Quake 3. Also, I would like to point out the excellent Delta3d which is a DoD funded and developed opensource simulation engine.
Notre Dame evaluates several engines in the paper A Survey of  Collaborative Virtual Environment Technologies. I would think that this would be best starting point as you will be able to access alot of existing knowledge on engines when applied to virtual environments.


Q:

How can I change the name of my C++ application in Visual Studio 2013 (The name that appears at the top of the window)?

I have tried changing the name of the active project, the solution, and the root directory of the project, but none of these affect the name that appears on the application window when I launch it. I have looked through the solution and project properties and haven't found a field that I can change.
I have found answers to this question that apply to VS 2010 and 2008 but they do not apply to 2013.
EDIT: I am referring to the GUI window created by the application with DirectX.

A:

I figured it out. The name was being read in from a .rc file!


Q:

Detecting if the microphone is on

Is there a way to programmatically detect whether the microphone is on on Windows?

A:

No, microphones don't tell you whether they're ‘on’ or that a particular sound channel is connected to a microphone device. The best you can do is to read audio data from the input channel you suspect to be a microphone (eg. the Windows default input device/channel), and see if there's any signal on it.
To do that you'd have to remove any DC offset and look for any signal above a reasonable noise floor. (Be generous: many cheap audio input devices are quite noisy even when there is no signal coming in. A mid-band filter/FFT would also be useful to detect only signals in the mid-range of a voice and not low-frequency hum and transient clicks.)


Q:

Ideals in an infinite direct product of fields

Let $R$ and $S$ be fields. Consider the ring $R \times S$.
Since $R$ (resp. $S$) is a field, the ideals of $R$ (resp. $S$) are $\{0_R\}$ and $R$ (resp. $\{0_S\}$ and $S$).
Since every ideal of the direct product of rings is the direct product of ideals of these rings, we get the following result using induction:
For fields $R_1,...,R_k$ and $S \subset \{1,...,k\}$, let $I(S) = \{(r_1,...,r_k) \in R_1 \times ... \times R_k : a_s = 0$ for all $s \in S \}$.
Then an ideal $I$ of $R_1 \times ... R_k$ equals to $I(S)$ for some $S \subset \{1,...,k\}$.
Now what happens if we consider an infinite sequence of fields ?
I believe that the set $\{ (r_1, r_2,...,r_n,0,0,...) \in \Pi_{i=0}^{\infty} R_i : \exists n \in \mathbb{N}$ and $r_m = 0$ for all $m > n \}$ is an ideal of $\Pi_{i=0}^{\infty} R_i$ and is not of the form $I(S)$ for some $S \subset \mathbb{N}$.
Are there other examples of ideals of $\Pi_{i=0}^{\infty} R_i$ that are not of the form $S(I)$ for some $S \subset \mathbb{N}$?
Thank you very much for your help!

A:

Your example is correct.  More generally, ideals in an arbitrary product $R=\prod_{i\in J} R_i$ of fields correspond to what are called (Boolean) ideals (of sets) on the index set $J$.  An ideal on a set $J$ is a collection $D$ of subsets of $J$ with the following properties:

$\emptyset\in D$.
If $A,B\in D$ then $A\cup B\in D$.
If $A\in D$ and $B\subseteq A$, then $B\in D$.

Intuitively, the idea is that the elements of $D$ are sets that are "small" in some sense.
Given an ideal $D$ on the set $J$, you can define an ideal $I(D)$ in the ring $R$ which consists of all elements whose set of nonzero coordinates is an element of $D$.  For example, if $D$ is the collection of all finite subsets of $J=\mathbb{N}$, then the ideal $I(D)$ is exactly your example.  But there are many other ideals of sets: you can take some random infinite collection of subsets of $J$ and consider the ideal they generate (i.e., their closure under the three conditions above).  Or, more systematically, many reasonable notions of "smallness" give ideals of sets.  You can find several examples on Wikipedia.
Conversely, using the fact that the $R_i$ are fields, you can show that every ideal in $R$ is of the form $I(D)$ for some ideal $D$ on $J$.  Namely, you can take $D$ to be the set of subsets $A\subseteq J$ such that some element of your ideal is nonzero on every coordinate in $A$.
When $J$ is finite, given any ideal $D$ on $J$ you can just take the union of all the elements of $D$ to get a set $S\in D$ which contains all the elements of $D$.  (We have $S\in D$ since $D$ is closed under finite unions.)  So, in this case $I(D)$ is just what you called $I(S)$.  The difference when $J$ is infinite is that an ideal $D$ on $J$ may not be closed under arbitrary unions, so there may be no single element of $D$ that contains all other elements of $D$.


Q:

How do I list two different things in the WHERE clause in SQL?

The question asks,
"List   product names   and the product vendor  for all products    where   the scale   of  the
products    is  1:700.  (Products   table)  and the product line    is  ‘Ships’."
So far I have listed,
SELECT productName, productVendor
FROM Products
WHERE productScales = '1:700', productLine = 'Ships';

There is an error in the WHERE clause according to SQL. Is this not the way to put two different items in SQL?
I appreciate any help, Thank you!

A:

you need to use AND not ,
SELECT productName, productVendor
FROM Products
WHERE productScales = '1:700' AND productLine = 'Ships';


Q:

how to show all records from a specific mySQL row - except duplicates?

Is there any easy way to show all records from a specific mySQL row - except the duplicated ones?

A:

select distinct myrow from mytable;


Q:

Uniform convergence of a family of functions on $(0,1)$

Let the family of functions be

$$f_n(x) = \dfrac{x}{1+nx}.$$

Is the sequence $f_n$ uniformly convergent in the interval $(0,1)$?

A:

$\frac{x}{1 + nx} = \frac{1}{\frac{1}{x} + n} \leq \frac{1}{n}$ which doesn't depend on $x$ hence your sequence converges uniformly to $0$


Q:

Should I generate android GCM registration ID app specific or user specific?

I am developing an app which has login functionality.I am generating only one gcm registration ID per app. If other user sign's in in same app he will start receiving notifications intended for the previous user.
How to handle this situation, so that each user will get notification intended for his/her?
Should I generate gcm reg id for each user?
What is the standard way to handle this situation?

A:

You could try the following things:

When the user logs off, send a request to delete the token on your server, and erase it on your app;
Once the user logs off, you could simply remove the association of "User ID" to "GCM Token" (Or Registration ID) on your server. And when someone logs in again, you make a new association to that Token.

The GCM Token is app specific, but the association you make on your server is totally up to you.
And I can't stress it enough, the token generated by GCM is APP SPECIFIC. If your user logs in on multiple devices, your server should handle that, associating the user ID to multiple Registration ID Tokens.

An ID issued by the GCM servers to the Android application that allows
  it to receive messages. Once the Android application has the
  registration ID, it sends it to the 3rd-party application server,
  which uses it to identify each device that has registered to receive
  messages for a given Android application. In other words, a
  registration ID is tied to a particular Android application running on
  a particular device.

And from the docs, your server should also:

Before you can write client apps that use GCM, you must have an
  application server that meets the following criteria:

Able to communicate with your client.
Able to send properly formatted requests to the GCM connection    server.
Able to handle requests and resend them using exponential back-off.
Able to store the API key and client registration tokens.
Able to generate message IDs to uniquely identify each message it    sends. Message IDs should be unique per sender ID.

EDIT: You can read more about GCM here.
For further reading, you could also read more on Device Group Messaging.
You can also download some code samples here.

A:

You should store regID as per user.
This is because there is test cases that user1 logs out and user2 logs in. In that case if you have stored regID app specific and not binding with user then user2 will also get notification.
So you need to store regID as per user , app and as well as device specific.


Q:

Create new mercurial repository cloning SINCE revision

I have a HUGE mercurial repository.
Cloning and some operations are starting to be slow.
I would like to get rid of old commits, but keep the history of revisions since a specific date.
Is there any way to keep the commits SINCE a specific commit on a single branch, and collapse all the older parent commits in a single one?
R1 -> R2 ->R3 ->R4 ->R5 -> R6 -> R7 ->R8 ->Tip
[R1-5] ->R6 ->R7 ->R8 ->Tip
I tried to do such thing using GRAFT, but it did not work (maybe I don't now how to do it properly).
Optional: Is there such an option on Sourcetree?

A:

You cannot clone it to achieve this. But you have basically two options:

history rewrite using histedit (it's an default extension, but needs enabling)
It gives you the option to fold commits, that is combine several one to a single.
convert (which in essence is also a history rewrite)
This gives you the chance to create a new repository with only the selected commits and branches. Thus you can simply leave out the first 4 commits and start with the 5th.

For each also checkout the help shipped with mercurial (hg help histedit, hg help convert).


Q:

Do laws of thermodynamics have a place in Theory of Everything?

I am having a difficulty understanding why second law of thermodynamics is still a valid universally accepted concept. I understand it works on paper for describing isolated heat systems. However, I do not understand how can it hold place as a valid concept on our path towards a theory of everything. I would like to generate a discussion around some ideas I have that brought me to this conclusion. Maybe there is someone out there who's also thinking about this. Maybe you've got time to point out errors in my logic or suggest reading.
Physicists assume matter and energy is conserved and also tell us "entropy increases!".
According to information theory, entropy is related to information.
The relationship is "when entropy increases information decreases". (Very short summary)
Now if entropy increases then at some point in the past there was less entropy. So if you go all the way back to Big Bang entropy was at minimum and the amount of information was at maximum. Well, there seems to be something contradictory here! In the present day picture, information is more abundant than ever, we have galaxies, particles, planets, life and all the other stuff, and at Big Bang or slightly after we just had some radiation.
From this, I can't understand why people state that entropy is increasing. Any useful insight?

A:

 That the early universe was in a very low entropy state is, in fact, one of the most confusing open questions in physics.  As of now, it is really nothing but an initial condition put into the equations, but it seems strange, a priori, that time should start in such a state.  As of now, there are no definitive answers for why the early universe was low-entropy, aside from heuristics arguing that we know the direction of time only from the change in entropy, so if you have some sort of fluctuation model of entropy, time seems to be going 'forward' on either side of an entropy minimum, even if these directions of time are opposite in some absolute sense.  That the low entropy state coincides with the big bang would be an interesting result if it was predicted by some new theory of physics that solved the GR/QFT problem.
 Saying that entropy is 'information' can be useful in some senses, and can be confusing in other senses.  When you are talking about primordial gas existing before humans did, it is probably best to think of entropy as measuring 'order' more than it is measuring 'information'--the early universe appeared to be in a VERY ordered state, where the gas had nearly constant density temperature and pressure--if you are DESPERATE to think of this in terms of information,w hat this means is that, in this state, knowing the properties in the gas at any point is almost completely possible from knowing the properties of the gas at any other point, no matter how far away--one bit of information gives you access to all of the rest of the information.


Q:

Reduce verbosity of method call with array of a lengthy generic type

Is there anyway to shorten the call to this method?  It seems to long, is the second parameter needed the strongly typed and does the  needed on the FindPercent if the List is known?
Model.FindPercent<IStatisticDisplay>(t => t.FaceoffsWon,
    new Func<IStatisticDisplay, double?>[] { q => q.FaceoffsWon, q => q.FaceoffsLost }, "-")

Method
public static string FindPercent<T>(this List<T> list, Func<T, double?> numerator,
    Func<T, double?>[] totals, string defValue)
{
    return Helper.FindPercent(list, numerator, totals, defValue);
}

A:

Just use params and drop the types !
public static string FindPercent<T>(this List<T> list, string defValue, Func<T, double?> numerator, params Func<T, double?>[] totals)
{
   return Helper.FindPercent(list, numerator, totals, defValue);
}

Model.FindPercent("-", t => t.FaceoffsWon, q => q.FaceoffsWon, q => q.FaceoffsLost );


Q:

Auto size height for rows in Apache POI

I am inputting values into a spreadsheet using Apache POI. These values have newlines, and I was able to use this code successfully:
CellStyle style = cell.getCellStyle()
style.setWrapText(true)
cell.setCellStyle(style)

Unfortunately, while the text is wrapping correctly, the rows are not always growing in height enough to show the content. How do I ensure that my rows are always the correct height?

A:

HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet =  workbook.createSheet("FirstSheet");
HSSFRow rowhead=   sheet.createRow((short)0);
HSSFCellStyle style = workbook.createCellStyle();
style.setWrapText(true);
row.setRowStyle(style);
row.getCell(0).setCellStyle(style);

The above code will generate dynamic height of rows.

A:

currentRow.setHeight((short)-1)

Works for XSSFCell and Excel 2013

A:

The only way I got this to work was write my own implementation to calculate the row height. The code is now released as the Taro project, so you could use that. It has numerous convenience methods to let you write an Excel file in far fewer lines of code.
If you prefer to put the implementation in your own code, you can find it in the SpreadsheetTab class. There is an autoSizeRow(int rowIndex) method half way down. It basically iterates down the row and for each cell finds the number of lines of text, then uses the font size to calculate the optimal cell height. It then sets the row height to the height of the tallest cell.


Q:

Can Mjolnir be lifted & wielded by anyone if Thor is touching it?

In The Big Bang Theory episode The Bakersfield Expedition, Penny, Amy, and Bernadette are having an argument if Thor's hammer:

Can be lifted by anyone in space.
Can be lifted & wielded by anyone if Thor is touching it.

The first argument is settled in Can Thor's hammer be wielded by anyone in outer space?.
But the second argument remains unsolved.  Can Thor's hammer be lifted & wielded by anyone if Thor is touching it?

A:

Yes, in Marvel comics and cartoons Thor's hammer can be lifted and wielded by others if Thor is touching it. The trick is that they have to be strong enough to overpower Thor.  The Hulk has done this in a recent issue of Avengers Assemble (#4):

The same thing happened earlier in the Hulk: Let the Battle Begin one-shot.

Finally, there are many, many instances of the Hulk either lifting or tossing Thor while Thor was wielding Mjolnir.  Here are just a few of those.

A:

The second point is up to interpretation, based on how you define "lift up".
This also depends on which interpretation of Thor you are considering: The original folklore has Thor's hammer stolen at least once, something I'd consider impossible, if only the worthy can lift it.
As for Marvel's Thor I'd say anyone (strong enough) could lift both at once. Otherwise no bad guy would be able to throw or kick Thor around as long as he's in possession of his hammer. I've only seen the old animated series years ago, but I think I remember him being kicked around at least once.


Q:

Laravel dosen't see path to file with Custom Request Class, how to fix it?

I created Custom ReadRequest Class. Than I created folder with "Order" name in Requests folder, and put there my ReadRequest.php file:

After this manipulation Laravel doesn't see this file in my Controller:

How can I fix that?

A:

You haven't written how you know that Laravel doesn't see this file but looking at your screen it seems your IDE doesn't see it it either. So make sure in your ReadRequest.php file you have
<?php

namespace App\Http\Requests\Order;

class ReadRequest
{
  // ...
}

It's very possible that you have invalid classname in this file or invalid namespace, so your IDE shows you the error and also composer cannot load the file.


Q:

How to render static file not in public or view folder after middlware in express js

I have a folder

api-docs inside that I have index.html some css and js file

I need to render api-doc for authenticated user.
I am not using it in views as In project I am using jade in view and api-doc is in html
I have tried
router.get('/v1/secure-api-documentation',(req,res)=>{
     console.log('A')
     res.sendFile(__dirname + '/../api-doc/index.html');
 });

and
router.get('/v1/secure-api-documentation',ensureAuthenticate,(req,res)=>{
     express.static(path.join(__dirname,'../api-doc'))
 });

A:

express.static(path, [options]) returns a function. So basically what your code is doing is :
router.get('/v1/secure-api-documentation',ensureAuthenticate,(req,res)=>{
    express_static_function // this function further accepts arguments req, res, next
    //there is no function call happening here, so this is basically useless
 });

However, this is not what express.static is used for
What express.static does is, takes the request path and looks for a file with the same name in the folder you specified.
Basically, if a GET request comes to '/v1/secure-api-documentation', it will take the request path after '/v1/secure-api-documentation' and look for that inside api_docs folder.
Passing express.static to router.get() will call it for the very SPECIFIC path. This is important.
GET '/v1/secure-api-documentation/index.html' will fail. Because such a route is not handled.
What you need to do this is call express static for any path like '/v1/secure-api-documentation/*'.
For this you need to take the express app object, and write the following code:
//make sure to use the change the second argument of path.join based on the file where your express app object is in.
app.use('/v1/secure-api-documentation',express.static(path.join(__dirname,'../api-doc')));

This will now work for not only the index.html file but any js/css file inside api_docs that is requested.


Q:

How to nicely throw an error to an Angular RXJS Observable subscriber

For the function below, how can I throw an error from the 'BROKEN' like that can be handled nicely by its subscriber in the same way as the 'WORKS' line of code?
What I'm seeing is that the 'Works' line passes the error neatly this function's subscriber, whereas the BROKEN line just blows up without getting handled by its subscriber. I'm using Angular (version 5.0.3) in an Ionic project, RXJS version 5.5.2, and the HttpClient in @angular/common/http.
public makeRequest(requestParameters) {

  return Observable.create(observer => {

    let url = 'http://example.com/service/action?a=b';

    this.http.get(url,{withCredentials: true})
      .subscribe(data => {
        if(data["success"] !== true)
          observer.error("Unexpected result");//BROKEN
        else
          observer.next(data["payload"]);
      },
      err => {
        console.log('error: ' + err);
        observer.error(err);//WORKS
      });
    });
}

Here's an example of a function that calls the one above:
public getStuffFromServer(){
  this.makeRequest({parameters go here}).subscribe(
      data => {
        //do something with the results
      },
      err => {
        //This never gets called from the 'BROKEN' code (but it does from the WORKS code
      }
    );
}

Thanks for your help!

A:

OK, it looks like I found the answer on this page: https://codingblast.com/rxjs-error-handling/
The key is to use the map and catch functions like so:
public makeRequest(requestParameters) {

return Observable.create(observer => {
let url = 'http://example.com/service/action?a=b';
this.http.get(url,{withCredentials: true})
  .map(data => {
    if(data["success"] !== true)
      throw new Error("Something meaningful");
    return data["payload"];
   })
  .catch(err => {
    return Rx.Observable.throw(err);
   });
  .subscribe(data => {
      observer.next(data);
  },
  err => {
    console.log('error: ' + err);
    observer.error(err);
  });
});
}

Hopefully this will help somebody. Thank you everyone who answered or gave it some thought!


Q:

Chrome not returning hash value

I'm using the following snippet if jQuery JavaScript to return a hash value at the end of a URL. It works perfectly in FF but the alert on line 4 returns empty in Chrome.
Seems like the window.location.hash.substring(1) line does not work. I have also tried window.location.hash.replace("#", "");
// Map Clicks
$("#tab2.tab_content #map").delayed('click', 500, function() {
    state = window.location.hash.substring(1);
    alert(state);
    jsonLink = 'http://ml.uscm.org/ministries.json?state=' + state + '&active=true&callback=?';
    getMapResults();
    return false;
});

What's the trick to retrieving a hash value from the URL in Chrome?
The URL is built like this :
http://www.ourdomain.com/thispage.html#IL

Where IL is a two letter abbreviation for a state. I want to get the "IL".
I have a working demo here:
http://richcoy.com/locator/index2.html
Click on the Search by State tab in Chrome then click on a state and you'll see the issue. The browser shows that the url that it wants to go to is built correctly. –
Thanks.

A:

You may want to try this instead:
$(window).on('hashchange', function() {
    console.log(window.location.hash.substring(1));
});

The click event triggers before the hashchange event so you can't rely on your map click implement (even if you delayed it).
Supported browsers list for hashchange: http://caniuse.com/hashchange
In case you don't have to use hash, here is a simpler solution:
$("#tab2.tab_content #map a").click(function() {
    console.log($(this).attr('href').substring(1));
});

In summary, you shouldn't use any kind of delayed methods.

A:

Isn't the problem quite apparent, or am I being silly? In the following function, you handle the clicks on the map, you listen to click, delay them by 500ms and then run through your function.
$("#tab2.tab_content #map").delayed('click', 500, function() {
  state = window.location.hash.substring(1);
  alert(state);
  jsonLink = 'http://ml.uscm.org/ministries.json?state=' + state + '&active=true&callback=?';
  getMapResults();
  return false;
});

But at the point where you alert your state, it's empty because you haven't yet set it. Your return false; will also stop the browser from changing the hash.
Try this function, and I bet you'll get something:
$("#tab2.tab_content #map").delayed('click', 500, function() {
  setTimeout(function(){
    var state = window.location.hash.substring(1);
    alert(state);
    jsonLink = 'http://ml.uscm.org/ministries.json?state=' + state + '&active=true&callback=?';
    getMapResults();
  }, 500);
});

A quick way to get it working would be to do the following:
$("#tab2.tab_content #map a").delayed('click', 500, function(e) {
  state = $(this).attr('href').replace('#', '');
  alert(state);
});

you could then easily change the hash manually by also adding this into the callback:
window.location.hash = state;

but your real issue is that your a (anchors) aren't changing the hash themselves, which makes it seem like there is somewhere in your code that's stopping it.

A:

I appreciate all the help and suggestions.
The answer to the question ended up that I needed to make the paths for the URLs absolute, not relative.
So as an example, a line in the JavaScript went from:
"AL": {tooltip: 'Alabama', attr: {fill: '#F9B625', href: '#AL'}},

To:
"AL": {tooltip: 'Alabama', attr: {fill: '#F9B625', href: 'http://richcoy.com/locator/index2.html#AL'}},

Once I changed this for all 50 states a click on the map pulled the data from the jasonp feed correctly and displayed it on the page in Chrome, as well as in Firefox.


Q:

Action Mailer - Heroku Push

I am new to action_mailer and I have no clue what could be going wrong. I've spent the last 12 hours going in circles with this. It might be a gem dependency, it might be something I did wrong. Please help!
Mailing works in my local environment, but I can't push to heroku. I keep getting this error:
-----> Preparing app for Rails asset pipeline
   Running: rake assets:precompile
   rake aborted!
   NoMethodError: undefined method `action_mailer' for #<Rails::Application:
:Configuration:0x00000002fad208>

EDIT NEW ERROR AFTER ADDING RAILS VERSION TO GEM FILE
Running: rake assets:precompile
       I, [2014-04-01T14:00:22.863048 #796]  INFO -- : Writing /tmp/build_a1da56
       f1-c7f3-455c-9bea-c9bf4306ef11/public/assets/blank_tan_vig-03e2648e62e03d21bb6cb
       8e57937edf8.jpg
       I, [2014-04-01T14:00:22.865246 #796]  INFO -- : Writing /tmp/build_a1da56
       f1-c7f3-455c-9bea-c9bf4306ef11/public/assets/rails-5c3c576fb6f357c0c4d2a32214da4
       4b6.png
       I, [2014-04-01T14:00:27.585107 #796]  INFO -- : Writing /tmp/build_a1da56
       f1-c7f3-455c-9bea-c9bf4306ef11/public/assets/application-bc6a900b1f1dc90eba371ab
       1e65adb36.js
       rake aborted!
       NoMethodError: undefined method `environment' for nil:NilClass

I am trying to use Mandrill for my SMTP server. I have the heroku addon installed and configured properly (as far as I could tell). I followed this: https://devcenter.heroku.com/articles/mandrill
user_mailer:
class UserMailer < ActionMailer::Base
  default from: "info@myflix.com"

  def send_welcome_email(user)
      @user = user
  mail(to: @user.email, subject: "Welcome to Myflix!")
  end
end

Production Env
Myflix::Application.configure do

 config.action_mailer.delivery_method = :smtp
 config.action_mailer.smtp_settings = {
   :address              => 'smtp.mandrillapp.com',
   :port                 => 587,
   :user_name            => ENV['MANDRILL_USERNAME'],
   :password             => ENV['MANDRILL_APIKEY'], # SMTP password is any valid API key
   :domain               => 'heroku.com', # your domain to identify your server when  connecting
   :authentication       => 'plain' # Mandrill supports 'plain' or 'login'
 }

 config.cache_classes = true
 config.eager_load = true
 config.consider_all_requests_local       = false
 config.action_controller.perform_caching = true

 config.serve_static_assets = false

 config.assets.compress = true
 config.assets.js_compressor = :uglifier

 config.assets.compile = false

 config.assets.digest = true

 config.i18n.fallbacks = true

 config.active_support.deprecation = :notify
end

Gemfile:
source 'https://rubygems.org'
    ruby '1.9.3'
gem 'bootstrap-sass'
gem 'coffee-rails'
gem 'rails', '4.0.0'
gem 'haml-rails'
gem 'sass-rails'
gem 'uglifier'
gem 'jquery-rails'
gem 'bootstrap_form'
gem 'bcrypt-ruby', '~> 3.0.0'
gem 'fabrication'
gem 'faker'

group :development do
  gem 'sqlite3'
  gem 'pry'
  gem 'pry-nav'
  gem 'thin'
  gem 'better_errors'
  gem 'binding_of_caller'
  gem 'letter_opener'
end

group :development, :test do
    gem 'rspec-rails'
end

group :test do
    gem 'shoulda-matchers'
  gem 'capybara'
  gem 'launchy'
end

group :production do
  gem 'pg'
  gem 'rails_12factor'
end

A:

Specify what version of Rails do you use in your Gemfile
For example, if you use Rails 3.2.13:
gem 'rails', '3.2.13'
or if you use Rails 4
gem 'rails', '4.0.0'
`
Run bundle install
Hope that works.


Q:

PHP MySQL Grouping Issue

If I have a table with the following data in MySQL:
Company           CompanyEntity        OrderNumber      Delivery Date
Deeway HS              20779             4608580         2020-11-11
Deeway Pearl HS        20780             4608580         2020-11-11
Deeway Stony HS        1273              4608558         2020-11-11
Zaper LTD              9995              4630230         2020-11-11
Zaper CP LTD           4295              4607371         2020-11-11
Wilder                 4224              6630210         2020-11-11
Wilder                 4224              7601371         2020-11-11

I need it to look like this:
Company                                        CompanyEntity        OrderNumber      Delivery Date
Deeway HS,Deeway Pearl HS,Deeway Stony HS     20779,20780,1273     4608580,4608558    2020-11-11
Zaper LTD,Zaper CP LTD                           9995,4295         4630230,4607371    2020-11-11
Wilder                                             4224            6630210,7601371    2020-11-11

I've tried:
SELECT
nextgenorder_companyname,
nextgenorder_company_entity,
nextgenorder_ordernumber,
nextgenorder_deliverydate
    FROM nextgenorders2
WHERE nextgenorder_deliverydate='2020-11-11'
GROUP BY nextgenorder_companyname,nextgenorder_company_entity
ORDER BY nextgenorder_companyname

Which does not give me the results I want. Any help would be greatly appreciated.
SQL Fiddle
Thank you

A:

You need to use GROUP_CONCAT to aggregate your values, and based on your sample data you want to group by the first word in the name, so you can use SUBSTRING_INDEX to extract that. To deal with possible / in the name as a separator instead of space, you can REPLACE them:
SELECT
    GROUP_CONCAT(DISTINCT nextgenorder_companyname) AS Company,
    GROUP_CONCAT(DISTINCT nextgenorder_company_entity) AS CompanyEntity,
    GROUP_CONCAT(DISTINCT nextgenorder_ordernumber) AS OrderNumber,
    GROUP_CONCAT(DISTINCT nextgenorder_deliverydate) AS `Delivery Date`
FROM nextgenorders2
WHERE nextgenorder_deliverydate='2020-11-11'
GROUP BY SUBSTRING_INDEX(REPLACE(nextgenorder_companyname, '/', ' '), ' ',1)
ORDER BY SUBSTRING_INDEX(REPLACE(nextgenorder_companyname, '/', ' '), ' ',1)

Output:
Company                                     CompanyEntity       OrderNumber         Delivery Date
Deeway HS,Deeway Pearl HS,Deeway Stony HS   20779,20780,1273    4608580,4608558     2020-11-11
Wilder                                      4224                6630210,7601371     2020-11-11
Zaper/LTD,Zaper CP LTD                      9995,4295           4630230,4607371     2020-11-11

Demo on SQLFiddle


Q:

Android Connection/SocketTimeOutException caught yet app still crash

Basically I'm trying to let user know when the app cannot reach the server/server down, while their phone internet/data connection is perfectly fine. So I set a timeout by following this post here: How to set HttpResponse timeout for Android in Java
It works great, except when the exception is caught correctly the app still crash instead of displaying the Toast message and return to the app screen. Notice that "Log.e("CONN TIMEOUT", e.toString());" logged correctly in logcat as: "CONN TIMEOUT org.apache.http.conn.ConnectTimeoutException: Connect to /192.168.11.60:80 timed out"
As requested, full logcat: http://pastebin.com/rpe8iKRi
    // Making HTTP request
    try {

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (ConnectTimeoutException e) {
        Toast.makeText(getApplicationContext(), "Server timeout", Toast.LENGTH_LONG).show();
        Log.e("CONN TIMEOUT", e.toString());
    } catch (SocketTimeoutException e) {
        Toast.makeText(getApplicationContext(), "Server timeout", Toast.LENGTH_LONG).show();
        Log.e("SOCK TIMEOUT", e.toString());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        Log.e("OTHER EXCEPTIONS", e.toString());
    }

A:

got it resolved. missing throws Exception { at the end of the function. duhhh
thanks @Alin for good hint.


Q:

How to cast std::make_unique so that I can use the functions declared in the class?

Or do I need to cast std::make_unique into any forms at all?
I have a FOO class with some functions that I can use:
 FOO::FOO(const yoo &yoo, float numbers) :
     num_to_execute(numbers)
 {
 ...
 ...
 }

 void FOO::execute()
 {
    execute(num_to_execute);
 }

In another .cpp, my given codes initated foo using the following method:
 new_foo = std::make_unique<FOO>(yoo, number);

(up until now everything is correct). What I want to do is to call execute on my new_foo. I tried with
 new_foo.execute();

But it says:
  error: 'class std::unique_ptr<WORK::TOBEDONE::FOO>' has no member named 'EXECUTE'

execute should be able to called on member <WORK::TOBEDONE::FOO> but the std::unique_ptr is giving me a hard time to understand what I should do.

A:

new_foo->execute();
unique_ptr behaves like a regular pointer in that sense, and has a operator-> and operator * overloaded.
you use a regular dot (.) to access unique_ptr functions (like std::unique_ptr::get) while using -> and * to access the pointee.
auto str = std::make_unique<std::string>("hello world");
auto i = std::make_unique<int>(5);

str->size();
*i = 4;
str.reset(); //deletes the pointee and make str point to null
i.reset(); //as above