text:
Q: Creating a queryset which represents a union of querysets Let's say I have the following models:
class House(models.Model):
    address = models.CharField(max_length=255)

class Person(models.Model):
    name = models.CharField(max_length=50)
    home = models.ForeignKey(House, null=True, related_name='tenants')

class Car(models.Model):
    make = models.CharField(max_length=50)
    owner = models.ForeignKey(Person)

Let's say I have a need (strange one, albeit) to get:

*

*list of people who live in a house or are named 'John'

*list of cars of the above people

I would like to have two functions:

*

*get_tenants_or_johns(house)

*get_cars_of_tenants_or_johns(house)
I could define them as:
from django.db.models.query_utils import Q

def get_cars_of_tenants_or_johns(house):
    is_john = Q(owner__in=Person.objects.filter(name='John'))
    is_tenant = Q(owner__in=house.tenants.all())
    return Car.filter(is_john | is_tenant)

def get_tenants_or_johns(house):
    johns = Person.objects.filter(name='John')
    tenants = house.tenants.all()
    return set(johns) | set(tenants)

The problem is that the logic is repeated in the above examples. If I could get get_tenants_or_johns(house) to return a queryset I could define get_cars_of_tenants_or_johns(house) as:
def get_cars_of_tenants_or_johns(house):
    return Car.objects.filter(owner__in=get_tenants_or_johns(house))

In order to do that, get_tenants_or_johns(house) would need to return a union of querysets, without turning them into other collections.
I cannot figure out how to implement get_tenants_or_johns(house) so that it would return a  queryset containing a SQL UNION. Is there a way to do that? If not, is there an alternate way to achieve what I am trying to do?

A: The | operator on two querysets will return a new queryset representing a union.
The function will need to change to (got rid of set() wrappers):
def get_tenants_or_johns(house):
    johns = Person.objects.filter(name='John')
    tenants = house.tenants.all()
    return johns | tenants

and everything will work exactly like needed.

A: You mention users who live in a house, but have no mention of your User model.
I think you really need to take a long look at the structure of your application - there are probably much easier ways to accomplish your goal.
But to answer your question let's set up three helper functions. Since, as I mentioned above, you haven't outlined what you want to do with the User class - I've assumed that the house that will be passed to these functions is an address:
helpers.py
def get_johns(house):
    is_john = Person.objects.filter(name='John')
    return is_john

def get_cars_of_tenants(house):
    cars = Car.objects.filter(owner__home__address=house)
    return cars

def get_tenants(house):
    tenants = Person.objects.filter(home__address=house)
    return tenants

Now you could create a view for each of your combination queries:
views.py:
import helpers.py
from itertools import chain

def get_cars_of_tenants_or_johns(request, house):
    results = list(chain(get_cars_of_tenants(house), get_johns(house)))
    return render_to_response('cars_or_johns.html', {"results": results,})

def get_tenants_or_johns(request, house):
    results = list(chain(get_tenants(house), get_johns(house)))
    return render_to_response('tenants_or_johns.html', {"results": results,})

And this can go on for all of the various combinations. What is returned is results which is a list of all of the matches that you can iterate over.


text:
Q: Making my for loop executable I've created this working for loop in Python:
a = 'word'

for i in range(len(a)):

 print a[i:] + a[:i], (a[i:] + a[:i])[::-1]

and I need to make it executable from the command line and also have it be able to take in new arguments.
I'm a little hazy on how to do this. I know that you need to use
if __name__ == '__main__':

somehow...And that I need to use sys.argv
If anyone could explain how to do this, and the format for making any script executable from the command line, I would really appreciate it.

A: You can just simply write
import sys
a = sys.argv[1]
etc..

And then run:
python yourcode.py argument

The
if __name__=='__main__':

is not required, but you can also put your whole code under that. It's purpose is to specify code which gets executed only if you run your program like "python yourcode.py" and to prevent the code under that if statement from getting executed if you write "import yourcode" in another .py file.

A: Depending on how flexible you want to have your Python script, I would structure the script like so:
def get_args():
    # logic for parsing arguments here
    # return e.g. a dictionary

def your_method(arg1=None,arg2=...):
    # further logic

if __name__ == "__main__":
    args = get_args()
    your_method(**args)

There are various modules to parse command line arguments. Have a look at argparse (easier) and optparse.
If you just need a simple way to access the command line arguments, you can go with sys.argv.
With this separation you are also able to import your function into other code.
Example:
import sys

def get_args():
    word = sys.argv[1] if (len(sys.argv) > 1) else ''
    return {"word": word}

def your_method(word=''):
    for i in range(len(word)):
        print word[i:] + word[:i], (word[i:] + word[:i])[::-1]

if __name__ == "__main__":
    args = get_args()
    your_method(**args)

and run it with
python yourscript.py someword

See also:

*

*How can I process command line arguments in Python?

*What does if __name__=="__main__": do?

A: import sys
if __name__ == '__main__':
    a = sys.argv[1] #sys.argv[0] is your file name, and [1] is the next argument
    for i in range(len(a)):
        print a[i:] + a[:i], (a[i:] + a[:i])[::-1]

Then you simply change to the directory with the file, and call it like:
python file.py wordHere

On the command line.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Build splitter.pyx (and splitter.pxd, from tree folder) using Cython on Sklearn Its probably a simple question, but I'm having some trouble on building the _splitter.pyx into _splitter.so (so I can try some changes I made). Right now I'm trying to build the original file with the command:

cython -a _splitter.pyx

And it generates the following error:

Error compiling Cython file:
...
                                           self.index_to_samples,
                                           self.feature_values,
                                           end_negative, start_positive)
cdef int compare_SIZE_t(const void* a, const void* b) nogil:
                                 ^
_splitter.pyx:1008:34: Expected ')', found '*'

I tried some changes like:

cython -3 _splitter.pyx

or

cython -a _splitter.pyx _splitter.pxd

But it only generated more errors. Am I doing something wrong?
When its fixed, I plan to use the command:

gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.7 -o _splitter.so _splitter.c

Is it the correct approach?
Thanks a lot for the help
EDIT:
Upgraded my Cython to 0.24 version. Now I get the following error in several lines:

Error compiling Cython file:
...
                     features[f_i], features[f_j] = features[f_j], features[f_i]
# Draw a random threshold
  current.threshold = rand_uniform(min_feature_value,
  max_feature_value,
  random_state)
^
_splitter.pyx:1547:65: Converting to Python object not allowed without gil

A: Try upgrading your Cython installation. Old versions (< 0.18) do not support const keyword.
See how do I use const

Answer: Since Cython 0.18, you can just use it in your code and in
  your declarations.
Earlier versions of Cython did not support const directly and required
  the following hack to compile it into the C source code:


text:
Q: Getting an error: 'UIAlertView' is deprecated: first deprecated in iOS 9.0 - UIAlertView is deprecated I'm developing a mobile app with Flutter. I realized  the app in Android but I'm stuck with iOS. I have this error message that I don't know how to fix.
This error appears with the plugin Geolocator.
- (void)showCamera {
  @synchronized(self) {
    if (_imagePickerController.beingPresented) {
      return;
    }
  }
  // Camera is not available on simulators
  if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] &&
      [UIImagePickerController isCameraDeviceAvailable:_device]) {
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    _imagePickerController.cameraDevice = _device;
    [[self viewControllerWithWindow:nil] presentViewController:_imagePickerController
                                                      animated:YES
                                                    completion:nil];
  } else {
    [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil)
                                message:NSLocalizedString(@"Camera not available.", nil)
                               delegate:nil
                      cancelButtonTitle:NSLocalizedString(@"OK", nil)
                      otherButtonTitles:nil] show];

    self.result(nil);
    self.result = nil;
    _arguments = nil;
  }
}

So the error is:

'UIAlertView' is deprecated: first deprecated in iOS 9.0 - UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead'


text:
Q: Devise: Some users on iOS keeps getting signed out, when they leave the browser I run a pretty simple rails 5.1 app with turbolinks where I use devise 4.4 for authentication. I have setup rememberable for devise, and it works well for most of my users. But for some with (iOS only so far, and not all) the remember me functionality does not work. After they have signed in and correctly checked the "remember me" checkbox, they get signed out as soon as they have left the browser (e.g. switched to another app than safari) for a couple of minutes.
The key files looks as follows:
user.rb:
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

devise.rb:
Devise.setup do |config|
  config.mailer_sender = 'webmaster@example.com'
  require 'devise/orm/active_record'
  config.case_insensitive_keys = [:email]
  config.strip_whitespace_keys = [:email]
  config.skip_session_storage = [:http_auth]
  config.stretches = Rails.env.test? ? 1 : 11
  config.reconfirmable = true
  config.remember_for = 1.year
  config.expire_all_remember_me_on_sign_out = true
  config.extend_remember_period = true
  config.password_length = 6..128
  config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
  config.timeout_in = 2.weeks
  config.reset_password_within = 6.hours
  config.sign_out_via = :get
end

sessions/new.slim:
h2
  | Log in
= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f|
  .field
    = f.input :email, autofocus: true, type: "email"
  .field
    = f.input :password, autocomplete: "off", type: 'passsword'
  - if devise_mapping.rememberable?
    .field
      = f.input :remember_me, as: :boolean
  .actions
    = f.submit "Log in", class: 'btn btn-primary'
br
= render "devise/shared/links"

I have no idea why this happens, what could cause it and how to debug it?

A: Okay, I think I have found out what goes wrong. Some of my iOS users had bookmarked my app on their homescreen. More specifically they had bookmarked the login screen. So whenever they opened up the app through the bookmark, it would try to authorise them, and eventually log them out.


text:
Q: Passing a class into a React component so that it can create new instances of said class? I have a component which renders a data structure. I am trying to create an editor for that structure and want to use the same renderer, but with certain sub-components overridden. The renderer has some data that I'd like to pass into the sub-component so I thought it might be best to use a passed class which the renderer would be able to call and include the data as props. Something roughly like:
class Editor extends React.Component{
    render(){
        return <Renderer overrideClass={OverridenComponent}/>;
    }
}
class Renderer extends React.Component{
    render(){
        return <this.props.overrideClass importantData="TEST"/>;
    }
}
class OverriddenComponent extends React.Component{
    render(){
        return
{this.props.importantData}
;
    }
}

I would expect that creating an <Editor/> would result in
TEST
 in the DOM, but instead I am getting what is equivalent to <overridencomponent></overridencomponent>, specifically non-capitalized and with no content.
Is this sort of behavior supported in some way? Is there a better way to accomplish this sort of overridable content while still allowing the Renderer class to pass data to the overridden version?

A: JSX only renders components which names are Capitalized. Therefore you should save the override class into a variable that is Capitalized.
Try:
class Editor extends React.Component{
    render(){
        return <Renderer overrideClass={OverridenComponent}/>;
    }
}
class Renderer extends React.Component{
    render(){
        const Component = this.props.overrideClass
        return <Component importantData="TEST"/>;
    }
}
class OverriddenComponent extends React.Component{
    render(){
        return
{this.props.importantData}
;
    }
}

