text:
Q: Expected number of cards we end up with in game Suppose that we have $N$ distinct cards arranged in no particular order. If the first card of the pack is less than the second card of the pack, we keep both cards. Otherwise we discard the second one and keep the first one. We then carry on the process in the same way and we want to determine the expected number of cards we end up with. The base cases can be solved in a straightforward way and give us $e_1=1$, $e_2=\frac{3}{2}$ and $e_3=\frac{11}{6}$, where $e_N$ is the expected value we are looking for if we play with $N$ cards. Looking at these base cases, it would appear that we have the following relation:
$$e_N=e_{N-1}+\frac{1}{N}=\frac{1}{N}\sum_{i=1}^{N-1} e_i+1=\sum_{i=1}^N\frac{1}{i}.$$
My question is how can we give a heuristic interpretation to this relation, i.e knowing that the expected value we end up with playing with $N-1$ cards is $e_{N-1}$, why should the expected value we end up with playing with $N$ cards be equal to $e_{N-1}+\frac{1}{N}$ (or $\frac{1}{N}\sum_{i=1}^{N-1} e_i+1$)? I am also very interested in trying to understand if there is any underlying explanation for the logarithmic order which would appear to come into play when we play with a large number of cards. Any comments or ideas would be greatly appreciated.

A: You keep the $n^{\text{th}}$ card if it is the highest of the first $n$, which happens with probability $\frac 1n$  This explains your value for $e_N$.  The logarithmic order then comes from the fact that the integral of $\frac 1n$ is $\log n$.  Your $e_N$ are the harmonic numbers, which are very close to $\log n + \gamma$ with $\gamma \approx 0.577$

A: The following does not directly answer why it should be the case that $e_N=e_{N-1}+1/N$, but rather it proves the assertion that $e_{N}=1+1/2+\cdots+1/N$.
Suppose that $e_{n,N}$ denotes the expectation of number of cards you keep by repeating the procedure for $N$ cards, given that your first draw is $n\le N$ (say we number the cards from $1$ to $N$ for simplicity).
Given $N$ cards, your first draw can be $n$ with probability $1/N$, and since distinct first draws partition the sample space, we have
$$
e_{N}=\frac{1}{N} \left( e_{1,N}+e_{2,N}+\cdots+e_{N,N} \right)
$$
Now if your first draw is $n$, then as you repeat the procedure any cards whose number is less than $n$ will surely be discarded at some point. So those cards with numbers less than $n$ are irrelevant to your expectation, and in fact it comes down to question of which of cards with numbers bigger than $n$ you keep at the end. Therefore, in fact for any $n$,
$$
e_{n,N}=e_{1,N-(n-1)}
$$
On the other hand, if your first draw is indeed $1$, then whatever number is written on the second card you will always keep it. So in a sense you can regard your second draw as a first draw of a new process containing $m-1$ cards. Therefore, we have
$$
e_{1,m}=1+e_{m-1}
$$
for any $m\ge 1$ where $e_{0}:=0$ for convenience. It follows that
$$
e_{N}=\frac{1}{N}\left( e_{1,1}+\cdots+e_{1,N} \right)=\frac{1}{N}\left( N+e_{1}+\cdots+e_{N-1} \right)
$$
Now you can use induction on $N$ to show that $e_N=\sum_{i=1}^{N} \frac{1}{i}$.

Edit: about your respond to @Ross Millikan's answer:
I think written as it is, it is a not quite logically correct.
You'd rather argue like this:
So you will keep last card if and only if the last card is numbered $N$. You can partition the sample space into events where whether or not you keep the last card. Now if you keep the last card, then it means last card is numbered $N$, and so any card before the last card is numbered from $1$ to $N-1$. You can regard the previous cards as a deck with $N-1$ distinct cards, and expectation of number of cards you get from them by repeating procedure is just $e_{N-1}$. Since you always keep the last card, then the expectation given that you keep the last card is just
$$
1+e_{N-1}
$$
Now suppose that you don't keep the last card. Probability of that happening is just $1-1/N=(N-1)/N$. Then last card is numbered some $m\neq N$. Then previous $N-1$ cards are numbered from $1$ to $N$ with $m$ being 'skipped'. But you can the then renumber them from $1$ to $N-1$ without changing the order, so in that case expectation is just $e_{N-1}$.
So by partition principle it follows that
$$
e_N = \frac{1}{N} (e_{N-1}+1) + \frac{N-1}{N} e_{N-1}=e_{N-1}+1/N
$$


text:
Q: Using Ruby & Sinatra, trying to populate an area on the page without reloading the entire page I am developing a small web application using Ruby, Sinatra & HAML.
The scenario I am struggling with at the moment is something that I used to solve in PHP using Ajax and Javascript, and am not sure how to best go about doing it in Ruby (what the best practice would be, if there is a more optimized way of approaching this).
I have a screen as follows:

What I wish to happen is that when a user clicks on one of the buttons (for example Show most popular), the system calls a function which queries the database to get the relevant records and re-populates the 'Entries' box with the appropriate records. I want to do this without the rest of the page re-loading or anything else being effected, just the 'Entries' box. Bonus - If I can show a little "LOADING" spiral while the data is being fetched.
My research led me to gem known as "typhoeus" which I found to be really great, but am not sure if it applies in this scenario (or how to implement it if it does).
Any kind of help would be greatly appreciated.
Much obliged.

A: It seems like pjax is what you would be looking for.
https://github.com/defunkt/jquery-pjax/tree/heroku
The author uses Sinatra in his example app.  Though he does use erb, I am sure that it wouldn't cause any problems if you switched the template engine to haml

redpajama_set_name: RedPajamaStackExchange


text:
Q: $this->db->get() give empty results on valid query I have MYSQL query whenever it is executed in codeIgnitor as php , $this->db->get() gives empty results and when i run it directly in phpmyadmin , it gives results , why is that?
phpmyadmin:

CodeQuery:
$this->db->select('courses.id AS courseId',false);
        $this->db->select('courses.Name AS courseName',false);
        $this->db->select("`assignments`.`Assignment#` AS assignmentName",false);
        $this->db->select('assignments.DueDate AS duedate',false);
        $this->db->select('assignments.DueTime AS duetime',false);
        $this->db->select('assignments.expiryDate AS expiryDate',false);
        $this->db->from('courses,user,assignments,course2teacher,follows');
        $this->db->where('user.id',$studentid);
        $this->db->where('follows.studentid=user.id');
        $this->db->where('follows.course2teacherid=course2teacher.id');
        $this->db->where('assignments.course2teacherid=course2teacher.id');
        $this->db->where('course2teacher.CourseId=courses.id');
        $query = $this->db->get();

        print_r($query); die();

Output Code Query is NULL ,  can anyone please explain what happened here , and how can i fix it ?
Edit:
My database structure is on : http://ondras.zarovi.cz/sql/demo/
Just goto link , click save/load click load , type isec click ok , it is second day now just struggling with single query


text:
Q: importing image dynamically (React Js) (Require img path cannot find module) I need to import images(several) from my image file dynamically by a map method. First, I want to set a base URL to my images file and then read the image's name from my JSON file which includes the image property and then set the image src accordingly.
The JSON file is like below :
{
      "title": "Blue Stripe Stoneware Plate",
      "brand": "Kiriko",
      "price": 40,
      "description": "Lorem ipsum dolor sit amet...",
      "image": "blue-stripe-stoneware-plate.jpg"
    },
    {
      "title": "Hand Painted Blue Flat Dish",
      "brand": "Kiriko",
      "price": 28,
      "description": "Lorem ipsum dolor sit amet...",
      "image": "hand-painted-blue-flat-dish.jpg"
    },

my images folder :
I have read the products by redux which is works perfectly  =>
const products = this.props.products;
console.log(products, 'from redux');
const fetchProducts = [];
    for (let key in products) {
      fetchProducts.push({
        ...products[key]
      });
    }

the console.log() =>
Now I want to define a base URL like this which later use as image src by adding the image's name from the JSON file in the map method :
const baseUrl = '../../components/assets/images/';
const fetchProducts = [];
for (let key in products) {
  fetchProducts.push({
    ...products[key]
  });
}

const productCategory = fetchProducts.map((product, index) => {
  return (
    <Photo
      key={index}
      title={product.title}
      brand={product.brand}
      description={product.description}
      imageSource={baseUrl + product.image}
      imageAlt={product.title}
    />
  );
});

my Photo component looks like below :
  const photo = props => (

    <img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />

{props.brand}

{props.title}

{props.price}

);

export default photo;

unfortunately, I have faced this error:
Thanks in advance and sorry for my bad English :)

A: Import is not working like that. You can use a base URL like that:
const baseUrl = "../../components/assets/images/";

Then you can pass to your Photo component like that:
<Photo
  key={index} // Don't use index as a key! Find some unique value.
  title={product.title}
  brand={product.brand}
  description={product.description}
  imageSource={baseUrl + product.image}
  imageAlt={pro.title}
/>;

Lastly, in your Photo component use require:
<img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />

or like that:

But, don't skip "" part or don't use it directly like:

since require wants an absolute path string and first two do this trick.

A: Try this solution for dynamic image:-
**Componet**
const photo = props => (

      <img src={require( `../../components/assets/images/${props.imageSource}`)} alt={props.imageAlt} />

{props.brand}

{props.title}

{props.price}

);

**Include Componet**
const productCategory = fetchProducts.map((product, index) => {
    return (
      <Photo
        key={index}
        title={product.title}
        brand={product.brand}
        description={product.description}
        imageSource={product.image}
        imageAlt={product.title}
      />
    );
});

A: So here is what I found and it worked for me.

"file-loader": "4.3.0"
React: 16.12

Run this in your terminal:
npm run eject

Check file-loader in config/webpack.config and located file-loader configurations. What I did was, I created a directory called static/media/{your_image_name.ext} following the notation there:
options: {
    name: "static/media/[name].[hash:8].[ext]"
}

and then imported this image like
import InstanceName from "static/media/my_logo.png";

Happy Hacking!

