Q:

Jconsole applet monitoring : Which process to monitor?

I want to monitor a java applet for memory usage, using jconsole in Windows, and i would like to find out which process is the one that i should focus in.

On the image i posted appear two processes which jconsole is able to connect to.
I am 100% sure that no other java process is executed except for a firefox instance running the applet.
The empty named process (PID 5152) is firefox.exe, and the "sun.plugin2.manin..." (PID 5628) named one is java.exe, according to windows task manager.
So which one should i monitor?
Thanks in advance.

A:

You should connect to the process starting with 'sun.plugin2'. The firefox process is the parent of the 'sun.plugin2' process.


Q:

Turn cron job commands into executable script that can run manually

I was running my crontab that backups some folders, but since then, I have started the practice of shutting down my computer at night, so I find that they do not run...go figure right? :-)
So my plan B is to create an icon that is placed on my desktop that executes an executable script file. Maybe something like backup.sh etc. So I can run the commands manually BEFORE I shut down the computer.
What is the best practice way to do this? Here is the crontab commands:
44 4 * * * /usr/bin/rsync -av --delete /var/www/html /media/stan/Seagate\ Expansion\ Drive/backups/
33 3 * * * /usr/bin/rsync -av --delete /home/stan/documents /media/stan/Seagate\ Expansion\ Drive/backups/
02 2 * * * /usr/bin/rsync -av --delete /var/backups /media/stan/Seagate\ Expansion\ Drive/backups/
44 1 * * * mysqldump -u root -ppassword --all-databases | gzip > /media/stan/Seagate\ Expansion\ Drive/backups/mysql/mysqlbak-$(date "+\%Y-\%m-\%d_\%H:\%M:\%S").sql.gz

A:

Create some scripts

sudo nano /usr/local/bin/rsync_html
#!/bin/bash
/usr/bin/rsync -av --delete /var/www/html /media/stan/Seagate\ Expansion\ Drive/backups/

sudo nano /usr/local/bin/rsync_documents
#!/bin/bash
/usr/bin/rsync -av --delete /home/stan/documents /media/stan/Seagate\ Expansion\ Drive/backups/

sudo nano /usr/local/bin/rsync_backups
#!/bin/bash
/usr/bin/rsync -av --delete /var/backups /media/stan/Seagate\ Expansion\ Drive/backups/

sudo nano /usr/local/bin/backup_mysql
#!/bin/bash
mysqldump -u root -ppassword --all-databases | gzip > /media/stan/Seagate\ Expansion\ Drive/backups/mysql/mysqlbak-$(date "+\%Y-\%m-\%d_\%H:\%M:\%S").sql.gz

Make the scripts executable
sudo chmod +x /usr/local/bin/rsync_html
sudo chmod +x /usr/local/bin/rsync_documents
sudo chmod +x /usr/local/bin/rsync_backups
sudo chmod +x /usr/local/bin/backup_mysql

Change your crontab
44 4 * * * /usr/local/bin/rsync_html
33 3 * * * /usr/local/bin/rsync_documents
02 2 * * * /usr/local/bin/rsync_backups
44 1 * * * /usr/local/bin/backup_mysql

Create some desktop files

nano ~/.local/share/applications/scrip1.desktop
[Desktop Entry]
Version=1.0
Type=Application
Name=rsync html
Exec=/usr/local/bin/rsync_html
Icon=
Categories=
Terminal=false
StartupNotify=true

nano ~/.local/share/applications/scrip2.desktop
[Desktop Entry]
Version=1.0
Type=Application
Name=rsync documents
Exec=/usr/local/bin/rsync_documents
Icon=
Categories=
Terminal=false
StartupNotify=true

nano ~/.local/share/applications/scrip3.desktop
[Desktop Entry]
Version=1.0
Type=Application
Name=rsync backup
Exec=/usr/local/bin/rsync_backups
Icon=
Categories=
Terminal=false
StartupNotify=true

nano ~/.local/share/applications/scrip4.desktop
[Desktop Entry]
Version=1.0
Type=Application
Name=backup mysql
Exec=/usr/local/bin/backup_mysql
Icon=
Categories=
Terminal=false
StartupNotify=true


Q:

Android: Attempting to switch between two Images and display them as the same size

So, basically, I just want to display an image, and when that image is clicked, I want to replace it with another image (and go back and forth between the two images onClick).  This works fine, but I want to display them as the exact same size, but no matter what I try, they're not appearing as the same size on screen.
Here's my java file:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final ImageView baneling = (ImageView) findViewById(R.id.bane);
    baneling.setTag("alive");
    baneling.setClickable(true);
    baneling.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(baneling.getTag().equals("alive"))
            {
                baneling.setImageResource(R.drawable.banelingexplosion);
                baneling.setTag("dead");
                resizeImage(baneling);
            }
            else
            {
                baneling.setImageResource(R.drawable.baneling);
                baneling.setTag("alive");
            }
        }
    });
}

public void resizeImage(ImageView v)
{
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT);
    v.setLayoutParams(layoutParams);
}

Here's my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dip" >
    <ImageView
            android:id="@+id/bane"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/baneling" />
</LinearLayout>

I've tried a ton of things and have successfully resized the images, but can never get them to be the same size, even why I explicitly assign them numerical pixel values in the xml and in the .java.

A:

Setting the android:scaleType="fitXY" attribute in your ImageView will make sure your image fills the entire bounds of the ImageView. That should help with explicitly setting the width and height of your image.
Nice Starcraft theme, by the way.


Q:

Merging two event loops (Cherrypy and Wxpython)

Okay, I have an application written with cherrypy, and I want to build a wxpython gui for it. The problem is that both modules use a close loop for event handling, which (I assume) means while one is running the other will be locked.
I asked for some advice and it was suggested that I merge the two event loops rather than using the stock entrypoints (quickloop() for cherrypy and MainLoop() for wx)
The problem is I have no idea how to do this. Any advice would be greatly appreciated.

A:

You already asked the same question here: cherrypy and wxpython, and I gave you the best response you're going to find anywhere there, which was voted up and you approved, apparently. Why are you asking again?


Q:

My twitter button says "Tweeten"

I put a twitter button on my website to allow people to easily tweet pages.
The weird thing is the button says "Tweeten".  Is this a language thing?  I'm set to English NA on my computer.  I'd like it to say "Tweet".
Here's an example: http://www.trainerroad.com/cycling/rides/41452
Here's the script/HTML on the page:
Tweet

A:

Its because your html language is set to nl (i.e. Dutch).
See the first line of your markup.

Either change that to en (English) i.e.

or you can force twitter to display English (i.e. Twitter) by,
Tweeter

See the attribute data-lang


Q:

How do I aggregate feeds together in a string and then parse them?

I am trying to aggregate a few youtube feeds, concatenate them, and then parse the feeds.
When I parse the individual feed on their own, I have no trouble and the code seems to work.  However, when I try to aggregate the feeds as one long string and then use etree.fromstring(aggregate_partner_feed), I get an error.  The error I get is ParseError: unbound prefix and the etree line (referenced earlier) is given as the error.  Any advice on how to fix this?
aggregated_partners_list = [cnn, teamcoco, buzzfeed]

i = 1
number_of_partners = len(aggregated_partners_list)
aggregate_partner_feed = ''

for entry in aggregated_partners_list:
    #YOUTUBE FEED
    #download the file:
    file = urllib2.urlopen('http://gdata.youtube.com/feeds/api/users/'+entry+'/uploads?v=2&max-results=50')
    #convert to string:
    data = file.read()
    #close file because we dont need it anymore:
    file.close()

    if i == 1:
        #remove ending </feed>
        data = data[:-7]

    if i>1 and i != number_of_partners:
        data = data[data.find('<entry'):]
        data = data[:-7]
        #remove everything before first <entry> in the new feed and the last </entry>

    #if last, then only remove everything before first <entry>
    if i == number_of_partners:
        data = data[data.find('<entry'):]

    #append the current feed to the existing feed
    aggregate_partner_feed += data

    #increment the counter
    i=i+1

print isinstance(data, basestring)                      #returns true
print isinstance(aggregate_partner_feed, basestring)    #returns true

#apply the parsing to the aggregated feed

#entire feed
root = etree.fromstring(aggregate_partner_feed)     #this is the line that give an error
#all entries
entries = root.findall('{http://www.w3.org/2005/Atom}entry')
#more code that seems to work...

A:

I parsed each feed individually and then used .append instead of concatenating the strings together and then parsing.


Q:

How to convert timestamp to date in php using date() without warping data?