A: In addition to the marked answer above, I found that passing in a callback function which takes the props and returns the class instance to be effective as well. It looked like:
class Editor extends React.Component{
    render(){
        return <Renderer overrideClass={(importantData) =>
            <OverridenComponent importantData={importantData}/>}
        />;
    }
}
class Renderer extends React.Component{
    render(){
        return this.props.overrideClass("TEST");
    }
}
class OverriddenComponent extends React.Component{
    render(){
        return
{this.props.importantData}
;
    }
}

I'm not sure exactly which method is better, but his answer was closer to what I was actually asking for as far as passing a class. I suspect that his way is more flexible too.


text:
Q: Save/Write encrypted Bytes from Cipher to a file I am currently trying to encrypt and decrypt a String with Cipher. The problem i ran into is that I am trying to save the encrypted bytes to a file and after that decrypt them again. I am currently trying to do this with BufferedReader and BufferedWriter. The problem is I dont get the same Byte array I saved. Any recommendations on how to write/read the bytes in a working way? I would already be happy if you could post a tutorial which includes saving the encrypted bytes to a file (and loading it again)

A:
I am currently trying to do this with BufferedReader and BufferedWriter.

Why? That's the problem right there. These classes are for character data. Use streams.


text:
Q: Custom PC won't boot Windows 7 DVD but does with Windows Vista I ordered a custom-built PC (assembled by the store). This is the setup:

*

*Motherboard: Asrock A75 PRO4-M

*DVD drive: LG GH24NS90

*SSD: Samsung 830 series 128 GB

*DDR3 SDRAM: 2× Corsair XMS3 CMX4GX3M1A1600C9 (2× 4 GB)

*APU (CPU+GPU): AMD A8-3850 Boxed

I got an installation DVD for Windows 7 Professional x64 English (including SP1), but it doesn't work. I then got a new one from the store and it doesn't work either. However they work on another PC, so the DVDs aren't bad.
I tried an old installation DVD for Windows Vista. Both 32-bit and 64-bit work. So the boot order and such are right and working on the new PC.
Is there something I'm missing here? Any ideas on how to make it work?

A: As per your comments, as the BIOS see's the DVD drive but the DVD won't run (despite running on other machines) it suggests the DVD drive's optic lens may be faulty, or may be it doesn't spin properly. Either way, as it's new, get a new DVD drive.


text:
Q: Linqpad performance vs Sql Management Studio I have a Linq query I run in Linqpad against EF5, and it runs about 10 sec.  When I copy the generated SQL for that statement into SMS, it runs in less than 2 sec.
Obviously, EF adds more processing overhead than a direct SQL and LinqPad is running in my computer, not a server.  So I expect it to be a bit slower.
But is there some way I can trace the Linqpad and EF execution steps of the query so I can identify the bottleneck(s)?
Thanks!

A: You can use a trial version of Ants Profiler and move linqpad code to some test console application.
Your SQL query is faster than LINQ because LINQ query generation is a expensive procedure. To have a fair comparison, try to compile the LINQ query and compare a 2nd run with pure SQL. LINQ would still be slower (LINQ does much more a than just execute the query) but the difference should be way smaller.


text:
Q: Linear Graham scan for convex hull of simple polygon failing Supposedly, the Graham scan algorithm should work to find the convex hull of a simple polygon in linear time, without the nlogn sorting step being necessary (since the vertices f a simple polygon are effectively already sorted). And I have an implementation of the Graham scan which seems to work fine:
function ccw(a: Vertex, b: Vertex, c: Vertex) {
    return (b.y - a.y)*(c.x - a.x) - (b.x - a.x)*(c.y - a.y);
}

// Graham Scan Convex Hull Algorithm
// This is destructive
export function convexHull(points: Vertex[]) {
    const n = points.length;
    if (n <= 3) return points;

    // Assume the first point is bottom-left-most
    const p0 = points[0];

    // Sort by angle
    points.sort((a, b) => {
        const c = ccw(p0, a, b);
        return c === 0 ? a.x - b.x : c;
    });

    // Keep points in the result if they "turn left"
    let len = 1;
    for (let i = 1; i < n; i++) {
        let b = points[len-1];
        let c = points[i];
        //if (b.x === c.x && b.y === c.y) { continue; } // identical points are already filtered out
        if (len >= 2) {
            let a = points[len-2];
            while (ccw(a, b, c) >= 0) {
                len--;
                if (len < 2) { break; }
                b = a;
                a = points[len-2];
            }
        }
        points[len++] = c;
    }
    points.length = len;
    return points;
}

(Note that polygon representations are already rotated so that point[0] is guaranteed to be the bottom-left-most point before this function is ever called.)
Given the test data
[
  { x: 0, y: -1 },
  { x: 0.2886751345948129, y: -0.5 },
  { x: 0.8660254037844387, y: -0.5 },
  { x: 0.5773502691896257, y: 0 },
  { x: 0.8660254037844387, y: 0.5 },
  { x: 0.28867513459481287, y: 0.5 },
  { x: 0, y: 1 },
  { x: -0.28867513459481287, y: 0.5 },
  { x: -0.8660254037844387, y: 0.5 },
  { x: -0.5773502691896257, y: 0 },
  { x: -0.8660254037844387, y: -0.5 },
  { x: -0.2886751345948129, y: -0.5 }
]

for a simple radius-1 six-pointed star, this gives the correct result, a bounding hexagon:
[
  { x: 0, y: -1 },
  { x: 0.8660254037844387, y: -0.5 },
  { x: 0.8660254037844387, y: 0.5 },
  { x: 0, y: 1 },
  { x: -0.8660254037844387, y: 0.5 },
  { x: -0.8660254037844387, y: -0.5 }
]

However, if I remove the angular sort, even though the input is a simple polygon, it ends up appending an extra interior vertex:
[
  { x: 0, y: -1 },
  { x: 0.8660254037844387, y: -0.5 },
  { x: 0.8660254037844387, y: 0.5 },
  { x: 0, y: 1 },
  { x: -0.8660254037844387, y: 0.5 },
  { x: -0.8660254037844387, y: -0.5 },
  { x: -0.2886751345948129, y: -0.5 }
]

Any help debugging this or suggestions for an alternate algorithm to use would be appreciated. I would like to use Lee's algorithm, but I cannot find a good reference implementation or complete psuedocode for it anywhere, and the prose-and-diagrams explanations are proving too hard to follow. I can use Melkman's algorithm, but I don't actually need online construction, and I'd prefer to avoid needing to pull in a deque rather than a stack if at all possible.

A: Well, I don't know about debugging the version I had, but I sat down with a blank screen and thought real hard about how to re-implement Graham scan from scratch, and I came up with something that actually does work:
// Graham scan. Assumes a simple polygon.
// This is destructive, collecting hull
// vertices in the prefix of the input array.
export function polygonHull(points: Vertex[]) {
    const n = points.length;

    // There can never be fewer than 4 vertices.
    // Assume the first point is bottom-left-most
    const p0 = points[0];

    let top = 1;
    for (let i = 2; i < n; i++) {
        // Duplicate points are pre-filtered
        // if (points[top].x === points[i].x && points[top].y === points[i].y) { continue; }
        points[++top] = points[i];
        while (top >= 2 && ccw(points[top-2], points[top-1], points[top]) >= 0) {
            points[top - 1] = points[top]; // delete internal point
            top--;
        }
    }

    // Fix up the join between the tail and start
    while (ccw(points[top-1], points[top], p0) >= 0) { top--; }

    points.length = top + 1;
    return points;
}

The idea was to stick to the original published version of the algorithm, using a circular doubly-linked list, as possible; and then just make minimal alterations to shift to an array representation, with special handling for the discontinuity at the ends of the array.

A: Your information is wrong, the Graham scan does not necessarily "works" on a simple polygon. What is true is:

*

*the Graham scan works on sorted points (star-shaped or monotone polygon) in linear time,

*the Melkman's algorithm works on simple polygons in linear time.

This said, for small polygons, sorting is not a big deal. My favorite version is the Monotone Chain version, as it avoids a conversion to polar coordinates.
Large polygons, unless they are pathological, are made of a few already sorted sequences, so sorting with a k-way merge can be advantageous.
If your point set has a large proportion of internal points, preliminary rejection à la Quickhull can be of interest - even leading to linear expected time. Unsure if large simple polygons enjoy this property.


text:
Q: Detecting touches outside a scroll view programmatically I am trying to create a horizontally scrollable UIScrollView. I am using this Ray Wenderlich tutorial. I have the scrollview appearing and working fine, but currently stumped on the "Detecting touches outside a scroll view" part of the tutorial.
The problem is that I am creating everything programmatically. I am especially stumped about this part of the tutorial code  (in ScrollViewContainer.m):
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == self) {
        return _scrollView;
        }
    return view;
}

where _scrollView is an IBOutlet (in ScrollViewContainer.h):
@property (nonatomic, strong) IBOutlet UIScrollView *scrollView;

As I understand it, the _scrollView "connection" is done on the Storyboard via outlet. How am I supposed to do that programmatically?

A: with the use of this code i find my touch object and hides the view so hope you can fix it with a bit of trick and modification on same code just pass your scrollview object and log inside that its touched or not.
#pragma mark
#pragma mark - Touch Events
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint imgPop = [touch locationInView: _scrollView];
    if ([_scrollView pointInside:imgPop withEvent:event])
    {
        NSLog(@"Touch Inside ScrollView");
    } else {
        NSLog(@"Touch Outside ScrollView");
    }
}

let me know if you find any difficulty to implement it.

A: Detecting the touches outside the scrollview you may simply access the touchEvents of the UIView.

*

*touchesBegan,

*touchesEnded,

*touchesMoved,

*touchesCancelled

Try touches began for any single tap you want.

A: That custom hitTest:withEvent: method in Ray Wenderlich tutorial is only needed if you've made the scroll view smaller that the screen (and set its clipsToBounds to NO):

The method will make touches happening outside the scroll view be forwarded to it.
So in your source code you need to call something like
@property (nonatomic, strong) UIScrollView *scrollView;
...
UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(
    20,
    20,
    self.view.frame.size.width - 20,
    self.view.frame.size.height - 20
)];


text:
Q: What can we say about this matrix?
Let $$V = \left\{ f : [0,1] \to \mathbb R\ :\ f \text{ is a polynomial of degree} \leq n \right\}$$ Let $f_j(x)=x^j$ for $0 \le j \le n$ and let $A$ be the $(n+1) \times (n+1)$ matrix given by
$$a_{ij} = \int_{0}^{1} f_i(x) \, f_j(x) \, \mathrm d x$$
Then which of the following is/are true?
$1.$ $\ \dim V=n$.
$2.$ $\ \dim V>n$.
$3.$ $\ A$ is non-negative definite, i.e., for all $v \in \Bbb R^n$, $\left < Av,v \right > \ge 0$.
$4.$ $\ \det A>0$.

