text:
Q: Choosing color for Bar in flot Chart I have an array with random numbers, and i want to clasify the data from this array in good (color green bar) or bad (color red bar) in the flot chart. Here's my code but it doesn't work. Can anyone please help me?

<script>
    var Max = 20;
    var Data = [];
    for (var i=0;i<Max;i++){
        Data [i]=Math.floor((Math.random()*3000)+1500);
    }
    var myData = [];
    for(var i=0;i<Max;i++){
       if(Data[i]<2000||Data[i]>2500){
            myData [i]= {color: "red", data:[Data[i],i]};
       }
       else {
            myData [i]= {color: "green", data:[Data[i],i]};
       }
    };
    var options = {
        bars:{
              show: true,
              horizontal: true,
        },
        yaxis: {
                tickLength:0,
                ticks:[]
        },
        xaxis: {
                tickLength:0,
                ticks:[]
        },
        grid: {
               clickable: true,
               hoverable: true,
               borderWidth: 2
        }
    }

    $(document).ready(function(){
    $.plot($("#mycanvas"),[{data:myData}],options);
    });
</script>

A: When you're building your series, you need to make the data object an array of values:
data: [[i, Data[i]]]

From the Flot API Data Series section (notice the format of the data object):

You don't have to specify any of them except the data, the rest are
  options that will get default values. Typically you'd only specify
  label and data, like this:
{
    label: "y = 3",
    data: [[0, 3], [10, 3]]
}

This JSFiddle demonstrates how to build the data array with your example code.


text:
Q: Marginal Spacing in Curriculum Vitae I have the following minimal example for a curriculum vitae:
\documentclass[12pt, a4paper]{curve}
\usepackage{currvita}

\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[ansinew]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}
\usepackage{eso-pic}

\begin{document}

\AddToShipoutPicture*{%
  \put(440,610){\includegraphics[width=39mm]{sherlock.jpg}}%
}

\begin{cv}{Curriculum Vitae}

\begin{cvlist}{Personal Details}
\item[Name:] Big Boss
\item[Phone:] 0123456789
\item[Email:] neruj@mailzi.ru
\item[Born:] 23.November 2015, Malibu (Beach)
\item[Status:] single
\end{cvlist}

\begin {cvlist}{Soft Skills}
\item[EDV:] Word, Excel, Python, TeX, SQL
\item[Sports:] National Hockey League Stanley Midwest Cup Playoffs 2015
\end{cvlist}

\cvplace{Miami}
\date{23.11.2015}

\end{cv}
\end{document}

The Sports line is limited by a relatively big margin, how could I decrease the margins and force it into one line?

A: The geometry package makes it easy to change the page layout parameters. You probably just need to insert
\usepackage[a4paper,width=16cm]{geometry}

in your preamble, and then experiment to get the best width for your cv (don't make it too wide, or you may strain the eyes of the person reading it).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I silently start up my MacBook Air? When I start up my MacBook Air, it makes a loud startup sound unless I muted the computer prior to shutting down last time.
However, I cannot guarantee that I had muted the computer last time before shut down because I share this Air with others.
How do I start up my Mac silently?

A: This is the only thing that worked for me under OS X 10.8.5 (Mountain Lion) on a 2012-era Mac Mini (Core i5 Intel CPU). In Terminal.app, enter the following command:
sudo nvram SystemAudioVolume=%80

The sudo command will ask for your login password. It needs elevated privileges to update your Mac's NVRAM settings (the Mac equivalent of a PC's BIOS). Don't be put off by the %80 value. It will indeed mute the start-up chime.
If you ever decide you want the chime back again, delete the setting from NVRAM with this command:
sudo nvram -d SystemAudioVolume

A: Plugging in headphones used to be the quick and dirty way to assure silence (back in the PPC hardware days).
Now, the self test startup chime still uses the internal speaker whether or not the headphone jack is in use, but the below trick will work on older macs. It is of use with new macs as long as you don't set your mac to reboot automatically and you don't forget about the current behavior and reboot it yourself.
I have a snipped nub of a headphone jack that I use when I am in a place where noise is prohibited no matter what the software decides.
You can get a plug without any cord for less than $5 at a store such as Radio Shack if you don't have headphones you can sacrifice or the cut cord doesn't please you.
It's simply not possible to change the NVRAM mute/volume setting after the mac is shut down (or sleeping) so even if you prepare properly, sound will be made if things don't go as planned on the shutdown.

A: For Snow Leopard and earlier machines download and install "StartupSound.prefPane" which will install a preference pane in system settings to allow you to adjust the startup volume and disable the startup sound:
http://www5e.biglobe.ne.jp/~arcana/StartupSound/BETA/index.en.html
Note that the above has mixed results in Lion.  For Lion users the following is recommended:

*

*Login as administrator and open a terminal window

*Create scriptfile for muting
sudo nano /path/to/mute-on.sh

*Enter this as content, when done press control+O to save and control+X to exit:
#!/bin/bash
osascript -e 'set volume with output muted'

*Create scriptfile for unmuting
sudo nano /path/to/mute-off.sh

*Enter this as content, when done press control+O to save and control+X to exit:
#!/bin/bash
osascript -e 'set volume without output muted'

*Make both files executable:
sudo chmod u+x /path/to/mute-on.sh
sudo chmod u+x /path/to/mute-off.sh

*Check if any hooks already exist (these will be overwritten, so make sure it is OK for you)
sudo defaults read com.apple.loginwindow LoginHook
sudo defaults read com.apple.loginwindow LogoutHook

*Add hooks for muting
sudo defaults write com.apple.loginwindow LogoutHook /path/to/mute-on.sh
sudo defaults write com.apple.loginwindow LoginHook /path/to/mute-off.sh
Notes:

*

*/path/to/ is the location of the scripts, I used /Library/Scripts/

*you can skip the unmuting loginhook (i.e. each logout will silence your machine), but I like it this way because I always have sound
  available exactly at the volume level I set last time

*root has to be the owner of the script files - running an editor from command line with sudo is the easiest way to achieve that
  (otherwise you need to chown)

*to delete the hooks, use the following:
sudo defaults delete com.apple.loginwindow LoginHook
sudo defaults delete com.apple.loginwindow LogoutHook

(source)


text:
Q: fire matlab uitable cellselection callback on mouse up I have a uitable with a checkbox column.
I want to toggle the checkbox status for each selected cell. Clearly, that does not work when the callback function executes when the user is still adding cells to the selection.
It should rather execute not earlier than the user releases the mouse.
The normal behaviour of a cell selection callback function however fires every time the selection area canges.
How can one change this behaviour?
A


text:
Q: App Engine error after Python web app is deployed - BlockingIOError: [Errno 11] Resource temporarily unavailable I am running my web app on a standard environment on Python 3.7 and when I test it locally everything works fine. However, after I deploy my app I am receiving the following error when the app tries to save files to the /tmp location that I have designated:
BlockingIOError: [Errno 11] Resource temporarily unavailable

This is how am designating the path to save as well as the file name.
file_num = os.urandom(10).hex()

handle, path = tempfile.mkstemp()

ytdl_format_options = {'format': 'bestaudio/best','outtmpl':path + 'song'+ file_num +'.mp3', 'quiet': True}

I'm not sure what is causing this error or if there is some type of config file setting that I am missing either on app.yaml or on gunicorn. I also tried locating the gunicorn files on the glcoud shell but they were not showing up in the directory.
I have noticed that my app will randomly work correctly when I commit new changes to files and re-deploy the app, however it will only work once and then if I immediately try running the function again it fails. This is the error I am receiving:
Traceback (most recent call last):
  File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 279, in handle
    keepalive = self.handle_request(req, conn)
  File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 348, in handle_request
    six.reraise(*sys.exc_info())
  File "/env/lib/python3.7/site-packages/gunicorn/six.py", line 625, in reraise
    raise value
  File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 331, in handle_request
    resp.write_file(respiter)
  File "/env/lib/python3.7/site-packages/gunicorn/http/wsgi.py", line 403, in write_file
    if not self.sendfile(respiter):
  File "/env/lib/python3.7/site-packages/gunicorn/http/wsgi.py", line 393, in sendfile
    sent += sendfile(sockno, fileno, offset + sent, count)
BlockingIOError: [Errno 11] Resource temporarily unavailable

A: From Filesystem:

The runtime includes a full filesystem. The filesystem is read-only
  except for the location /tmp, which is a virtual disk storing data
  in your App Engine instance's RAM.

So:

*

*using any location other than /tmp won't work

*the amount of available space is limited. Because of this your app needs to take care of deleting the temporary files after use. The behaviour you describe suggests the available space may only be enough for 1 of your files.

