text:
Q: Geometric sampling problem in the Euclidean space in high dimensions Let $T$ be the triangle whose vertices are three given points $\mathbf{x}, \mathbf{y}, \mathbf{z}\in\mathbb{R}^d$.

Question: What computationally efficient strategy can we use to sample a point $\mathbf{p}$ from $T$ with probability linearly proportional to $\|\mathbf{p}\|_2$?

A: It doesn't make any difference that $d\gg 1$. If $0<a<b<1$, $Q(a,b)=\|a\mathbf x+(b-a)\mathbf y+(1-b)\mathbf z\|_2^2=a^2\|\mathbf x\|^2+(b-a)^2\|\mathbb y\|^2+(1-b)^2\|\mathbf z\|^2+2a(b-a)\langle\mathbf x,\mathbf y\rangle+2(b-a)(1-b)\langle\mathbf x,\mathbf z\rangle$. That is, you should pick the point in the 2d simplex $\{(a,b)\colon 0<a<b<1\}$ with probability proportional to $\sqrt {Q(a,b)}$. This is then mapped to the point in your original triangle by $(a,b)\mapsto a\mathbf x+(b-a)\mathbf y+(1-b)\mathbf z$ (this mapping is linear, and so a proportion $t$ of the simplex maps to a proportion $t$ of the triangle).


text:
Q: Requiring modules in node I was going through this article
Which approach is better requiring the modules at the top of the file or requiring them inside the separate function in the main file where they are used?
//main file
var stripe = require('stripe');

//inside function of main file
function makePayment(){
   var stripe= require('stripe');
}

A: When called for the first time on a given module file, require() uses synchronous I/O to load the file.  It is designed primarily for use during server initialization because you usually do not want to do synchronous I/O during the regular operation of a server because it can wreck the scalability of your server (due to the single threadedness of node.js Javascript).
As such, the usual convention is to load all your dependencies with require() at module initialization time, not during the normal execution of runtime functions in the module.
So, I'd recommend using:
const stripe = require('stripe');

somewhere near the top of your module file and not inside your function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom shortcode for custom fields with Prefix in Wordpress I am trying to create a custom shordcode for all of my custom options fields that show up on the front end.
For each custom field i am using a custom prefix 'myprefix'.
Now if i add following shortcode it works fine:
[myfield field='myprefix-enable-logo']

function My_Custom_Shortcodes( $atts ) {
  return get_option($atts['field]');
}
add_shortcode( 'myfield', 'My_Custom_Shortcodes' );

But what i want is following structure of shortcode and the prefix is predefined in the function:
[myfield field='enable-logo']

How to achieve this?

A: I have solved this by getting the slug of the attribute of the custom field. then added the custom prefix to it in get_option like following:
function My_Custom_Shortcodes( $atts ) {
    $a = shortcode_atts( array(
        'field' => 'The slug',
    ), $atts );

  $mcf_slug = "{$a['field']}";
  return get_option('myprefix-' . $mcf_slug);

}
add_shortcode( 'myfield', 'My_Custom_Shortcodes' );


text:
Q: Searching for a valid kernel header path in Ubuntu 16.04 VMware I'm using a Ubuntu VM. Very recently I upgraded the system from Ubuntu 15.04 to 16.04. While installing ./vmware-tools.pl, I get the following line:
Searching for a valid kernel header path...
The path "" is not a valid path to the 4.4.0-116-generic kernel headers.

I've been looking at two other solutions online [this and this] but none seem to work.
My main goal is to have Copy/Paste enabled from the Host Machine. It did work for Ubuntu 15.04, it is not working now that I upgraded. Changing Settings in the VM does not seem to be enough.


text:
Q: MEAN app with angular 2 error: Cannot read property _id of undefined I am building an application for the first time to store, update, view and delete Client profiles. I followed the Angular tour of heroes to build the basic app and then pieced together the mongodb and express portions from around the net.
I am getting this error in my browser console when i attempt to delete a client profile -

ERROR TypeError: Cannot read property '_id' of undefined
      at ClientProfileComp.webpackJsonp.../../../../../src/app/components/clientProfile.component.ts.ClientProfileComp.delete
  (clientProfile.component.ts:53)... (etc).

I have confirmed using postman that my express routing is working as intended. I am able to get all/create clients at /api/clients, as well as get, put and delete from /api/clients/:_id (where _id is the autogenerated id for each entry).
I believe the problem is in one of my component files, as the error only occurs when I attempt to delete or view specific client detail, which causes another type of error entirely (CastError). The problem likely began when I attempted to remove all mentions of clientProfile: ClientProfile[]; (or Hero in the case of the tutorial) as I am no longer importing the details from client.ts (hero.ts) since I am using a mongoose schema instead, and I do not believe I should be importing that schema into my front-end angular.
here is the delete section of clientProfile.service.ts:
delete(_id: number): Promise<void>  {
    const url = `${this.clientProfilesUrl}/${_id}`;
    return this.http.delete(url, {headers: this.headers}).toPromise()
    .then(() => null).catch(this.handleError);
}

and here is clientProfile.component.ts as requested (the most likely source of my problem being that i replaced all instances of clientProfile: ClientProfile; with clientProfile: any; without knowing what I was doing)
note the commented out import statement.
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

//import { ClientProfile } from '../old/clientProfile';
import { ClientProfileService } from '../services/clientProfile.service';

@Component({
selector: 'app-clientprofile',
templateUrl: '../views/clientProfile.component.html',
styleUrls: [ '../styles/clientprofile.component.css' ]
})

export class ClientProfileComp implements OnInit {
selectedClientProfile: any;
clientProfiles: any = [];
clientProfile: any;

constructor(
    private clientProfileService: ClientProfileService,
    private router: Router
) { }

gotoDetail(): void {
    this.router.navigate(['/detail', this.selectedClientProfile._id]);
}

getClientProfiles(): void {
    this.clientProfileService.getClientProfiles().then(clientProfiles => {
        this.clientProfiles = clientProfiles;
    });
}

ngOnInit(): void {
    this.getClientProfiles();
}

onSelect(clientProfile: any): void {
    this.selectedClientProfile = clientProfile;
}

add(name: string, address: string): void {
    name = name.trim();
    address = address.trim();
    if (!name) { return; }
    this.clientProfileService.create(name, address).then(clientProfile => {
        this.clientProfiles.push(clientProfile);
            this.selectedClientProfile = null;
    this.getClientProfiles();
    });
}

delete(clientProfile: any): void {
    this.clientProfileService.delete(clientProfile._id).then(() => {
        this.clientProfiles = this.clientProfiles.filter(h => h !==
clientProfile);
        if (this.selectedClientProfile === clientProfile) { this.selectedClientProfile = null; }
    });
}
}

I have been poring over this all day, and have read a lot of similar posts here too - but most of the solutions don't seem to apply to this case. If anyone could point me in the right direction, i'd be really grateful. if any more code is needed to explain what i'm trying to do i will gladly post it.

A: Based on the error message it seems that the error is here:
this.router.navigate(['/detail', this.selectedClientProfile._id])

It appears that you only set it in onSelect and there are several places in your code that you are setting this.selectedClientProfile to null. That would be the best place to look.
If you'd like to create a plunker that demonstrates your issue, we could look at it further.
As a side note, you are using promises instead of the now more common Observables. If you want to change over to using Observables, I have a complete example of CRUD (create, read, update, and delete) operations here: https://github.com/DeborahK/Angular2-ReactiveForms in the APM folder.

A: Found out one problem - my delete button in the html file was in a div that only appeared when a client was selected, instead of next to each client. this was a result of a half-finished measure i took to ensure users don't just click delete willy-nilly on each client.
Code before:

Client Profiles

Add new client
<input placeholder="Client Name (required)" #clientProfileName />
<input placeholder="Client Address" #clientProfileAddress />
<button (click)="add(clientProfileName.value, clientProfileAddress.value);
clientProfileName.value=''; clientProfileAddress.value=''">
    Add</button>

    {{clientProfile.idnumber}}
    {{clientProfile.name}}

    {{selectedClientProfile.name | uppercase}} selected

<button (click)="gotoDetail()">View Details</button>
<button class="delete"
        (click)="delete(clientProfile);
$event.stopPropagation()">Delete</button>
//delete button will only appear when a client is selected

Code now:

Client Profiles

Add new client
<input placeholder="Client Name (required)" #clientProfileName />
<input placeholder="Client Address" #clientProfileAddress />
<button (click)="add(clientProfileName.value, clientProfileAddress.value);
clientProfileName.value=''; clientProfileAddress.value=''">
    Add</button>

    {{clientProfile.idnumber}}
    {{clientProfile.name}}
    <button class="delete"
        (click)="delete(clientProfile);
$event.stopPropagation()">Delete</button>
//delete button appears next to each client

    {{selectedClientProfile.name | uppercase}} selected

<button (click)="gotoDetail()">View Details</button>


text:
Q: MomentJs Get Years - Not Difference I am trying to get the years included within the given date range.
Such that a user and input Dec. 1st 2015 - July. 1st 2016. I can get 2015 but I need to include 2016 as well.
Currently I am doing the difference between the two dates as years:
   var tmpStart = moment($scope.dates1.startDate);
    var tmpEnd = moment($scope.dates1.endDate);
    var years = tmpEnd.diff(tmpStart, 'year');
    for (var i = 0; i < years+1; i++) {
        var tmpD = moment($scope.dates1.startDate);
        tmpD.add(i, 'years');
        sc.dtColumns.push(DTColumnBuilder.newColumn(tmpD.format('YYYY')).withTitle('Total ' + tmpD.format('YYYY')));
    }

What is the best way to do this? I am sure I can just parse the year as int and compare to see how many years there are but I feel like that cannot be the proper way.

A:   $scope.startDate = '01/01/2014';
    $scope.endDate = moment(d).format("MM/DD/YYYY");
    var tmpEndYear = moment(d).format("YYYY");
    var tmpStart = moment("20140101", "YYYYMMDD");
    sc.dtColumns = [DTColumnBuilder.newColumn('ProductNumber').withTitle('Item')];
    var tmpEnd = moment(d);
    $scope.dates1.startDate = moment("20140101", "YYYYMMDD");
    $scope.dates1.endDate = tmpEnd;
    for (var i = 2014; i <= tmpEndYear; i++) {
        sc.dtColumns.push(DTColumnBuilder.newColumn(i).withTitle('Total ' + i));
    }
    while (tmpEnd > tmpStart) {
        sc.months.push(tmpStart.format('MM-YYYY'));
        tmpStart.add(1, 'month');
    }

Did eventually parse the int out and use it from there.


text:
Q: Matlab AppDesigner: Listbox from Excel I'm creating an app in App Designer. What I would like to do is when selecting one or multiple options, these get assigned a value of 1.
The list(i.e. "Column") is read in the following way and list options are assigned to a struct variable with a default value of 0.
table1 = readtable("file.xls");

for i = 1:length(rmmissing(table1{:,"Column"}))
    s.(char(rmmissing(table1{i,"Column"}))) = 0;
end

This outputs the following table.
s.Anna = 0
s.Bett = 0
s.Cyrielle = 0
s.Dylan = 0

My problem is that I can't figure out a way of updating the value from 0 to 1, whenever I highlight one of the options. I don't know how to essentially pick up a selected value and updating it.
So as an example, If I highlight "Anna" and "Cyrielle", these should update to 1, as shown below.
s.Anna = 1
s.Bett = 0
s.Cyrielle = 1
s.Dylan = 0

I tried an if statement like. Whilst this works, it means I have to hard-code the names, which I don't want. So it needs to dynamically pick out the name that is selected.
    if app.ColumnListBox.Value == "Anna"
        s.Anna = 1;
    else
        s.Anna = 0;
    end

The listbox would look like this:
Listbox
The output I get when selecting one name is:
s =

  struct with fields:

        Anna: 1
        Bett: 0
    Cyrielle: 0
       Dylan: 0

However if I select multiple options, everything goes to 0:
Multiple names
s =

  struct with fields:

        Anna: 0
        Bett: 0
    Cyrielle: 0
       Dylan: 0

The code now is as follows:
names = fieldnames(s);
for j = 1:numel(names)
    name = names{j};
    if app.ListBox.Value == string(name)
            s.(name) = 1;
        else
            s.(name) = 0;
    end
end

assignin("base","s",s)

Any help would be much appreciated!

A: You should be able to make your if condition less hard coded with something like
names = fieldnames(s);
for iField = 1:numel(names)
    % Assign current name to variable, e.g. "Anna"
    name = names{iField};
    % loop over the fields and check if selected
    if app.ColumnListBox.Value == string(name)
        s.(name) = 1;
    else
        s.(name) = 0;
    end


text:
Q: Convert PHP to C# - how to handle arrays? I need to convert a few lines of PHP code to C#. However, I have only basic knowledge and I don't understand well the arrays yet.
Here is the code that I need to be converted to C#:
function decode_char($c, $a1, $a2)
{
  $result = $c;
  for($j = 0; $j < count($a1); $j++) {
    if ($c == $a1[$j][0]) {
      $result = $a2[$j][0];
      break;
    }
    if ($c == $a2[$j][0]) {
      $result = $a1[$j][0];
      break;
    }
  }
  return $result;
}

function decode_str($s)
{
  $a1 = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "W", "G", "X", "M", "H", "R", "U", "Z", "I", "D", "=", "N", "Q", "V", "B", "L");
  $a2 = array("b", "z", "a", "c", "l", "m", "e", "p", "s", "J", "x", "d", "f", "t", "i", "o", "Y", "k", "n", "g", "r", "y", "T", "w", "u", "v");

  $result = '';
  for($i = 0; $i < strlen($s); $i++) {
    $result .= decode_char($s[$i], $a1, $a2);
  }
  $result = base64_decode($result);
  return $result;
}