Clearly $\{1,x,x^2,\cdots, x^n \}$ is a basis for $V$. This shows that $\dim V=n+1>n$. Hence $(1)$ is incorrect but $(2)$ is a correct option. For determining whether or not $(3)$ and $(4)$ are correct options I first find the matrix $A$ which is
$$A=\begin{bmatrix}
1 & {\frac {1} {2}} & {\cdots} & {\frac {1} {n+1}} \\
{\frac {1} {2}} & {\frac {1} {3}} & {\cdots} & {\frac {1} {n+2}} \\
{\vdots} & {\vdots} & {\ddots} & {\vdots} \\
{\frac {1} {n+1}} & {\frac {1} {n+2}} & {\cdots} & {\frac {1} {2n+1}}
\end{bmatrix}.$$
Here I got stuck. How do I find $\det A$? Also after evaluating $ \langle Av,v \rangle$ I can't figure out whether or not $\langle Av,v \rangle \ge 0$ for all $v \in \Bbb R^n$. Please help me in this regard. Thank you very much.

A: Let $v=(v_0,\ldots,v_n)^T$ and $f=\sum_{i=0}^n v_if_i.$ Then
$$
\langle Av,v \rangle = \sum_{i=0}^n\sum_{j=0}^n v_iv_j\int_0^1f_i(x)f_j(x)dx \\
= \int_0^1\left(\sum_{i=0}^nv_if_i(x)\right)\left(\sum_{j=0}^nv_jf_j(x)\right)dx
=\int_0^1 \left(f(x)\right)^2dx
$$
Therefore $\langle Av,v\rangle > 0$ if $v\neq 0.$ The matrix is positive definite. (3) and (4) are correct.


text:
Q: iptable rules to allow downloading stuff while default policy is on DROP I was trying to install bind and for some reason I was getting issues most likely due to my iptable rules , I can ping google.ca anybody have any reccomndations down below are my current rulesets
iptables -F
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

#policy
iptables -A INPUT -i lo  -j ACCEPT
iptables -A OUTPUT -o lo  -j ACCEPT
#pings
iptables -A INPUT -p icmp -j ACCEPT
iptables -A OUTPUT -p icmp -j ACCEPT
#
#allow dns  pings

iptables -I INPUT -i ens33 -p udp --sport 53 -j ACCEPT
iptables -I INPUT -i ens37 -p udp --sport 53 -j ACCEPT
iptables -I OUTPUT -o ens33 -p udp --dport 53 -j ACCEPT
iptables -I OUTPUT -o ens37 -p udp --dport 53 -j ACCEPT
#
#forward chain
iptables -I FORWARD -p icmp -j ACCEPT
iptables -I FORWARD -p udp --dport 53 -j ACCEPT
iptables -I FORWARD -p udp --sport 53 -j ACCEPT
iptables -I INPUT -p tcp --sport 80 -j ACCEPT
iptables -I OUTPUT -p tcp --dport 80 -j ACCEPT # go to websites


text:
Q: USING PDO & MYSQL to get rows compared and switched to columns I have a Products table, an Imprint table, a Manufacturer table and an ingredients table - along with other tables.
I am currently generating information and use what is called "file_name" as the id (it is a FDA assigned 36-40 digit id that goes with each product).  What is happening now is people enter of few letters and the autocomplete dropdown provides the exact spelling.  When they click SUBMIT and it brings up all entries that match. If they select a generic product it also includes the "brand" product - if they enter a brand it also includes the generic.
The current display is as follows:
Sold by:        Sold using   Available    Chemical name                Data based
                  name        Since:                                   on company
                                                                     report submitted:
C----- Health    Lortab      2011-01-13  Hydrocodone Bitartrate etc  2010-12-07

R—Distributors   Hydrocodone 2010-02-18  Hydrocodone Bitartrate etc  2009-12-17
                 Bitartrate
                 And Acetaminophen

C-- Health       Vicodin     1983-01-07   Hydrocodone Bitartrate etc  2009-11-03

R—Distributors   Hydrocodone 2010-07-30   Hydrocodone Bitartrate etc  2010-12-28
                 Bitartrate
                 And Acetaminophen

This is working fine.  I will be adding a check box on the left which will allow up to 3 of the products to be chosen for comparison and additional information.
THE NEXT STEP:
After they check 1, 2 or 3 items, I want to display like this:
"ALL of the versions of the product you checked contain the following ingredients:"
(Those ingredients common to all chosen products).
ACETAMINOPHEN, CELLULOSE, CORN, CROSPOVIDONE, HYDROCODONE BITARTRATE, MICROCRYSTALLINE, STARCH and STEARIC ACID
(Show the ingredients in each product NOT held in common by all.
End result in COLUMNS)
"IN addition, EACH of the products you chose have the following ingredients:"
COLUMN 1(Product 1)         COLUMN 2 (Product 2)         COLUMN 3 ( Product 3)
COPOVIDONE                  MAGNESIUM STEARATE         CROSCARMELLOSE SODIUM
CROSCARMELLOSE SODIUM       POVIDONE                   D&C YELLOW NO. 10
D&C RED NO. 27              SILICON DIOXIDE            FD&C BLUE NO. 1
D&C RED NO. 30                                         POVIDONE
HYDRATED SILICA                                        SILICON DIOXIDE
MAGNESIUM STEARATE                                     SUCROSE

End of display
Ingredient table:  there are 20,000 rows,46 columns.  Each row is a different drug and contains the id, file-name and then the ingredients, Each drug (row) has a different combination and number of ingredients.  Unused fields are marked "Null";:
Ingredient columns in each row:
id, file_name, 0_gred, 1_gred, 2_gred, 3_gred, 4_gred, 5_gred, 6_gred, 7_gred, 8_gred, 9_gred, 10_gred, 11_gred, 12_gred, 13_gred, 14_gred, 15_gred, 16_gred, 17_gred, 18_gred, 19_gred, 20_gred (etc. up to 43_gred)

The question is how and what approach to use to get the format I need for the ingredients.  I have experience in developing registration systems, I am fairly knowledgeable in PHP and am starting to get use to PDO.  My Sql experience is minimal and is basically on a "need to know" basis.
I have wondered whether I should focus on a monster of a MySQL query or more on the php side.  I thought about a query giving the ingredients common to all 3 and then subtracting that result from each individual drug list to get  Part II but that appears to be quite advanced mysql – especially since I need the data to switch from row to COLUMN layout.  Any help?
Another idea was to do a query that concatenated the ingredients of each row and then doing array procedures on the php side.  Problems, I am having a hard time finding the right code to pull the ingredients out of each row since the number of "NULL" fields compared to "used" fields varies with each row.  (How to count null COLUMNS in PDO query?  I've tried and get the full count of columns in the table.)
To me, this is a braintwister with several steps.  I'm looking for the "magic" MySql Code (if it exists) and or suggestions as to what approach (using php, mysql, PDO) you would pursue.
Your interest/help is appreciated!!
Laura

A: I figured out a php way to do what I needed.  I'm sure there is a faster MySql way.  If you know of one please share!  Laura
First, I set the Mysql empty values to default to "no_ingre".
Then I did the following code 3 times for the 3 choices:
SELECT 'all the ingredient fields WHERE id=$name_of_id'
$result=$stmt->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
    if ($value == "no_ingre") unset($result[$key]);
}

FIND THE ingredients COMMON TO ALL:
$same_detect= array_intersect($result, $result2, $result3);
$p_same=(implode(", ", $same_detect));

echo "
The below ingredients are in all of the chosen products
";
echo $p_same;

