text:
Q: $a \in \mathbb{Z}[i]$ is a unit if and only if $a$ divides every element of $\mathbb{Z}[i]$? As the question title suggests, how do I see that $a \in \mathbb{Z}[i]$ is a unit if and only if $a$ divides every element of $\mathbb{Z}[i]$?

A: Suppose $a$ is a unit.  Then $ax = 1$ for some $x \in \mathbb{Z}[i]$.  Notice that, for any $y \in \mathbb{Z}[i]$, we have $a(xy) = y$, where of course $xy \in \mathbb{Z}[i]$, so by definition $a$ divides $y$.


text:
Q: Easiest way to make a wizard that takes input and generates a document In our Project we have a lot of People generating many plans and report (word and pdf) documents. Problem is that they don't get to follow same standards even after sharing a template.
What I wish. is making a program/solution something that does following;
1- Select the type of document u want (e.g. Status Report or Test Plan)
2- Based on the report u chose, it offers u some text Box to Write ur text
3- Next NeXT and after keep filling the necessary Fields - it generates a Word document from the input
So any opinion on how to and what tool to use to achieve this in quickest way possible?
Im not a Developer but I am have some basic Programming skills and knowledge

A: I used MS Access.
Made a Table with the fields I am interested in having
Using form Wizard, connected them to a very interactive form
Generated document in certain formats using the report wizard of MS Access

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unset the variables of a view for sub-views in codeigniter Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller
{

    public function index()
    {
        $this->load->model('Event');
        $todays_events = $this->Event->get_todays_events();

        $data = array(
            'todays_events' => $todays_events
        );
        $this->load->view('main/index', $data);
    }
}
?>

main/index view
<?php $this->load->view('partial/header'); ?>
<?php $this->load->view('components/calendar/mon_to_wed'); ?>
<?php $this->load->view('partial/footer'); ?>

components/calendar/mon_to_wed
(Has access to $todays_events, why is this?)

Whats Happening

    <?php foreach($todays_events as $event) : ?>
        <?php var_dump($event); ?>
    <?php endforeach; ?>

A: I've read the CodeIgniter core files, while hacking the core may solve this issue, another method exists that help to prevent defining variables in inner-views.
In the first view file, do this instruction:
foreach ($_ci_vars as $key => $value) $_ci_vars[$key]=NULL;

$this->load->view('your-inner-view', $_ci_vars);
$this->load->view('your-second-inner-view', $_ci_vars);
$this->load->view('your-third-inner-view', $_ci_vars);
// and so on...

I'll update my post, if I find a better solution
UPDATE:
Finally! I found the real solution, it is better to make your own Loader class instead of using default one. do the instructions below:

*

*Copy Loader.php class from /system/core/ to your /application/core/

*Find $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); at line #805

*change/replace that line to $this->_ci_cached_vars = $_ci_vars;
CodeIgniter has a variable cashing, once you use load->view() method, the variables will be cached in an array, and the second using of load->view() caused to merge cached variables and new variables if exists and then cache the result as a new array (which contains the old variables).
So, stop using of array_merge() would be the solution ;)

A: The given answer might work for single views, when assembling a view out of multiple sub-views, any data for the overall view gets deleted by the above fix.
What works for me is to explicitly set those data items for the sub-view to null if they are not needed.
For instance the sub-view expects $a, $b and $c.
The first time we render the sub-view we pass $data['a'=>'whatever', 'b'=>'whatever', 'c'=>'whatever'] and the view is rendered correctly.
The second time we pass $data['a'=>'whatever'], $b and $c get rendered in the sub-view with the data from the first call.
If instead we pass $data['a'=>'whatever', 'b'=>null, 'c'=>null], b and c do not get rendered in the sub-view.
This is of course assuming you are checking whether the data is null before you use it in the sub-view.


