text:
Q: \bigg is not working for left parenthesis \documentclass[11pt]{article}
\usepackage{xfrac, array, tabu, multirow, graphicx, setspace, dcolumn, tikz}
\usepackage[fleqn]{mathtools}
%the argument for d specifies the maximum number of decimal places
\usepackage[ngerman]{babel}
\usepackage[applemac]{inputenc}
\begin{document}

\begin{align}
x^2&=\sum_{x=1}^{30} \bigg((f_{obs}-f_{exp}\bigg)^2/f_{exp}\\
x^2&=\underline{10.55}
\end{align}
\end{document}

I can't seem to find the mistake, what am I missing?


text:
Q: Reconnecting a rewound 110vac motor to power Motor is (about) 5hp 110vac and powers a a table saw.
Motor was recently rewound but previous owner did not reconnect to the power cord.
There are no info plates on the motor to help w/ reconnecting.
There are 4 wires coming out of the motor in two pairs. One pair is 1 black wire and 1 white wire, the other pair is 1 black wire and 1 green wire.
The wires on the power side of the connection are a typical black, white, and green which go to the power via the on/ off switch on the front of the machine.
So I need to know which wires on the motor (right in photo) connect to which wires from the switched power wires (left in photo)
Motor wires: (on right in photo)
black, white, black, green.
Power wires from switch:
(On left in photo)
black, white, green.
Any help appreciated!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django: How to Add Default Location for Forms.ImageField I am changing my models to forms so that I can use a placeholder for my textboxes. In doing so, I am having difficulty changing the ImageField because it is providing me with an error that it recieved ``an unexpected keyword: default```
Here are my models.py:
class Project(forms.Form):
    name = forms.CharField(max_length=30)
    #owner = models.ForeignKey(User, on_delete=models.CASCADE, null = True)
    bPic = forms.ImageField(default='defaultproban.jpg', upload_to='project_banner')
    logo = forms.ImageField(default='defaultlogo.jpg', upload_to='project_logo')
    dep_choice1 = (
        ('Behavioral Sciences and Leadership', ('Behavioral Sciences and Leadership')),
        ('Chemistry and Life Science', ('Chemistry and Life Science')),
        ('Civil and Mechanical Engineering', ('Civil and Mechanical Engineering')),
        ('Electrical Engineering and Comptuer Science', ('Electrical Engineering and Comptuer Science')),
        ('English and Philosophy', ('English and Philosophy')),
        ('Foreign Languages', ('Foreign Languages')),
        ('Geography and Environmental Engineering', ('Geography and Environmental Engineering')),
        ('History', ('History')),
        ('Law', ('Law')),
        ('Mathematical Sciences', ('Mathematical Sciences')),
        ('Physics and Nuclear Engineering', ('Physics and Nuclear Engineering')),
        ('Social Sciences', ('Social Sciences')),
        ('Systems Engineering', ('Systems Engineering')),
        ('Independent', ('Independent')),
    )
    department = forms.CharField(
        max_length=50,
        choices=dep_choice1,
        default='Independent',
    )
    purpose = forms.CharField(max_length=50, null = True, widget=forms.TextInput(attrs={'placeholder':'Write Your Mission Statement'}))
    description=forms.TextField(widget=forms.TextInput(attrs={'placeholder':'Briefly Describe Your Project, Progress, Goals, and Your Team!'}))
    tag_choice = (
        ('Data Analysis' , ('Data Analysis')),
        ('3D Printing' , ('3D Printing')),
        ('Robotics' , ('Robotics')),
        ('Coding' , ('Coding')),
        ('Science' , ('Science')),
        ('Drones' , ('Drones')),
        ('Math' , ('Math')),
        ('Chemistry' , ('Chemistry')),
        ('Nuclear Engineering' , ('Nuclear Engineering')),
        ('Physics' , ('Physics')),
        ('Photonics' , ('Photonics')),
        ('MATLAB' , ('MATLAB')),
        ('SolidWorks' , ('SolidWorks')),
        ('Writing' , ('Writing')),
        ('Graphic Design' , ('Graphic Design')),
        ('Design' , ('Design')),
        ('Robotics' , ('Robotics')),
        ('Business' , ('Business')),
        ('Stocks' , ('Stocks')),
        ('Hacking' , ('Hacking')),
        ('Law' , ('Law Studies')),
        ('Coding' , ('Coding')),
        ('Environmental' , ('Environment')),
        ('Lifestyle' , ('Lifestyle')),
        ('Kinesiology' , ('Kinesiology')),
        ('Health' , ('Health')),
        ('Sleep' , ('Sleep')),
        ('Psychology' , ('Psychology')),
        ('Material Science' , ('Material Science')),
        ('Batteries' , ('Batteries')),
        ('Energy' , ('Energy')),
        ('Fiber Optics' , ('Fiber Optics')),
        ('Space' , ('Space')),
        ('Autonomous Vehicles' , ('Autonomous Vehicles')),
        ('Biology' , ('Biology')),
    )

    projectTag = forms.CharField(
        max_length=32,
        choices=tag_choice,
        default='Frauds',
    )

    look = (
        ('Expert Cadets.', ('motivated cadets with niche expertise.')),
        ('Any cadet who wants to help.', ('cadets who want to learn and help.')),
        ('an engineering cadet.', ('an engineering Cadet')),
        ('a cadet with a scientific background.', ('a cadet with a scientific background')),
        ('cadets with programming experience.', ('cadets with programming experience')),
        ('Stem interests.', ('cadets with an interest in STEM.')),
        ('scholarship', ('cadets seeking scholarships from research')),
        ('a lot of work.', ('cadets who can work 10-20 hours a week')),
        ('anyone', ('anyone!')),
    )

    lookingFor = forms.CharField(
        max_length=75,
        choices=look,
        default='an engineering cadet,',
    )

    recruit = (
        ('Yes', ('Yes')),
        ('No', ('No')),
    )

    recruiting = forms.CharField(
        max_length=50,
        choices=recruit,
        default='Yes',
    )
    statusOptions = (
        ('Active', ('Active')),
        ('Archived', ('Archived')),
        ('Deleted', ('Deleted')),
    )

    status = forms.CharField(
        max_length=50,
        choices=statusOptions,
        default='Active',
    )
    class Meta:
        verbose_name_plural= "projects"

    def __str__(self):
        return self.name

Thanks and please let me know if any other part of the code would help you but this should be good.

A: you can't use default keyword or upload_to, this is not a model.
if you want to save the image you should use a model and specify name and upload location there.


text:
Q: How to Map Data in embedded systems? I am asking the question for the second time because the first time I apparently did not manage to get my request across (insert a sad smiley here).The previous post has been deleted as I thought it could just add to the confusion if I just edit it.
Problem: I am getting a packet of data (payload) from a data source. This data is given to me in an array and I would like to split this data (like in a gateway) and send it to other peripherals.
The package data I received could look like this:
uint8_t received_payload[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66};

It is noticeable that what is behind this data is not apparent. This is because it can be measurement data, which can sometimes come from several sensors and these measurement values were thrown together in a data package.
I can assume that the measured values come periodically and that I can recognize data packets based on an ID. (This does not matter here, however).
What is interesting for me now is that I want to pass on these measured values. Under certain circumstances split into two or more separate messages.
The order and position should be given somehow and somewhere.
In the following I have shown an example of how these can be listed. I would like to emphasize again that this is only an EXAMPLE and that I have freely come up with these values. I just want to show visually how the data could be swapped under certain circumstances.
uint8_t totransmit_payload_1[] = {0x11, 0x22, 0x33};
uint8_t totransmit_payload_2[] = {0x44, 0x66, 0x55};

So I would like to have something stored somewhere that corresponds to the following information content:
totransmit_payload_1[0] = received_payload[0];
totransmit_payload_1[1] = received_payload[1];
totransmit_payload_1[2] = received_payload[2];
totransmit_payload_2[0] = received_payload[3];
totransmit_payload_2[1] = received_payload[5];
totransmit_payload_2[2] = received_payload[4];

This process should work bidirectionally and have a kind of dynamic because it won't be possible for me to write "how the data is split up" in the code.(Before questions arise. When I boot my system via SPI, I get a configuration file from a MicroSD card which describes how my system should behave.)
Of course I have already tried to find solutions on the World Wide Web, but I find it difficult to find something for my low level application. I am on a microcontroller of the STM class and only program in C.
What I found that would fit my application would be a kind of mapping.
Here as references: What Is Data Mapping?
Do you guys or girls have experience with something like that? Or ideas on how something like this could work efficiently?
Thanks for your help :D
Edit: I just want to know the best way to save in C which position in an array references to another position in another array.
Without hardcoding it.

A: Seems like you you start asking about data copying, then change midway to data mapping?  Anyway, these are small examples of both:
#include <string.h>  // for memcpy
...
void CopyBytes(const* uint8_t received_payload, uint8_t* totransmit_payload_1, uint8_t* totransmit_payload_2)
{
  // of course you'll need to make sure these buffers are appropriately sized
  memcpy(totransmit_payload_1, received_payload, 3);
  memcpy(totransmit_payload_2, received_payload + 3, 3);
}

Learn more about memcpy on the man page.
If you want some data mapping instead, I would create space for the actual data in one place (the receive buffer for instance), then you can have as many pointers as you want pointing to that data:
uint8_t received_payload[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66};

uint8_t* totransmit_payload_1[3];  // creates an array of uint8_t _pointers_
uint8_t* totransmit_payload_2[3];  // does the same

// now you can do your mapping
totransmit_payload_1[0] = &(received_payload[0]);  // save the _address_ of received_payload[0] to totransmit_payload_1[0]
totransmit_payload_1[1] = &(received_payload[1]);  // (don't think the parentheses are necessary, but I like them to be perfectly clear the [] dereference happens first)
totransmit_payload_1[2] = &(received_payload[2]);
totransmit_payload_2[0] = &(received_payload[3]);
totransmit_payload_2[1] = &(received_payload[5]);
totransmit_payload_2[2] = &(received_payload[4]);

Now, any time data changes in received_payload, you can access it from the totransmit_payload structures since they point to that data.  For example:
received_payload[0] = 5;
printf("received_payload[0] = %" PRIu8 "\n", *(totransmit_payload_1[0]));  // prints 5;

// It's "bi-directional", you can dereference the pointer and assign a value to that memory location, then access it from received_payload
*(totransmit_payload_2[2]) = 17;
printf("received_payload[4] = %" PRIu8 "\n", received_payload[4]); // prints 17


text:
Q: Not able to find query string value I am trying to find query string value for string
   www.example.com/product?id=23
I am following this code

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

myApp.controller('test', ['$scope', '$location', '$http', function ($scope, $location, $http) {
alert($location.search()['id']);
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<div app="myApp" controller="test">
</div>

Here is an example i want to get id value 23 as result.
How to do this>
following this

A: use below code to get the query parameter
$location.search().id

returns an object, consisting of the keys as variables and the values as its value
myApp.controller('test', ['$scope', '$location', '$http', function ($scope, $location, $http) {
alert( $location.search().id);
}]);

hey please check this link

A: Firstly should replace app and controller by ng-app and ng-controller
and $location.search().id


text:
Q: How to navigate textboxes in between different tables using arrow keys? I have the following code, it is working that is navigating between the textboxes, but the issue is it is navigating only within one table, but am having different tables in my page. How to make it work?
$('input[type="text"],textarea').keyup(function(e){
    if(e.which==39 || e.which==13)
        $(this).closest('td').next().find('input[type="text"],textarea').focus();
    else if(e.which==37 || e.which==8)
        $(this).closest('td').prev().find('input[type="text"],textarea').focus();
    else if(e.which==40 || e.which==13)
        $(this).closest('tr').next().find('td:eq('+$(this).closest('td').index()+')').find('input[type="text"],textarea').focus();
    else if(e.which==38 || e.which==8)
        $(this).closest('tr').prev().find('td:eq('+$(this).closest('td').index()+')').find('input[type="text"],textarea').focus();
});

    <form>

            ADVERTISING:

                DOMESTIC($)
                INTERNATIONAL($)
                NOTES

                    <td class="spending_table_title" title="<?php echo $this->data[14]->content; ?>"><?php echo $this->data[13]->content; ?>
                    <input type="text" value="" name="actual_marketing_dom_print" id="actual_marketing_dom_print"  size="30" style="height:20px; width:155px;" onChange="total_dom_advt();total_marketing_spending();format(this);"/>
                    <input type="text" value="" name="actual_marketing_intl_print" id="actual_marketing_intl_print"  size="30" style="height:20px; width:155px; " onChange="total_intl_advt();total_marketing_spending();format(this);"/>
                    <textarea name="actual_marketing_print_notes"  id="actual_marketing_print_notes" style="height:32px; width:300px;" rows="3" cols="20"  class ="notes"> </textarea>

            TOTAL PRESS AND PUBLIC RELATIONS (DOMESTIC AND INTERNATIONAL COMBINED):

            $
            NOTES

                    <td  class="spending_table_title" title="<?php echo $this->data[31]->content; ?>"><?php echo $this->data[30]->content; ?>

               <input type="text" value="" name="actual_marketing_industry_relations" id="actual_marketing_industry_relations"  size="30" style="height:20px; width:155px; " onChange="total_press_public();total_marketing_spending();format(this);"/>
                    <textarea name="actual_marketing_industry_relations_notes"  id="actual_marketing_industry_relations_notes" style="height:32px; width:300px;" rows="3" cols="20" class ="notes"> </textarea>

</form>

in my code am having two tables, after completing the textboxes in one table am not table to navigate to next table textboxes, i was not known how to do this

A: Interesting question, and hopefully you will find this helpful.
What I'm doing here is to check if there is an input above or below to go to with if (t.length == 0), and if not, move to the corresponding cell in the next or previous table instead.
$(document).ready(function () {
    $('input[type="text"],textarea').keyup(function (e) {
        if (e.which == 39) {
            $(this).closest('td').next().find('input[type="text"],textarea').focus();
        } else if (e.which == 37) {
            $(this).closest('td').prev().find('input[type="text"],textarea').focus();
        } else if (e.which == 40) {
            var t = $(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"],textarea');
            if (t.length == 0) {
                t = $(document).find('table:eq(' + ($('table').index($(this).closest('table')) + 1) + ')').find('tbody tr td').parent().first().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"]:not([readonly]),textarea');
            }
            t.focus();
        } else if (e.which == 38) {
            var t = $(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"],textarea');
            if (t.length == 0) {
                t = $(document).find('table:eq(' + ($('table').index($(this).closest('table')) - 1) + ')').find('tbody tr td').parent().last().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"]:not([readonly]),textarea');
            }
            t.focus();
        }
    });
});

http://jsfiddle.net/zxTfb/5/
Please note that right now, this only works on multiple tables on top of each other, not side by side. If you need them side by side, you could copy what I did for keys 40 and 38 and modify it to work for 39 and 37 as well.
Hope it helps.
Further explanation
Let's break down this line of code and look at inner workings:
t = $(document).find('table:eq(' + ($('table').index($(this).closest('table')) - 1) + ')').find('tbody tr td').parent().last().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"]:not([readonly]),textarea');

First we find the table above the one we are currently in. This is done with the selector :eq() which selects an element, table in this case, by it's index. We select the table with our current tables index -1 to get the table above.
$(document).find('table:eq(' + ($('table').index($(this).closest('table')) - 1) + ')')

Now that we have the table above our current position, we find the last
 element that does contain a , by first looking for all , then move up to it's parent
 with .parent() and finally select the last one (bottom row) with .last().
.find('tbody tr td').parent().last()

Now we know which
 to look in, so we move ahead and look for the specific  by index, so that we end up in the right column, corresponding to the one we are currently in. This is similar to when we found the
 by index at the top.
.find('td:eq(' + $(this).closest('td').index() + ')')

Finally, we now have our correct  element and now all that remains is to find our <input> or <textarea> that isn't readonly. We do this simply by selecting them like so
.find('input[type="text"]:not([readonly]),textarea');

And now we know where to move in the table above. Since we set t to this new element, all that remains is to move the focus there with t.focus().
And there you have it!

A: How about this?
Use a global counter to assign IDs to your inputs. Then, since you know what ID triggered the event, you just add or subtract from that ID to get the new ID you should go to. Here's some code:

 <form>

  <input type="text" id="1" name="5">
  <input type="text" id="2" name="6">
  <input type="text" id="3" name="7">
  <input type="text" id="4" name="8">

  <input type="text" id="5" name="5">
  <input type="text" id="6" name="6">
  <input type="text" id="7" name="7">
  <input type="text" id="8" name="8">

  <input type="text" id="9" name="5">
  <input type="text" id="10" name="6">
  <input type="text" id="11" name="7">
  <input type="text" id="12" name="8">

  <input type="text" id="13" name="5">
  <input type="text" id="14" name="6">
  <input type="text" id="15" name="7">
  <input type="text" id="16" name="8">

  <input type="text" id="17" name="5">
  <input type="text" id="18" name="6">
  <input type="text" id="19" name="7">
  <input type="text" id="20" name="8">

  <input type="text" id="21" name="5">
  <input type="text" id="22" name="6">
  <input type="text" id="23" name="7">
  <input type="text" id="24" name="8">

</form>


text:
Q: How can I hide one user's content from other user? Let A and B are two users. They created account and now they have their own profile page. Both the users can add, edit information about them.
When user A opens B's profile page the page controls for example, add, edit buttons shouldn't be visible to him.

A: On login store the user id of the logged in user in the session. Provide a variable somewhere  accessable (like a Base class that all pages extend from). Then on that page, if the user id matches the logged in user, show the controls. Otherwise don't. Also don't forget to validate the user id on submission of the user controls as it may be possible to inject malicious data to a different user id.


text:
Q: Determining orbits and stabilisers It is given that $$(x,y) \cdot \left [\begin{array}{cc} a & b \\
b & a \end{array}\right] =(ax+by,bx+ay)$$
defines an action on the group
$$G=\left\{\left [\begin{array}{cc} a & b \\
b & a \end{array}\right]:a^2 \neq b^2\right\}$$
1) Determine the orbits
2) Determine the stabilisers of (0,0),(1,0),(1,1)
How do I do this?

A: Given a (right) group action by $G$ on a set $S,$ and a point $x\in S,$ the Stabilizer at $x$ is  is the subgroup of $G$ defined as follows:  $$G_x = \{g \in G \ : \ xg=x\}.$$
For your group action, with $A= \left[\begin{array}{cc} a& b \\ b & a \end{array}\right]\in G,$ you have $(1,0)A = (1,0)$ if and only if $a-1=0$ and $b=0.$  Thus
$$
G_{(1,0)} = \left\{ \left[\begin{array}{cc} 1 & 0 \\ 0 & 1 \end{array} \right] \right\}.
$$
Similarly, we have $(1,1)A=(1,1)$ if and only if $a+b=1.$  Therefore,
$$
G_{(1,1)} =  \left\{ \left[\begin{array}{cc} a & 1-a \\ 1-a & a \end{array} \right]  \ : \ a \neq 1 \right\}.
$$
You should verify for yourself that $G_{(0,0)}= G.$


text:
Q: Why BFS is used in Edmonds Karp algorithm which make it better with Ford Fulkerson? As, when I studied above the Edmonds Karp algorithm, it states that Edmonds Karp uses BFS, so that the complexity doesn't depend on flow value, but I am not able to understand, how BFS helps?

A: Informally, when E–K pushes flow along a path, each node in the path is further from the source than its predecessor (where distance is defined with respect to the unweighted graph of residual arcs). The key invariant is that no node ever gets closer to the source. As an instantiation of F–F, E–K saturates one of the arcs on the path, whose tail is at some distance d and whose head is at distance d+1. For this arc to become residual again, we have to push flow on the reverse arc, which requires that the tail move to distance d+2. There is an upper bound of |V|−1  on distance, so this cannot happen an arbitrary number of times, as it can with F–F with irrational weights. The subsequent push-relabel algorithms extend this intuition by not recomputing shortest path distances from scratch every time.
(I'm told that CLRS has a formal proof.)


text:
Q: getting error whenever try to deploy backend with cdk via gitlab , in local it will works as expected I am trying to deploy backend serverless resources with CDK in AWS cloud but getting errors while deploying things via GitLab build.
trying with a local visual studio it works fine.
error is below :
$ npm run deploy-backend
> ui-dashboard-infra@0.0.0 deploy-backend /builds/project/control-panel/infra
> cdk deploy --app 'ts-node stacks/backend' --all --require-approval never
Bundling asset dashboard-A/restFunctionFallbackus-east-1/Code/Stage...
/builds/project/control-panel/infra/node_modules/@aws-cdk/core/lib/asset-staging.ts:398
      throw new Error(`Failed to bundle asset ${this.node.path}, bundle output is located at ${bundleErrorDir}: ${err}`);
            ^
Error: Failed to bundle asset dashboard-A/restFunctionFallbackus-east-1/Code/Stage, bundle output is located at /builds/project/control-panel/infra/cdk.out/bundling-temp-4607286efdd890681baca6f8a5d9b9b32929fa84e9947500fbe203e5b5d06a0f-error: Error: spawnSync bash ENOENT
    at AssetStaging.bundle (/builds/project/control-panel/infra/node_modules/@aws-cdk/core/lib/asset-staging.ts:398:13)
    at AssetStaging.stageByBundling (/builds/project/control-panel/infra/node_modules/@aws-cdk/core/lib/asset-staging.ts:246:10)
    at stageThisAsset (/builds/project/control-panel/infra/node_modules/@aws-cdk/core/lib/asset-staging.ts:137:35)
    at Cache.obtain (/builds/project/control-panel/infra/node_modules/@aws-cdk/core/lib/private/cache.ts:24:13)
    at new AssetStaging (/builds/project/control-panel/infra/node_modules/@aws-cdk/core/lib/asset-staging.ts:162:44)
    at new Asset (/builds/project/control-panel/infra/node_modules/@aws-cdk/aws-s3-assets/lib/asset.ts:68:21)
    at AssetCode.bind (/builds/project/control-panel/infra/node_modules/@aws-cdk/aws-lambda/lib/code.ts:180:20)

Subprocess exited with error 1
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ui-dashboard-infra@0.0.0 deploy-backend: `cdk deploy --app 'ts-node stacks/backend' --all --require-approval never`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ui-dashboard-infra@0.0.0 deploy-backend script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-08-10T08_29_17_449Z-debug.log

A: I got the same error as you. In my case, the issue was that I had esbuild installed as a dependency in the CDK folder, but not in the folder of my Lambda function.
I was able to fix the issue by installing esbuild as a dev dependency in my Lambda function folder. If you don't want to do that, you can also install it globally in your pipeline by adding the command npm i -g esbuild to your pipeline (consider pinning it to a particular version ie. npm i -g esbuild@x.y.z).
No idea why it was working locally without esbuild installed in the function folder, but then broke when doing the same thing in a Gitlab pipeline… I didn't have esbuild installed globally on my local machine or anything.

A: I have faced a similar kind of issue, and the problem is that there is a bug in cdk versions prior to the once released before 25th Feb 2021.
For that, please make sure either you are using the latest version of cdk, or you DO NOT HAVE ANY WHITE SPACES IN YOUR FILE PATHNAME (any directory name having space or your username that has a space might cause this problem). Once I removed the white spaces from the pathname, everything started to work as expected.


text:
Q: promises inside for loop ignore the syntax error.i need to do perform some thing with i value inside aggregate and need to update it,but when i execute the below code, the for loop is not waiting to finish till update.it iterate i value very fast and the aggregate skips every i value. am new to javascript so,incase if the question is silly sorry for that too
model.countDocuments((err,count)=>{
for(i=value;i<count;i++){
     console.log(i)
     model.aggregate({[//some update function]})
     .then((res)=>model.update({field:something},{$set:res.value}}))
})

A: Try using async/await functionality
Change your code to this
model.countDocuments(async (err,count)=>{
    for(i=value;i<count;i++){
         console.log(i);
         let res = await model.aggregate({[/*some update function]*/});
         model.update({field:something},{$set:res.value}});
    }
)

Using the await keyword will make the code wait until the promise is returned and continue on the next statement.
To use the 'await' keyword, the enclosing function needs to declare itself as an 'async' function

A: You can use Promise.all to still have most of your work done concurrently, and still have your results when they are all done running, in the same order you started them. Here's a fully working example that somewhat resembles your problem.
// Generate a random value between 250 and 500. Used for the delay to setTimeout
// to mimic "long running" operations.
const delay = () => Math.floor(Math.random()*(500 - 250 + 1))+250;

// This represents your model.aggregate function. Takes an input of a number for
// the sake of correlation in this example. Always resolves a string with the
// intention of passing it into the next "then."
const aggregate = (i) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => { resolve(`[${i}]: aggregated`) }, delay());
  });
};

// This represents your model.update function. Takes a number for the sake of
// correlation and the result from the "aggregate" function.
const update = (i, res) => {
  // result from aggregate
  console.log(`[${i}]: ${res}`);

  return new Promise((resolve, reject) => {
    setTimeout(() => { resolve(`[${i}]: updated`) }, delay());
  });
};

// A helper to generate an array of numbers. Just a "fancier" alternative to
// "for i=value; i<count; i++"
const range = (i) => [...Array(i).keys()]

// An arbitrary number for the amount of work to run in this example. This
// represents "count" in your example.
const count = 10;

// This is the equivalent of what would be your for loop's body. Executes "count"
// amount of work and stores all the the promises into an array. Even though we
// have a list of promises in the array, this is non-blocking and the program will
// continue until we wait for them to all resolve later.
const res = range(count).map((i) => {
  console.log(`[${i}]: starting`);
  return aggregate(i).then((res) => update(i, res));
});

// Wait for all promises to resolve and print the final results. At this
// exact moment, some be still running and some may have completed.
// Call then will let you get the results of all the work when they are
// are all resolved.
//
// The block in "catch" will be called when any one of them "rejects" or
// throws an exception.
Promise.all(res).
  then((vals) => { for (const val of vals) { console.log(val) } }).
  catch((err) => { console.error(err) });

Here's an example output:
[0]: starting
[1]: starting
[2]: starting
[3]: starting
[4]: starting
[5]: starting
[6]: starting
[7]: starting
[8]: starting
[9]: starting
[6]: [6]: aggregated
[2]: [2]: aggregated
[4]: [4]: aggregated
[7]: [7]: aggregated
[9]: [9]: aggregated
[3]: [3]: aggregated
[0]: [0]: aggregated
[1]: [1]: aggregated
[8]: [8]: aggregated
[5]: [5]: aggregated
[0]: updated
[1]: updated
[2]: updated
[3]: updated
[4]: updated
[5]: updated
[6]: updated
[7]: updated
[8]: updated
[9]: updated

Notice that the final outputs are in the same order as how they are started (0 through 9). However, the "aggregate" and "update" are still run asynchronously.
The point of this is that you don't need to wait for the first "aggregate then update" call to finish to run the next "aggregate then update," then the next "aggregate then update" after that and so on. Pretty much throwing "asynchronicity" out the window. Using async/await definitely has its place (and I use them plenty), but I'd argue that this is not a great place to use it.


text:
Q: How to realloc some memory allocated using calloc? I've allocated a string with the calloc function:
//string1 and string2 previously declared
char *stringClone = calloc(strlen(string1) + 1, sizeof(char));

Now I want to do the same thing on stringClone with a different string. Doing:
stringClone = calloc(strlen(string2) + 1, sizeof(char));

I'm gonna have some memory leak, right? How should I use the realloc in this case?

A: You can use realloc() to reallocate memory allocated by malloc(), calloc(), realloc(), aligned_alloc() or strdup(). Note that if the reallocated block is larger than the original block returned by calloc(), the newly allocated portion will not be initialized to all bits zero.
Note however that the syntax for realloc() is not what you use: you must pass the pointer as the first argument and a single size_t for the new size. Furthermore, if a new block cannot be allocated, NULL is returned and the block is not freed, hence you should not store the return value directly to stringClone.
If you want to use realloc(), here is what you should do:
//string1 and string2 previously declared
char *stringClone = calloc(strlen(string1) + 1, 1);
...
char *newp = realloc(stringClone, strlen(string2) + 1);
if (newp == NULL) {
    // deal with out of memory condition
    free(stringClone);
}

Since you do not seem to care that the contents of stringClone be preserved in the the reallocated block, you should probably simply write:
//string1 and string2 previously declared
char *stringClone = calloc(strlen(string1) + 1, 1);
if (stringClone == NULL) {
    // deal with out of memory condition
    ...
}
strcpy(stringClone, string1);
...
free(stringClone);
stringClone = calloc(strlen(string2) + 1, 1);
if (stringClone == NULL) {
    // deal with out of memory condition
    ...
}
strcpy(stringClone, string2);

Note also that on POSIX compliant systems, there is a memory allocation function that is very useful for your use case: strdup(s) takes a pointer to a C string, allocates strlen(s) + 1 bytes, copies the string to the allocated block and returns it:
//string1 and string2 previously declared
char *stringClone = strdup(string1);
if (stringClone == NULL) {
    // deal with out of memory condition
    ...
}
...
free(stringClone);
stringClone = strdup(string2);
if (stringClone == NULL) {
    // deal with out of memory condition
    ...
}

Note also that casting the return value of malloc, calloc and realloc is unnecessary in C and considered bad style.

A: The reason to use realloc is that it keeps the original data intact. However, if I understand your use-case correctly, you intend to erase the original data. In that case, it is simpler and clearer to just write:
char *stringClone = calloc(strlen(string1) + 1, sizeof(char));
// check for calloc error
// use stringClone for string1
free(stringClone);
stringClone = calloc(strlen(string2) + 1, sizeof(char));
// check for calloc error
// use stringClone for string2

The error-checking is simpler for calloc than for realloc, since no temporary variable is needed. Also, this pattern makes it clear that the array contents for string1 and string2 are not related.


text:
Q: batch script to handle files I have a config file, The file is like
mach.conf
Machine_IP = <IP Address>
Machine_Name = <Machine name>
User_Name = <UID>
ERRORCODE = 8000
..

Likewise. I am new to windows batch script, though I had read on internet about batch scripting and able to understand & write simple batch scripts. But no where I find handling files using batch script, like I want to read the config file if I see ERRORCODE = 8000
do a change and replace 8000 with 8001.
How to do this using batch scripting. Please provide me links or some hints.
Thanks...

A: I've added a bit of code that may not be necessary, but allows the program to manipulate unquoted <'s and >'s. All it does is pre-pend a ^ to them, so < becomes ^< and > becomes ^>.
@echo off
 setlocal enabledelayedexpansion
 if exist config.tmp del config.tmp
 for /f "tokens=1* delims== " %%x in (config.cnf) do call :processFile "%%x" "%%y"
 move config.tmp config.cnf > nul
 echo File Updated
 endlocal
goto :eof

:processFile
 set "Var=%~1"
 set "Val=%~2"

 :: Add Escape Code to the greater-than and less-than symbols so they don't
 :: act as pipes and create errors.
 set "Var=%Var:<=^<%"
 set "Var=%Var:>=^>%"
 set "Val=%Val:<=^<%"
 set "Val=%Val:>=^>%"

 if "%Var%"=="ERRORCODE" set /a Val=%Val% + 1

 echo %Var% = %Val%>> config.tmp


text:
Q: Rewards with multiple winners in WordPress First of all I am new with WordPress and PHP. I want a reward module where I can have multiple categories and for each category multiple winners.
I have achieved that in CI (CodeIgniter) but now wanted to implement the similar stuff in WordPress. Where I can Have one category and that category can have multiple winners with there respective position.And I will be able to perform simple crud functionality.
Any suggestion how can be this model can be implemented in WordPress or if there any plugin is available with somewhat similar functionality?
Should I create my own plugin for this and for the start I have tried this
 $your_db_name = $wpdb->prefix . 'your_db_name';

// function to create the DB / Options / Defaults
function your_plugin_options_install() {
    global $wpdb;
    global $your_db_name;

    // create the ECPT metabox database table
    if($wpdb->get_var("show tables like '$your_db_name'") != $your_db_name)
    {
        $sql = "CREATE TABLE " . $your_db_name . " (
        `id` mediumint(9) NOT NULL AUTO_INCREMENT,
        `field_1` mediumtext NOT NULL,
        `field_2` tinytext NOT NULL,
        `field_3` tinytext NOT NULL,
        `field_4` tinytext NOT NULL,
        UNIQUE KEY id (id)
        );";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

}
// run the install scripts upon plugin activation
register_activation_hook(__FILE__,'your_plugin_options_install');

Any suggestions? Thanks in advance

A: There's no need to create a custom database table to do this.

*

*Register a custom post type for Awards including just a few features (title,editor and image).

*Add a metabox to handle the winners (registered users).

*Attach a custom taxonomy for something like prizes.

*With that, you can use the default WP_Query capabilities and create regular theme templates, or widgets, or shortcodes, to output results.

There are good plugins to manage CPTs and Custom Fields that make this easy, but here's the small plugin outlined above:
<?php
/**
 * Plugin Name: (SO) Awards, prizes and winners
 * Plugin URI:  http://stackoverflow.com/q/25936506/1287812
 * Version:     0.1
 * Author:      brasofilo
 */

class SO_25936506
{
    private $cpt = 'reward';

    public function __construct()
    {
        add_action( 'init', array( $this, 'init' ) );
        add_action( 'save_post', array( $this, 'save' ), 10, 2 );
    }

     public function init() {
        $labels = array(
            'name' => _x( 'Rewards', 'post type general name' ),
            'singular_name' => _x( 'Reward', 'post type singular name' ),
            'add_new' => _x( 'Add New', 'reward' ),
            'add_new_item' => __( 'Add New Reward' ),
            'edit_item' => __( 'Edit Reward' ),
            'new_item' => __( 'New Reward' ),
            'all_items' => __( 'All Rewards' ),
            'view_item' => __( 'View Reward' ),
            'search_items' => __( 'Search Rewards' ),
            'not_found' =>  __( 'No rewards found' ),
            'not_found_in_trash' => __( 'No rewards found in Trash' ),
            'parent_item_colon' => '',
            'menu_name' => __( 'Rewards' )
        );
        $args = array(
            'labels' => $labels,
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'show_in_menu' => true,
            'query_var' => true,
            'rewrite' => array( 'slug' => _x( 'reward', 'URL slug' ) ),
            'capability_type' => 'page',
            'has_archive' => true,
            'hierarchical' => false,
            'menu_position' => null,
            'taxonomies' => array('prize'),
            'supports' => array( 'title', 'editor', 'thumbnail' ),
            'register_meta_box_cb' => array( $this, 'add_metabox' )
        );
        register_post_type( $this->cpt, $args );

        register_taxonomy('prize', $this->cpt, array(
            // Hierarchical taxonomy (like categories)
            'hierarchical' => true,
            // This array of options controls the labels displayed in the WordPress Admin UI
            'labels' => array(
                'name' => _x( 'Prizes', 'taxonomy general name' ),
                'singular_name' => _x( 'Prize', 'taxonomy singular name' ),
                'search_items' =>  __( 'Search Prizes' ),
                'all_items' => __( 'All Prizes' ),
                'parent_item' => __( 'Parent Prize' ),
                'parent_item_colon' => __( 'Parent Prize:' ),
                'edit_item' => __( 'Edit Prize' ),
                'update_item' => __( 'Update Prize' ),
                'add_new_item' => __( 'Add New Prize' ),
                'new_item_name' => __( 'New Prize Name' ),
                'menu_name' => __( 'Prizes' ),
            ),
            // Control the slugs used for this taxonomy
            'rewrite' => array(
                'slug' => 'prizes', //
                'with_front' => false,
                'hierarchical' => true
            ),
        ));
    }

    public function add_metabox()
    {
        add_meta_box(
            'winners',
            'Winners',
            array( $this, 'do_metabox' ),
            $this->cpt,
            'normal',
            'default',
            array( // to build the custom fields
                '_winner_gold' => array( 'title'=>'Gold', 'desc' => 'G desc' ),
                '_winner_silver' => array( 'title'=>'Silver', 'desc' => 'S desc' ),
                '_winner_bronze' => array( 'title'=>'Bronze', 'desc' => 'B desc' )
            )
        );
    }

    // back function of add meta box that displays the meta box in the post edit screen
    public function do_metabox( $post, $box )
    {
        wp_nonce_field( plugin_basename( __FILE__ ), 'noncename_so_25936506' );
        foreach( $box['args'] as $field => $value )
            $this->print_field( $field, $value, $post->ID );
    }

    public function print_field( $field, $value, $post_id )
    {
        $post_meta = get_post_meta( $post_id, $field, true);
        $selected = ($post_meta) ? $post_meta : false;
        $users_dd = wp_dropdown_users(array(
            'name' => 'author',
            'echo'=>false,
            'name'=>$field,
            'show_option_none'=>'Select winners'
        ));
        printf(
            '%s: %s %s
',
            $value['title'],
            $users_dd,
            $value['desc']
        );
    }

    public function save( $post_id, $post_object )
    {
        // Verify auto save
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
            return;

        // Security
        if (
            !isset( $_POST['noncename_so_25936506'] )
            || !wp_verify_nonce( $_POST['noncename_so_25936506'], plugin_basename( __FILE__ ) )
            )
            return;

        if ( $this->cpt !== $post_object->post_type )
            return;

        // Process post data
        foreach( array('_winner_gold','_winner_silver','_winner_bronze') as $field )
        {
            if ( isset( $_POST[$field] )  )
                update_post_meta( $post_id, $field, $_POST[$field] );
            else
                delete_post_meta( $post_id, $field );
        }
    }
}
new SO_25936506();


text:
Q: Export Plot to PDF results very messy When my nice looking DiscretePlot results are exported as PDF, they look very different from the original plots. For example, my original plot in Mathematica looks like

When this is exported as PDF, I have

Is there anyway I can export my plots exactly as they look?
EDIT
My model is a discrete dynamic model consisted of around ten variables and ten equations. So I used DiscretePlot, not Plot.
My code is:

a1 = 0.85;
a2 = 0.25;
L1 = 0.07;
L2 = 0.3;
w = 2;
b1 = 1;
b2 = 0.2;
x1[0] = 1;
x2[0] = 1;
p1[0] = 0.5;
p2[0] = 0.2;
mul0 = 0.9
mul1 = 3.9
mul2 = 2.8
H[0] = 1
r[0] = 0.1

x1[t_] := x1[t] = G*x1[t - 1];
x2[t_] := x2[t] = G*x2[t - 1];
mul[t_] := mul[t] = mul0 + mul1*r[t - 1] + mul2*(G - 1)
H[t_] := H[t] = H[t - 1]*G
m[t_] := m[t] = (mul[t]*H[t])/(L1*x1[t] + L2*x2[t])
exp[t_] := exp[t] = (m[t] - p2[t - 1]*w)/(p2[t - 1]*w)
r[t_] := r[t] = (exp[t]*(p2[t - 1]*w*L1*x1[t] +
   p2[t - 1]*w*L2*x2[t]))/((p1[t - 1]*a1 + p2[t - 1]*w*L1)*
  x1[t] + (p1[t - 1]*a2 + p2[t - 1]*w*L2)*x2[t])
p1[t_] := p1[t] = (1 + r[t])*(p1[t - 1]*a1 + p2[t - 1]*w*L1)
p2[t_] := p2[t] = (1 + r[t])*(p1[t - 1]*a2 + p2[t - 1]*w*L2)
check[t_] := check[t] = (x1[t] - a1 x1[t] - a2 x2[t])*p1[t] +
x2[t]*p2[t] -m[t]*(L1*x1[t] + L2*x2[t])

n1 = 1;
n2 = 200

Plot3 = Show[GraphicsRow[{DiscretePlot[p1[t], {t, n1, n2},
 PlotLabel -> "Price 1", BaseStyle -> {FontSize -> 10},
 PlotRange -> {{n1, n2}, {0, 10}}, Filling -> None,
 Joined -> True],
DiscretePlot[v1[t], {t, n1, n2}, PlotLabel -> "Price 2",
 BaseStyle -> {FontSize -> 10}, PlotRange -> {{n1, n2}, {0, 5}},
 Filling -> None, Joined -> True],
DiscretePlot[check[t], {t, n1, n2}, PlotLabel -> "check",
 BaseStyle -> {FontSize -> 10}, PlotRange -> {{n1, n2}, {0, 10}},
 Filling -> None, Joined -> True]}], ImageSize -> Full]
Export["Plot3.pdf", Plot3];

A: How are you producing the pdf?  What operating system are you using?  You haven't included any code, but in my attempt I don't reproduce your problem,
GraphicsRow[{
  Plot[(20 Exp[-t/2] + 2 Exp[-t/20] Cos[t] + 3), {t, 0, 50},
   PlotLabel -> "Price 1"],
  Plot[(30 Exp[-t/2] - 2 Exp[-t/5] Cos[t] + 14), {t, 0, 50},
   PlotLabel -> "Price 2"],
  Plot[(2 Exp[-t/2] - 2 Exp[-t/25] Cos[t] + 6), {t, 0, 50},
   PlotLabel -> "Price is Right"]}, ImageSize -> 700]
Export["pricecheck.pdf", %]

and here is a comparison of the results

A: *

*Select the cell with the plots

*Copy-paste into a new empty notebook

*File -> Printing Settings -> Page Setup...

*Choose paper size A3 and landscape

*Save as a new pdf

*Go to https://www.cutepdf-editor.com/edit.asp

*Upload pdf and crop it and save it

I have experienced that some of the symbols from mathematica (such as capital gamma) appear wrong when the file is loaded in cutepdf, but when I save them and open in adobe reader, they are right again.


text:
Q: 90 degree Skew Correction for OCR in opencv python Skew correction is common with OCR and my skew correction code using houghLinesP() and finding the angle of skewed image is working fine. What I wanted to ask was how do you deal with an image skewed 90 degrees? As the angle would probably be 0 degrees and tesseract wont extract any text.
So how to deal with this problem?

A: You can use osd function of tesseract for skew correction. Even though for normal images skew correction using traditional image processing may work, but for scanned and low-quality images, traditional approaches might fail. So better to go with osd functionality provided by tesseract

    import pytesseract
    import cv2
    import numpy as np

    ###function to rotate image

    def rotate_bound(image, angle):
        """Rotate image with the given angle

        :param type image: input image
        :param type angle: Angle to be rotated
        :return: rotated image
        :rtype: numpy.ndarray

        """
        (h, w) = image.shape[:2]
        ### centroid
        (cX, cY) = (w // 2, h // 2)
        ### creating rotation matrix
        M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)

        cos = np.abs(M[0, 0])
        sin = np.abs(M[0, 1])
        nW = int((h * sin) + (w * cos))
        nH = int((h * cos) + (w * sin))
        M[0, 2] += (nW / 2) - cX
        M[1, 2] += (nH / 2) - cY

        return cv2.warpAffine(image, M, (nW, nH))

    ###read input image
    image=cv2.imread('path/to/image.jpg')
    ###getting orientation info
    newdata=pytesseract.image_to_osd(image)
    ###filter angle value
    angle=re.search('(?<=Rotate: )\d+', newdata).group(0)
    print('osd angle:',angle)
    ### rotating image with angle
    skew_corrected_image=rotate_bound(image,float(angle))
    ### you can add tesseract OCR call here


text:
Q: Xamarin Forms, Dynamic ScrollView in XAML I'm wanting to create a GUI that has a similar to what the following code generates,  a scroll of frames.
However I want to be able to have a scroll of dynamic content frames, ideally in XAML and populated with an Item source. I don't think this is possible without creating a custom view based on itemsview from what I can see.  ListView and CollectionView don't quite do what I want.
I think I need to use the preview CarouselView, I was wondering if there is a way of doing what I'm after without.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FlexTest.MainPage">

    <ContentPage.Resources>
    <Style TargetType="Frame">
        <Setter Property="WidthRequest" Value="300"/>
        <Setter Property="HeightRequest" Value="500"/>
        <Setter Property="Margin" Value="10"/>
        <Setter Property="CornerRadius" Value="20"/>
    </Style>
    </ContentPage.Resources>

    <ScrollView Orientation="Both">
        <FlexLayout>
            <Frame BackgroundColor="Yellow">
                <FlexLayout Direction="Column">
                    <Label Text="Panel 1"/>
                    <Label Text="A Panel"/>
                    <Button Text="Click Me"/>
                </FlexLayout>
            </Frame>
            <Frame BackgroundColor="OrangeRed">
                <FlexLayout Direction="Column">
                    <Label Text="Panel 2"/>
                    <Label Text="Another Panel"/>
                    <Button Text="Click Me"/>
                </FlexLayout>
            </Frame>
            <Frame BackgroundColor="ForestGreen">
                <FlexLayout Direction="Column">
                    <Label Text="Panel 3"/>
                    <Label Text="A Third Panel"/>
                    <Button Text="Click Me"/>
                </FlexLayout>
            </Frame>
        </FlexLayout>
    </ScrollView>
</ContentPage>

Thanks
Andy.

A: Preface: I hope I understood your request correctly :)
If by dynamic content you mean having a dynamic ItemTemplate then you can try doing following:
Step One:
Define an ItemTemplateSelector, you can give it w.e name you want. In this class we will define what sort of templates we have, let us say we have the three which you defined: Yellow, OrangeRed, ForestGreen
   public class FrameTemplateSelector : DataTemplateSelector {
       public DataTemplate YellowFrameTemplate {get; set;}
       public DataTemplate OrangeRedFrameTemplate {get; set;}
       public DataTemplate ForestGreenFrameTemplate {get; set;}

       public FrameTemplateSelector() {
          this.YellowFrameTemplate = new DataTemplate(typeof (YellowFrame));
          this.OrangeRedFrameTemplate = new DataTemplate(typeof (OrangeRedFrame));
          this.ForestGreenFrameTemplate = new DataTemplate(typeof (ForestGreenFrame));
       }

       //This part is important, this is how we know which template to select.
       protected override DataTemplate OnSelectTemplate(object item, BindableObject container) {
          var model = item as YourViewModel;
          switch(model.FrameColor) {
            case FrameColorEnum .Yellow:
              return YellowFrameTemplate;
            case FrameColorEnum .OrangeRed:
              return OrangeRedFrameTemplate;
            case FrameColorEnum .ForestGreen:
              return ForestGreenFrameTemplate;
            default:
             //or w.e other template you want.
              return YellowFrameTemplate;
       }
   }

Step Two:
Now that we have defined our Template Selector let us go ahead and define our templates, in this case our Yellow, OrangeRed, and ForestGreen frames respectively. I will simply show how to make one of them since the others will follow the same paradigm excluding, with of course the color changing. Let's do the YellowFrame
In the XAML you will have:
YellowFrame.xaml:
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         x:Class="YourNameSpaceGoesHere.YellowFrame">
      <Frame BackgroundColor="Yellow">
                <FlexLayout Direction="Column">
                    <Label Text="Panel 1"/>
                    <Label Text="A Panel"/>
                    <Button Text="Click Me"/>
                </FlexLayout>
      </Frame>
</StackLayout>

In the code behind:
YellowFrame.xaml.cs:
public partial class YellowFrame : StackLayout {
   public YellowFrame() {
      InitializeComponent();
   }
}

Step Three
Now we need to create our ViewModel that we will use for our ItemSource that we will apply to FlexLayout, per the documentation for Bindable Layouts, any layout that "dervies from Layout" has the ability to have a Bindable Layout, FlexLayout is one of them.
So let us make the ViewModel, I will also create an Enum for the Color frame we want to render as I showed in the switch statement in step one, however, you can choose what ever means of deciding how to tell which template to load; this is just one possible example.
BaseViewModel.cs:
public abstract class BaseViewModel : INotifyPropertyChanged {

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = ""){
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public virtual void CleanUp(){
        }
    }

ParentViewModel.cs:
public class ParentViewModel: BaseViewModel {
   private ObservableCollection<YourViewModel> myViewModels {get; set;}
   public ObservableCollection<YourViewModel> MyViewModels {
      get { return myViewModels;}
      set {
          myViewModels = value;
          OnPropertyChanged("MyViewModels");
      }
   }

   public ParentViewModel() {
     LoadData();
   }

   private void LoadData() {
       //Let us populate our data here.
       myViewModels = new ObservableCollection<YourViewModel>();

       myViewModels.Add(new YourViewModel {FrameColor = FrameColorEnum .Yellow});
       myViewModels.Add(new YourViewModel {FrameColor = FrameColorEnum .OrangeRed});
       myViewModels.Add(new YourViewModel {FrameColor = FrameColorEnum .ForestGreen});
      MyViewModels = myViewModels;
   }
}

YourViewModel.cs:
public class YourViewModel : BaseViewModel {
    public FrameColorEnum FrameColor {get; set;}
}

FrameColorEnum.cs:
public enum FrameColorEnum {
   Yellow,
   OrangeRed,
   ForestGreen
}

We're almost there, so what we have done so far is we defined our view models that we will use on that page, the final step is to update our overall XAML where we will call our Template Selector. I will only update the snippets needed.
<ContentPage
...
    **xmlns:views="your namespace where it was defined here,
    normally you can just type the name of the Selector then have VS add the proper
    namespace and everything"**
<ContentPage.Resources>
<!--New stuff below-->
   <ResourceDictionary>
       <views:FrameTemplateSelector x:Key="FrameTemplateSelector"/>
   </ResourceDictionary>
</ContentPage.Resources>

<ScrollView Orientation="Both">
        <FlexLayout BindableLayout.ItemsSource="{Binding MyViewModels, Mode=TwoWay}"
                    BindableLayout.ItemTemplateSelector ="{StaticResource FrameTemplateSelector}"/>
    </ScrollView>

Live Picture:

A: Do you want to implement a scrollable view and each child contains multiple content that can be scrolled horizontally?
For this feature, try to display the CarouselView in a ListView.
Check the code:
<ListView ...>
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <CarouselView>
                    <CarouselView.ItemTemplate>
                        <DataTemplate>
                            ...
                        </DataTemplate>
                    </CarouselView.ItemTemplate>
                </CarouselView>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Tutorial about CarouselView:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/carouselview/introduction


text:
Q: Missing image in Jasper Reports I am trying to generate a Jasper report from my Java code, my Java application is Swing. I designed the Jasper report using the TIBCO Jaspersoft Studio 6.0.0 final. However, in my report, there is a Logo image. The image location is dynamically passed, it works fine when previewed on Jaspersoft Studio. Below is how the image is set in JasperSoft studio.The imagePath variable is String
<image>
    <reportElement x="210" y="0" width="140" height="76" uuid="2c20bfe9-e8af-4ca4-9c06-3c81ebe5f8a1"/>
    <imageExpression><![CDATA[$P{imagePath}]]></imageExpression>
</image>

This is how I generate the report in Java.
private class PrintClientListBtnAction implements ActionListener
     {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            ReportConnector r = new ReportHandler();
            try {
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("imagePath", ClassLoader.getSystemResourceAsStream("/ReportResources/Logo_Big2i.png"));
                r.printReport(getClass().getResourceAsStream("/ReportResources/Core_Clients.jasper"), params);

            } catch (JRException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, ex.getLocalizedMessage(),"Printing error",JOptionPane.ERROR_MESSAGE);
            }
        }

     }

The problem is, the report generated by the Java code do not have an image! what is wrong here?
Update
I tried with imagePath as InputStream as well, but the same result is here...

A: I don't think your images should be loaded through the system class loader. Try replacing
ClassLoader.getSystemResourceAsStream(

By
PrintClientListBtnAction.class.getResourceAsStream(


text:
Q: In SDI: where to disable menu, code ok in MDI I am trying to disable main menu items.
in MDI application, this works:
CWnd *pW=AfxGetMainWnd();
CMenu * pMenu=pW->GetMenu();
pMenu->EnableMenuItem(5, MF_BYPOSITION | MF_GRAYED | MF_DISABLED);

Not in SDI. Most likely, I am putting it into the wrong place. CMainframe? The view? Which speific subroutine? I tried the constructors, but no change in UI.
Any help is appreciated, I am banging my head and searched numerous web places (and here) but didn't find the right direction.
many thanks

A: You don't want to directly enable/disable menu items under MFC, whether it's SDI or MDI.
Instead, when you add the item to the menu, you add two event handlers for it. One will be for "COMMAND", the other for "UPDATE_COMMAND_UI".

the COMMAND handler actually carries out the command for that menu entry.
The UPDATE_COMMAND_UI handler (indirectly) enables/disables the menu entry by returning true/false to indicate whether it should be enabled.
As to why this is preferable: first and foremost, because you can have (for example) both a menu entry and a toolbar that invoke the same action. This automatically enables/disables both as appropriate.

A: you can do that by using class wizard to add function that handles Enabling/disabling menu items via UPDATE_COMMAND_UI:
void CMyAdoMfcView::OnUpdateAddnew(CCmdUI* pCmdUI)
{
    // TODO: Add your command update UI handler code here
    pCmdUI->Enable(true);
}

in my code I enabled the menu item AddNew.


text:
Q: Opening a full screen application on a specific window Running 19.04, with a triple monitor setup. I open games full screen on my centre monitor with Wine, simply by running wine game.exe. However, Wine recently updated, and now it's opening on my left-most monitor. How can I get it back to opening on my centre monitor?
I've tried using the --geometry option at the end of my Wine command, but it doesn't seem to make a difference. The software still opens in the same spot.
The centre monitor is also confirmed as the primary monitor.
Using Nvidia driver 430.26.

If I recall, X does not create separate screens for each monitor. Rather, it combines the monitors into one logical screen. Looking at nvidia-settings, I see X Screen 0 shown as 5040x1086. My three monitors are set to 1680x1050, 1920x1080, and 1440x900, from left to right.
I don't know if this is how X Server has always done it, but perhaps my issue could be solved if each monitor was its own separate screen. Is there a way to do that? Or is there a better/simpler solution to this problem?
I had asked a similar question almost a year ago, regarding how to open a terminal on a specific monitor. Unfortunately, the same method does not seem to apply to the situation here.

EDIT:
Information as shown by nvidia-settings indicates that X Screen 0, which contains my three monitors, has a display name of hiigaran:0.0.
As per earthmeLon's suggestion, I attempted to prepend SDL_VIDEO_FULLSCREEN_HEAD to the command I wished to use to start the application in question. The following three commands were used to test which monitor the application would open on:
SDL_VIDEO_FULLSCREEN_HEAD=0 wine game.exe
SDL_VIDEO_FULLSCREEN_HEAD=1 wine game.exe
SDL_VIDEO_FULLSCREEN_HEAD=2 wine game.exe

No difference was observed between using any of these commands, and using wine game.exe on its own. The application still opened full screen on the left-most monitor.

A: Typically, you use a single Screen, and all of your monitors belong to that one Screen, as you're seeing.  By using multiple Screens, you can more accurately define where applications load, but you cannot move applications between different Screens.
If you were using multiple Screens, you would determine which Screen via the DISPLAY variable:
DISPLAY=:1 wine

To set which monitor is used for full screen applications, as well as to ensure that all monitors aren't used altogether for full screen applications, I've had the most luck setting the SDL_VIDEO_FULLSCREEN_HEAD environment variable so that this is available within the window manager.  You set it to the number of your monitor, starting with zero:
export SDL_VIDEO_FULLSCREEN_HEAD=0

With three monitors, you can choose between 0, 1 and 2.  You can set this in ~/.xinitrc / ~/.xsessionrc.  Where you place this export is highly dependent on how your window manager starts up, using GDM, LightDM, or startx, etc.
You can test if this may work for you, or which monitor is which, by setting the variable at runtime:
$ SDL_VIDEO_FULLSCREEN_HEAD=1 wine

Note: OP mentions this testing does not work.

It may make sense to also set this as your default monitor, or ensure it is not your default monitor.  The default monitor can be set with xrandr:
$ xrandr primary NAME_OF_DEVICE

Wine Virtual Desktop
If all of this fails, you have the final option of configuring Wine to use a virtual desktop.  This will cause Wine to create a Windows window, and you are able to specify the resolution of this window (to match your monitor's resolution).  Full screen Windows applications run via Wine will then fill that window only.  You can use your Window Manager to move this to the correct desktop/monitor.
This can be done opening Wine Configuration (winecfg) and opening the Graphics tab, or by using the /desktop=name,1024x768 flag when running wine:
wine /desktop=name,1024x768 game.exe

A: So, it seems running Wine in a virtual desktop is the way to go. I had been avoiding doing this, because if I were to set the desktop to the resolution of the monitor I'd want to use it on, the virtual desktop's title bar, combined with Ubuntu's top/activity bar would cause a decent portion of the virtual desktop to be cut off at the bottom. Plus the dock would make things worse.
After fiddling around for a bit, the best solution I have come up with is as follows:

*

*Ensure hotkeys are set in gnome-control-center at Settings > Devices > Keyboard, for moving windows to a different monitor, and for entering full screen

*Start your desired program with Wine as per normal

*When the virtual desktop appears and takes focus, use your hotkeys to move the window to the desired monitor.

*Use your full screen hotkey to get the virtual desktop to use the entire monitor area

While it would have been ideal for software to open already full screen on the correct monitor, this has been a suitable solution for me, though technically, it's more of a workaround, than an actual solution.


text:
Q: Setting Global Variables in JS on Event Trigger - Google Maps API I'm using Google Maps API v3 and need to offset markers based on the current zoom level.
I have a global variable current_zoom_level, and an event listener for zoom in/out:
google.maps.event.addListener(map, 'zoom_changed', function() {
 current_zoom_level = map.getZoom();
 alert(current_zoom_level);
});
I've tried this bit in the initialization code and the code that calculates the offset.  The alert displays the correct current zoom level, but when I access it in build_loan_markers() (where I calculate offsets) current_zoom_level is undefined.
function build_loan_markers ()
{
        var offset;
 alert(current_zoom_level);
 if(!window.current_zoom_level){
  window.current_zoom_level = 1;
 }
 offset = 1/(window.current_zoom_level^2);
 alert('zoom: ' + current_zoom_level + ' offset: ' + offset);
        etc..
}
How can I globally set this variable?

A: To make a variable global, simply declare it outside any function definition.
var current_zoom_level = 0;

function something() {
   // Add your listener here
}

function build_loan_markers() {
  alert(current_zoom_level);
}

You shouldn't need to access your variable as window.current_zoom_level. It was unclear from your code which of the two alert(current_zoom_level)s was working, consider posting a link to a site that demonstrates the problem.


text:
Q: How do you version and sync your MySQL data model? What's the best way to save my MySQL data model and automatically apply changes to my development database server as they are made (or at least nightly)?
For example, today I'm working on my project and create this table in my database, and save the statement to SQL file to deploy to production later:
create table dog (
  uid int,
  name varchar(50)
);

And tomorrow, I decide I want to record the breed of each dog too.  So I change the SQL file to read:
create table dog (
  uid int,
  name varchar(50),
  breed varchar(30)
);

That script will work in production for the first release, but it won't help me update my development database because ERROR 1050 (42S01): Table 'dog' already exists.  Furthermore, it won't work in production if this change was made after the first release.  So I really need to ALTER the table now.
So now I have two concerns:

*

*Is this how I should be saving my
data model (a bunch of create
statements in a SQL file), and

*How
should I be applying changes like
this to my database?

My goal is to release changes accurately and enable continuous integration.  I use a tool called DDLSYNC do find and apply difference in an Oracle database, but I'm not sure what similar tools exist for MySQL.

A: At work, we developed a small script to manage our database versioning.  Every change to any table or set of data gets it's own SQL file.
The files are numbered sequentially.  We keep track of which update files have been run by storing that information in the database.  The script inserts a row with the filename when the file is about to be executed, and updates the row with a completion timestamp when the execution finishes.  This is wrapped inside a transaction.  (It's worth remembering that DDL commands in MySQL can not occur within a transaction.  Any attempt to perform DDL in a transaction causes an implicit commit.)
Because the SQL files are part of our source code repository, we can make running the update script part of the normal rollout process.  This makes keeping the database and the code in sync easy as pie.  Honestly, the hardest part is making sure another dev hasn't grabbed the next number in a pending commit.
We combine this update system with an (optional) nightly wipe of our dev database, replacing the contents with last night's live system backup.  After the backup is restored, the update gets run, with any pending update files getting run in the process.
The restoration occurs in such a way that only tables that were in the live database get overwritten.  Any update that adds a table therefore also has to be responsible for only adding it if it doesn't exist.  DROP TABLE IF EXISTS is handy.  Unfortunately not all databases support that, so the update system also allows for execution of scripts written in our language of choice, not just SQL.
All of this in about 150 lines of code.  It's as easy as reading a directory, comparing the contents to a table, and executing anything that hasn't already been executed, in a determined order.

A: There are standard tools for this in many frameworks: Rails has something called Migrations, something that's easily replicated in PHP or any similar language.


text:
Q: Trying to get vncserver running on solaris: Fatal server error: could not open default font 'fixed' I've looked at all the webpages and there are some good suggestions, but none has worked for me.
Solaris sparc box,
SunOS 5.10 Generic_120011-14 sun4u sparc SUNW,UltraAX-i2
The machine has openwin installed with symlinks from all of the usual X11 directories.
xfs is running and all the font directories are there, I ran mkfontdir and fc-cache and everything builds indexes all correctly, but no matter what I can't make it find the default font. (if that really is the problem)
I run as root, doesn't help.
Fatal server error:
could not open default font 'fixed'
Any suggestions?

A: The vncserver that's included in Solaris 10 4/08 (Update 5) and later should have the font path all setup correctly by default.
For other versions of vncserver/Xvnc:

*

*You can use xfs, but don't need to.
If you're using it, you would have
it set the Xvnc font path to
something like tcp/localhost:7100

*fc-cache & fontconfig aren't used by X servers to find fonts, only by
X clients, so they won't help

*the X11 font directories under Solaris 10 are in
/usr/openwin/lib/X11/fonts    with a
symlink under /usr/X11/lib/X11/fonts
The default X11 font path for the
Solaris 10 bundled Xvnc server is:
/usr/X11/lib/X11/fonts/TrueType/,/usr/X11/lib/X11/fonts/Type1/,/usr/X11/lib/X11/fonts/Type1/sun/,/usr/X11/lib/X11/fonts/F3bitmaps/,/usr/X11/lib/X11/fonts/misc/,/usr/X11/lib/X11/fonts/100dpi/,/usr/X11/lib/X11/fonts/75dpi/

For the X server to find "fixed" is a multi-step process, with things that
could break at each step, so you should check all of these:

*

*the font path needs to include the directory with the fixed font:    /usr/openwin/lib/X11/fonts/misc/ (font paths in X aren't recursive, so    you can't list just /usr/openwin/lib/X11/fonts and have it find all the subdirectories)

*/usr/openwin/lib/X11/fonts/misc/fonts.alias lists the alias converting the short name "fixed" to the full X11 font name:
fixed   "-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso8859-1"

*/usr/openwin/lib/X11/fonts/misc/fonts.dir lists the filename for the font with that full name:
7x13.pcf -misc-fixed-medium-r-normal--13-120-75-75-c-70-iso8859-1

*/usr/openwin/lib/X11/fonts/misc/7x13.pcf exists and is world readable

A: I had a similar problem to this myself once setting up vnc on a version of Linux.  It turned out that the scripts that started the Xwindows servers didn't have the correct path to the fonts.  Once I fixed that it worked just fine.
I don't know what version of vnc you are using but you might try editing the vncserver script to include the explicit paths to the fonts to see if that helps.  In the version I use (TightVNC on RHEL5) there is a portion of the script that sets up the exact command issued to start the vnc Xwindows system (Xvnc).  As part of this setup there is a line (commented out in my current version) that sets the font path with the -fp flag.  The code snippet in question looks like this:
# Now start the X VNC Server

$cmd = "Xvnc :$displayNumber";
$cmd .= " -desktop " . &quotedString($desktopName);
$cmd .= " -httpd $vncJavaFiles" if ($vncJavaFiles && ! $nohttpd);
$cmd .= " -auth $xauthorityFile";
$cmd .= " -geometry $geometry" if ($geometry);
$cmd .= " -depth $depth" if ($depth);
$cmd .= " -pixelformat $pixelformat" if ($pixelformat);
$cmd .= " -rfbwait 30000";
$cmd .= " -rfbauth $vncUserDir/passwd";
$cmd .= " -rfbport $vncPort";
$cmd .= " -pn";

# Add font path and color database stuff here, e.g.:
#
# $cmd .= " -fp /usr/lib/X11/fonts/misc/,/usr/lib/X11/fonts/75dpi/";
# $cmd .= " -co /usr/lib/X11/rgb";
#

The line to set the font path is in the commented out section at the end.  You might try finding the similar section in your start-up script and explicitly setting the paths to the fonts to see if that will at least get you past the fatal error.

A: On Solaris 10 x86_64 update 7 (05/09) I had a similar problem when installing as a VM on ESX. The following lines are able to correct the problem:

mkfontdir "/usr/X11/lib/X11/fonts/TrueType/"
mkfontdir "/usr/X11/lib/X11/fonts/Type1/"
mkfontdir "/usr/X11/lib/X11/fonts/Type1/sun/"
mkfontdir "/usr/X11/lib/X11/fonts/F3bitmaps/"
mkfontdir "/usr/X11/lib/X11/fonts/misc/"
mkfontdir "/usr/X11/lib/X11/fonts/100dpi/"
mkfontdir "/usr/X11/lib/X11/fonts/75dpi/"
echo -e 'fixed "-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso8859-1"' > /usr/openwin/lib/X11/fonts/misc/fonts.alias

A: PS: Meanwhile I found out that the installation ISO I had was corrupted (MD5 sum was not matching). There were some packages corrupt in the installation. After downloading another ISO the problems I had vanished.


text:
Q: How do I find which country has the lowest average time to finish a marathon? I have a data set with a column of countries and a column of time it took them to run a marathon. I want to find out which 5 countries completed it in the shortest time on average. I am new to R so only have basic knowledge. The column of time is in hours. eexample of the data: marathon$Countries is a column of the nationality of each runner, marathon$OverallHrs is the overall time it took to complete the marathon for each runner.
I have tried
tapply(marathon$OverallHrs, marathon$Country, mean)

It hasnt worked in the way I want it to

A: I am assuming that you are not referring to the trivial case where you don't have repeated countries for your "country" column. For a beginner in R, i would strongly encourage to start learning with the package "tidyverse".
Below is the solution, where you can have repeated countries for the column "Country"
library(tidyverse)

set.seed(123)
# Generate 10 Countries, each one 5 times
A = sample(rep(1:10,5))
# Generate 50 random timing from (5-20)
B = round(runif(50)*15 + 5)

#Create a dataframe with columns (Country, Timing), rows = 50
df = data.frame("Country" = paste0("Country",A),
                "Timing" = B)

#Dataframe will look like this
# Country Timing
# 1  Country5     15
# 2  Country4     17
# 3  Country4      5
# 4  Country3     12
# 5  Country5     16

# Calculate average marathon timing
df_mean <- df %>%
  group_by(Country) %>% #Group
  summarise(Mean_Timing = mean(Timing), .groups = 'drop') %>% #Calculate Mean_Timing
  arrange(Mean_Timing) # Arrange by fastest timing first

#Dataframe = df_mean
# A tibble: 10 x 2
# Country   Mean_Timing
# <chr>           <dbl>
# 1 Country9         10.6
# 2 Country1         11.4
# 3 Country3         11.4
# 4 Country4         11.4
# 5 Country2         12.2
# 6 Country10        12.6
# 7 Country8         13.2
# 8 Country7         13.6
# 9 Country5         15
# 10 Country6         15.2

#To get the first 5 country, would just be
df_mean$Country[1:5]
# "Country9" "Country1" "Country3" "Country4" "Country2"

There is always the aggregate function in R for calculating mean per group. Lesser code, but I still prefer the tidyverse method as it is intuitive to use after a while and can be tweaked slightly to solve any dataframe question.
Anyway, here is the solution using aggregate.
df_mean2 <- aggregate(df[, 2], list(df$Country), mean) # Calculate Mean
df_mean2[order(df_mean2$x), ] # Sort by ascending
     Group.1    x
10  Country9 10.6
1   Country1 11.4
4   Country3 11.4
5   Country4 11.4
3   Country2 12.2
2  Country10 12.6
9   Country8 13.2
8   Country7 13.6
6   Country5 15.0
7   Country6 15.2


text:
Q: nfl_frame = pd.read_clipboard() Panda system crash I am running windows 10, python 3, every time i run this command
nfl_frame = pd.read_clipboard(), the whole system crash

A: It might be an issue with Python 3. I tried it on python 2 and luckily it works. Also I came across this. Supposedly it's a bug.


text:
Q: Switching String or Multiple IF Statements I need to a perform an action based on the value of a string. I think that if I use a switch statement it will be slower than using multiple ifs and strcmp function. Thoughts?
Method 1:
switch ( $string ){
   case 'Hello': //do stuff
       break;
   case 'Howdy': //do stuff
       break;
}

Method 2:
if ( strcmp($string, 'Hello') == 0 ) // do stuff
if ( strcmp($string, 'Howdy') == 0 ) // do stuff

Which one will be most effective?


text:
Q: How to create an Object in a specific Entity Group with JPA? (Google AppEngine Java) I want to use transactions in GAE-J with JPA.
Without JPA it should be:
Entity child= new Entity("Child", "ParentKey");

but how to do it with JPA?
@Entity
public class Parent{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key id;
    private String text;
}

@Entity
public class Child{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key id;
    private Parent parent;
    private String text;
}

trying...
Parent parent = new Parent();
em.persist(parent);
em.refresh(parent);

Child child = new Child();
child.setParent(parent);
em.persist(child);

This doesn't work:
org.datanucleus.store.appengine.DatastoreRelationFieldManager$ChildWithoutParentException:
Detected attempt to establish Child(130007) as the parent of Parent(132001) but the entity identified by Child(132001) has already been persisted without a parent.  A parent cannot be established or changed once an object has been persisted.

That sounds a bit back to front...
Am I a blockhead? Or is there an easy way?
Thanks!

A: kay... just a little error in my first attempt.
This should work:
@Entity
public class Parent{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key id;
    private String text;
    @OneToMany(targetEntity=Child.class, mappedBy="parent", fetch=FetchType.LAZY)
    private Set<Child> children = new HashSet<Child>();
}

@Entity
public class Child{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key id;
    @ManyToOne(fetch=FetchType.LAZY, targetEntity=Parent.class)
    private Parent parent;
    private String text;
}


text:
Q: virtualenvwrapper: when does `workon` changes to the project directory? I use virtualenvwrapper to manage my environments. I create my projects with the -a <path-to-project> argument and PROJECT_HOME is not set, because my projects don't share a common path. VIRTUALENVWRAPPER_WORKON_CD is set to 1 though and a valid .project file exist in the virtual environments.
When I use the workon command, it only changes the working directory to the path of the project sometimes, while at other times, the directory stays the same, despite the environment being activated correctly.
So when and how does the directory change trough workon happens? And are there things I have to do / set for it to work?

A: I have a small solution albeit kinda hacky

*

*Go to the folder which this variable, $VIRTUALENVWRAPPER_HOOK_DIR is pointing to. You might need to be in a virtual environment to see that variable, but usually it has the same value as $WORKON_HOME

*In this folder you should see a script called postactivate

*Add this as the last line in the script: cdproject
Now what this does is that every time you type workon <project_name>, this script will run after the virtual environment is activated, and the directory you were working in will switch to the directory for that project.
For more life-cycle hooks, see here!
NOTE
I didn't fully test this to make sure it works no matter how the project was created, but to make sure it works, I recommend creating your virtual environments with mkvirtualenv -a <env_name> or if the environment exists and with the environment activated, go to it's project folder and run setvirtualenvproject. Now the next time you try to do workon ..., the script will kick in and take you to your project folder
Addendum
Since this is a shell script, you can do some fancy tweaks than just that one line. For example you might want to only do something if the activated project has a certain pattern, or part of a certain group of projects. Checkout some of the $VIRTUALENVWRAPPER_* variables to see what other useful information you can get

A: setvirtualenvproject is now called setprojectdir. To use the current directory write setprojectdir .


text:
Q: Ordered Integral solutions
If $a\times b\times c = 12 \times \gcd(a,b,c)$, how many ordered triplets $(a,b,c)$ are possible?

Assuming $a=hx,b=hy,c=hz$ where $h=\gcd(a,b,c)$ .I am getting $h^2xyz=12$.
Solving this I am getting $12$ ordered integral solutions, but the answer given is $21$.
Please can someone help me find out where am I going wrong?
EDIT : The integral solutions I am getting are(1,4,3) arranged by 3!= 6 ways.And (1,2,6) arranged by 3!= 6 ways.
So total = 6+6 =12 solutions.

A: I'm getting the following solutions by guess and check and rearranging triples with the same numbers.
$$(2,2,6) \text{ yields 3 solutions}$$
$$(1,1,12) \text{ yields 3 solutions}$$
$$(1,2,6) \text{ yields 6 solutions}$$
$$(1,3,4) \text{ yields 6 solutions}$$
$$(2,2,3) \text{ yields 3 solutions}$$
That's $21$ solutions in all.
What you forgot is all of the solutions with repeat numbers. Remember that those still count.


text:
Q: Neo4j algo.shortestPath with only certain label of relationship I am new to Neo4j and I am trying to figure out how to use a few basic path finding algorithms. Essentially, I have a collection of notes labelled LogisticalUnit, representing companies or locations that can ship goods to other places. Two such units can have a relationship SHIPS_TO with a property cost. Attempting to find a path with minimal cost to go from node A to B gives me a promising result using algo.shortestPath.stream:
match (startNode :LogisticalUnit {id: 2}), (endNode :LogisticalUnit {id: 5})
call algo.shortestPath.stream(startNode, endNode, 'cost', {direction: 'OUTGOING', nodeQuery: 'LogisticalUnit', relationshipQuery: 'SHIPS_TO'})
yield nodeId, cost
return *;

However, it turns out that if I have another relationship such as RECOMMENDS, and it has the cost property, it is considered as well. It seems the relationshipQuery config does not actually work. As a matter of fact, replacing the config with relationshipQuery: 'FOOBAR', while no such relationship even exists in my database, will still return the same result!
The nodeQuery property behaves as expected and if I change it to another label it will correctly dismiss the results.
Any idea where I'm going wrong here? Thanks a lot in advance.


text:
Q: What should I do with my old memory? I just replaced the 2 1GB DIMMs in my MacBook Pro with 2 x 2GB DIMMs. What can I do with the old memory?

A: If you don't think your gonna use it again, why not recycle it?  Or you could use the sticks as a really geeky bookmark.

A: Sell them? I'm sure you could make at least a little cash off them on eBay or Craigslist.

A: I am pretty sure you could simply sell it on. Especially since it's unlikely your going to reuse it as it's come out of your Mac. Is anyone else you know about to buy a similar model? Since 2g is the default maybe not..

A: You can sell it, or - as tj111 noted - recycle it. Note: in EU countries computer memory is considered dangerous waste, and by law should be properly disposed by appropriate recycling company. Ask your local computer store, they will help you.
On disposing:
http://ec.europa.eu/environment/waste/weee/index_en.htm

A: Give it to a local school.


text:
Q: forms con pasos Tengo un formulario, dividido en fielsets, al iniciar la pagina solo se mostrara el primero oculatando el otro fielset, y que al presionar el boton de siguiente
cambie automaticamente al otro fielset con ayuda de javascript o jquery, como puedo lograr el ocultamiento y la transicion al sigueinte,
al final tengo mi archivo de js llamado "cambios"
gracias

        <form>
            <fieldset>

opciones

                                <select class="form-control dropdown-toggle">
                                    <option>Si</option>
                                    <option>No</option>
                                </select>

TITULO

                             EJEMPLO DE TEXTO

TITULO

                                EJEMPLO DE TEXTO

                <button  type="button" class="btn btn-success mr-2" onclick="siguiente()">Siguiente</button>
                <button  type="button" class="btn btn-success mr-2" onclick="anterior()">Anterior</button>

            </fieldset>

             <fieldset>

opciones

                                <select class="form-control dropdown-toggle">
                                    <option>Si</option>
                                    <option>No</option>
                                </select>

                <button  type="button" class="btn btn-success mr-2" onclick="siguiente()">Siguiente</button>
                <button  type="button" class="btn btn-success mr-2" onclick="anterior()">Anterior</button>

            </fieldset>

        </form>

A: Veamos si solo tienes dos fieldset pues la cosa es fácil: cambiarle el display. Estas funciones ocultan uno y muestran el otro.
El html ponle un id="filed1" al primer fieldset y un id="field2" al segundo fieldset, esto te va a servir para identificarlos en los scripts.

function siguiente()
{
document.getElementById("field2").style.display = "block";
document.getElementById("field1").style.display = "none";
}

function anterior()
{
document.getElementById("field1").style.display = "block";
document.getElementById("field2").style.display = "none";
}

Si hay más bloques la solución es similar, pero hay que poner todos en oculto, excepto uno que se pondrá en visible. De alguna manera tienes que identificar al visible (con un class o con un id...).


text:
Q: Disable scrolling parent page when playing a game in iframe I have a very simply game page, where I have games in iframes. I want to disable scrolling on the main page when I am playing a game in iframe. I have tried overflow:hidden but it disables totally scrolling, which is useless.
When the page is longer than the screen pressing the down arrow scrolls the page down, and makes the game impossible to play.
Is there a basic way to disable scrolling during playing?
Game input listener:
/*
 This simply library keeps the state of the currently
 pressed keys by using keydown and keyup event handlers.
 */
(function() {
    var pressedKeys = {};
    function setKey(event, status) {
        var code = event.keyCode;
        var key;
        switch(code) {
        case 32:
            key = 'SPACE'; break;
        case 37:
            key = 'LEFT'; break;
        case 38:
            key = 'UP'; break;
        case 39:
            key = 'RIGHT'; break;
        case 40:
            key = 'DOWN'; break;
        default:
            // Convert ASCII codes to letters
            key = String.fromCharCode(code);
        }
        pressedKeys[key] = status;
    }
    document.addEventListener('keydown', function(e) {
        setKey(e, true);
        e.stoppreventDefault();
    });

Thank you for your help!

A: Consider using stopPropagation in your down-arrow event handler to stop the event from reaching the higher level container (i.e. window).
For example, in the keydown handler of the game:
function(e) {
  if(e.keyCode == 40 /* Down arrow */) {
    // Do your game stuff here.
    e.stopPropagation();
  }
}

In case you have higher level elements that require the down-arrow event (and you can't modify those functions to stopPropagation) you can also use preventDefault to prevent the default action (scrolling):
function(e) {
  if(e.keyCode == 40 /* Down arrow */) {
    // Do your game stuff here.
    e.preventDefault();
  }
}

Alternatively, if you don't want to or can't modify the game code, you can also swallow all down-arrow events at the window level.
window.addEventListener("keydown", function(e) {
  if(e.keyCode == 40 /* Down arrow */) {
    e.preventDefault(); // prevents the "default" action from happening, in this case, scrolling down.
  }
}, false);

Note that setting overflow:hidden on the main page has the (possibly unlikely) side effect where if your game frame is below the first screen height (perhaps due to headers, banner ads, the user having 50 toolbars installed, using a smaller window, or whatever else that may prevent the full game window from being shown), then it will be cut off without a way for users to scroll down.

A: The following snippet uses javascript to set the css overflow hide/auto when clicking in a button.
UPDATE: Instead of a button, you can set these actions to be triggered on iframe focus.
Example:

function offf(){
document.getElementsByTagName("body")[0].style.overflowY = "hidden";
}

function onn(){
document.getElementsByTagName("body")[0].style.overflowY = "auto";
}
body {
  width: 100%;
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
  margin: 0px;
}

div {
  background:honeydew;
  width:100%;
  height:150%;
}

button {
  border: 2px solid black;
}

#a {
  position:fixed;
  left: 10px;
  top: 10px;
  background: gold;
}

#b {
  left: 140px;
  top: 10px;
  position:fixed;
  background: hotpink;
}

<button id=a onClick="offf()">PLAY (hide scroll)</button><button id=b onClick="onn()">STOP (show scroll)</button>


text:
Q: Symfony date interval with multiple formats I have a Date interval of an entity called worker with a period of time see the next functions:
// Get date of retirement
public function getRetireYear()
{
    $this->retireYear = $this->getBirthDay()->add(new \DateInterval('P60Y'));
    return $this->retireYear;
}

// Get time left for retirement
public function getTimeToRetirement()
{
    // Date of today
    $today = new \DateTime('today');

    // Calculate date diff between today and retirement day.
    $this->timeToRetirement = $today->diff($this->retireYear);

    // Return the time to retirement time formated
    return $this->formatTimeInterval(
        $this->timeToRetirement,
        '%r%Y years, %m months, %d days'
    );
}

//Format the dateInterval numbers as string
public function formatTimeInterval($aDateDif, $format)
{
    return $aDateDif->format($format);
}

The only value that is stored in the database here is $this->getBirthDay(), then getRetireYear generates the year of retirement of a worker (birthDay + 60 years).
getTimeToRetirement gives the time left to retire someone and formatTimeInterval($,$) is used to format the date Interval.
Now I need to be able to use this dateInterval in different formats, for instance sometimes I just need the year to compare as integer with other values in the views, so I need this year as a single value to be accessible on the views.
I have tried a few things but I do not know the correct way to do it, so I have not get the nicer conclusion to this issue.
Also sometimes I need the month and the day for other tasks, not only the year, this values should be accessible on the views because in the controller I just search for an ArrayColletion of objects and pass it to the view, otherwise I have to go up and dow the array collection.
For more information about the problem you can read this thread

A: I think you would be better off having the getTimeToRetirement method return the DateInterval and move the formatTimeInterval method out of the entity altogether as it is more relevant to DateInterval formatting than to your worker. You could then have your DateInterval formatted as you want when you need it.
Something along those lines.
In your worker entity class:
// Get date of retirement
public function getRetireYear()
{
    $this->retireYear = $this->getBirthDay()->add(new \DateInterval('P60Y'));
    return $this->retireYear;
}

// Get time left for retirement
public function getTimeToRetirement()
{
    // Date of today
    $today = new \DateTime('today');

    // Calculate date diff between today and retirement day.
    $this->timeToRetirement = $today->diff($this->retireYear);

    // Return the time to retirement time as a DateInterval
    return $this->timeToRetirement;
}

You can then use the date Twig filter to format the DateInterval in the view. See http://twig.sensiolabs.org/doc/filters/date.html
If you need something more specific or encapsulated, you could also create a Twig extension for that. See http://symfony.com/doc/master/cookbook/templating/twig_extension.html

A: this is what I have done, but may be is not the most practical way:
    public function getYearsLeft(){
    $aux = $this->birthDay->add(new \DateInterval('P60Y'));
    //date today
    $today = new \DateTime('today');
    // Calculate date diff between today and retirement day.
    $this->yearsLeft = $today->diff($aux);
    $aux2 = $this->formatTimeInterval($this->yearsLeft, '%r%Y');
    $this->birthDay->sub(new \DateInterval('P60Y'));
    return $aux2;
}
public function getMonthsLetf(){
    $aux = $this->birthDay->add(new \DateInterval('P60Y'));
    //date today
    $today = new \DateTime('today');
    // Calculate date diff between today and retirement day.
    $this->monthsLetf = $today->diff($aux);
    //$this->yearsLeft = $aDateDif; //('%r%Y');
    $aux2 = $this->formatTimeInterval($this->monthsLetf, '%m');
    $this->birthDay->sub(new \DateInterval('P60Y'));
    return $aux2;
}

I will convert this two functions in 3 functions simpler and more reusable, and maybe create the helper if I need it from outside this environment.In the Controller I access the config file:
         $redTime = $this->container->getParameter('time_red');
         $orangeTime = $this->container->getParameter('time_orange');

Of course no I have to pass the list of workers to the view and also the config vars. And now in the view I can just access the variables as follows:
                {% for aWorker in aWorkerList %}
            {% if aWorker.retireYear is defined %}
              {% if colorOrange > aWorker.yearsLeft %}

                  {% if colorRed > aWorker.monthsLetf %}

                        {% elseif 0 > aWorker.yearsLeft %}

                  {% endif %}

              {% endif %}
                        Edit
                            Delete
                        {{aWorker.omang}}
                        {{aWorker.workerTitle}}
                        {{aWorker.workerName}}
                        {{aWorker.workerSurname}}
                        {{aWorker.birthDay|date('Y-m-d')}}
                        {{aWorker.dateOfEmployment|date('Y-m-d')}}
                        {{aWorker.retireYear|date('Y-m-d')}}
                        {{aWorker.timeToRetirement}}
                        {{aWorker.fileNumber}}

            {% endif %}
            {% endfor %}

It works fine... with independence of the philosophy violations!?


text:
Q: Auto select items-per-page (a drop down) using a Greasemonkey-like script If you take a look at this page, there's a drop down to show results per page: it can be 10, 20 or 50.
I would like a Greasemonkey-like script to simulate selecting 50 per page.
For ease of reference some of the HTML from the page is here:
<select><option value="10">10</option><option value="20">20</option><option value="50">50</option></select> per page

How can I achieve this, please?
Edits
URL updated with more than 20 items
This is for Greasekit on Fluid.app (which is very old, but I am restricted to using it). Brock reliably tells me it is very old and no longer updated. (I don't think I can even use jQuery)

A: Since that select is driven by jQuery, you can use jQuery to change it and trigger all the necessary javascript.
But your Greasemonkey script must use injection or @grant none mode, because you need to trigger the page's javascript functions.
A complete script for that sample page would be like:
// ==UserScript==
// @name        _Amazon-like store, auto select 50 items per page
// @include     https://dl.dropboxusercontent.com/u/5546881/*
// @grant       none
// ==/UserScript==

//-- $ not defined. Use jQuery
jQuery('#v_pagination_long select').val (50).trigger ('change');

Update:
Since the OP is not really using Greasemonkey, or a modern equivalent like Tampermonkey, @grant none is not supported.
Here is the same script using script injection, that will work on almost any browser+userscript-engine combo:
// ==UserScript==
// @name        _Amazon-like store, auto select 50 items per page
// @include     https://dl.dropboxusercontent.com/u/5546881/*
// @grant       GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
function GM_main () {
    jQuery('#v_pagination_long select').val (50).trigger ('change');
}

addJS_Node (null, null, GM_main);

function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}

Important:

*

*That sample page shows 9 items max, so it's impossible to be 100% sure that the script is doing everything needed. With the OP's new sample page, verified that the script works on FF+GM and Chrome+TM.

*The <select> is wrapped in a div with the id: v_pagination_long. Use that to help get the correct control.

*That page uses various mouse events (not click), so it may be that more stateful approaches are needed (Can't tell for sure, see item 1). Not needed in this case for the demo page. See Choosing and activating the right controls on an AJAX-driven site for other pages.


text:
Q: Unable to SSH into switch: Key exchange or Algorithm Negotiation failed on hold Referred here by Network Engineering Stack Exchange.
I am having a D-link 1510-28 switch to which I am trying to SSH into.
Upon trying the command:
srajan@srajan-Virtual-Machine:~$ ssh admin@10.82.64.5
Unable to negotiate with 10.82.64.5 port 22: no matching cipher found. Their offer: 3des-cbc,blowfish-cbc,twofish-cbc,twofish256-cbc,twofish192-cbc,twofish128-cbc,aes256-cbc,aes192-cbc,aes128-cbc,arcfour,cast128-cbc

I also tried upgrading it to the latest firmware available, but to no avail.
After googling, I tried using this
srajan@srajan-Virtual-Machine:ssh -c aes256-cbc admin@10.82.64.5
Received disconnect from 10.82.64.5 port 22:3: Disconnected: Key exchange or Algorithm Negotiation failed
Disconnected from 10.82.64.5 port 22

As suggested on NE Stack Exchange comments, I also tried this but received the same error.
C:\Users\xyz>ssh -c aes256-cbc -oKexAlgorithms=+diffie-hellman-group1-sha1 admin@10.82.64.5
Received disconnect from 10.82.64.5 port 22:3: Disconnected: Key exchange or Algorithm Negotiation failed
Disconnected from 10.82.64.5 port 22

I have attached the full debug log here as this site considers it as spam.
Full Debug log
EDIT: The second command verbose log can be found here.
Please help.

A: I was able to solve it by changing the RSA key length on the switch from 768 bit to 2048 bit Host key. The error stopped showing up after this!