To FIND THE ONES NOT COMMON TO ALL: Do the below code 3 times (for each ingredient array):
foreach ($result as $item) {
if (!in_array($item, $same_detect, true)) {
echo ("
" . $item . "
"); }


text:
Q: Construction involving regular polygons inside a circle Let's make a construction involving regular polygons:
► First, we begin with a equilateral triangle, with side $\ell_3 = 1;$
► After, we draw a square on the middle point each side of the initial triangle, with side $\ell_4 = \frac{1}{2} = \frac{\ell}{2}.$
Now, the construction continues, taking one of these steps:
► If the regular polygon have an even number of sides $n$ with length $\ell_n$, then we draw two regular polygons with $n + 1$ sides of length $\ell_{n+1} = \frac{\ell_n}{2},$ from the middle point of the extreme segments.
► If the regular polygon have an odd number of sides $n$ with length $\ell_n$, then we draw one regular polygons with $n + 1$ sides of length $\ell_{n+1} = \frac{\ell_n}{2},$ from the middle point of the unique extreme segment in this case.
To clarify the explanation, we will obtain a figure like the one below:

I have two questions about this:

Q1. This figure is inside a circumference with center in the incenter of the initial equilateral triangle? In affirmative case, what is the radius $R$ of the circumference?
Q2. The sequence of the lengths I adopted in the construction is
  $$\ell_n = \frac{1}{2^{n-3}}, \quad \forall n \ge 3 $$
  If I consider other sequence $\ell_n$, when exists a circumference with center in the incenter of the initial equilateral triangle and radius $R$ in which the figure is inside?


text:
Q: Take first argument from alias command and interpolate it to file name extension How to make alias that take argument and interpolate it to file extension to create it? I tired this and this doesn't work :
alias create-bash-file=' echo  "#!/bin/bash" > "$1.sh" '

as $1 is first argument and .sh is file extension and I wanted to make an alias that create a bash file included "#!/bin/bash" but the file name I want to take it as an argument so for example and I will write create-bash-file filename this should generate bash file called filename.sh

A: Aliases don't take arguments; functions do.
create-bash-file () {
    echo "#!/bin/bash" > "$1.sh"
}


text:
Q: Can we integrate google docs with windows azure I have a application where the documents will be uploaded to windows azure storage blobs, Since azure does not support for online viewing ,editing and sharing the documents , Can i integrate google docs feature with documents stored in azure storage blobs ?

A: No, you can't integrate Google Docs with documents stored in Azure Blob Storage. Google docs (online viewing, editing, collaborating) is only available for documents stored at Google Docs app online! You could probably use Google Docs API (or SkyDrive api, which also supports online editing, viewing, sharing, collaboration) to upload documents to the respective store directly!


text:
Q: Gradle - ear task I was trying to use 'appDirName'in ear task, which has 'META-INF/application.xml'
When it is creating ear file, it is creating with 'meta-inf/application.xml'.
Ear file is not deployable to Websphere 6.1. application server.
Please suggest.
Messsages from WAS 6.1:

The EAR file could be corrupt and/or incomplete. Make sure that the application is at a compatible Java 2 Platform, Enterprise Edition (J2EE) Level for WebSphere Application Server.
AppDeploymentException: [null] org.eclipse.jst.j2ee.commonarchivecore.internal.exception.DeploymentDescriptorLoadException: META-INF/application.xml

A: What kind of version do you create? I believe WebSphere 6.1 is J2EE 1.4, but gradle ear-plugin assumes version 6. I had that problem with Weblogic, however it was more verbose. See http://www.gradle.org/ear_plugin.html on how to alter ear-plugin:
ear {
  deploymentDescriptor {
    version = '1.4'
  }
}


text:
Q: Extracting HTML5 data attributes from a tag I want to extract all the HTML5 data attributes from a tag, just like this jQuery plugin.
For example, given:
Joe Bloggs

I want to get a hash like:
{ 'data-age' => '50', 'data-location' => 'London' }

I was originally hoping use a wildcard as part of my CSS selector, e.g.
Nokogiri(html).css('span[@data-*]').size

but it seems that isn't supported.

A: Option 1: Grab all data elements
If all you need is to list all the page's data elements, here's a one-liner:
Hash[doc.xpath("//span/@*[starts-with(name(), 'data-')]").map{|e| [e.name,e.value]}]

Output:
{"data-age"=>"50", "data-location"=>"London"}

Option 2: Group results by tag
If you want to group your results by tag (perhaps you need to do additional processing on each tag), you can do the following:
tags = []
datasets = "@*[starts-with(name(), 'data-')]"

#If you want any element, replace "span" with "*"
doc.xpath("//span[#{datasets}]").each do |tag|
    tags << Hash[tag.xpath(datasets).map{|a| [a.name,a.value]}]
end

Then tags is an array containing key-value hash pairs, grouped by tag.
Option 3: Behavior like the jQuery datasets plugin
If you'd prefer the plugin-like approach, the following will give you a dataset method on every Nokogiri node.
module Nokogiri
  module XML
    class Node
      def dataset
        Hash[self.xpath("@*[starts-with(name(), 'data-')]").map{|a| [a.name,a.value]}]
      end
    end
  end
end

Then you can find the dataset for a single element:
doc.at_css("span").dataset

Or get the dataset for a group of elements:
doc.css("span").map(&:dataset)

Example:
The following is the behavior of the dataset method above. Given the following lines in the HTML:
Joe Bloggs
Jim Foggs

The output would be:
[
 {"data-location"=>"London", "data-age"=>"50"},
 {"data-location"=>"Oxford", "data-age"=>"40"}
]

A: You can do this with a bit of xpath:
doc = Nokogiri.HTML(html)
data_attrs = doc.xpath "//span/@*[starts-with(name(), 'data-')]"

This gets all the attributes of span elements that start with 'data-'. (You might want to do this in two steps, first to get all the elements you're interested in, then extract the data attributes from each in turn.
Continuing the example (using the span in your question):
hash = data_attrs.each_with_object({}) do |n, hsh|
  hsh[n.name] = n.value
end

puts hash

produces:
{"data-age"=>"50", "data-location"=>"London"}

A: Try looping through element.attributes while ignoring any attribue that does not start with a data-.

A: The Node#css docs mention a way to attach a custom psuedo-selector. This might look like the following for selecting nodes with attributes starting with 'data-':
Nokogiri(html).css('span:regex_attrs("^data-.*")', Class.new {
  def regex_attrs node_set, regex
    node_set.find_all { |node| node.attributes.keys.any? {|k| k =~ /#{regex}/ } }
  end
}.new)


text:
Q: Python librosa.display cannot be imported My python version is 3.7.4,and Librosa version is 0.8.0
Below is my code:
import librosa
import librosa.display
import matplotlib.pyplot as plt
y, sr = librosa.load('./test/s1071511.wav', sr=None)

plt.figure()

librosa.display.waveplot(y, sr)
plt.title('Beat wavform')
plt.show()

I want to show the spectrum of a wav file, but I got:
ModuleNotFoundError: No module named 'librosa.display'; 'librosa' is not a package
I have searched the related documents for a while.
Could you help me? I really appreciate.

A: Are you able to load the audio file using librosa package?
If yes,  then try using installing librosa version 0.8.0


text:
Q: Circuit for controlling 3 DC motors I have a simple 3 motor robot arm. Without much experience or knowledge, I put together a circuit for controlling it. Circuit is below:

Now the circuit actually works and I can program the Arduino and have it move about as I wish. Here are the issues and questions I have:

*

*I have had several motor drive boards "smoke" and then never turn on again. Is this because the motors may have been stalled when I powered on the circuit? I.e. if my motors have a stall current of 20A, do I need a motor driver that can handle 20A? The reason I went with less (13A drivers) is because I was only planning on operating around 10A, which would be the max power operating point. Do I even have control of how much current is drawn?

*Is it advisable to use 1 battery like I am doing? I had to strip the other end of the aligator clips, strip the 3 sets of wires, wrap em around, and apply a lot of solder. I have no idea what the "reasonable" thing to do here is, maybe it's to have 3 batteries for all I know.

*I am using AWG wire #16, which is supposed to have a max chassis wiring limit of 22A (http://www.powerstream.com/Wire_Size.htm). Should this be alright? I haven't had any wire melting problems.

*Any other suggestions are welcome, I am new to this =)
Thanks for the help, and let me know if you need any additional information.

A: Your system looks right, this is how I would do it.

*

*If you had a motor driver smoke out then the voltage was too high or the current was too high or no back EMF protection. If you plan on running the motor at 20A max then your driver should be capable of dealing with 24A, at least. Don't forget that even if your motor draws 20A when stalled there is probebly is very short 30A-35A 'spike'. Always plan on 10%-30% more when selecting components.

*Both option would work but it would be better to use a single battery for the sole reason that your system will last longer. As long as you have large enough capacitors on your driver there shouldn't be any problem running all your motors from the same battery.

*Again, if you plan to run your motors at 20A it would be better to use a 14AWG wire that can deal ~30A. If this is a hobby project and your wires are not many meters long please don't save 2$ on wires. If you are going to make a million units then your should go for a 18AWG wire as this might be enough if you draw 20A for a very short period of time.


text:
Q: Parse JSON Children to objects I am attempting to parse JSON children values to objects in vb.net. The below code I have been able to get first set of children objects, but I am unable to go any deeper. When it reaches subitem2 it gives me An unhandled exception of type 'System.NullReferenceException' occurred.
Dim o As JObject = JObject.Parse(jsonstring)
        Dim results As List(Of JToken) = o.Children().ToList
        For Each item As JProperty In results
            item.CreateReader()

            Dim strfname As String
            Dim strlname As String
            Dim strphone As String

            For Each subitem As JObject In item.Value
                strfname = subitem("firstname")
                strlname = subitem("lastname")
                strphone = subitem("Phone")

                For Each subitem2 As JObject In subitem("Deposits")
                    Dim id As String
                    Dim amount As String
                    id = subitem("id")
                    amount = subitem("amount")
                Next
            Next
        Next

A: I know it is months after the event, but I was just looking for some Json parsing examples and stumbled across this. In your code I notice that the two lines:
id = subitem("id")
amount = subitem("amount")

look wrong - should they not be:
id = subitem2("id")
amount = subitem2("amount")

apologies if I am way off, but thought I would point out what I thought was the error.

A: I was unable to find a sufficient method to do this is directly in JSON. I converted the JSON String and did it in XML. I know this isn't the most efficient way but I have a few deadlines to meet. We will be fixing later on.

A: Replace:
For Each subitem2 As JObject In subitem("Deposits")
  Dim id As String
  Dim amount As String
  id = subitem("id")
  amount = subitem("amount")
Next

with :
Dim id As String = ""
Dim subitem2 As List(Of JToken) = subitem("device").ToList
For Each Citem As JProperty In subitem2
  Citem.CreateReader()
  Select Case Citem.Name
    Case "id"
      id = Citem.Value
  End Select
Next


text:
Q: ActiveRecord::StatementInvalid: Mysql2::Error: Table 'exchange_development.documents' doesn't exist: SHOW FULL FIELDS FROM `documents` I'm getting the following error: https://gist.github.com/glaksmono/859e495d61bfb4c66e1bdb24dbdf5719
And here's what I have in my databases:
mysql> mysql> SHOW DATABASES;
+----------------------+
| Database             |
+----------------------+
| information_schema   |
| exchange_development |
| exchange_production  |
| exchange_test        |
| mysql                |
| performance_schema   |
| sys                  |
+----------------------+
7 rows in set (0.00 sec)

mysql> USE exchange_development;
Database changed
mysql> SHOW TABLES;
Empty set (0.00 sec)

mysql>

I've tried executing bundle exec rake db:schema:load prior, and been searching over the web on this but none has worked so far. Thoughts?


text:
Q: PyQt - trouble with reimplementing data method of QSqlTableModel I'm a newbie with python and mainly with pyqt. The problem is simple: I have a QTableView and I want to "simply" change the color of some rows. Reading all around I found that the simplest solution should be to override the data method in the model in such a way:
class MyModel(QtSql.QSqlTableModel):

    def data(self,idx,role):
        testindex=self.index(idx.row(),idx.column(),idx.parent())
        if(role==QtCore.Qt.BackgroundRole):
            return QtGui.QColor(255,0,0)
        elif role == QtCore.Qt.DisplayRole:
            return QtSql.QSqlTableModel().data(testindex)

When I use this model reimplementation, the rows are changing color but the cell values disappear and the return statement QtSql.QSqlTableModel().data(testindex) is always None.
I'm getting crazy to find out a solution. Could you help me?

A: Your implementation is broken in a couple of ways: (1) it always returns None for any unspecified roles, (2) it creates a new instance of QSqlTableModel every time the display role is requested, instead of calling the base-class method.
The implementation should probably be something like this:
class MyModel(QtSql.QSqlTableModel):

    def data(self, index, role):
        if role == QtCore.Qt.BackgroundRole:
            return QtGui.QColor(255, 0, 0)
        return super(MyModel, self).data(index, role)


text:
Q: Let $\Omega=\{1,2,3,4,5,6\}$ & $H=\{g\in S_6:g(i)-g(j)\equiv i-j\mod 3\text{ for all }i,j\in\Omega\}\subset S_6 ={\rm Sym}(\Omega).$ Show $H\le S_6$. I am unsure with how I laid my answer out, in particular for the 2nd and 3rd requirements

Let $\Omega =\{1,2,3,4,5,6\}$. Let $H =\{g \in S_6 : g(i) - g(j) \equiv i-j \mod 3\text{
 for all }i,j \in \Omega\} \subset S_6 ={\rm Sym}(\Omega).$ Show that $H$ is a subgroup of $S_6$.

I am not allowed to use the finite subgroup test
$SG0$ - identity element $\in H$. $e$ is the identity function so for all $i,j \in \Omega$, $e(i) = i$ and $e(j)=j$. So, for all $i,j \in \Omega$, $e(i)-e(j) = i - j \equiv i-j \mod 3$ as required. So $e \in H$.
$SG1$ - for all $g,h \in H$, $gh \in H$ (closure). Let $g,h \in H$, so for all $i,j \in \Omega$, $g(i) - g(j) \equiv i-j \mod 3$, and $h(i) - h(j) \equiv i-j\mod 3$. Then, $gh = g(h(i)-h(j)) \equiv h(i)-h(j) \mod 3\equiv i-j\mod 3$ as required. So $gh \in H$.
$SG2$ - for all $h \in H$, we have $h^{-1} \in H$. Let $h \in H$, so for all $i,j \in \Omega$, $h(i) - h(j) \equiv i-j\mod 3$. Now, $h(h^{-1}(i)-h^{-1}(j))\equiv h^{-1}(i)-h^{-1}(j)\mod 3$. Thus, $i-j \equiv h^{-1}(i)-h^{-1}(j)\mod 3$, so $h^{-1}(i)-h^{-1}(j) \equiv i-j\mod 3$. So $h^{-1} \in H$.
So all requirements satisfied so $H$ is a subgroup of $S_6$. I am mainly unsure on my notation for the 2nd and 3rd requirement. Can someone please check this?


text:
Q: Why tomcat truncated my bytes output? I wrote a servlet to serve a mp4 file.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.reset();
    resp.setContentType("video/mp4");

    Path f = Paths.get(getServletContext().getRealPath("/WEB-INF/small.mp4"));
    int length = (int) Files.size(f);
    byte[] bytes = Files.readAllBytes(f);

    resp.setStatus(200);
    resp.setContentLength(length);

    ServletOutputStream sos = resp.getOutputStream();
    sos.write(bytes);
    resp.flushBuffer();
    sos.flush();
    sos.close();
}

The mp4 file is 1057148 bytes.
I captured the http messages using Charles and found the actual body size is less than the bytes I wrote. What's more strange is the actual entity bytes changed with different requests.
I don't know why tomcat truncate my output or what is something I missed.
My tomcat is apache-tomcat-8.0.27 on Mac OSX 10.11.2

Now I closed this question. I found the reason. Tomcat didn't truncate my response. That's Charles's problem. It showed: Client closed connection before receiving entire response.
So Charles seemed to have some bugs. I use Fiddler and found the response kept integrity as expected.


text:
Q: Crash in prepareForSegue() I am trying to transfer the score of a game over to a viewController once time has run out. I currently have this bit of code in one viewController.
var score = 0
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "toResults" {
            var svc = segue.destinationViewController as! Results
            svc.resultsScore == (score)
        }
    }

In my second view controller I have this code:
var resultsScore: Int!

@IBOutlet weak var finalScore: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    finalScore.text = "\(resultsScore)"

}

In the first viewController while trying to pass the score to resultsScore in the Results viewController it crashes at this line with this error code.
svc.resultsScore == (score)

fatal error: unexpectedly found nil while unwrapping an Optional value

Why would this be happening? I have passed data from one VC to another before and this has not happened. Is this unsafe to pass it this way?

A: svc.resultsScore == (score)

== is the comparison operator.
assign it using 1 equal sign, =
svc.resultsScore = (score)


text:
Q: VSCode When authenticated I currently have a welcome view that tells the user to log in before they can continue.
I'm primarily using this code to sign the user in.
However, how do I go about removing the welcome view if the user is signed in?
The documentation on the when clause doesn't say anything about authentication.
Am I forced to overwrite the context in order to change my welcome view?
I'm leaning towards doing something like:
vscode.commands.executeCommand('setContext', 'extension.authenticated', true)

But I'd rather not have to keep track of this context unless there are no other options.


text:
Q: Some clarifications and a question on basic probability. I have a few questions and some clarifications.
CLARIFICATIONS:
1. Assume we roll 2 four sided dice. What is P({sum of the rolls is even})? I answered the question correctly
I: Odd + Odd = Even
J: Even + Even = Even
K: Odd + Even = Odd
I answered the question with this line of thinking P(I) + P(J):
P(I) = (2 / 4) * (2 / 4) P(J) = (2 / 4) * (2 / 4)
= 1 / 2
*Is this a valid concept of solving the problem?
2. Assume we roll 2 four sided dice. What is P({first roll larger than second roll})?
P(1,<2,3,4>) + P(2, <3,4>) + P(3, 4)
(1 / 4 * 3 / 4) + (1 / 4 * 2 / 4) + (1 / 4 * 1 / 4) = 3 / 8
*Is this a valid concept of solving the problem? Are there better solutions?
QUESTION:
Say you're in a classroom with 29 other students (30 total students). What is the calculated probability that two students share the same birthdate? For simplicity, assume there are 365 days in a year and all birthdates are equally probable. I need help on this one.

A: Your approach is correct.  Your notation could use some work.
You are partitioning the event into a series of disjoint events, whose individual probabilities you can calculate and then sum using the Law of Total Probability.  That is exactly the approach you should use.

*

*Assume we roll 2 four sided dice. What is P({sum of the rolls is even})? I answered the question correctly

Let $X$ be the result of one die and $Y$ be the result of the other.
$$\begin{align}
\mathsf P(\mathrm{Even}(X+Y)) & = \mathsf P(\mathrm{Even}(X))\;\mathsf P(\mathrm{Even}(Y))+\mathsf P(\mathrm{Odd}(X))\;\mathsf P(\mathrm{Odd}(Y))
\\[2ex] & = \frac 2 4 \frac 2 4 + \frac 2 4\frac 2 4
\\[2ex] & = \frac 1 2
\end{align}$$
Alternatively you can just notice that whatever result of the first dice, half of the results of the second dice will give an even sum.

*Assume we roll 2 four sided dice. What is P({first roll larger than second roll})?

$$\begin{align}
\mathsf P(X > Y) & = \sum_{x=2}^4 \mathsf P(X=x) \mathsf P(Y< x)
\\[2ex] & = \mathsf P(X=2)\mathsf P(Y<2) + \mathsf P(X=3)\mathsf P(Y<3) + \mathsf P(X=4)\mathsf P(Y< 4)
\\[2ex] & = \frac 1 4 \left(\frac 1 4 + \frac 2 4 + \frac 3 4\right)
\\[1ex] & = \frac 3 8
\end{align}$$

Say you're in a classroom with 29 other students (30 total students). What is the calculated probability that two students share the same birthdate? For simplicity, assume there are 365 days in a year and all birthdates are equally probable. I need help on this one.

In this case you need to use the Rule of Complements.   The sum of the probabilities of complementary events is $1$.   The event that "at least two students share a birthdate" is the complement of the event that "all students have unique birthdates".   Can you calculate the probability that nobody shares a birthdate?


text:
Q: ORG alternative for C++ In assembly we use the org instruction to set the location counter to a specific location in the memory. This is particularly helpful in making Operating Systems. Here's an example boot loader (From wikibooks):
 org 7C00h

         jmp short Start ;Jump over the data (the 'short' keyword makes the jmp instruction smaller)

 Msg:    db "Hello World! "
 EndMsg:

 Start:  mov bx, 000Fh   ;Page 0, colour attribute 15 (white) for the int 10 calls below
         mov cx, 1       ;We will want to write 1 character
         xor dx, dx      ;Start at top left corner
         mov ds, dx      ;Ensure ds = 0 (to let us load the message)
         cld             ;Ensure direction flag is cleared (for LODSB)

 Print:  mov si, Msg     ;Loads the address of the first byte of the message, 7C02h in this case

                         ;PC BIOS Interrupt 10 Subfunction 2 - Set cursor position
                         ;AH = 2
 Char:   mov ah, 2       ;BH = page, DH = row, DL = column
         int 10h
         lodsb           ;Load a byte of the message into AL.
                         ;Remember that DS is 0 and SI holds the
                         ;offset of one of the bytes of the message.

                         ;PC BIOS Interrupt 10 Subfunction 9 - Write character and colour
                         ;AH = 9
         mov ah, 9       ;BH = page, AL = character, BL = attribute, CX = character count
         int 10h

         inc dl          ;Advance cursor

         cmp dl, 80      ;Wrap around edge of screen if necessary
         jne Skip
         xor dl, dl
         inc dh

         cmp dh, 25      ;Wrap around bottom of screen if necessary
         jne Skip
         xor dh, dh

 Skip:   cmp si, EndMsg  ;If we're not at end of message,
         jne Char        ;continue loading characters
         jmp Print       ;otherwise restart from the beginning of the message

 times 0200h - 2 - ($ - $$)  db 0    ;Zerofill up to 510 bytes

         dw 0AA55h       ;Boot Sector signature

 ;OPTIONAL:
 ;To zerofill up to the size of a standard 1.44MB, 3.5" floppy disk
 ;times 1474560 - ($ - $$) db 0

Is it possible accomplish the task with C++? Is there any command, function etc. like org where i can change the location of the program?

A: No it's not possible to do in any C compiler that I know of. You can however create your own linker script that places the code/data/bss segments at specific addresses.

A: Just for clarity, the org directive does not load the code at the specified address, it merely informs the assembler that the code will be loaded at that address. The code shown appears to be for Nasm (or similar) - in AT&T syntax, the .org directive does something different: it pads the code to that address - similar to the times line in the Nasm code.. Nasm can do this because in -f bin mode, it "acts as it's own linker".
The important thing for the code to know is the address where Msg can be found. The jmps and jnes (and call and ret which your example doesn't have, but a compiler may generate) are relative addressing mode. We code jmp target but the bytes that are actually emitted say jmp distance_to_target (plus or minus) so the address doesn't matter.
Gas doesn't do this, it emits a linkable object file. To use ld without a linker script the command line looks something like:
ld -o boot.bin boot.o -oformat binary -T text=0x7C00
(don't quote me on that exact syntax but "something like that")  If you can get a linkable object file from your (16-bit capable!) C++ compiler, you might be able to do the same.
In the case of a bootsector, the code is loaded by the BIOS (or fake BIOS) at 0x7C00 - one of the few things we can assume about the bootsector. The sane thing for a bootsector to do is not fiddle-faddle around printing a message, but to load something else. You'll need to know how to find the something else on the disk and where you want to load it to (perhaps where your C++ compiler wants to put it by default) - and jmp there. This jmp will want to be a far jmp, which does need to know the address.
I'm guessing it's going to be some butt-ugly C++!


text:
Q: How to install flutter and dart in Android Studio and InttelliJ? I am facing issues with installation. I get the following when I run
flutter doctor
[✓] Flutter (Channel beta, v0.4.4, on Mac OS X 10.11.6 15G19009, locale en)
    • Flutter version 0.4.4 at /Users/divyakrishnan/Development/flutter
    • Framework revision f9bb4289e9 (11 days ago), 2018-05-11 21:44:54 -0700
    • Engine revision 06afdfe54e
    • Dart version 2.0.0-dev.54.0.flutter-46ab040e58

[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    • Android SDK at /Users/divyakrishnan/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • Java binary at: /Applications/Android Studio 3.0 Preview.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)
    • All Android licenses accepted.

[!] iOS toolchain - develop for iOS devices
    ✗ Xcode installation is incomplete; a full installation is necessary for iOS development.
      Download at: https://developer.apple.com/xcode/download/
      Or install Xcode via the App Store.
      Once installed, run:
        sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
    ✗ libimobiledevice and ideviceinstaller are not installed. To install, run:
        brew install --HEAD libimobiledevice
        brew install ideviceinstaller
    ✗ ios-deploy not installed. To install:
        brew install ios-deploy
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without resolving iOS dependencies with CocoaPods, plugins will not work on iOS.
        For more info, see https://flutter.io/platform-plugins
      To install:
        brew install cocoapods
        pod setup

[✓] Android Studio
    • Android Studio at /Applications/Android Studio 3.0 Preview.app/Contents
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b01)

[!] IntelliJ IDEA Community Edition (version 2018.1.4)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • For information about installing plugins, see
      https://flutter.io/intellij-setup/#installing-the-plugins

[!] Connected devices
    ! No devices available

I do not see the flutter or dart plugin in Android Studio 3.0 and IntelliJ.

A: The plugins are not installed by default with Android Studio or IntelliJ. You need to install them yourself using the instructions from this page:
Install the Flutter and Dart plugins

Flutter is supported by two plugins:

*

*The Flutter plugin powers Flutter developer workflows (running, debugging, hot reload, etc.).

*The Dart plugin offers code analysis (code validation as you type, code completions, etc.).

To install these:

*

*Start the Android Studio.

*Open plugin preferences (Preferences>Plugins on macOS, File>Settings>Plugins on Windows & Linux).

*Select Browse repositories…, select the Flutter plugin and click install.

*Click Yes when prompted to install the Dart plugin.

*Click Restart when prompted.

A: Just follow these steps:

*

*Go to Plugins.

*Browse Repositories.

*Search for flutter.

*Tap on Install (a dialog will pop regarding dart dependency. click Yes).

*Once the installation is finished restart android studio.

Hope it helps.

A:
I had the same problem and these are the steps to solve my problem (Install the Flutter and Dart plugins):

*

*Start Android Studio.

*Open plugin preferences (Configure > Plugins as of v3.6.3.0 or later).

Note: Prior to v3.6.3.0, should follow:  Open plugin preferences
(Preferences > Plugins on macOS, File >
Settings > Plugins on Windows & Linux)

*Select the Flutter plugin and click Install.

*Click Yes when prompted to install the Dart plugin.

*Click Restart when prompted.

Run flutter doctor. You should get this output:

A: One of the most import thing always " RUN AS ADMINISTRATOR " you IDE i.e Android .. etc.
for flutter to avoid several errors.

A: Installing Flutter and Dart Plugins into Android Studio is very easy--
 Follow the steps to install-

*

*Click on Configure --> Plugins

*Browse Flutter repository from Search box

*Click on install button

*Click on Yes to install Dart plugin from Alter prompt

*After completing all process Restart Android Studio to activate plugins
For more information Click here to find detail steps with graphical inteface

A: This is the step for flutter install the Android Studio:
1.Go to Settings->Plugin->Install Flutter and Dart->Restart Android Studio
2.Download  the flutter sdk
3.In the environment Variable->User Variable->
ANDROID_HOME F:\AndroidSDK(Paste your Android SDK Path)
Path:F:\AndroidSDk;(Paste your Android SDK Path)
     c:\ProgramFiles\Java\jdk\1.8.0_20\bin;(Paste your jdk Path)
     c:\Users\Desktop\flutter\bin;(Paste your Flutter SDK Path)
4.Git install at c:\ProgramFiles\Git
5.Open Gitbash
$flutter doctor
$flutter doctor --android-licenses
Accept the licences Y Y Y Y
Make sure your Device should be connected your PC

A: I found this solution myself, so there is no link for proof or details.
I tried installing Dart and Flutter plugin via Android Studio (File - Settings - Plugins - Market Place). Every time after install it showed Restart IDE. After restart every time Android Studio use to show Disable Flutter plugin or install Dart.
After many attempts (installing Dart via above option), what I did I went into
*\.AndroidStudio4.0\system\plugins

copied flutter-intellij.zip and Dart-*.*.zip files into
*\.AndroidStudio4.0\config\plugins

and just unzipped these 2 files ( used extract here option) and launched android studio, the error was gone and Android Studio showed some data collection message.
Now I can see File -> New -> New Flutter Project ...


text:
Q: How do I resolve this error in Selenium : ERROR: Couldn't read tbsCertificate as SEQUENCE, ERROR: Failed parsing Certificate I'm trying to execute a selenium program in Python to go to a new URL on click of a button in the current homepage. I'm new to selenium and any help regarding this would be appreciated. Here's my code
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = 'https://nmit.ac.in'

driver = webdriver.Chrome()

driver.get(url)

try:
    # wait 10 seconds before looking for element
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located(By.LINK_TEXT, "Parent Portal")
    )

except:
    print()

driver.find_element(By.LINK_TEXT, "Parent Portal").click()

I have tried to increase the wait time as well as using all forms of the supported located strategies under the BY keyword, but to no avail. I keep getting this error.

A: As far as I know, you shouldn't be worried by those errors. Although, I proved your code and it's not finding any element in the web page. I can recommend you use the xpath of the element you want to find:
    # wait 10 seconds before looking for element
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "/html//div[@class='wsmenucontainer']//button[@href='https://nmitparents.contineo.in/']"))
    )
    element.click()
    #wait for the new view to be loaded
    time.sleep(10)
    driver.quit()