text:
Q: iphone: unable to post image on wall (facebook) I am trying to upload a Image to facebook and I gam getting image id uploaded in facebook and after getting that id I am trying to create a request appending that photo ID in grap library but everytime I am getting error. The code worked initially but now its failing
    NSString *message = [NSString stringWithFormat:@"For test only --> I think this its uploaded !"];

    NSURL *url = [NSURL URLWithString:@"https://graph.facebook.com/me/photos"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request addFile:savedImagePath forKey:@"file"];
    [request setPostValue:message forKey:@"message"];
    [request setPostValue:_accessToken forKey:@"access_token"];
    [request setDidFinishSelector:@selector(sendToPhotosFinished:)];

    [request setDelegate:self];
    [request startAsynchronous];

}

    - (void)sendToPhotosFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *responseString = [request responseString];

    NSMutableDictionary *responseJSON = [responseString JSONValue];
    NSString *photoId = [responseJSON objectForKey:@"id"];
    NSLog(@"Photo id is: %@", photoId);

    NSString *urlString = [NSString stringWithFormat:
                           @"https://graph.facebook.com/%@?access_token=%@", photoId,
                           [_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURL *url = [NSURL URLWithString:urlString];
    ASIHTTPRequest *newRequest = [ASIHTTPRequest requestWithURL:url];
    [newRequest setDidFinishSelector:@selector(getFacebookPhotoFinished:)];

    [newRequest setDelegate:self];
    [newRequest startSynchronous];

}

    - (void)getFacebookPhotoFinished:(ASIHTTPRequest *)request
{
    NSString *responseString = [request responseString];
    NSLog(@"Got Facebook Photo: %@", responseString);

    NSMutableDictionary *responseJSON = [responseString JSONValue];

    NSString *link = [responseJSON objectForKey:@"link"];
    if (link == nil) return;
    NSLog(@"Link to photo: %@", link);

    NSURL *url = [NSURL URLWithString:@"https://graph.facebook.com/me/feed"];
    ASIFormDataRequest *newRequest = [ASIFormDataRequest requestWithURL:url];
    [newRequest setPostValue:@"I'm learning how to post to Facebook from an iPhone app!" forKey:@"message"];
    [newRequest setPostValue:@"Check out the tutorial!" forKey:@"name"];
    [newRequest setPostValue:@"This tutorial shows you how to post to Facebook using the new Open Graph API." forKey:@"caption"];
    [newRequest setPostValue:@"From Ray Wenderlich's blog - an blog about iPhone and iOS development." forKey:@"description"];
    [newRequest setPostValue:@"http://google.com" forKey:@"link"];
    [newRequest setPostValue:link forKey:@"picture"];
    [newRequest setPostValue:_accessToken forKey:@"access_token"];
    [newRequest setDidFinishSelector:@selector(postToWallFinished:)];

    [newRequest setDelegate:self];
    [newRequest startAsynchronous];

}

    - (void)postToWallFinished:(ASIHTTPRequest *)request
{
    NSString *responseString = [request responseString];

    NSMutableDictionary *responseJSON = [responseString JSONValue];
    NSString *postId = [responseJSON objectForKey:@"id"];
    NSLog(@"Post id is: %@", postId);

    UIAlertView *av = [[[UIAlertView alloc]
                        initWithTitle:@"Sucessfully posted to photos & wall!"
                        message:@"Check out your Facebook to see!"
                        delegate:nil
                        cancelButtonTitle:@"OK"
                        otherButtonTitles:nil] autorelease];
    [av show];

}

error is

-JSONValue failed. Error trace is: (
      "Error Domain=org.brautaset.JSON.ErrorDomain Code=4 \"Valid fragment, but not JSON\" UserInfo=0x6078ae0 {NSLocalizedDescription=Valid fragment, but not JSON}"

Please enlighten me on this.
Regards
Ankit


text:
Q: Get real length of image Javascript How do I the length/width of the image I used.
I need to specify it in the second drawImage to repeat the image when the image end.
function Background() {
    this.speed = 2; // Redefine speed of the background for panning
    // Implement abstract function
    this.draw = function () {
        // Pan background
        //        this.x -= this.speed;
        this.context.drawImage(imageRepository.background, this.x, this.y);
        this.x -= this.speed;
        // Draw another image at the top edge of the first image
        this.context.drawImage(imageRepository.background, this.x, this.y);
        //        // If the image scrolled off the screen, reset
        //        if (this.x <= -this.background.naturalWidth) this.x = 0;
    };
}

A: The image passed as the first argument to context.drawImage should have a width and height property. So imageRepository.background.width should be the width of the imageRepository.background image, and imageRepository.background.height should be its height.


text:
Q: In SQL, how to query for rows based on the values in other rows at a certain relative position in the table I have a database containing events which have a "time" (an integer) plus some other attributes.
E.g.
CREATE TABLE events (time, attr1, attr2);
INSERT INTO events VALUES (1, 'a', 'foo');
INSERT INTO events VALUES (2, 'b', 'bar');
INSERT INTO events VALUES (4, 'a', 'baz');
INSERT INTO events VALUES (9, 'b', 'quux');
INSERT INTO events VALUES (10, 'c', 'foobar');

Now I want to do a somewhat complicated query: I want to find all events which have the property that the next event in the table satisfies some condition. For instance, I might want to find all events that satisfy all these conditions:

*

*attr1 == 'a'

*the next event (as determined by the time field) has attr2 == 'bar'

This should return the event at time 1, but not the event at time 4. Or a more complicated example would be: find all events that satisfy

*

*attr1 == 'a'

*the next event for which attr1 == 'c' has attr2 == 'foobar'

This would return both the events at times 1 and 4.
It seems like this ought to be possible via some sort of complicated nested select, but I haven't managed to work out how.
Other notes:

*

*I'm using sqlite.

*Events are irregularly spaced, so strategies that involve computing the position of the 'next' event won't work.

*I know these queries are going to be murder on the query optimizer, that's okay.

*I know how to do this by doing multiple selects + non-SQL logic, but I'd much rather do it using pure SQL, because this is embedded in a larger query generation system. I need to be able to generate queries of this form in general, conjoined with other constraints, etc., it's not just a single query I'll write once and be done with.

A: You can find a record that is the next after some specific time by combining ORDER BY and LIMIT:
SELECT *
FROM events
WHERE time > 1
ORDER BY time
LIMIT 1

By using this in a subquery, you can look up values from the next record.
Your first query can be implemented like this:
SELECT *
FROM events AS e2
WHERE attr1 = 'a'
  AND (SELECT attr2
       FROM events
       WHERE time > e2.time
       ORDER BY time
       LIMIT 1) = 'bar'

Your second query can be implemented like this (the additional condition belongs into the WHERE of the subquery):
SELECT *
FROM events AS e2
WHERE attr1 = 'a'
  AND (SELECT attr2
       FROM events
       WHERE attr1 = 'c'
         AND time > e2.time
       ORDER BY time
       LIMIT 1) = 'foobar'

The subquery lookups can be made faster with an index on the time column.

A: select * from events a
where exists
  (
   select * from events c where c.time =
  (select min(b.time) from events b where b.time > a.time)--next_event
   and c.attr2 = 'bar'
  )
and a.attr1 = 'a'

should be your first query. It returns time 1.
http://sqlfiddle.com/#!2/63baf/12
the second could be :
select * from events a
where exists
  (
   select * from events c where c.time =
  (select min(b.time) from events b where b.time > a.time and attr1 = 'c')
   and c.attr2 = 'foobar'
  )
and a.attr1 = 'a'

but it returns time 1 and 4 (unlike what you expect, but both these rows comply with your conditions)
http://sqlfiddle.com/#!2/63baf/15
hope this helps
Nicolas


text:
Q: Inform Visual Studio to ignore folder in a project directory I'm trying to create a VS project/solution from a folder containing python files, a data folder.
The data folder is very large and contains a lot of files (Gigs of gray scale images). I've had trouble creating a new project using create from existing python code and I resorted to manually creating the .sln and .pyproj files (Created an empty project and ported over the created files).
I still can't open my solution. While some files and code appear on the screen when I try to load this project. VS does not respond to any action. I assume this is because it's trying to load in all the images in this folder.
Is there a way to tell Visual Studio to ignore this folder when loading in this project?
While writing this post the project finally loaded to a point where I could use VS. But it didn't load any of the files in the solution explorer other than the default files from the empty project I created to port over the .sln and .pyproj files. I unloaded the project and when I reloaded it the same initial issue reappeared (very very slow loading to the point of no response).


text:
Q: $(...).Jcrop is not a function. using in Angular 2 i using jcrop with angular 2 but getting error.

added into index.html

<script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/2.0.4/js/Jcrop.js"></script>

Issue

component

 onSelect(media: Media): void {
        this.isSelecting = true;
        this.mediaFile = media;
        jQuery(this.element).ready(function ($: JQueryStatic): void {
            $('#target').Jcrop({
                aspectRatio: 1,
                setSelect: [175, 100, 400, 300]
            }, function (): void {
                const jcrop_api = this;
                const thumbnail = this.initComponent('Thumbnailer', {width: 130, height: 130});
            });
        });
    }

Html

  <img src="{{mediaFile.url}}" id="target" class="max-width-500">

A: I got solution like that and i posted here for help any one
need to to declare  into component
 declare var $: JQueryStatic;

Need to create interface
interface JQuery {
  container: JQuery;
  Jcrop(...options: any[]): JQuery;
}

Methods for Jcrop
 private _initJCrop(): void {
        const componentInstance = this;
        this.jCrop = $('#crop-image').Jcrop(this.defaultJCropConfig, function(): void {
            componentInstance.jCropApi = this;
            componentInstance.jCropApi.container.on('cropmove', function(e: any, s: any, c: any): void {
                currentSelection = c;
                componentInstance._updateSelection(currentSelection);
            });
        });
        this.selectionX = 0;
        this.selectionY = 0;
        this.selectionWidth = this.minWidth;
        this.selectionHeight = this.minHeight;
        let currentSelection = {
            x: this.selectionX,
            y: this.selectionY,
            h: this.selectionHeight,
            w: this.selectionWidth
        };
    }

    private _updateSelection(currentSelection: any): void {
        this.selectionX = parseInt(currentSelection.x, 10);
        this.selectionY = parseInt(currentSelection.y, 10);
        this.selectionWidth = parseInt(currentSelection.w, 10);
        this.selectionHeight = parseInt(currentSelection.h, 10);
    }

    onCrop(): void {
        this.dialogRef.close({
            x: this.selectionX,
            y: this.selectionY,
            h: this.selectionHeight,
            w: this.selectionWidth
        });
    }


text:
Q: INNER JOIN in jq Using the input given, I need to join the true "user" value from the tweets array with the id in the users array and display the users array object as part of the tweets array
Input:
{
  "tweets": [
    {
      "tweet": "Hey, i gonna release GPT4 soon",
      "user": 1
    },
    {
      "tweet": "We have launched falcon 10 yesterday, it was awesome, one step closer to Mars",
      "user": 2
    },
    {
      "tweet": "Databar acquires Statista.com, great news coming out",
      "user": 3
    },
    {
      "tweet": "Gpt4 is available",
      "user": 1
    }
  ],
  "users": [
    { "id": 1, "name": "a" },
    { "id": 2, "name": "b" },
    { "id": 3, "name": "c" }
  ]
}

Output
[
  {
    "tweet": "Hey, i gonna release GPT4 soon",
    "user": {
      "id": 1,
      "name": "a"
    }
  },
  {
    "tweet": "We have launched falcon 10 yesterday, it was awesome, one step closer to Mars",
    "user": {
      "id": 2,
      "name": "b"
    }
  },
  {
    "tweet": "Databar acquires Statista.com, great news coming out",
    "user": {
      "id": 3,
      "name": "c"
    }
  },
  {
    "tweet": "Gpt4 is available",
    "user": {
      "id": 1,
      "name": "a"
    }
  }
]

I tried using an if condition to find the equal values first, but it loops through the entire array, hence I cant get the specific value of the value in the users array that the ID is equal too

A: Build an INDEX, then use that to map your tweets:
INDEX(.users[]; .id) as $idx | .tweets | map({ tweet, user: $idx[.user|tostring] })

or using JOIN directly:
[JOIN(INDEX(.users[]; .id); .tweets[]; .user|tostring; .[0] + { user: .[1] })]

You could also do it the inefficient way, finding the correct user by iterating:
.users as $users
| .tweets
| map({ tweet, user: (.user as $user | $users[] | select(.id == $user))})

A: @knittl's solutions using INDEX are fine unless there is a "collision" of ids (e.g. if .id can be both 1 and "1").
To avoid collisions and to allow other types of .id values, you could use
SAFE_INDEX and lookup defined as follows:
def SAFE_INDEX(stream; idx_expr):
  reduce stream as $row ({};
    ($row|idx_expr) as $ix
    | .[$ix|type][$ix|tostring] = $row);

def lookup($value):
   .[$value|type] as $t
   | if ($t|type) == "object" then $t[$value|tostring] else null end;

So a generic solution to the problem would look like this:
SAFE_INDEX(.users[]; .id) as $idx
| .tweets
| map({ tweet, user: (.user as $user | $idx |lookup($user)) })


text:
Q: How do I list all installed packages with specific version numbers? I would like to list all the installed packages, with specific version numbers on my system.  I checked out dpkg --get-selections (How to list all installed packages) but it doesn't show me what I need.  For example:
$ dpkg --get-selections apache2
apache2                                         install

shows that apache2 is installed, however not the version.  I recently did a apt-get upgrade so apache2.2.22-1 should be version installed (http://packages.ubuntu.com/precise-updates/apache2.2-common), but how can I show that?
Thanks!

A: Use dpkg -l instead.
Example:
dpkg -l | grep '^ii' | grep skype

Outputs this:

alaa@aa-lu:~$ dpkg -l | grep '^ii' | grep skype
ii    skype      4.2.0.11-0ubuntu0.12.04.2       i386     client for Skype VOIP...

If you only want to extract the name and version, you can do this:
dpkg -l | grep '^ii' | grep skype | awk '{print $2 "\t" $3}'

Which will only print the second and third column from the above output, like this:

alaa@aa-lu:~$ dpkg -l | grep '^ii' | grep skype | awk '{print $2 "\t" $3}'
skype   4.2.0.11-0ubuntu0.12.04.2

Of course, if you want to list all of your installed packages with their versions, and not only Skype, then just remove the grep skype part to make the command like this:
dpkg -l | grep '^ii' | awk '{print $2 "\t" $3}'

A: Use
dpkg-query --show apache2

to get the version number for package apache2 and
dpkg-query --show

to get the version numbers for all installed packages


text:
Q: Simple circuit to sample 120 VAC and yield 8.33 ms pulses Have you noticed the lack of availability and prices of RTC chips lately? A simple DS1307 RTC is simply not available right now. Last year I purchased DS1307s for less than a buck. Now they are $4+ and on backorder.
So I am looking into implementing my own RTC in an interrupt handler using AC line input to provide 60 Hz synchronization.
I remember my office mate back in the dinosaur ages before RTCs were available coming up with a simple circuit which sampled 120 VAC line input and generated 8.33 ms DC pulses output. He borrowed this circuit from an old Intel 8048 app note. This output was fed into an 8051 interrupt where an interrupt handler implemented a firmware RTC. Evidently power generation stations must keep an average of 60 Hz over time so this provided an excellent accurate long term choice for a digital clock.
I remember his circuit used only simple passive components (resistors & capacitors) to produce this 5 VDC 8.33 ms pulse train. I remember an input capacitor isolating the AC input, but cannot remember how the 5 VDC pulses were generated.
Google has been of no help this afternoon. Does anyone have any suggestions on reviving this circuit? TIA.

A: Don't connect directly to the AC line. Use a low voltage transformer's AC output. If you have a 9 VAC output, you can drive a 4.7V zener diode via a 1 kΩ resistor, and with 1 uF in parallel with it. That will generate a 5 V square-ish wave. Use your software to avoid multiple counts per cycle by blanking subsequent transitions for ~ 9 ms after each detected edge.

A: An inexpensive way is to use a zero crossing optocoupler.  You will need two resistors, one for the LED part of the coupler to control the current and the second as a pull up resistor for the output device. These couplers come in several varieties and are generally less than a buck. If the voltage gets to high for your circuit construction you can use a simple transformer to lower the voltage.

A: I agree with some commentators that finding away to still use a 32.768 kHz RTC clock would be recommended. If you still want to do it you basically need a zero-crossing detector circuit. There are many examples available. Although commonly it is used for detecting presence of a live wire (for example in case of 3-phase system), you can use it for getting the 8.33ms period. You can find some links with example circuits below.
1: AC Optocoupler for 230V line detection
2: https://www.electroschematics.com/220v-power-line-interface/
3: https://www.researchgate.net/figure/Zero-crossing-detection-circuit-The-voltage-zero-crossing-signal-is-sent-to-MCU-port-RB0_fig6_323004890


text:
Q: Resolving symbolic links (pwd) Say I do the following:
cd /some/path
ln -s /target/path symbolic_name

If then do:
cd /some/path
cd symbolic_name
pwd

I get:
/some/path/symblic_name

and not:
/target/path

Is there a way to have the shell "fully resolve" a symbolic link (i.e. updating CWD, etc.), as if I had directly done:
cd /target/path

?
I need to run some programs that seem to be "aware" or "sensitive" about how I get to my target path, and I would like them to think that I arrived to the target path as if had done cd /target/path directly.

A: Your shell has a builtin pwd, which tries to be "smart". After you did a cd to a symlink the internal pwd fakes the output as if you moved to a real directory.
Pass the -P option to pwd, i.e. run pwd -P. The -P option (for "physical") tells pwd not to do any symbolic link tracking and display the "real" path to the directory.
Alternatively, there should also be a real binary pwd, which does not do (and is even not able to do) this kind of magic. Just use that binary explicity:
$ type -a pwd
pwd is a shell builtin
pwd is /bin/pwd
$ mkdir a
$ ln -s a b
$ cd b
$ pwd
/home/michas/b
$ /bin/pwd
/home/michas/a

A: Try cd -P <symlink_dirname>.
tim@ls:~$ mkdir a
tim@ls:~$ ln -s a b

tim@ls:~$ cd b
tim@ls:~/b$ pwd
/home/tim/b

tim@ls:~/b$ cd ..
tim@ls:~$ cd -P b
tim@ls:~/a$ pwd
/home/tim/a

You can also use set -o physical to make this behavior persist through the lifetime of the running shell.
Check out https://stackoverflow.com/questions/10456784/behavior-of-cd-bash-on-symbolic-links for some more good info.


text:
Q: Suppose $f$ is uniformly continuous on $(0,2)$ and $(1,3)$. Then is $f$ uniformly continuous on $(0,3)?$
*

*Suppose $f$ is uniformly continuous on $(0,2)$ and $(1,3)$. Then is $f$ uniformly continuous on $(0,3)?$

*If $f$ is uniformly continuous on $[n,n+1] \; \forall n\in N$, then is $f$ necessarily continuous on $[1, \infty]$?
for 1. take $x_n, y_n \in (0,3) $ such that $|x_n-y_n| \to 0$
then case 1. both $x_n, y_n \in (0,2) $ so $f$ uniform continuous on $(0,2)$ gives that $|f(x_n)-f(y_n)| \to 0$
case 2. similar if both belong to $(1,3)$, we're done
case 3. if both of them don't belong to same set among $(0,2)$ and $(1,3)$ (eventually),
then they must belong to $(0,1)$ and $(2,3)$ in which ever order, so$ |x_n - y_n| $ never tends to $0$ in this case.
is this argument correct?
also please help me for 2. I don't have any idea how to do this.

A: For number two, $f(x)=x^{2}$ is uniformly continuous on any compact interval, but it is not uniformly continuous on $[1,\infty)$.


text:
Q: Multilingual characters in GridView I have a gridView built using asp.net.  I have a text box in the grid view which accepts user input.
When the user gives any multilingual character for example "您好" , it is stored as "???"
How can I fix this issue?

A: In database table change the column datatype to nvarchar. this works for me to store text of different languages.


text:
Q: Error creating map in MapDB: ClassCastException: [J cannot be cast to [B I am using MapDB, and attempting to create a direct-memory map, using long-arrays as keys, and I am getting the following error:
java.lang.ClassCastException: [J cannot be cast to [B
    at org.mapdb.Hasher$2.hashCode(Hasher.java:46)
    at org.mapdb.HTreeMap.hash(HTreeMap.java:954)
    at org.mapdb.HTreeMap.get(HTreeMap.java:390)

My code is:
Map<long[],LongBitsWrapper> inUseMap;

DB db = DBMaker
    .newMemoryDirectDB()
    .transactionDisable()
    .asyncWriteFlushDelay( 100 )
    .make();

HTreeMapMaker maker =
    db.createHashMap( "longBitsInUseMap" )
        .hasher( Hasher.BYTE_ARRAY )
        .keySerializer( Serializer.BYTE_ARRAY );

inUseMap = maker.makeOrGet();

Any idea what I am doing wrong?

A: The map keys are of type long[] (binary name [J) but you're trying to use a hasher that works with byte[] ([B). Try using Hasher.LONG_ARRAY instead.


text:
Q: How to install Jinja2 and tornado for python on Windows XP I am new to python and need to develop a web application using jinja framework.
On the jinja website, tar file is given and I don't know how to install it on windows.
Is it possible to install jinja2 as well as tornado web server on windows-xp??
Is it possible?? if yes then how ??
Please help me as soon as possible

A: Here is a tutorial I wrote on how to use Jinja2 template engine with Tornado Web Server.
Like mentioned by Kyle, you need to install jinja2 and tornado using pip.
You can write your custom renderer using jinja2 like below.
class JinjaRenderer(tornado.web.RequestHandler):
    def render_template(self, template_name, **kwargs):
        template_dirs = []
        if self.settings.get('template_path', ''):
            template_dirs.append(
            self.settings["template_path"]
        )
        env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dirs))
        try:
            template = env.get_template(template_name)
        except jinja2.TemplateNotFound:
            raise jinja2.TemplateNotFound(template_name)
        return template.render(kwargs)

A: If you're developing a web app, you're much better off using Linux installed in a VM. I highly recommend using virtualbox.
With that out of the way, let's install it on Windows XP.
Install pip & setuptools. There is already a StackOverflow Q&A for installing pip in Windows.
Once pip is setup (and on your path), run these on the command line (cmd.exe or Powershell):
pip install jinja2
pip install tornado

Note: Other packages may require a compiler. This requires more yak shaving.


text:
Q: Ruby on Rails - Optional Associations? I would like to allow users to write comments on a site.  If they are registered users their username is displayed with the comment, otherwise allow them to type in a name which is displayed instead.
I was going to create a default anonymous user in the database and link every non-registered comment to that user.  Would there be a better way to do it?
Any advice appreciated.
Thanks.

A: The problem with creating an anonymous user is then you need to check if a comment was made by a "real" user, or an anonymous one when displaying the name, so that introduces complexity. Plus, if you have a way of viewing their profile page, which may include posting history, you'd need to exclude the anonymous user with an exception.
Generally it's better to have a column on your comments which represents the user's visible name, and just show that if provided, or the registered user's name otherwise. For instance, your view helper might look like this:
class Comment < ActiveRecord::Base
  belongs_to :user

  def user_name
    self.anonymous_name or (self.user and self.user.name) or 'Anonymous'
  end
end

This will display the contents of the anonymous_name field of the Comment record, or the user's name if a user is assigned, or 'Anonymous' as a last-ditch effort to show something.
Sometimes it's advantageous to actually de-normalize a lot of the database when dealing with large numbers of comments so you don't have to load in the user table via a join simply to display a name. Populating this field with the user's name, even if they're not anonymous, may help with this, though it does mean these values need to be updated when a username changes, presuming that's even possible.

A: I think you can make user_id on your comment model nullable since you want to allow non registered users to add comments as well. As far as adding names for the non registered users are concerned, there are two options for that
option 1. Add a column on Comment model and name it like anonymous_user where you will store names of non registered users
option 2. Create a another model AnonymousCommentor with name and comment_id attributes.
If you are going to use anonymous users for other things as well apart from comment in your application then you can make it polymorphic and use a suitable name like AnonymousUser instead of AnonymousCommentor


text:
Q: angular.js ng-repeat does not seem to be working I am using angular.js version 1.7.2
I have the following code
html

My Book Catalogue

Title	Author	Year	Language

                     {{ book.title }}
                     {{ book.author }}
                     {{ book.year }}
                     {{ book.language }}

In my app.js, I have the following:
books = [{'title': 'Finnegans Wake', 'author': 'Janes Joyce', 'language': 'English', 'Year': '1941'},
         {'title': 'Don Quixote', 'author': 'Miguel De Cervantes', 'language': 'Spanish', 'Year': '1615'}
];
angular.module('booksControllers',[]).
            controller('booksController', function($scope){
   $scope.books = books;
}
})
var booksApp = angular.module('booksApp',[
            'booksControllers',
            'ui.filters'
        ]);

The books array has 2 objects. ng-repeat is iterated twice, however the value is blank.
{{book.title }} and other books elements have blank value.
Am I missing something?

A: I was actually using writing the code not insdie a html file, but a .twig file.
I found that I can prevent twig from proessing a block by using
{% verbatim %}
{% endverbatim %}

I added this and now angular.js works as expected. I am sorry I did not mention the problem accurately.

A: When attempting this, I could get the code working when I moved the array down into the controller:
var booksApp = angular.module('booksApp',[
            'booksControllers',
            'ui.filters'
        ]);

 angular.module('booksControllers',[]).
            booksApp.controller('booksController', function($scope){
 $scope.books = [{'title': 'Finnegans Wake', 'author': 'Janes Joyce', 'language': 'English', 'Year': '1941'}, {'title': 'Don Quixote', 'author': 'Miguel De Cervantes', 'language': 'Spanish', 'Year': '1615'} ];
}
})

See if that works for you ?

A: You have to add   in your html file  if your app.js is like this. Refer this
 var app = angular.module('myapp', []);

        books = [{'title': 'Finnegans Wake', 'author': 'Janes Joyce', 'language': 'English', 'Year': '1941'},
                 {'title': 'Don Quixote', 'author': 'Miguel De Cervantes', 'language': 'Spanish', 'Year': '1615'}
        ];
        app.controller('BaseController', function($scope) {
          $scope.content = 'Hello World';
           $scope.books = books;
        });

        var booksApp = angular.module('booksApp',[
                    'BaseController',
                    'ui.filters'
                ]);

A: There is a two small issue in your code, the first one you have an extra } and the second one you need to declare your Angular Module name on the top of the controller.
    books = [{
  'title': 'Finnegans Wake',
  'author': 'Janes Joyce',
  'language': 'English',
  'Year': '1941'
}, {
  'title': 'Don Quixote',
  'author': 'Miguel De Cervantes',
  'language': 'Spanish',
  'Year': '1615'
}];

var booksApp = angular.module('booksApp', ['booksControllers']);

angular.module('booksControllers', []).
controller('booksController', function($scope) {
  $scope.books = books;
})

I have also run it on Plnkr
https://plnkr.co/edit/XliyEV1leyugSl9gXpnk?p=preview


text:
Q: Converting a spark dataframe that contains Vector as a feature into CSV file I need to convert a spark dataframe into a CSV file.
The problem is that one of the features is a Vector structure and I am not sure how to deal with it. I got this dataframe as a result of a lda.transform() function for Latent Dirichlet Allocation. I am using spark.ml library.
The general df.coalesce(1).write.option("header", true).csv("<file output path>") that I usually use doesn't work in this case.
This is how the dataframe looks like:
org.apache.spark.sql.DataFrame = [label: bigint, topicDistribution: vector]

scala> df_new.show
+-----+--------------------+
|label|   topicDistribution|
+-----+--------------------+
|    0|[6.71576085454879...|
|    1|[5.74898984641732...|
|    2|[1.50297841245588...|
|    3|[3.83251655971072...|
|    4|[8.62396858027641...|
|    5|[1.54900186503601...|
|    6|[1.61493761327978...|
|    7|[9.36938609746372...|
|    8|[1.34332824038935...|
|    9|[1.09991943420077...|
|   10|[1.29739085981008...|
|   11|[8.92839698024594...|
|   12|[4.12414455173398...|
|   13|[1.56497583389755...|
|   14|[1.80725990261967...|
|   15|[1.80725990261967...|
|   16|[9.36938609746372...|
|   17|[1.53335069918914...|
|   18|[1.51801264939744...|
|   19|[7.15931646362877...|
+-----+--------------------+
only showing top 20 rows

I don't need to expand these arrays into a separate features, I just need to convert it as it is.
How can I convert this into a CSV file?

A: Take into account that using coalesce(1) will affect the way the previous steps n the DataFrame will be performed. Passing only 1 partition as parameter for the coalesce will greatly reduce the parallelism and hence you may face memory errors.
Please, try repartition instead, since this will not affect the parallelism of previous operations and you will get a similar result (i.e. only one csv being written).
It would be something like:
df.repartition(1).write.option("header", true).csv("<file output path>")

A: At the end I managed to do it using
df.map { row => (row.getAs[Long]("label"), "[" + row.getAs[org.apache.spark.ml.linalg.Vector("topicDistribution").toArray.mkString(",") + "]") }

It works but this is a bad hack. I am sure there must be a better way but it will do for now.


text:
Q: Cloudberry Powershell scripts failing since version 4.6 (or later) - "Redirect location is empty" A number of people have raised similar issues, but solutions suggested don't seem to help (including adding Set-CloudOption -PathStyle Path etc.)
I've been using multiple scripts based on the following example that have worked well for a number of years.  These scripts all fail when using any version of Cloudberry Explorer PRO above v4.5.1.98 (4.6..., 4.7... etc.), so I'm stuck using version 4.5.
Example Script:
add-pssnapin CloudBerryLab.Explorer.PSSnapIn

Set-CloudOption -UseSSL $true

Set-CloudOption -PermissionsInheritance "inheritall"

Set-CloudOption -ThreadCount 5

$s3 = Get-CloudS3Connection -UseSSL -Key kkk -Secret ssss

$dest = $s3 | Select-CloudFolder -Path bucket/D/Data-Users

$local = Get-CloudFileSystemConnection

$source = $local | Select-CloudFolder \\server\D\Data-Users

$source | Copy-CloudSyncFolders $dest -CompareByContent -IncludeSubFolders -DeleteOnTarget -SSE -StorageClass standard

Error Reported:

Select-CloudFolder : Redirect location is empty At line:1 char:15
  + $dest = $s3 | Select-CloudFolder -path bucket/D/Data-Users
  +               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [Select-CloudFolder], Exceptio    n
      + FullyQualifiedErrorId : System.Exception,CloudBerryLab.Explorer.PSSnapIn
  .Commands.SelectCloudFolder

Any help would be greatly appreciated.

A:
-PathStyle  - Path style if this flag is specified. VHost otherwise.

from here http://www.cloudberrylab.com/amazon-s3-powershell.aspx
Thus correct would be:
Set-CloudOption -PathStyle VHost


text:
Q: How to avoid converting to INT array using Contains in Entity To Entities queries? sIDs contains IDs of string type. In second query I want to get all records with ids that are contained in sIDs. Because sIDs is string array I get error in where sIDs.Contains(t.Id). I cannot either to use where sIDs.Contains(t.Id.ToString()) because EF doesn't support ToString in query. I thought to convert sIDs to int array and then I could use where CONVERTED_TO_INT_IDs.Contains(t.Id).
Is there another way to do this?
var sIDs = (from t in cxt.myTbl
            select t.Parameters).ToList();

var oList = (from t in cxt.myTbl2
             where sIDs.Contains(t.Id)
             select t).ToList();

A: Take a look at the answer here: Problem with converting int to string in Linq to entities
(btw that's the first google match when searching for "ef tostring")


text:
Q: Error making disk image I am sorry if I am repeating someone's question, but I really couldn't find this one out there.
I am trying to make an image of my raspberry's microSD0, but I get this message:
"Error allocating space or disk image file: File too large (g-io-error-quark, 0)"
How do I solve it?
Ubuntu 20.10


text:
Q: How to aggregate new document from Mongodb I have a MonoDB showing incomes. It has _id, name, and income documents. I want to write a query the returns name and a new document call AverageIncome that reads "true" in income < 40,000 and false otherwise. I tried the following code.
db.collection.aggregrate([{income:{$exists:true}}, {$project:{income:1, Averageincome: {$cond:{if;{$gte:{$'income', 40000]}, then: true, else:false}}}}])

I get an output but it is far in excess of what I need. Any other thoughts?

A: You need to define within the $match stage your first step. Since the $gte operator returns true|false, you don't need to add the $cond operator.
Try this one:
db.collection.aggregate([
  {
    $match: {
      income: {
        $exists: true
      }
    }
  },
  {
    $project: {
      name:1,
      income: 1,
      Averageincome: {
        $gte: [
          "$income",
          40000
        ]
      }
    }
  }
])

MongoPlayground


text:
Q: R loop giving a Zero instead of one This is my code in R to run Gauss Elimination:
mat <- matrix(c(8,-2,5,-1,4,8,5,15,2,-2,10,-12),nrow = 3, ncol = 4, byrow = TRUE)
n = nrow(mat)
print(mat)
print(n)
for (k in 1:n-1){
  print(k)
  for (i in k+1:n){
    mat[i,k] <- mat[i,k] / mat[k,k]
    for (j in k+1:n-1){
      mat[i,j] <- mat[i,j] - mat[i,k] * mat[k,j]
    }
    print(mat)
  }
}

The k first value is 0 instead of 1. What is wrong?

A: This is because the : operator is more tightly bound than the arithmetic operators, so for(k in 1:n-1) means for(k in (1:n) - 1) which is the same as for(k in 0:(n-1)). I think you intended for(k in 1:(n-1)).
You make the same mistake in your other for loops. You must add the parentheses to make them work:
mat <- matrix(c(8,-2,5,-1,4,8,5,15,2,-2,10,-12),nrow = 3, ncol = 4, byrow = TRUE)
n = nrow(mat)
print(mat)
#>      [,1] [,2] [,3] [,4]
#> [1,]    8   -2    5   -1
#> [2,]    4    8    5   15
#> [3,]    2   -2   10  -12
print(n)
#> [1] 3
for (k in 1:(n-1)){
  print(k)
  for (i in (k+1):n){
    mat[i,k] <- mat[i,k] / mat[k,k]
    for (j in (k+1):(n-1)){
      mat[i,j] <- mat[i,j] - mat[i,k] * mat[k,j]
    }
    print(mat)
  }
}
#> [1] 1
#>      [,1] [,2] [,3] [,4]
#> [1,]  8.0   -2    5   -1
#> [2,]  0.5    9    5   15
#> [3,]  2.0   -2   10  -12
#>      [,1] [,2] [,3] [,4]
#> [1,] 8.00 -2.0    5   -1
#> [2,] 0.50  9.0    5   15
#> [3,] 0.25 -1.5   10  -12
#> [1] 2
#>      [,1]      [,2]     [,3] [,4]
#> [1,] 8.00 -2.000000  5.00000   -1
#> [2,] 0.50  9.000000  5.00000   15
#> [3,] 0.25  1.333333 10.83333  -12

Created on 2020-07-09 by the reprex package (v0.3.0)


text:
Q: how to bind dictionary to datagrid wpf i am trying to bind a dictionary to datagrid , for now couldn't found a clear way of doing if.
the dictionary key should be the grid header and its values should be the column data.
for example
C# Code:
var dictionary  = new Dictionary<string,string>();
dictionary.Add("First Name","Name");
dictionary.Add("Last Name","Last Name");
dictionary.Add("Phone","+123-123-123");

meaning i would like my datagrid to have 3 colunms:

*

*First Name

*Last Name

*Phone

is there a way of bind a dictionary with unknown number of Keys , to datagrid ?
for now i'm using Datatable instead
thanks

A: The best way to do what you want would be as follows:
In the CodeBehind, you can create an list of Anonymus objects, if you no have an model, and int the constructor populate the list and add to ItemsSource of DataGrid:
List<Object> mylist = new List<Object>(){
new {FirstName="myfirstName1", LastName="mylastName1", Phone="+123-123-123"},
new {FirstName="myfirstName2", LastName="mylastName2", Phone="+124-124-124"},
new {FirstName="myfirstName3", LastName="mylastName3", Phone="+125-125-125"}
}

this.myDataGrid.ItemsSource = myList;

In the XAML you place the following code, as statement of DataGrid:
<DataGrid x:Name="MyDataGrid" AutoGenerateColumns="false"   >
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding FirsName}" Header="First name"  />
        <DataGridTextColumn Binding="{Binding LastName}" Header="Last name"  />
        <DataGridTextColumn Binding="{Binding Phone}" Header="Phone"  />
    </DataGrid.Columns>
</DataGrid>

A: i'll try to be more specific.
let say i'm getting a list of objects for example table .
each table can have a different data structure and also different number of rows.
so i cannot be bound to any data structure.
for now the best solution i found is to bound by grid to DataTable
var selectedTable = new DataTable();
        if (tableEntities.Any())
        {
            var colunms = table.Properties;
            foreach (var colunm in colunms)
            {
                selectedTable.Columns.Add(colunm.Key);
            }

            foreach (var entity in tableEntities)
            {
                var row = selectedTable.NewRow();
                foreach (var property in entity.Properties)
                {
                    row[property.Key] = property.Value.GetStringValue();
                }
                selectedTable.Rows.Add(row);
            }

but i don't like this solution


text:
Q: Using a if statement condition to see NULL user input and print: "sometext ..." Python with its indents and no semi-colons and brackets is taking some time for me to  get used to ... coming from C++. This, I'm sure is an easy fix, but I can't seem to find the problem. Your help is greatly appreciated. Here is what I have. When I run this code it acts like the second 'if' statement does not exist. Even if I comment out the first 'if' statement, the print line in the second 'if' statement is never printed to screen:
import re

while True:
   stringName = raw_input("Convert string to hex & ascii(type stop to quit): ").strip()
   if stringName == 'stop':
      break
   if stringName is None: print "You must enter some text to proceed!"

   print "Hex value: ", stringName.encode('hex')
   print "ASCII value: ", ', '.join(str(ord(c)) for c in stringName)

A: The return value of raw_input() is always a string, and never None.  If you want to check for an empty string "", you can use
if not string_name:
    # whatever

A: raw_input always returns a string and never None. Check out raw_input help.

raw_input([prompt]) -> string
Read a string from standard input.  The trailing newline is stripped.
     If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
     On Unix, GNU readline is used if enabled.  The prompt string, if given,
     is printed without a trailing newline before reading.


text:
Q: Webpack Hot Reload with Angular2? I'm having the strangest issue with webpack hot reload middleware and angular 2.. I have a simple index.html that does <my-app></my-app>. My webpack config is pretty simple as well. It's below.
My app is a clone of the HMR docs (http://andrewhfarmer.com/webpack-hmr-tutorial/);
app.use(webpackDevMiddleware(compiler, {
    hot: true,
    filename: 'bundle.js',
    publicPath: '/',
    stats: {
        colors: true,
    },
    historyApiFallback: true
}));

app.use(webpackHotMiddleware(compiler, {
    log: console.log,
    path: '/__webpack_hmr',
    heartbeat: 10 * 1000
}));

On first load, this works great. App comes up, and index.html has <script type="text/javascript" src="http://localhost:3000/main.js"></script> in it. Then I go and change something in the app as a test, and I can see in the console that webpack rebuilds successfully, but the browser doesn't update. So I tried hitting reload, and the app is stuck on the loading banner, because the script tag appears to vanish entirely.
Has anyone seen this before? Any ideas how I might get this to work?
var webpack = require('webpack');
var helpers = require('./webpack.helpers');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    devtool: 'eval-source-map',
    entry: [
        'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
        './src/client/polyfills.ts',
        './src/client/vendor.ts',
        './src/client/main.ts'
    ],
    module: {
        preLoaders: [
            {test: /\.ts$/, loader: 'tslint'}
        ],
        loaders: [
            {
                test: /\.ts$/,
                loaders: ['ts-loader?configFileName=src/client/tsconfig.json', 'angular2-template-loader']
            },
            {test: /\.json$/, loader: "json-loader"},
            {test: /\.css$/, loader: "style-loader!css-loader"},
            {test: /\.scss$/, loaders: ['raw', 'sass']},
            {test: /\.less/, loader: "style!css!less"},
            {test: /\.png$/, loader: "url-loader?prefix=img/&limit=5000"},
            {test: /\.jpg$/, loader: "url-loader?prefix=img/&limit=5000"},
            {test: /\.gif$/, loader: "url-loader?prefix=img/&limit=5000"},
            {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff"},
            {test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
            {test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=application/octet-stream'},
            {test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=image/svg+xml'},
            {test: /\.html$/, loader: 'raw'}
        ],
        postLoaders: []
    },
    output: {
        path: helpers.root('../../dist/public'),
        publicPath: 'http://localhost:3000/',
        filename: '[name].js',
        chunkFilename: '[id].chunk.js'
    },
    resolve: {
        cache: false,
        root: helpers.root(),
        extensions: ['', '.ts', '.js', '.json', '.css', '.scss', '.html']
    },
    tslint: {
        emitErrors: false,
        failOnHint: false
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/client/public/index.html',
            chunksSortMode: 'dependency'
        }),
        new CopyWebpackPlugin([
            {from: './src/client/public'}
        ]),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ]
};


text:
Q: what does '\r' do and how would I use it in a given scenario? (Python) I've been trying to make a program for a card game, a quick summary: Write a python script to create a random card, representing the card as a tuple, storing the card value and the color.
One of the conditions was that whilst I loop 3 times, I have to make sure that each card does not have the same values and color as the rest so that no 2 cards are the same. (When the second card is created, check if it is the same as the first and if it is, try again.
When the third card is created, check if it is the same as the first
OR the second and if it is, try again.)
I would then have to create a function that adds together the value of 3 cards and returns
the sum.
Of course, there is more to it than that but my question is a simple one. So far what I've done:
import random

num = random.randint(0,9)
colour = random.choice(["red", "green", "blue", "yellow"])
card = (num, colour)

def get_uno_card(card):
  for _ in range(1):
    print(card)
    if num and colour == card:
      print(card)

  return card

def convert():
  a = str(card)
  return a

def add():
  b = num * 3
  return b

a = convert()
b = add()

print(get_uno_card(card))
print(a)
print(b)

This outputs:
(6, 'blue')
(6, 'blue')
(6, 'blue')
18

I have trouble trying to make sure the cards are not the same, therefore I was looking for ways to do this online and there was a post where they explained that I should use '/r'. I haven't come across this and don't know how I should use this in this scenario, or if I should use it at all.
Could someone explain how I could check if the 3 tuples are the same and if they are, how would I generate another card in its place?

A: \r is a carriage return character, and has nothing at all to do with the problem you're describing, which is one of sampling without replacement.
An easy way to make sure you don't have the same card twice is to make a "deck" of all the cards (which in Python is easily represented as a list) rather than generating each card individually.
With a real deck of cards, you can't get the same card twice because you remove the card from the deck when it's dealt; use your list the same way by popping items from it.
>>> import random
>>> cards = [(num, color) for num in range(10) for color in ["red", "green", "blue", "yellow"]]
>>> random.shuffle(cards)
>>> cards.pop()
(3, 'blue')
>>> cards.pop()
(4, 'yellow')
>>> cards.pop()
(5, 'blue')

Putting this in the context of some of the things you've tried to implement already:
import random

deck = [
    (num, color)
    for num in range(10)
    for color in ("red", "green", "blue", "yellow")
]
random.shuffle(deck)

def get_uno_card():
    return deck.pop()

def add_cards(cards):
    return sum(num for num, color in cards)

cards = [get_uno_card() for _ in range(3)]
print(cards)
print(add_cards(cards))

[(9, 'yellow'), (9, 'blue'), (3, 'yellow')]
21


text:
Q: Is there difference if you are running 32bit Linux on low end VPS instead of 64bit in memory consumption? Is 64bit Linux using more memory than 32bit version? I'm interested in this because I'm going to install linux to low end VPS, which has not that much memory etc., so if it is possible to save memory by using 32bit, then I would do that.

A: It really depends on what you're running on that Linux box. Generally speaking, yes, 32-bit instance will take less RAM to do the same job as 64-bit instance. However, there are two nuances:

*

*In some applications the difference is more pronounced than in others. For example, if it is a Ruby on Rails web application, difference is really big (from my experience).

*You can have a basic 64-bit system and run 32-bit apps on top of it (with the aid of proper libraries). Depending on your distribution, many of these libraries could already be installed for you.

A: 32-bit memory, pointers, instructions, etc, are all smaller than their 64-bit counterparts.  The 64-bit overhead gains big advantages when crunching lots of data or accessing lots of memory (e.g. 32-bit registers can't access over 3.6 gigs of RAM.)  But when you're talking about sub-Gig memory the 32-bit OS starts to sound good.  I've seen differences in a bare-install boot where a 64-bit OS took an extra 100+ megs of RAM.  If you're running on a 512 meg VPS that's going to kill your performance quickly.


text:
Q: How to run node server.js and npm start with one command I spun up a new create-react-app and an Express backend locally. Right now I have to run node server.js and npm start separately to make sure both the frontend and backend runs.
Is there a way that I can run both with just one npm command by just editing my package.json file?

A: This is how I do it using a module named concurrently.

*

*Install concurrently using npm.

*Add the script to the package.json file of the root folder.
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js",
    "client": "npm run start --prefix client",
    "server": "nodemon index.js",
    "dev": "concurrently \"npm run client\" \"npm run server\""
    }

A: Yes you can. Under your package.json file you can use:
{
  "name": "projectX",
  "version": "1.0.0",
  "scripts": {
    "dev:api": "node server.js",
    "dev:client": "npm start",
    "dev": "npm run dev:api && npm run dev:client"
  }
}

If you run npm run dev it will run both of your scripts.
But I wouldn't recommend this approach because you are making your backend & frontend dependent on each other. That means you will have one version for both, one CI/CD pipeline, one deployment.
I would have two separate projects.

A: In your package.json add another script

"scripts": {
    "start": "..."
    "start-server": "node server.js && npm start",
  }

A: In your package.json file just add this script. There is no need for an npm package. However, if you need one concurrently will do the trick.
"scripts": {
        "client": "npm run start --prefix client",
        "server": "npm run watch --prefix server",
        "watch": "npm run server & npm run client",
        "test": "echo \"Error: no test specified\" && exit 1"
      },


text:
Q: Proving that $[K(x):L]$ is finite where x is an indeterminate over the field K and L is an intermediate field of $K(x)/K$ such that $L\neq K$. Let $G=Aut(E/K)$ and let $H\leq J\leq G$. Then, I know that if $[H:J]$ is finite, so is $[L:M]$ where $L\subset M$ are the subfields of $E$ that are fixed by $J$ and $H$, respectively. I also know that $Aut(K(x)/K)$ is the set of automorphisms that map $x$ to $\frac{ax+b}{cx+d}$ with $ad\neq bc$.
Trivially, the subgroup of $Aut(K(x)/K)$ that fixes $K(x)$ is $\{1\}$. So, the question boils down to showing that the subgroup that fixes any intermediate field $L$, is finite but I don't have any idea about the subfields of $K(x)$, to begin with.

A: Let $L$ an intermediate field in the extension $K(x)/K$. Suppose $L\neq K$, so that, there is $p(x)/q(x)$, with $p(x), q(x)$ both relatively primes and one of them of degree at least one. Define
$$F(z)=p(z)-\frac{p(x)}{q(x)}q(z)\in L[z].$$
Since $x$ is a root of $F(z)$ which have degree at least one, we have that $x$ is algebraic over $L$, then $K(x)/L$ is finitely generated and algebraic, so that finite.


text:
Q: Macbook retina CSS: scrollable div scrollbar overlapped by parent scrollbar Found a strange problem, did some googling and didn't find anyone with similar issues.
In short. I have a position fixed div inside another position fixed div. On non-retina, everything's fine, but on macbook retina (webkit browsers) scrollbar of the parent overlaps scrollbar of the div that should be on top:
http://jsfiddle.net/3by6ohq0/
position:fixed

Does anyone have any ideas? Thanks in advance.
Visual comparison of non-retina vs. retina:
http://i.imgur.com/iTlRgmH.png

A: The reason behind this relates to your usage of pixels. Right now, your inner fixed div of class "floating" you have set to:
right:7px;

In your hope to make it off the scrollbar. However, for your unfortune, scrollbars are not all the same width in every operating system. On the Retina Macbooc Pro,there are more pixels that make up the width of the scrollbar (so it's not really tiny to your eye), probably 2X the amount, and therefore that 7px right does not justify for the greater amount of pixels. Nor does it on Ubuntu which I use. The best method would be this:
.floating {
    position:relative;
    float:right;
}

Or even absolute positioning would be better than fixed. Because right now since the parent element has a fixed position, the child element is actually justifying its position to the body, or the parent element of its parent element.


text:
Q: Adding a new dictionary to my plist file Root  ---- Array
  Item 0- Dictionary
    fullName  ---- String
    address   ---- String
  Item 1   ---- Dictionary
    fullName  ---- String
    address   ---- String
I have a plist that looks like the one about.  In a View I have a button that when clicked I'd like to add a new "Item 2" or 3 or 4 or 5 etc...  I just want to add a few more names and addresses.
I've spent 3 hours tonight searching for the perfect example but came up short. The Apple property lists samples were way too deep.  I've seen code that probably will come close.
Thanks So Much

NSMutableDictionary *nameDictionary = [NSMutableDictionary dictionary];
    [nameDictionary setValue:@"John Doe" forKey:@"fullName"];
    [nameDictionary setValue:@"555 W 1st St" forKey:@"address"];
NSMutableArray *plist = [NSMutableArray arrayWithContentsOfFile:[self dataFilePath]];
[plist addObject:nameDictionary];
[plist writeToFile:[self dataFilePath] atomically:YES];

- (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"children.plist"];
    return path;
}

A: Assuming that the plist is stored on disk as a file, you can reopen it and load new contents by calling the arrayWithContentsOfFile method.
// Create the new dictionary that will be inserted into the plist.
NSMutableDictionary *nameDictionary = [NSMutableDictionary dictionary];
[nameDictionary setValue:@"John Doe" forKey:@"fullName"];
[nameDictionary setValue:@"555 W 1st St" forKey:@"address"];

// Open the plist from the filesystem.
NSMutableArray *plist = [NSMutableArray arrayWithContentsOfFile:@"/path/to/file.plist"];
if (plist == nil) plist = [NSMutableArray array];
[plist addObject:nameDictionary];
[plist writeToFile:@"/path/to/file.plist" atomically:YES];

The -(void)addObject:(id)object always inserts at the end of the array. If you need to insert at a specific index use -(void)insertObject:(id)object atIndex:(NSUInteger)index method.
[plist insertObject:nameDictionary atIndex:2];


text:
Q: Identity versus Composite values for Primary Keys in Many-To-Many Tables I am in the middle of an interesting "Data Architecture" discussion at a place I am contracting & need some input.
As a habit, I always create a Surrogate Key as the Primary Key in my tables - be they Guid (UUID) or Identity values.  IMHO the synthetic-nature of a Surrogate Key has the distinct value of identifying a row without intruding on "real" or "natural" keys-or-values that may otherwise be useful Alternate Keys.
To me...it just seems natural - but maybe I am wrong.
Where I happen to be at the moment...they argue this good for "core" Entity tables, but is completely incorrect for Many-to-Many (relationship) tables.  While I will happily oblige the customer...I disagree.
Thoughts behind my approach are:

*

*A primary key value must be unique

*The primary key should be as compact as possible

*Primary key value should be stable

*Primary Key identifies a tuple...not the data INSIDE the tuple

MY QUESTION: Which is either correct or better?  And Why?
- Please provide reasoning etc.
NOTE:
Please Ignore the ID column naming in the samples below...that is how they do it here.

A: A Many-to-Many mapping table must have a unique index on the foreign key columns.  And should normally have an additional unique index on the foreign key columns in the reverse order.
So while adding an additional synthetic key doesn't do any great harm, it's just not very useful.


text:
Q: RenderScript Element packed into a single 24 bit field with 24 bit alignment When processing RGB data in RS through kernel-Allocation construct, I'm using uchar3/uchar4 data-type in RS to process RGB data. However both of these datatypes are single 32 bit field with 32 bit alignment. This way I lose out on r-component of 2nd pixel.
The RS developer docs suggests Element.Builder for creating custom data-types. However its usage doesn't quite give me a single 24-bit-field-with-24-bit-alignment element with most of the primitive datatypes (U8, RGB_888, etc.) . Is there a prescribed way to use/create a 24 bit field 24 bit aligned element?

A: No, Typically non-power of 2 alignment will create all sorts of havok for hardware units.  Some load units will bus fault, other runs at 1/4 speed.  For this reason the Vec3 types are all stored as if they were vec4.


text:
Q: Regex python - Match newline only if it is followed by number or special character and space I've been trying to figure out this regex in Python but it's not been producing the expected result.
I have a text file which I load that is in the format of:
"18 75 19\n!dont split here\n! but split here\n* and split here"

I'd like to get the following output:
['18 75 19\n!dont split here',
 '! but split here',
 '* and split here']

I'm trying to split my string by either 1) a new line followed by a number, or 2) a new line followed by a special character only if it is followed by a space (e.g. '! but split here', but not '!dont split here').
Here's what I have so far:
re.split(u'\n(?=[0-9]|([`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?])(?= ))', str)

This is close, but not there yet. Here's the output it produces:
['18 75 19\n!dont split here', '!', '! but split here', '*', '* and split here']

It incorrectly matches the special character separately: '!' and '*' have their own element.
There are two lookahead operators in the regex.
I'd really appreciate if you could help identify what I could change with this regex for it to not match the single special character, and just match the special character followed by the full line.
I'm also open to alternatives. If there's a better way that doesn't involve two lookaheads, I'd also be interested to understand other ways to tackle this problem.
Thanks!

A: Your regex is actually working, the issue is with the capturing group you have around [`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]. From the manual:

If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list

If you remove the () around that character class, you will get the results you expect.
Note that you don't need (?= ) in that alternation as it is already part of a lookahead, you can just use  (space). Also you might find it easier to write the symbols as a negated character class i.e.
re.split(u'\n(?=[0-9]|[^A-Za-z0-9] )', str)


text:
Q: How can I loop through the $cart array, add the quantity to a running total and use a comma-delimited string to use as a query into my database? I am having trouble understanding this part I have been stuck on it for a while and I think it is time to ask for some help.
What I am trying to do is use the quantity to add to a running total ($_SESSION['numItems']) and the product ID, with a comma added after it, to be appended to your $prodIDStr variable so I can use it in my table query.
This problem is just escaping me or either I am over thinking it. Either way I would appreciate some help and yes I have searched this site for another answer that would help me but with no luck.
foreach ($cart as $prodID => $prodQty) {
    // update the number of items in the cart
    $_SESSION['numItems'] = $prodQty;
    // comma-delimited string
    $prodIDStr = $prodIDStr . $prodID . ",";
}

A: Try this :
foreach ($cart as $prodID => $prodQty) {
    // add items to the cart (notice the '+' before '=')
    $_SESSION['numItems'] += $prodQty;
    // comma-delimited string
    $prodIDStr .= "$prodID,";
}

//remove the last comma
$prodIDStr = rtrim($prodIDStr, ',');

A: I am guessing that your problem is that $_SESSION['numItems'] does not contain the running total after this loop finished? That is probably because you assign $prodQty to $_SESSION['numItems'] instead of adding it. Try:
$_SESSION['numItems'] = 0;
foreach ($cart as $prodID => $prodQty) {
    // update the number of items in the cart (note the '+')
    $_SESSION['numItems'] += $prodQty;
    // comma-delimited string
    $prodIDStr = $prodIDStr . $prodID . ",";
}


text:
Q: Calculate price of radio button and drop-down list I have a radio-button list and a drop-down list that are populated from a database:

  <?php
  $stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
  $stmt->execute();
  $stmt->bind_result($case_id, $case_name, $case_price);
  while($stmt->fetch()) {
  echo '

 <input class="selectedoptions" id="'.$case_id.'" name="config-prod" value="'.$case_price.'" type="radio">
  '.$case_name.'         [£'.$case_price.']

';
 }
 $stmt->close();
 ?>

  <?php
  echo "<select class='form-control' id='plist' name='partlist'>";
  $type = "processors";

 $stmt2 = mysqli_prepare($link, "SELECT id, name, price FROM parts WHERE type=?");
 $stmt2->bind_param("s", $type);
 $stmt2->execute();
 $stmt2->bind_result($cpu_id, $cpu_name, $cpu_price);
 while($stmt2->fetch()){
  echo "<option value='$cpu_price'>$cpu_name</option>";
 }
 $stmt2->close();
 echo "</select>";
 ?>

I would like to be able to obtain the price of the selected item from the two lists. I have tried to do this with JS:

The total_cost should be output to this:
<input name="buildTotal" id="total" type="text" class="transparentFieldy float-price" disabled="" />

However, this does not output anything. How do I change this to be able to calculate the price based on the selected elements? Thanks!

A: To set the content of input-elements you have to use the value-property instead of innerHTML. You should also consider using parseFloat if you are dealing with currency.

let buildcost = 25.00;

function updateTotal() {
  let radios = document.getElementsByName('config-prod');
  let select = document.getElementById('plist');
  let partcost = 0;

  for (let i = 0, j = radios.length; i < j; i++) {
    if (radios[i].checked) {
      partcost = parseFloat(radios[i].value);
      break;
    }
  }

  partcost += parseFloat(select.options[select.selectedIndex].value);

  let total_cost = buildcost + partcost;
  document.getElementById('total').value = total_cost.toFixed(2);
}

    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    Item 1 [£1.00]

    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    Item 2 [£12.34]

    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    Item 3 [£9.99]

<select id="plist" name="partlist" onchange="updateTotal();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>

Total: <input id="total" type="text"><button id="update" onclick="updateTotal();">Update</button>


text:
Q: Puppeteer : JS files only work when placed inside puppeteer directory of node modules I have a Ubuntu 16.04 running on my system where I installed Puppeteer with the following command :
sudo npm install -g puppeteer --unsafe-perm=true

As I can see, the module is installed correctly at /usr/lib/node_modules/puppeteer/.
Now, if I add a file, example.js inside the above mentioned directory and run it with node example.js, I get the correct results, but if the file is placed anywhere else, puppeteer is not found.
Have I missed something, should I add something in the PATH? I want to access puppeteer globally. Thank you.
I checked the question suggested by the user, already have a NODE_PATH pointing to /usr/lib/node_modules. Even tried npm link puppeteer, didn't help.


text:
Q: Simple symmetries for two nonlinear partial differential equations I tried to investigate symmetry of two relatively simple partial differential equations.
Firstly I define what I mean by symmetry: change of variables $ t \rightarrow -t $ or $ x \rightarrow -x $ or function $ u \rightarrow -u $ are my symmetries, they can combine together.
My equation is:
$$
u_{t} = uu_{x}
$$
Then I concluded, that this equation don't have symmetries like S(t) (change of just $t$ does not lead to the same equation), S(x), S(u), S(xtu). But it has symmetries:
S(xt) (change of $x$ and $t$ leads to the same equation), S(xu), S(tu). I am especially not sure about $u \rightarrow -u$ symmetry. I just plug (-) sign for every $u$ in the equation. Do have these symmetries any name? If it is correct, do they say something about given equation?
The second example is equation:
$$
u_{t} = uu_{xxx}
$$
and it has actually the same symmetries as the first equation (S(xt), S(xu), S(tu)).

A: Yes, both of your question are true. Specifically, if $u(t,x)$ is a solution of $$
u_t=uu_x
$$
then so are $v_1(t,x):=-u(-t,x)$, $v_2(t,x):=-u(t,-x)$ and $v_3(t,x):=u(-t,-x)$. The same holds for your second equation $u_t=uu_{xxx}$. Of course these simetries have implications on the dynamics of the equation. For instance, if you have an equation with all of these simetries that also have soliton solutions (traveling waves), you would immediately conclude that if $u(t,x)=\phi(x-t)$ is a solitary wave solution of your equation, then so is $v(t,x)=-\phi(x+t)$. In particular, you would conclude the existence of "antisolitons" solutions moving to the left (which is not always true, there are many equations which have no "antisolitons" nor solitons moving to the left). And the same for the other simmetries.
About the names, I am not sure, but I think I would call "space-time reversal symmetry" to the map $(t,x)\mapsto(-t,-x)$ (maybe space-time inversion?). I don't think that the other two have names.
A final comment is that usually when these PDEs have Hamiltonian structure, these symmetries have associated conservation laws (by Nöether's Theorem). Hence, apriori, the existence of these symmetries (for hamiltonian PDEs at least) restricts how bad/bizarre can be the dynamic of the solution.
Edit: Notice also that both of your equations are invariant under space-time translations. There you have another two symmetries. That means: if $u(t,x)$ is a solution, then so is $u(t+t_0,x+x_0)$ for any $t_0,x_0\in\mathbb{R}$.


text:
Q: Mapping key combination with xmodmap I'm trying to achieve the following mapping
keycode 135 = <Ctrl-C>
Is it possible to achieve this in some way?

A: Have you tried Autokey ? It is a much easier way than xbindkeys or xmacro.

A: That's not possible with xmodmap. I don't think it's possible with XKB either, but I'm not sure.
Is your aim to have a key that's always identical to pressing Ctrl+C (e.g. in a terminal, it would interrupt the running program), or to have a clipboard copy key? If the latter, try
keycode 135 = XF86Copy

The XF86Copy keysym is intended for a copy-to-clipboard key, but I don't know how many applications have that shortcut out-of-the-box.
If you're on Ubuntu, and possibly even if you aren't, the recommended method to set up additional ("multimedia") keys is keytouch.
If you really want the key to be equivalent to Ctrl+C, your desktop environment or window manager may let you bind the keysym to a command that generates key press and release events for that key combination. If you prefer or must use a DE/WM-agnostic method, you can use xbindkeys to bind an arbitrary shell command to a key, and xmacro to manufacture key events to send to a window. You'll still need to have a keysym associated with the key; a good choice is F13 (or wherever the numbered function keys on your keyboard leave off). Then put this in your ~/.xbindkeysrc:
"{ echo KeySymPress Control_L; echo KeySym C; echo KeySymRelease Control_L; } | xmacroplay"
  F13

You'll need to start xbindkeys with your X session — from your ~/.xinitrc or ~/.xsession if you have one, or from the appropriate configuration interface in your DE/WM.

A: xmodmap -e 'keycode 133 = Menu
133 in this case is Super (ubuntu logo on touchpad)


text:
Q: I am looking for alternatives to the phrase "way too" or "far too" as in "Way too often..." I am editing a work written for professions and have come across a sentence beginning "Way too often I encounter ..." First, this seems very colloquial. In doing some research on google ([alternative to "way too"], [alternatives to saying "way too", grammar girl and grammarist, which did not not pull anything, I came here. Urban Dictionary states: A phrase originating from Welland, Ontario, Canada. The phrase means to do/be something to a great extent. The alternatives are professional than what I am starting with: [urban dictionary.com]. Any help appreciated. This is the first question I've posted; Apologize for posting errors.

A: "Much too" is a more "professional" way of saying "way too."

A: Since you are a little vague on the  contents are usage and did not give example as to when and what manner it is being used, it leads me to think you are reffering to time in a sense.
Like: She uses the words "way too" way too much and "far too" often.
If I am wrong please let me know and I will do my best to help you with how it is being used. I have done a lot of editing.
Check: http://www.thesaurus.com/browse/often
One Word:
Considerably, Consistently, Customarily, Decidedly, Eminently, Exceedingly, Exceptionally, Extremely, Frequently, Generally, Habitually, Intermittently, Notably, Oft, Often, Oftentimes, Recurrently, Regularly, Repeatedly, Routinely, Surpassingly, Usually, Very
More than One Word:
A great deal, As a rule, At regular intervals, At times, Every now and then, Fairly often, In many instances, Many a time, Time after time, Time and again, Time and time again, Very often
Hope these help. If you need more help, please feel free to ask.


text:
Q: How to generate the result of bigrams with highest probabilities with a list of individual alphabetical strings as input I am learning natural language processing for bigram topic. At this stage, I am having difficulty in the Python computation, but I try.
I will be using this corpus that has not been subjected to tokenization as my main raw dataset. I can generate the bigram results using nltk module. However, my question is how to compute in Python to generate the bigrams containing more than two specific words. More specifically, I wish to find all the bigrams, which are available in corpus_A, that contain words from the word_of_interest.

corpus = ["he is not giving up so easily but he feels lonely all the time his mental is strong and he always meet new friends to get motivation and inspiration to success he stands firm for academic integrity when he was young he hope that santa would give him more friends after he is a grown up man he stops wishing for santa clauss to arrival  he and his friend always eat out but they clean their hand to remove sand first before eating"]
word_of_interest = ['santa', 'and', 'hand', 'stands', 'handy', 'sand']

I want to get the bigram for each of the individual words from the list of word_of_interest. Next, I want to get the frequency for each bigram available based on their appearance in the corpus_A. With the frequency available, I want to sort and print out the bigram based on their probability from highest to lower.
I have tried out codes from on-line search but it does not give me an output. The codes are mentioned below:
for i in corpus:
    bigrams_i = BigramCollocationFinder.from_words(corpus, window_size=5)
    bigram_j = lambda i[x] not in i
    x += 1
print(bigram_j)

Unfortunately, the output did not return what I am planning to achieve.
Please advice me. The output that I want will have the bigram with the specific words from the word_of_interest and their probabilities sorted as shown below.
[((santa, clauss), 0.89), ((he, and), 0.67), ((stands, firm), 0.34))]

A: You can try this code:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer(ngram_range=(2,2),use_idf=False)

corpus = ["he is not giving up so easily but he feels lonely all the time his mental is strong and he always meet new friends to get motivation and inspiration to success he stands firm for academic integrity when he was young he hope that santa would give him more friends after he is a grown up man he stops wishing for santa clauss to arrival he and his friend always eat out but they clean their hand to remove sand first before eating"]
word_of_interest = ['santa', 'and', 'hand', 'stands', 'handy', 'sand']
matrix = vec.fit_transform(corpus).toarray()
vocabulary = vec.get_feature_names()

all_bigrams = []
all_frequencies = []
for word in word_of_interest:
    for bigram in vocabulary:
        if word in bigram:
            index = vocabulary.index(bigram)
            tuple_bigram = tuple(bigram.split(' '))
            frequency = matrix[:,index].sum()
            all_bigrams.append(tuple_bigram)
            all_frequencies.append(frequency)

df = pd.DataFrame({'bigram':all_bigrams,'frequency':all_frequencies})
df.sort_values('frequency',inplace=True)
df.head()

The output is a pandas dataframe showing the bigrams sorted by frequency.
    bigram  frequency
0     (for, santa)   0.109764
19  (stands, firm)   0.109764
18    (he, stands)   0.109764
17   (their, hand)   0.109764
16      (hand, to)   0.109764

The rationale here is that TfidfVectorizer counts how many times a token is present in each document of a corpus, then computes the term-specific frequency, and then stores this information in a column associated with that token. The index of that column is the same as the index of the associated word in the vocabulary that is retrieved with the method .get_feature_names() on the vectorizer already fit.
Then you just have to select all rows from the matrix containing the relative frequencies of the tokens, and sum along the column of interest.
The double-nested for loop is not ideal though, and there may be a more efficient implementation for it. The issue is that get_feature_names returns not tuples, but a list of strings in the form ['first_token second_token',].
I would be interested in seeing a better implementation of the second half of the above code.


text:
Q: How to configure 403 template in bjyauthorize I just setup the bjyoungblood/bjy-authorize and wonder how I can tell Zend Framework 2 where my error/403 template lies.
I didn't configure the initial setting of 'template' => 'error/403',
The 403.phtml file lies within the vendor directory but I get the following error message:

Warning: include(C:\myproject\config\autoload/../view/error/403.phtml) [function.include]: failed to open stream: No such file or directory in C:\myproject\vendor\zendframework\zendframework\library\Zend\View\Renderer\PhpRenderer.php on line 507

What is wrong with my configuration?

A: For performance reasons (mainly avoiding stat calls), BjyAuthorize uses the template map to define which file to use when the error/403 view is requested. This is an option of the view_manager settings, as described in the Zend\View documentation.
To set your own, you can simply define something like following in your config/autoload/your-settings.local.php:
'view_manager' => array(
    'template_map' => array(
        'error/403' => '/absolute/path/to/your/error/403.phtml',
    ),
),

Or, in your module config:
'view_manager' => array(
    'template_map' => array(
        'error/403' => __DIR__ . '/view/error/403.phtml',
    ),
),

I suggest always providing absolute paths for configuration, so be sure that your file C:\myproject\config\autoload/../view/error/403.phtml is the correct path.
You can also use a different view for 403 errors if you prefer to do so. That can be achieved by changing $config['bjyauthorize']['template']:
'bjyauthorize' => array(
    'template' => 'my-module/unauthorized-template',
),

A: You can manually set:
'error/403' => __DIR__ . '/../view/error/403.phtml',

in module/Application/config/module.config.php and comment out this line in module.bjyauthorize.global.php. I'm assuming you are working with the skeleton.
@aravind.udayashankara, BjyAuthorize does work with composer and the skeleton already comes configured to load modules in the vendor as well, so no need to move it in modules directory.
However, it does seem that phprender isn't able to access the view directory in the vendor. It might be the way "error/403' => DIR . '/../view/error/403.phtml" is actually mapped/interpreted at runtime.


text:
Q: How to compress/zip files in Microsoft Azure App Service console?
I know about the KUDU service in Microsoft Azure and it works great. However I have got very large data, which is greater than 3GB and it takes very long time to download and then upload to my new server. Is there a way to zip the data on Azure through command line and then do wget to download this data on new server. I have been doing this manually till now but it is taking it forever to download it to my PC first and then uploading to the server through FTP.
I am logged into Microsoft Azure App Service Console. I have tried compress, Compress-Archive and even zip command but nothing works. It says that famous internal and external command not found message.
'compress' is not recognized as an internal or external command, operable program or batch file.
How could I compress these file on Azure console? Earliest help would be appreciated.
Or is there a way to install some compression tool on this server through command line?

A: Now Windows and Kudu both support a native tar command, why not use that.
tar -cvzf my_archive.tar.gz input_dir
tar -xf my_archive.tar.gz

A: While the unzip utility is available, there's no zip tool.  One way around that is to upload the command line version of 7-Zip, it's a standalone .EXE file.


text:
Q: Downloading a file in MVC app using AngularJS and $http.post Any help is most welcomed and really appreciated.
I have an MVC action which retries a file content from a web service. This action is invoked from a Angular service (located in services.js) using $http.post(action, model), and the action is returning a FileContentResult object, which contains the byte array and the content type.
public ActionResult DownloadResults(DownloadResultsModel downloadResultsModel)
{
downloadResult = ... // Retrieving the file from a web service
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", downloadResult.FileName));
Response.BufferOutput = false;
return new FileContentResult(downloadResult.Contents, downloadResult.ContentType);
}

The issue I'm having is about the browser not performing the default behavior of handing a file (for example, prompting to open it, saving it or cancel). The action is completed successfully with having the content of the file and the file name (injected to the FileContentResult object), but there s no response from the browser.
When I'm replacing the post with $window.location.href, and construct the URI myself, I'm hitting the action and after it completes the browser is handling the file as expected.
Does anyone can think of any idea how to complete the 'post' as expected?
Thanks,
Elad

A: I am using below code to download the file, given that the file does exist on the server and client is sending server the full path of the file...
as per you requirement change the code to specify path on server itself.
    [HttpGet]
    public HttpResponseMessage DownloadFile(string filename)
    {
        filename = filename.Replace("\\\\", "\\").Replace("'", "").Replace("\"", "");
        if (!char.IsLetter(filename[0]))
        {
            filename = filename.Substring(2);
        }

        var fileinfo = new FileInfo(filename);
        if (!fileinfo.Exists)
        {
            throw new FileNotFoundException(fileinfo.Name);
        }

        try
        {
            var excelData = File.ReadAllBytes(filename);
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            var stream = new MemoryStream(excelData);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = fileinfo.Name
            };
            return result;
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
        }
    }

and then on client side in angular:
    var downloadFile = function (filename) {
        var ifr = document.createElement('iframe');
        ifr.style.display = 'none';
        document.body.appendChild(ifr);
        ifr.src = document.location.pathname + "api/GridApi/DownloadFile?filename='" + escape(filename) + "'";
        ifr.onload = function () {
            document.body.removeChild(ifr);
            ifr = null;
        };
    };


text:
Q: Equivalence between existence of limits and products+equalizers, for derivators $\require{AMScd}\def\D{\mathbb{D}}\def\prepull{\vcenter{\lrcorner}}$
It is well known that for a category $\cal C$ the existence of finite limits is equivalent to the existence of finite products and equalizers, or to the existence of a terminal object and pullbacks.
What about (pre)derivators? Is it true that, for example, the existence of finite homotopy limits (right Kan extensions), the existence of homotopy pushouts, and homotopy equalizers, can be interchanged?
More precisely, can one infer from the existence of all homotopy limits of shape $\prepull$, and from the presence of terminal objects, the existence of all homotopy limits of shape $\rightrightarrows$, and from this, in turn, the existence of all finite limits (homotopy limits indexed over a homotopy finite diagram)?
A rather naive attempt for such a a statement is: given $X\in\D(\prepull)$ there is a diagram $\bar X\in \D(\rightrightarrows)$ such that $t_{1,*}X\cong t_{2,*}\bar X$, if
$$
\begin{CD}
@. \D(\prepull)\\
@. @VVt_{1,*}V\\
\D(\rightrightarrows) @>>t_{2,*}> \D(e)
\end{CD}
$$ denote the respective homotopy limit functors. Conversely, given $\bar X$ there is $X$ satisfying the same condition.
I suspect this naive approach fails, though, especially because the proof of the fact that the existence of homotopy pushouts and finite homotopy colimits are equivalent appears here as 7.1, and relies on high-tech arguments. Moreover, this correspondence, if true and pushed to the highest coherence level, seems to set up an equivalence of derivators $\D^\prepull\cong \D^\rightrightarrows$, which is hard to believe.

A: $\require{AMScd}\def\D{\mathbb{D}}\def\prepull{\vcenter{\lrcorner}}$
The result you mention from the paper by Ponto-Shulman does not say exactly what you stated. The setting is that of derivators (so you already have all the homotopy Kan extensions indexed by small cats in some fixed category of diagrams). In that setting they prove the following:
Theorem 7.1 (Ponto-Shulman).
Let $A$ be a homotopy finite category.

*

*If $\mathbb D$ is a derivator and $\mathbb E \subseteq \mathbb D(e)$ contains the initial object and is closed under [homotopy] pushouts, then it is closed under [homotopy] $A$-colimits;

*If $F \colon \mathbb D \to\mathbb E$ is a morphism of derivators that preserves the initial object and [homotopy]
pushouts, then it preserves [homotopy] $A$-colimits.

The idea of their proof is that you can actually construct homotopy $A$-colimits via homotopy pushouts. You are actually asking about the dual setting, which of course holds similarly. In what follows I'll show that in the dual of the above theorem one can add to the characterization of classes closed under taking homotopy limits via homotopy pullbacks, also a characterization that uses homotopy equalizers. The reason for that is simple: homotopy pullbacks can be computed via homotopy equalizers:
Consider the following categories:

*

*$Ob(\prepull)=\{0,1,2\}$, $\hom_\prepull(0,1)=\{a\}$, $\hom_\prepull(2,1)=\{b\}$;

*$Ob(\rightrightarrows)=\{0,1\}$, $\hom_{\rightrightarrows}(0,1)=\{a,b\}$;

*$Ob(\square)=\{-\infty,0,1,2\}$, $\hom_\square(0,1)=\{a\}$, $\hom_\square(2,1)=\{b\}$, $\hom_\square(-\infty,0)=\{c\}$, $\hom_\square(-\infty,2)=\{d\}$;

*$Ob(\to\rightrightarrows)=\{-\infty,0,1\}$, $\hom_{\to\rightrightarrows}(0,1)=\{a,b\}$, $\hom_{\to\rightrightarrows}(-\infty,0)=\{c\}$.

Consider also the following functors:

*

*$i_{\prepull}\colon\prepull\to \square$ is the obvious inclusion;

*$i_{\rightrightarrows}\colon\{\rightrightarrows\}\to \{\to\rightrightarrows\}$ is the obvious inclusion;

*$q_{\prepull}\colon \prepull\to \{\rightrightarrows\}$ is such that $q_\prepull(0)=0=q_\prepull(2)$, $q_\prepull(1)=1$;

*$q_{\square}\colon \square\to \{\to\rightrightarrows\}$ is such that $q_\square(-\infty)=-\infty$, $q_\square(0)=0=q_\square(2)$, $q_\square(1)=1$. (Of course, $q_\square(c)=c=q_\square(d)$, $q_\square(a)=a$ and $q_\square(b)=b$).

Given a derivator $\mathbb D$ and $X\in \mathbb D(\prepull)$, I claim that
$$
(-\infty)^*(i_{\rightrightarrows})_*(q_\prepull)_*X\cong (-\infty)^*(i_\prepull)_*X.
$$
In other words, the object $\bar X$ you are asking for in your question is $(q_\prepull)_*X$. To prove the above claim you have to notice that $q_{\square} i_{\prepull}=i_{\rightrightarrows}q_{\prepull}$, hence $(q_{\square})_* (i_{\prepull})_*\cong(q_{\square} i_{\prepull})_*=(i_{\rightrightarrows}q_{\prepull})_*\cong (i_{\rightrightarrows})_*(q_{\prepull})_*$. Thus, we are reduced to verify that $(-\infty)^*(q_{\square})_*\cong (-\infty)^*$. Let $Y\in \mathbb D(\square)$, to compute $(-\infty)^*(q_{\square})_*Y$ one can use the axiom (Der.4) (i.e., Kan extensions are pointwise in a derivator), so that
$$
(-\infty)^*(q_{\square})_*Y\cong \mathrm{Hocolim}_{-\infty/q_{\square}} \mathrm{pr}^*Y
$$
where $\mathrm{pr}\colon -\infty/q_{\square}\to \square$ is the obvious projection. So let us describe the category $-\infty/q_{\square}$:

*

*$Ob(-\infty/q_{\square})=\{(-\infty,id),(-\infty,c),(-\infty,ac),(-\infty,bc)\}$

*the object $(-\infty,id)$ is clearly initial.
Hence,
$$
\mathrm{Hocolim}_{-\infty/q_{\square}} \mathrm{pr}^*Y\cong (-\infty,id)^*\mathrm{pr}^*Y\cong (-\infty)^*Y,
$$
where the first isomorphism holds by the well-known fact that taking the homotopy limit indexed by a category with an initial object is the same as evaluating at the initial object. This concludes the proof.
Let me add a final remark. In the comments to the question, Marc Hoyois suggests you to look at Proposition 4.4.3.2 in Lurie's Higher Topos Theory. If you look inside the proof of that result (dualizing to your setting), you will see that it actually gives a proof that homotopy pullbacks can be constructed using equalizers in the setting of $(\infty,1)$-categories. In fact, if you follow the steps in that proof (adapted to the setting of derivators), you start with an object $X\in \mathbb D(\prepull)$ and construct a "incoherent" diagram in $\mathbb D(e)^{\rightrightarrows}$ of the form:
$$
X_0\times X_1\rightrightarrows X_2
$$
This is exactly the underlying diagram of the object $(q_{\prepull})_*X$ constructed above.

Edit:
Let me be very precise on the exact statement of the theorem one gets with the above argument:
Theorem.
Let $A$ be a homotopy finite category.  If $F \colon \mathbb D \to\mathbb E$ is a morphism of derivators that preserves finite products and homotopy equalizers, then it preserves homotopy $A$-colimits.
Proof. By Ponto-Shulman it is enough to verify that $F$ preserves pullbacks, that is, given $X\in \D(\prepull)$, there is a natural isomorphism
$$
F((-\infty)^*(i_{\prepull})_*X)\cong (-\infty)^*(i_{\prepull})_*F(X).
$$
Now, we know that $(-\infty)^*(i_{\prepull})_*X\cong (-\infty)^*(i_{\rightrightarrows})_*(q_\prepull)_*X$ and, also using that $F$ commutes with $(-\infty)^*i_{\rightrightarrows}$, we get
\begin{align*}
F((-\infty)^*(i_{\prepull})_*X)&\cong F((-\infty)^*(i_{\rightrightarrows})_*(q_\prepull)_*X)\\
&\cong (-\infty)^*(i_{\rightrightarrows})_*F((q_\prepull)_*X)
\end{align*}
To conclude it is enough to show that the canonical morphism
$$
F(q_\prepull)_*X\to (q_\prepull)_*F(X)
$$
is an isomorphism. Since, in a derivator, a morphism is an iso if and only if its components are isos (this is usually the axiom (Der.2)), it is enough to look at the underlying diagrams. With some standard computation with the axiom (Der.4), one gets that the underlying diagram of $F(q_\prepull)_*X$ is $(F(X_0\times X_1)\rightrightarrows F(X_2))$, while the underlying diagram of $(q_\prepull)_*F(X)$ is $(F(X_0)\times F(X_1)\rightrightarrows F(X_2))$. Since $F$ also commutes with finite products, these diagrams are isomorphic, concluding our proof.\\\


text:
Q: List files under a folder within a Camel rest service I am creating a rest service using Camel Rest DSL. Within the service I need to list all files under a folder and do some processing on them. PFB the code -
from("direct:postDocument")
    .to("file:/home/s469457/service/content-util/composite?noop=true")
    .setBody(constant(null))
    .log("Scanning file ${file:name.noext}.${file:name.ext}...");

Please advice.
~ Arunava

A: I would suggest to write a processor or a bean to list files in directory. I think that would be more efficient and so much simpler. Using Camel's file component you would have to deal with intricacies you might not expect.
Regardless. You will need to do pollEnrich and afterwards aggregate the whole result. I also think that you would run into trouble and will not be able to read files multiple times, to solve that you might need to create idempotent repository, but when reading files there might be concurrency/file locking issues...
Here's some pseudocode to get you started if you want to go that way:
from("direct:listFiles")
    .pollEnrich("file:"+getFullPath()+"?noop=true")
    .aggregate(new AggregationStrategy {
       public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
          String filename = newExchange.getIn().getHeader("CamelFileName", String.class)
          if (oldExchange == null) {
              newExchange.getIn().setBody(new ArrayList<String>(Arrays.asList(filename)));
              return newExchange;
          } else {
          ...
       }
    })

A: //Camel Rest Api to list files
rest().path("/my-api/")
        .get()
            .produces("text/plain")
            .to("direct:listFiles");

//Camel Route to list files
        List<String> fileList = new ArrayList<String>();
        from("direct:listFiles")
        .loopDoWhile(body().isNotNull())
            .pollEnrich("file:/home/s469457/service/content-util/composite?noop=true&recursive=true&idempotent=false&include=.*.csv")
            .choice()
                .when(body().isNotNull())
                    .process( new Processor(){
                        @Override
                        public void process(Exchange exchange) throws Exception {
                            File file = exchange.getIn().getBody(File.class);
                            fileList.add(file.getName());
                        }
                    })
                .otherwise()
                .process( new Processor(){
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        if (fileList.size() != 0)
                            exchange.getOut().setBody(String.join("\n", fileList));
fileList.clear();
                    }
                })
        .end();


text:
Q: explode string at "newline,space,newline,space" in PHP This is the string I'm trying to explode. This string is part of a  paragraph which i need to split at every "newline,space,newline,space" :
s

 1

A result from textmagic.com show it contains a \n then a space then a \n and then a space.

This is what I tried:
$values = explode("\n\s\n\s",$string); // 1
$values = explode("\n \n ",$string);   // 2
$values = explode("\n\r\n\r",$string); // 3

Desired output:
Array (
    [0] => s
    [1] => 1
)

but none of them worked. What's wrong here?
How do I do it?

A: Just use explode() with PHP_EOL." ".PHP_EOL." ", which is of the format "newline, space, newline, space". Using PHP_EOL, you get the correct newline-format for your system.
$split = explode(PHP_EOL." ".PHP_EOL." ", $string);
print_r($split);

Live demo at https://3v4l.org/WpYrJ

A: Using preg_split() to explode() by multiple delimiters in PHP
Just a quick note here. To explode()  a string using multiple delimiters in PHP you will have to make use of the regular expressions. Use pipe character to separate your delimiters.
$string = "\n\ranystring"
$chunks = preg_split('/(de1|del2|del3)/',$string,-1, PREG_SPLIT_NO_EMPTY);

// Print_r to check response output.
echo '<pre>';
print_r($chunks);
echo '</pre>';

PREG_SPLIT_NO_EMPTY  – To return only non-empty pieces.