A: After trying all kinds of solutions, including backticks <img src={require( `${ props.imageSource }` )} and others, nothing was working. I kept getting the error Cannot find module, even though my relative paths were all correct. The only primitive solution I found, if you have a relatively small number of possible images, is to predefine a Map that will map to the actual imports. (Of course this won't work for lots of images.)
import laptopHouse from '../../images/icons/laptop-house.svg'
import contractSearch from '../../images/icons/file-contract-search.svg'
..

const [iconMap, setIconMap] = useState({
                                'laptopHouse': laptopHouse,
                                'contractSearch': contractSearch,
                                ..
                              });

..

A: i solved this typescript issue as follows in my project.
hope this is helpful
export const countryData = {
'sl': { name: 'Sri Lanka', flag: '/flag-of-Sri-Lanka.png' },
'uk': { name: 'UK', flag: '/flag-of-United-Kingdom.png' },
'usa': { name: 'USA', flag: '/flag-of-United-States-of-America.png' },
'ca': { name: 'Canada', flag: '/flag-of-Canada.png' },
'It': { name: 'Italy', flag: '/flag-of-Italy.png' },
'aus': { name: 'Australia', flag: '/flag-of-Australia.png' },
'me': { name: 'Middle East', flag: '/flag-of-Middle-East.png' },
'other': { name: 'Other', flag: '/flag-of-World.png' }, };

"part of URL within Double quotes" + dynamic_URL_via_var combo worked for me.
<Avatar src={require('../assets'+countryData['uk']['flag'])} />

A:   //json data.
  "ProductSlider":[
              {
                "image":"Product1.jpg"
              },
              {
                "image":"Product2.jpg"
              }]
   //mapping data list in parent component.
    {sliderData.map((data) => (
            <SwiperSlide className='w-10 '>
            <ProductCard data={{imgSrc: data.image}}  />
            </SwiperSlide>
          ))}

    //child component(linked image).
        import React from 'react'
        import { CardImg } from 'react-bootstrap'

        export default function ProductCard(props) {
          let {imgSrc} = props.data;

          return (

                <CardImg
                      variant='top'
                      src={require(`../assets/images/${imgSrc}`)}
                     />

Add to cart

          )
        }

A: Even I got the same error
{gallery.map((ch, index) => {....
cannot find module '/../..................png'

I went wrong here, I used src instead of ch
Error
<Image src={src.image} />

Solved
<Image src={ch.image} />


text:
Q: Visual basic .NET - Show the number of days in the selected month i'm brand new to VB and i'd like to create a program that: when i input the number of the month (in a input box) it tells me how many days there's is in that month and if i input a incorrect month it tells me "error".
Public Class Form1
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Me.Close()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim months As String
        months = InputBox("What is the number of the month?", "Months", , , )

    End Sub
End Class

Program so far

A: You're looking for DateTime.DaysInMonth().
You'll need to parse the user's input into an Integer with Int32.TryParse(), then pass the resultant Integer to DaysInMonth(), along with the current year which can be accessed via DateTime.Now.Year
Example:
Dim userMonth As String
' Prompt the user to enter the month and assign it to userMonth.

Dim iMonth As Integer = 0
If Int32.TryParse(userMonth, iMonth) AndAlso (iMonth >= 1 And iMonth <= 12) Then
   Dim iDaysInMonth As Integer = DateTime.DaysInMonth(DateTime.Now.Year, iMonth)
   Dim sMonthName As String = Microsoft.VisualBasic.DateAndTime.MonthName(iMonth)
   MessageBox.Show($"Days in month {sMonthName}: {iDaysInMonth}")
Else
   MessageBox.Show($"Invalid month specified: {userMonth}", "Error")
End If

You could also not check the value of iMonth and wrap the DateTime.DaysInMonth() call in a try/catch block, since it will throw an ArgumentOutOfRangeException if iMonth is invalid.


text:
Q: Android 9 armeabi-v7 emulator I am trying to install an app with an armeabi-v7a native library on my emulator. The old arm system images run really slowly in the emulator. According to the Emulator release notes here One can use any image of android version 9 and 11 to run armeabi-v7a. However after downloading Intel x86 atom image of android version 9 via the SDK manager, I am still not able to install/debug my app on the emulator. Is there anything else I need to do to get this working?

A: When selecting a system image for AVD, navigate to "x86 images" and select the one that says Android 9.0 (Google x86_ARM). Or use any R images as this announcement suggests: https://android-developers.googleblog.com/2020/03/run-arm-apps-on-android-emulator.html

A: Unfortunately, there is no Android 9.0 (Google x86_ARM) whatsoever listed (at least in the latest Android Studio (as of today).


text:
Q: Jmeter:Difference between jmeter.sh and jmeter without extension file in jmeter I would need clarification on jmeter.sh and jmeter file without ext ,which are in bin folder.
With example:
1.If i setup different HEAP size in jmeter and jmeter.sh file,which one will be considered.?
2.Does the above depend on how i run the test?(for ex: jmeter -n -t or jmeter.sh -n -t)
3.If the test started with jmeter command instead of jmeter.sh ,will intern jmeter.sh be called and hence heap in jmeter.sh be used or vice-versa?
related question to the difference b/w jmeter.bat and jmeter-
difference between jmeter.bat/jmeter.sh And jmeter.file

A: *

*jmeter.sh is a wrapper for jmeter script (without extension) which does some pre-requisite validations like getting current working dir, getting Java version, constructing arguments depending on Java version, etc. so you'd better use this file for running JMeter under Unix and derivatives

*jmeter is a wrapper for ApacheJMeter.jar binary, it sets default JVM arguments and overrides and adds more Java arguments depending on your operating system

The sequence is the following:

*

*jmeter.sh calls jmeter

*jmeter calls ApacheJMeter.jar
If you want to change HEAP or whatever - set the appropriate environment variable like:
HEAP=4G && export HEAP && ./jmeter.sh -n -t /path/to/test.jmx ...

More information: How to Get Started With JMeter: Installation & Test Plans

A: jmeter.sh calls jmeter, both unix scripts , jmeter is the main/default script

jmeter
run JMeter (in GUI mode by default). Defines some JVM settings which may not work for all JVMs.

jmeter.sh
very basic JMeter script (You may need to adapt JVM options like memory settings).

You can set before running both the JVM_ARGS

It may be necessary to set a few environment variables to configure the JVM used by JMeter. Those variables can be either set directly in the shell starting the jmeter script. For example setting the variable JVM_ARGS will override most pre-defined settings, for example

JVM_ARGS="-Xms1024m -Xmx1024m" jmeter -t test.jmx [etc.]

will override the HEAP settings in the script.


text:
Q: Remove the first 2
* content, except what you have inside the tag  How do I remove the content of the first 2
, except what you have inside the tag   of the second
.
My structure is like this:

        Text 1# <input type="text" value="" />

        Text 2# <input type="text" value="" />

        Text 3# <input type="text" value="" />

        Text 4# <input type="text" value="" />

        Text 5# <input type="text" value="" />

        Text 6# <input type="text" value="" />

        Text 7# <input type="text" value="" />

And would have to remove the codes and stay that way:

        2#

        Text 3# <input type="text" value="" />

        Text 4# <input type="text" value="" />

        Text 5# <input type="text" value="" />

        Text 6# <input type="text" value="" />

        Text 7# <input type="text" value="" />

DEMO CODE
(My English sucks, I hope you understood my question, and it has been clear for everyone.)

A: This removes the first list item completely, then all nodes except labels from the second list item.
Demo
$('ul li:nth-child(1)').remove();
$('ul li:nth-child(1)').contents().filter(function(){
    return !$(this).is('label');
}).remove();

A: Here's a possibility (just a quick lesson on JQuery here, but I would go for the 3rd option, see below) :
$('ul li:nth-child(1)').remove();
$('ul li:nth-child(1)').remove(); // child(1) ALSO, BECAUSE #2 HAS NOW BECOME #1 !

// OR MODULAR :
for (i=1; i < 3; i++)
{
    $('ul li:nth-child('+i+')').remove(); // OBVIOUSLY #3 AND #4 ARE REMOVED AS WELL.
}

// YOU CAN CAPTURE AND STORE THE LABEL CONTENT, ERASE THE CONTENT OF THE LI, AND PUT BACK THE LABEL :

for (i=1; i < 3; i++)
{
    var label_content = $('ul li:nth-child('+i+') label').html(); // GETTER
    $('ul li:nth-child('+i+')').html(''); // SETTER (set to empty)
    $('ul li:nth-child('+i+')').html(''+label_content+''); // REINJECT THE LABEL
}

Working Fiddle here : http://jsfiddle.net/U5K5q/1/

But it looks like you just want to "hide" (display:none) your inputs... If it is the case, you may as well do :
for (i=1; i < 3; i++)
{
    $('ul li:nth-child('+i+') input').css('display':'none');
    $('ul li:nth-child('+i+') input').attr('disabled'); // JUST TO MAKE SURE THIS INPUT IS NOT GOING SUBMITTED
}

Or, 3rd option, cleaner :
for (i=1; i < 3; i++)
{
    $('ul li:nth-child('+i+') input').remove(); // OBVIOUSLY #3 AND #4 ARE REMOVED AS WELL.
}

A: This could be your solution:
$('ul li label').each(function() {
    $(this).parent().empty().append($(this));
});

Fiddle:http://jsfiddle.net/FGJLg/


text: Q: Loop though names depending on f I have 11 different data frames called brand1, brand2, brand3, ...., brand11. And I need to create a loop that runs through different functions by calling each of these data frames. I have tried different commands that I found in other similar queries such as "assign" but it doesn't work


text:
Q: Calculating complexity when two recursive calls are involved How to calculate complexity when there are more than one recursive calls?
Such as in this problem.
F(n)
{
   if (n is 1)
     return;
   F(n/2)  //Call 1
   F(n/3)  //Call 2
   F(n/6)  //Call 3
}

A: You just need to solve the equation,
T(n)=T(n/2)+T(n/3)+T(n/6)+O(1)
Now as T(n/2)>T(n/3), we can instead solve for
T(n)=3T(n/2)+O(1)
Using master's theorem, T(n)=O(n^(log(base 2)3))=O(n^1.58)
Note that there might be better solution but as this is Big O notation, this is valid too

A: Interesting question.
I believe I can prove that the complexity of this function is O(nc) for any c > 1.
Recall the definition of big-O notation. We say a function g(n) is O(f(n)) if there exist constants k and n' such that g(n) < k*f(n) for all n > n'. (Colloquially, g(n) is bounded above by f(n) for sufficiently large n, ignoring constant factors.)
Pick any c > 1, and observe that for sufficiently large n,
1 > (1/2)c + (1/3)c + (1/6)c + 1/nc
This is easy to see because 1/2 + 1/3 + 1/6 = 1, and (1/2)c < 1/2 etc. because c > 1. And when n is big enough, 1/nc is arbitrarily small.
Multiply through by nc, to get that for sufficiently large n:
nc > (n/2)c + (n/3)c + (n/6)c + 1
Therefore, if the running time of F(m) is bounded above by mc for m=n/2, m=n/3, and m=n/6, then the running time of F(n) is bounded above by nc. Result follows by induction.
So although I was wrong that this function is O(n), it is arbitrarily close... In the sense that for any positive value epsilon, no matter how small, the function is O(n1+epsilon).
...
In general, for this type of question, I think you want to guess solutions of the form nc and then try to place a bound on c. This is essentially how the Master Theorem itself works.


text:
Q: Node.js chat on Azure website with SSL I created a Node.js chat application with Socket.io. It worked well on local environment. When I deployed on my Azure website with an SSL certificate, I got an error. Can you guys help me?
Server.js:
const connect = require('connect');
const fs = require('fs');

const options = {
  key: fs.readFileSync('./www.reic.vn.key'),
  cert: fs.readFileSync('./www.reic.vn.crt'),
  ca: fs.readFileSync('./bundle.crt'),
  requestCert: false,
  rejectUnauthorized: false
};

onst express = require("express");
const http = require('https');//.createServer(options);
const socketio = require('socket.io');

const bodyParser = require('body-parser');
const routes = require('./utils/routes');
const config = require('./utils/config');

const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/chat');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('we are connected!');
});
var chatSchema = mongoose.Schema({
    From:String,
    Message:String,
    To:String,
    FromIdWeb: String,
    ToIdWeb: String,
    FromImgWeb: String,
    ToImgWeb:String,
    IsReaded: {type:String,default:'1'},
    CreatedDate:{type:Date,default:Date.now}
});
var Chat = mongoose.model('Message',chatSchema);
//
class Server{
    constructor(){
        //this.port =  process.env.PORT || 3000;
        this.port = process.env.HTTPS_PORT||3000;
        this.host = `127.0.0.1`;
        this.app = express();
        //this.https = https.Server(options.this.app);
        this.http = http.Server(options,this.app);
        //this.http = http.Server(this.app);
        this.socket = socketio(this.http);
    }
    appConfig(){
        this.app.use(
            bodyParser.json()
        );
        new config(this.app);
    }
    /* Including app Routes starts*/
    includeRoutes(){
        new routes(this.app,this.socket).routesConfig();
    }
    /* Including app Routes ends*/
    appExecute(){
        debugger;
        this.appConfig();
        this.includeRoutes();
       this.http.listen(this.port, this.host, () => {
            console.log(`Listening on http://${this.host}:${this.port}`);
        });
    }
}
const app = new Server();
app.appExecute();

The port 3000 was created in Azure application setting.
I am using Comodo EssentialSSL certificate. I generated Comodo Certificate file into .gem and .key using OPENSSL-Win32.
This is the result when I run the command node sever.js:

And this error messsage from client computer:
Firefox can't establish a connection to the server at wss://www.reic.vn/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=SbXYLozbTo28Waa4k6r1fueDrvVEmjTozpydvGbJQqTXSiNdEiSr03svJNXa2D8gp1UwYUt85axpXvcdIn4Lkr7GBjP%2FUYN4%2BmEyu5nO7%2FtwC4SJHuV%2F8LjYzbCs1oJ97MMFKEYLo7kP4eHATVBBtw%3D%3D&connectionData=%5B%7B%22name%22%3A%22hubs%22%7D%5D&tid=10.

Hope you guys can help. Thank you!

A: Since you deployed the app to Azure Web Apps (also known as Azure Web Sites), you'd need to pay attention to the following.
1) You don't have to start the Node.js application running on Azure Web Apps via executing the command node server.js manually on Azure. As you have already an entrance file server.js and an IIS web.config in the root directory of your application, you can directly browse your Node.js application via the URL.
2) You shouldn't create any port variable in Azure application setting,  because of Azure uses a pipe port to translate HTTP requests, and Azure Web Apps only expose 80 & 443 port to public.
Please use the following instead:
this.port =  process.env.PORT || 3000;

3) Socket.IO uses WebSockets, which are not enabled by default on Azure. To enable web sockets, go into the Azure Portal, click the web app from the Web Apps blade, click All settings > Application settings. Under Web Sockets, click On. Then click Save.
For more details, please refer to Create a Node.js chat application with Socket.IO in Azure App Service and Secure your app's custom domain with HTTPS.