Psdt: you can use the extention Ranorex Selocity to extract a good and unique xpath of any element in a webpage and also test it!!
image

A: A lot of time passed while I was looking for a solution and I found it here.
options = webdriver.ChromeOptions()

options.add_experimental_option('excludeSwitches', ['enable-logging'])

driver = webdriver.Chrome(
    service= Service(chromedriver_path),
    options=options,
)

driver.get('https://www.google.com/')

It should remove all annoying errors and warnings from selenium


text:
Q: points not accessible after QVector insert function I am trying to follow the rule of three, however doing this has cause a problem specifically with QVector's insert function.
after adding a copy constructor and destructor, My program will produce an error where a vector of points are no longer accessible, and so the copy constructor fails to re-assign the points.
Here are some snippets from my code
QVector<QPointF> *mList = nullptr;
int area;

Shape::Shape()
{
    mList = new QVector<QPointF>();
    area = 0;
}
Shape::Shape(const Shape &obj)
{
    mList = new QVector<QPointF>();
    mList = *obj.mList;
    area = obj.area;
}
Shape::~Shape()
{
    delete mList;
}

Now I sort a group of 'Shape' objects by their area using qSort, which uses the QVector functions.
void T::sortByArea()
{
    qSort(listOfShapes);
}

When this method finishes. I find that one of the shapes now has an mList that has the value <not accessible>. Which only occurs in the sort when QVector::insert(int i, const T &value) is used.