Here's what I've got so far:
public string decode_str(string s)
{
       string[] a1 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "W", "G", "X", "M", "H", "R", "U", "Z", "I", "D", "=", "N", "Q", "V", "B", "L" };
       string[] a2 = { "b", "z", "a", "c", "l", "m", "e", "p", "s", "J", "x", "d", "f", "t", "i", "o", "Y", "k", "n", "g", "r", "y", "T", "w", "u", "v" };

       string result = "";
       for (int i = 0; i < s.Length; i++)
       {
           result += decode_char(s[i], a1, a2);
       }

           return result;
}

Can someone help with converting decode_char?
Thank you for fast answers. I already did it myself but using strings and not chars, so I will accept an answer tomorrow when I will revise my code.

A: This should be the equivalent of decode_char
public char decodeChar(char c, string[] a, string[] a2)
{
    for(var j = 0; j < a.Length; j++)
    {
        if(c == a1[j])
            return a2[j];
        if(c == a2[j])
            return a1[j];
    }
    return c;
}

A: I'll take a stab at rewriting decode_char; it's not that difficult...
public char decode_char(char input, string[] array1, string[] array2)
{
  var result = input;
  for(var j = 0; j < array1.Length; j++)
  {
    if (input == array1[j][0]) {
      result = array2[j][0];
      break;
    }
    if (input == array2[j][0]) {
      result = array1[j][0];
      break;
    }
  }
  return result;
}

This will work with what you have already. HOWEVER, I see room for improvement. In C#, there is a semantic difference between a char and a string[1]. If you define your arrays as arrays of characters instead of arrays of strings, they no longer have to be "two-dimensional"; you can simply refer to the index of the character instead of the index of the first character of the string at a given index.
You also generally shouldn't use += with strings in C#. Strings are immutable; one instance is created, and if it is changed a new instance is created and the reference held by the variable is moved to the new instance; the old instance then hangs around until GCed. The upshot is that each += operation creates a brand new string, all but one of which are almost immediately useless, which is a waste of memory. Instead, there is a class called StringBuilder which reduces this "thrashing" and economizes on memory:
Also, it's bad practice to define an empty string literal. That gets created as a constant, unique and separate from all other defined literals, again wasting memory. The String.Empty constant available on the String class is a centralized variable that represents the empty string literal.
Lastly, C# best practices say to name your variables descriptively. C, S, A1 and A2 are not great identifiers.
public string decode_str(string input)
{
       char[] array1 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'W', 'G', 'X', 'M', 'H', 'R', 'U', 'Z', 'I', 'D', '=', 'N', 'Q', 'V', 'B', 'L' };
       char[] array2 = { 'b', 'z', 'a', 'c', 'l', 'm', 'e', 'p', 's', 'J', 'x', 'd', 'f', 't', 'i', 'o', 'Y', 'k', 'n', 'g', 'r', 'y', 'T', 'w', 'u', 'v' };

       StringBuilder result = new StringBuilder(String.Empty);
       for (int i = 0; i < input.Length; i++)
       {
           result.Add(decode_char(input[i], array1, array2));
       }

       return result.ToString();
}

Lastly, C# has some extra tricks that PHP apparently does not which can make your decode_char function a bit more concise:
public char decode_char(char input, char[] array1, char[] array2)
{
  return array1.Contains(input)
     ? array2[array1.IndexOf(input)]
     : array2.Contains(input)
        ? array1[array2.IndexOf(input)];
        : input;
}

A: It's easy:
String DecodeChar(char c, string[] a1, string[] a2) {
  for(int i=0; i<a1.length; ++i) {
    if(a1[i] == c) return a2[i];
    if(a2[i] == c) return a1[i];
  }
  return c;
}

or:
String DecodeChar(char c, string[] a1, string[] a2) {
  var a1Id = Array.IndexOf(a1.ToCharArray(), c);
  var a2Id = Array.IndexOf(a2.ToCharArray(), c);
  if(a1Id != -1 && a1Id < a2Id) return a2[a1Id];
  if(a2Id != -1 && a2Id < a1Id) return a1[a1Id];
  return c;
}

A: Try with this:
char decode_char(char c, string a1, string a2)
{
    for (int i = 0; i < a1.Length; i++)
    {
        if (c == a1[i]) return a2[i];
        if (c == a2[i]) return a1[i];
    }
    return c;
}
string decode_str(string s)
{
    const string a1 = "0123456789WGXMHRUZID=NQVBL";
    const string a2 = "bzaclmepsJxdftioYkngryTwuv";
    StringBuilder sb = new StringBuilder();
    foreach (char c in s)
        sb.Append(decode_char(c, a1, a2));
    return DecodeFrom64(sb.ToString());
}
string DecodeFrom64(string encodedData)
{
    byte[] encBytes = Convert.FromBase64String(encodedData);
    return Text.Encoding.Unicode.GetString(encBytes);
}


text:
Q: Changing direction of D3 animation / transition? I've recently built a small heatmap whose individual cells appear through a fade-in one after another after the page is loaded:
https://codepen.io/ChrisBean/pen/KKwpmjb
The fade-in animation is triggered by setting the initial opacity value of the cells to 0
squares.transition()
    .duration(1000)
    .delay((_d, i) => i * 200)
    .style('opacity', 1);

As of now, the cells fade in from the bottom to the top column by column. I want them to fade in from left to right, row by row. This is the succession that I'm aiming at, quickly visualized with a pen drawing on a thinkpad:

Can anyone push me in the right direction of what to change in the transition trigger to change the direction?

A: There is no such a thing as the "direction of a transition" in D3. The whole issue here is that you're using the indices of the elements to set the delay. That being said, just change the order of the objects inside the data array, so the indices match the direction you want.
For instance:
data.sort(function(a,b){
    return myVars.indexOf(b.variable) - myVars.indexOf(a.variable) ||
        myGroups.indexOf(a.group) - myGroups.indexOf(b.group)
});

Here is the code with that change:

// set the dimensions and margins of the graph
const margin = {
  top: 0,
  right: 0,
  bottom: 0,
  left: 0,
};
const width = 400 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
// eslint-disable-next-line no-undef
const svg = d3.select('#my_dataviz')
  .append('svg')
  .attr('viewBox', '0 0 900 320')
  .append('g')
  .attr('transform',
    `translate(${margin.left},${margin.top})`);

// Labels of row and columns
const myGroups = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
const myVars = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v9', 'v10'];

// Build X scales and axis:
const x = d3.scaleBand()
  .range([0, width])
  .domain(myGroups)
  .padding(0.00);
svg.append('g')
  .attr('transform', `translate(0,${height})`)
  .call(d3.axisBottom(x));

// Build X scales and axis:
const y = d3.scaleBand()
  .range([height, 0])
  .domain(myVars)
  .padding(0.00);
svg.append('g')
  .call(d3.axisLeft(y));

// Build color scale
const myColor = d3.scaleLinear()
  .range(['white', '#363636'])
  .domain([1, 100]);

// Read the data
d3.csv('https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/heatmap_data.csv', (data) => {
  data.sort(function(a, b) {
    return myVars.indexOf(b.variable) - myVars.indexOf(a.variable) || myGroups.indexOf(a.group) - myGroups.indexOf(b.group)
  });
  // create a tooltip
  const tooltip = d3.select('#my_dataviz')
    .append('div')
    .style('opacity', 0)
    .attr('class', 'tooltip')
    .style('background-color', 'white')
    .style('border', 'solid')
    .style('border-width', '2px')
    .style('border-radius', '5px')
    .style('padding', '5px');

  // Three function that change the tooltip when user hover / move / leave a cell
  const mouseover = function() {
    tooltip.style('opacity', 1);
  };
  const mousemove = function(d) {
    tooltip
      .html(`Client Branch:${d.value}

             Project:
`)
      .style('left', `${d3.mouse(this)[0] + 70}px`)
      .style('top', `${d3.mouse(this)[1]}px`);
  };
  const mouseleave = function() {
    tooltip.style('opacity', 0);
  };

  // add the squares
  const squares = svg.selectAll()
    .data(data, (d) => `${d.group}:${d.variable}`)
    .enter()
    .append('rect')
    .attr('x', (d) => x(d.group))
    .attr('y', (d) => y(d.variable))
    .attr('width', x.bandwidth())
    .attr('height', y.bandwidth())
    .style('fill', (d) => myColor(d.value))
    .style('opacity', 0)
    .on('mouseover', mouseover)
    .on('mousemove', mousemove)
    .on('mouseleave', mouseleave);

  squares.transition()
    .duration(1000)
    .delay((_d, i) => i * 200)
    .style('opacity', 1);
});
<!DOCTYPE html>
<meta charset="utf-8">


text:
Q: Preventing excessive downcasting I have a class TreeNode, a class LeafNode which extends TreeNode and a class ParentNode that extends TreeNode as well. In the class ParentNode I have a method getChild that returns a TreeNode.
Whenever I call getChild successively, I have to do a bunch of downcasting.
LeafNode myLeafNode = (LeafNode) ((ParentNode) this.getChild(id1)).getChild(id2)
Is there a way I can avoid all this downcasting without changing the inheritance structure of my program?

A: You should only extend a class if the child has specific logic inappropriate for the parent.
I'm not sure why you need anything but "Node".  The "Root" node acts exactly like every other node, and if you assume that the left and right child nodes can be empty, a "Leaf" acts exactly like a node (with two empty child nodes)
Just a piece of advice--it's nice to know about "extends" but be careful of over using it, I made a project much harder than it had to be once by over-using extends.  Most classes tend to have a very simple lineage or none at all.
Every time you think to extend an object I suggest you think about the is-a/has-a rule first and then even if it is a "is-a" try to consider containment anyway, if containment isn't much harder just use that.  In the long run it will make your life easier.