text:
Q: Is there an enchanted sword in 3ds terraria? I really do not understand what two wikis said. One said that there is not one, and one says that there is an enchanted sword, but no shrines or arkhalis. If so, I want one for my collection.

A: As detailed on the Terraria Wiki, the Enchanted Sword does exist in the 3DS version, but the sword shrines do not exist. This means that you can only find the Enchanted Sword stuck in random background rocks (as shown on the wiki page). These rocks are a random spawn anywhere underground.


text:
Q: How to prove that $\mathrm{GL}_2(\Bbb Z_2)$ has only six subgroups I have found the six subgroups that I know that $\mathrm{GL}_2(\Bbb Z_2)$ has, but now I want to prove that this is all. How can I do this? I am currently thinking that I should argue using the fact that if $H \le G$ is a subgroup, then $|H|$ must divide $|G|$ which would imply that I can have no subgroup of order $4$ or $5$. However I don't think my reasoning is going down a conclusive route. Any help appreciated, thanks!

A: As you wrote in a comment, you're aware that $\mathrm{GL}_2(\Bbb Z_2) \cong S_3$. Subgroups of order $2$ or $3$ must be cyclic and thus generated by one non-identity element; there are five non-identity elements, two of which generate the same subgroup, so that makes $4$ subgroups. The only other possibilities are order $1$ for the trivial subgroup and order $6$ for the group itself, for a total of $6$ subgroups.


text:
Q: zend undefined URL handling hello I am working in Zend. I want to know some thing about undefined URL handling. I have a url like http://localhost/concierge/login and it has the following rule in url rule file.
'admin/login'                  =>array('login',                                array('module'=>'admin','controller' => 'index','action' => 'login'),array(),'login'),. It all works fine.
But if if change the url like http://localhost/concierge/lgin which I have not defined it goes to a blank page where an empty array is shown and there is written Page not Found. IT looks bad. I want to know if user writes any thing wrong in url, My application should show 404 error.
Now I want to know How can I achieve my task? Will I have to define an other rule for url rules files to handle all these errors? If so how this url rule will look like? And for controllers what should I do? Any help ?

A: I do this using the preDispatch hook of a front controller plugin.
public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $disp = Zend_Controller_Front::getInstance()->getDispatcher();
    if ( !$disp->isDispatchable($request) ) {
            $request->setModuleName('default');
            $request->setControllerName('error');
            $request->setActionName('error404');
    }

}
if the thing doesn't exist (  /registerxxx   instead of /register  for
example ) then they get bounced to a 404 page.  It has worked so far for me.


text:
Q: How to loop through 3d array with if statement python? I am trying to loop through a array with an if statement.
For example:
arr = np.arrange(125).reshape(5,5,5)
arr[0][1][:3]

I am trying to loop through the array and multiply by 0.1, if the values are arr[0][1][:3] else multiply by 1.
for a in arr:
  if a == arr[0][1][:3]:
    print(a*0.1)
  else:
    print(a*1)

A: Are you trying to do:
out = np.where(np.isin(arr, arr[0][1][:3]), arr*0.1, arr)

or:
arr = arr.astype(float)
arr[np.where(np.isin(arr, arr[0][1][:3]))] *= 0.1

output:
array([[[  0. ,   1. ,   2. ,   3. ,   4. ],
        [  0.5,   0.6,   0.7,   8. ,   9. ],  # the 3 values 5/6/7 are modified
        [ 10. ,  11. ,  12. ,  13. ,  14. ],
        [ 15. ,  16. ,  17. ,  18. ,  19. ],
        [ 20. ,  21. ,  22. ,  23. ,  24. ]],

       [[ 25. ,  26. ,  27. ,  28. ,  29. ],
        [ 30. ,  31. ,  32. ,  33. ,  34. ],
        [ 35. ,  36. ,  37. ,  38. ,  39. ],
        [ 40. ,  41. ,  42. ,  43. ,  44. ],
        [ 45. ,  46. ,  47. ,  48. ,  49. ]],

       [[ 50. ,  51. ,  52. ,  53. ,  54. ],
        [ 55. ,  56. ,  57. ,  58. ,  59. ],
        [ 60. ,  61. ,  62. ,  63. ,  64. ],
        [ 65. ,  66. ,  67. ,  68. ,  69. ],
        [ 70. ,  71. ,  72. ,  73. ,  74. ]],

       [[ 75. ,  76. ,  77. ,  78. ,  79. ],
        [ 80. ,  81. ,  82. ,  83. ,  84. ],
        [ 85. ,  86. ,  87. ,  88. ,  89. ],
        [ 90. ,  91. ,  92. ,  93. ,  94. ],
        [ 95. ,  96. ,  97. ,  98. ,  99. ]],

       [[100. , 101. , 102. , 103. , 104. ],
        [105. , 106. , 107. , 108. , 109. ],
        [110. , 111. , 112. , 113. , 114. ],
        [115. , 116. , 117. , 118. , 119. ],
        [120. , 121. , 122. , 123. , 124. ]]])


text:
Q: Changing PCIE/ m.2 SSD drive I have this following PCIE SSD on my Lenovo Ideapad U530 20289. I would like to replace this SSD with much more capacity, so I could install windows on it.

I went through few PCIE SSD and I found this following one common as I could not find the same RAMAXEL of higher capacity. Can I replace with this following one ?

A: I'm guessing not. The 'old' SSD is a M.2/NGFF drive, the new drive is a msata drive(which is an older format). You want another m2 drive. M.2 is a LOT smaller and has a different/incompatible pin out. There's also different varients using sata or pcie I believe, with the same M.2 pinout. You want a M.2 sata drive I suspect, rather than a M.2 PCIe drive.
EDIT: The revised drive option looks like it should work. I'd note for posterity the original question had an msata drive


text:
Q: Write to Event log from BizTalk When I try to execute an orchestration with something like EventLog.WriteEntry("MyEsb", "Msg"); in Expression shape, I get the exception The source was not found, but some or all event logs could not be searched.  To create the source, you need permission to read all event logs to make sure that the new source name is unique.  Inaccessible logs: Security. Why?
I'm running Win 7 64bit if this makes any sense.

A: When you write the event log from any application, the event source needs to be already created, or the application itself will try to create it before writing to it. Unfortunately, creating an event source is an action which requires local admin priveledges.
So you can do two things:

*

*pre-create the event source

*make sure the user which your biztalk host is running as is in local admins (bad)

To pre-create the event source is a nicer option. You can do this via the powershell command
New-EventLog -LogName "Application" -Source "MyEsb"

A: Might seem like I'm stating the obvious but has the BizTalk User got permission to write to the Eventlog? That is, the account of the Host Instance running the Orchestration.
You'll probably find that it hasn't.
HTH

A: Finally I've found a solution. As the error says, "To create the source, you need permission to read all event logs to make sure that the new source name is unique. Inaccessible logs: Security." So even though BizTalk User account has enough rights to write to the eventlog it has no rights to read EventLog\Security log as stated here in a Note in the Remarks section:

The reason for this requirement is that all event logs, including security, must be searched to determine whether the event source is unique. Starting with Windows Vista, users do not have permission to access the security log; therefore, a SecurityException is thrown.

So I just granted a Read Access to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Security for BizTalk User and the problem was solved.


text:
Q: Why python IDLE and Console produce different results I write a simple Python script to translate Chinese Punctuation to English.
import codecs, sys

def trcn():
    tr = lambda x: x.translate(str.maketrans(""",。!?;:、()【】『』「」﹁﹂""''《》~¥…—×""", """,.!?;:,()[][][][]""''<>~$^-*"""))
    out = codecs.getwriter('utf-8')(sys.stdout)
    for line in sys.stdin:
        out.write(tr(line))

if __name__ == '__main__':
    if not len(sys.argv) == 1:
        print("usage:\n\t{0} STDIN STDOUT".format(sys.argv[0]))
        sys.exit(-1)
    trcn()
    sys.exit(0)

But something is wrong with UNICODE.
I cannot get it passed. Error msg:
Traceback (most recent call last):
  File "trcn.py", line 13, in <module>
    trcn()
  File "trcn.py", line 7, in trcn
    out.write(tr(line))
  File "C:\Python31\Lib\codecs.py", line 356, in write
    self.stream.write(data)
TypeError: must be str, not bytes

After then, I test the out.write() in IDLE and Console.
They produced different results.
I don't know why.
In IDLE
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import sys,codecs
>>> out = codecs.getwriter('utf-8')(sys.stdout)
>>> out.write('hello')
hello
>>>