Another thing to consider is multiple parallel requests: if each of such request could create its own file, then the error could be hit because multiple files would be written simultaneously by different such requests. Adding a scheme limiting the number of requests processed in parallel would be a possible approach.
While not 100% certain I suspect the limit may also be dependent on the instance's total amount of RAM, in which case your app's configured instance class would matter as well. To check if this is true just temporarily configure an instance class with more RAM and see if that helps (without cleaning up the files maybe it'd work more than once before hitting the error, for example).
If the above suspicion is confirmed then choosing an appropriate instance class could also be an approach for addressing the problem.
Despite applying all the above it may still be possible to hit the issue, for example if some of the files you're writing are simply too big. If so then using the local filesystem is not appropriate for your app. A possible alternative would be to store your files in Google Cloud Storage (GCS) instead.


text:
Q: git format patch limit? I am trying to cherry pick some commits in my repo but it keeps on failing.
(I tried this tutorial on SO: "What is the best way to git patch a subrange of a branch?")
So I did a workaround:

*

*just do a git format-patch of the commits

*and just delete the extra files.

Really dirty stuff, but a bit easier to do.
So I do a
git format-patch -66

(the commit I was looking for was 66 commits away)
Problem with this is it keeps stopping at 047.
What gives? Is there a limit to the patches I can generate?

A: The -<n> option of git format-patch is a bit tricky, as this thread illustrates, from git contributor (for gitweb) and SO user Jakub Narębski:

It looks like there is a conceptual bug in how git-format-patch works, namely that '-<n>' is passed to rev-list / log generating machinery, and it limits number of commits to consider;
if some of those commits are merge commits, which cannot be represented as patches, the number of patches it generates is less than specified <n> (as you can see in
  the example I have provided, where <n> == 3, and git-format-patch generated 2 patches, not 3).
In extreme case (like 'pu') it can generate no patch.

(pu being here the public branch of the git-scm repo.)
In the OP's case, as he points out in the comment, it could mean 19 commits that are merge patches.

Jakub goes on proposing the following solution:

Update git-format-patch documentation to say 'commits' instead of 'patches',
  and perhaps also be loud about commits we are skipping, so that my example would look e.g. like this:

 $ git format-patch -3
 0001-gitweb-Prepare-for-splitting-gitweb.txt
 0002-gitweb-Create-Gitweb-Git-module.txt
 Skipping merge commit: Merge branch 'maint'

, to which Ramkumar Ramachandra proposes last August (2010) to write a patch.
You can see that patch simmering in this September 2010 what's cooking in git.git

[New Topics]
rr/format-patch-count-without-merges (2010-08-28) 2 commits
   - format-patch: Don't go over merge commits
   - t4014-format-patch: Call test_tick before committing

and is still in the latest what's cooking (Sept. 27th) in the [Cooking] section, with the following annotation:

Comments from potential users?


text:
Q: $(a+b\sqrt{2})^n =(c+d\sqrt{3})^m =>ab=cd=0$. If $a,b,c,d \in Q, m,n \in N^*$ and $(a+b\sqrt{2})^n =(c+d\sqrt{3})^m$ then to show that
$ab=cd=0$.
An idea to solve it by contradiction but ...

A: Assume that $AB\neq0$.
Hint: $\mathbb{Q}[\sqrt{2}] \cap \mathbb{Q} [\sqrt{3}] = \mathbb{Q}$.

 This tells us that $(a+b\sqrt{2})^n = p \in \mathbb{Q}$.

Hint: Consider conjugates.

 Taking the conjugates, we get that $(a-b\sqrt{2})^n = p$. Taking the difference, we get that $ 2b \sum {n \choose 2i} a^{n-2i}b^{i}2^i = 0$.

If $n$ is even, we have a non-zero ($2b$) multiplied by a (positive) sum of squares, which can't be 0. This is a contradiction.

 If $n$ is odd, we have $2ab \sum{n \choose 2i} a^{n-2i-1} b^i 2^i = 0 $. Once again, we have a non-zero ($2ab$) multiplied by a (positive) sum of squares, which can't be 0. This is a contradiction.

Hence, $AB=0$. Similarly, $CD=0$.


text:
Q: Any Graphical Text Editor for Amazon Linux on EC2? I am looking for something like gedit to use with my amazon linux ec2 instance. I am quite a bit of coding and would prefer the graphical environment over using vim. I am coding mainly php and javascript.
I am not using gedit as the package is not found by yum. I know that I can add the repo, etc. But I am hoping for something that is in the standard repos.
I am hoping someone could provide something like the below command with blah being what ever programs I need to install.
yum install blah blah blah

A: Use SFTP put and get commands from your cmputer, or set up filezilla on a folder in your computer(same protocols just pretty graphical interface) to sync with items from that folder to a folder on your EC2 instance.

A: Assuming you have ssh access to your linux instance on amazon - just use sshfs to mount the remote code directory and use whatever your preferred local poison is.
Not that I think this is a sensible approach; the suggestions in the comments make far more sense.


text:
Q: Overriding primary key protection in Rails Is there a way to overide the mass assignment protection on a model's primary key in Rails ?
My seed.rb data won't load because of it.
Update
I've found including the following code in the model removes the protection
def attributes_protected_by_default
  default = super
  default.delete self.class.primary_key
  default
end

Not ideal

A: Use attribute direct assignment. You can also take advantage of blocks.
Model.create! do |m|
  m.id = 27
  m.attribute = "foo"
end

A: I'm using rails 3.1 and none of the above answers work for me (working with a legacy db schema).
This works though:
class ActiveRecord::Base

  def self.no_pk_protection!
    # yikes
    default_scope :order => primary_key # this is necessary so first and last don't fail
    attr_accessor :mock_pk
    set_primary_key :mock_pk
  end

end

...and then:
class Category < ActiveRecord::Base

  no_pk_protection!

end

A: There is rarely a need to directly touch foreign keys e.g.
post = Post.create :title => "Lorem ipsum", :text => "dolor sit amet…"
comment = Comment.create :text => "Etiam mi mi, imperdiet a tempus suscipit…"
comment.post = post

A: Removing mass-assignment protection for the sake of seeding is, let's just say, unwise. Weppos suggested using direct assignment, to which you said:

Not ideal for seed data where you're trying to create significant numbers of records.

How does using direct assignment make a difference? You can iterate over an array or hash of data populating it with direct assignment just as easily as passing hash into constructor. You aren't really saving anything.
Another way would be to populate database directly with raw SQL, but seeding is not the kind of operation you need to run so frequently that it must be optimized.


text:
Q: Cassandra BETWEEN & ORDER BY operations I wanted to perform SQL operations such as BETWEEN, ORDER BY with ASC/DSC order on Cassandra-0.7.8.
As I know, Cassandra-0.7.8 does not have direct support to these operations. Kindly let me know is there a way to accomplish these by tweaking on secondary index?
Below is my Data model design.
Emp(KS){
    User(CF):{
         bsanderson(RowKey): { eno, name, dept, dob, email }
     prothfuss(RowKey): { eno, name, dept, dob, email }
}
}

Queries:
 - Select * from emp where dept='IT' ORDER BY dob ASC.
 - Select * from emp where eno BETWEEN ? AND ? ORDER BY dob ASC.

Thanks in advance.
Regards,
Thamizhananl

A: Select * from emp where dept='IT' ORDER BY dob ASC.

You can select rows where the 'dept' column has a certain value, by using the built-in secondary indexes. However, the rows will be returned in the order determined by the partitioner (RandomPartitioner or OrderPreservingPartitioner). To order by arbitrary values such as DOB, you would need to sort at the client.
Or, you could support this query directly by having a row for each dept, and a column for each employee, keyed (and therefore sorted) by DOB. But be careful of shared birthdays! And you'd still need subsequent queries to retrieve other data (the results of your SELECT *) for the employees selected, unless you denormalise so that the desired data is stored in the index too.
Select * from emp where eno BETWEEN ? AND ? ORDER BY dob ASC.

The secondary index querying in Cassandra requires at least one equality term, so I think you can do dept='IT' AND eno >=X AND eno <=y, but not just a BETWEEN-style query.
You could do this by creating your own index row, with a column for each employee, keyed on the employee number, with an appropriate comparator so all the columns are automatically sorted in employee-number order. You could then do a range query on that row to get a list of matching employees - but you would need further queries to retrieve other data for each employee (dob etc), unless you denormalise so that the desired data is stored in the index too.  You would still need to do the dob ordering at the client.

A: As I know  the columns will be sorted by comparator when you create column family and you can use clustring key for sorting on your opinion
and row in column family will be sorted by partitioner
I suggest you read this paper
Cassandra The Definitive Guide   Chapter 6


text:
Q: Turning on 'pretty viewing' in multi-indexed pandas DataFrame I have a multi-indexed pandas dataframe which looks like this:
                                         RFI
(Smad3_pS423/425_customer, 0, 1)    0.664263
(Smad3_pS423/425_customer, 0, 2)    0.209911
(Smad3_pS423/425_customer, 0, 3)    0.099809
(Smad3_pS423/425_customer, 5, 1)    0.059652

I've seen multi indexed data frames in the doc that are 'sparce-ified' to pretty viewing. So in this case it would look something like this:
                                         RFI
Smad3_pS423/425_customer  0  1    0.664263
                             2    0.209911
                             3    0.099809
                          5  1    0.059652

Does anybody know how to turn this option on? I've tried         pandas.set_option('display.multi_sparse', True) but this did not work.
=============Edit ==================================
To create the multi-index I used:
    df.index=df[['Antibody','Time','Repeats']]
    df.drop(['Antibody','Time','Repeats'],axis=1,inplace=True)

When I use df.index I get the following output:
Index([ (u'Smad3_pS423/425_customer', u'0', u'1'),
        (u'Smad3_pS423/425_customer', u'0', u'2'),
        (u'Smad3_pS423/425_customer', u'0', u'3'),
        (u'Smad3_pS423/425_customer', u'5', u'1'),
        (u'Smad3_pS423/425_customer', u'5', u'2'),
        (u'Smad3_pS423/425_customer', u'5', u'3'),
       (u'Smad3_pS423/425_customer', u'10', u'1'),
       (u'Smad3_pS423/425_customer', u'10', u'2'),
       (u'Smad3_pS423/425_customer', u'10', u'3'),
       (u'Smad3_pS423/425_customer', u'20', u'1'),
       ...
                     (u'a-Tubulin', u'120', u'3'),
                     (u'a-Tubulin', u'180', u'1'),
                     (u'a-Tubulin', u'180', u'2'),
                     (u'a-Tubulin', u'180', u'3'),
                     (u'a-Tubulin', u'240', u'1'),
                     (u'a-Tubulin', u'240', u'2'),
                     (u'a-Tubulin', u'240', u'3'),
                     (u'a-Tubulin', u'300', u'1'),
                     (u'a-Tubulin', u'300', u'2'),
                     (u'a-Tubulin', u'300', u'3')],
      dtype='object', length=216)

A: You can use MultiIndex.from_tuples, because index contains tuples:
df = pd.DataFrame({'RFI':[0.664263, 0.209911, 0.099809, 0.059652]},
                   index=[('Smad3_pS423/425_customer', 0, 1),
                          ('Smad3_pS423/425_customer', 0, 2),
                          ('Smad3_pS423/425_customer', 0, 3),
                          ('Smad3_pS423/425_customer', 5, 1) ])
print (df)
                                       RFI
(Smad3_pS423/425_customer, 0, 1)  0.664263
(Smad3_pS423/425_customer, 0, 2)  0.209911
(Smad3_pS423/425_customer, 0, 3)  0.099809
(Smad3_pS423/425_customer, 5, 1)  0.059652

df.index = pd.MultiIndex.from_tuples(df.index)
print (df)
                                   RFI
Smad3_pS423/425_customer 0 1  0.664263
                           2  0.209911
                           3  0.099809
                         5 1  0.059652

EDIT:
It seems you need set_index:
df = df.set_index(['Antibody','Time','Repeats'])


text:
Q: Follow download link and dismiss modal? I have inherited a GUI written with Angular, and at the moment I don't even know enough to trim it down to a fiddle.  So I'm hoping this is more straightforward than it appeared on a quick Google.
I have a modal dialog created using Bootstrap that is basically the same as the live demo here: http://getbootstrap.com/javascript/
A copy of the source from that link:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

The main difference in my case is that the "Save Changes" button is actually a link - to a resource which is downloaded without leaving the page.  It looks like this:
Download

My goal is to have the above modal dialog dismissed when the link is clicked, while still downloading the file.  If I use data-dismiss, the download doesn't happen.
If I need to go digging around the code, that's fine, but I'm hoping there's a simple change to the template that will do the trick.  Any suggestions?

A: You have to close the modal yourself. Here is a bootstrap.js only solution without angular. In angular you would open the modal with angular-bootstrap and close it also that way.
Download

function closeModal() {
  $('#myModal').modal('hide');
}

http://plnkr.co/edit/0sRb5VdT9isEFdJ66Rxe?p=preview

A: Here's a working Plunker.
JS
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.hideAndDownload = function() {
    $('#myModal').modal('hide');

    var link = document.createElement("a");
    link.download = "data:text/html";
    link.href = "http://code.jquery.com/jquery-1.11.3.min.js";
    link.click();
  }
});