A: If the method getChild() is in the TreeNode class, then I don't think you need the cast to ParentNode.

A: If the methods you're trying to call (not only getChild() but also whatever you plan to do with the LeafNode once you find it) are defined in TreeNode, then you won't need to cast back and forth.  Even if some operations don't make sense for leaf nodes (or non-leaf nodes, whichever), you can define them with an empty implementation and then rely on your code only to only call the valid ones (assuming your code is able to do that).


text:
Q: Python regex to find nested parentheses outside double quotes I have an input string which contains parenthesis inside and outside double quotes.These parentheses can be nested. I want to strip off strings with parentheses present only outside of double quotes.
I tried this regex r'\((?:[^)(]|\((?:[^)(]|\([^)(]*\))*\))*\)'
This fetches everything that is enclosed within round brackets no matter inside or outside double quotes.
    import re
    input_string = '''"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is(strip this (strip this also as it is outside double quotes))'''
    result = re.sub(r'\((?:[^)(]|\((?:[^)(]|\([^)(]*\))*\))*\)','', input_string)
    print result

The actual output I am getting is:
'"Hello World "  anything outside round brackets should remain as is'

I expect the output to be:
'"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is'

A: If your parentheses are balanced (with help of this answer):
import re
input_string = '''"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is(strip this (strip this also as it is outside double quotes) xxx) Also remain this (String this)'''

def strip_parentheses(g):
    n = 1  # run at least once
    while n:
        g, n = re.subn(r'\([^()]*\)', '', g)  # remove non-nested/flat balanced parts
    return g

s = re.sub(r'".*?"|([^"]*)', lambda g: strip_parentheses(g.group(1)) if g.group(1) else g.group(), input_string)

print(s)

Prints:
"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is Also remain this

EDIT Running some test-cases:
import re
input_string = '''"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is(strip this (strip this also as it is outside double quotes) xxx) Also remain this ((String this))'''

test_cases = ['Normal string (strip this)',
'"Normal string (dont strip this)"',
'"Normal string (dont strip this)" but (strip this)',
'"Normal string (dont strip this)" but (strip this) and (strip this)',
'"Normal string (dont strip this)" but (strip this) and (strip this) but "dont strip (this)"',
'"Normal string (dont strip this)" but ((strip this) and this) and (strip (strip this))',
'"Normal string (dont strip this)" but ((strip this) but "remain this (xxx)") ',
]

def strip_parentheses(g):
    n = 1  # run at least once
    while n:
        g, n = re.subn(r'\([^()]*\)', '', g)  # remove non-nested/flat balanced parts
    return g

def my_strip(s):
    return re.sub(r'".*?"|([^"]*)', lambda g: strip_parentheses(g.group(1)) if g.group(1) else g.group(), s)

for test in test_cases:
    print(test)
    print(my_strip(test))
    print()

Prints:
Normal string (strip this)
Normal string

"Normal string (dont strip this)"
"Normal string (dont strip this)"

"Normal string (dont strip this)" but (strip this)
"Normal string (dont strip this)" but

"Normal string (dont strip this)" but (strip this) and (strip this)
"Normal string (dont strip this)" but  and

"Normal string (dont strip this)" but (strip this) and (strip this) but "dont strip (this)"
"Normal string (dont strip this)" but  and  but "dont strip (this)"

"Normal string (dont strip this)" but ((strip this) and this) and (strip (strip this))
"Normal string (dont strip this)" but  and

"Normal string (dont strip this)" but ((strip this) but "remain this (xxx)")
"Normal string (dont strip this)" but ( but "remain this (xxx)")

EDIT: To remove all (), even with quoted strings inside them:
import re
input_string = '''"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is(strip this (strip this also as it is outside double quotes) xxx) Also remain this ((String this))'''

test_cases = ['"Normal string (dont strip this)" but (strip this) and (strip this) but "dont strip (this)"',
'"Normal string (dont strip this)" but ((strip this) and this) and (strip (strip this))',
'"Normal string (dont strip this)" but ((strip this) but "remain this (xxx)") ',
]

def strip_parentheses(g):
    n = 1  # run at least once
    while n:
        g, n = re.subn(r'\([^()]*\)', '', g)  # remove non-nested/flat balanced parts
    return g

def my_strip(s):
    s = re.sub(r'".*?"|([^"]*)', lambda g: strip_parentheses(g.group(1)) if g.group(1) else g.group(), s)
    return re.sub(r'".*?"|(\(.*\))', lambda g: '' if g.group(1) else g.group(), s)

for test in test_cases:
    print(test)
    print(my_strip(test))
    print()

Prints:
"Normal string (dont strip this)" but (strip this) and (strip this) but "dont strip (this)"
"Normal string (dont strip this)" but  and  but "dont strip (this)"

"Normal string (dont strip this)" but ((strip this) and this) and (strip (strip this))
"Normal string (dont strip this)" but  and

"Normal string (dont strip this)" but ((strip this) but "remain this (xxx)")
"Normal string (dont strip this)" but

A: Using regex instead of re, you could go with
"[^"]+"(*SKIP)(*FAIL) # ignore anything between double quotes
|                     # or
\(
    (?:[^()]*|(?R))+  # match nested parentheses
\)

See a demo on regex101.com.

In Python this could be

import regex as re

data = """"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is(strip this (strip this also as it is outside double quotes))"""

rx = re.compile(r'''
    "[^"]+"(*SKIP)(*FAIL)
    |
    \(
        (?:[^()]*|(?R))+
    \)''', re.VERBOSE)

data = rx.sub("", data)
print(data)

Yielding
"Hello World (Don't want to strip this (also not this))"  anything outside round brackets should remain as is


text:
Q: template operator << getting round In library code I have:
class VeryStrictClass
{
public:
    template<typename UNKNOWN_TYPE>
    VeryStrictClass& operator<<(const UNKNOWN_TYPE & value) {
        struct can_not_format_unknown_type {};
        can_not_format_unknown_type error = value;
    }
};

no way to reimplement it.
This forbids to declare functions like
template <typename MsgType>
/*check toString existance*/
VeryStrictClass& operator << (VeryStrictClass& o, const MsgType* msg)
{
  BOOST_ASSERT(msg != NULL);
  return o << msg->toString();
}

where toString() isn't virtual.
I have lots of similar classes to be put into VeryStrictClass. Is there any way to get round this constraint?

A: You could use template specialization for you own types of messages.
class foo {};

class bar : public foo {}

template <>
VeryStrictClass& VeryStrictClass::operator<< <foo> (const foo & bar) {
    // something something
    return *this;
}

VeryStrictClass v;
bar* b = new bar;
foo* f = new foo;
v << *foo << *((foo*)bar);

not sure if this works though
EdiT: added some polymorphism
Edit: otherwise you can not.


text:
Q: How to return image stream and text as JSON response from Python Flask API From a Python Flask API, I want to return an image stream and also some text in a single API response.
Something like this:
{
  'Status' : 'Success',
  'message': message,
  'ImageBytes': imageBytes
}

Also, I would like to know what would be the best format to use for imageBytes, so that the client applications (Java / JQuery) can parse and reconstruct the image.
If the above approach is not correct, please suggest a better approach.

A: The following worked for me:
import io
from base64 import encodebytes
from PIL import Image
# from flask import jsonify

def get_response_image(image_path):
    pil_img = Image.open(image_path, mode='r') # reads the PIL image
    byte_arr = io.BytesIO()
    pil_img.save(byte_arr, format='PNG') # convert the PIL image to byte array
    encoded_img = encodebytes(byte_arr.getvalue()).decode('ascii') # encode as base64
    return encoded_img

# server side code
image_path = 'images/test.png' # point to your image location
encoded_img = get_response_image(image_path)
my_message = 'here is my message' # create your message as per your need
response =  { 'Status' : 'Success', 'message': my_message , 'ImageBytes': encoded_img}
# return jsonify(response) # send the result to client

A: I used the following utility function to convert the image into ByteArry and returned as one of the parameter in my JSON output.
def getImageBytes(filePath):
img = Image.open(filePath, mode='r')
imgByteArr = io.BytesIO()
imgByteArr = imgByteArr.getvalue()
imgByteArr = base64.encodebytes(imgByteArr).decode('ascii')

return imgByteArr


text:
Q: DynamoDB Stream to Lambda slow/unsuable I've connected a lambda to a DyDB table via a stream. When a record is written to the table, it triggers the lambda. The traffic is very bursty, so nothing might happen for a while, then I'll write several thousand records.
What I'm seeing is a few lambda instances will be triggered, but not enough to handle the burst. Then at random times, the number of lambda instances will jump an order of magnitude or two (from 2 to 90 or more), and it will catch up. The problem is the jump might not occur for 30 minutes or more.
I'm seeing the records written to the table very quickly (seconds). The processing of 20 records by the lambda shouldn't take more than 2 minutes. It seems like the lambdas are spending most of their time sitting around waiting for records to show up. The record key for the table is a GUID.
Things I've tried

*

*Playing with the number of records to make sure there's no lambda timeouts (20 seems to be conservative, but 100 causes timeouts)

*Moving the lambda to a different subnet

*Batching the writes to the table (~500-1000 records in a batch)

*Breaking up the writes in hopes it would trigger more lambdas (~20-100 records in a batch)

*Increasing the lambda memory to the max (3GB)

*Reducing memory to be larger than used (1GB, 300Mb used)

Is there a better pattern to be using? Should I skip the stream and just write SNS messages? I don't care about order, but would prefer to not run the job more than once.

A: So here's what I found out.
It looks like the problem is contention on the DynamoDB stream by the lambda instances.
My solution was to skip the DynamoDB stream and not use it, and post to an SNS queue. The lambdas pick up the messages, and scale much better. Times have gone from hours to seconds.


text:
Q: $\sum_{n=1}^\infty\frac{z^2}{1+n^2z^2}$ converges to analytic function
For which $z$ does $\sum_{n=1}^\infty\dfrac{z^2}{1+n^2z^2}$ converge to an analytic function? What are its poles?

I think the poles should be $\pm\dfrac{i}{n}$, since those are the values at which one of the denominators disappear. I'm not sure about the converging to analytic function part

A: This sum have closed form. As it was proved earlier
$$
f(w)=\sum\limits_{n=1}^{\infty}\frac{1}{n^2-w^2}=\frac{1}{2w}\left(\frac{1}{w}-\pi\cot(\pi z)\right)
$$
so
$$
\sum_{n=1}^\infty\dfrac{z^2}{1+n^2z^2}=f(i/z)=-\frac{1}{2} z \left(z-\pi  \coth \left(\frac{\pi }{z}\right)\right)
$$
So the question simplifies significantly


text:
Q: Adding RedirectAttributes parameter causes "Model has no value for key" exception in Spring MVC controller method I have the following Spring MVC controller method:
@RequestMapping(value = "/tournament/{id}/set-format", method = RequestMethod.POST)
public String processSetTournamentFormat(Model model,
                                         @ModelAttribute("formatSettings") FormatSettings formatSettings,
                                         @AuthenticationPrincipal UserAccount currentUser,
                                         @PathVariable("id") int tournamentId,
                                         RedirectAttributes redirectAttributes)
        throws TournamentAccessDenied, TournamentNotFoundException, ModifyngOngoingTournamentException {

    Tournament currentTournament = tournamentManagementService.findTournamentById(tournamentId);

    tournamentManagementService.setTournamentFormat(currentTournament, formatSettings);

    model.addAttribute("tournamentId", currentTournament.getId());

    return "redirect:/tournament/{tournamentId}/setup";
}

When I click submit button in corresponding form I get an exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Model has no value for key 'tournamentId'
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
[...]