In Console
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys,codecs
>>> out = codecs.getwriter('utf-8')(sys.stdout)
>>> out.write('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python31\Lib\codecs.py", line 356, in write
    self.stream.write(data)
TypeError: must be str, not bytes
>>>

Platform: Windows XP EN

A: Your encoded output is coming out of the encoder as bytes, and therefore must be passed to sys.stdout.buffer:
out = codecs.getwriter('utf-8')(sys.stdout.buffer)

I'm not entirely sure why your code acts differently in IDLE versus the console, but the above may help. Perhaps IDLE's sys.stdout actually expects bytes instead of characters (hopefully it has a .buffer that also expects bytes).

A: IDLE redirects the stdout to its own GUI output. It apparently accepts bytes as well as strings, which normal stdout doesn't.
Either decode it to Unicode, or print it to sys.stdout.buffer.

A: It is very well obvious that the console's encoding is not utf-8. there is a way to specify the encoding as optional parameter when invoking python in console. just look for it in python docs.


text:
Q: Problem with import in latest version of Drools I'm new to Drools and I'm trying to start using different tutorials. Lately I've started those two: https://koziolekweb.pl/2008/10/30/jboss-rules-drools-silnik-regul-biznesowych/ and https://www.youtube.com/watch?v=zQhDe_PT60Y but they're using older Drools and I'm using version 7.62.Final. My errors are within those imports:
import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.StatefulSession;
import org.drools.StatelessSession;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.drools.rule.Package;

and
import org.drools.StatefulSession;

Have they changed in new version of Drools? How may I change them in the code while using for example PackageBuilder builder = new PackageBuilder(); etc? And where can I find this information if it's available?
Thanks

A: Those tutorials are written against a very old version of Drools (probably Drools 4 or 5, based on the publish date.) Between Drools 5 and 6 there was effectively a complete rewrite, so the backend of the Drools library is completely different.
The imports you mention no longer exist. They no longer exist because their concepts have fundamentally changed. In Drools 5, we had Rule Bases. In Drools 7, we have Kie Bases. Configurations, defaults, how you load and fire rules ... everything is different. If you want to follow those tutorials, down-rev to Drools 5 ... but you can't go to 6.x or newer.
Your best bet is to completely ignore the tutorials -- which are worthless -- and just read the documentation. The Drools documentation is actually very good, and very in depth. Otherwise if you insist on reading tutorials, make sure that you find tutorials targeting 7 (and the newer version of Drools 7 the better, because after 7.44 or so they started implementing non-backwards compatible changes in minor releases.)

A: Latest from drools is v7.x. I followed the drools examples from the official repository. Check the examples from https://github.com/kiegroup/drools.git
And make sure you switch to latest branch example 'r7.73.0.Final'
Refer the official documentation. I found it a bit overwhelming to understand it initially.
https://docs.drools.org/7.73.0.Final/drools-docs/html_single/index.html

A: If you build is complaining that it is not finding these imports the real problem is likely that you do not have the correct maven dependencies in your pom.xml downloaded; I am sure that DROOLS still uses the StatelessSession, StatefulSession, etc.
There are two ways to update your pom.xml to use the correct dependency.  Do a search on Google
maven org.drools.StatelessSession

and the first item returned is jar.download.com - which let's you download the JAR containing the StatelessSession class for a specific version of the tool.  The sixth entry returned by the search is for https://mvnrepository.com - where these JARs are officially stored - showing you the pom.xml dependency for a specific version.  Either way, you should make sure you get the correct version of the JAR specified in the pom.xml or downloaded.
DROOLS, JBPM, KIE, etc. use a BOM (bill of materials) project to specify the version of dependencies across a technology (i.e., so if there are 8 hibernate dependencies all 8 reflect the same version.)  Your DROOLS documentation probably lists these versions or has a link to the BOM.

A: One of the blog you are referring is very old and after that there huge amount of changes in the dependencies. You should try updating your pom.xml file and Java Code accordingly. You can download required dependencies from https://mvnrepository.com/
Can you attach you project here ?


text:
Q: Constructor throws eaccessviolation when initializing class variables Delphi 2010. I am trying to initialize class variables in the constructor of a class (A). Then I want to have a reference to that class throughout the functions of another class (B - the main Form). When I try to initialize the class using a local variable in a B function, all works but if I declare an instance of A in B's private or public areas or under var, it throws an eaccessviolation when Create is called. Having a ref to A global to B is absolutely essential in many programming tasks. Just cannot find a way to do it.
My code:
uses MyFavs;

type
  TForm4 = class(TForm)
    procedure FormActivate(Sender: TObject);
  private

  public
    mfav : TMyFavs;
  end;

var
  Form4: TForm4;

implementation

{$R *.dfm}

procedure TForm4.FormActivate(Sender: TObject);
begin
    mfav.Create;   //crash here
end;

TMyFavs is just dummy code that declares a private integer and assigns it value 1 in the constructor. Even if the constructor does nothing or there is no declared constructor, calling Create still throws the exception. The problem is not there, it must be in the declaration of myfav global to the class Form4 and this happens whether I put the declaration under the type's private, public or var. I know this is very basic but I cannot find the answer.


text:
Q: Randomised video background webflow - not working I'm trying to get a randomised video background for my webflow site. I've tried doing it in with Javascript pulling in the following links:
"https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63f787b42f81b8648e70feda_Goldfish.mp4" 10% of the time
"https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63f787fb4b2937100792cf14_Black%20Texture.mp4" 45% of the time
and
"https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63eb5f178ae8e42595f1d524_Fish%20TV.mp4" 45% of the time
This is the code I've tried - this was put in  section of the custom code in Webflow.
(function() {
  var videoUrls = [
    {
      url: "https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63f787fb4b2937100792cf14_Black%20Texture.mp4",
      probability: 0.45
    },
    {
      url: "https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63f787b42f81b8648e70feda_Goldfish.mp4",
      probability: 0.1
    },
    {
      url: "https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63eb5f178ae8e42595f1d524_Fish%20TV.mp4",
      probability: 0.45
    }
  ];

  var backgroundVideo = document.querySelector('.bg-video');

  // Create an array with one element for each video URL, where each element's value
  // is the URL repeated a number of times proportional to its probability
  var videoUrlsWeighted = videoUrls.reduce(function(acc, curr) {
    var weightedArray = Array(Math.round(curr.probability * 100)).fill(curr.url);
    return acc.concat(weightedArray);
  }, []);

  function playRandomVideo() {
    // Choose a random video URL from the weighted array
    var randomIndex = Math.floor(Math.random() * videoUrlsWeighted.length);
    var randomUrl = videoUrlsWeighted[randomIndex];

    // Set the background video to the chosen URL
    backgroundVideo.style.backgroundImage = 'url(' + randomUrl + ')';
  }

  // Play a random video when the page loads
  playRandomVideo();

  // Play a new random video after the current video has finished
  backgroundVideo.addEventListener('ended', function() {
    playRandomVideo();
  });

  // Set the videos to loop
  backgroundVideo.loop = true;
})();


text:
Q: Broadcast receiver OnReceive not being called in Xamarin Android I'm not usually posting questions on forums like this one, but today my frustration reached the sky.
I am trying to implement a solution that would let me update the Exchange rate list in my application every every hour/day (doesn't matter). I was looking for the answer to my problem on many forums, but even though other people had the same problem of onReceive not being called, none of answers helped me.
I am currently trying to run a Broadcast Receiver that is being fired by AlarmManager's SetRepeating Method. My code for Main activity + Receiver + Manifest look like this:
Main method (just a block of code with starting the alarm):
    var lvarManager = (AlarmManager)GetSystemService (Context.AlarmService);

    Intent lvarCurrencyIntent = new Intent (this, typeof(CurrencyUpdateService));

    var lvarPendingIntent = PendingIntent.GetBroadcast (this, 0, lvarCurrencyIntent, PendingIntentFlags.CancelCurrent);
    lvarManager.SetRepeating (AlarmType.Rtc, 1000, 5000, lvarPendingIntent);

Receiver:
    public class CurrencyUpdateService : BroadcastReceiver
{
    public override void OnReceive (Context context, Intent intent)
    {
        Toast.MakeText (context, "Running", ToastLength.Short).Show ();
    }
}

Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="SplitTheBill.SplitTheBill" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application android:label="SplitTheBill" android:icon="@drawable/groups"></application>
<receiver android:process=":remote" android:name=".CurrencyUpdateService"/>
<provider android:name="mono.MonoRuntimeProvider" android:exported="false" android:initOrder="2147483647" android:authorities="StockService.StockService.mono.MonoRuntimeProvider.__mono_init__" />

I want to state that I'm a somewhat new user of Xamarin and as it quite succesfully makes shure that you don't touch Manifest files, I only added the line:
<receiver android:process=":remote" android:name=".CurrencyUpdateService"/>

I tried running the code in a fresh solution and it didn't work. I tried using different types of Alarm types and Services with no luck.
Feel free to suggest your own solutions and laugh at my face for asking obvious questions ;)

A: 1st) Tag your broadcast receiver class with the BroadcastReceiver attribute so that the appropriate tag gets generated in your AndroidManifest.xml at compile time:
[BroadcastReceiver]
public class CurrencyUpdateService : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        Toast.MakeText(context, "Running", ToastLength.Short).Show();
    }
}

Now your receiver will start toasting every 5 seconds.
Note: Xamarin auto-generates Android class name identifiers so if you do not hard-code a name for your class, there is no way to manually edit the manifest to add this item.
AndroidManifest.xml from the above code generates (for me):
<receiver android:name="md57db81284125fca721c48509d8e9cea0b.CurrencyUpdateService" />

Now if you manually add a Name to the Attribute, you can control what is generated. This is needed in cases where other Android applications need to call you and need a pre-defined (static) name to do so.
[BroadcastReceiver(Name = "com.sushihangover.alarmso.Foobar")]
public class CurrencyUpdateService : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        Toast.MakeText(context, "Running", ToastLength.Short).Show();
    }
}

Note: Do not use Android-style "dot name", use the fully qualified name that includes your package name, see link for details
AndroidManifest.xml now contains:
<receiver android:name="com.sushihangover.alarmso.Foobar" />

2nd) As far as why you are trying to start a new process, remember that a BroadcastReceiver is not an Android Service... You can remove the :process tag in your manifest as it is not needed for what you're are doing.
If you really are looking to create and start a local or background service, you should checkout:

*

*https://developer.xamarin.com/guides/android/application_fundamentals/services/part_1_-_started_services/

A: Thank you for the answer.
I finally got it to work by adding an intent filter attribute to the CurrencyUpdateService class, but I realized that what I really needed was a sticky service that was going to run even if the application was closed.
I finished with a service that is running every day at specified time (also 5 seconds after the app is closed due to service being sticky) + BroadcastReceiver for system reboot to reschedule the service + couple of other broadcast receivers to make the app work smarter.
The only thing to remember is to not believe AlarmManager when it comes to testing on short intervals (< 10 mins) as sometimes it fires the alarm way out of time.


text:
Q: Android: Tabbed actionbar in portrait mode I am unsure what to search for this so all links are appreciated.
When I change the orientation of my device to portrait mode all the tabs are going below the action bar, not on it, even though there is plenty of room (I am using 2 tabs while testing on a Nexus 10). Will the tabs always appear below the action bar in portrait mode or is there a way around this?
What I want to happen:

(source: android.com)
What is happening: NOTE: this is the behavior I am getting even when there is PLENTY of room to display the tabs in the action bar:

(source: android.com)
Thanks in advance!

A:
Will the tabs always appear below the action bar in portrait mode

On small/normal screens, yes. Action bar tabs will go where the action bar implementation wants to put them... which includes them not being tabs at all in some cases, but a drop-down list instead.