Up until this point, this list of shapes is edited and manipulated but this is the only time up to this point that a Shape's list becomes inaccessible. What is the reasoning and how should I fix this?

A: As far as I can see, since you use const in your copy constructor argument list, the QVector is only shallow copied and not deep copied. This is because QVector is an implicitly shared container.
Removing the const should work, but better solution may be to explicitely copy the entire vector (eg. using memcopy), not just using the QVector's = operator.


text:
Q: How to save markers position to localStorage in leaflet? I am trying new to localStorage, and I am trying to save the markers that the user can create on the map.
I created this function to place markers and delete them:
var redmarker = L.icon({
iconUrl: 'http://icons.iconarchive.com/icons/paomedia/small-n-flat/48/map-marker-icon.png',

       iconSize:     [48, 48], // size of the icon
       iconAnchor:   [24, 48], // point of the icon which will correspond to marker's location
       popupAnchor:  [-2, -48] // point from which the popup should open relative to the iconAnchor
                        });

        var popup = L.popup();

        // On map click shows coordinates X, Y
        function onMapClick(e) {

          var geojsonFeature = {
            "type": "Feature",
            "properties": {},
            "geometry": {
              "type": "Point",
              "coordinates": [e.latlng.lat, e.latlng.lng]
            }
          }

          var marker;

          L.geoJson(geojsonFeature, {

            pointToLayer: function(feature, latlng){

              marker = L.marker(e.latlng, {

                title: "Resource Location",
                alt: "Resource Location",
                riseOnHover: true,
                draggable: true,
                icon: redmarker

              }).bindPopup("<X: " + e.latlng.lng + ", Y: " + e.latlng.lat + "
Delete marker");

              marker.on("popupopen", onPopupOpen);

              return marker;
            }
          }).addTo(map);
        }

        function onPopupOpen() {
          var tempMarker = this;

          $("#marker-delete-button:visible").click(function () {
            map.removeLayer(tempMarker);
          });
        }

        map.on('click', onMapClick);

I am not familiar with localStorage, this is new to me. Also I am trying to make the popup editable, an user input there for the user name the marker.
I saw this example of input:
http://tahvel.info/simpleStorage/example/
Something like that.
A working example of my function: http://fiddle.jshell.net/2g4h5eu5/1/
Can someone help  me save the markers in localStorage?
Also my problem is that I don't know what render's the markers on leaflet after I click, so I don't know exactly what I need to save in local storage to retrieve those markers.

A: you can use the following functions to manage your localStorage
localStorage.setItem('favoriteflavor','vanilla');
var taste = localStorage.getItem('favoriteflavor');
// -> "vanilla"
localStorage.removeItem('favoriteflavor');
var taste = localStorage.getItem('favoriteflavor');
// -> null
check this link
also you can use jQuery Storage API plugin to make things more cross-browser
http://fiddle.jshell.net/thesane/2g4h5eu5/29/
/// Load markers
function loadMarkers()
{
    var markers = localStorage.getItem("markers");
  if(!markers) return;
  markers = JSON.parse(markers);
  markers.forEach(function(entry) {
    latlng = JSON.parse(entry);
    var geojsonFeature = {
                        "type": "Feature",
                        "properties": {},
                        "geometry": {
                            "type": "Point",
                            "coordinates": [latlng.lat, latlng.lng]
                        }
                    }

                    var marker;

                    L.geoJson(geojsonFeature, {

                        pointToLayer: function(feature){

                            marker = L.marker(latlng, {

                                title: "Resource Location",
                                alt: "Resource Location",
                                riseOnHover: true,
                                draggable: true,
                icon: redmarker

                            }).bindPopup("<X: " + latlng.lng + ", Y: " + latlng.lat + "
Delete marker");

                            marker.on("popupopen", onPopupOpen);

                            return marker;
                        }
                    }).addTo(map);
});
}
/// Store markers
function storeMarker(marker)
{
    var markers = localStorage.getItem("markers");
  if(!markers) {
    markers = new Array();
    console.log(marker);
    markers.push(JSON.stringify(marker));
  }
  else
  {
    markers = JSON.parse(markers);
    markers.push(JSON.stringify(marker));
  }
   console.log(JSON.stringify(markers));
  localStorage.setItem('markers', JSON.stringify(markers));
}

// Delete Marker
function deleteMarker(lng, lat) {
  var markers = localStorage.getItem("markers");
  markers = JSON.parse(markers);
   for(var i=0;i<markers.length;i++){
    latlng = JSON.parse(markers[i]);

    if(latlng.lat == lat && latlng.lng == lng)
    {
        markers.splice(i,1);

    }
  }
  localStorage.setItem('markers', JSON.stringify(markers));
}


text:
Q: awsebcli installation failed,i am using python 3.4, pip 8.1.2  pip install awsebcli
    Collecting awsebcli
    Using cached awsebcli-3.7.7.tar.gz
    Collecting pyyaml>=3.11 (from awsebcli)
    Using cached PyYAML-3.11.zip
    Collecting botocore>=1.0.1 (from awsebcli)
    Using cached botocore-1.4.40-py2.py3-none-any.whl
Collecting cement==2.8.2 (from awsebcli)
  Using cached cement-2.8.2.tar.gz
Collecting colorama==0.3.7 (from awsebcli)
  Using cached colorama-0.3.7-py2.py3-none-any.whl
Collecting pathspec==0.3.4 (from awsebcli)
  Using cached pathspec-0.3.4.tar.gz
Collecting setuptools>=20.0 (from awsebcli)
  Using cached setuptools-25.1.0-py2.py3-none-any.whl
Collecting docopt<0.7,>=0.6.1 (from awsebcli)
  Using cached docopt-0.6.2.tar.gz
Collecting requests<=2.9.1,>=2.6.1 (from awsebcli)
  Using cached requests-2.9.1-py2.py3-none-any.whl
Collecting texttable<0.9,>=0.8.1 (from awsebcli)
  Using cached texttable-0.8.4.tar.gz
Collecting websocket-client<1.0,>=0.11.0 (from awsebcli)
  Using cached websocket_client-0.37.0.tar.gz
Collecting docker-py<=1.7.2,>=1.1.0 (from awsebcli)
  Using cached docker-py-1.7.2.tar.gz
Collecting dockerpty<=0.4.1,>=0.3.2 (from awsebcli)
  Using cached dockerpty-0.4.1.tar.gz
Collecting semantic_version==2.5.0 (from awsebcli)
  Using cached semantic_version-2.5.0-py3-none-any.whl
Collecting python-dateutil<3.0.0,>=2.1 (from botocore>=1.0.1->awsebcli)
  Using cached python_dateutil-2.5.3-py2.py3-none-any.whl
Collecting jmespath<1.0.0,>=0.7.1 (from botocore>=1.0.1->awsebcli)
  Using cached jmespath-0.9.0-py2.py3-none-any.whl
Collecting docutils>=0.10 (from botocore>=1.0.1->awsebcli)
  Using cached docutils-0.12-py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade): six in c:\python34\lib\site-packages (from websocket-client<1.0,>=0.11.0->awsebcli)
Installing collected packages: pyyaml, python-dateutil, jmespath, docutils, botocore, cement, colorama, pathspec, setuptools, docopt, requests, texttable, websocket-client, docker-py, dockerpty, semantic-version, awsebcli
  Running setup.py install for pyyaml ... error

this is the first error
        Complete output from command c:\python34\python.exe -u -c "import setuptools, tokenize;file='C:\Users\MADHAV~1\AppData\Local\Temp\pip-build-uddplklq\pyyaml\setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record C:\Users\MADHAV~1\AppData\Local\Temp\pip-gz9ygj2p-record\install-record.txt --single-version-externally-managed --compile:
        running install
        running build
        running build_py
        creating build
        creating build\lib.win32-3.4
        creating build\lib.win32-3.4\yaml
        copying lib3\yaml\composer.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\constructor.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\cyaml.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\dumper.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\emitter.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\error.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\events.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\loader.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\nodes.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\parser.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\reader.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\representer.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\resolver.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\scanner.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\serializer.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml\tokens.py -> build\lib.win32-3.4\yaml
        copying lib3\yaml__init__.py -> build\lib.win32-3.4\yaml
        running build_ext
        creating build\temp.win32-3.4
        creating build\temp.win32-3.4\Release
        checking if libyaml is compilable
        Traceback (most recent call last):
          File "", line 1, in
          File "C:\Users\MADHAV~1\AppData\Local\Temp\pip-build-uddplklq\pyyaml\setup.py", line 342, in
            'test': test,
          File "c:\python34\lib\distutils\core.py", line 148, in setup
            dist.run_commands()
          File "c:\python34\lib\distutils\dist.py", line 955, in run_commands
            self.run_command(cmd)
          File "c:\python34\lib\distutils\dist.py", line 974, in run_command
            cmd_obj.run()
          File "c:\python34\lib\site-packages\setuptools\command\install.py", line 61, in run
            return orig.install.run(self)
          File "c:\python34\lib\distutils\command\install.py", line 539, in run
            self.run_command('build')
          File "c:\python34\lib\distutils\cmd.py", line 313, in run_command
            self.distribution.run_command(command)
          File "c:\python34\lib\distutils\dist.py", line 974, in run_command
            cmd_obj.run()
          File "c:\python34\lib\distutils\command\build.py", line 126, in run
            self.run_command(cmd_name)
          File "c:\python34\lib\distutils\cmd.py", line 313, in run_command
            self.distribution.run_command(command)
          File "c:\python34\lib\distutils\dist.py", line 974, in run_command
            cmd_obj.run()
          File "C:\Users\MADHAV~1\AppData\Local\Temp\pip-build-uddplklq\pyyaml\setup.py", line 169, in run
            _build_ext.run(self)
          File "c:\python34\lib\distutils\command\build_ext.py", line 339, in run
            self.build_extensions()
          File "C:\Users\MADHAV~1\AppData\Local\Temp\pip-build-uddplklq\pyyaml\setup.py", line 211, in build_extensions
            with_ext = self.check_extension_availability(ext)
          File "C:\Users\MADHAV~1\AppData\Local\Temp\pip-build-uddplklq\pyyaml\setup.py", line 237, in check_extension_availability
            depends=ext.depends)
          File "c:\python34\lib\distutils\msvc9compiler.py", line 460, in compile
            self.initialize()
          File "c:\python34\lib\distutils\msvc9compiler.py", line 371, in initialize
            vc_env = query_vcvarsall(VERSION, plat_spec)
          File "c:\python34\lib\site-packages\setuptools\msvc9_support.py", line 52, in query_vcvarsall
            return unpatched['query_vcvarsall'](version, *args, **kwargs)
          File "c:\python34\lib\distutils\msvc9compiler.py", line 287, in query_vcvarsall
            raise ValueError(str(list(result.keys())))
        ValueError: ['path']


