Q:

Add getElementById with several IDs in the For loop

It is possible to add getElementById with several IDs in the For loop?
But first you have the querySelectorAll to list the IDs that have appeared.
Function that will return the formatted information if it exists:
function show_info(real_info, otp_inf) {
    if(real_info.indexOf('already exists') > -1) {
        var sinf = real_info.split("File '"+dir_files).pop();
        var sinf = sinf.split(' Overwrite').shift();
        $('#otp_'+otp_inf).html('
Not Encoded
File \''+ sinf +'');
    }
}

Here is the problem the For loop does not work if I put the getElementById inside:
var allids = document.querySelectorAll("#all_log div"); // To list all the IDs that have appeared
for (var i = 0; i < allids.length; i++) {
    if(allids[i].id.indexOf('bd_') > -1) { // Filter all IDs that start with...
        var idinfo = allids[i].id.split('bd_').pop(); // Show only the unknown name of the ID that will show the final text ......
        var id_info = document.getElementById(allids[i].id); // this line is not working
        show_info(id_info, idinfo);
    }
}

This will be the IDs:

    <?php
        echo '
'; //ID with the original text
        execOutput($cmd);
        echo '
';
        echo '

'; //ID with part of text
    ?>

A:

On the line, the goal is to collect the text in html of the ID, so it went wrong:
var id_info = document.getElementById(allids[i].id); // wrong

var id_info = $('#'+allids[i].id).html(); //correct


Q:

What happens with the avionics if in midair there is loss of power or fuel flow interrupted?

What happens if in midair there is loss of power, how will the avionics perform in such a situation (cockpit display, flight plan)?

A:

This is somewhat dependent on the aircraft of course, so I will focus on the Boeing 737 NG series as an example of a typical airliner. Details will differ with other aircraft, but the general concept should be the same.
When there is loss of thrust on both engines, both engine driven generators will stop providing power. The battery will take over powering some of the systems immediately. If two batteries are installed, all emergency systems can be supplied for at least 60 minutes:

Two 24 volt nickel–cadmium batteries, main and auxiliary, are located in the
  electronics compartment. The batteries can supply part of the DC system. The
  auxiliary battery operates in parallel with the main battery when the battery is
  powering the standby system. At all other times, the auxiliary battery is isolated
  from the power distribution system. Battery charging is automatically controlled.
  Two fully charged batteries have sufficient capacity to provide standby power for
  a minimum of 60 minutes. Battery voltage range is 22–30 volts.

(Boeing 737 NG FCOMv2 6.20.12 Electrical - System Description)
The batteries power some DC buses directly and the AC standby bus via a static inverter:

Standby Power System - Normal Operation
The standby system provides 115V AC and 24V DC power to essential systems
  in the event of loss of all engine or APU–driven AC power. The standby power
  system consists of:

static inverter
AC standby bus
DC standby bus
battery bus
hot battery bus
switched hot battery bus
main battery
auxiliary battery.

[...]
Static Inverter
The static inverter converts 24 volt DC power from the battery to 115V AC power
  to supply the AC standby bus during the loss of normal electrical power. The
  power supply to the inverter is controlled by the standby power switch and the
  battery switch on the overhead panel.

(Boeing 737 NG FCOMv2 6.20.16 Electrical - System Description)
The FCOM contains a long list with all systems that are powered in this configuration. In general, only the captain's side instruments will be available. I will not quote the full list here, since you only asked about "cockpit display, flight plan". The relevant items are:

All Generators Inoperative
The following list identifies the significant equipment that operates when the main
  battery and the auxiliary battery are the only source of electrical power.

emergency instrument flood lights
Captain's pitot probe heat
VHF No. 1
upper display unit
Captain's outboard and inboard display units (EFIS/MAP or PFD/ND)
clocks
left EFIS control panel
Standby instruments
FMC
left CDU
heading/track indications
VHF NAV No. 1
ILS No. 1
left IRS
left GPS

(Boeing 737 NG FCOMv2 6.20.19 Electrical - System Description)
This allows the Captain to continue flying the aircraft via manual reversion (no hydraulic pressure will be available, no autopilot is available). An emergency descent will have to be initiated without thrust. The checklist in the QRH will aim at restarting one or both engines. If that fails, the APU can be started in flight below 25,000 ft to provide more electrical power (all AC buses powered, all displays available again, electric hydraulic pumps available again).

A:

Although the accepted answer is basically correct, as an additional backup source of power (for hydraulics or electric, depending on the aircraft), there can be a Ram air turbine (RAT - https://en.wikipedia.org/wiki/Ram_air_turbine) that can be deployed in a failure of both primary and secondary energy sources.  It uses the airflow from the airplane's speed in the air to generate energy for hydraulics or electrical needs.

A:

Actual details vary between aircrafts. But in general, the battery can supply essential systems for some time and then APU/RAT/... should kick in.


Q:

highest weighted path for multiple destinations

I have a directed cyclic weighted graph. I want to find a path with the highest some of weights, in length of X vertices, and I don't care what is the destination. I only want to find the highest cost.

A:

This can be solved via dynamical-programming-like algorithm.
As you have only just a few hundreds of nodes and X is round 10. You can assign each node v an array Fv with size X, and Fv[i] represents the maximum cost from the source to the node v with length i.
Let s be the source. Set Fs[0] = 0, and all other Fs[i] = -infinity.
All other arrays are initialized as -infinity array.
Now,

for each node v, do the following update:
Fv[i] = max{Fv[i],  Fw[i-1] + cost(w, v) |  where w is neighbor of v}

repeat above updates for at least X times, and then check  Fv[X] for all v to get the maximum possible value you want.
You can use some extra information to retrieve the path, which should be very easy to do.
Above algorithm is a special case of Bellman-Ford Algorithm


Q:

Declaring variable final and static

This comment was made in a code review and the person who made it is no longer on our team.

Any type that must be resolved by the classloader at runtime should never have instances which are held by references declared to be both final and static.

Here's the line of code:
private final static Logger log = LoggerFactory.getLogger(MyClass.class);

I'm familiar with the debate of declaring loggers static or non-static, but this comment seems to be more general.  I can't find any explanations of why static and final are bad.  Can somebody elaborate?

A:

The comment is most likely related to a problem of Classloader Leaking (here is a good article).
In a nutshell, this problem happens in environments where classloader needs to be reloaded. If you load a class dynamically through a classloader and then try reloading the classloader, keeping static final fields with objects of classes created through this classloader will prevent unloading the classloader itself. Once this happens, you get an OutOfMemoryError.
The article linked above lists logging libraries among the top culprits that could produce this behavior, along with measures you can take to work around the leaks (such as releasing classloaders explicitly).

A:

The line of code is perfectly fine, and there is no real problem because the variable is final and static.
Maybe the person who made that comment was confused by the following.
In Java, when you create a public final static variable of type int (for example; it also works with some other types), then the compiler might, in places where you use that variable, substitute the actual constant value instead of a reference to the variable. For example, suppose you have the following:
class A {
    public final static int VALUE = 3;
}

public class B {
    public static void main(String[] args) {
        System.out.println(A.VALUE);
    }
}

When you compile and run this, it will obviously print 3.
Now suppose that you change class A and set VALUE = 4. You would expect that if you recompile class A and then run class B (without recompiling class B), you would see 4. But what happens is that you will still see 3. That is because the A.VALUE in class B was replaced by the actual constant value 3 when you compiled class B.
This is an optimization that the Java compiler does for constants.
As you can see this can cause problems, if you have such constants in the public API of your classes. Users of your code will have to recompile their code if you change the value of such constants.
But in the code you posted in your question this is not a problem, because the variable is private.
More details:
Java Language Specification 13.4.9


Q:

how to get the input given by a user through collect in a worflow through designer 2010?

i am using collect keyword to get an input from the user.
now inside the collect;
i have a custom form field with the name update status.
update status - choice field - user will be able togive approved/ rejected.
now in the sahrepoint designer workflow;
collect "Name" from "Jiben" (Output to variable:collect).
i want to update a field "STATUS" in the list associated with the workflow using the input from the user ?
is there any way to do that.
i am sturggling for doing this from today morning :( please help.

A:

Like explained here you will need to get your "Name" field via looking it up in the related tasks.
Let's say you have a collect data from user activity. "New Task". It has one custom field "MyField" (Text). It gets this data from user X and Output is set to Variable "collect". This variable will be the TaskID you want to look up.
So to set the field "Status" on your current list item, you can use a "Set Field in CUrrent Item" Activity. You only need to click the "Fx" and select the Task list where you have your collect data activity store your tasks (Association: Task List), Field from Source will be "MyField" and the Find the List Item you only need to set the Field to "ID" and the Value to "collect".
You should read some tutorials on how to design a workflow with Sharepoint Designer as there are many easy explanations and even nice sample videos explaining exactly your problem.


Q:

PHP Declare multidimensional arrays with square bracket syntax

I am trying to create a multi dimensional array using this syntax:
$x[1] = 'parent';
$x[1][] = 'child';

I get the error: [] operator not supported for strings  because it is evaluating the $x[1] as a string as opposed to returning the array so I can append to it.
What is the correct syntax for doing it this way? The overall goal is to create this multidimensional array in an iteration that will append elements to a known index.
The syntax ${$x[1]}[] does not work either.

A:

The parent has to be an array!
$x[1] = array();
$x[1][] = 'child';

A:

$x = array();
$x[1] = array();
$x[1][] = 'child';


Q:

Template HTML is always cached in browser

I've got a fairly simple Angular2 application in the works, and I'm trying to demo it to my boss on our staging server (typical Ubuntu LAMP). Every time I update a template and redeploy, I also have to clear my browser cache -- and so does my boss, and so do my future users! Not good!
I'm using templateUrl to load in my components' templates, and they are always being cached by the browser. I've tried disabling caching in .htaccess but it only seems to set the headers on the initial request and not for any of the XHR.
Is there a way to configure apache to disable caching for XHR? Or just completely disable browser caching no matter what?
Or am I doing something wrong in Angular? Is it a bad idea to run an Angular app on Apache?
Any advice or ideas would be greatly appreciated!

A:

It was Apache doing the caching, but the problem was simply a misunderstanding on my part. I never cleared my cache once I set Apache to stop caching. I assumed it would happen automatically, which is obviously not the way browser caching works.
So I'll have to clear my boss's cache one last time, and from there on out the problem will be solved.


Q:

Querying the Sphinx Search Index

I am using the Sphinx Search engine and I have an issue where a few files are not showing up in the search results and definitely should be.  I have checked to make sure no info. is missing that would prevent these files from appearing.
Is there some way for me to query the index directly to see if these records are in there, or to see whether or not a specific record is there?
I found a similar post on the subject:
Sphinx Search Index
So, it appears it is possible to do, but that post is not detailed enough on how to do it.  I am not following what exactly is going on in that post, in other words.  Do I just put this directly into the command line?
Or is there a tutorial available on this?  I searched and could not locate one.

A:

Sphinx provides connection through mysql's protocol, so you can use any of mysql's clients to connect and execute queries:
http://dev.mysql.com/doc/refman/5.5/en/programs-client.html
If you will install command-line client, you should connect like this:
$ mysql -h0 -P9306

Sphinx supports custom subset of SQL, called SphinxQL, you can use it to query data from index. There is documentation about SphinxQL:
http://sphinxsearch.com/docs/latest/sphinxql-reference.html


Q:

Can the ECS work in an unpressurized cabin?

Can you control the cabin temperature if the cabin is unpressurized? What if the "cabin" isn't really that big, like a fighter aircraft?
For example, could I cruise in comfort at 20,000 ft in an unpressurized cockpit with an oxygen mask and heater?

A:

If the cabin is unpressurised, the temperature could be controlled to a limited extent- this is usually done in a number of helicopters.
You can certainly cruise at 20k feet without a pressurized cabin - WWII pilots regularly did this with supplemental oxygen and heated clothing- though I'd hardly call it comfortable.

A:

Yes, you could. The smaller cabin is easier to heat because of its size.
If the engine is big enough to carry you to 20,000 ft, it produces plenty of waste heat for cabin heating. When the Russians experimented with docking fighters to bombers to extend the range of those fighters, the fighter pilots complained bitterly about the freezing temperatures in their cockpits once their engine was switched off. The first prototype of the FW-190 had no armament and a shorter fuselage, so the firewall was immediately ahead of the cockpit. The test pilot said flying it felt like having his feet roasted at a fireplace because the engine heat radiated into the cockpit.
Piston-engined aircraft allow to mix pre-heated and unheated air for cabin ventilation. The heat is either from a heat exchanger or just from piping the air near the engine. Jets and turbine-powered helicopters use bleed air which has been heated in the compressor as the source of cabin heat.
This is different in gliders, because there is no heat source and when flying at high altitude it can be really cold. You can wear thick clothing, but another problem is frosting of the canopy from the inside caused by the moisture in the pilot's breath. I found this more annoying than the cold temperature when flying in freezing air.


Q:

Always get checkout error with submodule on GitHub Desktop on Windows

I have a repo with a few branches. On one of them I deleted a directory, which does not really belong to the repo and added it back as a git submodule.
That's what I do:

Clone the repo
Switch to the branch with the submodule in GitHub Desktop
git submodule init
Until now I can switch the branches (between the ones with the submodule and no submodule without any issues).
git submodule update to finally get the "content" of the submodule

So everything is right until I try to switch the branch in GitHub Desktop (to another branch without any git submodules). If I do so I get a checkout error claiming I have uncommitted changes:

Failed to checkout the branch
The following files in your working
  directory would be overwritten by a checkout: [...] Please commit
  your changes before you can switch branches.

However as I said I did not changed anything - the only thing I did was updating my submodules.
git status shows everything is all right:
$ git status
On branch patch-submodule
Your branch is up-to-date with 'origin/patch-submodule'.

nothing to commit, working directory clean

When I deinit my submodules I can also switch the branches again.
So what's wrong here?
And how can I prevent this error or get around it?

A:

Thanks to the GitHub support I finally got a very useful reply.
Especially they directed me to Replaced third party code with git submodules, now I can't switch branches which exactly describes my issue - except of one difference: I did used the GitHub GUI and not the console.
And there is linked to git-scm where this is explained very nicely:

Switching branches with submodules in them can also be tricky. If you create a new branch, add a submodule there, and then switch back to a branch without that submodule, you still have the submodule directory as an untracked directory[.]
[...] You have to either move it out of the way or remove it, in which case you have to clone it again when you switch back—and you may lose local changes or branches that you didn’t push up.

This basically is all what this error messages meant in my case.


Q:

Our CMS is Expression Engine. Does this mean we can't use CiviCRM?

Is it possible to use CiviCRM when we have a website built with Expression Engine rather than Joomla, Drupal or WordPress?
Thanks
Karen

A:

You would not be able to have direct interaction between Expression Engine and CiviCRM like Drupal, WordPress or Joomla allows, but you could certainly install CiviCRM on a subdomain of your current website along with one of those three and use it on the subdomain. See https://civicrm.stackexchange.com/a/9385/105 for some great thoughts regarding this.
If you had developer support (your own or hired) you could use CiviCRM's API to have certain information from CiviCRM available on your current website.


Q:

How to get successive week number and year in java?

I am storing some data referenced with the week number. Now, I have two button to request for data. One for previous week and the another for the next week.And data for current week is fetched by defaultI just finished making exceptions for the year end that I learned that there is week 53 too next year (2020). Now it breaks everytime there is a week 53. (It just skips week 53s)Obviously, there must be a better way of doing this..
I just kept adding exceptions and following is the code I ended up with.
I am a noob, so please bear with the ugly logic.
LocalDate wks, mon, tue, wed, thu, fri, sat, wke;
try {
    week = Integer.parseInt(request.getParameter("week"));
    year = Integer.parseInt(request.getParameter("year"));
} catch (NumberFormatException e) {
    week = getWeek();
    year = getCurrYear();
    flag = 1;
}
LocalDate date = LocalDate.now()
.withYear(year) // year
.with(WeekFields.ISO.weekOfWeekBasedYear(), week) // week of year
.with(WeekFields.ISO.dayOfWeek(), 7);
wks = date.plusDays(-7);
if ((date + "").substring(0, 4).equals((wks + "").substring(0, 4))) {
} else if (flag == 1) {
    year++;
}
date = LocalDate.now()
.withYear(year) // year
.with(WeekFields.ISO.weekOfWeekBasedYear(), week) // week of year
.with(WeekFields.ISO.dayOfWeek(), 7);
wks = date.plusDays(-7);
mon = wks.plusDays(1);
tue = wks.plusDays(2);
wed = wks.plusDays(3);
thu = wks.plusDays(4);
fri = wks.plusDays(5);
sat = wks.plusDays(6);
wke = date;
System.out.println(week + " " + year);
heading = "<div class='row'>"
        + "<form action=\"";
if (week == 1) {
    heading += "javascript:setContent('/getData?week=52&year=" + (year - 1) + "')\" >";
} else {
    heading += "javascript:setContent('getData?week=" + (week - 1) + "&year=" + (year) + "')\" >";
}
heading += "<button type='submit'>Previous</button></form><form action=\"";
if (week == 52) {
    heading += "javascript:setContent('getData?week=1&year=" + (year + 1) + "')\" >";
} else {
    heading += "javascript:setContent('getData?week=" + (week + 1) + "&year=" + (year) + "')\" >";
}
heading += "<button type='submit'Next</button></form>";
out.print(heading);

function:  getWeek()
public static int getWeek() {
        java.util.Date date = new java.util.Date();
        SimpleDateFormat ft = new SimpleDateFormat("w");
        return (Integer.parseInt(ft.format(date)));
    }

function:  getCurrYear() {
public static int getCurrYear() {
         Date date = new Date();
         return (date.getYear() + 1900);
    }

I have to print the dates of the days in the week, that's why variables of monday to saturday.

I just want a function like below

function int[] getWeekYear(){
    return [prev week,prev week's year,current week,current year,next week,next week's year];
}

A:

tl;dr
YearWeek
.now(
    ZoneId.of( "Asia/Tokyo" )
)
.minusWeeks( 1 )
.getWeek()         // Returns an `int` in range of 1-52 or 1-53, the week number within a year.

Details
Never use either of the two Date classes. They are terrible, and are now legacy. They were supplanted years ago by the modern java.time classes defined in JSR 310.
The Answer by Renato is correct.
YearWeek
Furthermore, if your definition of a week is the standard ISO 8601 definition (week starts on a Monday, week # 1 contains first Thursday of calendar-year), then add the ThreeTen-Extra library to your project. This library has classes extending the functionality of java.time. In particular, you get the YearWeek class.
Get current week. This requires a time zone. For any given moment the date varies around the globe by time zone.
ZoneId z = ZoneId.of( "Africa/Tunis" );
YearWeek currentWeek = YearWeek.now( z ) ;

To get prior or next week, simply call the plus or minus methods.
YearWeek priorWeek = currentWeek.minusWeeks( 1 ) ;
YearWeek followingWeek = currentWeek.plusWeeks( 1 ) ;

If you want a date from a week, call atDay and pass a day-of-week from the DayOfWeek enum.
LocalDate localDate = priorWeek.atDay( DayOfWeek.MONDAY ) ;

You can interrogate for the week’s number and its year number (week-based-year that is).
int weekNumber = priorWeek.getWeek() ;
int weekBasedYearNumber = priorWeek.getYear() ;


Q:

Trying to create a list of decoded NavigableStrings in Beautiful Soup

I want to make a list of NavigableStrings ready to export to excel with all strings decoded. This is necessary since I need all text to not have the "u" in front of it when being exported to excel.
This is what I've done so far: I ran the list through a for loop and stored the output of each iteration into a new list. However, each element of the new list remains in unicode.
encoded_list = [u'first', u'second']
decoded_list = []

for elem in encoded_list:
     decoded_list.append(elem.decode())

print decoded_list
>>>[u'first', u'second']

`
It's obvious that NavigableStrings can be decoded, but not when they are stored into lists immediately proceeding iteration.
Is there any other way to make encoded_list into a list of decoded NavigableStrings?
Any help would be much appreciated!

A:

You need to encode, not decode. e.g.
encoded_list = [u'first', u'second']
decoded_list = []

for elem in encoded_list:
     decoded_list.append(elem.encode())

print decoded_list
>>>['first', 'second']

Also, you should pass an encoding to encode() otherwise it will just choose the default encoding for your Python installation.


Q:

Perl: How to process HTTP response with encode_base64

I have an task to generate an BASE64 string from HTTP response which will be used by the external program.Before I was doing this,I had known that if you use BASE64,the length of the string will be extend like 57 * 4/3 = 76.
But I've no idea which need to be handle if the HTTP respone longer than 57 bytes! So I had not any special handle for the HTTP response,just direct covert "$response->content" to which I want.(Actually length of the response more than 57 bytes).

3.The unexpected thing is that the length of the encode string not excatly follow 4/3 rule!!! When the len of input string is 57,then len of encode string is 77. When the len of input string is 114, the encode string is 154,why?
4.When I try to use the BASE64 output from an external c# arg(),seems it can only receive first 57 bytes.
#Sample Code
my $cont = $response->content;
$cont = substr ($cont, 0, 57);
my $encode = encode_base64($cont);
printf("Length Before Decode = %d.\n",length($cont));
printf("Length After Decode = %d.\n",length($encode));
#

A:

According to this note, encode_base64() adds a newline.  Are you counting that newline in the encoded string length?  It seems to account for your extra character.


Q:

Set directory for fixture_file_upload in Rails?

When using fixture_file_upload, the files are being uploaded to public/tmp as expected. However, these files are being created in a factory (factory_girl), and so my public/tmp is full of files uploaded during tests.
What is the recommended way to clear those files, or delete files after object is destroyed during testing?

A:

If you use RSpec you can define a block which run before or after the suite.
I prefere to delete the files before. This will leave the files after the tests, so I can inspect the temp-files; but it clears old files before the test, so I have a clean path each time I run the tests.
in spec/spec_helper.rb:
RSpec.configure do |config|
  ......
  config.before(:all) do
    if Rails.env.test? || Rails.env.cucumber?
      FileUtils.rm_rf(Dir["#{pstore_path}/[^.]*"])
    end
  end

pstore_path is another method in my spec_helper-file. You may change the line FileUtils.rm_rf.... to remove only the files you want to delete instead of an entire directory as shown in this example.
You can combine before and after filter to record the files already exists before the tests and then remove any files created during the test in an config.after block.


Q:

YUI get specific cell value when selecting a row to fire event

I am using Yahoo UI library, in particular this example.
What I want is to get a particular column's value when clicking (selecting) a row.
I am using this code:
var makis = function() {alert("blabla"); };
myDataTable.subscribe("rowClickEvent", makis);

and works, but i just dont know how to get a column's value in the particular row.
THanks and sorry for the poor grammar.

A:

Ok i found it on my own, i am posting if anyone has the same problem.
myDataTable.subscribe("rowClickEvent", function(oArgs) {
                                        var elTarget = oArgs.target;
                                        var oRec = this.getRecord(elTarget);
                                        console.log("value:" + oRec.getData("column_we_want"));
                                }


Q:

Converting Historical Timestamps from UTC to Local

I have a file with timestamps that are in the past and are all in UTC. I need to convert these to Eastern Time. I've gotten close, but it messes up around the daylight savings changeover.
#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;

#DST not in effect
my $utc = '2015-03-08 01:59:00.000';
my $local = utc_to_local($utc);
print "DST not in effect: utc($utc) = local($local)\n";

#DST not in effect
$utc = '2015-03-08 02:00:00.000';
$local = utc_to_local($utc);
print "DST not in effect: utc($utc) = local($local)\n";

sub utc_to_local
{
    my $utc_ts = $_[0]; #this has ms on right side, we want left 19 characters
    $utc_ts = substr $utc_ts, 0, 19;
    my $local_tp = localtime->strptime( $utc_ts, '%Y-%m-%d %H:%M:%S' );
    $local_tp = $local_tp + $local_tp->tzoffset();

    return $local_tp->strftime('%Y-%m-%d %H:%M:%S');
}

As you can see, if I try 1:59 AM UTC on 3/8 and 2 AM UTC on 3/8, it thinks the change has occurred, but 2 AM UTC is only 3/7 at 9 PM. Away from the daylight savings changeover it does -5 and -4 offsets correctly.
DST not in effect: utc(2015-03-08 01:59:00.000) = local(2015-03-07 20:59:00)
DST not in effect: utc(2015-03-08 02:00:00.000) = local(2015-03-07 22:00:00)

A:

$utc_ts isn't a local time.
my $local_tp = localtime->strptime( $utc_ts, '%Y-%m-%d %H:%M:%S' );

should be
my $utc_tp = Time::Piece->strptime( $utc_ts, '%Y-%m-%d %H:%M:%S' );

Then there's the issue of converting to localtime.
$local_tp = $local_tp + $local_tp->tzoffset();

should be
my $local_tp = localtime($utc_tp->epoch);

All together:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw( );
use Time::Piece;

sub utc_to_local {
    my ($utc_ts) = @_;
    my $utc_tp = Time::Piece->strptime( $utc_ts, '%Y-%m-%d %H:%M:%S' );
    my $local_tp = localtime($utc_tp->epoch);
    return $local_tp->strftime('%Y-%m-%d %H:%M:%S');
}

sub local_to_utc {
    my ($local_ts) = @_;
    my $local_tp = Time::Piece->strptime( $local_ts, '%Y-%m-%d %H:%M:%S' );
    my $utc_tp = gmtime($local_tp->epoch);
    return $utc_tp->strftime('%Y-%m-%d %H:%M:%S');
}

{
    $ENV{TZ} = 'America/Toronto';
    POSIX::tzset();

    # DST not in effect
    my $utc = '2015-03-08 06:59:00.000';
    my $local = utc_to_local(substr($utc, 0, -4));
    print "DST not in effect: utc($utc) = local($local)\n";

    # DST not in effect
    $utc = '2015-03-08 07:00:00.000';
    $local = utc_to_local(substr($utc, 0, -4));
    print "DST not in effect: utc($utc) = local($local)\n";
}

Output:
DST not in effect: utc(2015-03-08 06:59:00.000) = local(2015-03-08 01:59:00)
DST not in effect: utc(2015-03-08 07:00:00.000) = local(2015-03-08 03:00:00)


Q:

Computing limits example: Swaping limit to $0$ into infinity.

I have found the following example:
$$
  \lim_{x\to 0^{+}} \frac{e^{\frac{-1}{h}}}{h} =
  \lim_{z\to\infty} ze^{-z} =
  0
$$
Could you explain to a kid nice and slowly why does the limit of $x$ to $0$ now is limit of $z$ to $\infty$?
P.S. I know how to compute the limit from the left, I just found in the solution book this solution from the right which I found strange and is unknown to me.

A:

It is a substitution of $z := \frac{1}{h}$. So when $h\to 0^+$ we have that $z\to \infty$.


Q:

Cannot retrieve data from database in C#

I have an application,which is not able to fetch data from the database for this specific form, while other forms are working fine.
I am using this form to fetch data from database and then display that data onto labels on an another form.
The code for fetching data is:
string PName, DName, Psex, PPhoneNo, PAddress, Treatment, Teethno, PAge, Amount;

SqlDataAdapter a = new SqlDataAdapter("Select bills.BillNo,bills.PName,bills.DName,bills.PAge,bills.PSex,bills.PPhoneNo,bills.PAddress,bills.Treatment,bills.Amount,bills.Teethno,addpro.Medicines from bills,addpro where bills.BillNo=" + bno, Program.con);

DataTable t = new DataTable();
a.Fill(t);
PAge = Convert.ToString(t.Rows[3]);
Amount = Convert.ToString(t.Rows[8]);
PName = Convert.ToString(t.Rows[1]);
DName = Convert.ToString(t.Rows[2]);
Psex = Convert.ToString(t.Rows[4]);
PPhoneNo = Convert.ToString(t.Rows[5]);
PAddress = Convert.ToString(t.Rows[6]);
Treatment = Convert.ToString(t.Rows[7]);
Teethno = Convert.ToString(t.Rows[9]);

frmPrint sa=new frmPrint();
sa.start(bno, PAge, Amount, PName, DName, Psex, PPhoneNo, PAddress, Treatment,  Teethno);

when i try to load the next form which displays the data from this DataTable on labels it gives the following error:-

There is no row at position 3.

A:

Your're using Row and you want to be using Column:
foreach(DataRow row in t.Rows)
{
        PAge = row["PAge"].ToString();
        Amount = row["Amount"].ToString();
        PName = row["PName"].ToString();
        DName = row["DName"].ToString();
        Psex = row["PSex"].ToString();
        PPhoneNo = row["PPhoneNo"].ToString();
        PAddress = row["PAddress"].ToString();
        Treatment = row["Treatment"].ToString();
        Teethno = row["Teethno"].ToString();
}

Instead of using the number to identify the column, use the name.  If the order of the query was to change for any reason, this would not have an impact on your code.  If you used the Ordinal number, then you would need to change your row[n] code too since the order would have changed.


Q:

CKEditor 4. Shrinking of text selection

When I select some text and click on toolbar's item (dropdown, image gallery etc)  selection start shrinking
normal behavior
http://prntscr.com/iab12k
and afterward
http://prntscr.com/iab1qk
I tried to catch "selectionChange" event but it's not called when selection shrinking
PS: I found the issue. When SCAYT plugin (when it checking words for correctness)  works, it's happening
Any ideas?

A:

The reported issue is a known SCAYT issue. Shrinking of text selection is a visual effect only - your text remains be selected. So the issue isn't influenced SCAYT or CKEditor work and doesn't corrupt your content, formatting etc.


Q:

Populate html container based on link

I have a webpage with a container which loads different content when clicking on three possible buttons (Event, News and Others). This is achieved by using onclick on the buttons and a proper javascript function.
I'd like to craft a link to the page which is able to show the content without the user having to click the given button.
In other words, the default content shown is about News, however, there are cases in which I want to promote an event and therefore I need a link that people can click on (from outside my website) and automatically see the container with the events content.
The code I'm using, just for sake of clarity, is the following:

            News

            Eventi

            Crono Reg Ue

The javascript function is the following:
function changeTab(displayTab){
    if (displayTab == 'news') {
       document.getElementById("crono_regue").className = "hide";
       document.getElementById("eventi").className = "hide";
       document.getElementById("news").className = "";

       document.getElementById("cronoregue_btn").className = "grid-cell grid-33 bg-grey-light";
       document.getElementById("eventi_btn").className = "grid-cell grid-33 bg-grey-light";
       document.getElementById("news_btn").className = "cell-first grid-cell grid-33 bg-grey-light flex-active";
    }
    if (displayTab == 'eventi') {
       document.getElementById("crono_regue").className = "hide";
       document.getElementById("news").className = "hide";
       document.getElementById("eventi").className = "";

       document.getElementById("cronoregue_btn").className = "grid-cell grid-33 bg-grey-light";
       document.getElementById("news_btn").className = "cell-first grid-cell grid-33 bg-grey-light";
       document.getElementById("eventi_btn").className = "grid-cell grid-33 bg-grey-light flex-active";
    }
    if (displayTab == 'crono_regue') {
       document.getElementById("news").className = "hide";
       document.getElementById("eventi").className = "hide";
       document.getElementById("crono_regue").className = "";

       document.getElementById("cronoregue_btn").className = "grid-cell grid-33 bg-grey-light flex-active";
       document.getElementById("news_btn").className = "cell-first grid-cell grid-33 bg-grey-light";
       document.getElementById("eventi_btn").className = "grid-cell grid-33 bg-grey-light";
    }
}

I don't know whether this is achievable the way I designed my page cause I'm struggling to find a solution. I know the title I gave to the post might be to generic but I found explaining the problem only using few words hard.
Thanks in advance

A:

You make the link something like http://www.example.com#news...
if(window.location.hash) {
    var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
    changeTab(hash);
}

So when the page loads, JavaScript looks up the hash and passes it to your function.


Q:

How do I debug or print to console in Munit Haxe?

I'm trying to debug something in Haxe while running Munit. Is there a way I can debug or print to the console information while running my tests?

A:

Flash:
There's a little grey arrow that you can click for each test that will show all traces.
CPP:
haxelib run munit test -cpp
cpp.Lib.print("foo");


Q:

Logical error while running scanf in for loop, how do i fix it?

#include <stdlib.h>
#include <stdio.h>

struct card
{
   char Top;
   char Bottom;
};

int main()
    {
    int T,i;
    struct card cards[4];
    scanf("%d", &T);
    for(i=0; i<3; i++)
        {
            scanf("%c%c%c", &cards[0].Top, &cards[1].Top, &cards[2].Top);
            printf("%c%c%c\n", cards[0].Top, cards[1].Top, cards[2].Top);
        }
return 0;
}

It does not correctly print the three characters, outside the for loop it scans and prints fine.

A:

Solution to your problem
Change the scanf line to this. (Note the spaces before %c)
scanf(" %c %c %c", &cards[0].Top, &cards[1].Top, &cards[2].Top);

Other comments on your code
ALWAYS check return value from scanf. It should look like this:
if(scanf(" %c %c %c", &cards[0].Top, &cards[1].Top, &cards[2].Top) != 3) {
     // Print error message and exit program or something else
} else {


Q:

Constrain a regex match's starting point

I'm parsing a long string and want to use a regular expression for part of the parsing.
For simplicity, let's say my regex is <[a-z]*> and I'd like to run it when I get to the first <.
public int FindEnd(string longStr, int index) {
    // longStr[index] == '<'

    var match = regex.Match(longStr, index);
    if (!match.Success || match.Index != index) {
        throw new Exception("Mismatch");
    } else {
        return index + match.Length;
    }
}

I'd like to constrain the regex somehow so that it doesn't go over the entire string, but only looks for strings at the given starting point - is this possible? I tried ^<[a-z]*> but that didn't work - it wouldn't accept anything (except if index points to the start of the string).
Note: I'm not trying to parse HTML with a regex.

A:

I think you're looking for \G<[a-z]*>


Q:

Change order of operation applied to a dask bag

I am using a dask bag to handle parallelization of data processing on traces collected from a set of experiments. The paths to the data files for each experiment are turned into custom objects and common operations I perform on this type of data are object methods.
Each object has an identification number associated with the particular experiment. And at some point in the program I want to use this ID number to remove some of the experiments. As in this task graph, where a object is created from a sequence, detrending and deconvolution functions are then applied followed by a remove operation.

Because experiment identification number is static the remove operation can be performed at any step in the task graph and the end result will be the same. However if the remove operation is performed following other computationally costly methods the result will be mush slower, due to these computations being performed unnecessarily on objects that will end up being removed.
Is there a way to insert an operation at an earlier point in the task graph for the bag so that if someone adds a remove operation at any point, it will be the first operation performed?

A:

Instead of using dask bag you might want to look at dask delayed, which might give you a bit more flexibility:
http://dask.pydata.org/en/latest/delayed.html
If you really want to muck about with the task graph directly then you should read about the graph specification
http://dask.pydata.org/en/latest/spec.html


Q:

Show that the determinant of a matrix is nonzero

Suppose $u,v,w \in \mathbb{Q}$ with $u,v,w \neq 0$. Show that the
determinant of the following matrix is nonzero.
$$M = \begin{bmatrix} u & 2w & 2v \\ v & u & 2w \\ w & v & u \end{bmatrix}$$
Hint: Argue by contradiction, reduce to the case when $u,v,w$ are integers and use some number theory over $\mathbb{Z}$.

I know that the determinant is given by
$$ \det M = u^{3} + 2v^{3} + 4w^{3} - 6 \,u\,v\,w $$
It is unclear to me how to utilize the hint. How to convert the problem over $\mathbb{Z}$?

A:

As $u,v,w$ are rationals, you can just multiply every entry with a sufficiently large integer so that every entry becomes an integer. This will not change the fact whether the determinant is zero or not. Therefore, w.l.o.g. $u,v,w$ can be assumed to be integers. Similarly, we can assume that $u,v,w$ are not all even (otherwise just divide all entries by $2$ and repeat). Now observe that if $\det M = 0$, then $u$ must be even. But that means that $u^3+4w^3-6uvw = -2v^3$ is divisible by $4$. Hence $v$ is even, too. Thus $u^3+2v^3-6uvw = -4w^3$ is divisible by $8$, and so $w$ is even as well. Contradiction.


Q:

Declare dynamically added class properties in TypeScript

I want to assign properties to the instance of a class without knowing the property names, values and types of values in TypeScript. Lets assume we have the following example.ts script:
// This could be a server response and could look totally diffent another time...
const someJson:string = '{ "foo": "bar", "bar": "baz" }'

class MyClass {
  someProperty:boolean

  constructor( json:string ) {
    const parsedJson:any = JSON.parse( json )

    Object.keys( parsedJson ).forEach(
      ( key:string ) => {
        this[ key ] = parsedJson[ key ]
      }
    )

    this['someProperty'] = true
  }
}

const myInstance = new MyClass( someJson )

// Works fine, logs `true`.
console.log( myInstance.someProperty )

// Error: Property 'foo' does not exist on type 'MyClass'.
console.log( myInstance.foo )

// Error: Property 'bar' does not exist on type 'MyClass'.
console.log( myInstance.bar )

How can I make sure that the TypeScript compiler does not complain of the dynamically added properties but instead handle them as "key": value pairs of any type. I still want tsc to make sure that myInstance.someProperty has to be of type boolean but I want to be able to get myInstance.whatever even if it is not defined without running into compiler errors.
I did not find any documentation that makes this clear to me. Maybe because I'm not a native english speaker. So please keep the answers simple.
Edit:
I remember that there was something like the following but I never got that to work:
interface IMyClass {
  [name:string]: any
}

A:

The problem is that you're adding the new properties at runtime and the compiler has no way of knowing that.
If you know the property names in advance then you can do this:
type Json = {
    foo: string;
    bar: string;
}

...

const myInstance = new MyClass(someJson) as MyClass & Json;
console.log(myInstance.foo) // no error

Edit
If you do not know the properties in advance then you can't do this:
console.log(myInstance.foo);

Because then you know that foo is part of the received json, you'll probably have something like:
let key = getKeySomehow();
console.log(myInstance[key]);

And this should work without an error from the compiler, the only problem with that is that the compiler doesn't know the type for the returned value, and it will be any.
So you can do this:
const myInstance = new MyClass(someJson) as MyClass & { [key: string]: string };
let foo = myInstance["foo"]; // type of foo is string
let someProperty = myInstance["someProperty"]; // type of someProperty is boolean

2nd edit
As you do know the props, but not in the class, you can do:
type ExtendedProperties<T> = { [P in keyof T]: T[P] };
function MyClassFactory<T>(json: string): MyClass & ExtendedProperties<T> {
    return new MyClass(json) as MyClass & ExtendedProperties<T>;
}

Then you simply use it like so:
type Json = {
    foo: string;
    bar: string;
};
const myInstance = MyClassFactory<Json>(someJson);

Note that this will work only on typescript 2.1 and above.


Q:

Python - Should I put my helper functions inside or outside the class?

In Python, if some methods of a class need a helper function, but the helper function itself doesn't use anything in the class, should I put the helper function inside or outside the class?
I tried putting it inside but PyLint was complaining that this function could have been put outside.
@Karl:
The class is a software upgrader and the helper function creates a new folder if the folder doesn't exist yet. The class is in a module having pretty much only the code for the class as of now. Other classes may be added later on.

A:

When deciding where to put helper functions the question I ask is, "Is it only for this class?"  If it can help in other places, then it goes at the module level; if it is indeed only for this class, then it goes in the class with either staticmethod (needs no class data to do its job) or classmethod (uses some class, but not instance, data to do its job).
Another python code checker is pyflakes.

A:

It's possible that the helper function better fits in at the module level rather than the class.
If you don't agree that this is the case, there is a staticmethod decorator that you can use on functions inside of the class. Simply put, a static method behaves the same between object instantiations of the same class. It does not rely on instance data.
For this reason, the staticmethod decorator renders behavior on the function such that it does not take an implicit first argument (typically self) as stated in the documentation).


Q:

Excel.Interop unable of progressing after a new instance is initialized

I am sitting with the following issue: after a new instance of Interop.Excel.Application() is initialized, my application hangs without timeout or any other progress/exception, nadda.
A bit of background, it is a brand new installation of Office 2013 on a Windows 2012 R2 server. I have got an IIS application pool running under a unique built-in account. This specific account has got full administrative rights on the server. I have added Local Launch and Local Activation DCOM configuration permissions for this specific user under the Component Services > Launch and Activation Permissions section and also created the Desktop folder on System32\config\systemprofile.
Below is the code I use to instantiate a new instance of Excel:
var excelApplication = new Microsoft.Office.Interop.Excel.Application();

On our dev environment, I do not have this issue and I also did not have to specifiy the DCOM configuration permissions. The Dev environment is running on a Windows 2008 R2 Standard server and Office was also newly installed a couple of weeks ago. Same configuration on IIS applies whereas it is a unique built-in account for the application pool identity.
Any help would be greatly appreciated!

A:

It turned out that the IIS custom-account user did not have adequate permissions on the production server. Once the account was updated, it worked.


Q:

how to design a generator for list loop in python3

I want to design a generator as gen(num):
the idea is to generator a sequence of number. such as if num=3, the sequence will be (1,2,3,2,1,2,3,2,1.....). if num=4,  the sequence will be (1,2,3,4,3,2,1,2,3,4,3,2,1,....)
def gen(num)

And how to use this generator in a for loop?
such as
a = [1,2,3,4,5]
b = gen(10)
for item in a:
    a+next(b)

it is good to use next(b) or we have better solution?

A:

def gen(n):
    c, i = 1, -1
    while True:
        if c in (1, n):
            i *= -1
        yield c
        c += i

a = [1,2,3,4,5,6,7,8,9,10]
b = gen(3)
for va, vb in zip(a, b):
    print('{}\t{}\t{}'.format(va, vb, va + vb))

Prints:
1   1   2
2   2   4
3   3   6
4   2   6
5   1   6
6   2   8
7   3   10
8   2   10
9   1   10
10  2   12

Update: Version of the generator with itertools.cycle:
from itertools import cycle

gen = lambda n: cycle([*range(1, n+1)] + [*range(n-1, 1, -1)])


Q:

Moving down, right, left and up in matrix recursively causes stack overflow exception

the program is for finding out the shortest path between two points in a matrix,
wherein i traverse down,right, left and up but due to recursion it goes into an infinite loop coming back and forth.
this program basically traverses through the matrix where

'C' denotes destination
'B' denotes source
'_' denotes allowed move
'D' means not allowed

the problem is to find the shortest bath between B and C.
How i can i make this code work ?? as in to stop the control to go downwards after once.
import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Stockroom
{
    //static int m = 0;
    //static int n = 0;
    //static char a[][] = new char [m][n];

    public static boolean checkFeasibility(int x, int y, int row, int col, char a[][])
    {
        if(x>=0 && x<row && y>=0 && y<col && a[x][y] != 'D')
        return true;

        else
        return false;
    }

    public static boolean shortestPath(char a[][], int bx, int by, int x, int y, int len, int minLen)
    {
        if( checkFeasibility(bx,by,x,y,a)==false )
            return false;

           if(a[bx][by]=='C')
           {
               minLen = Math.min(len,minLen);
               System.out.println(minLen-1);
               return true;
           }

               len++;

               if(shortestPath(a,bx+1,by,x,y,len++,minLen)== true)
               return true;

               if(shortestPath(a,bx,by+1,x,y,len++,minLen)==true)
               return true;

               if(shortestPath(a,bx,by-1,x,y,len++,minLen)== true)
                   return true;

               if(shortestPath(a,bx-1,by,x,y,len++,minLen)== true)
               return true;

               else {
                   len--;
                   return false;
               }

    }

    public static void main (String[] args) throws java.lang.Exception
    {
           char arr[][] = {
                            {'_','B','_','_'},

                            {'D','_','_','D'},

                            {'_','D','_','_'},

                            {'_','_','C','_'},

                          };

           int bx =0,by=1,px=3,py=2;
           int n =4,m=4;

           shortestPath(arr, bx, by, m, n, 0, 100);

    }
}

A:

Elaborating a bit on Frank Puffer’s idea:
class Stockroom {

    public static boolean checkFeasibility(int x, int y, int row, int col,
            char a[][]) {
        if (x >= 0 && x < row && y >= 0 && y < col && a[x][y] != 'D')
            return true;

        else
            return false;
    }

    public static boolean shortestPath(char a[][], int bx, int by, int x,
            int y, int len, int minLen) {
        if (checkFeasibility(bx, by, x, y, a) == false)
            return false;

        if (a[bx][by] == 'C') {
            minLen = Math.min(len, minLen);
            System.out.println(minLen - 1);
            return true;
        }

        len++;

        if (len >= minLen) { // this was not shortest
            return false;
        }

        // hack to make sure we don’t go through the same spot again
        a[bx][by] = 'D';

        if (shortestPath(a, bx + 1, by, x, y, len, minLen) == true) {
            // remove temporary block so this space can be used in other paths
            a[bx][by] = '_';
            return true;
        }

        if (shortestPath(a, bx, by + 1, x, y, len, minLen) == true) {
            a[bx][by] = '_';
            return true;
        }

        if (shortestPath(a, bx, by - 1, x, y, len, minLen) == true) {
            a[bx][by] = '_';
            return true;
        }

        if (shortestPath(a, bx - 1, by, x, y, len, minLen) == true) {
            a[bx][by] = '_';
            return true;
        }

        len--;
        return false;

    }

    public static void main(String[] args) {
        // find path from B to C; don’t go through D
        char arr[][] = { { '_', 'B', '_', '_' },
                         { 'D', '_', '_', 'D' },
                         { '_', 'D', '_', '_' },
                         { '_', '_', 'C', '_' },
                        };

        int bx = 0, by = 1, px = 3, py = 2;
        int n = 4, m = 4;

        shortestPath(arr, bx, by, m, n, 0, 100);
        System.out.println(Arrays.deepToString(arr));
    }
}

This repairs the overwriting of '_' fields, but still overwrites the 'B'. The program prints 3 since the shortest path has length 4 and you subtract 1.


Q:

apt-cache under Debian 6.0 displays a packet both as a dependency and conflict at the same time

Could somebody explain how can a syslinux packet both depend on and conflict with syslinux-common:
martin@IBM:~$ dpkg -l syslinux syslinux-common
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                      Version                   Description
+++-=========================-=========================-==================================================================
un  syslinux                  <none>                    (no description available)
un  syslinux-common           <none>                    (no description available)
martin@IBM:~$ apt-cache depends syslinux
syslinux
  Depends: libc6
  Depends: syslinux-common
  Suggests: dosfstools
  Suggests: mtools
  Conflicts: syslinux-common
  Replaces: syslinux-common
martin@IBM:~$

Or how should one understand the output of apt-cache depends <packagename>?

A:

If you look at the output of apt-cache show syslinux it will probably shed more light:
For brevity, I'm only showing the fields I'm referring to, from the second result (the highest version) to the command above:
Package: syslinux
Version: 2:4.05+dfsg-6+deb7u1
Replaces: syslinux-common
Depends: libc6 (>= 2.7), libuuid1 (>= 2.16), syslinux-common (= 2:4.05+dfsg-6+deb7u1)
Recommends: mtools
Suggests: dosfstools, os-prober
Breaks: syslinux-common (<< 2:4.05+dfsg-6+deb7u1)

As you can see, syslinux 2:4.05+dfsg-6+deb7u1 depends on syslinux-common 2:4.05+dfsg-6+deb7u1, and it breaks any version of syslinux-common less than 2:4.05+dfsg-6+deb7u1.
apt-cache depends is a simple tool, and is almost certainly conflating "conflicts" and "breaks" here, which is how you end up with syslinux both depending on and conflicting with syslinux-common. If apt-cache depends showed version numbers it would be clearer.


Q:

How to redirect URLs to login page?

I have an application which has a login page which comes up with the URL:
http://localhost:8080/Analyze
when the user fills the login page and clicks submit.it goes to a page with the URL:
http://localhost:8080/Analyze/analyze
Now if i copy the url:http://localhost:8080/Analyze/analyze and paste in a new browser window I get
HTTP Status 405 - HTTP method GET is not supported by this URL
What can I do to redirect back to the login page:
http://localhost:8080/Analyze if I copy paste http://localhost:8080/Analyze/analyze in a new browser window.

A:

You didn't state how you are handling the requests so my answer is necessarily vague.
For that URL you need to write code to handle the HTTP GET method and forward the request to the page you want.  If you're in a servlet you'd do something like this:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException
{
  String urlStr = "/Analyze";
  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
  dispatcher.forward(req, resp);
}


Q:

SQLSTATE[23000] On non empty column [ANGULAR 5 & NODEJS]

I'm using Angular 5 and a NodeJS API (using express).
I'm trying to save some data from a form to my "training" table but I'm getting this error:

code":"ER_BAD_NULL_ERROR","errno":1048,"sqlMessage":"The field
  'denivele_positif' cannot be null
  (null)","sqlState":"23000","index":0,"sql":"Insert into trainings
  values(NULL,20,'00:50:00',NULL,NULL,'2018-01-01',NULL)

I don't know why I get this error because the data are correctly sending, here's what I get with Firefox network debugger in the "Params" tab

Here's my table
I think the problem come from the API so here's my "router.post" function
router.post('/', function(req,res,next) {

Training.addTraining(req.body, function (err, count) {
    if (err) {
        res.json(err);     // Si une requete est fausse on retourne un JSON "satus: false"
    }
    else {
        res.json(
            {status: true}
        );      // Si une requete est vraie on retourne un JSON "satus: true"
    }
});

And my "addTraining" function:
addTraining:function(trainings,callback){
    console.log(trainings);
    return db.query("INSERT INTO `trainings` (`id`, `distance`, `temps`, `denivelePositif`, `deniveleNegatif`, `date`, `userEmail`) VALUES(?, ?, ?, ?, ?, ?, ?)", [trainings.id, trainings.distance, trainings.temps, trainings.denivelePositif, trainings.deniveleNegatif, trainings.date, trainings.userEmail],callback);
},

I did a console.log of my object "trainings" in my "addTraining" function** just before the "Insert into ..." and the "trainings" object contain all my value, so there's a problem with my SQL query (I think)...

Please tell me if you want anything.
Thanks you for your help
Regards,

A:

Thanks @Barmar, it was some typos in my "addTraining" function, now it's:
addTraining:function(trainings,callback){
    console.log(trainings);
    return db.query("INSERT INTO `trainings` (`id`, `distance`, `temps`, `denivelePositif`, `deniveleNegatif`, `date`, `userEmail`) VALUES(?, ?, ?, ?, ?, ?, ?)", [trainings.id, trainings.distance, trainings.temps, trainings.denivPositif, trainings.denivNegatif, trainings.date, trainings.emailUser],callback);
},


Q:

Data Structure - Avoid Duplicate in List and Map

I have a million Employee Objects in a List. The Employee Objects get modified and also sorted many times while processing. Also, while processing, there is a need to fetch Employee objects by Department. Means, I have to maintain a Map with Department as Key and List as value.
While processing, the RAM shoots up to 100+ GB. Whereas, the Employess per se on a file is about 2 GB.
List is the master, while Map is there for convenience (to fetch by Department).
Now, my question is: How can I avoid duplication of Employee objects in List & Map? Whenever a getByDept is called, if I loop through List it's expensive & time consuming.
I need a Map with List as  backing data. Any changes to the Employee object in List should reflect in the Map too.
Any ideas to build a data structure without duplicating Employee objects in Map?
Thanks in advance.

A:

Try to use a Set instead of a List:

A collection that contains no duplicate elements

Adding two times the same element in the set doesn't change the set.
Remember to define the methods equals (and hashcode) to use correctly a Set because they are used internally by the Set methods.


Q:

Python - Row calculation using Pandas

I am working on large table using python (using pandas library).
I would like to perform various kind of vector operations such as Correlation with each rows of the table.
It might be a simple problem, but for me it is difficult to deal with the DataFrame structure. I do not have a good idea about how to convert each row (or column) into lists (or numpy arrays).
Even counting the number of rows does not seem to be a simple problem, because function like df.count() seems to ignore null data.
Simple data table and the expected result table are like below. In this case, I would like to calculate sum of each row pairs.
The size of real table is much bigger (more than 1000 rows and columns) and contains some null values.

Data.csv:
Label Col1 Col2
Row1 1 2
Row2 3 4
Row3 5 6

Output.csv:
Label Col3
Row1,Row2 4,6
Row1,Row3 6,8
Row2,Row3 8,10

A:

Pandas is a lot faster and more natural when working with columns. Thus, I would propose to transpose DF first, and then just sum columns
Link: Invert index and columns in a pandas DataFrame


Q:

Azure table storage and caching

Is it worth caching data from Azure Table storage with the Azure Caching Preview?
Or is the table storage fast enough in large scale applications?
Thanks

A:

The short answer is it depends.  In the application I am currently working on there is some information that we use caching for to handle both the latency of retrieving data from Table Storage and to accommodate the desired number of transactions per second.
We started out serving the information from Table Storage and moved to caching only when our performance requirements dictated it.  I'd recommend a similar approach: make it work, then make it fast.

A:

In addition to what Robert said, you should also consider following points:
Windows Azure Table Storage allows to store up to 100TB in size (in chunks). At first glance, that size of data may seem overwhelming. However, Table Storage can be partitioned.  Each partition of Table Storage can be moved to a separate server by the Azure controller thereby reducing the load on any single server and improving performance.
If you have very high load on your application, you cache with frequent inserts will approach the maximum cache size very quickly and then cache items eviction process starts. In most cases frequent inserts into cache and frequent cache items eviction processes end up with performance degradation instead of improvement. Then you would need to increase cache maximum size, which in turn will affect your application cost (sometimes this might be a blocker).
Last but not least, you can access Windows Azure Table Storage data using the OData protocol and LINQ queries with WCF Data Service .NET Libraries; you do not have that ability with Azure Cache.
Please bear in mind that those points may or may not be valid in your case. All depends on your system architecture; expected load etc.
I hope my answer will help you in making good system architecture decisions.


Q:

How to prevent dead-code removal of utility libraries in Haxe?

I've been tasked with creating conformance tests of user input, the task if fairly tricky and we need very high levels of reliability.  The server runs on PHP, the client runs on JS, and I thought Haxe might reduce duplicative work.
However, I'm having trouble with deadcode removal.  Since I am just creating helper functions (utilObject.isMeaningOfLife(42)) I don't have a main program that calls each one.  I tried adding @:keep: to a utility class, but it was cut out anyway.
I tried to specify that utility class through the -main switch, but I had to add a dummy main() method and this doesn't scale beyond that single class.

A:

You can force the inclusion of all the files defined in a given package and its sub packages to be included in the build using a compiler argument.
haxe --macro include('my.package') ..etc
This is a shortcut to the macro.Compiler.include function.
As you can see the signature of this function allows you to do it recursive and also exclude packages.
static include (pack:String, rec:Bool = true, ?ignore:Array<String>, ?classPaths:Array<String>):Void

I think you don't have to use @:keep in that case for each library class.
I'm not sure if this is what you are looking for, I hope it helps.
Otherwise this could be helpful checks:

Is it bad that the code is cut away if you don't use it?
It could also be the case some code is inlined in the final output?
Compile your code using the compiler flag -dce std as mentioned in comments.
If you use the static analyzer, don't use it.
Add @:keep and reference the class+function somewhere.
Otherwise provide minimal setup if you can reproduce.


Q:

What's inside the stack?

If I run a program, just like
#include <stdio.h>
int main(int argc, char *argv[], char *env[]) {
  printf("My references are at %p, %p, %p\n", &argc, &argv, &env);
}

We can see that those regions are actually in the stack.
But what else is there? If we ran a loop through all the values in Linux 3.5.3 (for example, until segfault) we can see some weird numbers, and kind of two regions, separated by a bunch of zeros, maybe to try to prevent overwriting the environment variables accidentally.
Anyway, in the first region there must be a lot of numbers, such as all the frames for each function call.
How could we distinguish the end of each frame, where the parameters are, where the canary if the compiler added one, return address, CPU status and such?

A:

Without some knowledge of the overlay, you only see bits, or numbers.  While some of the regions are subject to machine specifics, a large number of the details are pretty standard.
If you didn't move too far outside of a nested routine, you are probably looking at the call stack portion of memory.  With some generally considered "unsafe" C, you can write up fun functions that access function variables a few "calls" above, even if those variables were not "passed" to the function as written in the source code.
The call stack is a good place to start, as 3rd party libraries must be callable by programs that aren't even written yet.  As such, it is fairly standardized.
Stepping outside of your process memory boundaries will give you the dreaded Segmentation violation, as memory fencing will detect an attempt to access non-authorized memory by the process.  Malloc does a little more than "just" return a pointer, on systems with memory segmentation features, it also "marks" the memory accessible to that process and checks all memory accesses that the process assignments are not being violated.
If you keep following this path, sooner or later, you'll get an interest in either the kernel or the object format.  It's much easier to investigate one way of how things are done with Linux, where the source code is available.  Having the source code allows you to not reverse-engineer the data structures by looking at their binaries.  When starting out, the hard part will be learning how to find the right headers.  Later it will be learning how to poke around and possibly change stuff that under non-tinkering conditions you probably shouldn't be changing.
PS. You might consider this memory "the stack" but after a while, you'll see that really it's just a large slab of accessible memory, with one portion of it being considered the stack...

A:

The contents of the stack are basically:

Whatever the OS passes to the program.
Call frames (also called stack frames, activation areas, ...)

What does the OS pass to the program? A typical *nix will pass the environment, arguments to the program, possibly some auxiliary information, and pointers to them to be passed to main().
In Linux, you'll see:

a NULL
the filename for the program.
environment strings
argument strings (including argv[0])
padding full of zeros
the auxv array, used to pass information from the kernel to the program
pointers to environment strings, ended by a NULL pointer
pointers to argument strings, ended by a NULL pointer
argc

Then, below that are stack frames, which contain:

arguments
the return address
possibly the old value of the frame pointer
possibly a canary
local variables
some padding, for alignment purposes

How do you know which is which in each stack frame? The compiler knows, so it just treats its location in the stack frame appropriately. Debuggers can use annotations for each function in the form of debug info, if available. Otherwise, if there is a frame pointer, you can identify things relative to it: local variables are below the frame pointer, arguments are above the stack pointer. Otherwise, you must use heuristics, things that look like code addresses are probably code addresses, but sometimes this results in incorrect and annoying stack traces.

A:

The content of the stack will vary depending on the architecture ABI, the compiler, and probably various compiler settings and options.
A good place to start is the published ABI for your target architecture, then check that your particular compiler conforms to that standard.  Ultimately you could analyse the assembler output of the compiler or observe the instruction level operation in your debugger.
Remember also that a compiler need not initialise the stack, and will certainly not "clear it down", when it has finished with it, so when it is allocated to a process or thread, it might contain any value - even at power-on, SDRAM for example will not contain any specific or predictable value, if the physical RAM address has been previously used by another process since power on or even an earlier called function in the same process, the content will have whatever that process left in it.  So just looking at the raw stack does not tell you much.
Commonly a generic stack frame may contain the address that control will jump to when the function returns, the values of all the parameters passed, and the value of all auto local variables in the function.  However the ARM ABI for example passes the first four arguments to a function in registers R0 to R3, and holds the return value of the leaf function in the LR register, so it is not as simple in all cases as the "typical" implementation I have suggested.


Q:

Is there a way to check if the script is running by PowerShell ISE?

I want to skip the Start-Transcript, Stop-Transcript lines if the PowerShell script is running by Powersehll ISE.
Is this possible? And how can I achieve this?

A:

You can do:
if ($host.name -eq 'ConsoleHost') # or -notmatch 'ISE'
{
  .. do something ..
}
else
{
  .. do something else..
}

A:

Know this was asked quite a while ago, and already marked as answered, but one more way:
function Test-IsISE {
# try...catch accounts for:
# Set-StrictMode -Version latest
    try {
        return $psISE -ne $null;
    }
    catch {
        return $false;
    }
}

$psISE is available in ISE:
http://technet.microsoft.com/en-us/library/dd819500.aspx

A:

Here's a method that looks for the existance of $psISE without generating exceptions:
if (Test-Path variable:global:psISE)
{
...
}


Q:

Can urgent pointer in TCP increase communication speed?

TCP has a field called Urgent Pointer.
From RFC 793, about urgent pointer:

This field communicates the current value of the urgent pointer as a positive offset from the sequence number in this segment. The urgent pointer points to the sequence number of the octet following the urgent data. This field is only be interpreted in segments with the URG control bit set.

Let's say I want to upload a file to a remote server that is handling multiple requests from multiple clients.
Can setting this flag improve the total perfromance of the transmission: speed, goodput, time?
If the above example is not suitable, in what scenario can urgent pointer improve performance?

A:

The urgent pointer is just a marker that this packet contains information which should be processed with urgency by the end application. It does not cause any faster delivery in the network and thus it does not improve network performance. The only performance it improves is how fast the application might react to user activity in that it can process OOB data  (like a Control-S, i.e. stop terminal output) before processing all the preceding data (like terminal output).


Q:

got stuck in recursion return value

I have written a small recursive function to find the level of menuItem.
Here is the function:
const getSelectedMenuItemLevel = (menuItems, path, level = 0) => menuItems.forEach((menuItem) => {
  console.log(menuItem.path, path, menuItem.path === path, level);
  if (menuItem.path === path) {
    return level;
  }
  return getSelectedMenuItemLevel(menuItem.children, path, level + 1);
});

This is how I call it:
console.log(getSelectedMenuItemLevel(menuItems, 'two/three'));

Here is the menuItems Array:
[
  {
    path: 'one',
    name: 'One',
    children: [
      { path: 'one/one', name: 'One/One', children: [] },
      { path: 'one/two', name: 'One/Two', children: [] },
    ],
  },
  {
    path: 'two',
    name: 'Two',
    children: [
      { path: 'two/one', name: 'Two/One', children: [] },
      { path: 'two/two', name: 'Two/Two', children: [] },
      { path: 'two/three', name: 'Two/Three', children: [] },
    ],
  },
{
    path: 'three',
    name: 'Three',
    children: [],
  }
]

This recursive function always returns me undefined. I expect it to return level

A:

You need a variable in the function and store it by checking the iteration for a found level with Array#some, bedcause this method uses a short circuit if a valid level is found.
Basically you need to extend the wanted return values to undefined or to a numerical value.

const getSelectedMenuItemLevel = (menuItems, path, level = 0) => {
    let value;
    menuItems.some((menuItem) => {
        if (menuItem.path === path) {
            value = level;
            return true;
        }
        const temp = getSelectedMenuItemLevel(menuItem.children, path, level + 1);
        if (temp) {
            value = temp;
            return true;
        }
      return false;
    });
    return value;
};

var menuItems = [
  {
    path: 'one',
    name: 'One',
    children: [
      { path: 'one/one', name: 'One/One', children: [] },
      { path: 'one/two', name: 'One/Two', children: [] },
    ],
  },
  {
    path: 'two',
    name: 'Two',
    children: [
      { path: 'two/one', name: 'Two/One', children: [] },
      { path: 'two/two', name: 'Two/Two', children: [] },
      { path: 'two/three', name: 'Two/Three', children: [] },
    ],
  },
{
    path: 'three',
    name: 'Three',
    children: [],
  }
];

console.log(getSelectedMenuItemLevel(menuItems, 'two/three'));


Q:

500 (Internal Server Error) ASP.Net MVC 5 c#

I keep getting the error 500 (Internal Server Error) when I'm trying to save an object. I can't seem to find any way to even check what the exact error might be.
I'm trying to save an object through an API controller and then return the object when complete. I can return a string and the error goes away, which I'm sure I could figure out a way to make that work for me, but that just seems like a dirty way to fix a simple issue.
The object saves just fine, it just keeps throwing that error after it runs through my controller.
This is my API call:
self.postCategory = function (data) {
return $.ajax({
    url: '/API/Category/',
    type: 'POST',
    dataType: 'json',
    data: ko.toJSON(data),
    contentType: 'application/json; charset=urf-8',
    success: function (data) {
        self.getAlert('sucessfully saved category', 1);
        self.Category(data);
    },
    error: function (error) {
        self.getAlert(error, 4);
    }
});
}

This is the controller to handle the call:
public Category Post([FromBody]Category category)
{
using (MyContainer db = new MyContainer())
{
    if (db.Categories.Where(n => n.Id == category.Id).Any())
    {
        db.Categories.Attach(category);
        db.Entry<Category>(category).State = EntityState.Modified;
    }
    else
    {
        db.Categories.Add(category);
    }
    try
    {
        db.SaveChanges();
        return category;
    }
    catch (Exception e)
    {
        Elmah.ErrorSignal.FromCurrentContext().Raise(e);
        return new Category();
    }
}
}

This seems to only happen to categories with records related to it in a one-to-many relationship. New categories or updates to categories without related records do not have the same issue.
It just doesn't make sense to me anymore.
Any help would be greatly appreciated!
Thank you!

A:

The problem was with my knockout binding.
This:
function CategoryModel(data) {
    var self = this;

    self.Id = data.Id;
    self.Name = ko.observable(data.Name);

    self.Products = ko.observableArray([]);
}

Should have been this:
function CategoryModel(data) {
    var self = this;

    self.Id = data.Id;
    self.Name = ko.observable(data.Name);

    self.ProductModels = ko.observableArray([]);
}

In my .edmx I was naming the associations between my entities as Products and Category by default. Then when I made the call it would send the category with the products, make the update to the category, then return the category with complex objects. Which is bad for webapi, and hence the 500 error.
Solution: Name your observableArray literally ANYTHING other than the same name as the association.
Thanks for the help!


Q:

Using MVVM, how can I implement INotifyPropertyChanged on a predefined collection of objects?

I think this question could of already been answered, which if this is the case I will delete immediately. I'm new to WPF (and new to C# really) and I'm trying as hard as possible to follow MVVM but I'm really struggling with finding a way to NOT implement INotifyPropertyChanged on my Model.
My Model contains a collection of predefined objects which are created from another reference. Within the Model, I have properties which are updated as and when the Task is completed.
CustomObject - API
public class CustomObject
{
  private string _myTaskOutput;

  public CustomObject()
  {
     _myTaskOutput = MyTaskMethod();
  }

   //MyTaskMethod()

  //Get & Setter for _myTaskOutput;
}

Util - API
 public static class Util
 {
     public IEnumerable<CustomObject> GenerateObjects()
     {
         var customObjectCollection = SomeHelperMethod();
         return customObjectCollection;
     }
 }

Model
   public class CustomObjectCollectionModel
   {
     private IEnumerable<CustomObject> _customObjectCollection;

     public CustomObjectCollectionModel()
     {
         _customObjectCollection = Util.GenerateObjects();
     }

     //Get & Setter for IEnumerable<CustomObject>
   }

The object reference does not change so I believe having an ObservableCollection is out of the question (is this correct?) and implementing INotifyPropertyChanged on CustomObject works as intended but I understand this not the correct way of doing things.

A:

If CustomObject is some kind of domain or business object, you could wrap it in a view model class in your client application. So instead of binding to an ObservableCollection<CustomObject> you bind to an ObservableCollection<CustomObjectWrapper> where CustomObjectWrapper is a client-specific class that implements the INotifyPropertyChanged interface (provided that you actually need to provide change notifications in your UI).
You will indeed have to create a CustomObjectWrapper for each CustomObject that you receive from your service API - you could do this in your view model class - but at the same time you don't have to pollute your business objects with client-specific code. Binding directly to domain-specific business objects is rarely useful.


Q:

How to convert Dates stored to millisecond in mongoDB

I know there are many examples relating this topic, but almost all are relating new dates or ISODATE() inputs and my problem is wuite different.
I have an existing database in mongoDB, and I'm trying to subtract two dates or convert those dates in millisecond and subtract them. I'm doing this project:
{$project:{
    _id:0,
    'CrtDat':1,
    'CloDat':1,
    "CrtMs": { $millisecond: "$CrtDat" },
    "CloMs": { $millisecond: "$CloDat" },
    "TotalTime": {$subtract: ["$CloMs", "$CrtMs"] }
}},

My complete document query:
db.tickets.aggregate([
{$match:{
    'Nms.Org': 'Org',
    'Nms.Cmp':'Company'
    }},
{$project:{
    _id:0,
    'CrtDat':1,
    'CloDat':1,
    'Nms.Org':1,
    'Nms.Cmp':1,

    }},

    {$group:
    {_id:{
            Org:'$Nms.Org',
            Cmp:'$Nms.Cmp',
            CrtDate:'$CrtDat',
            CloDate:'$CloDat'
            },
            Total_Closed:{$sum:1}
        },

    },
    { $project : {
        Total_Closed : 1

  }},

])
Apparently I would be able to see in TotalTime: CloMS-CrtMS in milliseconds but robomongo retrieving me the following error message:
Error("Printing Stack Trace")@:0
()@src/mongo/shell/utils.js:37
([object Array])@src/mongo/shell/collection.js:866
@(shell):90

uncaught exception: aggregate failed: {
    "errmsg" : "exception: can't convert from BSON type NULL to Date",
    "code" : 16006,
    "ok" : 0
}

Seems that my dates CrtDat and CloDat are NULL but if I do a db.tickets.findOne() (my collection is called tickets) I can see both dates likes this:
Key                     Value                             Type
----------------------------------------------------------------
CrtDat                  2015-05-01 03:36:42.000Z          Date
CloDat                  2015-05-07 09:52:35.000Z          Date

My output:
{
    "_id" : {
        "Org" : "Org",
        "Cmp" : "Company",
        "Wkg" : "Wkg",
        "CurEntNme" : "Entity",
        "CurTskId" : 1,
        "DueDate" : ISODate("2014-11-12T16:01:54.000Z"),
        "CrtDate" : ISODate("2014-11-10T22:01:50.000Z"),
        "CloDate" : ISODate("2014-11-19T00:15:49.000Z")
    },
    "Total_Closed" : 1
}

Anybody can help me, please?
Thanks in advance.

A:

You could try converting the datetime fields to a timestamp by using the $mod and $subtract operators in your $project pipeline.
Suppose your minimum test case is as follows:
db.test.insert(
    {
        CrtDat: ISODate("2015-05-01T03:36:42.962Z"),
        CloDat: ISODate("2015-05-07T09:52:35.517Z")
    }
)

The following aggregation pipeline will give you the difference in milliseconds between the two datetime fields:
db.test.aggregate([
    {
        "$project": {
            "_id": 0,
            'CrtDat':1,
            'CloDat':1,
            "TotalTime": {
                "$subtract": [
                    {
                        "$subtract": [ "$CloDat", new Date(0) ]
                    },
                    {
                        "$subtract": [ "$CrtDat", new Date(0) ]
                    }
                ]
            },
            "TestTotalTime": {
                "$subtract": [
                    {
                        "$subtract": [
                            {
                                "$subtract": [ "$CloDat", new Date(0) ]
                            },
                            {
                                "$mod": [
                                    { "$subtract": [ "$CloDat", new Date(0) ] },
                                    5 * 60 * 1000
                                ]
                            }
                        ]
                    },
                    {
                        "$subtract": [
                            {
                                "$subtract": [ "$CrtDat", new Date(0) ]
                            },
                            {
                                "$mod": [
                                    { "$subtract": [ "$CrtDat", new Date(0) ] },
                                    5 * 60 * 1000
                                ]
                            }
                        ]
                    }
                ]
            }
        }
    }
])

Sample Output:
/* 0 */
{
    "result" : [
        {
            "CrtDat" : ISODate("2015-05-01T03:36:42.962Z"),
            "CloDat" : ISODate("2015-05-07T09:52:35.517Z"),
            "TotalTime" : 540952555,
            "TestTotalTime" : 540900000
        }
    ],
    "ok" : 1
}

For more examples, refer to the manual on the sections Subtract Two Dates and Subtract Milliseconds from a Date.


Q:

why does "1 ? (int*)1 : ((void*)((x) * 0l))" work correctly?

I have been following the C language hack for detecting integer constant expressions using Macros - Idea by Martin Uecker.
https://lkml.org/lkml/2018/3/20/805
When I started playing around with the code, I found a weird behavior by interchanging the expressions of the ternary operator.
See the below code,
#include <stdio.h>
#include <stdlib.h>

// https://lkml.org/lkml/2018/3/20/805
#define ICE_P(x) (sizeof(int) == sizeof(*(1 ? ((void*)((x) * 0l)) : (int*)1)))
//Why is this working?
#define ICE_P2(x) (sizeof(int) == sizeof(*(1 ? (int*)1 : ((void*)((x) * 0l)))))

int main() {

    int a = 5;
    int b = ICE_P(a);
    int c = ICE_P2(a);

    int d = ICE_P(5);
    int e = ICE_P2(5);
    return 0;
}

ICE_P(x) works perfectly, as described in the above link. However, when I interchanged the left and right expressions of the ternary operator, the program is still behaving as the same which I was not expecting.
When ICE_P2 is called, 1 ? (int*)1 : ((void*)((x) * 0l)) will be evaluated.

Scenario with Correct behavior.

ICE_P2(5) - (void*)((5)*0l)) will be NULL

According to the standard, if one side of the ternary operator gets evaluated to 'NULL' then irrespective of the conditional expression the value other than NULL will be returned.
So, in this case always, (sizeof(int) == sizeof(int*)) will be evaluated and the result will be 1.
Scenario with the behavior I'm not understanding.

ICE_P2(a) - (void*)((a)*0l)) will not be NULL

My expectation:

Now, 1 ? (int*)1 : (void*)(<Not NULL>) should be evaluated to (int*)1 as 1 is always true.
Overall expression macro will be evaluated as (sizeof(int) == sizeof(*(int*)))
And the result is 1.

Actual:

Now, 1 ? (int*)1 : (void*)(<Not NULL>) is evaluating the value as (void*)(<Not NULL>).
Overall expression macro will be evaluated as (sizeof(int) == sizeof(void*))
And the result is 0.

For more understanding on the ICE_P refer to the stackoverflow question or this reddit post.

A:

So let's get through the standard. C11 6.3.2.3p3

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. [...]

In the construct (void*)((x) * 0l), the value is clearly always 0 for any integral value, therefore it always results in a null pointer given any kind of integer value on most platforms, but to a null-pointer constant iff the x is an integer constant expression.
Now, the question is why does x ? (void *)0 : (int *)1 work the same as x ? (int *)1 : (void *)0 when wrapped in sizeof(* (...)). For that we need to read 6.5.11p6:

If both the second and third operands are pointers or one is a null pointer constant and the other is a pointer, the result type is a pointer to a type qualified with all the type qualifiers of the types referenced by both operands. Furthermore, if both operands are pointers to compatible types or to differently qualified versions of compatible types, the result type is a pointer to an appropriately qualified version of the composite type; if one operand is a null pointer constant, the result has the type of the other operand; otherwise, one operand is a pointer to void or a qualified version of void, in which case the result type is a pointer to an appropriately qualified version of void.

So if either the 2nd or 3rd expession is a null pointer constant, the result of the conditional operator has the type of the other expression, i.e. both x ? (void *)0 : (int *)1 and x ? (int*)1 : (void *)0 have type int *!
And in other case, i.e. x ? (void *)non_constant : (int *)1 the latter part of the bolded text says that the type of that expression must be void *.
The type is completely decided during the compilation phase, based on the types of the second and the third operands; and the value of the first operand plays no role in it. If this is then used in a sizeof then the entire expression becomes just another integer constant expression.

Then comes the dubious part: sizeof(* ...). The pointer is "dereferenced", and the sizeof of the dereferenced value is used in calculations. ISO C does not allow the evaluation of sizeof(void) -actually, it doesn't even allow the dereference of a void * - but GCC defines it as sizeof(void).
As Linus said: "That is either genius, or a seriously diseased mind. - I can't quite tell which."

By the way, for many similar uses, the GCC builtin __builtin_constant_p would be sufficient - but while it would return 1 for all integer constant expressions, it would return 1 for any other lvalues for which the optimizer can substitute a constant in code; the difference being that only constant integer expressions can be used as for example as non-VLA array dimensions, in static initializers and as bitfield widths.


Q:

Using self->ivar when accessing instance variables directly

I have noticed that most Objective-C coders never use the self->ivar syntax when accessing instance variables directly. Most sample code that I see simply references the instance variable without self->. I think that it is rather confusing to reference an instance variable without making clear that it is an instance variable and not simply a variable of the current scope.
I feel like I want to write stuff like:
- (void)dealloc {
    [self->someVar release];
    [self->anotherVar release];
    [super dealloc];
}

or
- (void)setVar:(Foo *)newVar {
    [self->var autorelease];
    self->var = [newVar retain];
}

There aren't a whole lot of occasions when we ever even should access our instance variables without using an accessor for encapsulation, but sometimes we need to such as in dealloc, or in custom getters and setters.
Am I a bad person/programmer for doing this? Is there some really good reason for not writing code like this? Because it feels really good to do it this way.

A:

There's no reason you shouldn't write it that way. I think people tend to write it the other way because they try to avoid shadowing their ivars anyway, so there shouldn't be any ambiguity in what variable they're talking about — and it's shorter.

A:

Chuck is correct in that there's no technical reason you shouldn't write it that way, unless you're shadowing ivars with local variables, which is is generally a bad idea. However, it's arguable that omitting self-> is stylistically cleaner, and it certainly results in less verbose code. Personally I would find the self-> to be distracting (especially if the code is well-designed and variables are well-named) but if it makes things more understandable for you, by all means do it. Just be aware that if you show your code to other Objective-C programmers, they're likely to have a conflicting opinion, so it's good to have a think skin. Besides, most programmers find that their perception of what makes code "feel good" changes over time and with experience, and those opinions often mellow out with age. :-)

A:

Short answer: No, you are not a bad programmer because of that :) There is also no good reason for not writing code this way; most programmers are simply lazy or never really have written an exhausting method in their whole life.
Long answer: Technically when you access a variable without "self->", the compiler will first for a variable of that name in the local scope and if it cannot find one, it will repeat that search with instance variables. If it finds a hit there, it will actually generate code as if "self->..." had been written there. If there was no match for instance variables either, the compiler would try within global scope, BTW.
Most programmers only read their own code and they know pretty well what is an instance variable and what not. Once you ever had to work with code you have not written yourself, where the method is 4 screen pages long (and I have a bigg screen), you are really thankful when the programmer made it absolutely clear on every variable access: Is that variable a parameter fed to the method call, a local variable of this method, an instance variable of the object or possibly a global variable (only global to all instances of this class or possibly application global). You are thankful, because if there are just a bunch of variables with similar name and with no special naming or access pattern, however all of different type, you pretty quickly lose oversight. And relying on the fact that Xcode syntax highlighting highlights instance variables in a different way than local variables is also stupid, because no programmer is forced to edit code in Xcode to begin with and even if he does, he may have a color scheme where instance variables are the same color as local ones.
Accessing instance variables via self-> is perfectly fine, but consider also a to maybe use a prefix/suffix, which will also make obvious those are instance variables and also avoid naming conflicts with method parameters or local variables.


Q:

Now() function with time trim

So the function =Now()....is there a way I can use this and only get the date, not the time?
or is there just a function for this idea?

A:

There is a Date function.

A:

Dates in VBA are just floating point numbers, where the integer part represents the date and the fraction part represents the time. So in addition to using the Date function as tlayton says (to get the current date) you can also cast a date value to a integer to get the date-part from an arbitrary date: Int(myDateValue).

A:

DateValue(CStr(Now()))

That's the best I've found. If you have the date as a string already you can just do:
DateValue("12/04/2012 04:56:15")

or
DateValue(*DateStringHere*)

Hope this helps someone...


Q:

Tail recursion in ruby - what's the difference between these two implementations?

I'm new to Ruby and just started to pick up the language a couple of days back. As an exercise, I tried to implement a simple quicksort
class Sort
  def swap(i,j)
    @data[i], @data[j] = @data[j], @data[i]
  end

  def quicksort(lower=0, upper = @data.length - 1)
    return nil if lower >= upper
    m = lower
    i = 0
    ((lower+1)..upper).each do |i|
      swap(++m, i) if @data[i] < @data[lower]
    end

    swap(m, lower)

    quicksort1(lower, m -1)
    quicksort1(m+1, upper)
  end
end

Calling quicksort on say 10000 integers gives me a stack-level error. After googling, I figured out that tail-recursion isn't supported yet in Ruby (kind of). But then I found the following snippet (from here)
def qs(v)
  return v if v.nil? or v.length <= 1
  less, more = v[1..-1].partition { |i| i < v[0] }
  qs(less) + [v[0]] + qs(more)
end

Running the second snippet works perfectly well even with a million integers. Yet, as far as I can tell, there's tail recursion at the end. So what am I not understanding here?

A:

Neither of the methods you've shown are tail recursive (well technically the first one is half tail-recursive: the second recursive call is a tail call, but the first one is not - the second method is not tail recursive at all).
The reason that the first method overflows the stack, but the second one does not is that the first method recurses much deeper than the second (linearly instead of logarithmically) because of a bug (++m just applies the unary + operator to m twice - it does not actually do anything to m).
When given a large enough array both versions will overflow (and would do so even if ruby did perform TCO), but without the bug 10000 elements is not nearly large enough.


Q:

bind JSON properties to a form

I have a JSON object and a <form>. If the JSON object has a property whose name matches the name of a form <input> I want the input to display the value of this property. Is there a simple way to do this with JQuery?
var json = {foo: 'foo', bar: 'bar};
def form = $('#myform');

// something magical that assigns JSON property values to form inputs with matching names

The form in question looks something like:
<form id = "#myform" action="/foo/bar/">
  <input name="foo"/>
  <input name="bar"/>
</form>

A:

You can run a loop that will search the elment and put the value:
$.each(json, function(key, value) {
    form.find("input[name='" + key + "']").val(value);
});

and for the form:
<form id="myform">
    <input type="text" name="foo" />
    <input type="text" name="other" />
</form>

using .field instead of input is to work with textarea and select


Q:

Quine Program Example in C

In my course slides, I have this example but without much explanation:
char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c";main(){printf(f,34,f,34,10);}

I understand what quine programs in general mean but I do not quite understand what's happening in the code above. This is the output I get if I run it:
char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c";main(){printf(f,34,f,34,10);}

But how is it reproducing its own code? I don't really understand how the output is produced.

A:

Start by writing it out in a way that'll be clearer (not changing anything but the layout):
char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c";

main()
{
    printf(f,34,f,34,10);
}

So we see a main function as we'd expect (it should return an int but you're allowed to get away with not in C; likewise for no function arguments).
And before that, a regular string.  It's a funny-looking string, but it is not really that different to char*f="fish";.
Okay, so what if we expand the printf by putting the string in there by hand?
printf("char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c" ,34,f,34,10);

We can see that it's going to print out some guff, and substitute in some values along the way.  They are:
 First %c : 34   (the ASCII code for " (quotes))
 First %s : 'f'  (our string, once again)
Second %c : 34   (" again)
 Third %c : 10   (the ASCII code for Newline)

Let's substitute those all in then too (though I've replaced the contents of the string with <the string>, and "'s with \"'s to make it actually work as a standalone statement):
main()
{
    printf("char*f=\"<the string>\";main(){printf(f,34,f,34,10);}\n");
}

Well look at that!  main simply prints out the line we first started with.  Hurrah!

Edited to add:
Although I've basically spelled out the answer for you, there is still a puzzle remaining.  Consider for yourself why we bother substituting in the 34, f, 34, 10, rather than just putting them directly into the string like I did in my final code.


Q:

Free database of Google word frequencies?

On the Stackoverflow podcast this week, Jeff mentioned that in 2004 he wrote a script which queried Google with 110,000 English words and collected a database containing the number of hits for each word. They use this on Stackoverflow e.g. for the "Related" list on the right-hand side of each question page.
Since creating one of these today with a similar script would be difficult (as Joel mentioned, "at 30,000 words you get a knock at your door"), I was wondering if anyone knows of a more up-to-date, free database of Google word frequencies (e.g. for IT words which have surely changed since then such as jquery, ruby, azure, etc.).

A:

A quick Google search(!) turns up a few hits. This link looks promising:
But it's not targeted at IT words.

A:

It maybe late to answer this but I can propose you different way.
Instead of getting "number of hits" from Google to compute some approximation of it by yourself. Get big collection of text pages (Corpus) and count the number of each word in it.
I have done this with the Wikipedia. There is a dump of all wiki pages. You just need to write a parser to extract text and to count words. The result is a list of more then 110K words (at least 2M-3M).
If you really need numbers in Google search result you can get some sample of words and query Google and then make some normalization of computed values to match the Google values.
I hope this helps.