text:
Q: AS3 - Drag to scroll ScrollPane with middle/right button I know that it's possible to let the user drag the content in a ScrollPane around using scrollDrag, so that they don't have to use the scrollbars. However, with scrollDrag, it only works for the left mouse button.
What I want to be able to do is pretty much the same, but for either the middle (mousewheel) or right mouse button. That way the user can use the left button for other functions.
Does anybody know of a feature I may have missed that can do this, or a custom method? Note that I don't want this, I just want scrollDrag with other mouse buttons.


text:
Q: (SQL) How to select the correct row for each group? I have a piece of data:
+------------+-----------+-----------+------------+--------------+
| first_name | last_name | family_id | is_primary | is_secondary |
+------------+-----------+-----------+------------+--------------+
| a          | b         |         1 |          1 |            0 |
| aa         | bb        |         1 |          0 |            0 |
| c          | d         |         1 |          0 |            0 |
| cc         | dd        |         1 |          0 |            0 |
| e          | f         |        10 |          0 |            0 |
| e          | f         |        10 |          0 |            1 |
| gg         | hh        |        10 |          0 |            1 |
| gg         | hh        |        10 |          0 |            0 |
| gg         | hh        |        10 |          0 |            0 |
| gg         | hh        |        10 |          0 |            0 |
+------------+-----------+-----------+------------+--------------+

What I want to do are:

*

*Group by family_id (So we will have two groups)

*For each group, if there are some rows that have is_primary equals 1, then choose a random row of them and get its first_name and last_name as the output of the group's two columns

*For each group, if there is no row that has is_primary equals 1, find a row (any row is ok) that has is_secondary equals to 1 and get its first_name and last_name as the output of the group's two columns

So based on the logic described above and the data, the correct result should be:
+-----------+------------+-----------+
| family_id | first_name | last_name |
+-----------+------------+-----------+
|         1 | a          | b         |
|        10 | e          | f         |
+-----------+------------+-----------+

Or
+-----------+------------+-----------+
| family_id | first_name | last_name |
+-----------+------------+-----------+
|         1 | a          | b         |
|        10 | gg         | hh        |
+-----------+------------+-----------+

How can I write the query to get the correct result?
Below is the script to create the test table.
USE tempdb
GO
IF OBJECT_ID('dbo.mytable') IS NOT NULL DROP TABLE dbo.mytable;
CREATE TABLE mytable (
    first_name   VARCHAR(2) NOT NULL,
    last_name    VARCHAR(2) NOT NULL,
    family_id    INTEGER    NOT NULL,
    is_primary   INTEGER    NOT NULL,
    is_secondary INTEGER    NOT NULL);

INSERT INTO mytable VALUES ('a','b',1,1,0);
INSERT INTO mytable VALUES ('aa','bb',1,0,0);
INSERT INTO mytable VALUES ('c','d',1,0,0);
INSERT INTO mytable VALUES ('cc','dd',1,0,0);
INSERT INTO mytable VALUES ('e','f',10,0,0);
INSERT INTO mytable VALUES ('e','f',10,0,1);
INSERT INTO mytable VALUES ('gg','hh',10,0,1);
INSERT INTO mytable VALUES ('gg','hh',10,0,0);
INSERT INTO mytable VALUES ('gg','hh',10,0,0);
INSERT INTO mytable VALUES ('gg','hh',10,0,0);
GO

SELECT * FROM dbo.mytable;

A: Try this approach:
;with x as (
    select *, row_number() over(partition by family_id order by is_primary desc, is_secondary desc) rn
    from mytable
    where is_primary+is_secondary = 1
)
select * from x where rn = 1

(thanks for the create & insert script)
EDIT:
As per OP comment (that both flags could be 1), change the WHERE clause to this:
where is_primary = 1 or (is_primary = 0 and is_secondary = 1)

A: If the rows selected must be random, then use the following:
WITH primary_families AS (
    SELECT   family_id
            ,first_name
            ,last_name
            ,ROW_NUMBER() OVER(ORDER BY NEWID()) AS r
    FROM familytable
    WHERE is_primary = 1
),
secondary_families AS (
    SELECT   family_id
            ,first_name
            ,last_name
            ,ROW_NUMBER() OVER(ORDER BY NEWID()) AS r
    FROM familytable f
    WHERE is_secondary = 1
    AND NOT EXISTS (
        SELECT 1
        FROM familytable
        WHERE family_id = f.family_id
        AND is_primary = 1
    )
)

SELECT   f.family_id
        ,f.first_name
        ,f.last_name
FROM primary_families f
WHERE f.r = 1

UNION

SELECT   f.family_id
        ,f.first_name
        ,f.last_name
FROM secondary_families f
WHERE f.r = 1

A: It's not an answer to your specific question, just an observation. If I had to develop a software or web application with such logic I would move it from SQL to the available programming language. Retrieve the interested data set, scan it, split in group and sort.


text:
Q: Stop items showing before Masonry is initialised I am trying to append Masonry elements to existing ones.
However, what I currently have is this - the items show before Masonry is initialised then jump into position a second later. I'd like them to be hidden until they're in position.
This is the code (within an infinite scroll plugin) that I'm using to append the Masonry items:
$container.append(data);
$container.imagesLoaded( function()
{
    $container.masonry('reloadItems').masonry();
});

And here it is being initialised:
$(document).ready(function ()
{
    $container = $('#container');
    // initialize the masonry instance
    $container.imagesLoaded(function(){
        $container.masonry({
            columnWidth: 1,
            itemSelector: '.item',
            transitionDuration: 0
        });
    });

    $('#container').scrollPagination({

        nop     : 36, // The number of posts per scroll to be loaded
        offset  : 0, // Initial offset, begins at 0 in this case
        error   : 'No More Posts!', // When the user reaches the end this is the message that is
                                    // displayed. You can change this if you want.
        delay   : 500, // When you scroll down the posts will load after a delayed amount of time.
                       // This is mainly for usability concerns. You can alter this as you see fit
        scroll  : true // The main bit, if set to false posts will not load as the user scrolls.
                       // but will still load if the user clicks.
    });
});

UPDATE
Based on Josh's answer, my code now looks like this:
$container.append(data);
$container.imagesLoaded( function()
{
    $(".item").show();
    $container.masonry('reloadItems').masonry();
});

And I've added <class='hide'> to the item tag.
However, now no elements show up when I refresh the page.

A: Have them load with the bootstrap hidden class set, and remove it after masonry runs.
If masonry needs them to be visible to do its calculations, have them displayed off-screen when loaded. Z-index, crazy position, etc.
Update
http://masonry.desandro.com/methods.html
So I gave a quick glance at methods here, without this trickery I talked about, I do believe you can ajax-load your new items, then use the masonry.addItems( items ) method.


text:
Q: How to convert XML to Java Object in Android I wondering that which is the best libray to convert XML to Java Object easily.
I have used XStream but i am not getting what i want.
I want to pass this xml.
http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=ttc&r=54
Please, suggest me some good library.

A: XStream and JAXB allows you to convert an XML Schema (XSD) file into a collection of Java classes. This may be more "structured" than the XMLEncoder/Serializable approach that Andy's (excellent, by the way) answer provides.


text:
Q: diagonal matrix and unbiaseness Let the model be linear $Y=X\beta+e$ with $m$ covariates in X and error be i.i.d Gaussian. I noticed that if there are some collinearity in X then, $X'X$ is not diagonal. Then the estimation of the parameter is biased, $\hat\beta=(X'X)^{-1}X'y$. Is that really true that estimations are biased in the presence of collinearity in variables?