text:
Q: Domain Models - Designing the model Regarding domain driven design:
I have domain models, repositories and services. My questions is regarding the modelling of the domains.
For instance, I have a database table with Employee, CountryId, State Id

*

*How would I model my domain object, would I model it with the id or with the literal value?

*At what point would I resolve the Id value to the literal value?

*Should I use the services to point to the CRUD operations of the repository or is that an anti-pattern?

Your help would be highly appreciated.

A: How would I model my domain object, would I model it with the id or with the literal value?
Is the id part of the domain or is only used by your relational database? In the latter case you would not model using the id. Strictly speaking you are thus also not allowed to store the id in your entities, but this would require you to create data transfer objects, which would probably mirror your entities in almost every way. Therefore personally I do not take DDD so strictly.
At what point would I resolve the Id value to the literal value?
Your infrastructure layer should take care of this.
Should I use the services to point to the CRUD operations of the repository or is that an anti-pattern?
Services may call the repositories. It would however be an anti-pattern if there are two ways to (seemingly) achieve the same effect within a codebase. You could expose your services to a higher layer (and hide the repositories from that layer) and use the repositories within those services. In between it would be possible to have some additional logic.


text:
Q: Change radio model on button click [angularjs] What i want to achieve is trigger the change of the model "value" of the radio  when i click on the button change input.
Why do i need to call twice click so that the model gets updated and the radio gets checked?
http://jsfiddle.net/7GfB9/
HTML
<div ng-app ng-controller="Ctrl">
    <input type="radio" ng-model="value" ng-value="33">
    <input type="radio" ng-model="value" ng-value="22">{{ value }}
    <button onclick="changeInput()">Change input</button>
</div>

JS
function Ctrl($scope) {

}

function changeInput() {
    $('input:eq(0)').click().click();
}

A: Likely because the value is updated before your onclick function is called. Why don't you update the value in your onclick function and only use one click?

A: Forget jQuery and try this :
<button ng-click="value = 33">Change input</button>

http://jsfiddle.net/7GfB9/3/

A: Solution i've come up with. I'm new to angularjs seems like im not used to it yet.
HTML
<div ng-app ng-controller="Ctrl">
    <input type="radio" ng-model="value" ng-value="33">
    <input type="radio" ng-model="value" ng-value="22">{{ value }}
    <button ng-click="changeInput()">Change input</button>
</div>

js
function Ctrl($scope) {
    $scope.changeInput = function () {
        $scope.value=$('input:eq(0)').val();
    }
}


text:
Q: How to obtain line number at the node visitor during tree building in sonarqube plugin For more complex analysis puproses we need to collect some info into Sensor implementation class and next line number binding.
Where can I find line number of tree element?
java.plugin.version: 3.13.1
sonar.plugin.api.version: 5.2
May be newer versions are more functional?
Our goal - to check that package name and class name, containing some naming conventions details, must not import some packages.
From the node visitor we unable to see all tree nodes, it's obvious.
But here we can register an issue for node specific place of code by internal mechanism of addIssue().
/**
* First step implementation of node visitor for complex multinode check
*/
@Rule(key = "ImportClassCheck",
  name = "Import classes should not contain web or form",
  description = "Import classes should not contain web or form",
  priority = Priority.CRITICAL,
  tags = {"bug" })

public class ImportClassCheck extends IssuableSubscriptionVisitor {

@Override
public List<Kind> nodesToVisit() {
    return ImmutableList.of(Tree.Kind.IMPORT, Tree.Kind.PACKAGE, Tree.Kind.CLASS);
}

@Override
public void visitNode(Tree tree) {
    if (JavaCodeSensor.packages.get(context.getFileKey()) == null) {
        JavaCodeSensor.packages.put(context.getFileKey(), new ImportClassCheckState());
        JavaCodeSensor.packages.get(context.getFileKey()).file = context.getFile();
    }

    if (tree.is(Kind.PACKAGE))
        JavaCodeSensor.packages.get(context.getFileKey()).packageTree = (PackageDeclarationTree) tree;

    if (tree.is(Kind.CLASS))
            JavaCodeSensor.packages.get(context.getFileKey()).classTree.add((ClassTree) tree);

    if (tree.is(Kind.IMPORT))
        JavaCodeSensor.packages.get(context.getFileKey()).importTree.add((ImportTree) tree);
}
}

Then we come to Sensor interface implementation of analyse() - Oops, here is no info about line of code to register an issue for class name, for example at the line of class declaration, without parsing of file again.
/**
* First step to register an Issue
*/
@Override
public void analyse(Project project, SensorContext sensorContext) {
    for (Entry<String, ImportClassCheckState> entry : packages.entrySet()) {
        if (entry.getValue().isRuleFails()) {
            NewIssue newIssue = sensorContext.newIssue().forRule(
                                RuleKey.of("java-custom-rules-template", "ImportClassCheck"));
            newIssue.at(newIssue.newLocation()
                    .on(filesystem
                            .inputFile(filesystem.predicates().is(entry.getValue().file)))
/* Here is a problem to identify code of line, but needed tree nodes are exists in
ImportClassCheckState members*/
                            .at(new DefaultTextRange(new DefaultTextPointer(1, 0),
                        new DefaultTextPointer(1, 0))));
            newIssue.save();

            logger.info("Issue registered for file " + entry.getValue().file.getName());
        }
    }
}

A: Multiple way to answer your question.
Let me rephrase it first : how to access line information from a node of the tree.
Best way to answer just this question : upgrade to the latest version (4.2) and use the firstSyntaxToken().line() methods available on each node of the tree.
But what is better is that you don't need this at all, you should use the methods available in the issuableSubscriptionVisitor (either addIssue or reportIssue) to report issue and not raise issue within the sensor.


text:
Q: Handle menuitem selection with speed dial floating action buttons I'm currently developing my first Android app and therefore I'm using fab-speed-dial. I've implemented the floating action button so that the options suit my needs. But now I need to assign actions to the menu items.
E.g. I want to show an input field if one clicks on "add room" in the Screenshot below:

I've tried so add some listeners but obviously I'm doing something wrong. This is the code I'm currently using in my MainActivity.java
FabSpeedDial fabSpeedDial = (FabSpeedDial) findViewById(R.id.fab_speed_dial);
    fabSpeedDial.setMenuListener(new SimpleMenuListenerAdapter() {
        @Override
        public boolean onMenuItemSelected(MenuItem menuItem) {
            //what do I do here?
            return false;
        }
    });

My activity_main.xml looks like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <io.github.yavski.fabspeeddial.FabSpeedDial
        android:id="@+id/fab_speed_dial"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        app:fabGravity="bottom_end"
        app:fabMenu="@menu/menu_speeddial"
        app:miniFabBackgroundTint="@android:color/white"
        app:miniFabDrawableTint="?attr/colorPrimaryDark"
        app:miniFabTitleTextColor="?attr/colorPrimaryDark" />

</FrameLayout>

And last but not least the menu entries in menu_speeddial.xml
<?xml version="1.0" encoding="utf-8"?>
  <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
      android:id="@+id/add_room"
      android:icon="@drawable/ic_action_home"
      android:title="@string/menu_item_room"
      android:onClick="gotClicked"/>
  <item
      android:id="@+id/add_furniture"
      android:icon="@drawable/ic_action_armchair"
      android:title="@string/menu_item_furniture"/>
 </menu>

Any help on how to deal with this would be highly appreciated.

A: I havent used this library. But seeing your code, I can guess that the issue would be in the MenuListener.
@Override
        public boolean onMenuItemSelected(MenuItem menuItem) {
            if (menuItem.getItemId()==1){
                System.out.print("number 1 clicked");
            }
            return false;
        }

I think, you have to check equals with the resource id. Like this,
if (menuItem.getItemId() == R.id.add_room){
                System.out.print("number 1 clicked");
            }


text:
Q: Override arguments of parent symfony service using defaults world!
I'm trying to override some arguments of basic PHP-class in Symfony DI, using parent attribute, but I can't.
Basic class has many arguments and their defaults are described in abstract symfony service. The YAML:
    App\BasicClass:
      class: App\BasicClass
      public: false
      abstract: true
      arguments:
        - '@App\Finder\DefaultFinder' #App\Finder\FinderInterface
        - '@App\Builder\DefaultBuilder' #App\Builder\BuilderInterface
        - ...
        - ...
        - !php/const App\Enum\CountryCode::COUNTRY_UNDEFINED

In my child class I need to override just 3 of them. What I've tried:
    app.myChildClass:
      parent: App\BasicClass
      bind:
        App\Finder\FinderInterface: '@App\Finder\CustomFinder'
        App\Builder\BuilderInterface: '@App\Finder\CustomBuilder'

In this case I get an error:
A binding is configured for an argument of type \"App\\Finder\\FinderInterface\" for service \"app.myChildClass\", but no corresponding argument has been found
Even though namespace of interface is correct. The same error if I specify argument name (as it is in constructor) instead of namespace:
$finder: @App\Finder\CustomFinder
Overriding works only if I use "arguments" attribute instead of "bind" with argument names like below:
app.myChildClass:
  parent: App\BasicClass
  arguments:
    $finder: '@App\Finder\CustomFinder'
    $builder: '@App\Finder\CustomBuilder'

But the second problem I've got is that I hoped to bind one argument (a const) through the _defaults section:
    _defaults:
      bind:
        $country: !php/const App\Enum\CountryCode::COUNTRY_UKR

    app.myChildClass:
      parent: App\BasicClass
      arguments:
        $finder: '@App\Finder\CustomFinder'
        $builder: '@App\Finder\CustomBuilder'

But id doesn't jump into my service probably due to using "arguments", not "bind" :( So I'm confused, is here any chance to simplify this overriding or I must duplicate the row
$country: !php/const App\Enum\CountryCode::COUNTRY_UKR

in my child service definition?
Thank you!


text:
Q: jquery attr('href') not working Update, problem solved. The issue was with a function that I was calling after trying to change the HREF, which was essentially changing it back.

Using jQuery, I am trying to change the HREF attribute of a series of links based on the hash contained in the URL, but the attribute simply is not changing, it's being changed to an empty string.
Can anyone see what I'm doing wrong here? Why isn't it working?
http://fwy.pagodabox.com/categories/sculptures/#grid
The links in question are

All
      Exhibitions
      Installations
      Objects
      Prints
      Sculptures

In the secondary nav
function navHash($navlinks, hashtxt) {

        // loop through specified links
        $navlinks.each(function(){
            var $me = $j(this),
                myhref,
                index;

            // Does this link have an href… if not move on
            if( typeof $me.attr('href') === "undefined" )
                return false;

            myhref = $me.attr('href');
        index = myhref.indexOf('#');

        // if my href doesn't have the specified hash text, add it, else remove it
        if(myhref.indexOf(hashtxt) === -1) {
            $me.attr("href", hashtxt);
        } else {
            $me.attr("href", myhref.substring(0, index));
        }
    });
}

   $j(document).ready(function($){

        var $navlinks = $j('.sub-nav li:not(.views) a');

        if(window.location.hash == '#grid') {
            navHash($navlinks, '#grid');
            $('.views .ic-grid').click();
        }
// so on...

Thank you!!!

A: If you return false here you will stop looping.
if(typeof $me.attr('href') === "undefined")
   return false;

Return true to continue looping.


text:
Q: Dynamic form field creation with increment Following is my piece of code which I am using to create dynamic forms by click "Add more..." button. My question is how can I add +1 on the dynamically generate fields so their names should look like testimonial1, testimonial2, testimonial3 and so on.
Fiddle.
HTML:

            <input title="Testimonial" name="testimonial" class="testimonial required" type="text" placeholder="Testimonial"/>
            <input name="testimonial_by" id="testimonial_by" class="testimonial_by required" type="text" placeholder="by..."/>

Add more...

JS:
$("#more_testimonials").click(function() {
    $("#testimonial_ul").append('

<input class="testimonial" type="text" placeholder="Testimonial"/><input class="testimonial_by" type="text" placeholder="by..."/>
Remove
 ');
});

A: Try this:
var counter = 1;
$("#more_testimonials").click(function () {
    $("#testimonial_ul").append('

<input  name="Testimonial'+counter+'" class="testimonial" type="text" placeholder="Testimonial"/><input name="Testimonial'+counter+'" class="testimonial_by" type="text" placeholder="by..."/>
Remove
 ');
    counter++;
});

Working Fiddle.

A: I have updated your fiddle CHECK HERE
var formInputLen = $('.testimonial').length;

Calculate the total elements with class testimonial. And add the incremented counter to the id id="testimonial' + (formInputLen + 1) +'".

A: You can replace some special string to number of inputs.
http://fiddle.jshell.net/k1twc1tz/1/


text:
Q: Racket macro to define functions given a repeated pattern The problem is quite difficult to explain because I need to collect my thoughts, so bear with me. I've been able to reduce the problem to a minimal example for illustrative purposes. The example will not make any sense as to what this would be useful for, but I digress. Say I want to extend the racket language to write things that look like this:
(define-something
  (['a] 'whatever)
  (['b 'c] 'whatever2))

Between the square brackets is a sequence of one or more symbols, followed by a sequence of racket expressions (the whatever's, which are not important for the problem statement)
The example would match a macro that looks something like this:
(define-syntax (define-something stx)
  (syntax-case stx ()
    [(_  ([symb ...] body ...) ...)
     #'()]))

Actually here we match 0 or more symbols, but we can assume there is always going to be at least one.
In the macro's body I want to generate function definitions using the concatenated symbols as the identifier. So for our silly example the macro would expand to something like:
(define (a) 'whatever)
(define (bc) 'whatever2)

I have found a similar question where the poster generates functions using a pre-defined list of strings, but I am not that fluent with macro's so I have not been able to translate the concepts to solve my problem. I thought perhaps I could try generating a similar list (by concatenating the symbols) and applying their tactic, but I've been getting way too confused with all the ellipses in my macro definition. I'm also a bit confused about their use of an ellipsis in with-syntax.

A: It's possible to solve this with with-syntax and syntax-case, but the easiest way to do this is by using syntax-parse's syntax classes. By defining a syntax class that parses a list of symbols and produces a single concatenated identifier, you can lift the symbol parsing out of the macro body:
(require (for-syntax syntax/parse
                     racket/string))

(begin-for-syntax
  (define-syntax-class sym-list
    #:attributes [concatenated-id]
    (pattern (~and stx (sym:id ...))
             #:attr concatenated-id
             (let* ([syms (syntax->datum #'(sym ...))]
                    [strs (map symbol->string syms)]
                    [str (string-append* strs)]
                    [sym (string->symbol str)])
               (datum->syntax #'stx sym #'stx #'stx)))))

Now you can define your macro pretty easily:
(define-syntax (define-something stx)
  (syntax-parse stx
    [(_ (syms:sym-list body ...) ...)
     #'(begin
         (define (syms.concatenated-id) body ...)
         ...)]))

Note that this uses unquoted symbols in the name clause, so it would work like this:
(define-something
  ([a] 'whatever)
  ([b c] 'whatever2))

The names can't be expressions that evaluate to symbols because the information needs to be known at compile-time to be available to macro expansion. Since you mentioned in a comment that this is for an FRP-like system, your signal graph will need to be static, like Elm's is for example. If you want the ability to construct a dynamic signal graph, you'll need a more complex strategy than macros since that information will need to be resolved at runtime.


text:
Q: Doctrine 2 limit IN subquery I'm trying to use a subquery in a IN statement in Doctrine2.
Here's what the raw SQL query should look like :
SELECT * FROM license
WHERE id
IN (SELECT id
    FROM license
    WHERE subscription = x
    ORDER BY date DESC
    LIMIT 5)
ORDER BY name ASC;

What I want to do is display the 5 last results ordered by name, so I have to first query the last 5 results and then order by name in the main query.
The problem is that I can't seem to LIMIT the inner query.
Here's my current code :
$qb = $this->createQueryBuilder('l');
$qb->select('l.id');
$qb = $this->whereSubscriptionId($qb, $subscription_id);
$qb = $this->offsetLimitOrder($qb, 0, 5, 'deliveryDatetime desc');

//Second Query, adds the "order by X"
$qb2 = $this->createQueryBuilder('l2');
$qb2->add('where', $qb2->expr()->in('l2.id', $qb->getQuery()->getDQL()));
if(isset($order)){
    $order = explode(' ', $order);
    $qb2->addOrderBy('l2.'.$order[0], $order[1]);
 }

 return $qb2->getQuery()
            ->getResult();

As you can see, I create my first query, I order and limit it (via a custom method) and then I try to use it in the second query.
However, it seems that the LIMIT is not part of the DQL statement because when I var_dump the first query's DQL, the LIMIT is absent, which means that it's completly ignored when I run $qb2->getQuery()->getResult();
I made it work by launching the first query and manually inputing the results in the second one, but it's ugly.
Any idea on how to do it properly ?
Thanks !

A: Unfortunately Doctrine does not support limit on nested queries. Even if you use 2 QueryBuilders and setMaxResults() on the inner QueryBuilder, it will simply be ignored.
The only way to do this at this time is to run 2 individual queries.