I am using the php function date() to take a timestamp and turn it into a readable date.  It is stored under type=timestamp, function=now in mysql, and the timestamp I'm using reads "2013-12-17 16:23:00" in the database.  And it can echo out perfectly using $date1.  However, when I try to convert it using this code:
echo date('m/d/Y, $date1)
It turns into "12/31/1969" on the page.  I have no idea why.

A:

To convert a MySQL timestamp you'll need to make use of the strtotime function
date('m/d/Y', strtotime($date1));

The function strtotime will take must formats of date/timestamp and convert it into a unix timestamp which can then be converted to another readable format using date(). Reference: http://php.net/strtotime
The above works, but it's not to say that it's the best way of doing so, I'd be happy to hear alternatives.
The date you're getting is because date() expects a unix timestamp (seconds that have passed since 1/1/1970), and I assume that your web server is configured to a UTC-, so you're getting the day before. It's an annoying bug that can come from the way that MySQL handles timestamps.


Q:

C# - is this possible to declare a class where all fields are wrappers of another class's fields?

Please feel free to modify the title, I couldn't come up with any better one =\
Given the following example class
public class Person
{
    public string Name;
    public int ID;
    public string City;
}

I need to create another mirror class, where every field is actually a wrapper of the original class:
public class PersonMirror
{
    public FieldWrapper<string> Name;
    public FieldWrapper<int> ID;
    public FieldWrapper<string> City;
}
public class FieldWrapper<T>
{
    public T Value;
    public bool someBool;
    public int someCounter;
    // ..whatever
}

The thing is, I have many classes to mirror, and some of them have many fields! Moreover, the original class may be changed from time to time (add / remove / rename field), and every change must be applied to the mirrored class - not a good practice for maintainability.
My question is - is there a type safe way automate the decleration (rather then creation, such as generated code) of such mirrored classes?
EDIT:
Let's start from the beginning. In our SOA system, there is a resource access service (serviceX) responsible for updating items in the DB. Other services send it the modifications they would like to perform - in json that would be something like: {ID: 123, name : "myNewName"}. serviceX would then build an update query to send to the DB. However, there is a requirement that serviceX will expose a POCO interface, so that the interface will be language independent, so expressions such as (p=> p.name, "MyNewName") are not allowed. Another requirement is type safety, so json is not allowed either. Currently, the above solution is the best one we came up to answer all the requirements. Any better solutions are more then welcome!

A:

IMO, there's no way to do what you want, except code generation.
Approaches for code generation could differ (this maybe source code generation + compilation, emitting IL code, either your own or existing one), but this is the only way.


Q:

Update one column value with another column value using SQL Query

I have a table which has three columns with integer values. In first two columns I have some values. Now I need to update the third column with the value which is minimum of other two columns.
I have tried using
update table set col3 = (SELECT CASE WHEN (col2 is null OR col1 < col2 )
THEN col1
ELSE col2
END AS col3
FROM  table
WHERE col1 is not null or col2 is not null)`.

But I am getting an error like below:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

A:

You can use LEAST in order to update:
UPDATE mytable
SET col3 = LEAST(COALESCE(col1, col2), COALESCE(col2, col1))
WHERE col1 IS NOT NULL OR col2 IS NOT NULL

You don't have to query your table table to get col2, col1 values. You can use them directly in the SET part of your UPDATE query.
Note: COALESCE is used to handle NULL values. If both col1, col2 are NULL then col3 is also set to NULL.
In SQL Server you can use:
UPDATE mytable
SET col3 = CASE
              WHEN col2 IS NULL OR col1 < col2 THEN col1
              ELSE col2
           END
WHERE col1 IS NOT NULL OR col2 IS NOT NULL

In SQL Server 2012, or later, you can use IIF:
UPDATE mytable
SET col3 = IIF(col2 IS NULL OR col1 < col2, col1, col2)
WHERE col1 IS NOT NULL OR col2 IS NOT NULL

Demo here


Q:

Markup glitch: “Tagline to show on mouseover”

I just saw this ad:

on a SF&F page (it was here, although I doubt that it matters).
I moved my mouse pointer over it
and the text “Tagline to show on mouseover” appeared.

Obviously that’s a template value that was meant to be replaced.
Browser is Internet Explorer 11.

A:

This is because the person who posted the ad on our Community Promotion Ads page didn't include a proper tagline other than the generic one. Here's his post in edit mode:

I just edited the tagline to "Find canon Star Wars information", so this is now fixed.


Q:

How to user pushViewController page transition in mainViewController

I want to implement transition of this like only in code.
gif link
But i seem not using the navigationController in the navigationBarViewController of Material.
So pushViewController method is not available for page transition?
this code is use Material
  import UIKit
  import Material

  /// MaterialCollectionViewDelegate methods.
  extension FeedViewController: MaterialCollectionViewDelegate {
      /// Executed when an item is selected.
      func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
          print(indexPath)
          // --------------------------------My Question--------------------------------------//
          let vc = DetailViewController()
          self.navigationBarViewController?.pushViewController(vc, animated: true)
          // ----------------------------------------------------------------------//
      }
  }

  class FeedViewController: UIViewController {
      private var collectionView: MaterialCollectionView = MaterialCollectionView()

      override func viewDidLoad() {
          super.viewDidLoad()
          prepareView()
          prepareCollectionView()
      }

      override func viewWillLayoutSubviews() {
          super.viewWillLayoutSubviews()
          collectionView.frame = view.bounds
          collectionView.reloadData()
      }

      override func viewWillAppear(animated: Bool) {
          super.viewWillAppear(animated)
          navigationBarViewController?.navigationBarView.titleLabel?.text = "Home"
      }

      /// Prepares view.
      private func prepareView() {
          view.backgroundColor = MaterialColor.grey.lighten4
      }

      /// Prepares the collectionView
      private func prepareCollectionView() {
          collectionView.dataSource = self
          collectionView.delegate = self
          collectionView.spacingPreset = .Spacing1
          collectionView.contentInsetPreset = .Square1
          collectionView.registerClass(MaterialCollectionViewCell.self, forCellWithReuseIdentifier: "MaterialCollectionViewCell")

          // To avoid being hidden under the hovering MenuView.
          view.addSubview(collectionView)
      }
  }

  extension FeedViewController: MaterialCollectionViewDataSource {
      /// Retrieves the items for the collectionView.
      func items() -> Array<MaterialDataSourceItem> {
          return [
              MaterialDataSourceItem(
                  data: [
                      "title": "Summer BBQ",
                      "detail": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
                      "date": "February 26, 2016"
                  ],
                  width: 150, // Applied when scrollDirection is .Horizontal
                  height: 150 // Applied when scrollDirection is .Vertical
              ),
              MaterialDataSourceItem(
                  data: [
                      "title": "Birthday gift",
                      "detail": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
                      "date": "February 26, 2016"
                  ],
                  width: 250, // Applied when scrollDirection is .Horizontal
                  height: 150 // Applied when scrollDirection is .Vertical
              )
          ]
      }

      /// Number of sections.
      func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
          return 1
      }

      /// Number of cells in each section.
      func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
          return items().count
      }

      /// Retrieves a UICollectionViewCell.
      func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
          let c: MaterialCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("MaterialCollectionViewCell", forIndexPath: indexPath) as! MaterialCollectionViewCell

          let item: MaterialDataSourceItem = items()[indexPath.item]

          if let data: Dictionary<String, AnyObject> =  item.data as? Dictionary<String, AnyObject> {

              var cardView: CardView? = c.contentView.subviews.first as? CardView

              // Only build the template if the CardView doesn't exist.
              if nil == cardView {
                  cardView = CardView()

                  c.backgroundColor = nil
                  c.pulseColor = nil
                  c.contentView.addSubview(cardView!)

                  cardView!.pulseScale = false
                  cardView!.divider = false
                  cardView!.depth = .None

                  let titleLabel: UILabel = UILabel()
                  titleLabel.textColor = MaterialColor.grey.darken4
                  titleLabel.font = RobotoFont.regularWithSize(18)
                  titleLabel.text = data["title"] as? String
                  cardView!.titleLabel = titleLabel

                  let detailLabel: UILabel = UILabel()
                  detailLabel.numberOfLines = 2
                  detailLabel.textColor = MaterialColor.grey.darken2
                  detailLabel.font = RobotoFont.regular
                  detailLabel.text = data["detail"] as? String
                  cardView!.detailView = detailLabel

                  c.contentView.addSubview(cardView!)
              } else {
                  cardView?.titleLabel?.text = data["title"] as? String
                  (cardView?.detailView as? UILabel)?.text = data["detail"] as? String
              }

              cardView!.frame = c.bounds
          }

          return c
      }
  }

A:

In Material 1.36.0, there are two new classes, NavigationBar and NavigationController. NavigationController is a subclass of UINavigationController, so all the features for pushing and popping UIViewControllers on the stack of items is the same, while getting the ability to customize the controller's look and feel with ease.
The example App project shows how to use this.


Q:

Setup a TCP listener in PHP

We're using a system at the moment that takes an incoming JSON request over TCP and responds using JSON too. Currently I've set up my socket like so in PHP:
$socket = fsockopen($host, $port, $errno, $errstr, $timeout);

if(!$socket)
{
  fwrite($socket, $jsonLoginRequest); // Authentication JSON

  while(json_decode($loginResponse) == false) // We know we have all packets when it's valid JSON.
  {
     $loginResponse .= fgets($socket, 128);
  }

  // We are now logged in.

  // Now call a test method request
  fwrite($socket, $jsonMethodRequest);

  while(json_decode($methodResponse) == false) // We know we have all packets when it's valid JSON.
  {
     $methodResponse .= fgets($socket, 128);
     echo $methodResponse; // print response out
  }

  // Now we have the response to our method request.
  fclose($socket);
}
else
{
  // error with socket
}

This works at the moment, and the server responds to the method request. However, some methods will respond like this to acknowledge the call, but will also respond later on with the results I'm after. So what I really need is a TCP listener. Could anyone advise how I could write a TCP listener using fsock like I have above?
Thanks

A:

To create a listening socket use the following functions:

socket_create_listen (this one is cool)
socket_accept

I'm not shure if fwrite()/fread() are working with those sockets otherwise you have to use the following functions:

socket_recv
socket_send

Message-loop
I have now written some function to read a single JSON responses with the assumption that multiple responses are separated by CRLF.
Here's how I would do it (assuming your php-script has unlimited execution time):
// ... your code ...

function readJson($socket) {
    $readData = true;
    $jsonString = '';
    while(true) {
        $chunk = fgets($socket, 2048);
        $jsonString .= $chunk;

        if(($json = json_decode($jsonString)) !== false) {
            return $json;
        } elseif(empty($chunk)) {
            // eof
            return false;
        }
    }
}

// ....
// Now call a test method request
fwrite($socket, $jsonMethodRequest);

$execMessageLoop = true;
while($execMessageLoop) {
    $response = readJson($socket);
    if($response === false) {
        $execMessageLoop = false;
    } else {
        handleMessage($socket, $response);
    }
}

function handleMessage($socket, $response) {
    // do what you have to do
}

Now you could implement the "handleMessage" function which analyses the response and acts to it.


Q:

Median using mobile window bash script

i need to create a file txt that contains a list of Median value that change
if i have a file like:

1
2
35
40
50

i want an output like

1
1.5
2
18.5
35

i tried picking up one number at the time from my input file then using sort but i didn't go far..
i hope i made myself clear, thank you!

A:

You could use awk to realize this. For example when you have your data in a file named in.txt:
 awk '{c[NR]=$1; asort(c); if (NR%2) {print c[(NR+1)/2]} else {print (c[(NR/2)]+c[(NR/2)+1]) / 2.0}}' < in.txt

results in the output
1
1.5
2
18.5
35


Q:

What is the purpose of prewedding photography session?

many of the wedding photographers offer pre wedding sessions for the couple. I always wonder how is it helpful? it make the final day's photography better?

A:

My wedding photographer did an "engagement " shoot as part of the package. This served a few purposes from our point of view.

To get to know each other a bit, so photographer and couple will be comfortable with each other on the day
To understand what kind of shots the couple favour, so these can be prioritised
For the couple to get used to being natural with a camera pointing at them. Most people aren't used to this so it's good to get a go at it when the results don't matter as much.
Of course, for the couple to get some lovely photos showing how much in love they are a short time before their big day.

We aren't the sort of people who generally like being photographed so we weren't sure what to expect,  but our engagement shoot was amazing fun and well worth it to feel more at ease with the photographers on the day.


Q:

How do I go about removing all digits and all punctuations in a string?

How do I go about removing all digits and all punctuations in a string using regex?
For example:
  From Eric-Has555-Books to EricHasBooks
I am trying to use String.replace(), but my regex below doesn't work:
str = 'Eric-Has555-Books'
reg = /[0-9]-/g;
str.replace(reg, '');

A:

You can use [^a-z] which says "Remove everything that isn't a letter". This is also known as Negated Character Classes

let r = 'Eric-Has555-Books'.replace(/[^a-z]/gi, '')

console.log(r)


Q:

Parse all substrings before a pattern without a loop?

I have a long string that consists of many numbers separated by spaces (and sometimes there's even a new line thrown in there). I'd like to go through the string and append all the numbers to a new list that come before the start of 0.000000000000000000e+00 numbers. So here's a sample of my string:
my_string = '1.249132165057832031e+13 1.638194600635518555e+13 2.127995187558799219e+13 2.744617593148214062e+13 -2.558800658636701519e+28 5.918883595148564680e+30 3.603563681248702509e+31 4.325917213186498068e+31 4.911908042151239481e+31 4.463331378152286632e+31 3.684371076399113503e+31 2.500614504012405068e+31 9.997365425073173512e+30 -7.046725649106466938e+30 -2.192076417151744811e+31 -2.531287564917444482e+31 -6.962936418905874724e+30 3.281685507310205847e+31 9.241630178064907840e+31 1.730544785932614751e+32 2.619210949875333106e+32 2.984440142196566918e+32 8.964375812060072923e+31 -8.515727465135046667e+32 -3.425309034394939997e+33 -8.145884847188906515e+33 -9.922370830834364410e+33 -2.119464668318252366e+28 -1.689726703118075140e+27 1.440101653069986610e+26 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 6.186324149659251562e+13 8.113154959294240625e+13 1.053889122977165625e+14 1.359271226298647969e+14 -2.097046363337115528e+28 4.850777756495711585e+30 2.953274256558218597e+31 3.545273642763729060e+31 4.025456872055449111e+31 3.657581460085835446e+31 3.018816679659856350e+31 2.048223110003727437e+31 8.176806147340775115e+30 -5.796250740354887641e+30 -1.798839398031696094e+31 -2.076444435341100150e+31 -5.711669151245612857e+30 2.691583747083509247e+31 7.579958708961477309e+31 1.419395486743453834e+32 2.148287875274468622e+32 2.447859658750551118e+32 7.352862842410293685e+31 -6.984595303325589259e+32 -2.809449882735912952e+33 -6.681296633318354125e+33 -8.138406580426555140e+33 -1.740744048703962454e+28 -1.411749034480591280e+27 8.079362883576220633e+25 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00'

and from this string, all I want in the end would be:
new_list = ['1.440101653069986610e+26', '8.079362883576220633e+25']

I was thinking I'd use regex, but this seems a little tricky since I there are a bunch of 0.000000000000000000e+00 occurrences grouped together and I only want the nonzero number right before the first zero occurrence. I also cannot assume that there's always an equal number of zeros grouped together.
I also thought of splitting on the spaces and iterating through, but my full string is actually far too long to do this efficiently. How can I do this?

A:

You can use negative lookbehind assertion:
In [55]: re.findall(r'(\S+)(?<!0\.000000000000000000e\+00)\s+0\.000000000000000000e\+00', my_string)
Out[55]: ['1.440101653069986610e+26', '8.079362883576220633e+25']

Using negative lookahead assertion, the regex could be refined to improve performance, as mentioned in comment by @revo:
([-+]?\d\.(?!0+e\+0+)\S+)\s+(?:0\.0+e\+00\s*)+

Live demo


Q:

Refactoring code to display an alertbox (what would be a proper approach?)

I'm working on iOS project, and one thing I notice is that I'm creating an alertbox again and again whenever I need to display an error. I would like to refactor that code to remove redundancy. My question is : is creating an error handling class a proper approach to refactoring for this particular scenario? For instance, I would create a following class
class ErrorHandler {

     func ShowAlertBox(Title: String, Message: String, ViewController: UIViewController) {

          let alertController = UIAlertController(title: Title, message: Message), preferredStyle: .Alert)
          let doneAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label to cancel sign-in failure."), style: .Cancel, handler: nil)
    alertController.addAction(doneAction)
          ViewController.presentViewController(alertController, animated: true, completion: nil)
     }
}

And call like this :
instanceofErrorHandler.ShowAlertBox("Error","Log In Error", SignInViewController)

A:

I suspect there's a lot of differing opinions on how to handle this scenario and I don't see any problems with your approach. That said, the way I do it is to create an Extension called ViewControllerUtilities and put all of my common functions in there:
protocol ViewControllerUtilities {}

extension ViewControllerUtilities where Self: UIViewController {
    func showAlert(_ title: String = "Error", message: String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
        present(alertController, animated: true, completion: nil)
    }
}

FYI, I also have functions in there to check if the network is reachable. Then I get all this functionality simply by adding ViewControllerUtilities to the list of protocols that my view controller conforms to:
class MyViewController: UIViewController, ViewControllerUtilities {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        showAlert("Error", message: "Sorry,  had an error.")
    }

}


Q:

Trouble with deserialization in mono

Anyone have any idea why the following XML generated by a data contract serializer in C# works just fine in Windows but not under Linux on Mono?
The XML:
<Message i:type="UserMessage" xmlns="http://schemas.datacontract.org/2004/07/NetTunnel"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><type>UserMessage</type>
<nick>Unnamed</nick><services><Service><enabled>true</enabled><port_ranges i:nil="true"/>
<service_name>vent</service_name></Service></services><state>Created</state>
<userid>1</userid></Message>

The error:
Unhandled Exception: System.Runtime.Serialization.SerializationException: Deserializing
type 'System.Object'. Expecting state 'EndElement'. Encountered state 'Element' with
name 'enabled' with namespace 'http://schemas.datacontract.org/2004/07/NetTunnel'.

It also gives me an error if there are no services listed (xml tag <services/>). The services variable is of type List<Service>. Is this just a type Mono can't handle? Would another type be more appropriate? Or is it something else entirely?

A:

From the comments, you don't need WCF and just want to share data. In which case, I would look at protobuf-net. I'm quite biased (since I'm the author), but it is free (with source), so I'm not recommending it from self gain. Simply; it is a fast, portable serialization API modelled after google's "protocol buffers" data format. Very fast to process (typically much faster than xml, for example) and pretty small on the wire.
If you already using data-contracts, you might be able to tweak them simply by adding unique Order values (it uses this as a numeric identifier):
[DataContract]
public class Foo {
    [DataMember(Order = 1)]
    public int Id {get;set;}

    [DataMember(Order = 2)]
    public string Name {get;set;}
}

(or you can use the specific protobuf-net attributes)
The full source is available, and it works on Mono, regular .NET, CF, etc.


Q:

jQuery vs. jQuery Mobile for DIY mobile UI layer?

I'm about to start building UI widgets for our mobile web site. The main factors are:

they are relatively unique interactions, so it doesn't seem practical to start with an off-the-shelf widget library (jQuery UI, for isntance)
we need to support a wide range of browsers/mobile OSes

The team seems happy to go down the jQuery path, which I am happy about. The next question is which flavor? What do I need to consider to decide if we should go with a minimum jQuery library or to go with jQuery Mobile.
Perhaps a better way to ask the question: aside from the pre-built UI components in jQuery Mobile, are there advantages to using jQuery mobile over jQuery in the mobile space?
UPDATE:
I think I have a better way to ask this question. I'd like to use the 'stripped down' version of jQuery but have the touch-events of jQuery Mobile (but don't need the whole jQuery Mobile UI layer). Based on that, what's the approach I should be taking?
I like having the touch-centric events of jQuery Mobile, but won't be using any of the default UI elements/framework. I like the fact that one can use jQuery sans any UI elements, but it doesn't have the touch events (or does it?)

A:

If you don't use the built-in UI components, the biggest things that you gain in jQuery Mobile are the new events. There are events for things like gestures, taps, and orientation changes.
See: http://jquerymobile.com/demos/1.0a4.1/docs/api/events.html
You also gain a ton of built-in CSS classes that define things like screen size, platform, and orientation.
I do recommend that you at least look at the pre-built components (especially for menus) as they are good looking and drastically decrease development time. There is also a CSS stylesheet (which admittedly seems weird if you are used to non-mobile jQuery) which helps format your page for mobile devices. If you don't use the pre-built components you are really missing out on a lot of jQuery Mobile.
Keep in mind that jQuery Mobile is in Alpha so there will be bugs.


Q:

substring(0,4) on jquery html giving null

This is my code:
var revista = $('#revistas_esp_1 option:selected').html();
var myname = revista.substring(1,3);
console.log(myname);
console.log(revista);

gets the html alright, but myname shows empty.
I have tried with substr aswell, same result. I don't get any error, just an empty log. I also have tried to use text() instead of html().

A:

It was a blank space issue, it got solved putting the indenting space in the php and not in the HTML.


Q:

How can I create a table in BigQuery with non-required fields?

I'm making a RESTful API in Go that writes rows in BigQuery. I'm using Google BigQuery package for Go.
In order to create the BigQuery scheme, I'm  infering the schema from a struct as described in the example.
The problem is that, the resulting schema has all the non-repeated fields as "Required", so that, when I want to upload a struct with null values, the null values are uploaded as empy fields...
This is an example of my struct:
type Stats struct {
    Name            string        `bigquery:"name"`
    LastName        int           `bigquery:"last_name"`
    PhoneNumber     string        `bigquery:"phone_number"`
}

This is an example of how the schema is created:
testSchema, err := bigquery.InferSchema(Stats{})
if err != nil {
    // TODO: Handle error.
}

And, if I upload a struct with only one field set:
rows := []*Stats{
    {Name: "testA"},
}

u := table.Uploader()
err2 := u.Put(ctx, rows)

The result is that, in BigQuery, the fields "last_name" and "phone_number" is an empty string "" instead of NULL

A:

For that, apparently you would have to use the specific BigQuery nullable types (NullInt64, NullFloat64, NullString, NullBool, NullTimestamp, NullDate, NullTime and NullDateTime).
Example using bigquery.NullBool: https://godoc.org/cloud.google.com/go/bigquery#ex-InferSchema--Tags


Q:

Concatenation of String and int types (on declaration!)

I wanted to give an unique ID number equal to the times an object of class ship has been created
therefore I tried this code I knew from java (but it doesn't work unfortunately)
Name is inherited by parent class vehicle
I would like an implementation that works in GNU c++ compiler (and declaration only)
#include <iostream>
static int id = 0;

class Ship:private Vehicle
{
    Ship()
    {
        id++;
        this->name="Pirate"+id;
    }
}

A:

// C++98

Ship() {
  std::ostringstream tmp;
  tmp << "Pirate" << ++id;
  name = tmp.str();
}

// C++11

Ship() : name("Pirate" + std::to_string(++id)) {}


Q:

How do I sort JavaScript strings by codePoint?

I am looking to sort objects by a string field that contains unicode characters. However, I want to sort the strings by code point, not by locale. So, here is an example, where JavaScript sorts objects so that \u24B7 and b are both considered the same character.
Incorrect sort order:
> [{name: 'a'}, {name: 'b'}, {name: 'd'}, {name: '\u24B7'}].sort((a,b)=> a.name.localeCompare(b.name))
[ { name: 'a' }, { name: 'b' }, { name: 'Ⓑ' }, { name: 'd' } ]

However, this is not what I want. I want the following sort order, where they are considered different characters. This is the default behavior when comparing strings and not including a comparator function.
Correct sorting order (notice that b and \u24B7 are no longer considered the same sort character):
> ['a','b','\u24B7','d'].sort()
[ 'a', 'b', 'd', 'Ⓑ' ]

In the real application, the strings will be more than one character and may contain multiple unicode chars and we want them sorted according to unicode number (ie- code point).
My question: is there a simple way to sort by code point for strings? I'd rather not re-implement a custom comparator for this.

A:

I usually do it like this:
let cmp = (a, b) => a > b ? 1 : a < b ? -1 : 0;

objects.sort((a, b) => cmp(a.name, b.name));

or rather
let sortBy = (a, f) => a.sort((x, y) => cmp(f(x), f(y)));

sortBy(objects, x => x.name);


Q:

Using hyphen and quote marks in composed term?

Possible Duplicate:
When is it necessary to use a hyphen in writing a compound word?

I want to write a term composed out of multiple words, and I would like to know whether I have to use hyphens or quotes.
Following options came to my mind:

'but he said' argument
'but he said'-argument
but-he-said argument
but-he-said-argument

A:

I would choose quotation marks without hyphenation:

…a “but he said” argument…

“But he said” functions not only as an adjective—it describes the kind of argument—but also as a quote, from one of the hypothetical arguers. Hyphens also make sense:

…a but-he-said argument…

But I think this is less readable. Regardless, I would not use a hyphen before argument.


Q:

Why does Firefox remove TR and TD strings when using innerHTML on the parent

I'm getting a HTML fragment back from an ajax call. I'm using jQuery and only want the TR within the fragment. Using jQuery selectors to find the TR yields nothing in Firefox, only IE.
So as a workaround I thought I might try
$(ajaxString).filter('form').first().html()

and also
$(ajaxString).filter('form').first()[0].innerHTML

Those two methods only worked in IE, in Firefox, the TR and TD elements are gone and only the span is returned. What's the problem and solution? :-)
<form method="post">

    stuff

<form>

A:

When Firefox error corrects invalid elements being wrapped around table rows, it places that element after the end of the table in the DOM.
i.e. it doesn't remove them when using innerHTML, it removes them when parsing the not-really-HTML in the first place.
The relationship between a form and a table can either be "The table is in a form" or "The form is in a table cell".


Q:

How to evaluate $\int^{2\pi}_0\frac{d\theta}{b^2\cos^2\theta + a^2 \sin^2\theta}$ for $a>0$ and $b>0$

How to evaluate $\int^{2\pi}_{0}\frac{d\theta}{b^2\cos^2\theta+a^2\sin^2\theta}$ for $a,b>0$

I came across this integral while solving a line integral problem . but it doesn't looks easier to integrate . I tried substitution of $\tan x$ .but i'm not sure tan can be used as the tan is discontinuous at $\pi/2$ i tried other substitution but none of them work.

A:

Your method works. We have
$$\begin{align*}
\int^{2\pi}_{0}\frac{\mathrm d\theta}{b^2\cos^2\theta+a^2\sin^2\theta}&=4\int^{\frac\pi 2}_{0}\frac{\mathrm d\theta}{b^2\cos^2\theta+a^2\sin^2\theta}\\&=4\int^{\frac\pi 2}_{0}\frac{\sec^2 \theta\mathrm d\theta}{b^2+a^2\tan^2\theta}\\
&=4\int^{\infty}_{0}\frac{\mathrm du}{b^2+a^2u^2}\\&=\frac4{ab}\arctan\left(\frac{au}{b}\right)\Big|^\infty_0\\&=\frac{2\pi} {ab}.
\end{align*}$$ Here's an another approach. We have
$$\begin{align*}
\int^{2\pi}_{0}\frac{\mathrm d\theta}{b^2\cos^2\theta+a^2\sin^2\theta}&=\int^{2\pi}_{0}\frac{\mathrm d\theta}{\frac{a^2+b^2}2+\frac{b^2-a^2}2\cos(2\theta)}\\&=\int^{2\pi}_{0}\frac{\mathrm d\theta}{\frac{a^2+b^2}2+\frac{b^2-a^2}2\cos\theta}\\
&=\frac{2\pi}{\sqrt{\left(\frac{a^2+b^2}2\right)^2-\left(\frac{b^2-a^2}2\right)^2}}\\
&=\frac{2 \pi}{ab}.
\end{align*}$$ Here, $$
\int^{2\pi}_{0}\frac{\mathrm d\theta}{\alpha+\beta\cos\theta}=\frac{2\pi}{\sqrt{\alpha^2-\beta^2}}, \quad \alpha>|\beta|\tag{*}
$$ is used. (See, for example, this earlier post. The first approach can be seen as a way of showing the integral $(*)$.)


Q:

PHP method can't return two dimensional array?

Hello I stuck on really strange thing.
I'm writing simple PHP MVC WebApp for school project and I can't return two dimensional array.
I solve this problem this way:
class Post{
    public $author;
    public $cat;
    public $table;
    function getPosts($cat = ""){
        dbstart();
        global $dbconn;
        empty($cat) ? $query = mysqli_query($dbconn, "SELECT * FROM pytania") : $query = mysqli_query($dbconn, "SELECT * FROM pytania WHERE cat = $cat");
        while($row = mysqli_fetch_assoc($query)){
        $output[] = $row;
        $this -> table = $output;
        dbstop();
        }
    }

}

It works perfectly when I'm calling property in controller
"poststable" => $post -> table

Gives me all four posts (two dimensional array with 4 rows) but I want to remove public $table property so I can directly call method like this way:
 "poststable" => $post -> getPosts($cat)

Unfortunately, when I change my method code with this:
return $output;

$data "poststable" Gives me only first post (array stores only one post)
Anyone has idea what I'm doing wrong? Thanks in advance for help!

A:

You need to build up the entire output in the while loop, after which you can return it. In addition, you should do your DB clean up outside the loop.
<?php
class Post{
    public $author;
    public $cat;
    function getPosts($cat = ""){
        dbstart();
        global $dbconn;

        empty($cat)
            ? $query = mysqli_query($dbconn, "SELECT * FROM pytania")
            : $query = mysqli_query($dbconn, "SELECT * FROM pytania WHERE cat = $cat");

        // Use an array as your return value
        $output = [];
        while($row = mysqli_fetch_assoc($query)){
            // Build up the array
            $output[] = $row;
        }

        // Do your clean up out here
        dbstop();

        // Now return the result
        return $output;
    }

}


Q:

How to handle ProcessEngineCdiException "Cannot resume task with id ..."

It may happen that the user wants to start a task that no longer exists.
Then the user trigger a exception.
   ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/qed].[Faces Servlet]] (http-localhost/127.0.0.1:8080-5) JBWEB000236: Servlet.service() for servlet Faces Servlet threw exception: org.camunda.bpm.engine.cdi.ProcessEngineCdiException: Cannot resume task with id 'a4291177-f7ba-11e4-90b2-62ef20524153', no such task.
    at org.camunda.bpm.engine.cdi.BusinessProcess.startTask(BusinessProcess.java:294) [camunda-engine-cdi-7.2.0.jar:7.2.0]
    at org.camunda.bpm.engine.cdi.BusinessProcess.startTask(BusinessProcess.java:313) [camunda-engine-cdi-7.2.0.jar:7.2.0]
...

How can I handle those exceptions?
I use the embedded camunda engine with JSF forms.

A:

This is not really camunda specific. If your UI is talking to a system that might fail or has illegal states, you have to catch the exception and display something useful for the enduser and/or check the precondition (task exists) before even allowing the UI operation.
In case of camunda, this can be achieved by keeping the tasklist up to date (server push, auto update) and checking the existence of the task before associating it with the camunda cdi context.


Q:

hp officejet 4500 detected by sane-find-scanner but not lsusb or Simple Scan in Ubuntu Lucid

I upgraded to ubuntu 10.04 from 8.04 recently. When I try to use Simple Scan it says "No scanners detected". sane-find-scanner detects my printer/scanner but lsusb does not. Also I am able to print from my printer so it's just a problem with the scanner and lsusb.
lsusb:
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 002: ID 045e:00db Microsoft Corp. Natural Ergonomic Keyboard 4000 V1.0
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
sudo sane-find-scanner:

# sane-find-scanner will now attempt to detect your scanner. If the
# result is different from what you expected, first make sure your
# scanner is powered up and properly connected to your computer.

# No SCSI scanners found. If you expected something different, make sure that
# you have loaded a kernel SCSI driver for your SCSI adapter.

found USB scanner (vendor=0x03f0 [HP], product=0x4712 [Officejet 4500 G510a-f]) at libusb:001:005
# Your USB scanner was (probably) detected. It may or may not be supported by
# SANE. Try scanimage -L and read the backend's manpage.

# Not checking for parallel port scanners.

# Most Scanners connected to the parallel port or other proprietary ports
# can't be detected by this program.
In var/log/syslog:
Nov  9 11:14:18 snoopy kernel: [40994.348199] usb 1-3: new high speed USB device using ehci_hcd and address 3
Nov  9 11:14:18 snoopy kernel: [40994.484270] usb 1-3: configuration #1 chosen from 1 choice
Nov  9 11:14:20 snoopy udev-configure-printer: add /devices/pci0000:00/0000:00:1d.7/usb1/1-3/1-3:1.1
Nov  9 11:14:20 snoopy kernel: [40996.551347] usblp0: USB Bidirectional printer dev 3 if 1 alt 0 proto 2 vid 0x03F0 pid 0x4712
Nov  9 11:14:20 snoopy kernel: [40996.551407] usbcore: registered new interface driver usblp
Nov  9 11:14:20 snoopy udev-configure-printer: parent devpath is /devices/pci0000:00/0000:00:1d.7/usb1/1-3
Nov  9 11:14:20 snoopy udev-configure-printer: Device vendor/product is 03F0:4712
Nov  9 11:14:20 snoopy udev-configure-printer: failed to claim interface
Nov  9 11:14:20 snoopy udev-configure-printer: invalid or missing IEEE 1284 Device ID
Nov  9 11:14:21 snoopy udev-configure-printer: add /devices/pci0000:00/0000:00:1d.7/usb1/1-3/1-3:1.1/usb/lp0
Nov  9 11:14:21 snoopy udev-configure-printer: parent devpath is /devices/pci0000:00/0000:00:1d.7/usb1/1-3
Nov  9 11:14:21 snoopy udev-configure-printer: MFG:HP MDL:Officejet 4500 G510a-f SERN:CN049F20C905H2 serial:CN049F20C905H2
Nov  9 11:14:23 snoopy kernel: [40999.240548] usb 1-3: usbfs: interface 1 claimed by usblp while 'usb' sets config #1
Nov  9 11:14:23 snoopy hp[4537]: io/hpmud/pp.c 627: unable to read device-id ret=-1
Nov  9 11:14:25 snoopy udev-configure-printer: SERN fields match
Nov  9 11:14:25 snoopy udev-configure-printer: URI match: usb://HP/Officejet%204500%20G510a-f?serial=CN049F20C905H2
Nov  9 11:14:25 snoopy udev-configure-printer: SERN fields match
Nov  9 11:14:25 snoopy udev-configure-printer: URI match: hp:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2
Nov  9 11:14:25 snoopy udev-configure-printer: Consider also queues with "/usb/lp0" or "/usblp0" in their URIs as matching
Nov  9 11:14:25 snoopy udev-configure-printer: URI of print queue: hp:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:25 snoopy udev-configure-printer: URI of detected printer: usb://HP/Officejet%204500%20G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:25 snoopy udev-configure-printer: Queue ipp://localhost:631/printers/Officejet_4500_G510a-f has matching device URI
Nov  9 11:14:25 snoopy udev-configure-printer: Re-enabled printer ipp://localhost:631/printers/Officejet_4500_G510a-f
Nov  9 11:14:25 snoopy udev-configure-printer: URI of detected printer: hp:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:25 snoopy udev-configure-printer: Queue ipp://localhost:631/printers/Officejet_4500_G510a-f has matching device URI
Nov  9 11:14:26 snoopy udev-configure-printer: Re-enabled printer ipp://localhost:631/printers/Officejet_4500_G510a-f
Nov  9 11:14:26 snoopy udev-configure-printer: URI of print queue: hp:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: usb://HP/Officejet%204500%20G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: Queue ipp://localhost:631/printers/Officejet_4500_G510a-f_2 has matching device URI
Nov  9 11:14:26 snoopy udev-configure-printer: Re-enabled printer ipp://localhost:631/printers/Officejet_4500_G510a-f_2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: hp:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: Queue ipp://localhost:631/printers/Officejet_4500_G510a-f_2 has matching device URI
Nov  9 11:14:26 snoopy udev-configure-printer: Re-enabled printer ipp://localhost:631/printers/Officejet_4500_G510a-f_2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of print queue: hpfax:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: hpfax usb officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: usb://HP/Officejet%204500%20G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: hp:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of print queue: hpfax:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: hpfax usb officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: usb://HP/Officejet%204500%20G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: hp:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of print queue: hpfax:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: hpfax usb officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: usb://HP/Officejet%204500%20G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: hp:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of print queue: cups-pdf:/, normalized: cups pdf
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: usb://HP/Officejet%204500%20G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2
Nov  9 11:14:26 snoopy udev-configure-printer: URI of detected printer: hp:/usb/Officejet_4500_G510a-f?serial=CN049F20C905H2, normalized: officejet 4500 g510a f serial cn049f20c905h2

dmesg | grep usb:

[    0.124495] usbcore: registered new interface driver usbfs
[    0.124519] usbcore: registered new interface driver hub
[    0.124574] usbcore: registered new device driver usb
[    0.312547] usb usb1: configuration #1 chosen from 1 choice
[    0.313151] usb usb2: configuration #1 chosen from 1 choice
[    0.313627] usb usb3: configuration #1 chosen from 1 choice
[    0.314062] usb usb4: configuration #1 chosen from 1 choice
[    0.314486] usb usb5: configuration #1 chosen from 1 choice
[    0.900795] usb 3-2: new low speed USB device using uhci_hcd and address 2
[    1.122525] usb 3-2: configuration #1 chosen from 1 choice
[    1.429716] usbcore: registered new interface driver hiddev
[    1.431864] usbcore: registered new interface driver usbhid
[    1.433611] usbhid: v2.6:USB HID core driver
[    1.560705] input: Microsoft Natural® Ergonomic Keyboard 4000 as /devices/pci0000:00/0000:00:1d.1/usb3/3-2/3-2:1.0/input/input3
[    1.560882] microsoft 0003:045E:00DB.0001: input,hidraw0: USB HID v1.11 Keyboard [Microsoft Natural® Ergonomic Keyboard 4000] on usb-0000:00:1d.1-2/input0
[    1.584491] input: Microsoft Natural® Ergonomic Keyboard 4000 as /devices/pci0000:00/0000:00:1d.1/usb3/3-2/3-2:1.1/input/input4
[    1.584673] microsoft 0003:045E:00DB.0002: input,hidraw1: USB HID v1.11 Device [Microsoft Natural® Ergonomic Keyboard 4000] on usb-0000:00:1d.1-2/input1
[163980.380089] usb 1-3: new high speed USB device using ehci_hcd and address 3
[163980.514030] usb 1-3: configuration #1 chosen from 1 choice
[163982.225839] usblp0: USB Bidirectional printer dev 3 if 1 alt 0 proto 2 vid 0x03F0 pid 0x4712
[163982.225904] usbcore: registered new interface driver usblp
[163984.395465] usb 1-3: usbfs: interface 1 claimed by usblp while 'usb' sets config #1

Also I am unable to access my modem configuration at http://192.168.1.254 as it continuously prompts me for my user name and password. I was able to before the upgrade. My ISP confirmed I have the correct info. So could there be a problem with the software used to communicate with devices?
I know dbus was part of the upgrade & I think I installed a new version from the source (and I think some other packages) when I didn't have an internet connection and was trying to complete the upgrade. I also followed tips to fix a common problem with the password ring. Should I re-install the dbus package or some other packages?
My computer is several years old, don't have the exact age. I have installed all the latest software updates according to Update Manager. My processor: model name : Intel(R) Celeron(R) CPU 2.40GHz stepping : 4 cpu MHz : 2394.331 cache size : 256 KB

A:

Simple Scan and lsusb detects the scanner after doing the following:

Install hplip and hplip-cups using System>Administration>Synaptic Package Manager. In my case, I also had to go to Settings>Repositories and uncheck 'Cdrom with Ubuntu 10.04' in the 'Installable from CD-ROM/DVD' box at the bottom in order download the packages. This stopped the package manager from repeatedly prompting me to insert the cdrom after clicking 'Apply'.
Run hp-check -r
In my case, the output said that the user 'root' needed to be in the 'lp' and 'lp-admin' groups so I used usermod -G group-name user-name to add 'root' to those groups.


Q:

Highlighting the dates between a start and end date in JQuery Datepicker

I have three datepickers - I have one datepicker which shows a six month span across the top, and then two date pickers beneath that applied to input fields. When the input fields are changed, I want the datepicker across the top of the webpage to highlight the start and end dates, and all the dates in between.
I have so far been able to get it to highlight both the start and end date as you can see in the following code, but I'd really appreciate someones help in how I should go about highlighting the days in between.
    var $test = $.datepicker.formatDate('yy-m-d', $('#date-start').datepicker('getDate'));
    var $test2 = $.datepicker.formatDate('yy-m-d', $('#date-end').datepicker('getDate'));

    var dates1 = {};
    dates1[$test] = 'first date';

    var dates2 = {};
    dates2[$test2] = 'second date';

    $( "#calendar" ).datepicker({
            firstDay: 1,
            numberOfMonths: 6,
            dateFormat: 'yy-mm-dd',
            beforeShowDay: function(date) {
            var search = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate());

                    if (dates1[search]) {

                      return [true, 'highlight', dates1[search] || ''];
                    }

                    if (dates2[search]) {

                      return [true, 'highlight', dates2[search] || ''];

                    }

                    return [false, '', ''];

            },
            onSelect: select_arrive,
            minDate: '+' +minimumLeadDays+ 'D',
            onChangeMonthYear: get_availability
    });

Thanks for any help in advance!
Edit:
Thanks for your help, I'll take a look at those links and see if I can figure it out - thanks again! :)

A:

Thanks for everyone's help. I found the solution to what I wanted to do here:
Need to highlight range of dates in jquery datepicker
It was nice and simple to follow, and I hope it helps someone else :)


Q:

Data frames with variable-length data in R/Splus

The following works fine in R
myarray <- as.array(list(c(5,5), 9, c(4,2,2,4,6)))
mydf    <- as.data.frame(myarray)

But in Splus it does not---giving the error message:
Problem in data.frameAux.list(x, na.strings = na.st..: arguments imply differing
 number of rows: 2, 1, 5
Use traceback() to see the call stack

Q: What's going on? How can I get this to work in Splus?
EDIT: I should make clearer why I'm going through this strange process of treating a list as a data.frame. It's because I'd eventually like to do something like the following in Splus:
mypos <- timeSeq("1/1/08", "1/3/08", by = "days")
myts <- timeSeries(data = mydf, positions = mypos)

The best feasible option right now, I guess, would be to build a list like:
mytshack <- list(mypos, as.list(myarray))

But this is clunky and I'd like to get the functionality of a timeSeries if possible

A:

EDITED after comments.
SPlus does not allow vectors as values in a dataframe, contrary to R. You'll have to use a list for that, and I'd simply do :
day <- c("1/1/2000","1/2/2000","1/3/2000")
names(myarray) <- day

which allows access to the data the usual way :
> myarray[["1/1/2000"]]
[1] 5 5

Given your confirmation this is actually what you want, and the extra information about the dataset, try this :
myarray <- as.array(list(c(5,5), 9, c(4,2,2,4,6)))
mydf <- as.matrix(myarray)
colnames(mydf) <- "myarray"

mypos <- timeSeq("1/1/08", "1/3/08", by = "days")
myts <- timeSeries(data = mydf, positions = mypos)
seriesData(myts)

This works in SPlus. timeSeries needs a rectangular object, and as.rectangular can't deal with arrays. So converting to a matrix will do. Still, I'd just use the package timeSeries in R instead of hacking it together in SPlus.


Q:

how to use stl map for more than one fields without nesting another map in it

i have to use stl map containing 3 values : float(key) , int ,int.
For the last two ints without using another map , how can i declare my map and insert values in it?
Thanks in advance.

A:

struct foo
{
    int x;
    int y;
};

...

std::map<float,foo> myMap;

...

foo a = { 5, 2 };
myMap[3.2] = a;


Q:

Expose specific file in a docker-compose named volume

This is a named volume (shared between multiple apps, so its neater than a bind mount):
foo:
  image: foo:latest
  volumes:
    foo_data:/etc/foo:ro

volumes:
  foo:

Lets say I want to expose a single file:
foo_data/etc/foo/bar.conf:/etc/foo/bar.conf:ro

Obviously that syntax is incorrect.
Is there a way to do this without resorting to bind mounts?

A:

This is not possible without using a bind mount.
You would be able to specify which folder is referenced by the named volume however you are still mounting the entire folder.


Q:

Group By and Count in Xquery

I am trying to count Similar 'itemid_ref', to get numbers of each Items ref in this:
<?xml version="1.0" encoding="utf-8"?>
<electrystore>
  <itembill>
   <itembill_id>1</itembill_id>
   <itemid_ref>2</itemid_ref>
   <billid_ref>2</billid_ref>
   <price>20000</price>
  </itembill>
   <itembill>
   <itembill_id>2</itembill_id>
   <itemid_ref>3</itemid_ref>
   <billid_ref>3</billid_ref>
   <price>250000</price>
  </itembill>
  <itembill>
   <itembill_id>3</itembill_id>
   <itemid_ref>3</itemid_ref>
   <billid_ref>3</billid_ref>
   <price>30000</price>
  </itembill>
  <itembill>
   <itembill_id>4</itembill_id>
   <itemid_ref>1</itemid_ref>
   <billid_ref>2</billid_ref>
   <price>140000</price>
  </itembill>
  <itembill>
   <itembill_id>5</itembill_id>
   <itemid_ref>2</itemid_ref>
   <billid_ref>1</billid_ref>
   <price>10000</price>
  </itembill>
</electrystore>

I am trying to get the output from xquery to be like this:
<?xml version="1.0" encoding="UTF-8"?>
<results>
<result>
    <itemid_ref>
       2
    </itemid_ref>
    <numberOfitemes>2</numberOfitemes>
</result>
<result>
    <itemid_ref>
       3
    </itemid_ref>
    <numberOfitemes>2</numberOfitemes>
</result>
<result>
   <itemid_ref>
       1
    </itemid_ref>
    <numberOfitemes>1</numberOfitemes>
</result>

how can I do this?

A:

There's no group by in XQuery 1.0, but usually you can get by using distinct-values, as long as the data set isn't too large.
for $itemid_ref in distinct-values(/electrystore/itembill/itemid_ref)
let $count := count(/electrystore/itembill[itemid_ref = $itemid_ref])
return element result {
  element itemid_ref { $itemid_ref },
  element numberOfitemes { $count }
}

To be performant on large sets of data, you'll probably need to look into extensions available within your XQuery processor that allow access to indexes.
In XQuery 3.0 it's a little simpler:
for $itembill in /electrystore/itembill
let $itemid_ref := $itembill/itemid_ref
group by $itemid_ref
return element result {
  element itemid_ref { $itemid_ref },
  element numberOfitemes { count($itembill) }
}


Q:

Is there a problem if I delete or copy photos from my SD card using Windows Explorer?

If I just insert the card in the PC and delete some photos inside DCIM folder, or add some, can this damage my card or camera? Should I use some special software for this?

A:

No. it will not damage your card or camera.
The worst case scenario is that the camera would stop reading the card and the solution is to copy anything important on the card to your computer and format the card in camera.
I've been doing this for years with lots of different cameras and never had any problem.

A:

No it shouldn't be a problem.
I copy/cut all of my photos this way, the only time when you might have a problem is when you say rotate the photo and leave it on the card, then the camera might not be able to show the image in preview.

A:

There should be no problem at all if you copy or delete files from the card, but each camera uses particular ways of managing data in the cards, so writing, adding or editing files with a computer or other devices may interfere with some functions of the camera.
Using Windows Explorer or another file management utility gives you the best flexibility and often faster operation than the bundled software of certain cameras. This flexibility may allow to perform operations that the camera is not prepared for. Normally, none of such operations may cause damage to either the card or the camera, they may in worst cases prevent the camera from performing certain operations or have unexpected results and cause data loss.
Reading a card will not cause any trouble, as long as the computer, the card, the reader and any cables used are in good condition (there are no virus, damaged physical conductors, etc.)
Deleting files is also safe, but you must remember that Windows OS does not "send to recycle bin" any file that is in a memory stick, usb drive or memory card, so deletion is definitive. That's why the advice here is to be very careful to delete only files that you have already made a backup or to be very precise with your selection and deletion procedure.
Many cameras won't display or read pictures that have been edited by third party software (even pictures rotated with windows picture viewer won't be displayable for some cameras).
Some cameras have "post production" options in-camera, but some cannot apply such filters to pictures that have been taken with another make (or even model) of camera. Conversely, such in-camera edited pictures, may not be viewable/editable in another camera. Some cameras won't even let you re-edit a file or apply the same "filter" again to the edited picture, but most of them will preserve the original file and save an edited copy with a different name.
Another concern is file names, if by any chance you place a file in the same folder the camera uses for it's own pictures an this file has a name the camera will use later, results may be unpredictable. In the best case, the camera will use the next available filename, but you may (depending on the camera programming) loose the file you recorded first, or loose the current shot.
Depending on the number of files with conflicting names and file name generation logic of your camera you could cause some performance issues, for example the camera taking too long to record a new shot.
However, most cameras use a two or three level folder system, typically in the root of the card, they place a folder named like the maker of the camera, inside that, another folder named "DCIM" or something similar, and even inside of that one some other folder with a name like XXX100, XXX101, etc...(Or some other combination of names)
Usually you can do whatever you like outside such folders, that is, create another folder and copy any file that fits in the available space. Normally the camera won't even notice such files, so they may be pictures, music, documents... The downside is that the camera won't be able to delete, move or copy those files, so if you run out of space while taking pictures, you'll be forced to delete pictures from the camera's folder or downloading them to a computer (Either case you have to shop shooting).
If you really need to edit pictures in the same card and folder, or need to write files in the same directory of the card used by your camera, it is advisable to make an appropriate backup and perform some test to be sure to know the camera's specific behavior, so you know what to expect afterwards.
Conclusions:

Using your camera card directly in your pc and using file management
software (i.e. Windows Explorer or Mac's Finder) does not damage the
card or the camera.
It's best not to write files to the card, and not to edit the pictures in the same card, but, if for some reason you are forced to do so, create a different folder in the card, so that the files interfere as little as possible with camera functions.
Direct copy causes no problem at all in normal conditions.
Deleting causes no problems but must be done carefully.

(Based on first hand experience in use of several models and makes of cameras including Canon, Casio, Nikon, Olympus, Panasonic, Samsung and Sony. In most cases, user manual did not mention anything regarding this kind of issue.)


Q:

How to prove that this infinite product of continued fractions converges to $1-\frac{1}{z}$?

$$\cfrac{z}{1+z} \cdot \cfrac{z}{1+z-\cfrac{z}{1+z}} \cdot \cfrac{z}{1+z-\cfrac{z}{1+z-\cfrac{z}{1+z}}} \cdots= 1-\frac{1}{z}$$
I propose that this works for any $z \in C$ if and only if $|z|>1$.
That much I got by experimenting and by the identity I already proved using Euler's continued fraction formula:
$$\cfrac{z}{1+z-\cfrac{z}{1+z-\cfrac{z}{1+z-\cfrac{z}{1+z-\cdots}}}}=\begin{cases}1 & |z| > 1\\z & |z| \leq 1\end{cases}$$
But I don't know how to prove the above product. Any ideas?

A:

Well, let's start by calling the terms of your product $a_n$, that is, $a_1=\frac{z}{1+z}, a_{n+1}=\frac{z}{1+z-a_n}$. Some experimenting suggests the formula:
$$a_n=\frac{z+z^2+...+z^n}{1+z+z^2+...+z^n}=\frac{z(1-z^n)}{1-z^{n+1}}$$
and this can be verified fairly easily by induction. Now, let's consider the partial products:
$$a_1a_2\cdots a_n=\frac{z(1-z^1)}{1-z^{2}}\cdot \frac{z(1-z^2)}{1-z^{3}}\cdots \frac{z(1-z^n)}{1-z^{n+1}}=z^n\frac{1-z}{1-z^{n+1}}=\frac{z-1}{z-z^{-n}}$$
Considering the cases $|z|<1, |z|>1$ separately, we see that:

$|z|<1$ causes the product to "diverge to 0"
$|z|>1$ lets the product converge to $\frac{z-1}{z}$
$|z|=1$ has varied behaviour - if the $z$ is a root of unity, the product will contain terms of both $0$ and $\infty$, and if not, it will vary without converging.


Q:

Food safe fix for broken plastic valve

I have a second hand espresso machine (this or similar - 800ESXL) and a valve in it has broken. From a bit of research, it looked like Breville knew the part was prone to failure and they quickly made it obsolete without a compatible replacement. I can't find a new replacement for it, so following advice here, I thought it'd be worth it to try gluing it back together.
I don't see any visible markings on the piece to indicate what type of plastic it is. How can I fix this as robustly as possible in a food safe way? I think this is before the boiler, so shouldn't be exposed to particularly high temperatures.
I'm looking for both whether this is possible from a materials perspective (is there a go-to general product for adhering "plastic" without knowing what type it is?) and a technique perspective - this is a small diameter piece and is threaded on the outside, so adhering the pieces as cleanly as possible would also be important.

A:

You already tagged the answer.  Epoxy is fine for food content.
Food feedstock tanks are painted with epoxy paint, that's what you use for that. (We're talking genuine 2-part epoxy paint, not hardware store 1-part paint that has chunks of already-cured epoxy in it for marketing purposes.  No one will sell consumers uncured epoxy if there's a remote chance you might spray it.)
Steel cans are lined with epoxy (if you recall the fuss about BPAs, BPA is a common curing agent in epoxy; it should be fully consumed in the curing process unless the mixing is botched.)
Getting the epoxy to adhere to the broken parts is a real problem.  Even if it adheres, it may be stronger than the native material, which if deteriorated, would simply break again at the boundary layer or someplace else.  I would say "sand it flat" but then you'll lose the thread sync.
You may be wasting your time if the material is deteriorated.
At that kind of price you ought to be able to consult the factory? They may have deprecated the whole assembly and have a replacement.   Or they may simply say "tough beans, this is a top end product like Beats headphones, not made to be repaired."   In that case they must have prototyped it from something; I would search Grainger, McMaster-Carr etc. for similar components in metal and food-grade.


Q:

why isn't my environment variable visible from the command line?

I'm trying to run the james smtp server on Lion.  When I do this ...
sudo JAVA_HOME=/Library/Java/Home ./james-2.3.2/bin/run.sh

... it works fine.
However, I'd like to make JAVA_HOME an environment variable so it is visible to other applications too.
I edited ~/.bash_profile to look like this ...
export JAVA_HOME=/Library/Java/home

... and the variable appears to be visible from the command line like so ...
$ echo $JAVA_HOME
/Library/Java/home

But when I run james again like this, I get a warning about JAVA_HOME ...
$ sudo ./james-2.3.2/bin/run.sh
ERROR: JAVA_HOME not found in your environment.

Please, set the JAVA_HOME variable in your environment to match the
location of the Java Virtual Machine you want to use.

Any ideas what I'm doing wrong?  Why can't the command to run james see the JAVA_HOME environment variable?
Any info is greatly appreciated, thanks!
Rob

A:

The issue is that you are not running in your environment so any changes to ~/.bash_profile will have no effect on the command. It will be visible to other processes
sudo runs as another user - in this case root as you have not provided a -u username parameter. Thus you need to change the root environment to make JAVA_HOME visible to the run.sh command


Q:

storyboard appdelegate changes for multipleview

created a singleview application with storyboard.
Added three viewcontrollers apart from the one view present by default,Now how to refer to this ViewController programmatically from the AppDelegate did finishlaunchingoptions function? I've created 3 view controller classes and what are the changes i should do in appdelegate

A:

Well it seems as if a tutorial would make sense so you could learn how storyboard based development in iOS 5 works.
A great one i found is this one written by Ray Wenderlich.


Q:

Add proguard enabled apk later in play store

I wan to  add android apk in google play without pro-guard and after some releases build with pro-guard enabled.
Can we add android apk in google play without pro-guard and after some releases can we add build with pro-guard enabled.

A:

Yes.  The Play Store has no idea if proguard is used or not.  The only restrictions on future builds uploaded to the Play Store is that you must sign with the same key, and you must increase the version number in the manifest/gradle.


Q:

Passing ModelState to RedirectToAction into a ViewModel

How can I pass back the validation errors I find when using DbEntityValidationException
            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        this.ModelState.AddModelError(validationError.PropertyName,
                        validationError.ErrorMessage);
                    }
                }
                return RedirectToAction("AccessDetail", "Home", new { IDValue = access.ID });
            }

It appears that when I do this RedirectToAction my ModelState refreshes and I can not view the errors it found.
The AccessDetail populates a view model that has many different sources of data in it.  So passing just the access to the View does not work.
I was looking at this question but it didn't fit my needs as my view is populated with a ViewModel

A:

RedirectToAction helper method issues a 302 response to the client which makes the clients to issue a new GET request to the new url.
If you want to persist some data between these 2 requests, Use TempData.
TempData["Errors"] = yourListOfErrors;
return RedirectToAction("AccessDetail", "Home", new { IDValue = access.ID });

And in your GET action, read the TempData values and display it.
But If you do not want to do the RedirecToAction, You may simply return the viewmodel back to the view and if you have the ValidationSummary helper method, it will show the validation error messages.
simply use
return View(model);


Q:

Java Multithreading large arrays access

My main class, generates multiple threads based on some rules. (20-40 threads live for long time).
Each thread create several threads (short time ) --> I am using executer for this one.
I need to work on  Multi dimension arrays in the short time threads --> I wrote it like it is in the code below --> but I think that it is not efficient since I pass it so many times to so many threads / tasks --. I tried to access it directly from the threads (by declaring it as public --> no success) --> will be happy to get comments / advices on how to improve it.
I also look at next step to return a 1 dimension array as a result (which might be better just to update it at the Assetfactory class ) --> and I am not sure how to.
please see the code below.
thanks
Paz
import java.util.concurrent.*;
import java.util.logging.Level;

public class AssetFactory implements Runnable{
    private volatile boolean stop = false;
    private volatile String feed ;
    private double[][][] PeriodRates= new double[10][500][4];

    private String TimeStr,Bid,periodicalRateIndicator;
    private final BlockingQueue<String> workQueue;
    ExecutorService IndicatorPool = Executors.newCachedThreadPool();

    public AssetFactory(BlockingQueue<String> workQueue) {
      this.workQueue = workQueue;
    }

    @Override
    public void run(){
      while (!stop) {
       try{
          feed = workQueue.take();
            periodicalRateIndicator = CheckPeriod(TimeStr, Bid) ;
            if (periodicalRateIndicator.length() >0) {
                IndicatorPool.submit(new CalcMvg(periodicalRateIndicator,PeriodRates));
            }

          }

          if ("Stop".equals(feed)) {
              stop = true ;
          }

       } // try
       catch (InterruptedException ex) {
           logger.log(Level.SEVERE, null, ex);
           stop = true;
       }

      } // while
    } // run

Here is the CalcMVG class
public class CalcMvg implements Runnable {
    private double [][][] PeriodRates = new double[10][500][4];

    public CalcMvg(String Periods, double[][][] PeriodRates) {
        System.out.println(Periods);
        this.PeriodRates = PeriodRates ;
    }

    @Override
    public void run(){
       try{
          // do some work with the data of PeriodRates array e.g. print it (no changes to array
          System.out.println(PeriodRates[1][1][1]);
          }
       catch (Exception ex){
          System.out.println(Thread.currentThread().getName() + ex.getMessage());
          logger.log(Level.SEVERE, null, ex);
         }
      }//run

  } // mvg class

A:

There are several things going on here which seem to be wrong, but it is hard to give a good answer with the limited amount of code presented.
First the actual coding issues:

There is no need to define a variable as volatile if only one thread ever accesses it (stop, feed)
You should declare variables that are only used in a local context (run method) locally in that function and not globally for the whole instance (almost all variables). This allows the JIT to do various optimizations.
The InterruptedException should terminate the thread. Because it is thrown as a request to terminate the thread's work.
In your code example the workQueue doesn't seem to do anything but to put the threads to sleep or stop them. Why doesn't it just immediately feed the actual worker-threads with the required workload?

And then the code structure issues:

You use threads to feed threads with work. This is inefficient, as you only have a limited amount of cores that can actually do the work. As the execution order of threads is undefined, it is likely that the IndicatorPool is either mostly idle or overfilling with tasks that have not yet been done.
If you have a finite set of work to be done, the ExecutorCompletionService might be helpful for your task.

I think you will gain the best speed increase by redesigning the code structure. Imagine the following (assuming that I understood your question correctly):

There is a blocking queue of tasks that is fed by some data source (e.g. file-stream, network).
A set of worker-threads equal to the amount of cores is waiting on that data source for input, which is then processed and put into a completion queue.
A specific data set is the "terminator" for your work (e.g. "null"). If a thread encounters this terminator, it finishes it's loop and shuts down.

Now the following holds true for this construct:
Case 1: The data source is the bottle-neck. It cannot be speed-up by using multiple threads, as your harddisk/network won't work faster if you ask more often.
Case 2: The processing power on your machine is the bottle neck, as you cannot process more data than the worker threads/cores on your machine can handle.
In both cases the conclusion is, that the worker threads need to be the ones that seek for new data as soon as they are ready to process it. As either they need to be put on hold or they need to throttle the incoming data. This will ensure maximum throughput.
If all worker threads have terminated, the work is done. This can be i.E. tracked through the use of a CyclicBarrier or Phaser class.
Pseudo-code for the worker threads:
public void run() {
  DataType e;
  try {
    while ((e = dataSource.next()) != null) {
      process(e);
    }
    barrier.await();
  } catch (InterruptedException ex) {
  }
}

I hope this is helpful on your case.


Q:

Regression line in ggplot doesn't match computed regression

Im using R and created a chart using ggplot2.
ggplot(Month.Data, aes(y=Measure, x=Samples)) +geom_point()  + geom_smooth(method = "lm", se = FALSE)

I then create a regression so I can make some predicitions
regression <- lm(Samples ~ Measure, data = Month.Data)

I pass my data frame of "Measures" to the predict function
predict(regression, Measures)
I'd expect the predictions to be the same as if I used the regression line on the chart, but they aren't the same. Why would this be the case? Is there a setting in ggplot or is my expectation incorrect?

A:

ggplot(Month.Data, aes(y=Measure, x=Samples)) + ...

Here your y values are Measure and your x values Samples.
regression <- lm(Samples ~ Measure, data = Month.Data)

Here your y values are Samples and your x values Measure.
Those are different models and predictions will be different since OLS minimizes the sum of squared residuals in y direction.


Q:

What will happen when bitcoin's popularity multiplies and the number of transactions explodes?

As I understand, every transaction in the bitcoin network is stored into one huge "chain". What happens when bitcoin gets more popular and there will be millions of transactions per minute? Doesn't the blockchain grow "too big"?

A:

According to Bitcoin Block Size - What are the rules? each block can be up to 1MB per size and contain roughly 2400 transactions. As transaction blocks are supposed to be found every ten minutes, this would mean that 14400 transactions per hour or 4 transactions per second could be handled.
If there should be more transactions sent they would compete for inclusion into the blocks. Transactions with smaller fees would gain priority by aging and would at some point be included at times of fewer transactions. People that require their transactions to arrive quickly would attach bigger transaction fees for faster inclusion. At some point microtransactions would cost more than the amount of value they transport and/or would have to wait very long. Perhaps some transactions would move off the blockchain,  some e-wallet services already allow their users to transfer balances to other users of the service for free and without wait.
The protocol as it is today would not be able to sustain a transaction volume of millions per minute (although that is too big a number, even VISA only has 150 million transactions per day, which are about 100k per minute). The bitcoin network is currently averaging just above 60000 transactions per day, so this is already about 1/6 of what the network can handle with the current block size limit.
However, apparently a significant amount of transactions are generated by gambling, so I am unsure how pressing the matter really is for the network.
Edit:
Reading more about the scalability of the system I learned that the bitcoin network could scale to more than 40000 tps on today's hardware. The regular users would probably not store the complete blockchain anymore, but only the unspent outputs without the entire history of the transactions.


Q:

Is this $3\times3$ matrix diagonalizable?

After browsing through similar posts, I was wondering if I am understanding the meaning of "$n$ distinct eigenvalues" for the following theorem.

If the $n\times n$ matrix $A$ has $n$ distinct eigenvalues, then the corresponding eigenvectors are linearly independent and $A$ is diagonalizable.

$A = \begin{bmatrix}
3 & 2 & 1 \\
0 & 0 & 2 \\
0 & 2 & 0 \\
\end{bmatrix}$
$\lambda I - A = 0 =
\begin{bmatrix}
\lambda - 3 & -2 & -1 \\
0 & \lambda - 0 & -2 \\
0 & -2 & \lambda - 0 \\
\end{bmatrix} =
(\lambda - 3)\begin{vmatrix}
\lambda & -2 \\
-2 & \lambda \\
\end{vmatrix}
=
(\lambda - 3) (\lambda ^ 2 - 4 )
$
I get $\lambda = 3, 2, -2$. I tried to find an eigenvector with $\lambda = 3$ and got a weird looking matrix that doesn't look linearly independent. Despite this weird matrix, I rearranged the rows via column operations and managed to find an eigenvector. It appears the matrix is diagonalizable? I am not sure I handled $\lambda = 3$ correctly though.
$3I - A
=
\begin{bmatrix}
0 & -2 & -1 \\
0 & 3 & -2 \\
0 & -2 & 3 \\
\end{bmatrix}
\rightarrow
\begin{bmatrix}
0 & 1 & 0 \\
0 & 0 & 1 \\
0 & 0 & 0 \\
\end{bmatrix}
\rightarrow
\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 0 \\
\end{bmatrix}
=
\begin{bmatrix}
x_1 \\
x_2 \\
x_3 \\
\end{bmatrix}
=
\begin{bmatrix}
0x_2 + 0x_3 \\
0x_3 \\
x_3 \\
\end{bmatrix}
=
x_3 \begin{bmatrix}
0 \\
0 \\
1 \\
\end{bmatrix}$
$2I - A
=
\begin{bmatrix}
-1 & -2 & -1 \\
0 & 2 & -2 \\
0 & -2 & 2 \\
\end{bmatrix}
\rightarrow
\begin{bmatrix}
1 & 0 & 3 \\
0 & 1 & -1 \\
0 & 0 & 0 \\
\end{bmatrix}
\rightarrow
\begin{bmatrix}
x_1 \\
x_2 \\
x_3 \\
\end{bmatrix}
=
\begin{bmatrix}
3_x3 \\
-x_3 \\
x_3 \\
\end{bmatrix}
=
x_3 \begin{bmatrix}
-3 \\
1 \\
1 \\
\end{bmatrix}$
$-2I - A
=
\begin{bmatrix}
-5 & -2 & -1 \\
0 & -2 & -2 \\
0 & -2 & -2 \\
\end{bmatrix}
\rightarrow
\begin{bmatrix}
1 & 0 & -.2 \\
0 & 1 & 1 \\
0 & 0 & 0 \\
\end{bmatrix}
\rightarrow
\begin{bmatrix}
x_1 \\
x_2 \\
x_3 \\
\end{bmatrix}
=
\begin{bmatrix}
-.2x_3 \\
x_3 \\
x_3 \\
\end{bmatrix}
=
x_3 \begin{bmatrix}
.2 \\
-1 \\
1 \\
\end{bmatrix}$
$P =
\begin{bmatrix}
0 & -3 & .2 \\
0 & 1 & -1 \\
1 & 1 & 1 \\
\end{bmatrix}$,
$P^{-1}AP =
\begin{bmatrix}
3 & 0 & 1.4e^{-13} \\
-.5 & 2 & 0 \\
-2.5 & 0 & -2 \\
\end{bmatrix}$

A:

Your error is in the first eigenvector:
$$
\begin{bmatrix}
0 & 1 & 0 \\
0 & 0 & 1 \\
0 & 0 & 0
\end{bmatrix}
$$
gives $x_2=0$ and $x_3=0$, with $x_1$ free; thus an eigenvector is
\begin{bmatrix} 1\\0\\0\end{bmatrix}
You cannot transform it into
$$
\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 0
\end{bmatrix}
$$
which is a very different linear system.


Q:

UIScrollview zoom is making UIScrollview's subview Pan

I have some troubles with my UIScrollView. So here's the situation:
I have a UIScrollView with few small UIView inside.
UIView have a Pan event to move them inside the scrollview. But When I zoom my scrollview and one of my finger is on a UIview that make a pan begin and my UIScrollView is not zooming (and the UIview is moving).
I tried to set the MaximumNumberOfTouches of the pan but that doesn't work. I think it's because the second touch is outside the view.
Do you have any idea how to make it work?
Thank you !

A:

You have to implement the UIGestureRecognizerDelegate protocol in your View Controller, so that you can use the gestureRecognizer(_:shouldRequireFailureOfGestureRecognizer: method and return true when needed. You can form a restrictive predicate by comparing the first and second parameters with, respectively, your Pan Gesture Recognizer and the Scroll View's Pinch Gesture Recognizer:
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOfGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return gestureRecognizer == myPanGestureRecognizer && otherGestureRecognizer == scrollView.pinchGestureRecognizer
}

That way, the latter will wait until the Scroll View's Gesture Recognizer fails before transitioning to state .Recognized. More information can be found in Apple Gesture Recognizer Programming Guide.
Do not forget to set your Pan Gesture Recognizer's delegate property to self :
myPanGestureRecognizer.delegate = self


Q:

fixing WEP by treating all messages as one long stream

in the course of introduction to cryptography on coursera
professor suggested treating all messages as a long stream XORing them with the key
this way we will not need to change the key and will not have the IV problem
and the question is
if so how can we generate a key that will encrypt the whole traffic using just XOR

A:

Well, WEP uses RC4 to encrypt, and RC4 can be used to generate a long keystream to encrypt multiple messages.  The key would be negotiated when the connection starts; both sides would hand over the negotiated session key to the RC4 algorithm, and RC4 then generates a long keystream that can be used to encryption.  In fact, when SSL uses RC4, it does exactly this.
However, when it comes to WEP, there is a significant practical problem that doesn't arise with SSL; message reliability.  With SSL, the protocol assumes that the protocol is run over a reliable transport (generally TCP); the transport protocol will ensure that the receiver will get every message the sender sends, and in the correct order (and if it can't ensure that, it raises an error condition that shuts down the connection.
This is important for RC4; it generates a separate part of the keystream for every message.  For, if we encrypt two 100 byte messages, bytes 0 through 99 of the keystream will be used to encrypt message 1, and bytes 100 through 199 of the keystream will be used to encrypt message 2.  When the receiver gets the encrypted message 1, he can use his copy of the RC4 keystream generator to create bytes 0 through 99 of the keystream, and decrypt message 1.
The problem comes in if the receiver never receives message 1, and instead receives message 2.  If he were to ask RC4 for the next 100 bytes of the keystream, he'd get bytes 0 through 99, which won't decrypt message 2 properly at all.
With SSL, this situation never comes up; the underlying TCP protocol will ensure that message 1 will always arrive first (unless there's some man-in-the-middle attacker; yes, he can cause the connection to shut down; there's other protections in place that ensure he can't do anything else).
However, WEP is designed to protect wireless connections; the messages that it protects are datagrams transmitted over the radio.  In practice, it is quite common for messages to not be received correctly (because of interference).  Because of this, WEP cannot assume that all transmitted messages will be received, and so WEP cannot use a long-standing RC4 key.
A cryptographic protocol needs to meet multiple goals; they ought to be secure; however, they also need to work well with the overall system design.  WEP, as designed, does the latter reasonably well; it's just the former they missed a bit.


Q:

Scrapy - How to access a returned dictionary in parse from another parse function

I'm trying to use parse as a central hub to gather dicts from other parse functions since I need to use multiple URL and domains but I can't seem to figure out how to get all the data back into one dictionary. Here is an example of what I'm trying to do:
def parse(self, response):
    request_1 = scrapy.Request(domain_1_url, callback = parse_2)
    request_2 = scrapy.Request(domain_2_url, callback = parse_3)
    #unpacks the two dicts from the 2 requests and return them as 1 to the pipeline
    yield {**request_1, **request_2} #what I want to do, doesn't work because they are requests, not dicts

def parse_2(self, response):
    yield {'someKey': 'some value'}

def parse_3(self, response):
    yield {'someOtherKey': 'some more values'}

Is there someway I can achieve this? Or is there a better way to do it like throwing everything to the pipeline and have that handle combining the data instead?
EDIT:
I thought about passing an Item object to the other requests thinking that modifying it in the other requests will also modify the one in the main parse because of Python's "call-by-object" properties:
def parse(self, response):
    item = CustomItem()
    request_1 = scrapy.Request(domain_1_url, callback = parse_2)
    request_1.meta['item'] = item
    request_2 = scrapy.Request(domain_2_url, callback = parse_3)
    request_2.meta['item'] = item
    print(item) #still empty
    yield item

def parse_2(self, response):
    item = response.meta['item']
    item['someKey'] = 'some value'
    yield item

def parse_3(self, response):
    item = response.meta['item']
    item['someOtherKey'] = 'some more values'
    yield item

Not quite sure why this doesn't work but the item object in parse() is still empty after calling the 2 requests

A:

Credits to @TomášLinhart for the solution in the comments above
What I ended up doing is chaining the 3 parses instead of using one as a central hub. I really dislike this solution since parse_2 and parse_3 has no relationship with one another and they each crawl on different domains in my situation so if anyone have a more elegant solution please feel free to answer
def parse(self, response):
    item = CustomItem()
    request_1 = scrapy.Request(domain_1_url, callback = parse_2)
    request_1.meta['item'] = item
    yield request_1

def parse_2(self, response):
    item = response.meta['item']
    item['someKey'] = 'some value'
    request_2 = scrapy.Request(domain_2_url, callback = parse_3)
    request_2.meta['item'] = item
    yield request_2

def parse_3(self, response):
    item = response.meta['item']
    item['someOtherKey'] = 'some more values'
    yield item


Q:

Azure AKS .NET Core with SignalR SSL Ingress

What's the recommended way to setup SSL/TLS with AKS for a .NET Core website that uses SignalR?
From what I can tell Azure Front Door doesn't work because it doesn't support Websockets.
And AKS doesn't have a service like AWS does for doing SSL/TLS.
Do I really have to use a ngnix proxy on top to make this work?
Also, looks like same problem for gRPC in .NET Core and Azure. Basically no way to hose gRPC on Azure at all right now.
Suggestions?

A:

Application Gateway provides native support for WebSocket across all gateway sizes. There is no user-configurable setting to selectively enable or disable WebSocket support. see Overview of WebSocket support in Application Gateway.
With the application gateway, you can create listeners on port 80/443 to support WebSocket traffic and health probe supports for HTTP and HTTPS protocols. APP GW also support SSL offload and end to end SSL traffic.
There are two options for App GW conjunction with AKS. One is simply to put the APP GW in front of the internal or public Loadbalancers with AKS, see this blog. Another better one currently is using Application Gateway Ingress Controller. This is supported by Application Gateway v2 only.

For more references:

Expose a WebSocket server
How to configure Azure Application Gateway work with AKS via SSL.