A: If $Y = X\beta + \varepsilon$ and $E(\varepsilon) = 0$ then (as Brian mentioned) $E(\hat \beta) = \beta$. That happens no matter what $X$ is (provided it is known and fixed), although we are assuming that $X$ is full rank when we use the existence of $(X^T X)^{-1}$.
What happens when $X^T X$ is diagonal is that each $\hat \beta_i$ is independent. Without loss of generality let's assume that $X^T X = I_p$, so that $X$ is orthonormal. Let's also assume $\varepsilon \sim \mathcal N(0, \sigma^2 I_n)$ so that these results are exact rather than asymptotic. We can show from this that $\hat \beta \sim \mathcal N(\beta, (X^T X)^{-1}\sigma^2)$ so if $X^T X = I$ then $\forall i \neq j$ $Cov(\hat \beta_i, \hat \beta_j) = 0$ $\implies$ $\hat \beta_i \perp \hat \beta_j$ (since they're jointly normal).
So, in conclusion, when our predictors are correlated (and consequently $X^T X$ is not diagonal) we still have unbiasedness, but it is no longer the case that $\hat \beta_i \perp \hat \beta_j$. This means that the addition or deletion of one predictor may affect the estimated effects of the other predictors.

A: If $y=X\beta$, then what is $E[\hat{\beta}]$?  It's pretty easy to show that $E[\hat{\beta}]=\beta$.


text:
Q: Percent of Total by row pivot table Im am using the following function:
def pivot_count(df, rows, columns, calc_field):
    df_pivot = df.pivot_table(values=calc_field,
                              index=rows,
                              columns=columns,
                              aggfunc=np.size
                             ).dropna(axis=0, how='all')
    return df_pivot

To create a pivot table with the count of each 'calc_field' to get something like this :
ProfitCluster   Affluent Customer   High Net Worth  Mass Customer
HighMargin             302                324           568
HighRevenue            301                323           645
LessProfitable         246                246           529

How can i modify the function to get something like this :
ProfitCluster   Affluent Customer   High Net Worth  Mass Customer
HighMargin             0.25               0.27          0.47
HighRevenue            0.23               0.25          0.50
LessProfitable         0.24               0.24          0.51

Thanks, SOA community.

A: Change to crossstab
def pivot_count(df, rows, columns, calc_field):
    df_pivot = pd.crossstab(values=df[calc_field],
                              index=df[rows],
                              columns=df[columns],
                              normalize='index',
                              aggfunc=np.size
                             )
    return df_pivot


text:
Q: Video encoding for websites I am a little new to embedding videos on a website. What is the best way to go about it? I just started reading up on it.
I read that I should use HTML5 and the browser's native player. -- Does anyone know of a javascript library that will use the browser's player and detect if the browser is not using HTML5 to downgrade to a flash player?
As far as encoding what is the best approach? I am planning on writing a little console app to use FFMPEG to convert the videos. But what encoding should I use? I heard H.264 is promising? But

A: This is what you're looking for: http://videojs.com/
Encoding wise, I think H.264 and WebM is a wise choice. That way you'll satisfy all modern browsers and mobile devices (incl. iOS and Android), and only fall back to Flash for older, pre-HTML5  browsers (and FF 3.6, which only supports Theora.)

A: The DIY approach would be to use the Video For Everybody embed code. That will lead with HTML5 video and fallback to flash.
Then for video encoding, you can use FFmpeg like you said.
To make your life easier, you should check out VideoJS for your HTML5 video player. It handles a lot of cross browser issues and some extra features that browsers don't support yet.
For video encoding, if you're planning to use FFmpeg specifically for automating encoding, you should check out Zencoder's video encoding API. It could save you some set up time and compatibility issues.
For codecs, #1 priority should be h.264, specifically using the baseline profile so it will work on smartphones. After that, ogg and webm are both good choices. WebM is higher quality for file size, but Ogg can be viewed by way more users because older version of Firefox support it. And just to note, if you only do h.264, the Video For Everybody code won't fallback to Flash in Firefox and Opera (that don't support h.264) so you'll need to use a player like VideoJS.

A: Use Handbrake for video encoding, especially for HTML 5 support.
HTML 5 is an awesome way of embedding video, however it hasn't been standardized yet.  You definitely want to use it if you're supporting iOS devices, as they of course don't support Flash which is the most mainstream way of embedding video.
HTML5 is pretty awesome because this is how simple it is:
<video src="video.m4v" />

Here is a fantastic link you will find useful:
http://www.robwalshonline.com/posts/tutorial-serving-html5-video-cross-browser-including-ipad/

A:
I read that I should use HTML5 and the
  browser's native player

Which idiot told you that? Given that you will loose out on a significant portion of the client population you either run a monoculture of HTML 5 browsers, of whoever said that should be serving burgers at McDonalds, not give advice to people. HTML 5 and the integrated player are nice, but not there yet for the general public. In a couple of years, yes. Now - if I hire a web company for putting videos on a website and they do that, they get sued for gross neglect and incompetence.
Today, playback is mostly flash - that has a high penetration. A flash video player is also what sites like youtube currently use. If you go for less (penetration), Silverlight is very good and has the complete backend infrastructure.

I heard H.264 is promising?

So what? FIRST you need to fix the playback side, then you use whatever format is most efficient given your playback decision.


text:
Q: Add class to current tr I'm dynamically populating a table. If a certain condition applies, I want to add a class to the current tr:
number = 3;

for (i = 0; i < 5; i++) {
  var row = "";
  row += "
Test" + i + "
"

  $('#mytable').find('tbody:last').append(row);

  if (i == number) {
    $('#mytable').find('tbody:last').addClass("red");
  }
}

Unfortunately, the class is being added to all trs, not only the one of them.
Here is a fiddle.

A: You can use .eq() or :eq() selector
$('#mytable tbody tr').eq(number).addClass('red');

Fiddle Demo
Note that the index provided to eq() is zero-based. Thus passing 3 will select the fourth element.

The counter in the loop i can also be used with conditional operator
row += "
Test" + i + "
"
//              ^^ ================================ ^^

Fiddle Demo

A: I would try this:
number = 3;
for (i = 0; i < 5; i++) {
  var row = $('
');
  if (i == number) row.addClass('red');
  row.append($('').html('Test'+i));
  $('#mytable').find('tbody:last').append(row);
}

A: Create the row as a jQuery object so you have a reference to it. Then you can simply add a class to it if your clause is met rather than having to find it again.
EG:

var number = 3;
var $tbody = $('#mytable');
for (i = 0; i < 5; i++) {
    var $row = $("
Test"+i+"
");// create the row as a jquery object so we have a reference to it
    $tbody.append($row);// append it to the table
    if (i == number) {// if your clause is met
        $row.addClass("red");// add a classname
    }
}
.red {color:red;}

A: $('#mytable tbody:last tr:last').addClass("red");

This will select last tr and adds class only to last tr(which you just appended)

A: No need to modify more on this just replace one thing find('tbody tr:last'), please find code below
number = 3;

for (i = 0; i < 5; i++) {
 var row = "";
 row += "
Test" + i + "
"

 $('#mytable').find('tbody:last').append(row);

 if (i == number) {
   $('#mytable').find('tbody tr:last').addClass("red");
 }
}

A: You could avoid using addClass() altogether by adding a class directly when constructing the HTML:
for (i = 0; i < 5; i++) {
  var row = "";
  var rowClass = (i == number) ? " class='red' " : "";
  row += "
Test" + i + "
"

  $('#mytable').find('tbody:last').append(row);
}

https://jsfiddle.net/0k9fazum/
Otherwise as Pointy has pointed out you should select tr not tbody and Tushar's answer demonstrates how you can select specific tr via indices when :latest won't help.

A: Problem:  $('#mytable').find('tbody:last').addClass("red");
 Solution :  $('#mytable').find('tbody tr:last').addClass("red");
 number = 3;

    for (i = 0; i < 5; i++) {
      var row = "";
      row += "
Test" + i + "
"

      $('#mytable').find('tbody:last').append(row);

      if (i == number) {
        $('#mytable').find('tbody tr:last').addClass("red");
      }
    }

https://jsfiddle.net/shadiq_aust/Lan0fv36/4/


text:
Q: Need to escape two colons in jquery selector I need to select an HTML element using JQuery, and the selector that I'm using has two colons. I'm trying to escape these colons.

function escapeColon(selector) {
   return selector.replace(/::/, '\\\\:\\\\:');
}
var stringToEscape = "some::value_test";
var selector = $("[value|='" + escapeColon(stringToEscape) + "']");

My code above isn't working for some reason. I can get it to work fine when there is one ':' in the selector, but not when there are two.

A: jQuery has the method built in. escapeSelector

var stringToEscape = "some::value";

var elem = $("[value|='" + $.escapeSelector(stringToEscape) + "']");
console.log(elem.attr("value"));

stringToEscape = "some::value_test";
elem = $("[value|='" + $.escapeSelector(stringToEscape) + "']");
console.log(elem.attr("value"));

With your code, you are escaping the \ too many times.

function escapeColon(selector) {
   return selector.replace(/:/g, '\\:');
}
var stringToEscape = "some::value";
var elem = $("[value|='" + escapeColon(stringToEscape) + "']");

console.log(elem);


text:
Q: Remove element by name/value from json object How can I remove "window3" from below json object str
var json1 = {"panel0": {"window3":{"collapsed":false},"window0":{"collapsed":false}},"panel1": {"window2":{"collapsed":false},"window1":{"collapsed":false}},"floating":{},"orientation": "horizontal"};
Thank you.

A: In JSONiq it would be:
delete json $json1("panel0")("window3")

(see http://www.zorba-xquery.com/html/demo#KkcoASbF2krqvFgXSwf22RLQJgo= )


text:
Q: NetBeans HTML Code Hinting/Completion for Attributes Has anyone had success with getting NetBeans to display code hinting/completes for html attributes? Yes, it can auto complete tags, but I can't seem to find a definitive answer on whether or not there is a plugin or option to enable completion for attributes akin to Dreamweaver's style.
This is in Dreamweaver:

And this is in NetBeans:

Can NetBeans mimic this feature through a plugin or an obscure option I can't seem to find?

A: If you create a new file of type "HTML" (using file->new file, type->other->html), the attributes will be suggested when you open, say a "" tab. This, I assume, is what you are looking for (me too!). However, I have noticed that you do not get the same if you create a "php web page",
Sorry this does not completely answer the question but it may point you in the right directon. Netbeans needs to be configured to apply the same intellisense dictionary to a php web page (and whatever type of webpage you are editing) that it applies to a html type page

A: You you will get the list of attributes by clicking Ctr+space in php file


text:
Q: VBA-code does not look through hidden rows for adding a row with tracking number I have another question which I hope to resolve with your help.
What do I want to do.
I use Excel to track my work, activities, contacts, et cetera. While doing that I found I was doing a lot of repetitive work in adding rows at the end of a sheet called "Activities".
What I want to do is this:
 - Press a button and adding a row.
 - Increase the trackingnumber with 1
 - Insert default values
The code.
To automate this, I have found (copy, pasted, adjusted it to my needs) the following code:
 Sub AddRowActiviteiten_NewAtEnd()
'Add's a new row at the end of the sheet.

Dim wsActiviteiten As Worksheet
Set wsActiviteiten = Sheets("Activiteiten")

DefType = "Daily"
DefStatus = "Open"
DefIssue = "*****"
DefImpact = "*****"
DefPrio = "Laag"
MyDate = Date

wsActiviteiten.Range("A4").Value = "1"

'Copy the "One Row To Rule Them All"
wsActiviteiten.Range("A3:Q3").Copy

wsActiviteiten.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial (xlPasteAll)

'Stop the "copy-action"
Application.CutCopyMode = False

'Increase the tracking number with "one"
LastNumber = wsActiviteiten.Range("A" & Rows.Count).End(xlUp).Value
wsActiviteiten.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Value = LastNumber + 1

'Insert default values
LastRow = wsActiviteiten.Range("A" & Rows.Count).End(xlUp).Offset(-1, 0).Row
Cells(LastRow + 1, 2) = DefType
Cells(LastRow + 1, 3) = DefStatus
Cells(LastRow + 1, 4) = DefIssue
Cells(LastRow + 1, 5) = DefImpact
Cells(LastRow + 1, 6) = DefPrio
Cells(LastRow + 1, 8) = MyDate

'Step down 1 row from present location.
ActiveCell.Offset(1, 0).Select

End Sub

The problem.
In this sheet I open new items, but I also close them. I do this by changing their status and hide them from view. And this is the point where it goes wrong. When I close the last item on the list and want to add a new row, the macro adds a new row below the last visible entry. It does not find the last entry I have just hidden. And also, when this happens, adding the default values to the new row does not work. It adds them at the row above the added one.
Somehow this makes perfect sense. I tell the macro to look for the last entry, but what I don't understand is why it looks at the last visible entry and why it does not look in the hidden rows.
To replicate. Copy the code into a sheet (maybe you need to change the name of the sheet) and add a few lines. Put some info in the last row and hide it. Add another few lines and see what happens.
The solution. Is there a way to resolve this? Maybe there is a smarter way of doing things? I looked into things, but mostly I got results using "("A" & Rows.Count).End(xlUp)". A loop could work, but I am afraid that 1) It does not search through hidden rows and 2) it makes the sheet (somewhat) sluggish. I must say I have tried to make a loop, first I want to see if my first solution is salvageable.
Thank you for your input, if there are any questions please let me know.
Simon
EDIT: Working code for anyone interested
  Sub AddRowActiviteiten_NewAtEnd()
'Add's a new row at the end of the sheet.

Dim wsActiviteiten As Worksheet
Set wsActiviteiten = Sheets("Activiteiten")

DefType = "Daily"
DefStatus = "Open"
DefIssue = "*****"
DefImpact = "*****"
DefPrio = "Laag"
MyDate = Date

'Copy the One Row To Rule Them All
wsActiviteiten.Range("A3:Q3").Copy

'Offset(y,x)
'De -16 is een getal dat iets doet, maar ik weet niet wat.
wsActiviteiten.Range(Split(ActiveSheet.AutoFilter.Range.Address, ":")(1)).Offset(1, -16).PasteSpecial (xlPasteAll)

'Stop the "copy-action"
Application.CutCopyMode = False

'Het volgnummer verhogen met 1
'Het laatste getal selecteren (LastNumber) en dan plus 1.
LastNumber = wsActiviteiten.Range(Split(ActiveSheet.AutoFilter.Range.Address, ":")(1)).Offset(0, -16).Value
wsActiviteiten.Range(Split(ActiveSheet.AutoFilter.Range.Address, ":")(1)).Offset(1, -16).Value = LastNumber + 1

'Insert default values
LastRow = wsActiviteiten.Range(Split(ActiveSheet.AutoFilter.Range.Address, ":")(1)).Offset(-1, 0).Row
Cells(LastRow + 1, 2) = DefType
Cells(LastRow + 1, 3) = DefStatus
Cells(LastRow + 1, 4) = DefIssue
Cells(LastRow + 1, 5) = DefImpact
Cells(LastRow + 1, 6) = DefPrio
Cells(LastRow + 1, 8) = MyDate

'Step down 1 row from present location.
ActiveCell.Offset(1, 0).Select

End Sub

A: Say we have a status column  AB and we currently close an item by placing the word "Closed" in that column and then hiding the row.
Instead:

*

*Unhide all rows

*Perform any required inserts and edits

*Via a loop, hide all rows marked "Closed"

A: Update
I see your sheet has an autofilter "hiding" the status rows - which Find wont detect, unlike hidden rows.
Suggest you try this updated code below:
Sub Test()

Dim rng1 As Range
If ActiveSheet.AutoFilterMode Then
    MsgBox ActiveSheet.Range(Split(ActiveSheet.AutoFilter.Range.Address, ":")(1)).Row
Else
    Set rng1 = Columns("A:A").Find("*", [a1], xlFormulas, , xlByRows, xlPrevious)
    If Not rng1 Is Nothing Then MsgBox rng1.Row
End If
End Sub

initial post
If you are hiding rows then you can use Find with the xlFormulas option to find entries in hidden rows (unlike xlValues).
Dim rng1 As Range
Set rng1 = Columns("A:A").Find("*", [a1], xlFormulas, , xlByRows, xlPrevious)
MsgBox rng1.Address

A: Use this for getting the last row and it will see the last row, even if it is hidden.
LastRow = wsActiviteiten.UsedRange.Rows.Count

A: I've just found solution:
If you have at least one column in your range with 'consistent' data (all cells in that column are not empty/blank) you can use formula COUNTA and you can reference you code to value of that COUNTA formula.
For example:
Insert formula '=COUNTA(A1:A100000)' in 'B1' cell.
In B1 you will get how many rows you have they are hidden or not.
In your code change:
wsActiviteiten.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial (xlPasteAll)

to
wsActiviteiten.Range("A" & Range("B1").Value).Offset(1, 0).PasteSpecial (xlPasteAll)

Of course, if, for example, cell 'A2' is blank and this is the only blank cell you will need to adjust your formula to '=COUNTA(A1:A100000) +1'.
If you have more blank/empty cells and you don't know the exact number of them (blank cells have been changed dynamically) this method will not work.
As I said previously you need to have at least one column with 'consistent' data (with known number of empty cells in advance if any).


text:
Q: Adding addTarget: method to custom UIView I created a custom UIView something like UIStepper, because I don't like the appearance of the UIStepper. I want UIStepper have a personal count label so I added it to my custom view and created a method to increase-decrease it. Now I need a [customView addTarget:(id) action:(del) forControlEvents:(UIControlEvents)] method to catch UIControlEventValueChanged; but I couldn't find anything about implementing it. I dig around the UIButton.h, UIStepper.h files but no luck too.. Can anyone help me to do that?
Here is how I created the custom view...
CounterView.h
#import <UIKit/UIKit.h>

@interface CounterView : UIView
@property NSString* name;
@property NSInteger count;
@property UILabel *label;
@property NSInteger customTag;

- (id)initWithX:(CGFloat)xPoint WithY:(CGFloat)yPoint WithName:(NSString*)newName withCount:(NSInteger)newCount withCustomTag:(NSInteger)newTag;
@end

CounterView.m
@implementation CounterView

- (id)initWithX:(CGFloat)xPoint WithY:(CGFloat)yPoint WithName:(NSString*)newName withCount:(NSInteger)newCount withCustomTag:(NSInteger)newTag
{
self = [super initWithFrame:CGRectMake(xPoint, yPoint, 24, 52)];
if (self) {
    self.customTag = newTag;
    self.count = newCount;
    self.name = newName;

    UIButton *btnUp = [[UIButton alloc] initWithFrame:CGRectMake(3, 2, 18, 12)];
    [btnUp setImage:[UIImage imageNamed:@"top.png"] forState:UIControlStateNormal];
    [btnUp addTarget:self action:@selector(increaseValue) forControlEvents:UIControlEventTouchUpInside];
    UIButton *btnDown = [[UIButton alloc] initWithFrame:CGRectMake(3, 38, 18, 12)];
    [btnDown setImage:[UIImage imageNamed:@"bottom.png"] forState:UIControlStateNormal];
    [btnDown addTarget:self action:@selector(decreaseValue) forControlEvents:UIControlEventTouchUpInside];
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 14, 24, 24)];
    [self.label setText:[NSString stringWithFormat:@"%ld", (long)self.count]];
    self.label.textAlignment = NSTextAlignmentCenter;

    [self addSubview:btnUp];
    [self addSubview:btnDown];
    [self addSubview:self.label];
}
return self;
}