Markup
        <button type="button" class="btn btn-primary" ng-click="hideAndDownload()">Save changes</button>

A: First, when using with AngularJS 1.x, always use Bootstrap UI.

When using Bootstrap UI's $uibModal, it is way easier to manipulate the modal, and pass data between the view and the modal. The reason the link does not work, is because the modal should be closed first.
You can create a simple function which replaces href or ng-href: It closes the modal first, and goes to the link second.
And, remember, please do not use jQuery, and always try to use AngularJS dependencies like $window instead of window, when they're available. This also goes for onclick. always use ng-click, and handle the logic in your controller.

In your template, add the controller, and an ng-click-attribute:

     Go

In your controller, add the logic, for closing the modal, and following the link:
app.controller('MyCtrl', function($uibModalStack, $window) {
    this.go = function(path) {
        $uibModalStack.dismissAll();
        $window.location.href = path;
    }
})


text:
Q: How to add data from list to excel using apex coding I am querying some fields of Account objects records. And i am storing them in a list. Now i want to send this data through mail with  excel sheet attached(which contains list data of Account Records) on click of send email from VF page. But i am getting the error as blob variable do not exist. Please check the below code.
     List<Account>  ObjectList1 = [SELECT id,Name FROM Account];
     Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
     blob csvBlob = Blob.valueOf(ObjectList1);
     string csvname= 'Duplicate.xls';
     csvAttc.setFileName(csvname);
     csvAttc.setBody(csvBlob);
     Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
     String toAddresses = 'xyz@abc.com';
     String subject ='Duplicate Data';
     email.setSubject(subject);
     email.setToAddresses( toAddresses );
     email.setPlainTextBody('Duplicate Data');
     email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
     Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

A: There are a couple of bits that won't work in your code:
Blob csvBlob = Blob.valueOf(ObjectList1);

ObjectList1 is List<Account> in your code. Blob.valueof takes String as input. This is the source of your error.
Another error is in this line:
email.setToAddresses(toAddresses);

This method requires input of List<String>, and you are passing a single string.
But I think what you will have the most success by running a report through the Analytics API and generate the results as CSV (String) and then pass it into your Blob.valueof() method. This technique is discussed in another StackExchange question that you can find here.
Generating this through a report gives you the ability to change the data produced in the PDF without changing code. You can also secure access to the report, or open it up to other users to modify, if need be.


text:
Q: Bullet Prefab fire in the same direction the player is facing So I am trying to have my bullet prefab fire in the same direction that my player is facing. Currently if the player faces north that's where the bullet fires, if the player faces south the bullet still fires north shooting straight through the player backwards.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FireRocket : MonoBehaviour
{
    public GameObject rocketPrefab;
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject rocketObject = Instantiate(rocketPrefab);
            rocketObject.transform.position = this.transform.position + transform.forward;

        }
    }
}

The bullet has a box collider and a rigidbody with the script attached. What else do i need to include so that I can have my bullet fire in the same direction my player is facing?
Rocket Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rocket: MonoBehaviour
{
    public float speed = 15f;
    public float RocketLife = 10f;

    private float RocketLifeTimer;
    // Start is called before the first frame update
    void Start()
    {
        RocketLifeTimer = RocketLife;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position += transform.forward * speed * Time.deltaTime;

        RocketLife -= Time.deltaTime;
        if (RocketLifeTimer <= 0f)
        {
            Destroy(this.gameObject);
        }
    }
}

A: you need to add transform.rotation = player rotation / or camera rotation


text:
Q: In MySQL, should I add an index even if the query that scans the table is only ran once a month? Concretely, is it worth it to add an index to a query that scans the table of a mysql database,
even if that index would only be used once a month?
For example, having a users a table and then querying for all the users of a certain type.
EXPLAIN SELECT type FROM users WHERE type in (1,3);

+----+-------------+------------------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table            | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+----+-------------+------------------+------+---------------+------+---------+------+--------+-------------+
|  1 | SIMPLE      | users            | ALL  | NULL          | NULL | NULL    | NULL | 1000685 | Using where |
+----+-------------+------------------+------+---------------+------+---------+------+--------+-------------+

A: An IN clause breaks down to an OR
SELECT type FROM users WHERE type = 1 OR type = 3;

OR is typically (but not always) non-SARGable. That means an index won't be used too seek data but will be scanned. This is the same (roughly) as scanning the table anyway: same number of rows.
So given there is minimal benefit, I wouldn't bother in most cases.
If you have millions of rows and the query is blocking other processes, then you can do this if you have an index. No you have 2 seeks.
SELECT type FROM users WHERE type = 1
UNION ALL
SELECT type FROM users WHERE type = 3;

Summary: not worth it unless you have a big table and blocking issues.

A: Here is one sure way to know if an index is worth it:
Run these queries:
SELECT type,COUNT(1) indtypecount FROM users GROUP BY type WITH ROLLUP;
SELECT COUNT(DISTINCT type) typecount FROM users GROUP BY type WITH ROLLUP;

This query will give you the count of each type (indtypecount aka individual typecount) and the table count as the last row.
If indtypecount is more than 5% of the rowcount of the whole table, the MySQL Query Optimizer will ignore any index no matter how many times you run ANALYZE TABLE.
If your table is huge and the indtypecount for a type is less than 5%, an index scan is better than a full table scan anyday.
If typecount (cardinality of type) is something ridiculously small, this is all a moot point. Indexing values such as gender (M,F), day of week, active status, and marital status would produce indexes that resemble monster link lists of types that the MySQL Query Optimizer would find totally useless and, thus, space wasted.
If the running time of once-a-month queries is not a concern, indexing or not is strictly your personal choice.


text:
Q: DataGridView becomes null for some reason I have a NET 2.0 framework ASP.NET application ..
The page I'm having trouble with has a button (B1), and the below that a DataGridView (DGV), and then below that a second button (B2) ..
Initially only B1 is visible. When user clicks B1, I do some DB queries, fetch some data, put it in a DataTable, and then set the DataSource of that DGV to this DataTable .. B1 also makes DGV and B2 visible, both of which were invisible before .. Now user fills in some data in the now-visible DGV and clicks B2 ..
Problem is that in B2's code, if I try to see the DataSource of that DGV, its null !? .. I need to access the updated values in that DGV .. How do I do that ?
I've tried a few hacks, but nothing seems to work .. I've sort of got it working through FindControl, but I don't want to use that because I need the original DataTable for other reasons (not mentioned here because they're quite complex) ..
Code behind B1, setting DataTable DataSource:
epsDGV.DataSource = epsDataDT; // epsDataDT is the DataTable:
Code behind B2, fetching DataTable:
DataTable epsDataDT2 = (DataTable)epsDGV.DataSource; //returns null

