Q:

Google Cloud VM IIS hosted site DNS setup

I've been running through the google cloud instructional to setup DNS on a custom website but I can't get it to work. Google cloud doco suggests posting on this forum so I'll outline what I've done and hopefully someone can assist, I haven't needed to expose a website before, hopefully I'm missing something simple.
Instructional I followed: https://cloud.google.com/compute/docs/tutorials/setting-up-dns
What I have done:

Google Cloud VM IIS website works on localhost (via RDP session)
Google Cloud website works by IP address from my desktop at home
Google cloud IP address has been made static
GoDaddy nameservers have been updated to point to google cloud
-ns-cloud-d1.googledomains.com.
-ns-cloud-d2.googledomains.com.
-ns-cloud-d3.googledomains.com.
-ns-cloud-d4.googledomains.com.
Google cloud - I have created a zone for my .com
Google cloud - I have 3 record sets under my zone
-mydomain.com - NS (this was there by default)
-mydomain.com - SOA (this was there by default)
-www.mydomain.com - CNAME

What else do I need to do?

A:

You need to add an A record in the Cloud DNS to point to your VM's IP address. You can have more information in this article.


Q:

Shoe covers (or other tricks) for commuting in shorts

I commute to work by bike, very often in casual shorts and waterproof North Face sneakers. Provided I don't want to change my clothes (in particular I don't want to get SPD etc.), is there a good way to keep my feet dry when it's raining?
In particular, would shoe covers be of any help? My impression is that most of the rain gets into my sneakers by streaming down along my ankles/socks, which is why I have doubts if shoes covers would be of any help when I cycle in shorts (but I've never really used them so please correct me if I'm wrong).
In case it's of any importance - if I wear the same clothes and just go for a walk/jog, then my feet stay dry for much longer. Ideal solution would allow my feet to stay dry for a similar amount of time when I cycle.

A:

if I wear the same clothes and just go for a walk/jog, then my feet stay dry for much longer

Do you have mudguards (fenders) on your bike? If not your feet are in the spray from the front wheel and will get wet unless you wear over-boots. Or gumboots.
For cycling when the roads are wet mudguards make a huge different to your comfort. You'll stay dryer because the rain will only hit you from above, rather than spraying up from your wheels as well.
Gary.Ray's answer deals well with the actual shoe cover question. What I would add is that plastic bags and rubber bands work well as a short-term solution for one trip, but they don't last long. But that might help you decide whether shoe covers are worth having at all.

A:

The main thing that would determine whether or not a particular brand or style of shoe cover will help would be the closure around your ankle, above the top of the shoe.
A standard, non-cycling over-shoe or shoe cover like those made by Totes and other manufacturers will usually cover most of the shoe, but the opening is wide and water will run down your leg into the shoe.
A cycling specific shoe cover will usually have some kind of opening in the back that zips closed. When you place your foot into the cover it zips partly up your leg and will stop most of the water from running into your shoe. I personally use neoprene covers, but covers of other materials may work just find as long as they close relatively tightly against your leg. If the closure is not quite tight enough, wearing an old-fashioned terry cloth sweat wrist band above your ankle and under the shoe cover would help absorb any water that leaks in. I have a set of 2" wide reflective bands with a terry cloth backing that I occasionally overlapping the top edge of mine if I think the rain will be torrential.
Since you are wearing a shoe that is not cycling specific, you will likely want to visit your local bike shop or outdoor retailer to try the covers on. If you buy online based on the size of your shoe you will likely want to order a size up at least to account for the additional sole support and padding in a normal shoe.

A:

I used to ride in almost exactly the same gear as you (gym shorts rather than casual shorts), so I know where you're coming from.
The mudguards (US: fenders) help a little, but not if it's actually raining while you're riding, as you basically ride into the rain drops.
It's not the shorts, cycling tights/running leggings will do the same.  Even waterproof overtrousers are of limited help as the headwind from riding tends to push them against your shin.  And you get so hot you'll be almost as wet from sweat ("breathable" kit  doesn't work too well with a film of wtare on the outside while you're actively sweating ).  I haven't tried shoe covers but would only consider them in the winter -- in summer (even UK summer) I'd rather get rained on than boil.
One thing that I found was that after riding for 40 minutes in waterproof shoes I could at least wring my socks out and sometimes pour the water out (you can't always stop pedalling for puddles, e.g. a little dip on an uphill).  In hot weather (sometimes with sudden downpours) I wore sports sandals, and the water just went straight through and out the other side.  Now I've got SPDs I've got ventilated shoes (even on the sole) and the water can't accumulate.
My suggestion: Go for shoe covers when it's cold, but in warmer weather choose shoes that can't fill up with water (also maybe no socks).  Either way a change of shoes/socks on arrival is probably appropriate, even though you have a .ac.uk homepage listed and can probably wear what you like.


Q:

Am I supposed to do a brew ln after every brew install? (Mac OS Package Manager homebrew)

I'm not sure I'm using the Mac OS brew package manager properly. Packages don't end up in /usr/local unless I follow a
brew install foo

with a
brew ln foo

What makes me suspicious is nearly every quickstart tutorial I see on using brew doesn't indicate that the ln step is required.
Am I missing something?
It's especially annoying when I install something like ffmpeg, that installs a lot of prerequisites. I find myself having to read the log, finding what it installed and manually doing a
brew ln yasm
brew ln videolan
brew ln faac

etc, for each prerequisite installed. I can't believe it's supposed to work this way. What am I doing wrong.

A:

You shouldn't have to; brew ln should be performed automatically after a package is installed.


Q:

Bootstrap Stateful Button on a Input Form Submit

I'd like to use the Stateful functionality of a button in a form's submit button (input). But I can not for the life of me figure out how to accomplish that.
My form executes a php page. I want the button to change during the loading of that php page (depending on content, it could take up to 20 seconds). Is this possible?
http://getbootstrap.com/javascript/#buttons
Sample Code:
<form method='post'>
<input type='text' name='test'></input>
<input type='submit' id='loading-example-btn' value='Submit' data-loading-text="Loading...">
</form>
<script>
  $('#loading-example-btn').click(function () {
    var btn = $(this)
    btn.button('loading')
    $.ajax(...).always(function () {
      btn.button('reset')
    });
  });
</script>

A:

Have you looked for errors in your browser javascript console? As it stands your js is invalid (unless you've abbreviated it?).
Assuming you are not trying to post your form using ajax, just remove the following lines and you should get the behaviour you want:
$.ajax(...).always(function () {
  btn.button('reset')
});

Additionally, this line is invalid HTML as input is a void element and doesn't require the closing </input> tag.
<input type='text' name='test'></input>


Q:

What is an efficient alternative for an extremely large HashMap?

I'm trying to break a symmetric encryption using a 'meet-in-the-middle' attack. For this I need to store 2**32 integer-integer pairs. I'm storing the mapping from a 4-byte cyphertext to a 4-byte key.
At first I tried using an array, but then I realized that you cannot have such a big array in java (the max size is bound by Integer.MAX_VALUE).
Now I'm using a HashMap, but this gets way too slow when the map gets large, even when increasing the max memory to 8GB with -Xmx8192M.
What is an efficient alternative for an extremely large HashMap?
This is the code I'm currently using to populate my hashmap:
HashMap<Integer, Integer> map = new HashMap<>(Integer.MAX_VALUE);
// Loop until integer overflow
for (int k = 1; k != 0; k++)
    map.put(encrypt_left(c, k), k);

I haven't seen this code finish, even after letting it run for hours. Progress logging shows that the first 2**24 values are created in 22s, but then the performance quickly decreases.

A:

I'm storing the mapping from a 4-byte cyphertext to a 4-byte key.

Conveniently, 4 bytes is an int. As you observed, array sizes are limited by Integer.MAX_VALUE. That suggests you can use an array – but there's a minor hangup. Integers are signed, but arrays only permit values >=0.
So you create two arrays: one for the positive cyphertexts, and one for the negative cyphertexts. Then you just need to make sure that you've given the JVM enough heap.
How much heap is that?
4 bytes * Integer.MAX_VALUE * 2 arrays
= 17179869176 bytes
= ~16.0 gigabytes.


Q:

cabal install glib makes error

I tried installing gtk2hs in many ways
but have no luck so far
installation always failed with glib issue
So I tried installing glib first
with cabal install glib
but error arise again
the error is this
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
...
...
...
Registering glib-0.12.0...
Installing library in C:\Documents and Settings\dreambook\Application
Data\cabal\glib-0.12.0\ghc-7.0.3
Registering glib-0.12.0...
setup.exe: internal error: unexpected package db stack: [UserPackageDB]
cabal: Error: some packages failed to install:
glib-0.12.0 failed during the final install step. The exception was:
ExitFailure 1

my enviornment is Windwos xp sp3 on x86 processor
help
thanks

A:

This seems to be a known problem according to google and gtk2hs-trac.
According to the following haskell-ticket try do do the manual install. Either download glib from hackage or look the tar file up in cabal cache. (I don't know by heart where that is on Windows but it should be somewhere near cabal.exe.
After this unzip the package and look for Gtk2HsSetup.hs and change:
#if CABAL_VERSION_CHECK(1,10,0)
                                    installedPkgInfo pkg lbi inplace [packageDb]
#else
                                    installedPkgInfo pkg lbi inplace packageDb
#endif

to
#if CABAL_VERSION_CHECK(1,10,0)
                installedPkgInfo pkg lbi inplace (withPackageDB lbi)
#else
                installedPkgInfo pkg lbi inplace packageDb
#endif

After this run cabal install in the same directory where you found gtk2HsSetup.hs file.


Q:

Get codepoint for a matched character

I want to replace the characters in the range from U+00C0 to U+02AF by their codepoint  with \u… e.g. á -> \u00E1. Is there any sed function for getting the codepoint number for a matched character?

A:

There's no such function in sed. Perl to the rescue:
perl -i~ -CD -pe 's/([\x{c0}-\x{2af}])/sprintf "\\u%04X", ord $1/ge' file.txt

(Works for the input in UTF-8.)
Explanation:

-i~ tells Perl to replace the file in place, leaving a backup.
-CD  tells Perl to assume UTF-8 on input and output.
-p tells perl to process the input line by line, like sed.
s///g is global substitution, like in sed.
the /e option means the replacement should be evaluated, i.e. it's not a string but code whose returned value is used to replace the matching part. The code here takes the ord of the char, i.e. its code, and uses printf to convert it to hex.


Q:

How should my in-major or technical GPA be calculated for my resume?

In my unofficial transcript, all that's listed is my cumulative GPA, semester GPA, transfer GPA, etc.  I often see the recommendation that your resume should contain your in-major or technical GPA, especially if it's better than your cumulative GPA.  I know that my in-major GPA is quite a bit better than my overall GPA, but I'm not entirely sure what classes I should include to calculate it.
I'm a Computer Science major.  Every class in the major is a CS class aside from Calc I, Calc II, and a Logic class.  Should I include these three non-CS (but required) classes when calculating my in-major GPA?  I would like to only include CS classes, but I obviously do not want my calculations to be unethical.
Is there a standard way of calculating this?  Also, what should it be called on my resume?  Should I just label it as my GPA, or should I call it my "technical GPA" or "in-major GPA"?
As always, I greatly appreciate your insight.

A:

The Purpose of the "In-Major GPA"
If you are a CS major applying for a programming job, chances are the employer wants to use your GPA within CS as an indicator of whether or not you'll be able to do the job. If you nailed the pure CS portions, but failed at statistics, that is probably important information to the employer (since a lot of programming requires math). If I'm applying for a job as an economist, and leave off the fact that I can't do simple arithmetic, it has a large impact on my ability to be an effective economist.
So the employer is (probably) expecting that while you'll try to make yourself look good, you will be giving them a good representation of your ability to do that type of work.
Think About the Consequences
So let's say I have the following grades:

CS 101: 3.5
CS 201: 3.5
CS 301: 3.5
CS 401: 3.5
Math 101: 2.0
Math 201: 2.0

They are all requirements for my major (they are assumed by the school to be important in having a well-rounded CS education). I have two choices:

List my in-major GPA as 3.5 (leaving out the math)
List my in-major GPA as 3.0 (including the math)

Obviously listing the 3.5 will make me look better, but is it worth the risk?
Let's say my overall GPA is even worse (2.7, let's say) on my transcript. Any employer is going to notice there's probably something fishy going on. How did I get a 3.5 in my major (which is the bulk of my classes) while only managing a 2.7 overall?
If you'd be embarrassed to answer a reasonable question about the disparity, then you're better off not listing it in a 'creatively positive' manner.
Your Resume Shouldn't Focus on Your GPA
Your resume is supposed to sell you as an individual. If the difference between success and failure is a few tenths of a point in GPA within your major, then your chances are likely bleak. List your GPA in a way that makes you comfortable (that you can explain when asked by someone with access to your full transcript), and then focus on making the resume and cover letter bang-on for the job you're applying to.

A:

Is there a standard way of calculating this? Also, what should it be called on my resume? Should I just label it as my GPA, or should I call it my "technical GPA" or "in-major GPA"?

This is simple. Is it a required class for your major? Yes? Then it's part of your major. Your degree program requires you to take those specific classes. How are they not part of your major?
If you have something different you could use, such as a "CS Core" or something like this (my degree had a "core" which included mostly just classes directly related to my major, electives were outside this core), that might be different.
You are asking for problems if you say your overall GPA is 3.5 when anyone looking at a transcript is going to see 3.3 or 3.2 or whatever it is.
Now, if you had taken classes outside your actual degree program, then you might put something like

Major GPA: 3.5
Cumulative GPA: 3.2

You could probably put something similar in your case and do

ComSci GPA: 3.5
Cumulative GPA: 3.2

but I would definitely not use "in-major GPA" to exclude classes which are part of your major.

A:

If your school has a placement office for helping soon-to-be graduates and recent alumni find work, they may have more insight into this than people on a Q&A site such as this.  OTOH, they may just tell you to do it in the manner which makes you look best.  That latter comment is probably the real answer, since resumes are supposed to make you look the best. It seems to me that for something like this as long as whatever method you use can be reasonably justified, is acceptable.
That said, to my knowledge, your "in major" GPA applies to those classes in the department of your major field of study.  So, if Mathematics and Computer Science are different departments, you would only use your computer science courses when calculating your in major GPA.
In fact, this may depend on your college/university.  My Bachelor's is also in CS.  My undergraduate school had a department of Mathematics and Computer Science.  There were several math courses required to get a CS degree.  However, these math courses did not count as C.S. classes when you calculated how many CS credits you had toward your degree in CS As such, whenever I computed my CS GPA, I only counted the CS classes.  However, if your math credits are rolled into your CS credits, you may need to include them.


Q:

Universal Cover of the Punctured Torus

I am currently trying to compute the universal cover of the punctured torus. I originally thought it would be a lattice, but while computing the fundamental group I saw that the punctured torus is actually homotopy equivalent to the wedge product of two circles.
I know the universal cover of the wedge of two circles is the Cayley graph that looks like a cross everywhere locally, however the punctured torus isn't quite the same as the figure eight, so I'm wondering what exactly the universal cover of the punctured torus looks like.
Thanks for any help.

A:

Here is a diabolical argument which one can only love or hate:
Put a complex structure on your torus and delete your point.
Since the universal cover of this punctured torus  is simply connected but not compact it is holomorphically isomorphic to $\mathbb C$ or to a disk by Riemann's uniformization theorem.
In both  cases it is thus homeomorphic to a disk!
[Actually it is also isomorphic to a disk holomorphically, but never mind]


Q:

Following w3c best practice video solution with youtube  embed code

According to w3schools, the best HTML solution for embedding videos directly into a web app is to use the video, object, and embed tags to deal with various issues inherent in video embedding.  However, the next chapter after shows an example that embeds a youtube video with the standard youtube embed code that uses the iframe tag.  Why is it that w3schools is not implementing their own solution into their youtube example?  Thanks in advance.
Edit:  Fixed my error by renaming w3c to w3schools

A:

W3schools is not W3C.
The two methods explained on the site are different solutions to a common problem, adding a video to your site. Both have their pros and cons: for example, YouTube will host the video for you, but if you want to use the HTML video-tag, you will have to upload it to your server or some other web storage.
It's up to you what solution to use.


Q:

Check if the current user has liked the posts of a firebase list

I'm struggling with this logic and can't find where I'm mistaken. I'm using AngularFire, Ionic 3 and Firebase.
I have a news feed. It is populated by posts from this firebase call:
this.postlist = this.db.list('/posts/').map( (arr) => { return arr.reverse();});
In my view, an *ngFor loops through the list of posts to display them.
Now for where I'm stuck.
I want to display a full red heart on the post if the current user has liked it already. I want it to be grey and outlined if not.
In my view, I have this:
<button ion-button icon-start (click)="likePost(post)" *ngIf="!likedPost(post)">
    <ion-icon name="md-heart-outline"></ion-icon> {{post.likes}}
</button>

<button ion-button icon-start (click)="likePost(post)" *ngIf="likedPost(post)">
    <ion-icon name="md-heart" color="redtext"></ion-icon> {{post.likes}}
</button>

My likedPost() function looks like that:
likedPost(post){

  //Init my own id
  let myId = this.userid;

  //Fetch the likes for this post in the firebase db
  let postLikersList = firebase.database().ref(`/likes/${post.$key}`);

  //Check in postCheck if the list of likes for this post has one that is mine
  postLikersList.once("value")
    .then(function(snapshot) {
    var postCheck = snapshot.hasChild(`${myId}`);

      if (!postCheck) {

        //Outlined button
        return false;

      } else {

        //Full red button
        return true;

      }
    });
}

It seems to work when I log the results in the console, but the button doesn't change at all.
Hope you can help me and it can help other people with the same problem.
Have a good day!

A:

You have to maintain array object like this post.islikedPost and changed its value according to your use case.Then use it as shown below.
.html
<button ion-button icon-start (click)="likedPost(post)" *ngIf="!post.islikedPost">
    <ion-icon name="md-heart-outline"></ion-icon> {{post.likes}}
</button>

<button ion-button icon-start (click)="likedPost(post)" *ngIf="post.islikedPost">
    <ion-icon name="md-heart" color="redtext"></ion-icon> {{post.likes}}
</button>

Another variation of this is where you don't need 2 buttons at all.You can do it like this.
<button ion-button icon-start (click)="likedPost(post)">
 <ion-icon name="md-heart-outline" *ngIf="!post.islikedPost"></ion-icon> {{post.likes}}
 <ion-icon name="md-heart" color="redtext" *ngIf="post.islikedPost"></ion-icon> {{post.likes}}
</button>


Q:

How to unload a FireBreath Plugin

I am using FireBreath in MAC OS X Snow Leopard.
I have a plugin which is loaded in a webpage where User do some task invoking this plugin, however I wanna unload the plugin just when user is redirected to another page where the plugin it is not used anymore.
How can I destroy the instance of this plugin?

A:

You can destroy the instance of the plugin simply by removing the object tag from the page; note that this will only destroy the instance, it will not unload the actual plugin module / shared library. There is no way to force the browser to completely unload the plugin short of restarting the browser.
Also note that when you browse away from a page with an object tag in it the plugin instance will be destroyed, so you don't actually need to do anything if the user is redirected to another page because the object tag will no longer be there.


Q:

how can i get the object not map address?

I'm try to connect java spring boot with mysql. when i run the code i got the map address like this
This is my first code
This is EmpController1
package com.example.rest.controller;

import com.example.rest.repository.R1pro;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.rest.repository.EmpRepository1;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/emp")
@Slf4j
public class EmpController1 {
    @Autowired
    private EmpRepository1 empRepository1;
    @RequestMapping(value="/ee", method = RequestMethod.GET)
    @ResponseBody
    public String getCategoryList() {
        List<String> sj = new ArrayList<String>();
        Gson gson= new Gson();
        System.out.println(123);
        List<R1pro> emps1 = this.empRepository1.findByLimit();

        return emps1.toString();
    }
}

This is my EmpRepository1 code
package com.example.rest.repository;
import com.example.rest.Emp;
import com.example.rest.Emp1;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface EmpRepository1 extends JpaRepository<Emp1, Integer> {

    @Query(value = "select * from d_RANGE limit 1",nativeQuery = true)
    public List<R1pro> findByLimit();
}

This is R1pro code
package com.example.rest.repository;

import java.util.Date;

public interface R1pro {
    public String USER_ID();
    public String CUST_GP();
}

This is my Emp1 code
package com.example.rest;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;

@Entity
@Table(name = "TEMP_TEST_M78_2W")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Emp1 {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String USER_ID;
    private String CUST_GP;
}

This is my Application code
package com.example.rest;
import com.example.rest.repository.EmpRepository;
import com.example.rest.repository.EmpRepository1;
import com.example.rest.repository.R1pro;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.List;

@SpringBootApplication
@Slf4j
public class Application {
    @Autowired
    EmpRepository empRepository;
    @Autowired
    EmpRepository1 empRepository1;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner start() {
        return args -> {mysql();};
    }

    private void mysql() {
        List<R1pro> emp1 = this.empRepository1.findByLimit();
    }
}

When i run the code i got this result
[org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap@27ae5583]

So i change the EmpController1 code
package com.example.rest.controller;

import com.example.rest.repository.R1pro;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.rest.repository.EmpRepository1;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/emp")
@Slf4j
public class EmpController1 {
    @Autowired
    private EmpRepository1 empRepository1;
    @RequestMapping(value="/ee", method = RequestMethod.GET)
    @ResponseBody
    public String getCategoryList() {
        List<String> sj = new ArrayList<String>();
        Gson gson= new Gson();
        System.out.println(123);
        List<R1pro> emps1 = this.empRepository1.findByLimit();

        for (int i =0; i<emps1.size();i++)
        {
            sj.add(emps1.get(i).USER_ID()+" "+ emps1.get(i).CUST_GP());
        }

        return sj.toString();
    }
}

When i run the code i got this Error message
java.lang.IllegalArgumentException: Invoked method public abstract java.lang.String com.example.rest.repository.R1pro.USER_ID() is no accessor method!

Actually this method same as mysql data columns
USER_ID varchar(150)
CUST_GP varchar(1)

This is my sql columns informations
I don't know what is the problem also any solution.. so if someone knows that please teach me
I really admire to solve this issue
thank you!

A:

You need to tweak your interface into something like this -
public interface R1pro {
    String getUSER_ID();
    String getCUST_GP();
}

The resultset is mapped only to the getter methods similar to the one created in Emp1 class


Q:

node.js game CPU usage

My friend and I are making a node.js game, and we have been testing CPU. After profiling, it was determined that this process called zlib is sucking most of the CPU/RAM.
3 clients connected to a game is fine, but when 12~13 players are connected it uses 58% where zlib is using about 30% of this CPU.

inclusive      self           name
ticks   total  ticks   total
64775   58.5%  64775   58.5%  /lib/x86_64-linux-gnu/libc-2.19.so
25001   22.6%    224    0.2%  LazyCompile: *callback zlib.js:409
//this one is a different zlib
7435    6.7%     82    0.1%  LazyCompile: ~callback zlib.js:409

Is there any way to decrease the CPU usage from this? Or is there a reason why it is increasing so much?
I have done some reading and I am told it is from socket.io, so here is our section of socket sending most of the data:
for (var i = 0; i < users.length; i++) {
    if (u.room == users[i].room && users[i].x + users[i].radius >= u.x - u.screenWidth / 2 - 20 && users[i].x - users[i].radius <= u.x + u.screenWidth / 2 + 20 && users[i].y + users[i].radius >= u.y - u.screenHeight / 2 - 20 && users[i].y - users[i].radius <= u.y + u.screenHeight / 2 + 20) {
        if (users[i].id == u.id) {
            visiblePlayers.push({
                x: users[i].x,
                y: users[i].y,
                angle: users[i].angle,
                hue: users[i].hue,
                radius: users[i].radius,
                squeeze: users[i].squeeze,
                name: users[i].name,
                dead: users[i].dead,
                isPlayer: true,
                kills: users[i].kills
            });
        } else {
            visiblePlayers.push({
                x: users[i].x,
                y: users[i].y,
                angle: users[i].angle,
                hue: users[i].hue,
                radius: users[i].radius,
                squeeze: users[i].squeeze,
                name: users[i].name,
                dead: users[i].dead
            });
        }
        // SEND DYING INFO: (FOR OFFLINE ANIMATION):
        if (users[i].dying) {
            visiblePlayers[visiblePlayers.length - 1].dying = true;
        }
    }
}
var visibleEnergy = [];
for (var i = 0; i < energies.length; i++) {
    if (u.firstSend || (energies[i].updated && energies[i].room == u.room)) {
        var anim = energies[i].animate;
        if (u.firstSend)
            anim = true;
        visibleEnergy.push({
            x: energies[i].x,
            y: energies[i].y,
            radius: energies[i].radius,
            index: i,
            animate: anim,
            hue: energies[i].hue,
            room: energies[i].room
        });
    }
}

// SEND PLAYER UPDATES TO CLIENTS:
sockets[u.id].emit('serverTellPlayerMove', visiblePlayers,
    visibleEnergy);

A:

As I wrote in a comment, changing the code here won't change zlib usage, as that's something that's happening at a lower level. Still, I wanted to review the code. However, as TastyLemons rightfully notes in a comment, if you can simply send less stuff all the time, it'll help. But with that much CPU usage for zlib, I'm guessing there's something wonky in the node/zlib/server configuration.
For the first loop (users loop):

That is a very long and complex if condition! And it's filled with magic numbers, as well as numbers that I assume you don't need to calculate over and over again.
The object you're building is mostly the same in both the inner branches, so it'd be easier to build the common part first, and then only add the parts that differ.
There are other small changes that would make things simpler, like setting the dying boolean in the object before pushing it to the array.
You can make good use of the map and filter array methods

For the condition, you're checking if the user is in the same room, and in view of the u user (Sidenote: u is not a terribly descriptive label, and it doesn't help that you sometimes use player and other times use user to refer to the same kind of entity).
I'd make that a method, for instance on the User prototype, if you have such a thing:
User.prototype.canSee = function (otherUser) {
  // initial check
  if(this.room !== otherUser.room) {
    return false;
  }

  // x and y distances between user and other's "radius"
  var dx = Math.abs(otherUser.x - this.x) - otherUser.radius,
      dy = Math.abs(otherUser.y - this.y) - otherUser.radius;

  return dx <= this.xViewDistance && dx <= this.yViewDistance;
};

(if you don't have a User prototype, you can change the function to be a plain function that takes two arguments.)
I'm assuming here, that the *ViewDistance values are already calculated, since I imagine they don't really change (or at least don't change all the time). So if the screenWidth doesn't change much, you could calculate a screenHalfWidth and keep it around, so you don't always have to divide by 2 to get the same result. And the 20 needs to be a needs constant (I know JS doesn't have constants; I mean a variable you treat as constant). Something like SCREEN_WIDTH_MARGIN and maybe a similar thing for height.
So xViewDistance might be defined as user.screenHalfWidth - SCREEN_WIDTH_MARGIN, which itself is a value that probably won't change all the time, and can thus be stored.
Point is, you end up with code, where:

your magic numbers are labelled so you know what they mean
your magic numbers are defined in exactly 1 place, so you only need to hunt down the same number in 23 different places if it needs to change
calculations are done once, and the results stored, rather than recalculated constantly despite not having changed.

For building the objects I'd again suggest a method on the User prototype (though again, it can also be a function that just takes an argument). Something like:
User.prototype.getInfo = function (isPlayer) {
  var info = {
    x: this.x,
    y: this.y,
    angle: this.angle,
    hue: this.hue,
    radius: this.radius,
    squeeze: this.squeeze,
    name: this.name,
    dead: this.dead,
    dying: this.dying
  };

  if(isPlayer) {
    info.isPlayer = true;
    info.kills = this.kills;
  }

  return info;
};

Putting it together, you might get:
var visibleUsers = users.filter(function (user) {
  return user.id === currentUser.id || currentUser.canSee(user);
}).map(function (user) {
  return user.getInfo(user.id === currentUser.id);
});

That's everyone's info, including the current user/the player, ready to be sent.
For the energies, the story's similar: Add some methods/functions to do the heavy lifting, and use filter/map to iterate the array. Only trick is that if firstSend is true, we could really skip the filter function, but I've left it pretty much as-is:
var visibleEnergies = energies.filter(function (energy) {
  return currentUser.firstSend || (energy.updated && energy.room === currentUser.room);
}).map(function (energy) {
  var info = energy.getInfo();
  info.anim = info.anim || currentUser.firstSend; // override anim if necessary
  return info;
});


Q:

Converting none to zero (0) in geodatabase table using ArcPy?

I have an attribute table looks like this

How do I convert Nulls into 0?
I've tried to set this table non nullable type but got this:

while the official doc says this:

At least one of them is wrong.
Then I tried many ways to do the job, like this:
RValues=arcpy.SearchCursor(sr)

for RValue in RValues:
    #print (RValue.getValue(field))
    if RValue.getValue(field) == None:
       #print (RValue.getValue(field))
       return 0
    else
       return
       float(RValue.getValue(field))

print(RValue.getValue(field))

This gives error 999999, don't know why, possible a bug.
Then I tried this:
RValues=arcpy.SearchCursor(sr)
print (RValues)

for RValue in RValues:
    if RValue.getValue(field) == None:
        print (RValue.getValue(field))
        arcpy.CalculateField_management(sr, "RValue",  esp, "PYTHON3")
    print (RValue.getValue(field))

Well, the first print gives a
<geoprocessing cursor object object at 0x0000025F5C161E70>

the second print does isolate all none items, as there is no null in python.
Here is the trick:
the third print either gives error or turn everything into null or 0,focus on everything, expressions I use are as follows:
esp="!RValue!.replace(None, 0)"

esp2="!RValue! * 0"

esp3="set field = 0 where field is null"

esp4="NVL(RValue,0)"

esp5="select nvl(RValue, 0) from sr.RValue"

esp6="None"

How is that even possible when the if before it already isolate only those nones?

A:

In your second version, you've mixed cursors and CalculateField_management().  They don't work together in this way.  CalculateField_management() will change the value for ALL RECORDS*, and pays no attention to what is happening in your cursor.
You should use either an UpdateCursor (NOT a SearchCursor) OR use a CalculateField_management().  Not both.
I usually do this sort of thing with just a CalculateField_management().
 You can do this in one of two ways:
OPTION 1:
This is quicker than OPTION 2 below (but I posted 2 first, so will leave it there as is).  This method only updates the records that need changing and also requires fewer lines.  I think it is somewhat easier to read too.
Firstly, either select just the records that you want to change to '0' OR make a feature layer that only includes those records.  I prefer the latter, as I feel safer (in the case the select doesn't work, you'll change ALL records; in the case the new feature layer doesn't work, you'll just get an error).
Then change all selected/layer records.
It's merely two lines:
arcpy.MakeFeatureLayer_management(sr, "srLayer", "RValue IS NULL")
arcpy.CalculateField_management("srLayer", "RValue", "0", "PYTHON")

Although you may like to clean up afterwards by deleting the layer with a third line:
arcpy.Delete_management("srLayer")

OPTION 2:
Include a code block which will determine the correct value for all records.  Note that this will update records that don't need to be changed, but it will update them with the same value they already have, so not a big deal.
But this means that it is slower than OPTION 1 and also not as good for auditing purposes (eg, if you use editor tracking!).
codeblock = """
    def calcRValue(rvalue):
        if rvalue is None:
            return 0
        else:
            return rvalue
"""
arcpy.CalculateField_management(sr, "RValue", "calcRValue(!RValue!)", "PYTHON", codeblock)

OTHER NOTES:
Don't use arcpy.SearchCursor or arcpy.UpdateCursor, which have been superceded.  Use arcpy.da.SearchCursor or arcpy.da.UpdateCursor.  They are massively faster (even if marginally more difficult syntax).
I'm not sure what your first version is trying to do, but the last line (print) uses the variable RValue out of scope and I would not expect it to work there.  Perhaps it should be indented to be within the loop to print the value each time around the loop?  But I'm not sure what it's supposed to be doing there.
*actually, all selected records if there are any, or all records otherwise.

A:

I prefer to use an UpdateCursor to manipulate feature class attributes. However, make sure to use the modern Data Access da cursors. For example:
import arcpy

fc = r'C:\path\to\your\geodatabase.gdb\featureclass'

with arcpy.da.UpdateCursor(fc, "some_field") as cursor:
    for row in cursor:
        if row[0] == None: # None appears as <Null> in attribute table float fields
            row[0] = 0
        cursor.updateRow(row)


Q:

How to deploy a website in jsp

I have a website in JSP developed with Java EE technologies like Struts and Hibernate using Netbeans and Glassfish.
I want to deploy it on web. How do I do it? I also need about 10 MySql Databases and 3 email accounts on hosting.
Which server is suitable for it, Windows or Linux?
I am also not finding anywhere written JSP on any of the hosting provider websites. What is the senario about JSP?
Also list some most secure and best web hosting provider which respects customers privacy and security. I am from Delhi, India.

A:

JSP may be hosted on both Linux and Windows server.
However, most of the popular and low-cost hosts do not support JSP as Java is resource-intensive.
I would recommend Network Solutions.
You may want to check with the hosts directly regarding support for JSP.
Alternatively, you may check out Hosting Review for great deals. However, for those hosts who do not state whether they support JSP, do contact their live support to confirm.
Be sure to read the reviews on the hosts carefully before making a decision and do not just go for the cheapest one.
An additional tip would be to deactivate auto-renewal and remove your credit card information totally from the host after payment as some rogue hosts may impose hidden fees and automatically charge them to your card according to your card details.


Q:

403 forbidden on image url on production asp.net

I've referred lots of site and questions, but did not find any solution. It is working on my local site but not on production.
Structure:
-Root
 -Files
  -Products
   -Product01.jpg
 -others
   -Product01.jpg

I'm able to access Product01.jpg from others folder, but when I'm trying to access image from Products it gives me an error of 403 forbidden:You have attempted to view a resource that does not have Read access..
I've Added IUSer, IIS_IUser and NETWORK SERVICES with full access. But getting same error.
Also tried with allow anonymous authentication, but no luck!
Side: All users roles have full permission.

A:

Okay, I got the answer.
I'm using IBM VPS server, So need configure as below.
IIS > Folder >  Handler mappings  > Edit Feature Permissions > check here is enabled or not! and checked Read and Script


Q:

Always need to renew ssh-keys working with Bitbucket from two machines

I've never had any problems working with my repos hosted on Bitbucket using SSH connection with a generated keypair. But since I'm accessing my repos from two different machines (e.g. home machine, work machine), I always get
Permission denied (publickey).fatal: Could not read from remote repository.

everytime I switch machines. So my current not so great workaround is to delete my current key with
rm -r .ssh

(I'm just using one) and then generate a new one, either using Sourcetree or Terminal. Then I remove the old key for the machine I'm using from my Bitbucket Account and paste in the new key.
This has been working since, but there has to be a better solution. I've browsed the Bitbucket docs, but it just says to add a new key for every machine, which is accessing the repos and obviously this it not working. I'm sure I'm missing something. Thanks for any help!

A:

So here is a link to a guide on how to fix that problem.
https://github.com/jirsbek/SSH-keys-in-macOS-Sierra-keychain
As described in the comments, Apple changed SSH behavior in Sierra/High Sierra. Theres a Sourcetree issue with status 'resolved' about this topic (https://jira.atlassian.com/browse/SRCTREE-4499), so Sourcetree adds keys to .ssh/config with the needed flags since 2.7.2 but still this hasn't worked for me. I needed to add ssh-add -Ato my launch agents.


Q:

Is there a proper pattern to mix different types in a GraphQLUnionType?

I have a problem where I need to create a query that will return different possible types for a node, I am also exploiting the __typename property to determine which one I received.
The reason I am not using an EnumType is because the different subtypes can be vastly different.
A few of them are empty (e.g. they do not possess any properties).
This causes a problem because I cannot create a UnionType.
I tried to use ScalarTypes for these empty definitions, but for Union I can only use ObjectTypes, which require a 'fields' definition.
For example, here are some definitions of classes I used from the service side
classA {
token: string
}

classB {
}

classC {
}
type returnType = classA | classB | classC

For each of those I define a type
typeA = GraphQLObjectType ofType classA with fields => {token}
typeB = GraphQLObjectType ofType classB with fields => undefined
typeC = GraphQLObjectType ofType classC with fields => undefined

The problem occurs when building union type for the query
new GraphQLUnionType({
      types: [typeA, typeB, typeC]
})

I would like to know what's the proper way of dealing with this scenario, from a client I'd simply like to do something like
query {
   myquery {
     mode: __typename
     ... typeA {
         token
     }
  }

I tried to inject the name as a property, and this works because every type will have one, but this is redundant.

A:

I'd probably work around this by adding some field to the otherwise-empty object types.
"""Objects of this type don't have properties."""
type classB {
  """Just a placeholder value; always null."""
  _placeholder: Bool
}

Once you have that it can participate in the union type normally, and you can query its __typename as normal.  You don't specifically have to mention it in the query if you don't want to.
query {
  myquery {
    __typename
    ... on classA {
      token
    }
    # No need for a fragment ...on classB
  }
}


Q:

IF EXISTS block

I have 2 tables UserSession and Sale.
Table User has 4 columns, namely UserID, UserSessionID, SessionOpenDate and SessionCloseDate.
Table Sale has 2 columns, which are price, cost, userID and CompletedDate.
When a user logs in, a new row is created in the User table, where the user's login timestamp will be saved in the SessionOpenDate and a new UserSessionID will be assigned to the session. When the user logs off, the log off timestamp will be be saved in SessionCloseDate.
When the user is still logged in, the user can make some sale and the sale information is saved in the Sale table. The timestamp when the sale is finalized in saved in CompletedDate column.
For some reason, I need to get the all sales done in a certain UserSessionID where the CompletedDate must be within the SessionOpenDate and SessionCloseDate. However, if the user has not logged off yet, which means that the value in SessionCloseDate is null, the CompletedDate  should be between SessionOpenDate and now.
Here's my query:
SELECT SUM(s.cost) AS Cost, SUM(s.price) AS Price
FROM Sale AS s
  INNER JOIN UserSession AS u
  ON s.userID = u.userID
WHERE
  (s.CompletedDate >=
    ( SELECT SessionOpenDate
      FROM UserSession
      WHERE (UserSessionID = u.UserSessionID)
)
  )
  AND
  (s.CompletedDate <
    (
      IF EXISTS
       (
         SELECT SessionCloseDate AS closeTime
         FROM UserSession AS UserSessionTemp
         WHERE (UserSessionID = u.UserSessionID)
       )
       BEGIN
         SET closeTime = SELECT CURRENT_TIMESTAMP
       END
    )
  )
  AND u.UserSessionID IN (1)

However, Sql Server says Incorrect syntax near the keyword 'IF'. and Incorrect syntax near ')'.
Can anyone tell me what went wrong with my IF block?
Thanks

A:

You can't use an IF block inside a SELECT statement. Also, I don't know what you're really trying to accomplish with SET, since closeTime is not a variable/parameter.
You can use IIF in SQL Server 2012 (syntactical sugar for CASE WHEN <condition> THEN <true_value> ELSE <false_value> END - use this syntax for earlier versions):
IIF(EXISTS
   (
     SELECT SessionCloseDate AS closeTime
     FROM UserSession AS UserSessionTemp
     WHERE (UserSessionID = u.UserSessionID)
   ), (
     SELECT SessionCloseDate AS closeTime
     FROM UserSession AS UserSessionTemp
     WHERE (UserSessionID = u.UserSessionID)
   ),
     CURRENT_TIMESTAMP
)

Honestly, without getting too complicated, here's what I would do instead:
SELECT SUM(s.cost) AS Cost, SUM(s.price) AS Price
FROM userSession AS u
INNER JOIN Sale AS s ON u.userID = s.userID
WHERE u.UserSessionID = @UserSessionId
AND s.CompletedDate >= u.SessionOpenDate
AND (u.SessionCloseDate IS NULL OR s.CompletedDate < u.SessionCloseDate)

Or,
SELECT SUM(s.cost) AS Cost, SUM(s.price) AS Price
FROM userSession AS u
INNER JOIN Sale AS s ON u.userID = s.userID
WHERE u.UserSessionID = @UserSessionId
AND s.CompletedDate BETWEEN u.SessionOpenDate
                    AND COALESCE(u.SessionCloseDate, '12/31/9999 23:59:59.9999')


Q:

How to parse a report using Shell script?

I have a command line program that prints out a report such as:
I found 0 problems on your database,
0 problems were found on your database

and so on.
I would like to write a linux shell script that exports the number only to a variable. I can't find the correct way of doing so. I suspect I am not using grep properly (or there's a better command);
i.e.
I found 43 problems on your database,
43 problems were found on your database
$VAR=43

please advise

A:

$ var=$(echo -e "I found 43 problems on your database,
43 problems were found on your database" | grep -om 1 '[0-9]\+')
$ echo $var
43


Q:

Put paragraph to h2 using jQuery

First: I am new to jQuery. I try put a paragraph tag into a h2 tag using jQuery. Website is built on a CMS so the HTML is generated by the CMS. But I can give you a few HTML code and a short jQuery code what I tried before:
HTML:

Title goes here

jQuery:
$(document).ready(function(){
    $('#container').find('h1').replaceWith(function(){
        return '
' + $(this).text() + '
';
    });
    $('

').prependTo('h2');
});

The jQuery code does this with my HTML code (which is not too bad, it just has to be optimized):

    Title goes here

My problem now is, I'd like to get the "Title goes here" into the p tag. Is there a jQuery function to do this or am I completely wrong? I already had a look at the jQuery API Documentation but I didn't find anything what could help me. Any suggestions?
Cheers
PS: Here is a fiddle: Demo

A:

This is very easy: you select the contents of the h2 with contents and then wrap them all in a p with wrapAll. You can combine this with the function syntax of replaceWith to do this all in one line.
$('h1').replaceWith(function(this) {
    return $(this).contents().wrapAll('
').wrapAll('
').closest('h2');
});

A better question would be why you want to do this. h2 elements may not contain p elements.
Updated fiddle.


Q:

ignite shutdown node while putting in transaction

I'm trying Apache Ignite and play with examples. I took an example from screencast about transactions. Started 3 server nodes, and start code that begins transaction and putting 50k elements in cache. While it running i kill 2 of 3 nodes. I expected Ignite to fail commit with error, but in fact there were no any errors and I get partially saved data. It is no fully ACID transaction as said in manuals. May be I don't understand something important?

A:

Transactions are thread-local. This means that to enlist a cache operation into transaction, it has to be executed by the same thread that started the transaction. Commit or rollback has to be happen in this thread as well.
In your example you start new threads to execute updates, so they are not enlisted. Essentially, each operation is executed in a separate implicit transaction, which results in the behavior you observe.


Q:

How can I use .Contains() to get at a property of a collection using LINQ to Objects?

I have an IEnumerable of the following object:
public class Recipient
{
    public  int UserID { get; set; }
    public  string Name { get; set; }
}

So, I have an IEnumerable<Recipient> Recipients, and I'd like to do a .Contains() on Recipients.  Except, I'd like to do a .contains() on each recipients UserID, to see if my Recipients contain a particular userID.
If I just had an IEnumerable<Int> Recipients, it would be easy to do Recipients.Contains(5);
But, because I'm trying to get a property of the collection, how do I use Contains in that instance?

A:

Recipients.Any(r => r.UserID == 5)

Alternatively, you can map the collection to a collection of UserID values and perform a Contains there:
Recipients.Select(r => r.UserID).Contains(5)


Q:

Export data to a file using apex

I have a requirement to

Run SELECT query on custom object
export the data to csv file
Automate / schedule step-1 and step-2 .

I know how to achieve step-3, by using apex scheduler class. But I couldn't find anything on exporting data from apex code. We have been using Jitterbit, but now our client wants to get rid of it, and use only salesforce.

A:

If you're concerned about time or memory limits, use a batch class. This is how I would perform the export of a potentially unknown size (10k+ records).
global class X implements Database.Batchable<SObject>, Database.Stateful {
    string[] Lines;

    global Database.QueryLocator start(Database.BatchableContext bc) {
        lines = new String[0];
        return Database.getQueryLocator( your-query-here );
    }
    global void execute(Database.BatchableContext bc, SObject[] scope) {
        for(Sobject record: scope) {
            String line = '';
            // build your csv line here
            lines.add(line);
        }
    }
    global void finish(Database.batchablecontext bc) {
        String finalResults = String.join(lines, '\n');
        lines = null; // Free temp memory to avoid heap errors
        // proceed to send attachment by email
    }
}

The best performance I've gotten for a synchronous export (that is, a direct query, plus processing about 30 fields per record) is about 5,000 records before a CPU timeout exception, so if this is a concern, definitely go with a batch. If you're confident that you can beat the timeout, you could perform the query and translation directly in the scheduler class itself without resorting to a batch.


Q:

SQL - delete row if another table exists

I'm trying to delete a row from a table if another table doesn't exist. I've tried using the following statement
 IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'user3project3'))
 BEGIN
     DELETE FROM user1table WHERE id=3
 END

However I get the following error:
 Unrecognized statement type. (near "IF" at position 0)

I'm using phpMyAdmin with XAMPP, if that matters.
Thanks a lot in advance!

A:

The IF statement is only allowed in programming blocks, which in practice means in stored procedures, functions, and triggers.
You could express this logic in a single query:
DELETE FROM user1table
    WHERE id = 3 AND
          NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'user3project3');

That said, you have a very questionable data model if you are storing a separate table for each user.


Q:

Can someone please tell me why the out.println isn't working?

the JDBC code below inserts data into a table in a MySQL database. It is working fine, except for the out.println response and the requestdispatcher. When update is successful, it should print "Employee Account successfully created". And similarly if update is unsuccessful. However, it is not printing the output.
        try{

             Class.forName("com.mysql.jdbc.Driver").newInstance();
             Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
             PreparedStatement ps = con.prepareStatement("INSERT INTO payroll_system.employee_info(employeeID, FirstName, LastName, Admin,DOB,Address,Email,HourlyRate,Gender,ALeaveBalance,SLeaveBalance,ActiveStatus,Role,BSB,BankName,AccNumber,SuperNumber,SuperCompany) values(?,?,?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?)");
             ps.setString(1, employee_id);
             ps.setString(2, firstName);
             ps.setString(3, lastName);
             ps.setString(4, admin);
             ps.setString(5, DOB);
             ps.setString(6, address);
             ps.setString(7, email);
             ps.setString(8, HPR);
             ps.setString(9, gender);
             ps.setString(10, ALB);
             ps.setString(11, SLB);
             ps.setString(12, Role);
             ps.setString(13, BSB);
             ps.setString(14, BankName);
             ps.setString(15, BAN);
             ps.setString(16, SAC);
             ps.setString(17, SAN);

             int count = ps.executeUpdate();

             if(count>0) {
                 out.println("Employee Account Successfully Created");
             }
             else {
                 out.println("Failed to create account");
             }

         }catch(Exception e)
        {
            e.printStackTrace();
        }

A:

You are calling executeUpdate twice, the second call will return nothing, you should remove a call .
So, just replace :
ps.executeUpdate();

int count = ps.executeUpdate();

with :
int count = ps.executeUpdate();


Q:

In Perl, how do I process multiple lines

Say, I have a file that has the following lines with a "TIMESTAMP" "NAME":
10:00:00  Bob
11:00:00  Tom
11:00:20  Fred
11:00:40  George
12:00:00  Bill
I want to read this file, group the names that occur in each hour on a single line, then write the revised lines to a file, for example.
10:00:00 Bob
11:00:00 Tom, Fred, George
12:00:00 Bill

A:

Given that, per comments on the original question, all entries for the same hour are contiguous and the file is too large to fit into memory, I would dispense with the hash entirely - if the raw file is too big to fit in memory, then a hash containing all of its data will likely also be too large.  (Yes, it's compressing the data a bit, but the hash itself adds substantial overhead.)
My solution, then:
#!/usr/bin/env perl

use strict;
use warnings;

my $current_hour = -1;
my @names;

while (my $line = <DATA>) {
  my ($hour, $name) = $line =~ /(\d{2}):\d{2}:\d{2} (.*)/;
  next unless $hour;

  if ($hour != $current_hour) {
    print_hour($current_hour, @names);
    @names = ();
    $current_hour = $hour;
  }

  push @names, $name;
}

print_hour($current_hour, @names);

exit;

sub print_hour {
  my ($hour, @names) = @_;
  return unless @names;

  print $hour, ':00:00 ', (join ', ', @names), "\n";
}

__DATA__
10:00:00 Bob
11:00:00 Tom
11:00:20 Fred
11:00:40 George
12:00:00 Bill


Q:

Ways to avoid using switches to map strings to classes

I have a C# solution that reads records from a db and processes them into another db. The records to be processed are essentially one long string that represents the data and then another string "code" that determines how that big data string should be parsed. There are dozens and dozens of different kinds of records; I have them represented as distinct concrete classes that all inherit from an abstract class.
I can generate the code to make classes for the different records easily enough. However, is there a better (i.e. less verbose, more dynamic) way to map the "code" to the class that represents it? Right now I'm just using a huge switch, something like:
BaseRecord record;
switch(code) {
    case "A":
        record = new A(stringData);
    case "B":
        record = new B(stringData);
    .
    .
    .
    case "Z":
        record = new Z(stringData);

where A, B, ..., Z all derive from BaseRecord.
Other than reflection, I can't think of a way to map string representations of class names to the classes they represent.

A:

Well, it is possible to avoid the switch statement: You can create an abstract factory class, and have some classes inherit from it (ideally via a template argument) to produce objects of the different derived types. Then you can put all the concrete factories you need in a map and use the strings to index into that map to produce a factory for the desired dynamic type.
However, while possible, this is hardly worth doing. As far as I can see, your switch statement is mind-numbingly simple (albeit long). The abstract factory would introduce a lot of additional complexity, so the switch seems to be more compliant to the KISS principle.
Generally speaking, there's nothing bad about a switch statement, not even one with a lot of cases (as long as the cases are simple and self contained). The problem with switch statements is only when they crop up everywhere, which indicates that you should be using inheritance instead. A single switch to perform deserialization seems fine to me.


Q:

Typescript - How to explicitly assign the type of each property when we know all of it is the same?

Let says I have the object
interface Name {
  first: string;
  middle: string;
  last: string;
  blah: string;
  blahblah: string;
}

As you can see, every one of property is string. Is there a way to not typing "string" so much time?

A:

You can use Record instead:
type Name  = Record<
  | 'first'
  | 'middle'
  | 'last'
  | 'blah'
  | 'blahblah', string>

Playground Link


Q:

The save() method in cakePHP

I am doing some self-learning about cakePHP 1.26.
I got a table which has two fields {topic, username}
I got a simple HMTL form like this:
<input type=text name="data[testing][topic]" id="data[testing][topic]"/>

The data from this input field was passed to the specific controller with this code:
$who=$this->Session->read('user.name'); // username retrieved successfully
$this->Testing->save($this->data);

When I checked the database, I could only see the data from the Input text field, but
the username field is empty.
How do I alter the code in the controller so that the username retrieved from the session can be saved into the database?
Could you help me please?

A:

Like this:
$who=$this->Session->read('User.id');
$this->data['Testing']['user_id'] = $who; // set the data
$this->Testing->save($this->data);


Q:

Adding attr tag in html via PHP

I would like to add another property and value into my HTML object,
but instead, it's replacing the current value.
This is what I've coded so far in my PHP file.
function htmlEncode ( $html ){

$html = preg_replace('~>\s+<~', '><', $html);
$html = html_entity_decode($html);

$dom = new DOMDocument();
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('*') as $div){

    foreach ($div->attributes as $attr) {

        if($div->nodeName == "h2"){
            $class = $attr->nodeName;
            $className = $attr->nodeValue;
            $div->setAttribute("aria-label", $div->nodeValue);

            $result = [
                 "tagName" => $div->nodeName,
                 "value" => $div->nodeValue,
                 $class=> $className,
                 $attr->nodeName => $attr->nodeValue
            ];
        } else {
            $result[] = [
                 "tagName" => $div->nodeName,
                 "value" => $div->nodeValue,
                 $attr->nodeName => $attr->nodeValue
           ];
        }
    }
}

$json = json_encode($result, JSON_UNESCAPED_UNICODE);

return $json;
}

but when I run the code
echo json_encode($attr->nodeName);

I get the two attributes:
"class" "aria-label"

A:

Try the below code.
Changes done:
1. $class[] = array();

2. $class[$attr->nodeName] = $attr->nodeValue;
3. Removed `class` from results
4. Added
            foreach($class as $key=>$classValues){
                if(!empty($classValues)){
                     $result[$key] = $classValues;
                }
             }

Complete code:
function htmlEncode ( $html ){

$html = preg_replace('~>\s+<~', '><', $html);
$html = html_entity_decode($html);

$dom = new DOMDocument();
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('*') as $div){
    $class[] = array();
    foreach ($div->attributes as $attr) {
        if($div->nodeName == "h2"){
            $class[$attr->nodeName] = $attr->nodeValue;
            $div->setAttribute("aria-label", $div->nodeValue);

            $result = [
                 "tagName" => $div->nodeName,
                 "value" => $div->nodeValue,
                 $attr->nodeName => $attr->nodeValue
            ];
            foreach($class as $key=>$classValues){
                 if(!empty($classValues)){
                        $result[$key] = $classValues;
                 }
            }
        } else {
            $result[] = [
                 "tagName" => $div->nodeName,
                 "value" => $div->nodeValue,
                 $attr->nodeName => $attr->nodeValue
           ];
        }
    }
}

$json = json_encode($result, JSON_UNESCAPED_UNICODE);

return $json;
}


Q:

Angular JS console errors: line numbers don't refer to my source files

I am making my first Angular app and I'm trying to figure out how to use the errors displayed in the console to figure out where in my code things are breaking. Here is an example console error:
Error: [$injector:unpr] Unknown provider: HomeProvider <- Home
http://errors.angularjs.org/1.2.5/$injector/unpr?p0=HomeProvider%20%3C-%20Home
    at http://recipe-app/lib/angular/angular.js:78:12
    at http://recipe-app/lib/angular/angular.js:3519:19
    at Object.getService [as get] (http://recipe-app/lib/angular/angular.js:3646:39)
    at http://recipe-app/lib/angular/angular.js:3524:45
    at getService (http://recipe-app/lib/angular/angular.js:3646:39)
    at invoke (http://recipe-app/lib/angular/angular.js:3668:13)
    at Object.instantiate (http://recipe-app/lib/angular/angular.js:3689:23)
    at http://recipe-app/lib/angular/angular.js:6714:28
    at link (http://recipe-app/lib/angular/angular-route.js:897:26)
    at nodeLinkFn (http://recipe-app/lib/angular/angular.js:6168:13) <div ng-view="" class="full-screen ng-scope">

See how all the line numbers refer to lines within the angular.js file and not my source files? That leaves me guessing where my error is.
Note: I'm not looking for a solution to this specific error. I'm trying to figure out in general how to find the source of these errors using Angular.
I've installed Batarang already, but thats not showing me this error at all. Also, other SO answers show you how to manually log error information to the console by inserting code in specific places, but that assumes I have a general idea where it's coming from.
Thanks in advance, sorry for being dim.

A:

This happens when any of your services are not defined. So check if all your services are included to index.html. In your case I see that your Home service is not found.


Q:

Force a textarea to be on the same line with other elements

I have a webpage with the following layout:
Text
Radio Button
Radio Button
Button

I want to add a textarea that will be on the same line as the elements, like:
Text            **********
Radio Button    *Textarea*
Radio Button    **********
Button          **********

(the asterixes mark the place occupied by the textarea)
But it ends up being just under the elements:
Text
Radio Button
Radio Button
Button
**********
*Textarea*
**********
**********

What CSS styling should I apply to resolve this problem?

A:

you need to float your content or use the inline-block option
Here is an exemple of what you want:http://jsfiddle.net/uDLZF/3/
CSS
#first, #second{
    float:left;
}
ul { list-style-type: none; }

HTML

Text

Radio Button

Radio Button

Button

**********

*Textarea*

**********

**********


Q:

Dump process memory to disk to analyze for memory leaks

I have a 32 bit msvc++ application running in a production environment that is leaking memory.  It basically will run for a few hours until it consumes all 3 gb of addressable memory and terminates.
I was thinking that if there was a way to suspend a process and dump it's memory to disk, I could analyze the memory to see if there are any patterns to what it leaking.
Not sure if this is even possible.  I'm just throwing science at the wall and seeing what sticks.
Some input would be much appreciated.

A:

This is extremely straightforward as long as you're confident that you have some means of finding something useful by analyzing the process' heap. The tools involved are all free and instructions are here: Dump Files
That said, if you could just run a debug build for a while, the CRT will do all the work for you. See Finding Memory Leaks Using the CRT Library


Q:

Python - How can I scrape with bs4 a javascript code)?

So I have been trying to scrape out a value from a html that is a javascript. There is alot of javascript in the code but I just want to be able to print out this one:
var spConfig=newProduct.Config({
  "attributes": {
    "531": {
      "id": "531",
      "options": [
        {
          "id": "18",
          "hunter": "0",
          "products": [
            "128709"
          ]
        },
        {
          "label": "40 1\/2",
          "hunter": "0",
          "products": [
            "120151"
          ]
        },
        {
          "id": "33",
          "hunter": "0",
          "products": [
            "120152"
          ]
        },
        {
          "id": "36",
          "hunter": "0",
          "products": [
            "128710"
          ]
        },
        {
          "id": "42",
          "hunter": "0",
          "products": [
            "125490"
          ]
        }
      ]
    }
  },

  "Id": "120153",

});

So I started by doing a code that looks like:
test = bs4.find_all('script', {'type': 'text/javascript'})
print(test)

The output I am getting is pretty huge so I am not able to post it all here but one of them is the javascript as I mentioned at the top and I want to print out only var spConfig=newProduct.Config.
How am I able to do that, to be able to just print out var spConfig=newProduct.Config....  which I later can use json.loads that convert it to a json where I later on can scrape it more easier?
For any question or something I haven't explained well. I will apprecaite everything in the comment where I can improve myself aswell here in stackoverflow! :)
EDIT:
More example of what bs4 prints out for javascripts
<script type="text/javascript">varoptionsPrice=newProduct.Options({
  "priceFormat": {
    "pattern": "%s\u00a0\u20ac",
    "precision": 2,
    "requiredPrecision": 2,
    "decimalSymbol": ",",
    "groupSymbol": "\u00a0",
    "groupLength": 3,
    "integerRequired": 1
  },
  "showBoths": false,
  "idSuffix": "_clone",
  "skipCalculate": 1,
  "defaultTax": 20,
  "currentTax": 20,
  "tierPrices": [

  ],
  "tierPricesInclTax": [

  ],
  "swatchPrices": null
});</script>,
<script type="text/javascript">var spConfig=newProduct.Config({
  "attributes": {
    "531": {
      "id": "531",
      "options": [
        {
          "id": "18",
          "hunter": "0",
          "products": [
            "128709"
          ]
        },
        {
          "label": "40 1\/2",
          "hunter": "0",
          "products": [
            "120151"
          ]
        },
        {
          "id": "33",
          "hunter": "0",
          "products": [
            "120152"
          ]
        },
        {
          "id": "36",
          "hunter": "0",
          "products": [
            "128710"
          ]
        },
        {
          "id": "42",
          "hunter": "0",
          "products": [
            "125490"
          ]
        }
      ]
    }
  },

  "Id": "120153"
});</script>,
<scripttype="text/javascript">document.observe('dom:loaded',
function(){
  varswatchesConfig=newProduct.ConfigurableSwatches(spConfig);
});</script>

EDIT update 2:
try:
    product_li_tags = bs4.find_all('script', {'type': 'text/javascript'})
except Exception:
    product_li_tags = []

for product_li_tag in product_li_tags:
   try:
        pat = "product.Config\((.+)\);"
        json_str = re.search(pat, product_li_tag, flags=re.DOTALL).group(1)
        print(json_str)
   except:
       pass

#json.loads(json_str)
print("Nothing")
sys.exit()

A:

You can use the .text function to get the content within each tag.  Then, if you know that you want to grab the code that specifically starts with "varoptionsPrice", you can filter for that:
soup = BeautifulSoup(myhtml, 'lxml')

script_blocks = soup.find_all('script', {'type': 'text/javascript'})
special_code = ''
for s in script_blocks:
    if s.text.strip().startswith('varOptionsPrice'):
        special_code = s.text
        break

print(special_code)

EDIT: To answer your question in the comments, there are a couple of different ways of extracting the part of the text that has the JSON.  You could pass it through a regexp to grab everything between the first left parentheses and before the ); at the end.  Though if you want to avoid regexp completely, you could do something like:
json_stuff = special_code[special_code.find('(')+1:special_code.rfind(')')]

Then to make a usable dictionary out of it:
import json
j = json.loads(json_stuff)
print(j['defaultTax'])  # This should return a value of 20


Q:

Display previous page results when we click back button in browsers

I have an application in PHP which is a search form.If i make a search in the search box and i submit the form then a list of products will get displayed then if i click any product it goes to the product page,now what is my issue is when i click the back option in the browser an alert for re-submission is getting still i go previous page search results are not shown
it is redirect to home page not to the search form also.
   Since i have list of variables i am using POST method instead of GET method.But if i use GET method there is no issue but i want to know whether the same can be in POST method also.

A:

Use GET. There's a lot of debate about what qualifies for each of the HTTP verbs, but generally speaking this fits squarely in the GET world. The POST warning by the browser is unwarranted: the first sign that you shouldn't be using it for this particular operation (search).


Q:

Is Spring Roo no longer supported?

I used to use Roo for starting new projects and want to advocate for in our company, however I've stumbled upon the fact that it does not support Java 8 and there is a ticket for it: https://jira.spring.io/browse/ROO-3505
I found it some time ago and recently I went to check if it was updated and was surprised that it is still there. I paid attention though that the latest version of Spring Roo was released in January 2014 (1.2.5) and there were no more bug fixes or feature releases since.
It is especially strange in the light of the fact that recent Spring Core was significantly updated to support Java 8 last year (version 4.0.0 was released in December 2013)
Does it mean that Spring Roo project is dead and Spring Source has no plans to support it?

A:

Some months ago DISID and Pivotal reached an agreement on Roo project. Take a look at http://blog.gopivotal.com/pivotal/news-2/disid-to-lead-spring-roo-project
Posted on April 24, 2014

We are happy to announce that Pivotal and DISID will collaborate on further development of the Spring Roo project. Roo will continue in its goal of providing a code-generation style of RAD framework, focused on helping developers get Java projects done on time. Pivotal and DISID have been collaborating around Roo for some time, so we’re excited to be formalizing what originally was an informal, developer led partnership, a partnership that DISID is committed to.

A:

Spring Roo is back, they released Version 1.3.0 on 2014-11-21, it contains Java 8 support.

A:

I just submitted my second Roo bug fix (3rd actual pull request) the other day and plan to submit more over time, so I can say that Roo is no more dead than any other open source Java based tool with active contributors. I am also an active user of Roo, so I tend to fix bugs as I encounter them in my own projects.  So, despite its list of open issues and apparent lack of popularity at the current point, I still find it to be as useful if not moreso than most of the other Java tools out there.  If you want to help it along, why not convert some of the energy harping on the tool and come help make it better?


Q:

Simple if statement not working in wordpress echo is working

I am hoping that someone can help me, I am writing a simple if statement inside WordPress but for some reason it does not seem to execute the way I want it to work.
    $g_map = get_the_id().(get_post_meta($post->ID, '_et_business_g_pagetype', true));
if ('map' == $g_map) {
    echo "
This is the map page
".$g_map;
    }

The if statement is to execute when a Custom Post Meta Field = map
If I execute this line echo get_the_id().(get_post_meta($post->ID, '_et_business_g_pagetype', true)); outside the if statement is does show that the value is "map"
So "map should equal map" and the echo should run as intended, but I cannot understand why it is not...
Any ideas why this maybe happening and how I can fix it will be appreciated.

A:

I have placed the get_the_id() to see if I have the right post! - so infact map did not equal map... it was map = (postnumber)map and this is why the if statement did not work! - Thanks a million for pointing me in the right direction! It is now solved!


Q:

Java generics & incompatible types using

abstract class AbsClass {}

class MyAbs extends AbsClass {}

class MyClass<S extends AbsClass> {
    S getObj() {
        return new MyAbs();
    }
}

Getting compiler issue:

Error:(33, 16) java: incompatible types: MyAbs cannot be converted to S

What is the correct way to do this?
Edit:
I was hoping to be able to intialize MyClass{MyAbs} then call getObj() which would return me a MyAbs object. With Andy's answer, I would have to cast the AbsClass to MyAbs or MySecondAbs which was what I was trying to avoid

A:

Andy has described how to fix the problem, I'll try to explain why.
S is not guaranteed to be assignable to MyAbs, only to AbsClass, and each instance will specify a subclass of AbsClass.
Consider:
class MyOtherAbs extends AbsClass {}

MyClass myClass = new MyClass<MyOtherAbsClass>{};

This would conflict with what you have.
UPDATE:
Based on your comments it looks like you want to achieve the above.  The challenge is what if MyOtherAbs has a constructor with arguments?  Or is implemented as a Singleton (i.e. a private constructor and static getInstance()).  In short, there is no guaranteed unified way you can construct these.  Further, due to type erasure, at runtime, the concept of S is gone, so you cannot do something like:
return new S();

You basically have two alternatives, one is to use subclassing:
public interface AbsClassFactory<S extends AbsClass>{ //takes the place of MyClass
    public S getInstance();
}

MyAbsFactory implements AbsClassFactory<MyAbs>{
    public MyAbs getInstance(){
        return new MyAbs(); //or however MyAbs is instantiated
    }
}

The other option is reflection:
class MyClass {
    public <S extends AbsClass> S getObj(Class<S> clazz) throws InstantiationException, IllegalAccessException {
        return clazz.newInstance();
    }
}

Note that the second assumes there is a no arg constructor available and will throw a runtime exception if one is not.

A:

S extends MyAbs, not the other way around. any object of type S can be cast into MyAbs, but MyAbs cannot be cast into it's derived classes.
Please explain what you are trying to achieve.


Q:

The most optimal solution for sending Java Source Code to Google App Engine via Google Cloud Endpoints

I am developing an application which needs to accept Java Source code from the client via the Google Cloud Endpoints, and then the Google App Engine would work on it. The simplest solution was to send the Java Source Code as a String from the JavaScript client and make an endpoint which accepts the String. However a GET request more than 2kB is giving errors and Source Codes can be (and are generally often) far larger than 2kB.
It will be important to note here that minification of the code is not allowed.
Then what should be the  best way to achieve so?
An advanced thanks for trying to solve my issue.

A:

You're using it wrong. @Named parameters become part of the url (like http://server.com/api?source=Java+source+here.), and that has the same limitations as a GET request.
You can encapsulate your data in a pojo and add it as method parameter. For example
@Api(name = "myApi", version = "v1")
public class MyApi {

    public static class PseudoCon {
        public String foo;
    }

    public static class SourceContainer {
        public String source;
    }

    @ApiMethod(name = "pseudo", path = "pseudo", httpMethod = HttpMethod.POST)
    public PseudoCon getPseudoCode(SourceContainer sourceContainer){
        String source = sourceContainer.source;
        PseudoCon result = new PseudoCon();
        result.foo = source.substring(0, 1);
        return result;
    }
}

That allows for a proper POST with a request body:
POST http://localhost:8888/_ah/api/myApi/v1/pseudo

{
 "source": "Java source here."
}

(source becomes encapsulated in a json object)
With reply
200 OK
{
 "foo": "J"
}


Q:

Black screen when executing test app on Tizen Emulator

I'm starting to work with Tizen and I'm following its tutorials. When I test my apps, they only get with a black screen when I open them on the emulator, and I don't know why is that.
Would someone know what can cause this, and how to solve it?
I'm using Windows 7 64bits, I've installed the Intel Haxm and enabled the virtualization. The emulator seems to work fine, but, I still get this problem with my apps.
Thank you for the help.

A:

Turn the GPU of the emulator off . In some machines GPU is not supported.
GPU option is available in the emulator manager.


Q:

How to read aloud c++ expressions with the input/output operators?

I feel pretty stupid, but I'm just starting to learn c++ after coming from other languagues, and I cannot for the life of me comprehend statements that use "<<" and ">>".  I know it is simple, but it confuses me every time.
The book I'm using made a really good recommendation to read const declarations from right to left.  Is there any similar method for "<<" and ">>"?

A:

On the phone, back when I was a consultant frequently needing to "read aloud" C++ code to clients' employees on the phone, I (explaining once or twice, then they got it) read "input" operator >> as "absorb" and "output" operator << as "emit".  "get" and "put" would work just as well if they didn't conflict with alas-too-common other uses.  But that doesn't seem to have much to do with right-to-left vs left-to-right, just with your Q's title about "reading aloud" -- "cin absorb x" or "essteedee cout emit blach emit essteedee endl" kinds of "reading code aloud" (e.g. on the phone)!-)


Q:

How to make a prompt box input invoke a function?

How do I get rid of the button onclick="clickMe()" and just have the input from the prompt box execute the function?
I need the input from a prompt box to invoke the if statement, i think?
<!DOCTYPE html>

<title>Demo</title>

This is an example on DOM

    weekdays

Monday

Tuesday

Wednesday

Thursday

Friday

    weekends

Saturday

Sunday

<button onclick="clickMe()">Try it</button>

A:

If I understand correctly, you want the prompt to jump when the page is loaded, and then execute the code in "clickMe" (without the prompt) once the user has input a value?
In that case, you need to run the prompt after the page has loaded. You can see an example here:
http://jsfiddle.net/7a6e9r2f/1/
Note that jsfiddle automatically calls the javascript code at the bottom after the page has been loaded. In your case, you need to add

to your html so that the onLoaded function is called.


Q:

Why is this true for any x and y where x and y are whole numbers?

$x,y,z ∈ Z$
$∀x∀y∃z((x < z) ⇒ (x ≥ y))$
We know that to prove it wrong, we just have to find a counterexample. That means we have to find $T⇒F$. If we have: $x=2$. Sure, there exists a z that is larger than x. But why is it given that x also then is larger than or equals to y? Can't we just set $z=5, y=1$ and have a counterexample?

A:

your proposition is equivalent to
$\forall (x,y)\in \mathbb Z^2$ there exists $z\in \mathbb Z$ such that
$x\geq z$ or $x\geq y$.
It is always true if we take $z=x-1$.


Q:

Implementing repository pattern

As per this tutorial on asp.net, it shows this code:
using System;
using ContosoUniversity.Models;

namespace ContosoUniversity.DAL
{
    public class UnitOfWork : IDisposable
    {
        private SchoolContext context = new SchoolContext();
        private GenericRepository<Department> departmentRepository;
        private GenericRepository<Course> courseRepository;

        public GenericRepository<Department> DepartmentRepository
        {
            get
            {

                if (this.departmentRepository == null)
                {
                    this.departmentRepository = new GenericRepository<Department>(context);
                }
                return departmentRepository;
            }
        }

        public GenericRepository<Course> CourseRepository
        {
            get
            {

                if (this.courseRepository == null)
                {
                    this.courseRepository = new GenericRepository<Course>(context);
                }
                return courseRepository;
            }
        }

        public void Save()
        {
            context.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

Do I have to write code every time I want add a new database table?  For instance, if I wanted to add a StudentsRepository, I would have to do this (?):
private GenericRepository<Student> studentRepository;

public GenericRepository<Student> StudentRepository
{
    get
    {

        if (this.studentRepository == null)
        {
            this.studentRepository = new GenericRepository<Student>(context);
        }
        return studentRepository;
    }
}

What if my database has 50 tables?  Do I have to write this code for all 50!?

A:

The answer to your question is "yes", the unit of work should contain properties to access all possible repositories.
If it bothers you to write code, create a T4 template and let the class be generated automatically.


Q:

Distinct roots of a function involving an integral

Find the total number of distinct root for $x\in [0,1]$ for which $$\int_0^x\dfrac{t^2}{t^4+1}dt =2x-1$$

The answer is $1$  but I am not able to proceed.

A:

Sketch:
We want to find the number of zeroes of the function
$$f(x)=\int_0^x\frac{t^2}{t^4+1}\,dt-2x+1$$
in the interval $[0,1]$.
We have
$$f'(x)=\frac{x^2}{x^4+1}-2$$
so $-2\le f'(x)\le -3/2$ for $0\le x\le 1$. This means that $f$ is decreasing, so it can have at most $1$ root.
Finally, note that $f(0)=1$ and
$$f(1)=1+\int_0^1f'(x)\,dx\le1+\int_0^1(-3/2)\,dx=-1/2<0$$
so $f$ changes sign in the interval $[0,1]$, and therefore it has a root there.

A:

Let
$$ F(x) = \int_{0}^{x} \left(2 - \frac{t^2}{t^4 + 1}\right)dt$$
We are looking for roots of $$F(x) = 1$$
Now we have the following inequality
$$ \frac{t^2}{t^4 + 1} \le \frac{1}{2}$$
(follows from $(t^2 -1)^2 \ge 0$)
Thus
$$F'(x) \ge \frac{3}{2}$$
and so $F(x)$ is increasing.
We also have that $$F(1) \ge \int_{0}^{1} \frac{3\ dt}{2} = \frac{3}{2}$$
And $F(0) = 0$
Thus there is exactly one root of $F(x) = 1$ in the interval $[0,1]$


Q:

Where do I handle asynchronous exceptions?

Consider the following code:
class Foo {
    // boring parts omitted

    private TcpClient socket;

    public void Connect(){
        socket.BeginConnect(Host, Port, new AsyncCallback(cbConnect), quux);
    }

    private void cbConnect(IAsyncResult result){
            // blah
    }
}

If socket throws an exception after BeginConnect returns and before cbConnect gets called, where does it pop up? Is it even allowed to throw in the background?

A:

Code sample of exception handling for asynch delegate from msdn forum. I beleive that for TcpClient pattern will be the same.
using System;
using System.Runtime.Remoting.Messaging;

class Program {
  static void Main(string[] args) {
    new Program().Run();
    Console.ReadLine();
  }
  void Run() {
    Action example = new Action(threaded);
    IAsyncResult ia = example.BeginInvoke(new AsyncCallback(completed), null);
    // Option #1:
    /*
    ia.AsyncWaitHandle.WaitOne();
    try {
      example.EndInvoke(ia);
    }
    catch (Exception ex) {
      Console.WriteLine(ex.Message);
    }
    */
  }

  void threaded() {
    throw new ApplicationException("Kaboom");
  }

  void completed(IAsyncResult ar) {
    // Option #2:
    Action example = (ar as AsyncResult).AsyncDelegate as Action;
    try {
      example.EndInvoke(ar);
    }
    catch (Exception ex) {
      Console.WriteLine(ex.Message);
    }
  }
}

A:

If the process of accepting a connection results in an error your cbConnect method will be called.  To complete the connection though you'll need to make the following call
socket.EndConnection(result);

At that point the error in the BeginConnect process will be manifested in a thrown exception.


Q:

URLs for deleted questions get SEO'd automatically - is this a security issue?

When a user visits the link of a deleted questions, he can still see the title in the address bar. For example, when I go to https://stackoverflow.com/q/1, which is a deleted question, it redirects the user to https://stackoverflow.com/questions/1/where-oh-where-did-the-joel-data-go, showing the question's title. Is this a (non-critical) security issue?

A:

I don't think this is really a bug. It's more of a showcase that "you can never truly delete what has been on the Internet", so status-bydesign. Even if a question is deleted from a Stack Exchange site, it might still be available via the Wayback Machine which not only stores its title but its entire content, including answers. Also, users with access to moderator tools can view the question, just as if it weren't deleted (the Help Center link contains some reasons why this is useful).
Note that questions which have been marked as spam, or rude/abusive, such as this one: https://meta.stackexchange.com/questions/327537 don't have their title restored.


Q:

How to change value in variable type tensor in tensorflow kernel code?

I am trying to change output values in ctx(OpKernelContext) in Compute function. I could check the values by tensor->flat<>() when the operation is performed by constant.
However, I can't find them when the operation is performed by a variable. If I do flat<>(), it returns segmentation error. I want to access the values of outputs in some operation which have some variable inputs.

A:

This is impossible to reproduce with more detail about what you tried.
That said, directly accessing the content of variable tensors shouldn't lead to a segfault. What does is if you try to dereference a pointer to GPU memory in a CPU kernel, which might be what is happening here.


Q:

Dynamically invoke object

I have an object :
const Foo = {
  bar: function(baz) { ... }
}

I want to do something like:
let x = 'Foo';
let y = 'cookies';

x.bar(y);

I tried using eval: eval(x + '.bar' + '(' + y + ')'); but it's not working.
I cannot use window, this is code will not run in a browser. Any suggestions are welcomed.

A:

const Foo = {
  bar: function(baz) {
    console.log(baz);
  }
}

let x = 'Foo';
let y = 'cookies';

eval(x).bar(y);


Q:

Going in production with Symfony 2

before going in production with Symfony 2 I noticed there are a lot of bundles that are loaded by the framework in AppKernel.php. The defaults are:
$bundles = array(
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        new Symfony\Bundle\SecurityBundle\SecurityBundle(),
        new Symfony\Bundle\TwigBundle\TwigBundle(),
        new Symfony\Bundle\MonologBundle\MonologBundle(),
        new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
        new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
        new Symfony\Bundle\AsseticBundle\AsseticBundle(),
        new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
        new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
    );

I use assetic, doctrine, twig, framework, monolog bundles. Can I safely remove the others so that the speed of loading will raise?

A:

You can safely remove the SwiftmailerBundle.
The other ones (SecurityBundle, SensioFrameworkExtraBundle, JMSSecurityExtraBundle) may be harder as they have relations and your bundles may also have dependencies.
I would go ahead and just remove one bundle, run my tests (or manually test, if you don't have some) and see what's happening. If everything works, you can remove the next one.
Make sure to delete the cache after each removal (just to be safe).


Q:

How to make a shallow copy of an array?

I pass a two-dimensional array as a property to my user control. There I store this values in another two-dimensional array:
int[,] originalValues = this.Metrics;

Later, I change values in this.Metrics. But now if I retrieve values from originalValues, I get the changed values from this.Metrics. How do I make a copy of the elements of this.Metrics and don't just get the reference of the array?

A:

I don't know where I got this from, but this works well for me.
public static class GenericCopier<T>    //deep copy a list
    {
        public static T DeepCopy(object objectToCopy)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, objectToCopy);
                memoryStream.Seek(0, SeekOrigin.Begin);
                return (T)binaryFormatter.Deserialize(memoryStream);
            }
        }
    }

A:

You can clone an array, which makes a copy of it:
int[,] originalValues = (int[,])this.Metrics.Clone();

A:

The crux of your problem is here:

There I store this values in another two-dimensional array

This is actually inaccurate. You are not creating a new array; you are setting your originalValues variable to the same array. For a more detailed explanation, see below.

The confusion expressed in the comments to Pieter's answer is due to some uncertainty surrounding the term "deep copy."
When it comes to copying objects, there's deep copying and shallow copying.
Deep copying involves making a copy of all the data belonging to an object, which means that if the object includes members which are themselves complex (for example, instances of user-defined reference types), those objects must be deep-copied as well (along with all of their members, and so on).
Shallow copying involves simply copying all of the fields from one object to another, which means that if the object includes reference types, only the references need to be copied (and so the copied references will be pointing to the same objects).
In the case of the code you've posted:
int[,] originalValues = this.Metrics;

... there's actually no copying of any objects at all. All you've done is copied a single reference, assigning the value of this.Metrics (a reference) to the variable originalValues (also a reference, to the very same array). This is essentially the same as a simple value assignment, like this:
int x = y; // No objects being copied here.

Now, the Array.Clone method makes, in fact, a shallow copy. But as Pieter pointed out, there's really no difference between a "shallow" or "deep" copy of an array of integers, since integers are not complex objects.
If you had something like this:
StringBuilder[,] builders = GetStringBuilders();
StringBuilder[,] builderCopies = (StringBuilder[,])builders.Clone();

..., you'd end up with a whole new array (a copy, yes), but one containing all of the same StringBuilder objects (so a shallow copy). This is where deep versus shallow copying comes into play; if you wanted a new array containing copies of all of the StringBuilder objects from builders, you'd need to make a deep copy.


Q:

Unable to create table with foreign key

  private static final String MINDMAPS_TABLE_CREATE =
        "create table mindmaps (_id integer primary key autoincrement, "
                + "title text not null);";

  private static final String BUBBLES_TABLE_CREATE =
    "create table bubbles (_id integer primary key autoincrement, "
    + "title text not null), " +
            "_bmid integer, " +
            " FOREIGN KEY (_bmid) REFERENCES mindmaps (_id))";

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(MINDMAPS_TABLE_CREATE);
        db.execSQL(BUBBLES_TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS bubbles");
        db.execSQL("DROP TABLE IF EXISTS mindmaps");
        onCreate(db);
    }
}

I am get exception as follows:
 Caused by: android.database.sqlite.SQLiteException: near ",": syntax error (code 1): , while compiling: create table bubbles (_id integer primary key autoincrement, title text not null), _bmid integer,  FOREIGN KEY (_bmid) REFERENCES mindmaps (_id))
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)

What is wrong with the statement?

A:

You have a superfluous closing paren in your create table statement:
create table bubbles (_id integer primary key autoincrement,
    title text not null),
-----------------------^
    bmid integer,
    FOREIGN KEY (_bmid) REFERENCES mindmaps (_id))

If you remove it, the code should work.
Also, auto_increment has a underscore.
Here is a SQL Fiddle with the working code.
create table mindmaps (
    _id integer primary key auto_increment,
    title text not null
);

create table bubbles (_id integer primary key auto_increment,
    title text not null,
    _bmid integer,
    FOREIGN KEY (_bmid) REFERENCES mindmaps (_id)
);