-(void) increaseValue{
self.count++;
[self.label setText:[NSString stringWithFormat:@"%ld", (long)self.count]];
}
-(void) decreaseValue{
self.count--;
[self.label setText:[NSString stringWithFormat:@"%ld", (long)self.count]];
}
@end

A: Just allow the actions to be set from outside of your control. Here is how to do it:
@interface CounterView : UIView
...
@property(nonatomic, strong) UIButton *btnUp;
@property(nonatomic, strong) UIButton *btnDown;

- (void)addUpTarget:(id)target action:(SEL)action;
- (void)addDownTarget:(id)target action:(SEL)action;

@end

@implementation CounterView

...

- (void)addUpTarget:(id)target action:(SEL)action
{
    [_btnUp addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
}

- (void)addDownTarget:(id)target action:(SEL)action
{
    [_btnDonw addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
}

...

@end

Then use methods:
- (void)addUpTarget:(id)target action:(SEL)action;
- (void)addDonwTarget:(id)target action:(SEL)action;

to set a target and actions for increasing and decreasing the values.

A: in the ViewController where you instantiate your CounterView you add this
UITapGestureRecognizer *singleFingerTap =
  [[UITapGestureRecognizer alloc] initWithTarget:self
                                          action:@selector(handleSingleTap:)];
[yourViewInstantiation addGestureRecognizer:singleFingerTap];
[singleFingerTap release];

and the you implement the call back method:
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
  CGPoint location = [recognizer locationInView:[recognizer.view superview]];

  //Do stuff here...
}

i hope that help you !


text:
Q: Access custom data-* attributes for a list item that has been stored as an array element I can't figure out the right syntax to access custom data-* attributes for list elements of an unordered list that has been sorted and then stored as array elements using:
$("#gridlist").sortable("toArray");

The list elements in the unordered list are generated dynamically by processing array elements like this:
<?php  //generate the list items

for ($i=0;$i<$listsize;$i++){
?>
    <li id="griditem_<?php echo $i ?>"
        class="grid-sort-items"
        data-var1="<?php echo $varone[$i] ?>"
        data-var2="<?php echo $vartwo[$i] ?>"
        data-var3="<?php echo $varthree[$i] ?>"
        data-var4="constant1"
        data-var5="constant2">

        <img class="grid-sort-img" src='<?php echo $image-url[$i] ?>'/>
        <?php echo $image-title[$i] ?>

<?php
}
?>

So far, so good. The unordered list is created, it displays as it should, and it's sortable.  The custom data-* attributes contain/echo what they should.
After sorting the array, I create a new array with the new order of list elements for further processing before sending to database.
The js to create the new sorted array:
    $("#gridlist").sortable({stop: function(event, ui) {
    result = $("#gridlist").sortable("toArray");

    // WHAT I NEED TO DO NOW IS ACCESS A CUSTOM data- ATTRIBUTE OF ANY
    // LIST ITEM STORED IN THE result ARRAY.  I'M NEW TO CUSTOM DATA
    // ATTRIBUTES AND I CAN'T FIGURE IT OUT :( .  THIS DOESN'T WORK:

    alert(result[0].griditem_0.getAttribute('data-var1'));

    }});

I think all I need help with is getting that alert working so I'll understand the syntax.  I have more work to do after that, but once I know how to get at the custom data- attibutes, I think Bob's my uncle.

A: Usage of data attributes is not like that. They are attributes not tags. I don't know what actually going to do but you can give them to li like below.
<?php  //generate the list items

for ($i=0;$i<$listsize;$i++){?>
        <li id="griditem_<?php echo $i ?>"
            class="grid-sort-items"
            data-var1="<?php echo $varone[$i] ?>"
            data-var2="<?php echo $vartwo[$i] ?>"
            data-var3="<?php echo $varthree[$i] ?>"
            data-var4="constant1"
            data-var5="constant2">

            <img class="grid-sort-img" src='<?php echo $image-url[$i] ?>'/>
            <?php echo $image-title[$i] ?>

<?php
}
?>


text:
Q: how to determine what address is invalid for PCI/PCIe memory space I'm writing a PCIe device driver and want to add a sanity check for validity of I/O addresses in memory-mapped space, i.e. that in case a driver user provides invalid address, a driver API that reads/writes in PCI memory-mapped space would return error. The PCI/PCIe spec doesn't define which addresses are considered invalid.
By a driver user I mean another kernel module that might use my API exposed via EXPORT_SYMBOL().
UPDATE
What I have on PCI hardware is as follows:
BAR0 register 0xCDE00000 & 0xFFFFFFF0 = 0xCDE00000 (mask out info bits from BAR register). Now derive the size of region pointed to by BAR0:

*

*save original value of BAR

*write a value of all 1's to BAR register

*read it back

*mask the information bits

*perform a bitwise NOT and increment the value by 1

*restore the original BAR value

Size value is 0x100000, that is 1M, which makes all offsets 20-bits long, so to validate an offset, we can simply apply mask 0xfffff:
if (offset & 0xfffff)
   /* offset is valid */


text:
Q: Show that if $p'=2p+1$ and $p\equiv 3\pmod{4}$, then $2^p\equiv 1\pmod{p'}$ Unsure if this is relevant: In the previous part of the question I deduced that if a number of the form $2^n-1$ is prime (a Mersenne prime), $n$ must also be prime.
Question: For primes $p$ and $p'$, where $p'=2p+1$, does $p\equiv 3\pmod{4}$ imply that $2^p\equiv 1\pmod{p'}$?
Attempt: By Euler's theorem, since $(2,p)=(2,p')=1$ we have $2^{\phi(p')}\equiv 2^{p'-1}\equiv 1\pmod{p'}$. Substituting $p'=2p+1$, we obtain $2^{p'-1}\equiv2^{2p}\equiv 1\pmod{p'}$, and thus $2^p\equiv\pm 1\pmod{p'}$.
Letting $p\equiv 4p_0+3$, then $p'\equiv 2(4p_0+3)+1 \equiv 8p_0+7$. So $p'\equiv 7\pmod{8}$.
I am stuck as to how to link this last bit to show that $2^p\equiv 1\pmod{p'}$, not $2^p\equiv -1\pmod{p'}$.

A: As you pointed out, $p'$ is of the form $8k+7$.  You have probably already seen the proof of the fact that $2$ is a quadratic residue of the odd prime $q$ if and only if $q\equiv \pm 1\pmod{8}$.
So $2$ is a quadratic residue of $p'$, say $2\equiv x^2\pmod{p}$. But $x^{p'-1}=x^{2p}\equiv 1\pmod{p'}$ and therefore $2^{p}\equiv 1\pmod{p'}$.


text:
Q: Show that the ring of polynomials with coefficients in a field, and in infinitely many variables, is not Noetherian Show that the ring of polynomials with coefficients in a
field, and in infinitely many variables, is not Noetherian, that is, $R = k [x_i: i\geq1]$ is not Noetherian.
I know that I need to exhibit an ideal of the ring that is not finitely generated, what could this ideal be? Could it be $(x_1,x_2,...,)$?
Or could I give the following chain of ideals that do not have a maximal element $(x_1)\subset(x_1,x_2)\subset(x_1,x_2,x_3)\subset...$?How can all ideals that are not finitely generated be classified? What to do in the case where the number of variables is non-countable?

A: A ring is Noetherian if and only if it satisfies the ascending chain condition, i.e. every increasing chain of ideals terminates. Now you have a chain
$$(x_1)\subsetneq(x_1,x_2)\subsetneq(x_1,x_2,x_3)\subsetneq\cdots$$
that never terminates, so $k[x_i: i\ge 1]$ is not Noetherian.

A: You've got all the right ideas. You don't need to fully classify the non-finitely-generated ideals to prove that $(x_1,x_2,\dots)$ is not finitely generated. One way to do it is to reason:
Suppose $I = (x_1,x_2,\dots)$ were finitely generated. Then there would be a finite list of generators $f_1,\dots,f_n$. Each $f_i$ would be a polynomial in finitely many variables (because that's what elements of this ring are). Thus, there would be some $N$ that is the maximum $N$ for which $x_N$ appears in any of the $f_i$'s. Then, supposedly, every element of $I$ would be expressible as a linear combination of the $f_i$'s with coefficients in the ring of polynomials. But how would you ever express $x_k$ this way when $k>N$?


text:
Q: Microk8s doesn't start without internet access I have a mickrok8s install from snap that after a power off doesn't start without internet access. Need a solution for not depending on the internet accessibility for my local cluster to work.
Trying to get the status will generate a bunch of:
The connection to the server 127.0.0.1:16443 was refused - did you specify the right host or port?
Any idea what I can do?

A: There has been some discussion on the microk8s github about this issue here : https://github.com/ubuntu/microk8s/issues/1653
Maybe it helps as a solution was proposed there which worked for the issue reporter:

It's working now and I will list out what I did for the benefit of others.
Assuming 192.168.210.32 is your master node IP address.

*

*Run sudo ip route add default via 192.168.210.32 for ALL VM nodes (Worker nodes too otherwise pulling image from local docker registry wouldn't work).

*Disable and enable dns in microk8s

*Run sudo snap restart microk8s

*Remove worker-nodes from cluster and add them back. You should now see Join node with: microk8s 192.168.210.32:25000/JSKjpIGPOcVsJWKrKeoNOGbKdvvYiCiF, notice the IP is now your master node IP (it was the router IP if you have internet connection I think?).

*For me, I encountered ImagePullBackErr in the VMs that hasn't assign a hostname to 192.168.210.32. The pull error was fixed once I assigned 192.168.210.32 with the same hostname as the master node VM's. i.e. I append the line 192.168.210.32 master-node to /etc/hosts


text:
Q: How to split a string by tabs and newlines? I got a tab-delimited file that I want to split by tabs and by newlines where a tab represents the delimiter between fields and a newline represents a new object that should be created. The file can look like this:
Peter\tpeter@example.com\tpeterpassword\nBob\tbob@bobby.com\tbobbypassword\n...
where \t is a tab and \n is a newline.
I want to enable uploading this file to my program that creates a new user for every line in the file with the fields on the line. But how can I use two tokens - both tab and newline? My code would look something like the following:
String everything = "";
BufferedReader br = null;
try {
    br = new BufferedReader(new InputStreamReader(file.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {

       //now create object according to the string
       StringTokenizer st = new StringTokenizer(line , "\t");
       String name = st.nextToken();
       String email = st.nextToken();
       String password = st.nextToken();
       User.createNewUser(name, email, password);

        sb.append(line);
        sb.append('\n');
        line = br.readLine();
    }
    everything = sb.toString();
    br.close();
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println("Everything: " + everything);

Would code like the above work?

A: I would do a String.split("\\n") for each line.  Then you have all the information you need for each user.  Do another String.split("\\t") and construct your object using the resulting array.
From the Java Doc:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html


text:
Q: tensorflow Word2Vec error I downloaded source code of word2vec in github below.
https://github.com/tensorflow/models/blob/master/tutorials/embedding/word2vec.py
I am using tensorflow on pycharm.
I'm using windows 10.
I installed tensorflow, python, numpy which are needed to use tensorflow on windows.
In word2vec.py source code, I set the savepath, trainpath, and evalpath.
I downloaded the training text file from http://mattmahoney.net/dc/text8.zip
which the source code recommended.
But when I ran the code I get the error below:

C:\Users\Sungjin\AppData\Local\Programs\Python\Python35\python.exe
  C:/Users/Sungjin/PycharmProjects/untitled/ImpW2V.py Traceback (most
  recent call last):   File
  "C:/Users/Sungjin/PycharmProjects/untitled/ImpW2V.py", line 43, in

      word2vec = tf.load_op_library(os.path.join(os.path.dirname(os.path.realpath(file)),
  'word2vec_ops.so'))   File
  "C:\Users\Sungjin\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\load_library.py",
  line 64, in load_op_library
      None, None, error_msg, error_code) tensorflow.python.framework.errors_impl.NotFoundError:
  C:\Users\Sungjin\PycharmProjects\untitled\word2vec_ops.so not found
Process finished with exit code 1

I checked Readme.md file on github but there is nothing mentioned about the file.
It seems I have to make word2Vec_ops.so file but I don't know how.

A: You're using windows and .so files are (almost) the equivalent of DLL files but under unix systems. So, even if you could find the .so file, that wouldn't work under windows.
If you're willing to install linux and do everything from there, in the same place where you found word2vec.py you can also find how to build the .so file.
( https://github.com/tensorflow/models/tree/master/tutorials/embedding , it says You will need to compile the ops as follows ). If you don't know how linux and g++ / gcc work, you should probably switch to another project that is windows specific.


text:
Q: How to keep property value of object? This question belongs to fabricJS and canvas. I have define a property named background and initially it set as a false. I need to change object's property state as a true when user add a object to a canvas.
I have tried using background = true; but it change property value in whole canvas. How I do this for particular object when it add to the canvas.

A: If you want objects to have a background property, you need to equip the fabric.js Object type with a background property, by adding that to the prototype.
fabric.Object.prototype.background = false;
Later when you add an object, you can select your target object and assing
myObject.background = true
If you need to alter the object that is being added, you can listen to the object:added global listener on the canvas, like this:
myCanvas.on( 'object:added', function( e ) {
        var object = e.target;
        object.background = true;
} );

If you use object serialization somewhere in your code, you might need to modify the fabricjs-provided object serialization method to include your newly added background property.
fabric.Object.prototype.toObject = ( function ( toObject ) {
    return function () {
        return fabric.util.object.extend( toObject.call( this ), {
            background: this.background
        } );
    };
} )( fabric.Object.prototype.toObject );


text:
Q: Suggestion to execute rule expressions We have a situation where the user will define some set of business rules or expressions. That will be look like,
if(riskvalue <= 100)  // condition
      notifyObservers() // action
      remarks = remarkshistory //expression
      if(allowedriskvalue <= riskvalue) //child condition
          do something   //can be expression or action
      else
          do some other thing

else
     do some thing

We will plan to parse this and save it as a expression with it's type, like condition, expression and action.
We have some set of operands and functions that can be allowed in the rule definition.
Please suggest me some validation techniques to validate the rule definition.
And, I want suggestion that either,

*

*use expression tree to execute the rule expressions?

*use any custom rule parser / evaluator?

*build the logic in dynamic class using code dom and execute it?

Thanks in advance!!!


text:
Q: Selected state is not retaining new selected option OS: Windows 10 Pro
Browser: Opera
So, the issue I'm having, is that when a selection with onChange() is made, the selected option will immediately display (go back) to its previous selected option state.
So, and using the following code:
cont options = [
    { value: 'one', label: 'One' },
    { value: 'two', label: 'Two' }
];

class funcName extends React.Component {

render() {

return (

logChange = (val) => {
    console.log("Selected: " + val);
}

<Select
    name="form-field-name"
    value="one"
    options={options}
    onChange={logChange}
/>
);
}
}

attempting to select option 'Two' is never retained. Immediately the selection is made it goes back to select option 'One' and the displayed value of (val) is always 'One'. If I comment out the onChange line, then the select box functions as expected.
What is the issue here?

A: By specifying the value field you reassign the value each time the render function is invoked. Use defaultValue instead.
LE: Might be worth reading a bit about controlled vs uncontrolled components: https://facebook.github.io/react/docs/forms.html

A: Your root problem is that you don't actually have a component doing anything in your code, so the Select just renders with the static props you set in the beginning.
As Alex says, you need to update the value prop that you are sending to the Select component in order for it to update visually.  At a very basic level you do this by calling setState on a parent component, which you have not created in your example, and pass that value to the child Select component.
<Select
  name="form-field-name"
  value={this.state.selection.value}
  options={options}
  onChange={this.changeSelection}
/>

I have updated your code here for a complete working sample: https://plnkr.co/edit/TlUe2eJd3OSxGkdHIKJP?p=preview


text:
Q: Convert between hypervisor types My company needs to automate the creation of new VM's with our proprietary solution, for this we would like to ship the product either on a a standardized format (OVA seems to be the only "standard" out there) or to be able to convert from the same machine to various different Virtualization types.
Thus far this is made manually, meaning that if a client wants a HyperV VM we need to build it on a HyperV Server we have inhouse, VMWare on VMWare etc... Our goal is to have this automated.
Explaining better: The plan is to have a KVM server, provision the VM and after provisioning export it to an OVA Format, and possibly as as extra courtesy to our clients on their Hypervisor of choice.
I can convert the disks just fine with "qemu-img convert" however i cannot seem to convert the machine definition (XML) to to other formats as needed by other hypervisors.
I cannot find any appropriate tools for this, suggestions?
Note: we do not have access to the hypervisor where these will be installed so we need to export it as OVA/TAR etc...

A: Unfortunately OVA promises far more than it is able to deliver. At best it is a standard format for distributing disk images, but it does very little, if anything, to ensure that a disk image can be booted seamlessly on multiple hypervisors. Every hypervisor emulates a different set of virtual hardware, so guest OS will need different drivers installed for each hypervisor. Some operating systems like Linux are reasonably good are being able to boot with arbitrary hardware, autodetecting drivers to match what they find, but even then its easy to mess up are make it break. eg if your /etc/fstab lists "/" as being on /dev/vda1 disk (for QEMU's virtio-blk disk driver) that's not going to work when booted on VMWare with a SCSI disk that appears as /dev/sda1. Windows is really hard to adapt to different harware as it likes to tightly bind specific drivers to each disk / NIC / etc.
There's also problem that every hypervisor has its own preferred disk image format - VMWare prefers vmdk, QEMU likes raw or qcow2 ideally, VirtualBox has another, etc, etc.  OVA does nothing to address any of these hard problems.
These kind of problems are why tools like virt-v2v (http://libguestfs.org/virt-v2v.1.html) exist which take a disk image for one hypervisor and re-configure the guest OS to work on a different hypervisor, changing disk format at the same time.
Even if you somehow build a disk image that you think works on all of them, you still need to put it through a full QA test cycle to ensure you've actually got it working correctly.
IMHO it is way easier to just build a dedicated disk image for each hypervisor.