Everything works well when I remove redirectAttributes parameter but I need it to add flash attributes in case of any error. I try to understand why URL template doesn't work. It is also ok when (without removing redirectAttributes) I just use:
return "redirect:/tournament/" + currentTournament.getId() + "/setup";

My Spring version is 4.1.7

A: There's no point providing both Model and RedirectAttributes parameters in your handler method. RedirectAttributes can do everything Model can do and more.
The actual issue is the following:

*

*The Spring MVC request handling process uses a single ModelAndViewContainer which holds a reference to a Model.

*To provide a Model argument to your handler method, Spring MVC returns the default Model in the ModelAndViewContainer.

*To provide a RedirectAttributes argument to your handle method, Spring MVC creates a new instance and uses it to overwrite the default ModelAndViewContainer Model.

*When you add the attribute to the Model, the ModelAndViewContainer won't have access to it and therefore neither will component that process the redirect: view name.

Choose one. You don't need both.
redirectAttributes.addAttribute("tournamentId", currentTournament.getId());


text:
Q: Formatting BigDecimal to Locale specific Currency String using Locale(languageCode, countryCode) I am converting a BigDecimal currency value to a locale specific Currency Format using the Locale(languageCode, countryCode) constructor as shown in the code below
public static String formatCurrency(BigDecimal amount, String languageCode, String countryCode) {

    Format format = NumberFormat.getCurrencyInstance(new Locale(languageCode, countryCode));
    String formattedAmount = format.format(amount);
    logger.debug("Orginal Amount {} and Formatted Amount {}", amount, formattedAmount);
    return formattedAmount;
}

Now as per the excellent resource at Oracle Docs

The runtime environment has no requirement that all locales be supported equally by every locale-sensitive class. Every locale-sensitive class implements its own support for a set of locales, and that set can be different from class to class. For example, a number-format class can support a different set of locales than can a date-format class.

Since my languageCode and countryCode are entered by User, how do I handle the situation (or rather how does the NumberFormat.getCurrencyInstance method handle it) when a user enters wrong input like say, languageCode = de and countryCode = US.
Does it default to some Locale ? How does one handle this situation.
Thanks.

A: Based on suggestion from @artie, I am using LocaleUtil.isAvailableLocale to check if the locale exists. If it is an invalid Locale I dafult it to en_US. That solves the problem to some extent.
However, it still doesn't solve the problem of checking if the NumberFormat supports that Locale. Will accept any other answer that solves this issue.
   public static String formatCurrency(BigDecimal amount, String languageCode, String countryCode) {

        Locale locale = new Locale(languageCode, countryCode);
        if (!LocaleUtils.isAvailableLocale(locale)) {
            locale = new Locale("en", "US");
        }
        Format format = NumberFormat.getCurrencyInstance(locale);
        String formattedAmount = format.format(amount);
        logger.debug("Orginal Amount {} and Formatted Amount {}", amount, formattedAmount);
        return formattedAmount;
    }


text:
Q: Why the polarity of V source changed ? (Thevenin) I don't understand why the polarity of the voltage source in the Thevenin equivalent circuit in the left corner is changed...

A: Using the ground symbol as a zero-volt reference point from fig.9.46:
Point b is one-third of E.
Point a is one-quarter of E.
So point b is at a higher potential than point a.
Now on to the Thevenin equivalent circuit (fig. 9.47). The Thevenin circuit doesn't use ground as a reference point. It is perhaps a mistake to show the ground symbol in fig. 9.47, because it may have confused you. The Thevenin model must appear between point a and point b of fig.9.46.
Fig. 9.47 correctly shows point b at a higher potential than point a.

A: glen_geek is right about voltages, the "b" voltage is 6V higher than "a" point. However the ground is not a mistake. The 3||6 Ohms branch gives an equivalent of 2 Ohms and the 4||12 Ohms give a parallel equivalent of 3 Ohms. That's the reason for the 5 Ohm resistor. If you look for the lowest impedance to the ground, from "b" to ground is only 2 Ohms while from "a" to ground is 3 Ohms. The ground is definitely on the "b" side.


text:
Q: Working with group cosets in MAGMA When working with group cosets in MAGMA is there a way of treating the cosets as subsets of the overlying group. Specifically I have a group    $G$    and subgroups    $H$     and     $K$   . I wish to look at the intersection of a pair of cosets     $Hh$    and    $Kk$    for some     $h,k\in G$    , but am unable to perform such operations in MAGMA when they are considered as cosets.

A: As far as I can see, the only way to do that directly with cosets $ C1$ and $C2$ of $G$ is
$\{ x :  x\ {\rm in}\  G\ |\ x\ {\rm in}\ C1\ {\rm and}\ x\ {\rm in}\ C2 \}$
which looks very inefficient, because it is iterating over all of $G$.
I would suggest first find a right transversal $T$ of $H \cap K$ in $H$, and then search through $T$ looking for an element $t \in T$ with $thk^{-1} \in K$. If you find such a $t$, then the intersection is the coset $(H \cap K)th$, and otherwise it is empty.

A: Well, this is trivial in GAP.
Here is an example:
gap> G:=SymmetricGroup(7);;
gap> H:=Stabilizer(G,1);;
gap> K:=SylowSubgroup(G,2);;
gap> c1:=RightCoset(H,(1,2));;
gap> c2:=RightCoset(K,(1,2,3));;
gap> Intersection(c1,c2);
[ (1,2,3), (1,2,3)(5,6), (1,2,3,4), (1,2,3,4)(5,6) ]
gap>

By the way, GAP is free, unlike Magma...


text:
Q: Full text timed out Exception I'm using freetext in my query but I encounter this error just the first time i run the query. what's wrong?
I didn't have this problem in SQL server 2005.
I just have 10 records in my table.
Word breaking timed out for the full-text query string. This can happen if the wordbreaker took a long time to process the full-text query string, or if a large number of queries are running on the server. Try running the query again under a lighter load.

I'm using SQL server 2008 version 10.0.1600.22 ((SQL_PreRelease).080709-1414 ).
I have read about wordbreaking dll in the other forums but I don't kow what to do.
this is a simplified code of  my query:
select tbl_Workshops.Name as WorkshopName
from tbl_Workshops
 where (@Creteria='""' or freetext(tbl_Workshops.Name,@Creteria))

A: The word breaker may be trying to verify signature, and unable to reach the service.
Try...
SELECT FULLTEXTSERVICEPROPERTY('VerifySignature');
GO
-- if 1, then turn off verify_signature
EXEC sp_fulltext_service 'verify_signature', 0;
GO

A: Make sure that the service called SQL Full-text Filter Daemon Launcher (INSTANCE) is running and logs on using the same credentials as SQL Server (INSTANCE)


text:
Q: Четное число в javascript делится на другое число без остатка Есть некий промежуток, который задается через prompt. Для этого промежутка нужно вывести все четные числа, которые делятся без остатка на 3.
Как прописать в if второе условие, что "i % 3 == 0" ?

for (i = firstNumber; i <= secondNumber; i++)
if (i % 2 == 0) {
alert (i);
}

A:

for (i = 1; i <= 20; i++) {
  if (i % 2 == 0 && i % 3 == 0) {
    console.log(i);
  }
}


text:
Q: Could you explain this kind of future? "Clare wants to be a doctor when she is older." Could you explain this kind of future, please?

Clare wants to be a doctor when she is older

Why isn't there are any use of will or going to?

A: I believe it was answered in the comments but I'll give you a clearer example here.

Clare wants to be a doctor when she is older.

This is asserting Clare's current desire.

Clare will want to be a doctor when she is older.

This is asserting that in the future Clare will have this desire.

A: Since you are from Peru, I expect you are wondering why the sentence is not constructed the way it is in Spanish.

Clare quiere ser una doctora cuando sea grande.

which in English we say as...

Clare wants to be a doctor when she is older.

The verb in the first clause indicates a desire at the present moment, and is the same as in Spanish.
However, English does not have a subjunctive to use with time words.

...cuando sea grande

In clauses with time words (when, until, after) we usually use the present tense to talk about the future.
ex.

We will talk about it when I come home.
Don't do anything until we talk.
You can make a decision after we discuss it.

It follows the same pattern as if and unless clauses when talking about the future.

I will take care of it if you agree.
I won't buy it unless you like it.

Will is not usually used with time words or if.
"Going to" is usually used to express intention, or a prediction.

This weekend I'm going to the beach.
It looks like it is going to rain.

We could also say...

Clare is going to be a Doctor when she is older.

...to indicate her intention. Or we could also say...

Clare would like to be a Doctor when she is older.

...to indicate her current desire for the future, but the clauses with time words stay the same as the above examples.


text:
Q: How to add Script in the Page  dynamically I use asp.net 4 and c#.
I have a Web User Control inside a Web From page.
When I include the Web User Control I would like also include programmatically some script within the  tags for the final generated page.
Any idea how to do it?
Maybe ScriptManager could help on this?
Please provide me a sample of code I'm pretty new at developing thanks for your time on this!

A: Peter's answer will add to the page, but not the head element. Take a look at this article:
http://weblogs.asp.net/johnkatsiotis/archive/2008/08/08/add-scripts-to-head-dynamically.aspx
It provides a nice clean way to add a script to the head element using an extension method.

A: I realize that this is an old question, but there is a much simpler way.
Try This:
Page.Header.Controls.Add(
    new LiteralControl(
        "<script>alert('Literal Added to <Head>.');</script>"
    )
);

If you want to add the script at a particular index of the <head> you can use
AddAt(index, new LiteralControl(...)) where index 0 equals the top of the <head>
Also, joelmdev mentioned in a comment you need to add runat="server" in your head tag e.g. <head id="head1" runat="server">

A: Take a look at RegisterClientScriptBlock of the ClientScriptManager.
From MSDN:
...
ClientScriptManager cs = Page.ClientScript;

// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
  StringBuilder csText = new StringBuilder();
  csText.Append("<script type=\"text/javascript\"> function DoClick() {");
  csText.Append("Form1.Message.value='Text from client script.'} </");
  csText.Append("script>");
  cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
...


text:
Q: Use Multiple Model In One View .net Mvc yah there are many way to use multiple model in one view. and i pick one option from there => and is create a extra class and add those multiple class into that class =>
the combined class =>
public class combo
{
    public IEnumerable<User> User { get; set; }
    public IEnumerable<StudentRegistrationViewModel> StudentRegistrationViewModel { get; set; }
    public IEnumerable<StudentFullRegistrationViewModel> StudentFullRegistrationViewModel { get; set; }
}