A: DataSource is not available during a postback. It is used during the current page lifecycle to fill the grid with the relevant data for each row, and is then discarded.
If it didn't do this, then it would need to send it back to the client inside the viewstate. Given that you could have handed it a list containing thousands of records (only some of which it might be showing, depending on paging settings), it would cause huge bloat to the viewstate - all of which needs to be sent to the client, then back up to the server when you clicked on B2.
Instead, the grid control will keep track of the data populated into its columns. This will include the changes made during inline editing.
Most examples online I've found suggest using FindControl to get the new value back, and using ViewState to store (and retrieve) the datasource - if you really do need to save it. However, I would highly recommend against doing that unless you can guarantee that the datasource is very small - otherwise you risk choking the clients bandwidth (particularly if they are on a slow connection)
If you need to store it in Viewstate, just create a property like below (NB: your datasource object needs to be serializable, or it won't be able to get stored in the ViewState):
public List<Items> Items
{
    get
    {
        if (ViewState["Items"] != null)
            return (List<Items>)ViewState["Items"];
        else
            return null;
    }
    set { ViewState["Items"] = value; }
}

then set it during your Data Load methods. On postback, you can call the property to pull it back out of the Viewstate.


text:
Q: Hashed shard key in MongoDB on the _id so then what? If I do create a hashed index with ensureIndex({ _id: "hashed"}) will Mongo know to take any queries on the _id field and run them against the hashed index? Or do I need to update all the queries that use _id to be the _id_hashed?

A: Mongodb doesn't modify the _id field when a hashed index is created.  It will do the right thing, and query against _id appropriately.  The hash will only be used to query and balance the shards.


text:
Q: Integrate CKEeditor with ACEeditor Can any tell how to integrate CKEeditor with ACE editor as codesnippet.
Now I use CKEditor with highlight, but try to use with ACE (https://ace.c9.io/#nav=about)
Detailed explanation:
I use ACE as an editor for PLSQL, SQL, Javascript, ...
For documentation, I use CKE. But in some CKE documents, I need to include code (PlSql, Sql, JS, css).
I use a plugin in CKE to highlight syntax. That plugin is "codesnippet" and the syntax highligter is uses by default is "highlight".
What I try is to change the default syntax highligter in CKE to use ACE. I've seen it's possible, or perhaps it was possible Integrate CKE and ACE, but that documentation is old and example doesn't exists.
Thanks for your help

A: Not sure if I fully understand your needs "codesnippet", so taking a shot in the dark here.
I use CKEditor plugin http://ckeditor.com/addon/pbckcode which has the ACE Editor for many projects.
You might read more about the plugin here to see if it fits your needs. I have been very happy with it.


text:
Q: Is there a filter to define the OG image on a given post? I am looking for a filter to define what image on a post sets the facebook OG image. In my case I have the image I want to use in a post meta field.
I have looked around but am unsure of the best way to handle this. Is there a core wordpress filter for this? If so I could not find one.
One solution that I looked into was through modifying the yoast seo plugin filters since we do have that plugin on our site. By default it looks to put the OG meta on the featured image which is not what I am looking for.

A: The wpseo_opengraph_image filter can only be used to modify the existing og:image. Otherwise, you will need to hook into the wpseo_opengraph action to add a different image.
Here's an example of adding an image from a custom field on the post object (assuming you're using ACF here).
function my_wpseo_opengraph() {
    global $post;

    if (isset($post)) {
        $og_image = get_field('your_field_name', $post->ID);
        if ($og_image) {
            $image_url = $og_image['sizes']['large'];
            $GLOBALS['wpseo_og']->image_output($image_url);
        }
    }
}

add_action('wpseo_opengraph', 'my_wpseo_opengraph', 29);


text:
Q: Udp readfrom until the end Socket Used : udp
I have a client who sends 5000 bytes and a server with this code :
Client code :
cod = sendto (sFd, (void *) buffer, 5000, 0, (struct sockaddr *)
            &soc, sizeof (struct sockaddr_in));

Server code :
//leghtBuffer = 5000
while (lenghtBuffer > 0 )
{
 //I will insert a signal if pass more than 30 s ...
 cod = recvfrom (sFd, buffer,256 , 0, (struct sockaddr *) &clientSoc, &lungimeSocket);

 printf("Am received %d bytes " ,cod );
 lenghtBuffer = lenghtBuffer - cod;

}

How can I read more than 1 time 256 bytes from this while (still using Udp socket)?

A: UDP is a message (datagram) based transport protocol and not stream based like TCP.  Each sendto/recvfrom works in terms of complete messages.
On the sending end, each call to sendto() creates a datagram of the specified size and data, which in your case is 5000 bytes.
On the receiving end, each call to recvfrom() copies the next message in the receive buffer.  Since your datagrams are 5000 bytes, but you're only providing a 256 byte buffer, your datagram is being truncated to 256 bytes as it's copied.
The recvfrom() OpenGroup specification clarifies the behavior in this case:

For message-based sockets such as SOCK_DGRAM and SOCK_SEQPACKET, the entire message must be read in a single operation. If a message is too long to fit in the supplied buffer, and MSG_PEEK is not set in the flags argument, the excess bytes are discarded.

You'll want to increase your buffer on the receive end to be 5000 bytes to account for the entire datagram


text:
Q: Do libraries reported by ldd resolve all undefined references of an input library? I'd like to know what exactly ldd does. Does it print only libraries from DT_NEEDED structures of .dynamic section? This is not a complete list of libraries that are required to resolve all undefined symbols of ldd's input library, as far as I know. In this case, what is the use of ldd at all?
Or does it really list all the libraries the ldd's input library actually depends on?
This is not a question about whether ldd shows dependencies of dependencies - this is a question about whether libraries reported by ldd resolve all the undefined symbols of ldd's input library.

A:
Does ldd print only libraries from DT_NEEDED structures of .dynamic section?

No, that is what readelf --dynamic does.

what is the use of ldd at all?

ldd shows what libraries the runtime linker ld.so loads when starting your executable or loading a shared library. This is a recursive process, e.g. an executable needs a shared library (DT_NEEDED), so that library gets loaded. Then it proceeds to load the dependencies of the loaded library (DT_NEEDED) and so on.
You don't necessarily need ldd, you can just set LD_DEBUG=all environment variable to make ld.so print that information and more. See man ld.so for more information.
Each loaded executable or shared library expose their defined exported dynamic symbols as a lookup scope (a hash table). Lookup scopes form a list. When resolving an undefined symbol ld.so walks the lookup scopes and finds the first one that defines the symbol and resolve the symbol reference. If ld.so reaches the end of lookup scopes it reports the symbol as unresolved.
There is no correspondence between the unresolved symbol name and an executable/shared library it is supposed to come from. ld.so loads all shared libraries from DT_NEEDED sections recursively, builds that list of lookup scopes and then looks for unresolved symbols in there.
How To Write Shared Libraries by U. Drepper explains this in full detail.

A: There is no way to derive the list of libraries needed to resolve undefined symbols in the shared object from the shared object itself. Such a list may or may not exist. It is easy to create a library with an undefined symbol that cannot be resolved by any existing library in the world.
# cat test.c
extern void foo99988776543quzzu();
void test() {
    foo99988776543quzzu();
}
# gcc -fPIC -shared -o libtest.so test.c

Here we have created a library with an undefined symbol that no other library in the world can satisfy — until we build one.
# cat foo.c
void foo99988776543quzzu() {}
# gcc -fPIC -shared -o libfoo.so foo.c

No magic in the world can help ldd libtest.so find libfoo.so. But it is easy to build a loadable, runnable program from libtest.so and libfoo.so.
# cat main.c
extern void test();
int main() { test(); }
# gcc main.c -lfoo -ltest -L. -Wl,-rpath=.
# ./a.out

ldd does not attempt to produce an impossible list of librarirs required to resolve undefined symbols. It does exactly what it says on the tin:

ldd prints the shared objects (shared libraries) required by each program or shared object specified on the command line.

The word "required" here does not mean "required to resolve undefined symbols". As said, a list of objects required to resolve undefined symbols cannot be produced. Instead, "required" means the set of dynamic dependencies, a.k.a. "shared objects required by DT_NEEDED recursively", as detailed in ldd(1) and ld.so(8).

what is the use of ldd at all?

DT_NEEDED sections contain sonames. ldd collects these sonames, recursively, and maps them to file paths using information in DT_RUNPATH, DT_RPATH, LD_LIBRARY_PATH, /etc/ld.so.conf, and whatever places we're searching this week. So the output of ldd contains a list of file paths for shared objects that will be loaded when the shared object on ldd command line is loaded. Here's an example:
#ldd ./test
    linux-vdso.so.1 (0x00007fff0593f000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fe7e6776000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe7e6385000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fe7e5fe7000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fe7e6d01000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fe7e5dcf000)

This is quite a bunch of useful information even for a most casual of observers. We see that test appears to be a 64-bit C++ program for x86 Linux built with a relatively recent version of gcc or a compatible compiler, for example. We also see that it has no third party dependencies.
On the other hand,
# ldd  /usr/bin/kdiff3
    linux-vdso.so.1 (0x00007ffeeed79000)
    libkparts.so.4 => /usr/lib/libkparts.so.4 (0x00007f801a14d000)
    libkio.so.5 => /usr/lib/libkio.so.5 (0x00007f8019c9b000)
    libkdeui.so.5 => /usr/lib/libkdeui.so.5 (0x00007f8019637000)
    libkdecore.so.5 => /usr/lib/libkdecore.so.5 (0x00007f801916b000)
    libQtCore.so.4 => /usr/lib/x86_64-linux-gnu/libQtCore.so.4 (0x00007f8018c79000)
    libQtGui.so.4 => /usr/lib/x86_64-linux-gnu/libQtGui.so.4 (0x00007f8017f84000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f8017bfb000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f801785d000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f801746c000)
    libQtXml.so.4 => /usr/lib/x86_64-linux-gnu/libQtXml.so.4 (0x00007f8017226000)
    libQtNetwork.so.4 => /usr/lib/x86_64-linux-gnu/libQtNetwork.so.4 (0x00007f8016ed1000)
    libQtSvg.so.4 => /usr/lib/x86_64-linux-gnu/libQtSvg.so.4 (0x00007f8016c78000)
    libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007f8016940000)
    ... many more lines ...

lists a lot of dependencies. If it fails to load, we should be able to use the list to figure out the reason. For example, any line that says => not found would be very helpful.

A:
Do libraries reported by ldd resolve all undefined references of an input library?

No. A shared library may be linked containing undefined references
(and this is commonplace). So it may be linked containing undefined references that
will not be resolved by any of its (recursive) DSO dependencies, or indeed any DSO or object file that exists.
foo.c
#include <stdio.h>

extern void bar(void);

void foo(void)
{
    puts(__func__);
    bar();
}

Make shared library:
$ gcc -shared -o libfoo.so foo.c

ldd libfoo.so lists recursively the DSO dependencies of libfoo.so:
$ ldd libfoo.so
    linux-vdso.so.1 (0x00007ffc30bf5000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd19209b000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fd19268e000)

None of them resolves the undefined reference to bar.


text:
Q: PostGIS installation on Ubuntu 10.12 (Amazon Services) On Ubuntu 10.12 (AMI on Amazon), I use aptitude to install Postgresql and PostGis.
On terminal running psql interactive prompt, I type CREATE EXTENSION postgis and
ERROR:  could not open extension control

file "/usr/share/postgresql/9.1/extension/postgis.control": No such
  file or directory

Is there something I forgot to install?