i did like =>(my model)
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;

    namespace TSMS_Atp_2_Final_Project.Models.Com.Tsms
    {
        public class User
        {
            [Key]
            [Required(AllowEmptyStrings = false, ErrorMessage = "User Id Is Required!")]
            [MaxLength(12, ErrorMessage = "You Have Exceed The Max length Of User ID which is [12] character!")]
            [RegularExpression("[1-3]{2}-[0-9]{5}-[123]{1}|[1-3]{2}-[0-9]{7}-[123]{1}", ErrorMessage = "Invalid Id,It should [xx]-[xxxxx]-[x] or [xx]-[xxxxxxx]-[x]!")]
            [Display(Name = "User ID")]
            public string UserId { get; set; }
            ///
            /// ////////
            ///
            [Required(AllowEmptyStrings = false, ErrorMessage = "Password Is Required!")]
            [MaxLength(20, ErrorMessage = "Password Max Length Is 20 Character!")]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            public string password { get; set; }
            ///
            /// ////////
            ///
            [MaxLength(100, ErrorMessage = "The Max Length For User Level Is 100 Character!")]
            [RegularExpression("^(?:admin|Admin|student|Student)$", ErrorMessage = "Invalid User Level!")]
            [Display(Name = "User Level")]
            public string level { get; set; }
            ///
            /// /////////
            ///
            [NotMapped]
            [Display(Name="Remember Me")]
            public bool RememberMe { get; set; }

            //relationship with other table----
            public List<UserDetail> UserDetail { get; set; }
        }

        public class UserPassViewModel
        {
            [Required(AllowEmptyStrings = false, ErrorMessage = "Old Password Is Required!")]
            [MaxLength(20, ErrorMessage = "Old Password Max Length Is 20 Character!")]
            [DataType(DataType.Password)]
            [Display(Name = "Old Password")]
            public string Oldpassword { get; set; }
            ///
            /// ///////
            ///
            [Required(AllowEmptyStrings = false, ErrorMessage = "New Password Is Required!")]
            [MaxLength(20, ErrorMessage = "New Password Max Length Is 20 Character!")]
            [DataType(DataType.Password)]
            [Display(Name = "New Password")]
            public string Newpassword { get; set; }
            ///
            /// ////////
            ///
            [Compare("Newpassword", ErrorMessage = "New Password And Confirm Password Is Not Matched!")]
            [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm Password Is Required!")]
            [MaxLength(20, ErrorMessage = "Confirm Password Max Length Is 20 Character!")]
            [DataType(DataType.Password)]
            [Display(Name = "Confirm Password")]
            public string Confirmpassword { get; set; }
        }

        public class StudentRegistrationViewModel
        {
            [Required(AllowEmptyStrings = false, ErrorMessage = "First Name IS Required!")]
            [MaxLength(50, ErrorMessage = "The Max Length Of First Name Is 50 Character!")]
            [DataType(DataType.Text, ErrorMessage = "Invalid First Name!")]
            [Display(Name="First Name")]
            public string FirstName { get; set; }
            ///
            /// ///////
            ///
            [Required(AllowEmptyStrings = false, ErrorMessage = "Last Name Is Required!")]
            [MaxLength(50, ErrorMessage = "The Max Length Of Last Name is 50 Character!")]
            [DataType(DataType.Text, ErrorMessage = "Invalid Last Name!")]
            [Display(Name = "Last Name")]
            public string LastName { get; set; }
            ///
            /// //////
            ///
            [Required(AllowEmptyStrings = false, ErrorMessage = "Full Name Is Required!")]
            [MaxLength(100, ErrorMessage = "The Max Length Of Full Name Is 100 Character!")]
            [DataType(DataType.Text, ErrorMessage = "Invalid Full Name!")]
            [Display(Name = "Full Name")]
            public string FullName { get; set; }
            ///
            /// /////
            ///
            [Required(AllowEmptyStrings = false, ErrorMessage = "Email Is Required!")]
            [EmailAddress(ErrorMessage = "Invalid Email Address!")]
            [Display(Name = "Email Address")]
            public string Email { get; set; }
            ///
            /// //////
            ///
            [Required(AllowEmptyStrings = false, ErrorMessage = "Password Is Required!")]
            [MaxLength(20, ErrorMessage = "Password Max Length Is 20 Character!")]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            public string Password { get; set; }
            ///
            /// /////////
            ///
            [Compare("Password", ErrorMessage = "Password And Confirm Password Is Not Matched!")]
            [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm Password Is Required!")]
            [MaxLength(20, ErrorMessage = "Confirm Password Max Length Is 20 Character!")]
            [DataType(DataType.Password)]
            [Display(Name = "Confirm Password")]
            public string ConfirmPassword { get; set; }
        }

        public class StudentFullRegistrationViewModel
        {
            public String MyProperty { get; set; }
        }

        public class combo
        {
            public IEnumerable<User> User { get; set; }
            public IEnumerable<StudentRegistrationViewModel> StudentRegistrationViewModel { get; set; }
            public IEnumerable<StudentFullRegistrationViewModel> StudentFullRegistrationViewModel { get; set; }
        }
    }

and my view =>
    @using something
    @model combo

    @{
        ViewBag.Title = "User Login";
    }

    @if (ViewBag.Message != null)
    {
        @section Scripts{

        }
    }

                                Login

                                Register

                                @*login form*@
                                <form id="login-form" method="post" role="form" style="display: block;">
                                    @Html.AntiForgeryToken()
                                    @Html.ValidationSummary(true, null, new { @class = "text-danger" })

                                        @Html.TextBoxFor(model => model.StudentFullRegistrationViewModel., new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.UserId) })
                                        @Html.ValidationMessageFor(model => model.UserId, null, new { @class = "text-danger" })

                                        @Html.PasswordFor(model => model.password, new { @class = "form-control", @placeholder = Html.DisplayNameFor(model => model.password) })
                                        @Html.ValidationMessageFor(model => model.password, null, new { @class = "text-danger" })

                                        @Html.CheckBoxFor(model => model.RememberMe, new { @tabindex = "3" })
                                        @Html.LabelFor(model => model.RememberMe)

                                                <input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-login" value="Log In">

                                                    Forgot Password?

                                </form>
                                @*registration form*@
                                <form id="register-form" action="" method="post" role="form" style="display: none;">

                                        @*@Html.TextBoxFor(mode => mode.body, new { @style = "border-radius:3px;", @class = "form-control", @id = "VendorDetails", @placeholder = Html.DisplayNameFor(model => model.body), @autocomplete = "off" })
                                        @Html.ValidationMessageFor(model => model.body, null, new { @class = "text-danger" })*@

                                       last name

                                        full name
                                        @*<input type="email" name="email" id="email" tabindex="1" class="form-control" placeholder="Email Address" value="">*@

                                        email
                                        @*<input type="email" name="email" id="email" tabindex="1" class="form-control" placeholder="Email Address" value="">*@

                                        password
                                        @*<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">*@

                                        confirm password
                                        @*<input type="password" name="confirm-password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password">*@

                                                <input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">

                                </form>

but problem is its showing some error like =>

the fist one above picture is giving me error and thats why i havent change all =>(and also not xhowing me intellisense)=>

i also try =>
public class combo
{
    public User User { get; set; }
    public StudentRegistrationViewModel StudentRegistrationViewModel { get; set; }
    public StudentFullRegistrationViewModel StudentFullRegistrationViewModel { get; set; }
}

thts one also not working .please help me?

A: this is why your combo has member user is IEnumerable of Users
 public IEnumerable<User> User { get; set; }

so you have more than one user which cannot have only single control to manipulate them (all your users)
so if your need is to have single user just change your class definition to
 public User User { get; set; }

or if you are in need to have multiple user objects so use foreach and bind each of your user object to single control


text:
Q: Проблема с геокодированием при получении адреса с csv файла через pandas Есть список адресов(.csv) для которых нужно вытащить координаты
Скрипт выглядит следующим образом
import requests
import json
import pandas as pd
df = pd.read_csv(r'D:\Arcgis\TATARS.CSV',delimiter=';')
for da in df.address:
    r = requests.get('http://search.maps.sputnik.ru/search/addr?q=da')
    data = (r.json()['result']['address'][0]['features'][0]['geometry']['geometries'][0]['coordinates'])
    print (data)

При запуске выдаёт следующее
[-14.900021, 12.100035] неправильные данные
Если вместо da вставлять адрес то выгрузка работает нормально
r = requests.get('http://search.maps.sputnik.ru/search/addr?q=Респ. Татарстан, р-н. Агрызский, г. Агрыз, ул. Азиатская, д. 47')

Выдаёт
[52.9944, 56.511395]
Проверил
df = pd.read_csv(r'D:\Arcgis\TATARS.CSV',delimiter=';')
print (df.address[1])

Выдаёт правильный адрес Респ. Татарстан, р-н. Агрызский, г. Агрыз, ул. Азиатская, д. 47
В чем может быть косяк ?

A: import requests
import json
import pandas as pd
df = pd.read_csv(r'D:\Arcgis\TATARS.CSV',delimiter=';')
for da in df.address:
    r = requests.get('http://search.maps.sputnik.ru/search/addr?q='da)
    data = (r.json()['result']['address'][0]['features'][0]['geometry']['geometries'][0]['coordinates'])
    print (data)


text:
Q: Listing all nodes created for a time period, Drupal I'd like to get/create a list of ALL the nodes created during a time period?
Is there an easy way to do this (w/out creating a custom view and selecting by a time period)?
Is there a module that might already expose this?
I have a large amount of content that will get added to the system every night, and I want to be able to peruse this list; title, url, etc.

A: If you do not like Views, then your only option is to write a custom module. Need help with it? Just ask where are you stuck.


text:
Q: Method of separation of variables in a wave problem A guitar string of length $l$ is pulled at the point $x=\xi$ over a small distance $h$ and released. Find the deflection $u(x,t)$ of the string for $t>0$.

Initial conditions:
$u(0,t)=0$
$u(l,t)=0$
$u(x,0)=f(x)$
$\left.
\begin{array}{l}
\frac{l}{\xi}x & 0<x<\xi\\
\frac{h}{\xi}(l-x) & \xi<x<l
\end{array}
\right\}
=f(x)$
$u_t(x,0)=0$
$1$- Wave equation:
$\frac{\partial^2 u}{\partial x^2}=\frac{1}{c^2} \frac{\partial^2 u}{\partial t^2}$
$X''T=\frac{1}{c^2} XT''$
$\frac{X''}{X}=\frac{1}{c^2}\frac{T''}{T}=-m^2$ , where $-m^2$ is the separation constant.
$X''+Xm^2=0 \rightarrow X=A\cos{mx}+B\sin{mx}$
$T''+m^2c^2T=0 \rightarrow T=C\cos{mct}+D\sin{mct}$
Applying initial conditions I get $m=\frac{n\pi}{l}$
Further, $u(x,t)=C\sin{mct}.B\cos{mx}$
By superposition,
$u(x,t)=\sum^{\infty}_{n=1} E_n \sin{\frac{n\pi x}{l}}\cos{\frac{n\pi c t}{l}}$
Finding $E_n$:
$E_n=\frac{2}{l}\int^{\xi}_{0}\frac{h}{\xi} x \sin{\frac{n \pi}{l}x$ dx+ \frac{2}{l}\int^l_[\xi} \int ^l_{xi} \frac{h}{\xi}(l-x)\sin{n\pi}{l}x$ $dx$
$=\frac{4h}{\xi n^2\pi^2}\sin {\frac{n\pi}{l}}-4h\cos{\frac{n\pi\xi}{l}}+\frac{2h}{n\pi}\cos{\frac{n\pi\xi}{l}}$
But that is not the answer.

A: The initial displacement function $f$ should be $0$ at $x=0$ and $x=l$, and should be $h$ at $x=\xi$, and it should be continuous. So your displacement function should be
$$
        f(x) = \left\{\begin{array}{ll}
                          \frac{hx}{\xi}, & 0 \le x \le \xi, \\
                          \frac{h(l-x)}{(l-\xi)}, & \xi \le x \le l.
                      \end{array} \right.
$$
Then, when you compute the Fourier coefficients, you can use
$$
     f(0)=0=f(l), \\
     f'(x) = \left\{\begin{array}{ll}
                          \frac{h}{\xi}, & 0 \le x \le \xi, \\
                          -\frac{h}{(l-\xi)}, & \xi \le x \le l,
                      \end{array} \right.
$$
and use integration by parts to evaluate the Fourier coefficients of $f$:
\begin{align}
      E_n & =\frac{2}{l}\int_{0}^{l}\sin\left(\frac{n\pi x}{l}\right)f(x)dx \\
  & = \frac{2}{l}\cdot\frac{l}{n\pi}\int_{0}^{l}\cos\left(\frac{n\pi x}{l}\right)f'(x)dx \\
 & = \frac{2}{n\pi}\left[\int_{0}^{\xi}\cos\left(\frac{n\pi x}{l}\right)dx\frac{h}{\xi}-\int_{\xi}^{l}\cos\left(\frac{n\pi x}{l}\right)dx\frac{h}{l-\xi}\right] \\
 & = \frac{2}{n\pi}\frac{l}{n\pi}\left[\sin\left(\frac{n\pi\xi}{l}\right)\frac{h}{\xi}+\sin\left(\frac{n\pi\xi}{l}\right)\frac{h}{l-\xi}\right] \\
 & = \frac{2l}{n^2\pi^2}\sin\left(\frac{n\pi\xi}{l}\right)\frac{hl}{\xi(l-\xi)} \\
 & = \frac{2hl^2}{n^2\pi^2\xi(l-\xi)}\sin\left(\frac{n\pi\xi}{l}\right).
\end{align}


text:
Q: Estimating the Average and Standard Deviation of a Population based on a Sample with Missing Data with Known Ranks I need a way to shows me how the parameters of PDF, log-normal in this case, can be estimated based on a set with missing data points at the tail end of a sample.
For example, Consider we had 20 numbers with specified μ and σ, and then missed two largest number of them. How do we can estimate the mean (μ) and standard deviation (σ) of these 20 numbers with only 18 available numbers, if we know that all of them obey a log-normal distribution?! (this is obvious that these 2 missing numbers are in the tail end of log-normal distribution)
*I am a structural engineering student. So please don't present complex solutions :) I want to code a program in Matlab to do this for me.


text:
Q: Triangular Numbers and Perfect Squares
Prove that $n$ is a triangular number if and only if $8n+1$ is a perfect square.

I proved the easier part first (I think), that is, if $n$ is a triangular number then $8n+1$ is a perfect square.
I don't know where to start from for the other part, please help.
By the way, this was taken from David Burton's book, Elementary Number Theory and sadly it doesn't have all the  solutions...

A: *

*If $n$ is a triangular number, then $n = \frac{k(k+1)}{2}$ and $8n+1 = 4k(k+1)+1 = (2k+1)^2$.

*If $8n+1$ is a perfect square, then $8n+1 = (2m+1)^2 \implies n = \frac{4m^2+4m+1-1}{8} = \frac{m(m+1)}{2}$ (because $8n+1$ is odd so it must be square of an odd number).


text:
Q: css selector specificity conflicts due to multiple stylesheets Ok, I've  been reading through stackoverflow css selectors.  on the thread here what is the differences in this syntax?  What does the ^= mean? What is it selecting? all?
[class^='Rating']

and
div.Rating0_5

Also, there's a statement here that reads:
Note: Repeated occurrances of the same simple selector are allowed and do increase specificity.
What does that mean?
I'm asking because I'm having to clean up alot of CSS code on a website.  There are over a dozen stylesheets each containing 200+ lines of code, and there are styles that are overriding each other among the stylesheets, maybe even within them if repeated occurences increase specificity.  It's painstaking to go line by line through the stylesheets to find out what particular class, div, etc is over-riding another and some of the specificity is seven selectors deep! It's almost impossible for me and very stressful.
Is there a tool to use that will target styles overwriting other styles?  Is it easy to use and what does it do exactly?  If not, how can I write my CSS with enough specificity without having extremely long selectors to hopefully ensure uniqueness so that they will not be overwritten by another stylesheet of rules?
Thanks, I hope this makes some sense and someone has had this experience.

A: ^= is "starts with" for CSS selector. In your case it will apply to classes with names starting with "rating".
With traditional CSS you do have to make really long selectors to be specific and I think the statement meant you can have duplicate selector and the styling will be combined.
In terms of cleaning up the CSS I don't have a good suggestion for an automated tool but you can take a look at http://sass-lang.com/ (SCSS) for a better syntax layer on top of CSS that does variable and inheritance of selectors. Does clean up CSS a lot.


text:
Q: Getting Error "Request Error: No ad to show" in AdMob Native ads iOS I have developed native adMob in my application by coping code from Sample Application given by google from below URL https://github.com/googleads/googleads-mobile-ios-examples/tree/master/Objective-C/admob/NativeExample
I am getting: Error by using my AdUnitID:  failed with error: Request Error: No ad to show.
But when i use test key given in Google sample app than my application native ads are working fine.
So What is the problem with my native Ad unitId ?
Google Native AdUnitID : ca-app-pub-3940256099942544/3986624511 My App Native AdUnitID : ca-app-pub-3415315092173981/2210049154
Update: When i put "testDevices" with my application UnitID than my application native ads are working fine. but when i remove "testDevices" than getting same error.

A: Try with the ad unit ID for testing: ca-app-pub-3940256099942544/2562852117
Also, if the height is too small, then there will be no ads too. For a "small" ad, I have to set to 140 height for it to show up.

A: Usually if there are no ads it will give error that no ads are available.


text:
Q: Delete one of the OS via Ubuntu I'm currently running on dual boot (win 7 and ubuntu). I'd like to know how to delete my Windows 7 OS using ubuntu

A: Hi and welcome to askubuntu,
I assume that you have a ubuntu live cd or usb in hand. The simplest and safest way would be to use OS-Uninstaller, a easy to use GUI tool which helps you uninstall any Operating System installed on your system with one click.But, please note that, you should install OS-Uninstaller on ubuntu live.
To install this tool, open up your terminal(Ctrl + Alt + T) on ubuntu live and type:
sudo add-apt-repository ppa:yannubuntu/boot-repair

Press Enter and type :
sudo apt-get update; sudo apt-get install -y os-uninstaller && os-uninstaller

Press Enter once again and OS-Uninsaller will be installed on your system.
Now open OS-Uninstaller(onen the dash and type OS-Uninstaller).
You will now see a window showing all Operating Systems installed on your system. Choose the one you want to remove (Windows 7 in your case) and click "OK". A confirmation window will appear, click "Apply" on that.
You can find the detailed documentation of OS-Uninstaller here : https://help.ubuntu.com/community/OS-Uninstaller
Hope it helps!

A: *

*Graphical with "gparted". You can install it from Ubuntu software center. You can ONLY edit partitions that are not active (Windows from Ubuntu will not be so you are OK there). Otherwise create a bootable gParted DVD (always handy when you have one around)

*From command line you can do this with the command "parted".


text:
Q: jQuery: tablesorter not working on table loaded using jquery load() I'm trying to use jquery tablesorter on tables that are loaded dynamically. But, while table sorter works fine in a static table, I can't get it to work in a loaded table.
I've tried calling tablesorter() after the load() and also calling it in the callback function of the load(), according to an answer to a similar question posted here. But none of them works.
This is an example of what I'm doing:

Name	Number

John	100

Paul	200

And also the contents of 'secondtable.html':

Name	Number

Steve	500

Alice	800


text:
Q: Crear niveles de usuario en sistema de login usando sesiones Quisiera poder establecer niveles de usuario (administrador y usuario normal) usando las sesiones, ya tengo en mi tabla de usuarios el nivel de la cuenta ahora quisiera validar su entrada pero no se como obtener el nivel de la tabla
uso lo siguiente:
CONECTARSE.php
          <?php
   session_start();
   if (isset($_POST['aceptar'])) {

      require_once 'conexion.php';

      $usuario =   $_POST['txtusuario'];
      $contrasena =$_POST['txtcontrasena'];

      $sql = "SELECT * FROM usuarios WHERE usuario=? AND contrasena=?";

   $statement=$conexion->prepare($sql);
   $statement->bind_param('ss',$usuario, $contrasena);
   $statement->execute();
   $statement->store_result();

    if ($statement->num_rows===0) {
     echo "Verifique sus datos";

   } else {

      $stmt = $conexion->prepare("SELECT nivel_id from usuarios WHERE usuario='$usuario' AND contrasena='$contrasena'") or die($conexion->error);
      $stmt->execute() or die($conexion->error);
      $stmt->store_result();
      $numfilas=$stmt->num_rows;
      echo $numfilas;
      $stmt->bind_result($nivel_id);
      while ($stmt->fetch())
      {
      $nivel=$nivel_id;
      echo $nivel;
      }
         $_SESSION['nivel']=$nivel;
         $_SESSION['conectado']=true; //esta conectado//
         $_SESSION['usuario']=$usuario;
         $_SESSION['inicio'] = time();
         $_SESSION['expira'] = $_SESSION['inicio'] + (5 * 60);

        if ($nivel==1){
              header ("location: unidades/menu_unidades.php");
               }
              elseif ($nivel==4){
              header ("location: administrador/menu_administrador.php");
      }

         }
   }

   ?>

Pagina del Administrador
<?php
session_start();
if (isset($_SESSION['conectado'] ) && $_SESSION['conectado'] == true && $_SESSION['nivel']==2) {
if()
include 'conexion.php';
include 'encabezado.php';
echo "Conectado como:" . $_SESSION['usuario'];
} else {
echo "Esta pagina es solo para usuarios registrados y administradores.
";
header ("location: index.php");
exit;
}
$now = time();
if($now > $_SESSION['expira']) {
session_destroy();
echo "Su sesion a terminado">
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
      <title>Sistema Automatizado de Orden de Medida Disciplinaria</title>

Menu Principal

                        UNIDADES

                        USUARIOS

                        CONSULTAS

Salir

ERROR:

Fatal error: Call to undefined method mysqli_stmt::fetch_array() in >C:\wamp\www\Sistema Automatizado OMD\conectarse.php on line 22

NOTA ADICIONAL: uso php 5.2.0 y los header que estan comentados me dan error (dicen que ya se hizo el output), alguna solucion?

A: el problema viene siendo $statement. Cuando se ejecuta la consulta la trabajas como un objeto pero en verdad es un arreglo ya q una consulta puede devolver mas de un row aunque este no el caso debido a la consulta q haces, pero php no lo sabe y te devuelve un arreglo q nada mas tiene un objeto por eso te da error prueba haciendo esto:
$statement[0]->nivel;

A: Lei sobre las sentencias preparadas (sugerencia de @aldanux) y quedo asi:
<?php
    session_start();
    if (isset($_POST['aceptar'])) {

       require_once 'conexion.php';

       $usuario =   $_POST['txtusuario'];
       $contrasena =$_POST['txtcontrasena'];

       $sql = "SELECT * FROM usuarios WHERE usuario=? AND contrasena=?";

    $statement=$conexion->prepare($sql);
    $statement->bind_param('ss',$usuario, $contrasena);
    $statement->execute();
    $statement->store_result();

     if ($statement->num_rows===0) {
      echo "Verifique sus datos";

    } else {

       $stmt = $conexion->prepare("SELECT nivel_id from usuarios WHERE usuario='$usuario' AND contrasena='$contrasena'") or die($conexion->error);
       $stmt->execute() or die($conexion->error);
       $stmt->store_result();
       $numfilas=$stmt->num_rows;
       //echo $numfilas;
       $stmt->bind_result($nivel_id);
       while ($stmt->fetch())
       {
       $nivel=$nivel_id;
       //echo $nivel;
       }
          $_SESSION['nivel']=$nivel;
          $_SESSION['conectado']=true; //esta conectado//
          $_SESSION['usuario']=$usuario;
          $_SESSION['inicio'] = time();
          $_SESSION['expira'] = $_SESSION['inicio'] + (5 * 60);

         if ($nivel==1){
                header("location: menu_unidades.php");
                }
               elseif ($nivel==2){
                header("location:menu_administradores.php");
       }

          }
    }
    ?>

Comparto una guia con ejemplos para consultar, modificar, borrar y actualizar datos con sentencias preparadas y mysqli:
tabla.sql
CREATE TABLE IF NOT EXISTS `pruebas` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nombre` varchar(15) NOT NULL,
  `apellidos` varchar(25) DEFAULT NULL,
  `edad` tinyint(4) NOT NULL,
  `fechanac` date NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

conexion.php
<?php
    //////////////////////////
    // conexion.php
    //////////////////////////

    // Datos configuración de la conexión al Servidor MySQL.

    $nombrebase="basedatos";
    $usuario="usuario";
    $servidor="localhost";

    $password="password";
    //////////////////////////////////////

    // Hacemos la conexión al servidor de MySQL utilizando la clase mysqli
    // Utilizamos la @ antes de crear el objeto, ya que si da error,
    // queremos mostrarlo con un mensaje personalizado.

    $mysqli=@new mysqli($servidor,$usuario,$password,$nombrebase);

    if ($mysqli->connect_error)
    {
        die ("Error en conexión base datos: ".$mysqli->connect_error);
    }
?>

altas.php
<?php
// Crear el formulario para recoger datos de los usuarios.

// Si estamos recibiendo datos del formulario...
// Insertamos esos datos en la tabla.

if ( isset($_POST['nombre']) && $_POST['nombre']!=""   )
{
    // Nos conectamos a la base de datos.
    require("conexion.php");

    // Preparamos la instrucción SQL. Prepare nos devuelve un objeto de la clase mysqli_stmt
// o false si hay un error.
    $stmt = $mysqli->prepare("insert into pruebas (nombre,apellidos,edad,fechanac,password)
values(?,?,?,?,?)") or die($mysqli->error);

    // Enlazamos los parámetros (5 cadenas de texto 's')
    $stmt->bind_param("sssss",$_POST['nombre'],$_POST['apellidos'],$_POST['edad'],$_POST['fechanac'],
$_POST['password']);

    // Ejecutamos la sentencia preparada.
    $stmt->execute() or die($mysqli->error);

    // Mostramos el mensaje x filas insertadas correctamente.
    printf("%d fila insertada correctamente.\n",$stmt->affected_rows);

    // Cerramos la sentencia preparada.
    $stmt -> close();

    // Cerramos la conexión.
    $mysqli->close();
}
else
{
// En otro caso mostramos el formulario de altas.
?>

 Alta de Usuarios

    <form name="formulario" method="post">
    Nombre: <input name="nombre" type="text"/>

    Apellidos: <input name="apellidos" type="text"/>

    Edad: <input name="edad" type="text" size="2" maxlength="2" />

    Fecha Nacimiento: <input name="fechanac" type="text"/>

    Password: <input name="password" type="password"/>

    <input type="reset" value="Limpiar"/>
    <input type="submit" value="Alta Usuario"/>

    </form>

<?php
}
?>

bajas.php
<?php
// Conectamos a la base de datos
require("conexion.php");

if (isset($_POST['id']) && $_POST['id']!="-1")
{
    // Construimos la sentencia de borrado SQL.
    $stmt = $mysqli->prepare("delete from pruebas where id=?") or die($mysqli->error);

    // Enlazamos los parámetros (1 entero 'i')
    // http://es2.php.net/manual/es/mysqli-stmt.bind-param.php

    $stmt->bind_param("i",$_POST['id']);

    // Ejecutamos la sentencia preparada.
    $stmt->execute() or die($mysqli->error);

    // Mostramos mensaje
    echo "Registro borrado correctamente";

    // Cerramos la sentencia preparada.
    $stmt->close();
}
?>

 Borrado de registros

<form name="formulario" method="post">
<select name="id">
<option value="-1">Seleccione registro</option>
<?php
    // Cubrimos dinámicamente el formulario.

    // Construimos la sentencia de select SQL
     $stmt = $mysqli->prepare("select id,nombre,apellidos from pruebas") or die($mysqli->error);

    // No tenemos ningún parámetro a enlazar, así que..
    // ejecutamos la sentencia preparada directamente
    $stmt->execute() or die($mysqli->error);

    // Si es una consulta de select almacenamos el resultado con el método store_result() del objeto $stmt.
    $stmt->store_result();

    // Número de filas obtenidas, si fuera necesario.
    // $numfilas=$stmt->num_rows;

    // Vinculamos unas variables a los resultados con el método bind_result() de stmt,
    // antes de llamar al método fetch() de stmt
    $stmt->bind_result($campoid, $camponombre, $campoapellidos);

    // Recorremos el recordset:
    while ($stmt->fetch())
    {
        $cadena=sprintf("<option value='%s'>%s %s</option>",$campoid,$camponombre,$campoapellidos);
        echo $cadena;
    }

    // Liberamos el resultado.
    $stmt-> free_result();

    // Cerramos la sentencia preparada.
    $stmt->close();

    // Cerramos conexión
    $mysqli->close();
?>
</select>
<input type="submit" value="Borrar Registro"/>
</form>

modificaciones.php
<?php
// Conectamos a la base de datos.
require("conexion.php");

// Si recibimos datos formulario de selección.
if (isset($_POST['selectid']) && $_POST['selectid']!=-1)
{
    // Preparamos la consulta SQL
    $stmt= $mysqli->prepare("select id,nombre,apellidos,edad from pruebas where id=?")
or die($mysqli->error());

    // Enlazamos los parámetros (1 entero 'i')
    // http://es2.php.net/manual/es/mysqli-stmt.bind-param.php
    // Vinculamos los parámetros a la consulta
    $stmt->bind_param("i",$_POST['selectid']);

    // Ejecutamos la consulta preparada.
    $stmt->execute();

    // Si es una consulta de select almacenamos el resultado.
    $stmt->store_result();

    // Vinculamos unas variables a los resultados con el método bind_result() de stmt,
    // antes de llamar al método fetch() de stmt
    $stmt->bind_result($elid, $elnombre, $losapellidos, $laedad);

    // Leemos la primera fila de ese recordset
    // Los datos que hemos leído estará en las variables que hemos vinculado antes.
    $stmt->fetch();

    // Construimos el formulario y ponemos los datos
    // de ese usuario en los campos.
?>

Edición de Usuario

    <form name="formulario" method="post">
    Nombre: <input name="nombre" type="text" value="<?php echo $elnombre ?>"/>

    Apellidos: <input name="apellidos" type="text" value="<?php echo $losapellidos ?>"/>

    Edad: <input name="edad" type="text" size="2" maxlength="2" value="<?php echo $laedad ?>"/>

    <input type="hidden" name="id" value="<?php echo $elid ?>"/>

    <input type="reset" value="resetear"/>
    <input type="submit" value="Actualizar"/>

    </form>

<?php
}
// Si recibimos datos del formulario de edición...
if (isset($_POST['id']))
{
    // Preparamos la consulta SQL
    $stmt= $mysqli->prepare("update pruebas set nombre=?,apellidos=?,edad=? where id=?");

    // Enlazamos los parámetros (3 string:'s' y 1 entero:'i')
    // http://es2.php.net/manual/es/mysqli-stmt.bind-param.php
    $stmt->bind_param("sssi",$_POST['nombre'],$_POST['apellidos'],$_POST['edad'],$_POST['id']);

    // Ejecutamos consulta de update.
    $stmt->execute() or die($mysqli->error());

    // Cerramos la sentencia preparada.
    $stmt -> close();

    // Mostramos mensaje de OK.
    echo "Actualización correcta de los datos del usuario: {$_POST['nombre']} ";
}
?>

 Actualización de Registros

<form name="formulario" method="post">
<select name="selectid">
<option value="-1">Seleccione registro</option>
<?php
    // Cubrimos dinámicamente el formulario.

    // Construimos la sentencia de select SQL
     $stmt = $mysqli->prepare("select id,nombre,apellidos from pruebas") or die($mysqli->error);

    // No tenemos ningún parámetro a enlazar, así que..
    // ejecutamos la sentencia preparada directamente
    $stmt->execute() or die($mysqli->error);

    // Si es una consulta de select almacenamos el resultado con el método store_result() del objeto $stmt.
    $stmt->store_result();

    // Número de filas obtenidas, si fuera necesario.
    // $numfilas=$stmt->num_rows;

    // Vinculamos unas variables a los resultados con el método bind_result() de stmt,
    // antes de llamar al método fetch() de stmt
    $stmt->bind_result($campoid, $camponombre, $campoapellidos);

    // Recorremos el recordset:
    while ($stmt->fetch())
    {
        $cadena=sprintf("<option value='%s'>%s %s</option>",$campoid,$camponombre,$campoapellidos);
        echo $cadena;
    }

    // Liberamos el resultado.
    $stmt-> free_result();

    // Cerramos la conexión.
    $mysqli->close();
?>
</select>
<input type="submit" value="Seleccionar"/>
</form>

consultas.php
<?php
    // Conectarse a la base de datos.
    require("conexion.php");

    // Preparamos la consulta.
    $stmt = $mysqli->prepare("SELECT nombre,apellidos,edad from pruebas") or die($mysqli->error);

    // Ejecutamos la consulta preparada.
    $stmt->execute();

    // Si es una consulta de select almacenamos el resultado.
    $stmt->store_result();

    // Número de filas obtenidas en $stmt->num_rows
    echo "Se han encontrado $stmt->num_rows registros.

";

    // Vinculamos unas variables a los resultados con el método bind_result() de stmt,
    // antes de llamar al método fetch() de stmt
    $stmt->bind_result($elnombre, $losapellidos, $laedad);

    // Recorremos el recordset.
    echo "
";
    echo "
Nombre	Apellidos	 Edad
";

    while ($stmt->fetch())
    {
        echo "
".$elnombre."	".$losapellidos."	".$laedad."
";
    }

    echo "
";

    // Liberamos el espacio que ocupa ese resultado en memoria.
    $stmt -> free_result();

    // Cerramos la conexión con el servidor mysql.
    $mysqli->close();
?>


text:
Q: How to make where query with join I have a table in which i have four columns

*

*id

*user_type

*user_role

*org_id

Now if the user_type is 1 (i.e individual) then the user_role and org_id will be null,
but if the user_type is 2 (i.e organisation) then it will have org_id (id of the organisation) and user_role (his role in the organisation).
There are three type of role in an organisation

*

*admin (only one person could be the admin).

*finance secrearty (could be more than one).

*approvers (also could be more than one).

What I want
I want to fetch only one person (probably admin of the organisation) if the user_type is 2 from each organisation and all the users having user_type 1.
My table
-------------------------------------
| tbl_user                           |
-------------------------------------
| id | user_Type | user_role | org_id|
--------------------------------------
| 1  | 1         | null      | null  |
| 2  | 2         | 1         | 1     |
| 3  | 2         | 2         | 1     |
| 4  | 2         | 3         | 1     |
| 5  | 2         | 3         | 1     |
| 6  | 1         | null      | null  |
| 7  | 2         | 1         | 2     |
| 8  | 2         | 2         | 2     |
| 9  | 2         | 3         | 2     |
| 10 | 2         | 3         | 2     |

by using query
SELECT * FROM YourTable t
WHERE t.user_type = 1
   OR t.user_role = 1

Expected result
-------------------------------------
| tbl_user                           |
-------------------------------------
| id | user_Type | user_role | org_id|
--------------------------------------
| 1  | 1         | null      | null  |
| 2  | 2         | 1         | 1     |
| 7  | 2         | 1         | 2     |
| 6  | 1         | null      | null  |

Then i have to join the result with tbl_user_meta with (where zipcode = 85225).
My tbl_user_meta follows-
 -------------------------------------
| tbl_user_meta                       |
--------------------------------------
| id | uid       | user_name | zipcode|
--------------------------------------
| 1  | 1         | abc       | 85225  |
| 2  | 2         | asd       | 85225  |
| 3  | 3         | asd       | 85225  |
| 4  | 4         | sdf       | 345678 |
| 5  | 5         | fgd       | 23456  |
| 6  | 6         | rgy       | 23567  |
| 7  | 7         | hyt       | 12345  |
| 8  | 8         | ukl       | 12345  |
| 9  | 9         | tko       | 21334  |
| 10 | 10        | ert       | 85225  |

What i finally want to achieve is this record
-------------------------------------
| tbl_user_meta                       |
--------------------------------------
| id | uid       | user_name | zipcode|
--------------------------------------
| 1  | 1         | abc       | 85225  |

P.S - I am doing this with codeigniter
Thanks.

A: I think I have my answer:
 $this->db->select('tbl_user.*,tbl_user_meta.*');
 $this->db->from('tbl_user');
 $this->db->where('user_type', 1);
 $this->db->or_where('user_role', 1);
 $this->db->where('tbl_user_meta.zipcode',85225);
 $this->db->join('tbl_user_meta','tbl_user_meta.did=tbl_user.id');

 $query=$this->db->get();

 return $query->result();

A: you can join the table as under remember remove "" from "85225" if it is integer.
select * from tbl_user, tbl_user_meta where tbl_user.id = tbl_user_meta.id AND tbl_user_meta.zipcode = "85225";

A: select a.id, a.uid, b.username, a.zipcode
from tbl_user_meta a
inner join tbl_user b
where a.uid = b.id ;

This can be achieved like this in codeigniter.
public function gettable(){
$query ='select a.id, a.uid, b.username, a.zipcode
    from tbl_user_meta a
    inner join tbl_user b
    on a.uid = b.id
    where a.zipcode = 85225';

   $query = $this->db->query($query);
   $result = $query->result();
   return $result;
}


text:
Q: Why Jaeger Opentelemetry traces does not show correct Database Query execution Time? I am using Spring JdbcTemplate and SybaseDB along with OpenTelemetry traces enabled. I am using an aspect logger around JdbcTemplate query and execute method that logs time taken to execute those methods.
What I observed that the time that the time logged by the aspect is significantly huge than the time observed in OpenTelemetry Jaegar UI Span.
For an instance, the time logged by the aspect was 556ms and the observed time in Jaegar UI is 225.6ms
Why is there such a huge difference in the logged and the observed time?
Ideally the observed time taken by query to execute in logs and Jaegar traces should be same


text:
Q: How to display content based on two dropdownlists in AngularJS? I want to display content based on two dropdownlists. I know how to change based on options with single dropdownlist. Kindly help me regarding this.
This is to display based on single drop downlist. I have another dropdownlist with Branchwise. I am strucked to filter the data based on CAREER and BRANCHES. Kindly helpme
<select ng-model="myVar">
<option value="">CAREER OPTIONS
 <option value="1">HIGHER EDUCATION
  <option value="2">JOBS
  <option value="3">ENTERPRENUERSHIP
</select>

H E details

Jobs details

Enterprenuership details

A: here's working plnk, this does exactly the same you need, based on selection from 2 dropdown/select the message changes

A: Add ng-if in each section
<select ng-model="myVar1" ng-change="myVar3 = (myVar1+myVar2)">
    <option value="">CAREER OPTIONS
    <option value="1">HIGHER EDUCATION
    <option value="2">JOBS
    <option value="3">ENTERPRENUERSHIP
</select>

<select ng-model="myVar2" ng-change="myVar3 = (myVar1+myVar2)">
    <option value="">Branch OPTIONS
    <option value="1">Branch 1
    <option value="2">Branch 2
    <option value="3">Branch 3
</select>

H E details

Jobs details

Enterprenuership details


text:
Q: Llave foranea de tipo SERIAL - mySQL En la tabla "Detalles de orden" (ordCodigo) y (prodCodigo) son llaves primarias pero a la vez foraneas (ye hice esto alguna vez) pero el problema aqui es que el tipo de dato es SERIAL.
Esto puede hacer?
Como?

A: De acuerdo a la documentación de

*

*MySQL 5.7

*MySQL 8
Un dato de tipo serial posee las siguientes características

*

*BIGINT

*UNSIGNED

*NOT NULL

*AUTO_INCREMENT

*UNIQUE
Lo cual implica que si deseas crear una serie de tablas donde sus llaves primarias y foráneas sean de tipo SERIAL como las que a continuación se muestran
CREATE TABLE usuarios(
  id SERIAL,
  name VARCHAR(20)
);

Y una segunda tabla de este modo
CREATE TABLE posts(
  id SERIAL,
  cantidad INT,
  usuario_id SERIAL,
  CONSTRAINT posts_usuarios FOREIGN KEY(usuario_id) REFERENCES usuarios(id)
);

Se obtendrá un resultado de error como el siguiente

Incorrect table definition; there can be only one auto column and it must be defined as a key

Que nos identifica un error con la creación de la segunda tabla, pues si bien la PK id es serial la FK que es usuario_id al ser también serial entra en conflicto pues intenta crear un valor AUTO_INCREMENT de la cual solo debe existir una y que sea declarada como la PK de dicha tabla.
Tampoco podrás declarar a la FK usuario_id de un tipo distinto a INT o BIGINT pues entraría en conflicto por los tipos de datos y características que posee SERIAL mencionadas ya mas arriba.
En conclusión deberías estar usando algún tipo de dato INT o BIGINT de manera explícita para la declaración de tus llaves primarias PK y así mismo de tus llaves foráneas FK


text:
Q: How can I change the type of a property in Geddy How can I change the type of an existing property in Geddy?
I believe I need to change the type as set when defining the properties in the model file:
this.defineProperties({
  title: {type: 'string', required: true},
  description: {type: 'text'},
  status: {type: 'boolean'}
});

I also think I need to alter the table in a migration.  I'm using the 'changeColumn' function as documented here http://geddyjs.org/guide#models
var StatusToBoolean = function () {
  this.up = function (next) {
    this.changeColumn("step", 'status', 'boolean', function (err, data) {
      if (err) { throw err; }
      next();
    });
  };

  this.down = function (next) {
    this.changeColumn('step', 'status', 'string', function (err, data) {
      if (err) { throw err; }
      next();
    });
  };
};

exports.StatusToBoolean = StatusToBoolean;

However, when I run this migration I get a 'SQLITE_ERROR: near "ALTER"' error:
Hindenburg:to_do Tom$ geddy jake db:migrate  --trace
Running migrations for development environment...
Running status_to_boolean (up)
jake aborted.
Error: SQLITE_ERROR: near "ALTER": syntax error
Hindenburg:to_do Tom$

This makes me think I'm doing something wrong. I tried the '--trace' option (as you can see), but that didn't give any helpful information.
I also suspect that I need to actually change some of the data in the table (so that it can map to the new datatype), but the documentation is unclear on how to do that.
Any help is appreciated. Thanks.

A: Unfortunately SQLite doesn't support ALTER COLUMN (http://www.sqlite.org/lang_altertable.html). This is only a problem in the SQLite adapter, and it doesn't affect Postgres or MySQL. There are also workarounds, as described here: How do I rename a column in a SQLite database table? You could write a migration that performs these steps. Version 0.4.16 of Geddy's ORM (now on NPM) now includes a friendly error message when you try to do this with the SQLite adapter.


text:
Q: geolocalisation is very slow I've a application for the geolocalisation and I retrieve the current geoposition but the display on the application is VERY slow...
The constructor :
        public TaskGeo()
        {
            InitializeComponent();
            _geolocator = new Geolocator();
            _geolocator.DesiredAccuracy = PositionAccuracy.High;
            _geolocator.MovementThreshold = 100;
            _geolocator.PositionChanged += _geolocator_PositionChanged;
            _geolocator.StatusChanged += _geolocator_StatusChanged;

            if (_geolocator.LocationStatus == PositionStatus.Disabled)
                this.DisplayNeedGPS();
        }

the code for the display on the app :
    void _geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
    {
        // saving and display of the position
        App.RootFrame.Dispatcher.BeginInvoke(() =>
        {
            this._CurrentPosition = args.Position;
            this.lblLon.Text = "Lon: " + this._CurrentPosition.Coordinate.Longitude;
            this.lblLat.Text = "Lat: " + this._CurrentPosition.Coordinate.Latitude;
            this.LocationChanged(this._CurrentPosition.Coordinate.Longitude, this._CurrentPosition.Coordinate.Latitude);
        });
    }

And the code for the query :
    private void LocationChanged(double lat, double lon)
    {
        ReverseGeocodeQuery rgq = new ReverseGeocodeQuery();
        rgq.GeoCoordinate = new GeoCoordinate(lat, lon);
        rgq.QueryCompleted += rgq_QueryCompleted;
        rgq.QueryAsync();
    }

How can I improve the code to display faster the position ? Thanks in advance !

A: Getting this sort of information is basically pretty slow. To quote the great Louis C. K. "It is going to space, give it a second". Because you've specified PositionAccuracy.High this means that the location must be found using GPS, which is comparatively slow, and not any of the faster fallback methods such as using local wi-fi or cell phone towers.
You could reduce your demands for accuracy overall or initially request a lower accuracy and then refine it once the information from the GPS is available. The second option is better. If you look at a map application they typically do this by showing you about where you are and then improving it after the GPS lock is acquired.


text:
Q: MVC4 code first force database column name I have the following problem: I have a hierarchy of entities that uses inheritance. I have a two identical fields( the name and type is the same ) in two of the sub-entities. When I try to "Update-Database -Force" on the project EF5 complains that there are there is already a column with name X.
The way EF5 generates the tables is that it actually generates single table and puts there all the fields of the base entity plus the all the fields of the derived entities.
Is there a way to force a different database column name from the property name.
Are there any other solutions( I know it might be architectural problem to duplicate data but making this common will introduce more complex database hierarchy that I don't want to use ).
Thanks:)

A: This can be done in one of two ways, either using Fluent API or property attributes on your class properties.
[Column("ColumnName")]
public string PropertyName
{
   get;
   set;
}

See MSDN - ColumnAttribute Class for more details on the column attribute.
Otherwise, use Fluent API. Within your context class-
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);

   modelBuilder.Entity<YourClass>().Property(yc => yc.PropertyName).HasColumnName("ColumnName");

See MSDN - HasColumnName extension method for more on this method.
The article linked by Baximilian will be useful in learning more about this.

A: If I understand you correctly, you need to change column name in DB for field, so you can use ColumnAttribute.
You can find more information here


text:
Q: SQL: Проверка на наличие записи в таблице, вывод собственных значений Итак, ситуация такая:
мне нужно проверить, есть ли нужное значение ("abcd")в таблице.
В случае того, если значения нет, нужно получить сообщение (с помощью SELECT), к примеру, такое: "value abcd is missing".
Как это возможно выполнить с помощью SQL?

A: Два стопроцентно работающих варианта:
Верная реалиция предложенная коллегой с моими комментариями:
SELECT
      CASE
        WHEN EXISTS (SELECT TOP (1)
            1
          FROM [Table]
          WHERE [field] = 'abcd') THEN 'EXISTS'
        ELSE 'value abcd is missing'
      END

Второй вариант:
IF (SELECT COUNT(1) FROM [Table] where [field]='abcd')>0
BEGIN
     SELECT 'EXISTS'
END
ELSE
BEGIN
     SELECT 'value abcd is missing'
END

IF Через EXISTS:
IF EXISTS (SELECT TOP (1) 1 FROM [Table] where field='abcd')
BEGIN
     SELECT 'EXISTS'
END
ELSE
BEGIN
     SELECT 'value abcd is missing'
END

A: Вот это , например, должно работать в MS SQL:
SELECT CASE WHEN EXISTS(SELECT TOP 1 1 FROM Table where field='abcd')=1 THEN 'EXISTS' ELSE 'value abcd is missing' END

По идее, и во многих других СУБД это должно сработать.
Можно еще тоже самое через IF ELSE сделать.