A: i can install postgre 9.2 and postgis 2.03 using:
-- INSTALL POSTGRESQL
-- remove previous version
sudo apt-get remove postgresql
-- require
sudo apt-get install libpq-dev
sudo apt-get install python-software-properties
sudo apt-get install software-properties-common
-- add new repository
sudo add-apt-repository ppa:pitti/postgresql
sudo apt-get update
-- install postgresql
sudo apt-get install postgresql-9.2 postgresql-common postgresql-server-dev-9.2 postgresql-contrib-9.2  postgresql-client-9.2
-- command for start or stop  the service
sudo /etc/init.d/postgresql start
sudo /etc/init.d/postgresql stop
*-- opcional if show error for character local setting use:
*sudo locale-gen en_US.UTF-8*   -- or other you need*
*-- configure file are in
/etc/postgresql/9.2/main/*
*-- if need change password to user postgres in linux use:
sudo passwd postgresql*
-- install pgadmin
-- if exist previous version
sudo apt-get remove pgadmin3
-- add repository
sudo apt-add-repository ppa:voronov84/andreyv
-- install
sudo apt-get update
sudo apt-get install pgadmin3
-- INSTALL POSTGIS 2.0.3
-- require
sudo apt-get install build-essential libproj-dev
sudo apt-get install libxml2-dev libjson0-dev xsltproc docbook-xsl docbook-mathml
sudo apt-get install libgdal1-dev
-- dowbnload an install GEOS
wget http://download.osgeo.org/geos/geos-3.3.8.tar.bz2
tar xvfj geos-3.3.8.tar.bz2
cd geos-3.3.8
./configure
make
sudo make install
cd ..
-- Download and install postgis
wget http://download.osgeo.org/postgis/source/postgis-2.0.3.tar.gz
tar xfvz postgis-2.0.3.tar.gz
cd postgis-2.0.3
./configure
make
sudo make install
sudo ldconfig
sudo make comments-install
-- configure
sudo ln -sf /usr/share/postgresql-common/pg_wrapper /usr/local/bin/shp2pgsql
sudo ln -sf /usr/share/postgresql-common/pg_wrapper /usr/local/bin/pgsql2shp
sudo ln -sf /usr/share/postgresql-common/pg_wrapper /usr/local/bin/raster2pgsql
--in psql
su postgres
psql
CREATE EXTENSION postgis;
CREATE EXTENSION postgis_topology;
CREATE EXTENSION btree_gist;
\q
-- prepare template if you need
------ postgis
sudo -u postgres psql template1
sudo -u postgres createdb template_postgis
sudo -u postgres psql -d template_postgis -c "UPDATE pg_database SET datistemplate=true WHERE datname='template_postgis'"
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.2/contrib/postgis-2.0/postgis.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.2/contrib/postgis-2.0/spatial_ref_sys.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.2/contrib/postgis-2.0/postgis_comments.sql
---- raster
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.2/contrib/postgis-2.0/rtpostgis.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.2/contrib/postgis-2.0/raster_comments.sql
---- topology
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.2/contrib/postgis-2.0/topology.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.2/contrib/postgis-2.0/topology_comments.sql

ok
thanks
Dante

A: PostGIS is now officialy supported by amazon RDS. That makes things very easy as explained in Setting up PostGIS.
See also PostGIS on Amazon RDS: A Spatial Database in the Cloud.


text:
Q: VirtualBox Guest OS High CPU Usage/Wrong CPU Speed? I have created a VM image out of a physical PC running Windows XP. I am now trying to run that image as a guest OS under Ubuntu Linux using VirtualBox. Everything seems to be running smoothly with the exception of one issue:
The performance of the guest OS is extremely slow, and it shows extremely high CPU usage to complete even simple tasks like opening up a dialog box.
One thing that I have noticed is that when I right click on "My Computer" and go to "Properties" in the guest OS, it shows the CPU information as follows:
Pentium (D) CPU 2.80Ghz
3.95Ghz, 896MB RAM
Now the intriguing part here is that the Pentium D 2.8Ghz processor is what the host machine is running, but I have no idea what the 3.95Ghz is about. I should also note that the 3.95Ghz during a previous boot of the image read something along the lines of 5.2Ghz!
I'm thinking there is a processor issue here. Does anyone have a solution? I have already tried uninstalling the processor in the Device Manager and rebooting, which didn't fix it.

A: I've had a similar issue and had to use the 'taskset' tool to set the affinity for CPU0; it appears a number of folks have the same problem. Here's a concise artticle:
https://help.ubuntu.com/community/VirtualBox/Previous
On my system I did it a little more directly than 'taskset -c 1' as they list; I found the direct command in the process list that launches the exact VM I want (which includes the VM's unique SID) and created a simple helper script to run it, like so:
#!/bin/sh
/bin/taskset 0x00000001 /usr/lib/virtualbox/VirtualBox -comment WindowsXP -startvm a7487a75-6119-4a14-a8ea-195ce2906a4b &

This was on Fedora, the Ubuntu paths might be a slight bit different so adjust as necessary.

A: "Pentium (D) CPU 2.80Ghz" is the processor name passed by the hypervisor (via cpuid), "3.95Ghz" is the estimated frequency computed by the guest. The calibration routine is probably confused by the virtualization... if the guest is using TSC for calibration and the host CPU does not have synchronized TSCs between cores then from guest POV the TSC will tick at an incorrect rate (it could even go backward); the Pentium D have synced TSCs. so the problem is elsewhere... SpeedStep probably (the host changes CPU frequency and the guest is not aware of the change).
Are you running the latest version of VBox?


text:
Q: Shuttle SG31G2V2 Intel Socket T(LGA775) Intel G31 Motherboard Model? Can anyone tell me what is the Intel motherboard model for this shuttle bare bone kit?
I know the chipset is G31 but for drivers from Intel what is the exact model number for this system?
Shuttle Computer SG31G2V2

A: Shuttle designs their own motherboards. IF you bought the SG31 new, there is a CD in the box with the drivers. If you got it second hand, the drivers are on Shuttles site. Don't forget to update the BIOS too. Older ones do not support all the latest Core2Duo and Core2Quad models.

A: I think it is a shuttle brand motherboard using an intel chipset.
Sg31G2 V2 on their site. "The Shuttle XPC Glamor SG31G2 V2 is designed based on Intel® G31 Express Chipset supporting the 45nm Intel® Core™ 2 multi-core processors. "
I think you will need to get the drivers from shuttle. Download Link They definitely have chipset drivers available for that model.
There is something to be said that this may be more of a superuser.com question.


text:
Q: Spark saveAsTextFile extremely slow near finish I'm basically running a sorting using spark. The spark program will read from HDFS, sort on composite keys, and then save the partitioned result back to HDFS.
pseudo code is like this:
input = sc.textFile
pairs = input.mapToPair
sorted = pairs.sortByKey
values = sorted.values
values.saveAsTextFile

Input size is ~ 160G, and I made 1000 partitions specified in JavaSparkContext.textFile and JavaPairRDD.sortByKey. From WebUI, the job is splitted into two stages: saveAsTextFile and mapToPair. MapToPair finished in 8 mins. While saveAsTextFile took ~15mins to reach (2366/2373) progress and the last few jobs just took forever and never finishes.
Cluster setup:
8 nodes
on each node: 15gb memory, 8 cores
running parameters:
--executor-memory 12G
--conf "spark.cores.max=60"
Thank you for any help.


text:
Q: Replacement for MC12149 (Voltage Controlled Oscillator) I need to build up a VCO from 250-350 MHz. I have found an interesting IC called MC12149 from Motorola. However, it seems to be archived and no longer manufactured. Looking at the datasheet, it looks very simple configuration. I have been searching here on Stack and in many stores yet I have not found a substitution for such IC.
Do you know any suitable IC?

A: You can use a colpitts oscillator with simple varactor control. Here's one that claims to oscillate at 1 GHz : -

It has a good tuning range too (2.3:1). Just scale components to suit your mid frequency and you should be in business. Note that the VCO control voltage may be a bit excessive but this comes with the territory for this type of control.
As for supply voltage to the main circuit, it's highly likely that this design will work down to below 3V. Here's one that uses a lower control voltage but has less range so, somewhere between the two might be exactly what you are looking for: -

Alternatively just buy one from mini-circuits: -


text:
Q: How to know if final equation is a circle (complex plane) in my proof of line transformation in a circle i get and equation:
$z'(\frac{\bar{w}}{c})+\bar{z'}(\frac {w}{c})+\bar {z'}{z'}=0$.
How can i show that it is a circle equation?

A: Let $z'\bar{w}=q\in\mathbb{C},c\in \mathbb{R}$;
$$z'(\frac{\bar{w}}{c})+\bar{z'}(\frac {w}{c})+\bar {z'}{z'}=z'(\frac{\bar{w}}{c})+\overline{{z'}(\frac {\bar{w}}{c})}+|{z'}|^2=c^{-1}(q+\bar q)+|{z'}|^2=2c^{-1}\Re(q)+|{z'}|^2.$$
Rearranging terms, the following equation is obtained:
$|z'|^2\equiv(\sqrt{x^2+y^2})^2=-2c^{-1}\Re(q)\in\mathbb{R}$
$\therefore x^2+y^2=-2c^{-1}\Re(q)$
Thus, the equation is a circle with a radius of $({2c^{-1}\Re(q)})^{\frac{1}{2}}$ iff $-2c^{-1}\Re(q)>0$. If $c^{-1}\Re(q)=0$, it is the zero point and if RHS $<0$, the equation is undefined.


text:
Q: How to adjust image dynamically with CSS for resizing of browser window So I want my image to be a 'fixed height' on the page. i.e. 500px. but upon resizing the browser window, I want the image to adjust automatically (I guess by zooming in and out) so it remains proportional and not blurred.
I have this:

.homepageheaderbox
{
height: 470px;
width: 100%;
margin-top:0%;
padding-left: 0;
width: 100%;
margin-bottom: 0;
margin-right: 0;
}
.homepageheaderbox img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

I know there is some unnecessary code here, I am still playing around with it.
Currently, the image resizes dynamically as the browser is resized, but the image height on the page changes also. To see more clearly what I am aiming to get, please visit: http://ryanteaches.com/ (<-- my target) and place it side by side with http://ryanteaches.com/newindex.html then readjust. You can visually see the difference.
Cheers!

A: Sorry for this not being a comment (still not 50 rep),
I could recommend you looking at Tutorial W3School's tutorial on responsive images. Or another solution for you is to use @media query in CSS Tutorial. I hope this helps you out!


text:
Q: Numberless range with different prefixes using siunitx? I'm using the siunitx package in the Masters/Doctoral Thesis template and I'd like to write something along the lines of "on timescales of μs-s" but am as yet unable to replicate this using the \SIrange function.
Can anyone help, or direct me to a previously given answer if I've missed one? I have found an answer to different prefixes but not with numberless units.
Thanks


text:
Q: System.Web.Http reference version reducing from v5.2.3.0 to v5.1.0.0 after installing fluentvalidation.webapi I want to install fluentvalidation.webapi package in my webApi project. When i install this package through nuget, i notice a strange thing that it reduces the version of my system.web.http reference.
System.Web.Http reference version before fluentvalidation.webapi package installation: version 5.2.3.0
System.Web.Http reference version after fluentvalidation.webapi package installation: version 5.1.0.0
Can anyone tell me reason for this? this further gives me other issues like Getting Microsoft.AspNet.WebApi.Cors version issue in WebAPI

A: Try upgrading System.Web.Http to latest version after installing fluentvalidation.webapi. If the dependant library uses specific version of System.Web.Http library, you can specify binding redirect in your web.config, which would basically instruct the app to use most recent version of the library. For documentation on setting binding redirects, please, see https://msdn.microsoft.com/en-us/library/twy1dw1e(v=vs.110).aspx


text:
Q: Should one use the definite article before a job title followed by a name? A banner one might spot in Minsk, Belarus these days reads,

Warm greetings to President of the Republic of India Pranab Mukherjee

My question is more specific than this one and this one. Neither has "President of <country>" and a name following a job title in a single sentence.
Is it necessary to put the definite article between "to" and "President"?

A: The basic question is whether you are saying "Greetings to [honorific][human's name]" or "Greetings to [official title], [human's name]".
You would say "Greetings to the President of the Republic of India", but "Greetings to Pranab Mukherjee".
Combine them one way and you get "Greetings to the President of the Republic of India, Pranab Mukherjee".  Combine them the other way and you get "Greetings to President of the Republic of India Pranab Mukherjee", where "President of the Republic of India" is an honorific (just like "Mr." or "General" or whatever).
The banner is correct as it appears, so long as it contains no comma.  It might read a hair better the other way (with comma), but protocol may dictate against that.

A: I think it would have been better if they had printed either of the following.

*

*Warm greetings to the President of India, Pranab Mukherjee

*Warm greetings to the President of the Republic of India, Pranab Mukherjee

The first one sounds good because there is no repetition of "the". The second one is correct, but it doesn't sound so good as the first one.
You need to use "the" to refer to unique things (though people tend to omit it often).
Examples

*

*The sun rose at 6:17 this morning.

*You can go anywhere in the world.

*Clouds drifted across the sky.

*The president will be speaking on TV tonight.

*The CEO of Total is coming to our meeting.

— EF.com


text:
Q: Angular.js route problems I have a app.js with defined routes and a menu with ng-href fields, like:

  My Content Flow

  My Videos

   My Blogs

Route Provider config:
$routeProvider
        .when('/:searchType?/:searchValue?', {
            templateUrl: 'partials/name/flow/',
            controller: 'FlowCtrl'
        })
.otherwise({
    redirectTo: '/'
});

$locationProvider.html5Mode(true);

:searchType is the user nick
:searchValue is gallery, movie or blog_post
Sometimes, when I click on the link, angular.js refresh the whole page, doing an application re-initialization. Can I avoid the whole refresh without using special directives and why sometimes works and sometimes doesn't?
If you want to see the demo go on filmannex with:
email: queeply@gmail.com
password: testing
Thanks

A: You should have a leading / before your ng-href values. I suspect they are interpreted as relative URLs so it is probably falling into the otherwise() bucket and redirecting to /
user
movies


text:
Q: Find and replace conditional column value by row for a large data frame in R All, I have a large genomic data that I want to do find-and-replace based on "REF" and "ALT" column values for each row. The replacement rules are:

*

*If the value = 0, replace it with "-/-"

*If the value = 1, replace it with two REF alleles

*If the value = 2, replace it with two ALT alleles

*If the value = 3, replace it with one REF allele and one ALT allele

Here is a small subset of an example data:
Chr Pos REF ALT  A  B  C  D  E
  1  70   A   G  1  0  1  1  1
  1  80   T   G  1  0  3  3  3
  1 100   C   T  1  0  1  1  1
  2  20   G   A  1  0  0  0  1
  2  80   C   T  1  0  0  0  2

The desired output is:
Chr Pos REF ALT    A    B    C    D    E
  1  70   A   G  A/A  -/-  A/A  A/A  A/A
  1  80   T   G  T/T  -/-  T/G  T/G  T/G
  1 100   C   T  C/C  -/-  C/C  C/C  C/C
  2  20   G   A  G/G  -/-  -/-  -/-  G/G
  2  80   C   T  C/C  -/-  -/-  -/-  T/T

Reproducible data frame:
df=data.frame(
  Chr=c(1,1,1,2,2),
  Pos=c(70,80,100,20,80),
  REF=c("A","T","C","G","C"),
  ALT=c("G","G","T","A","T"),
  A=c(1,1,1,1,1),
  B=c(0,0,0,0,0),
  C=c(1,3,1,0,0),
  D=c(1,3,1,0,0),
  E=c(1,3,1,1,2)
)

I wrote a for loop for the task:
K=data.frame()
for (r in 1:nrow(df)){
  k=df[r,]
  ks=df[r,-1:-4]
  ks[ks==0]="-/-"
  ks[ks==1]=paste0(k$REF,"/",k$REF)
  ks[ks==2]=paste0(k$ALT,"/",k$ALT)
  ks[ks==3]=paste0(k$REF,"/",k$ALT)
  ks=cbind(k[,1:4],ks)
  K=rbind(K,ks)
}

That worked okay, however, I have about 150,000 lines of them and the row by row operation takes very long time so I was wondering if there is a faster way to process this?
Thank you very much for the help!

A: We may use case_when - loop across the columns 'A' to 'E', create the format with sprintf based on the condition created in `case_when
library(dplyr)
df %>%
   mutate(across(A:E, ~ case_when(. == 0 ~ '-/-',
                  . == 1 ~ sprintf('%1$s/%1$s', REF),
                  .==2 ~ sprintf('%1$s/%1$s', ALT),
                   TRUE ~ sprintf('%s/%s', REF, ALT))))

-output
 Chr Pos REF ALT   A   B   C   D   E
1   1  70   A   G A/A -/- A/A A/A A/A
2   1  80   T   G T/T -/- T/G T/G T/G
3   1 100   C   T C/C -/- C/C C/C C/C
4   2  20   G   A G/G -/- -/- -/- G/G
5   2  80   C   T C/C -/- -/- -/- T/T

NOTE: As this is done by column and not by row, it should be much faster than the OP's approach


text:
Q: Java Powers display table I need to display an output like this:
Enter an integer: 3
Number  Squared Cubed

======  ======= =====

1       1       1

2       4       8

3       9       27
But instead, when I run the code, I get this output:

Number  Squared Cubed

======  ======= =====
3       9       27
In other words, I need to display the powers of an integer,including the powers of the numbers less than or equal to the integer.  The numbers of the lesser integers need to be listed but are not displayed along with the integer being entered.  How do I fix the code to make sure it outputs all of the integers that are less than or equal to the integer being entered?  There are no errors (i.e. red exclamation mark circles) but I need to figure out the proper calculation.
Here is the code:
====================
import java.util.Scanner;

public class Powers
{

public static void main(String[] args)
{

    System.out.println("Welcome to the Squares and Cubes Table");
    System.out.println();

    Scanner sc = new Scanner(System.in);
    String choice = "y";

    while(choice.equalsIgnoreCase("y"))
    {
            // get the input from the user
            System.out.println("Enter an Integer: ");
            int integerNext = sc.nextInt();

            System.out.println("Number" + "  " + "Squared" + "  " + "Cubed");
            System.out.println("======" + "  " + "======" + "  " + "======");

            for(int i = 1; i <= integerNext; i++)
                  {
                  i = integerNext;
                  int numberSquared = (int) Math.pow(i, 2);
                  int numberCubed = (int) Math.pow (i, 3);

             String message = "\n" + i + "       " + numberSquared + "       " + numberCubed;

             System.out.println(message);
             System.out.println();

             // see if the user wants to continue
              System.out.print("Continue? (y/n): ");
              choice = sc.next();
              System.out.println();
                  }
             }
        }
   }

Help is always appreciated. Thanks.

A: Firstly, as Nikhil said: "Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed".
Secondly, move the first closing curly brace to before getting user input - you want to run the loop, and only ask about continuing when that's finished, if I understand correctly.

A: Remove the line  i = integerNext; It is resetting the value of I and therefore only last row is printed

A: Your are almost there. Since you are looping from 1 to integerNext (which is 3 in your text), the looping variable i will get the values [1,2,3] each iteration, so you don't have to set i manually. When you do:
i = integerNext;

you are setting i to 3, so the loop will finish when it reaches the loop condition.
You may also want to put the "Continue?" check outside the loop:
for (int i = 1; i <= integerNext; i++) {
    int numberSquared = (int) Math.pow(i, 2);
    int numberCubed = (int) Math.pow(i, 3);

    String message = "\n" + i + "       " + numberSquared + "       " + numberCubed;

    System.out.print(message);
}

// see if the user wants to continue
System.out.print("\nContinue? (y/n): ");
choice = sc.next();
System.out.println();

A: import java.util.Scanner;

public class SquaresAndCubes {

    public static void main(String[] args)
    {
        // Welcome the user
        System.out.println("Welcome to the Squares and Cubes table");
        System.out.println();

        Scanner sc = new Scanner(System.in);
        String choice = "y";

        do
        {
            // Get input from the user
            System.out.print("Enter an integer: ");
            int integer = sc.nextInt();

            // Create a header
            String header = "Number  " + "Squared " + "Cubed   " + "\n"
                        +   "======  " + "======= " + "=====   ";
            System.out.println(header);

            int square = 0;
            int cube = 0;

            String row = "";
            for (int i = 1; i <= integer; i++)
            {

                square = i * i;
                cube = i * i * i;

                row = i + "       " + square + "       " + cube;
                System.out.println(row);
            }

            // See if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();

        }
        while (!choice.equalsIgnoreCase("n"));
    }
}

A: Basic way to do it with foor loop and some printlines
Scanner sc = new Scanner(System.in);
    System.out.print("What number would you like to go up to? ");
    int userInt = sc.nextInt();
    System.out.println("");
    System.out.println("Here is your table!");
    System.out.println("");
    System.out.println("number | squared | cubed");
    System.out.println("------ | ------- | -----");

    for (int i = 1; i <= userInt; i++){
        System.out.println(i + "      | " + (i * i) + "       |" + "  " +(i * i * i));
    }


text:
Q: Dynamic render of multiple custom markers with react-native-maps I have a major performance issue with rendering markers based on active filters on the map.
I have a data structure, which is something like
const businesses = [
  {
    ...location,
    businessType: 'Market'
  },
  ...etc
]

There's 150 items in that dataset right now. All of the markers are rendered by default. Currently I'm generating the data for markers randomly.
Now, I as well have categories which can be toggled, if category is toggled => render that business type.
Now, whenever I toggle categories my JS thread jumps to 0 fps and the UI thread get's blocked.
Here's my current code:
import React, { PureComponent } from 'react';
import { InteractionManager } from 'react-native';
import generateRandomMapData from 'utils/generateRandomMapData';
import CustomMarker from './CustomMarker';

const CENTER_OF_BERLIN = {
  latitude: 52.5200,
  longitude: 13.4050,
};

const RADIUS = 5000;
const AMOUNT_OF_MARKERS = 150;

class Markers extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      markers: null
    }
  }
  componentDidMount() {
    this.interactionHandle = InteractionManager.runAfterInteractions(() => {
      this.setState({ markers: generateRandomMapData(CENTER_OF_BERLIN, RADIUS, AMOUNT_OF_MARKERS) }, () => {
        this.interactionHandle = null;
      })
    })
  }
  componentWillUnmount() {
    if (this.interactionHandle) this.interactionHandle.cancel();
  }
  renderMarkers() {
    const { markers } = this.state;

    if (markers && markers.length) {
      return markers.map((b, i) => <CustomMarker location={b.location} key={i} businessType={b.businessType} />)
    }

    return null;
  }
  render() {
    return this.renderMarkers()
  }
}

export default Markers;

And the file for individual Markers
import React, { PureComponent } from 'react';
import { View, InteractionManager } from 'react-native'
import { Marker } from 'react-native-maps';
import { connect } from 'react-redux';
import SVG from 'components/svg/SVG'

const BUSINESS_COLORS = {
  market: '#EC6D52',
  farm: '#763DAB',
  restaurant: '#C45D72',
  UrbanFarm: '#4B85DD',
  store: '#65A077',
}

class CustomMarker extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      shouldRender: false
    }
  }
  componentWillMount() {
    const { businessType, categories } = this.props;

    this.interactionHandle = InteractionManager.runAfterInteractions(() => {
      if (this._getActiveCategories(categories).includes(businessType) !== this.state.shouldRender) {
        this.setState({ shouldRender: this._getActiveCategories(categories).includes(businessType) }, () => {
          this.interactionHandle = null;
        });
      }
    });
  }
  componentDidUpdate() {
    if (this.interactionHandle) this.interactionHandle.cancel();

    const { businessType, categories } = this.props;
    const { shouldRender } = this.state;

    this.interactionHandle = InteractionManager.runAfterInteractions(() => {
      if (this._getActiveCategories(categories).includes(businessType) !== shouldRender) {
        this.setState({ shouldRender: this._getActiveCategories(categories).includes(businessType) }, () => {
          this.interactionHandle = null;
        })
      }
    });
  }
  componentWillUnmount() {
    if (this.interactionHandle) this.interactionHandle.cancel();
  }
  _getActiveCategories(categories) {
    const active = [];

    for (let category of categories) {
      if (category.active) {
        active.push(category.icon)
      }
    }

    return active;
  }
  render() {
    const { businessType, location } = this.props;
    const { shouldRender } = this.state;
    const iconColor = BUSINESS_COLORS[businessType.toLowerCase()];

    const opacity = shouldRender ? 1.0 : 0.0;

    return (
      <Marker coordinate={{ ...location }} opacity={opacity}>
        <View style={{ width: 29, height: 36 }}>
          <SVG icon="Marker" width="29" height="36" fill={iconColor} />
        </View>
      </Marker>
    );
  }
}

const mapStateToProps = (state) => ({
  categories: state.categories
});

export default connect(mapStateToProps, {
})(CustomMarker);

The categories themselves live in Redux and the Markers are mapped based on that.
It seems that calling setState on like 25 affected markers at the same time is incredibly heavy, even if used InteractionManager.
Any ideas how to optimize this performance?


text:
Q: Why does $g \circ f$ being injective imply that $f$ is injective too? Algebraically I do understand the usual proof of the proposition, like the on in the accepted answer: If $g \circ f$ is injective, so is $g$
But I still am missing something. When I draw the composition of $g$ and $f$, I can draw $g \circ f$ as injective while $f$ is merely surjective. What am I doing wrong here? According to the proposition this should not be possible.
In the figure, $f$ is blue $g$ is red and thus $g \circ f$ is violet. Notice how $g \circ f$ is injective (while $g$ alone is not), but $f$ is not injective.

A: In your picture, $f$ is not surjective.
The beginning of the red arrow has no preimage, hence $f$ is not surjective but your result require $f$ to be a surjective function.
Edit: Also, as mentioned in the comment, $g\circ f$ is not injective as well.
btw, to make sure your function has a chance to be injective, make sure your codomain is at least as large as your domain. Notice that domain of $g\circ f$ is equal to the domain of $f$.
Strictly speaking, the second part is just the function $g$ and the whole picture is $g \circ f$.


text:
Q: What is the idiomatic way of creating foldable collection out of file hierarchy? Having a collection of files/directories I'd like to create a collection of all leaves files.
I'd like the resulting collection extend the clojure.core.protocols/CollReduce protocol.
Do I need to extend the protocol or are there helper functions for that?
In other words. Do reducers only help in parallel reduction or can I use them to effectively generate reducible collections in parallel as well?
To illustrate the problem let me show the implementation which could work, granted that the file hierarchy is no deeper than two levels (e.g our collection can contain files and directories, but the directories can contain only files)
(ns user
  [import [java.io File]])

(defn expand [reduction-function]
  (fn [result input]
    (if (.isFile input)
       (reduction-function result input)
       ; if not a file we assume it's a directory
       (reduce reduction-function result (.listFiles input)))))

(defn process [xfn c]
  (lazy-seq (when-let [s (seq c)]
    (concat ((xfn #(concat %1 (list %2))) '() (first s))
      (process xfn (rest s))))))

(def f (File. "C:\\WORK"))

(process expand [f])    ; => produces list of files

Now, it would be nice to have the expand defined in recursion-like style (or rather as a cascade of transformations), so it works for all levels, but executed in parallel fashion. As with reducers we can define early termination in reduction, I'd like to have ability to define generation (collection expansion) which stops when certain criteria is met (reaching file in directory hierarchy tree, as in file example)


text:
Q: Calling a Class Public Sub into a Form I created an Application all in Forms. I want to break the logic out into Classes. This should be rather simple. Below is my Method/Public Sub. I want to call it into a button in my form. I am not sure how to do this.expecting help from you.
Public Sub Test()
    Using conn = New OracleConnection(ODB)
        conn.Open()
        Me.ODB.Update(dt)
        Me.myDataSet.AcceptChanges()
        conn.Close()
    End Using
End Sub
Private Sub Update_Click(sender As System.Object, e As System.EventArgs) Handles Update.Click, Update.Click
     Test()
End Sub

A: your question is not so clear to me, but maybe that was your intent(?):
Public Class myOtherClass
Implements IDisposable ' optional
Public Sub Test()
    Using conn = New OracleConnection(ODB)
        conn.Open()
        Me.ODB.Update(dt)
        Me.myDataSet.AcceptChanges()
        conn.Close()
    End Using
End Sub
End Class

Public Class Form2
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myClassInstance As New myOtherClass ' create an instace of other class
    myClassInstance.Test() 'call the requested sub
    myClassInstance.Dispose() ' optioanl - if you implmented IDisposable in 'myOtherClass' you can dispose it when you finished using it
End Sub
End Class

A: Put your :
Public Sub Test()
    Using conn = New OracleConnection(ODB)
        conn.Open()
        Me.ODB.Update(dt)
        Me.myDataSet.AcceptChanges()
        conn.Close()
    End Using
End Sub

in a module else than a class could make the job.


text:
Q: How to debug Segmentation fault due to "Jump to the invalid address"? I am working on an application which runs on am335x arm processor.
I am defining following structure which contains function pointer to "Command" function. "Command" function is defined below in same file
ObjectDef BPObjectDef = { CCR_COMMS, 1, ATTRIBUTES, "BP", Command };

static BYTE Command( ObjectPtr Obj, BYTE Command)
{
<not writing code because function is big>
}

I cross complied above code and binary is generated. With objdump -t I can see that "Command" function got following address
00013f0d l     F .text  0000016c              Command

But when I run the binary on target machine I get following address for "Command" function
address of BPObjectDef.Command = 0x3f0d0000

as we can see that last two bytes of addressed are swapped with first two bytes. This leads to segmentaion fault while accessing this function.
Anybody has faced similar issue before? How to debug in this case? I guess I cannot use address sanitizer as it is an arm platform.Thanks

A: @Yunnosch you are genius! As you've mentioned in comments, address was getting altered because of structure padding. Using #pragma pack(1) before structure declaration solved the problem. Thank you very much


text:
Q: How to create multiple origins with Azure CDN Verizon Edgecast Premium? I come from AWS Cloudfront where I can create multiple origins for a given endpoint.
I can serve part of the url from one origin and part from another origin.
Is there anyway we can do with Azure CDN Verizon Edgecast Premium?
EDIT1: (Cloudfront Example with Single Distribution)
https://example.com/origin1/index.html <-- This is served from origin1
https://example.com/origin2/index.html <-- This is served from origin2
or like this also,
https://example.com/endpoint/index.html <-- comes from origin1
https://example.com/endpoint/index1.html <-- comes from origin2

A: Here is how I solved it. Looks horrible in the modern era, but it is what it is at the time of this writing.
If you want to have multiple origins. Create one endpoint for each origin.
Endpoint1 --> Origin1
Endpoint2 --> Origin2

Create another endpoint Endpoint to create rewrite rules to those endpoints with a rewrite rule.
Endpoint3/origin1 rewrite to Endpoint1
Endpoint3/origin3 rewrite to Endpoint2

You can create rewrite rules only to other endpoints and not to any origin.

Hope it helps.


text:
Q: How to save data in a few places how can I put data from my database in several places to save different data. I do not know if this is a completely understandable question, which is why I will try to bring them a bit closer.
I would like to save the names of dishes for each day of the week:
i.e. i have a list with the names of the days of the week:
- Monday,
- Tuesday,
- Wednesday,
- Thursday,
- Friday,
- Saturday,
- Sunday
and now I would like to save various dishes there when choosing a particular day. Eg on Monday, chop + potatoes, Tuesday - spaghetti etc. I know that I will have to use different tables to put information there, but I do not know how to do it if I want to write something else each day. Do I have to create a separate Activity for each day of the week and create separate tables for a specific day there?
I did not put in any code, I do not have a problem with it, just the problem I can not get to know.

A:
I know that I will have to use different tables to put information
  there

Not necessarily:-

*

*You could have a column in the dishes table for each day of the week.

*You could have a single column that could be used for all days of the week.

*

*e.g. if Monday were assigned the value 1, Tuesday 2, Wednesday 4, Thursday 8, 16, 32, 64.  (i.e  2 to the power of the day of the week (1-7)).

*Then if the dish were to be for Monday and Thursday then you could store a single value comprised of logically OR'ing the respective days 1 (Monday) logically OR'd with 8(Thursday) would be 9; adding Friday(16) the stored value would then be 25.
Assuming the latter, you could then extract (where daysused is the column that indicates the day(s) the dish should appear on the menu):-
Mondays menu using :-
SELECT * from dishes WHERE (daysused & 1) > 0

Fridays menu using :-
SELECT * from dishes WHERE (daysused & 16) > 0

Weekends menu using :-
 SELECT * from dishes WHERE (daysused & (32 | 64)) > 0

Do I have to create a separate Activity for each day of the week and
  create separate tables for a specific day there?

No. You could have a general activity, perhaps with a button to select the day of the week or a spinner or a Radio group.
Clicking/selecting would calculate the day or days which is then used to determine the days to be viewed, this value being fed into the selection criteria along the lines of the above. The resultant Cursor could then be used as the source of a ListView to display the menu.
Example :-
The Database Helper
public class MyMenuDBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mymenu";
    public static final int DBVERSION = 1;
    public static final String DISHES_TABLE = "dishes";
    public static final String DISHES_ID_COL = BaseColumns._ID;
    public static final String DISHES_NAME_COL = "dishes_name";
    public static final String DISHES_DAYSONMENU_COL = "dishes_daysonmenu";

    MyMenuDBHelper(Context context) {
        super(context,DBNAME,null,DBVERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String crtSQL = "CREATE TABLE IF NOT EXISTS " +
                DISHES_TABLE + "(" +
                DISHES_ID_COL + " INTEGER PRIMARY KEY, " +
                DISHES_NAME_COL + " TEXT, " +
                DISHES_DAYSONMENU_COL + " INTEGER " +
                ")";
        db.execSQL(crtSQL);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long addDish(String name,
                   boolean usemonday,
                   boolean usetuesday,
                   boolean usewednesday,
                   boolean usethursday,
                   boolean usefriday,boolean usesaturday, boolean usesunday) {

        int daysused = MainActivity.NODAYS_FLAG;
        if (usemonday) daysused = daysused | MainActivity.MONDAY_FLAG;
        if (usetuesday) daysused = daysused | MainActivity.TUESDAY_FLAG;
        if (usewednesday) daysused = daysused | MainActivity.WEDNESDAY_FLAG;
        if (usethursday) daysused = daysused | MainActivity.THURSDAY_FLAG;
        if (usefriday) daysused = daysused | MainActivity.FRIDAY_FLAG;
        if (usesaturday) daysused = daysused | MainActivity.SATURDAY_FLAG;
        if (usesunday) daysused = daysused | MainActivity.SUNDAY_FLAG;

        ContentValues cv = new ContentValues();
        cv.put(DISHES_NAME_COL,name);
        cv.put(DISHES_DAYSONMENU_COL,daysused);
        return this.getWritableDatabase().insert(DISHES_TABLE,null,cv);
    }

    public Cursor getMenu(int daystoinclude) {
        // SQL SELECT * FROM dishes WHERE (dishes_daysonmenu & the_daystoshow_as_passed) > 0
        Cursor csr = this.getWritableDatabase().query(DISHES_TABLE,null,
                "(" + DISHES_DAYSONMENU_COL + " &  ?) > 0",
                new String[]{Integer.toString(daystoinclude)},
                null,null,null
                );
        int count = csr.getCount(); //<<< Just for debugging breakpoint
        return csr;
    }
}

The "Single Activity" - MainActivity
public class MainActivity extends AppCompatActivity {

    public static final String TEST = "test";
    public static final int MONDAY_FLAG = 1 << 0;
    public static final int TUESDAY_FLAG = 1 << 1;
    public static final int WEDNESDAY_FLAG = 1 << 2;
    public static final int THURSDAY_FLAG = 1 << 3;
    public static final int FRIDAY_FLAG = 1 << 4;
    public static final int SATURDAY_FLAG = 1 << 5;
    public static final int SUNDAY_FLAG = 1 << 6;
    public static final int NODAYS_FLAG = 0;

    Button[] daybuttonids = new Button[7];
    ListView mMenuList;
    MyMenuDBHelper mDBHelper;
    Cursor mCsr;
    SimpleCursorAdapter mSCA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        daybuttonids[0] = (Button) this.findViewById(R.id.mon);
        daybuttonids[1] = (Button) this.findViewById(R.id.tue);
        daybuttonids[2] = (Button) this.findViewById(R.id.wed);
        daybuttonids[3] = (Button) this.findViewById(R.id.thu);
        daybuttonids[4] = (Button) this.findViewById(R.id.fri);
        daybuttonids[5] = (Button) this.findViewById(R.id.sat);
        daybuttonids[6] = (Button) this.findViewById(R.id.sun);
        mMenuList = this.findViewById(R.id.menulist);

        mDBHelper = new MyMenuDBHelper(this);
        addSomeDishes();

        mCsr = mDBHelper.getMenu(NODAYS_FLAG);
        mSCA = new SimpleCursorAdapter(
                this,   // Context
                android.R.layout.simple_list_item_1, // layout
                mCsr, // Cursor
                new String[]{MyMenuDBHelper.DISHES_NAME_COL}, // column(s)
                new int[]{android.R.id.text1}, // View
                0   // flags
        );
        mMenuList.setAdapter(mSCA);
        setButtonListeners();
    }

    private void setButtonListeners() {
        for (int i=0; i < daybuttonids.length; i++) {
            daybuttonids[i].setTag(new Integer(i));
            daybuttonids[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int daytouse = 1 << Integer.valueOf(v.getTag().toString());
                    Log.d("DAYTOUSE","Day to use is " + Integer.toString(daytouse));
                    refreshList(daytouse);
                }
            });
        }
    }

    private void refreshList(int daystoshowinmenu) {
        mCsr = mDBHelper.getMenu(daystoshowinmenu);
        mSCA.swapCursor(mCsr);
    }

    private void addSomeDishes() {
        mDBHelper.getWritableDatabase().delete(MyMenuDBHelper.DISHES_TABLE,null,null);
        mDBHelper.addDish("Chip and Fishes",true,false,false,false,true,false,true);
        mDBHelper.addDish("Egg under Toast", false,true, false, false,false,true,true);
        mDBHelper.addDish("Mashed Bangers", true, false,true,false,true,false,true);
    }
}

What the App looks like :-

*

*Initially (nothing as NODAYS was used for the cursor)

*

*Monday button clicked

*

*Tuesday Button clicked :-

*

*.... Sunday Button clicked :-

Of course you could have multiple tables,
Perhaps you'd have one table for the dishes and another table for the daily menus with the latter having an indicator for the day and the dish (i.e, a reference/link/association to the dish). This would be preferable say if you wanted to keep a tally of dishes served per day as then each combination of dish/day could be uniquely identified and a column could be included for the count of uses.


text:
Q: In Neptune's Brood, how does slow money work? New member here.
I'm reading Charles Stross' Neptune's Brood and I can't wrap my mind around the slow money concept. I just don't understand how it works.
From the description, it looks like a bond backed by the economy of the emitting star system. But bonds have a face value, a maturation date and an interest rate. Slow money doesn't have a maturation date as far as I can tell and the face value ins't clear. They're also referred as bitcoin-like, but it seems to be more for the cryptography and block-chain properties than an abstract nature.
So, can anybody explain how slow money works and where the incredible value comes from?

A: Stross spoke about "slow money" on his blog.

Slow money is a digital currency backed by debt—the debt incurred by
  constructing a new interstellar colony. To exchange slow money tokens
  requires something like (but not identical to) David Chaum's Digicash;
  all transactions need to by cryptographically signed by a trusted
  third party. With slow money, rather than relying on a "banker", each
  party can operate as a banker—but bank A can't sent cash to bank B
  without getting the transaction irrevocably notarized by bank C. By
  putting the third party in another star system, both participants in
  the exchange can verify that they're not being scammed, because to get
  your digicash packet countersigned by your banker you need to
  literally aim your laser communicator at their home star system. And
  wait. And wait a bit longer, because this whole process takes
  ages—slow money (thanks to requiring notarization/acknowledgement)
  travels no faster than a third the speed of light.

Essentially, the cost of creating a colony world and any onward ships is so vast and prohibitively expensive that only an economy based on long terms bonds valued in thousands of years can possibly function. Unless there's a good reason why one colony world would choose to keep paying another one so far into the future, the galactic economy would collapse and future colonisation would become impossible.

A: It's possible the conceit doesn't really hold together (but still falls apart in very interesting ways).
1) One possible approach is to think of slow money as a currency ("cash" in the sense that that word would appear on a balance sheet, though not literally coins and notes). By this interpretation, slow money is not made up of bonds denominated in some other currency. Slow money is a currency. It is also a currency constituting a separate sphere of exchange. In other words, slow money is only really used for building spaceships and settling stars, although there additionally may be status and clout associated with holding a lot of slow money. Conversion from one sphere to another is an elaborate and costly procedure (and not just for cultural reasons. There is also the usual thing of waiting for a third party to verify the transaction). Unless you are somehow connected with building spaceships and settling stars, you don't have much reason for holding a lot of slow currency. If you build a diverse portfolio, you would perhaps hold some as a hedge: in itself it is an extremely safe asset class, even less risky than "cash" (fast money).
Of course, you can still make high-risk loans denominated in slow money. The riskiness of any particular loan depends on that loan's particular circumstances. But the high credit risk (the chance that everyone on the colony will become infected by extraterrestrial fast prions and die, for instance) is counterbalanced by the low market risk (the chance that slow money will depreciate rapidly). Loans are possible in slow money that wouldn't be possible in fast money.
So it's just a currency, and a fiat currency at that. Any talk about it being "backed" by stellar colonization debt is a bit metaphorical: you can't show up somewhere and redeem it for property rights in interstellar infrastructure, or anything. It is not really "more valuable" than fast money. In one sense, it's differently valuable: it can be used to buy only certain things (terraforming, starships), and if you use it to buy something it's not meant to buy (Wispas, hats) you won't get as much bang for you buck. (In another more trivial sense, it's more valuable only in the sense that one cent of slow money happens to exchange for hundreds or thousands or millions of cents of fast money. But it's just a convention that the word "cents" is used for both: actually they're completely different units).
2) Or perhaps slow money is made up of bonds, as you suggest, issued by fresh colonies. It could perhaps be a perpetual bond, or a bond with an extremely long maturity (1000 years, then it turns into fast money).
(You would imagine the face value would be very high in cent terms, but it's not too hard to explain that away by some arbitrary convention (perhaps the figures involved are so large, everybody always divides by a million. So by convention a cent of slow money means a bond, denominated in fast money, with a yield-to-maturity of a million cents)).
Perhaps there's a parallel with government bonds: just as they are "backed" by the government's tax raising power, slow money bonds are backed by the colony's capacity to send out new starships, saddled with massive debts, to create new colonies.
I'm not sure the bond version quite adds up though: as you point out, you'd really expect to hear a bit more about face value, maturity, etc. Besides, the way Stross depicts it, the colony needs slow money to buy things to establish itself. If it created a bond (which we're provisionally calling "slow money"), then what the colony would have to spend would be what the lenders paid for that bond: fast money.
3) Or perhaps a hybrid of (2) and (3): slow money is a currency that can be redeemed for bonds with maturities of 1000 years or so.
More of me trying to wrap my head around it here.


text:
Q: How to return only a number out of a string I am trying to get only the number part out of a string that results after a search query that looks something like this (142 items found, displaying 1 To 30.)
I want to save only "142" for later use.
This is my code so far.
private UserSearchPage selectGutsPartner() {
    find(PARTNER).sendKeys(PARTNER_NAME);
    find(SEARCH_BUTTON).click();
    return new UserSearchPage(driver);
}

public String getItemsOnPage() {
    selectGutsPartner();
    return find(ITEMS_FOUND).getText();
}

public String getOnlyNumberOfItems() {
    Pattern pat = Pattern.compile("(//d+) items found, displaying *.");
    String text = getItemsOnPage();
    Matcher matcher = pat.matcher(text);
    System.out.println(matcher.group(1));
    return text;
}

But the number is not striped out.
Thanks.

A: use
String var="142 items found, displaying 1 To 30.";
return Integer.parseInt(var.split(" ")[0]);

A: To get all numbers:
int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", ""));
// i == 1234

And for just the first number:
int i = Integer.parseInt("x-42x100x".replaceAll("^\\D*?(-?\\d+).*$", "$1"));
// i == -42

Already answered here: number out of string in java

A: Try
 Pattern pat = Pattern.compile("(\\d+) items found, displaying.*");

backslash, not forward slash. And period in front of the * (since the * is a quantifier for the "thing that precedes it", and you want that "thing" to be "any character", not "any number of spaces". But you don't really need it at all. If you stopped at items found it would work just fine (and still work if everything fitted on one page, which might change the message):
 Pattern pat = Pattern.compile("(\\d+) items found");

A: Using java regex here is the a working method
public String getOnlyNumberOfItems(String text) {
    Pattern pattern = Pattern.compile("^[0-9]+  items found, displaying*");
    Matcher textVerifyMatcher = pattern.matcher(text);

    if(textVerifyMatcher.find()){
        System.err.println("The text is not in the correct format");
        return null;
    }

    Pattern numPattern = Pattern.compile("^[0-9]+ ");
    Matcher m = numPattern.matcher(text);

    if(m.find()){
        text = m.group(0);
        System.out.println("Number: " + m.group(0));
    }
    return text;
}

if the given text is not in the right format the method will return null, it would be better to return an exception though.

A: import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
public class Test {
public static void main(String[] args) {
String str = "142 items found, displaying 1 To 30";
Iterable<String> res = Splitter.on(CharMatcher.JAVA_LETTER).split(str);

}
}