text:
Q: VB Simulate a key press In my program, I want to simulate the pressing of the MediaPlayPause key. Just as a note, I do not want to check to see if the key is down or pressed, I want to press the key via my program.
I have tried SendKeys.Send but the special keys are limited to {Enter} and {Tab}, etc.

A: Ok, I ported the c# code from this answer: https://stackoverflow.com/a/7182076/2000557
I don't know VB.Net, but it wasn't too hard to copy over using this guide: http://msdn.microsoft.com/en-us/library/172wfck9.aspx
Anyway, I put a button on the form with a click event.
Imports System.Runtime.InteropServices

Public Class Form1

    'this constant represents the hex value for the key to send to user32.dll
    Const APPCOMMAND_MEDIA_PLAY_PAUSE = &HE0000
    'this constant represents which command. Sort of like the function in user32.dll we are calling.
    Const WM_APPCOMMAND = &H319

    'this declares the user32.dll call to SendMessageW we are making
    Declare Auto Function SendMessageW Lib "user32.dll" Alias "SendMessageW" (
    ByVal hWnd As Integer,
    ByVal Msg As Integer,
    ByVal wParam As Integer,
    ByVal lParam As Integer) As Integer

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'call the SendMessage function with the current window handle, the command we want to use, same handle, and the button we want to press
        SendMessageW(Handle, WM_APPCOMMAND, Handle, APPCOMMAND_MEDIA_PLAY_PAUSE)
    End Sub
End Class

I tested it by opening WMplayer, and the button play/paused the music I had. Let me know if you need any other help. Here's a reference if you want to implement other keys: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646275(v=vs.85).aspx


text:
Q: exported indesign file to pdf, then back to indesign, lost original files I was directed here from Graphic Design Stack Exchange.
The original indesign files were lost, all we have is the File>Save As>*.PDF file remaining. We would like to convert pdf back to indesign. The end result is to rebuild the database in excel, if there are any suggestions to convert directly to excel that would save several steps. If you need to see a sample, let me know. The text is stacked (vertically) and I want to breakout from this format: (stacked vertically)
Name,
Street Address,
City, State, ZIP,
Area Phone,
website
into this: Name, Address, City, State, Zip, Area, Phone, website (horizontally)
This is NOT a table copy and paste.
Any suggestions are deeply appreciated along with software suggestions to accomplish this. Many thanks in advance for your time and suggestions.

A: Depending on what is delimiting the text blocks, try capturing the text with copy all, paste into a new Indesign document, and use the Find/Change function to turn the delimiters (hopefully soft returns) into tabs. Best approach the Find/Change function with caution, i.e.: find, change and find next; not change all!
I believe you could then take that text raw into excel, but that's beyond my realm.
Also watch for Adobe's sketchy order of appearance, equally mysterious!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Processing odd and even values I'm learning about channels and concurrency in GO and I'm stuck on a task.
I want to function that passes a slice, filters the numbers and then prints the channel values. The issue is that when I use the channel it deadlocks the program. This is my code:
package main

import (
    "fmt"
)

func processOdd(inputs []int) chan int {
    oddValues := make(chan int)
    for _, numbers := range inputs {
        go func(num int) {
            if num%2 != 0 {
                oddValues <- num
            }
        }(numbers)
    }
    return oddValues
}

func processEven(inputs []int) chan int {
    evenValues := make(chan int)
    for _, numbers := range inputs {
        go func(num int) {
            if num%2 == 0 {
                evenValues <- num
            }
        }(numbers)
    }
    return evenValues
}

func main() {
    inputs := []int{1, 17, 34, 56, 2, 8}
    evenCH := processEven(inputs)
    for range inputs {
        fmt.Print(<-evenCH)
    }
}

A: Close the channel when done sending values:
func processEven(inputs []int) chan int {
    evenValues := make(chan int)
    var wg sync.WaitGroup
    for _, num := range inputs {
        wg.Add(1)
        go func(num int) {
            defer wg.Done()
            if num%2 == 0 {
                evenValues <- num
            }
        }(num)
    }
    go func() {
        wg.Wait()
        close(evenValues)
    }()

    return evenValues
}

The code uses a WaitGroup to wait for the senders to complete.
Loop receiving values until the channel is closed:
func main() {
    inputs := []int{1, 17, 34, 56, 2, 8}
    evenCh := processEven(inputs)
    for num := range evenCh {
        fmt.Println(num)
    }
}

Range on a channel loops until the channel is closed.


text:
Q: PHP MySQL, data not returned, even though it is in database So the project I'm working on is built on the Cloud9 development platform, and I've hit a problem. This specific MySQL query is missing one of it's column data's, it just refuses to return it.
Part of my login code, with query;
http://i.stack.imgur.com/kmx9O.png
in code:
$sql_command = "SELECT Salt FROM User WHERE Name ='" . $username . "';";
    $result = $conn->query($sql_command);

    if($result->num_rows > 0)
    {
        //echo "
 username: ". $username . "
";
        //echo "
 password: ".$password . "
";

        $salt = $result->fetch_array()[0];

        //echo "
salt " . $salt . "
";
        $hashed_password =  hash("sha256", $salt . $password);

        $sql_command = "SELECT `ID`, `Status` FROM User WHERE Password ='" . $hashed_password .
                        "' AND Name = '" . $username . "';";
        $result = $conn->query($sql_command);

        //echo $hashed_password;
        if($result->num_rows > 0)
        {

            $user = $result->fetch_array()[0];
            $status = $result->fetch_array()[1];

            if($status != -1)
            {
                $_SESSION['login_user'] = $user;
                $_SESSION['login_status'] = $status;
                $_SESSION['login_user_name'] = $username;
            }

data in question, Status column;
http://puu.sh/ec3fP/de1e63b384.png
The only column, that doesn't return any data, is the Status column.
Every other query works fine.
The column status is a int type, with 11 length. No other special characteristics.

A: $result->fetch_array(), if run multiple times like you do it, will jump to the next row every time, hence it tries to fetch the status from the second row of your query result, which is nonexistent.
You could use e.g.
 $data = $result->fetch_array();
 $user = $data[0];
 $status = $data[1];

A: It's not refusing to fetch the array. It DID - you simply threw away the result:
This fetches a row:
  $user = $result->fetch_array()[0];

This fetches the NEXT row:
  $status = $result->fetch_array()[1];

Presumably your query will only ever return ONE row, so the second fetch will return a boolean false, signifying "no more data".
Your code should be:
$row = $result->fetch_array();
$user = $row[0];
$status = $row[1];


text:
Q: What is Fastest way to query a database android? I have a database that contains 35000 records, and can easily get up to about 60000 records,
What is the best way to query these data? Will ORMLite or GreenDAO be usefull? Or should i just stick with Cursor?

A: That depends on what you mean by "best".
Fastest, most flexible, best integration with Android library functions: Stick with Cursor. Since ORMs are just wrappers around the native Android cursors, they are unlikely to be faster than direct access. In many cases, the Android UI library classes are optimized for Cursors (e.g. SimpleCursorAdapter, which allows you to bind a cursor to a UI list).
Most readable, most maintainable: An ORM might help here, but that depends on a lot of factors, including your project complexity, your application architecture, etc.
See the following programmers.se question for more information:

*

*Does it make sense to use ORM in Android development?


text:
Q: How can I get the name of the team instead of its ID I have 2 tables
teams

*

*TeamID as PK, int

*TeamName

matches (bridge table)

*

*MatchID as PK, int

*TeamID_1 as PK, FK, int

*TeamID_2 as PK, FK, int

*MatchWinner

How could I manage to get TeamName instead of TeamID in the final table?
Already tried using, inner and outer joins etc.
Here is my query:
SELECT CONCAT(m.MatchID, m.TeamID_1, m.TeamID_2) AS MatchID, m.TeamID_1 AS 'Team 1', m.TeamID_2 AS 'Team 2', m.MatchWinner AS 'Winner'
    FROM teams t
    JOIN matches m
    ON t.TeamID IN (m.TeamID_1, m.TeamID_2)
    WHERE t.TeamName = 'Fnatic';

The final table should look like
MatchID - Team 1 - Team 2 - Winner
18582 - Fnatic - Astralis - Fnatic

A: You must join matches with 2 copies of teams:
select m.matchid, t1.teamname team1, t2.teamname team2, m.Winner
from matches m
inner join teams t1 on t1.teamid = m.teamid_1
inner join teams t2 on t2.teamid = m.teamid_2
where 'Fnatic' in (t1.teamname, t2.teamname)


text:
Q: Using Python to optimize a linear programming problem with a fraction as a constraint I am trying to solve the following linear programming problem with a constraint that requires at least 10% of each ingredient. The problem is asking that the solution consists of at least 10% seeds, 10% raisins, 10% flakes, 10% pecans, and 10% walnuts. At the moment I have the constraints set up under "#ingredients" but am not able to figure out how to make the value 10%. I am using the fraction method, but I continue to get the following error.

from fractions import Fraction as Fraction
# declare the model
model = ConcreteModel()

# declare decision variables
model.seeds = Var(domain=NonNegativeReals)
model.raisins = Var(domain=NonNegativeReals)
model.flakes = Var(domain=NonNegativeReals)
model.peacans = Var(domain=NonNegativeReals)
model.walnuts = Var(domain=NonNegativeReals)

# declare objective
model.cost = Objective(
                  expr = 4*model.seeds + 5*model.raisins + 3*model.flakes + 7*model.peacans + 6*model.walnuts,
                  sense = minimize)

# declare constraints
# Vitamin Content
model.Vitamins = Constraint(expr = 10*model.seeds + 20*model.raisins + 10*model.flakes + 30*model.peacans + 20*model.walnuts >= 20)
# Mineral Content
model.Minerals = Constraint(expr = 5*model.seeds + 7*model.raisins + 4*model.flakes + 9*model.peacans + 2*model.walnuts >= 10)
# Protein Content
model.Protein = Constraint(expr = 1*model.seeds + 4*model.raisins + 10*model.flakes + 2*model.peacans + 1*model.walnuts >= 15)
# Calorie Content
model.Calories = Constraint(expr = 500*model.seeds + 450*model.raisins + 160*model.flakes + 300*model.peacans + 500*model.walnuts >= 600)
#ingredients
# Seed Constraint
model.Seeds = Constraint(expr = model.seeds >= (Fraction(1, 10))
# Raisin Constraint
model.Raisin = Constraint(expr = model.raisins >= (Fraction(1,10))
#Flakes Constraint
model.Flakes = Constraint(expr = model.flakes >= (Fraction(1,10))
# Peacans Constraint
model.Peacans = Constraint(expr = model.peacans >= (Fraction(1,10))
# Walnuts Constraint
model.Walnuts = Constraint(expr = model.walnuts >= (Fraction(1,10))

# show the model you've created
model.pprint()

A: You're missing a right parenthesis on the previous line.
model.Seeds = Constraint(expr = model.seeds >= (Fraction(1, 10))
Count 'em: you've got 3 lefts and two rights. Same for the Raisins line and the following lines.
When you get syntax errors, that's always a likely culprit.


text:
Q: AAR: Android Application record dispatch system In the Android API, we are told the following:

If a tag contains an AAR, the tag dispatch system dispatches in the
  following manner:

*

*Try to start an Activity using an intent filter as normal. If the
  Activity that matches the intent also matches the AAR, start the
  Activity.

*If the Activity that filters for the intent does not match
  the AAR, if multiple Activities can handle the intent, or if no
  Activity handles the intent, start the application specified by the
  AAR.

*If no application can start with the AAR, go to Google Play to
  download the application based on the AAR.

Part 2 of this is a little bit confusing. If the intent matches more than one Activity then we launch the application. So if my activity that filters for the NFC intent is not my default application launch activity, I will not be starting it in the case where multiple activities filter for the intent?
Put another way, if my application has a default Activity 'A' and another activity 'B' that filters for an NFC intent, then without any other activities filtering for that intent, an AAR intent will launch B. But if others DO filter for the intent, I will get a different behaviour and activity A will be started.
Does this mean I may as well make the intent filter always sit on Activity A (the default launch activity) as there is always a chance the intent will be delivered to it?
Hope this was clear,
Sam

A: So if multiple Activity filters match, Android defaults to the main application Activity.
Seems better than selecting one (which?) of the matching Activities. If you write 'competing' filters, this is what you get, but no one is forcing you ;-)


text:
Q: Combine png-images to video with alpha channel in python My Intention was:
- Extract all frames from video
- Apply background removal to each frame
- Merge all frames together as a video with transparency
Problem:
- The resulting video doesn't have the desired transparency where the background used to be
My code for the Merging-Part
import cv2
import os

image_folder = r"C:\Users\youre\Documents\machine_learning\bg-rm\output"
video_name = r'C:\Users\youre\Documents\machine_learning\bg-rm\test.avi'
images =  # list of all frames
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*"MJPG"), 30, (width, height))
for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()

My question:
- What do I have to do in order to have my transparency over the background in the resulting video, because my code just gives me a black background. More specific: How do I merge the png-frames together with an alpha channel?

A: MJPG video format does not support alpha channel.
This is just a sequence of JPEG image and JPEG format does not support transparency.
You should choose a codec that support it. But I'm not sure one is available through OpenCV and this depends on your platform.
Instead you can save each image as PNG (with alpha channel) and merge them with a third party tool like FFMPEG.
HAP is the only free and open source video format that I know that support alpha channel but I don't know them all.


text:
Q: point of having an instance variable as final? what is the point of having an instance variable as final?
isn´t it better to have that variable set as a static final variable then?
cause if it can't be changed by any of the objects, then it's the same as a class (static) variable, right?

A: Two reasons:
1) From the class design view, it allows a programmer to rely on the fact that the field will not change since instantiation - so called "immutable object" (where applied to class members, not the object's reference). Java tutorial says:

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

Immutable objects are a cornerstone of various programming styles, e.g. pure functional programming.
2) The second reasons is JVM optimizations. If all fields are final, then JVM knows the object's state can't be changed, and thus it can make many optimizations, e.g. ommiting thread safety checks etc.

A: I guess you are thinking about simple case such as:
 private final int num = 3;

That can be better written as:
 private static final int NUM = 3;

However, often you will have references to objects that are mutable, and therefore cannot be shared between classes:
 private final List<Node> children = new ArrayList<Children>();

Or perhaps, a value passed into or derived in the constructors:
 public final class MyThing {
      private final String name;
      public MyThing(String name) {
          this.name = name;
      }
      [...]
 }

Note: final fields can be assigned in constructors (or instance initialiser), not just as part of the declaration.

A: Nope.  static means it's the same across all instances of the class.  final means it's not assignable after its initial assignment.  So two instances could have different values for a non-static final variable.
There are many reasons you might want to make a variable final; one of the best is clarity.  If I read a method and notice that the foo is final, I don't have to worry about where it's changing down below - because it isn't; it can't.  I can make more changes to code with final variables with less concern ("did I change the value of foo before or after bar, and does it matter?") because I know that some variables aren't subject to change.  It also focuses my attention on the variables that are subject to change - and they're the ones that deserve more attention.

A: You can assign it a value that is specific to the object instance, which you can't do with a static class variable.

A: It prevents other programmers from doing stupid things that they shouldn't try doing anyway...

A: class A{
    public final int x;

    A(int arg){
        x = arg;  // This is legal  !!!
    }
}

public class HelloWorld{

     public static void main(String []args){
         A  a = new A(1);
         A  b = new A(2);
         System.out.printf("a.x = %d, b.x = %d", a.x, b.x);
     }
}


text:
Q: Best practice discussion: When to favor a webview over a native UI in titanium? I'm currently working on a cross-platform mobile app and have gone through the process of creating the UI of my application using the given Titanium api.
Compared to when you are building a mobile web application this is a time consuming task, because you don't have the possibility to work on the rendered UI like you can on a rendered webpage using firebug.
Especially form creation is bothersome, so I decided to build my forms using html and render them in a Webview, which worked out pretty sweet for several reasons:

*

*WebViews are automatically scrollable, so the soft keyboard won't cover the input fields in your HTML form

*You can control which keyboard type is displayed with a WebView form by setting attributes on the <input> tag.

*You can use JavaScript libraries to add form validation, field highlighting, and so forth to an HTML form.
Although this works like a charm and the titanium documentation encourages you to use webviews for building forms, I have mixed feelings about having mixed native UIs with webviews.
My questions to you:

*

*What do you think of mixing native UIs with Webviews?

*Do you have other use cases that favor a Webview?

*What could be general criteria for using one or the other?
Thank you in advance :)

A: What do you think of mixing native UIs with Webviews?
The real question would be : Do you care about the user experience ? If yes, then go exclusively Titanium/Native. Sometimes, you need to use the Webviews to get around some problems (I had one year ago) : I remember I couldn't open online PDF files with Titanium : As Android platforms didn't open the PDF "natively" (Now you can), you had to pass the pdf's path to a Webview. That was the only time I was forced to pop up a WebView.
Do you have other use cases that favor a Webview?
If you are you talking about frameworks that base the rendering on Webviews then :
If you have a client who owns a full static website and tell you to turn it into a mobile application It could be useful. Or, If you aim many platforms (more than Titanium does), you can use frameworks such as PhoneGap that will allow you creating WP7/iPhone/Android/BlackBerry apps.
What could be general criteria for using one or the other?
Which platform are you aiming ? As I said, Titanium won't allow you exporting your app for the WP7 platform.
Then, if you need better performances, then go for Titanium/Native apps.
On the other hand, if you want to reuse your code, think PhoneGap.


text:
Q: Given a parametric solution $\vec{x}(t)$ to $Ax = b$, how can I choose the parameter $t$ so that all entries in $\vec{x}(t)$ is between 0 and 1? Given a solution to the matrix equation $A\vec{x} = \vec{b}$ on the form $\vec{x}(t)$, how can I choose the parameter t such that all entries in $\vec{x}$ are squeezed between 0 and 1? That is, for any entry $x_n$:
$0\leq x_n \leq 1$.
I intend to implement this restriction in an algorithm, and I want to avoid having to iterate through values of the parameter $t$. Additionally, how would I check if such there really is a value $t$ where all entries in $\vec{x}(t)$ is squeezed between 0 and 1?

A: In general it is very difficult to just "inspect" your equation $Ax = b$ by hand and tell if there is a solution that will have all entries in $x$ that satisfy certain inequalities. What you CAN do, in this case, is formulate a linear programming feasibility problem:
$$Ax = b, \,\,\,\,\, 0 \leq x_i \leq 1, \,\,\,\, \forall i$$.
And this is possible because all the inequalities on the $x_i$ are linear combinations of the $x_i$ set to be less than or equal or greater than or equal to (or strictly equal to) some constant. There is a lot of free software available online to find a feasible solution to a linear programming problem, and you can even find an "optimal" feasible solution that maximizes $c \cdot x$ for any vector $c$ that you want.
If your vector $x$ is parametrized by an argument $t$ that defines a curve, then the problem is basically impossible to decide without explicitly knowing and being able to work with the form of $x(t)$ as a function of $t$. Just imagine the feasibility region: You can define infinitely many curves $x(t)$ that pass through the feasibility region and infinitely many curves that don't. And they can basically look like anything. How are you going to decide whether an arbitrary given curve $x(t)$ intersects the feasibility region?


text:
Q: Sincronizar librerías necesarias de un proyecto (jar) y trabajar con GitHub Estoy empezando a trabajar con GitHub y acabo de subir mi primer repositorio pero me surge esta duda. Tengo algunas librerías en archivos .jar. Cuando trabajo en netbeans al compilar estas se agregan automáticamente pero ¿Como se trabaja en github? De manera que pueda seguir utilizando las librerías y a la vez clonar el repositorio sin problemas.

A: Github (o cualquier otro sistema de control de versiones) NO es la herramienta para tratar con dependencias. De hecho no se debería incluir allí nada que sea "generado" (.class, .jar, .war), etc1.
Para desarrollos internos, en ocasiones la opción era hacer que todos los desarrolladores pusieran las librerías en la misma ubicación de su máquina. Obviamente no era muy cómodo, y resultaría inmanejable para una desarrollo opensource o incluso un departamento de desarrollo grande.
La mejor solución es usar una herramienta de gestión de dependencias, como puedan ser Maven (que parece lo más utilizado), Graddle o Ivy (esta última integrada con Ant). Tú indicas en tu fichero que tu proyecto depende de tal y tal librería, con las versiones indicadas, y el gestor de dependencias te las descarga, incluye en el empaquetado, etc.
Los inconvenientes son dos:

*

*Obviamente, tienes que aprender a usar la herramienta. Maven es más que un gestor de dependencias y se encarga de todo el build, pero puede ser complicado adaptar problemas que no sigan su filosofía. Ant + Ivy es más flexible, pero tienes que "programar en XML" todo lo que quieres que se haga durante el build.

*Si quieres gestionar las librerías propias (que tú o tu equipo producís), deberías montarte un repositorio para ellas, lo cual es una complicación adicional.

1 Como cada vez que hagas un build volverás a crear todos esos archivos, subirlos implicaría a) una cantidad de cambios enormes y b) una "fiesta" continúa de conflictos con los commits de otros desarrolladores.

A: Dale, yo no domino el tema, pero se algo. En mi caso uso 2 formas, trabajando con IntellIJ como IDE, es muy sencillo de configurar, con ello haces los commits y push directamente al repositorio y tienes consigo el CSV (control de versiones). Y la segunda es usando el desktop de GitHub, clonas el repositorio en tu máquina y luego abres el proyecto directamente desde ahí, es sencillo pero pierde su gracia ya que tendrías que el control de versión radica en el, y no el IDE (cosa novedosa). Ahora dime cual usarás y puedo ayudarte.


text:
Q: The best solution to build a website mobile appliction use phonegap I'm building an forum like website and also provide a mobile version, which will detect user agent and return page built on jQuery mobile. However, it will be great to have its mobile application for iphone, android and other platform so user can use their camera and gps from mobile to upload picture and determine their location.Therefore, I turned into phonegap.
I'm new to phonegap and what I'm trying to do is:

*

*for reading my forum content, how can I reuse my mobile version

Due to the cross domain communication, I'm thinking JSONP. But it's kind of waste to re-produce the page. (I need to parse JSON, and dynamically create DOM element) Since my mobile version's page has all page elements, can I simply load the page?
or ChildBrowser? to load my mobile version website? Just heard Childbrowser today, can any one share experience?
2 . develop a post form page.
I'm going to use phonegap's camera api. is it possible for this form page also load remotely?

A: My first suggestion is to look at the documentation provided
 http://docs.phonegap.com/
The google group for phoneGap is great, and very active
http://groups.google.com/group/phonegap
You should be able to read your forum content is you create an API that will allow for AJAX calls from the phoneGap Application
I do not believe you are going to have a cross-domain issue from inside the phoneGap Application
Pretty thorough Camera Demo Here
And I have posted some PhoneGap related stuff on my blog


text:
Q: Implicit Resolution with Contravariance Given classes Parent and Child.
scala> class Parent
defined class Parent

scala> class Child extends Parent
defined class Child

Define implicits for Parent and Child
scala> implicit val a = new Parent
a: Parent = Parent@5902f207

scala> implicit val b = new Child
b: Child = Child@3f7d8bac

Use implicitly to find out which implicit gets resolved.
scala> implicitly[Child]
res1: Child = Child@3f7d8bac

illustration of my understanding:
         Parent
           |
         Child -- implicit resolution gets the most specific, lowest sub-type

Now, let's use a contravariant type.
scala> trait A[-T]
defined trait A

scala> case class Concrete[T]() extends A[T]
defined class Concrete

Then define a Parent and Child class.
scala> class Parent
defined class Parent

scala> class Kid extends Parent
defined class Kid

Create implicits for them too.
scala> implicit val x = Concrete[Parent]
x: Concrete[Parent] = Concrete()

scala> implicit val y = Concrete[Kid]
y: Concrete[Kid] = Concrete()

scala> implicitly[A[Parent]]
res1: A[Parent] = Concrete()

scala> implicitly[A[Kid]]
    <console>:21: error: ambiguous implicit values:
     both value x of type => Concrete[Parent]
     and value y of type => Concrete[Kid]
     match expected type A[Kid]
                  implicitly[A[Kid]]
                        ^

In the first example (without contravariance), Scala was able to resolve the implicit Child for implicitly[Parent]. It seems to me that it's picking the lowest sub-type.
However, when using contravariance, the behavior changes. Why?

A: Your implicits are typed Concrete and that is invariant here.
Try either
case class Concrete[-T]() extends A[T]

or
implicit val x: A[Parent] = Concrete[Parent]

More words:
Implicits (values or views) should have an explicit type so you're never surprised by the inferred type. Picking the implicit is all about the type.
It picks one of your implicits using the same rules as the overloading resolution conversion that is used to pick alternatives of an overloaded symbol.
For simple values (not function calls), that comes down to conformance or subtyping.
There is also the rule that a definition in a "derived type" (usually a subclass) is preferred.
Here is a test you can do using only commonly available household materials:
scala> :power
** Power User mode enabled - BEEP WHIR GYVE **
** :phase has been set to 'typer'.          **
** scala.tools.nsc._ has been imported      **
** global._, definitions._ also imported    **
** Try  :help, :vals, power.<tab>           **

scala> trait A[-T]
defined trait A

scala> case class Concrete[T](i: Int) extends A[T]
defined class Concrete

scala> class Parent ; class Kid extends Parent
defined class Parent
defined class Kid

// it will pick X if X isAsSpecific as Y but not conversely
scala> typer.infer.isAsSpecific(typeOf[Concrete[Kid]],typeOf[Concrete[Parent]])
res0: Boolean = false

scala> typer.infer.isAsSpecific(typeOf[Concrete[Parent]],typeOf[Concrete[Kid]])
res1: Boolean = false

scala> case class Concrete[-T](i: Int) extends A[T]
defined class Concrete

scala> typer.infer.isAsSpecific(typeOf[Concrete[Kid]],typeOf[Concrete[Parent]])
res2: Boolean = false

scala> typer.infer.isAsSpecific(typeOf[Concrete[Parent]],typeOf[Concrete[Kid]])
res3: Boolean = true

Edit:
Another view of why it matters what type you're testing:
scala> trait A[-T]
defined trait A

scala> case class Concrete[T](i: Int) extends A[T]  // invariant
defined class Concrete

scala> class Parent ; class Kid extends Parent
defined class Parent
defined class Kid

scala> implicitly[Concrete[Parent] <:< Concrete[Kid]]
<console>:13: error: Cannot prove that Concrete[Parent] <:< Concrete[Kid].
              implicitly[Concrete[Parent] <:< Concrete[Kid]]
                        ^

scala> implicit val x: Concrete[Parent] = Concrete[Parent](3)  // the inferred type
x: Concrete[Parent] = Concrete(3)

scala> implicit val y  = Concrete[Kid](4)
y: Concrete[Kid] = Concrete(4)

// both values conform to A[Kid] (because A is contravariant)
// but when it puts x and y side-by-side to see which is more specific,
// it no longer cares that you were looking for an A.  All it knows is
// that the values are Concrete.  The same thing happens when you overload
// a method; if there are two candidates, it doesn't care what the expected
// type is at the call site or how many args you passed.

scala> implicitly[A[Kid]]
<console>:15: error: ambiguous implicit values:
 both value x of type => Concrete[Parent]
 and value y of type => Concrete[Kid]
 match expected type A[Kid]
              implicitly[A[Kid]]
                        ^

Give them explicit types and the variance of Concrete won't matter.  You always supply explicit types for your implicits, right?  Just like retronym tells us to?
scala> implicit val x: A[Parent] = Concrete[Parent](3)
x: A[Parent] = Concrete(3)

scala> implicit val y: A[Kid] = Concrete[Kid](4)
y: A[Kid] = Concrete(4)

scala> implicitly[A[Kid]]
res2: A[Kid] = Concrete(3)


text:
Q: using mysql queues to list the number of students I'm learning mySQL and I'm a little confused how I can use mySQL queries to say...list the total number of Employees in a Department.
Emp(eid: integer, ename: string, age: integer, salary: real)
Works(eid: integer, did: integer, pct_time: integer)
Dept(did: integer, budget: real, managerid: integer)
*this is the example my book is working with but I guess I'm just asking can someone help me walk through an example using the sum aggregate function? Or would I be totally off in using this to say...list the total number of employees?

A: You need to join the table Dept with Works first using LEFT JOIN in order for all records (all department) to be shown on the final result, those departments that have no employee will be on the list but with value of 0.
SELECT  a.Did, COUNT(b.DId) TotalEmployee
FROM    Dept a
        LEFT JOIN Works b
            ON a.Did = b.DId
GROUP   BY a.Did

To further gain more knowledge about joins, kindly visit the link below:

*

*Visual Representation of SQL Joins

A: You're going to want to use SUM, like you said. So, you would first need to Join the tables, and then take a SUM of the employee_id row.
Select Emp.eid, SUM(Emp.eid) as employee_sum From, Dept.did
Emp
LEFT JOIN Works On
Emp.eid = Works.eid
INNER JOIN Dept ON
Works.did = Dept.did
Group By Emp.eid, Dept.did

A: The simplest way to do it is to simply using joins:
Select count(E.eid)
from Emp E,Works W,Dept D
where (E.eid = W.eid AND D.did = W.did);
Works table would be linking the two tables together ie Emp and Dept.
So this query will return you only the no of Employees in a department.


text:
Q: RegEx for extracting number from a string I have a bunch of files in a directory, mostly labled something like...
PO1000000100.doc or .pdf or .txt
Some of them are PurchaseOrderPO1000000109.pdf
What i need to do is extract the PO1000000109 part of it. So basically PO with 10 numbers after it...
How can I do this with a regex?
(What i'll do is a foreach loop on the files in the directory, get the filename, and run it through the regex to get the PO number...)
I'm using C# - not sure if this is relevant.

A: Try this
String data =
  Regex.Match(@"PO\d{10}", "PurchaseOrderPO1000000109.pdf",
    RegexOptions.IgnoreCase).Value;

Could add a Regex.IsMatch with same vars above ofc :)

A: If the PO part is always the same, you can just get the number without needing to use a regex:
new string(theString.Where(c => char.IsDigit(c)).ToArray());

Later you can prepend the PO part manually.
NOTE: I'm assuming that you have only one single run of numbers in your strings. If you have for example "abc12345def678" you will get "12345678", which may not be what you want.

A:
Regex.Replace(fileName, @"^.?PO(\d{10}).$", "$1");

Put stars after dots.

A: string data="PurchaseOrderPO1000000109.pdf\nPO1000000100.doc";
MatchCollection matches = Regex.Matches(data, @"PO[0-9]{10}");
foreach(Match m in matches){
    print(m.Value);
}

Results
PO1000000109
PO1000000100

A: This RegEx will pick up all numbers from a string \d*.
As described here.

A: A possible regexp could be:
^.*(\d{10})\.\D{3}$

A: var re = new System.Text.RegularExpressions.Regex("(?<=^PurchaseOrder)PO\\d{10}(?=\\.pdf$)");
Assert.IsTrue(re.IsMatch("PurchaseOrderPO1234567890.pdf"));
Assert.IsFalse(re.IsMatch("some PurchaseOrderPO1234567890.pdf"));
Assert.IsFalse(re.IsMatch("OrderPO1234567890.pdf"));
Assert.IsFalse(re.IsMatch("PurchaseOrderPO1234567890.pdf2"));


text:
Q: What user profile info is available on the Facebook Messenger Platform? The messenger platform docs shows an example of how to get the user profile info via their API (see this).
I could quite understand if the example shown actually contains all the info possible to retrieve (meaning: first_name, last_name, profile_pic, locale, timezone, gender) or it is just an example and I could find more user data via the API (again, referring to doing this just via the messenger platform, aka via bots).
Thanks !

A: This is the only user information available at the moment via chat bot API and you cannot use any other API to query user information because the User Id (Sender Id) we get on our webhook is just for the scope of the App-Page and is completely different than the actual Facebook UserId and currently there's no way to link these two Ids.
You can ask a user to login using FB Login API and link the two Ids at your end but that won't be the ideal way to do it.
Edit: 2016-07-26
Facebook has introduced a new feature for the messenger platform called Account Linking. This can be used to identify a user who has created an account on your website via Facebook Login. Facebook login has its own set of permissions which can be used to get a lot more information via Facebook graph API. You can find the complete list here.

A: You can retrieve - first_name, last_name, profile_pic, locale, timezone, gender
This information can be retrieved with a quick call to the FB graph:
https://graph.facebook.com/v2.6/<USER_ID>?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=<PAGE_ACCESS_TOKEN>

see Complete Guide - Messenger Platform

A: Facebook recently added "is payment enabled" field https://developers.facebook.com/docs/messenger-platform/user-profile to the user profile API. This tells you if the user can pay using Facebook Payments.


text:
Q: Format date in SELECT * query Is it possible to format a date field in a SELECT * query? I want to get all of the columns from my table but need a different format from the date.
Something like:
SELECT *, FORMATDATE(date,'%m-%d-%y') AS date FROM my_table;

or do I have to process it in php after the query?

A: Use DATE_FORMAT:
SELECT *, DATE_FORMAT(date, "%m-%d-%y") AS date FROM my_table;

A: select DATE_FORMAT(your_date_field_name,'%m-%d-%y') AS whatever FROM your_table_name_here;

the result is something like this
09-22-11
as opposed to this
2011-02-02 15:42:51

A: I don't know what FORMATDATE is, but you can use DATE-FORMAT
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

A: If you are writing application containing different timezones and formats better practice will be using UNIX timestamp stored in int(8) field, otherwise you can format date fields in queries.

A: you can put name of column in back of date_format. like this :
$rs = mysql_query("select  blablabla,DATE_FORMAT(name_column, '%d-%b-%y | %H:%i')name_column,DATE_FORMAT(name_column2, '%d-%b-%y | %H:%i')as name_column2 from db ORDER BY id DESC limit $offset,$rows");

or you can put "as"
yes, you must select one by one. its work !!!!

A: in the above solutions the select first extract all columns, then the date column with a requested format, this means that the date columns is returned twice, once in default format and once in requested format. Actually if you want to change the format of 1, 2 ou 3 date columns from you table and you also want to avoid duplicate data returned, you shall remove "*" from the request and name each and every column instead, correct?
is there a way to ask mysql to change the format of all the datetime columns and ignore the rest with a single command?


text:
Q: Generating SQL query to get related results I have a theme gallery system. I need to implement a 'related themes' item inside the theme preview page.
Each theme has colors and tags, so between 5 tables i have:

*

*theme

*

*id_theme

*title

*color

*

*id_color

*title (red)

*tag

*

*id_tag

*title (planets)

*theme_color

*

*id_theme

*id_color

*theme_tag

*

*id_theme

*id_tag

The catch, is that I only have to receive 5 results, and they must show the ones that have more matches between colors and tags. With that requirement, I have no idea on where to start. Any ideas?

A: If you want the five themes that have the most items in common with a given theme, you might try something like:
DECLARE @target_id_theme INT;
SET @target_id_theme = 1; -- this is the id_theme you want to find similar themes for

SELECT t.id_theme, COUNT(*) as matching_things
FROM theme AS t
LEFT OUTER JOIN theme_color AS tc ON tc.id_theme = t.id_theme
LEFT OUTER JOIN theme_tag AS tt ON tt.id_theme = t.id_theme
WHERE tc.id_color IN (SELECT id_color FROM theme_color WHERE id_theme = @target_id_theme)
OR tt.id_tag IN (SELECT id_tag FROM theme_tag WHERE id_theme = @target_id_theme)
GROUP BY t.id_theme
ORDER BY COUNT(*) DESC
LIMIT 5

Not tested, buyer beware, but I hope you get the idea. This creates a row for every color or tag that matches a color or tag assigned to the @target_id_theme, orders them by count descending, and gives you the top 5.

A: Try this:
SELECT * FROM theme t
   FULL OUTER JOIN theme_color tc ON tc.id_theme = t.id_theme
   INNER JOIN color c ON c.id_color = tc.id_color
   FULL OUTER JOIN theme_tag tt ON tt.id_theme = t.id_theme
   INNER JOIN tag ta ON ta.id_tag = tt.id_tag
WHERE tag LIKE '%' + @KEYWORD + '%' OR color LIKE '%' + @KEYWORD + '%' OR title LIKE '%' + @KEYWORD + '%'


text:
Q: Radius of convergence of $\displaystyle{\sum_{n=0}^{\infty}} {(n!)^3 \over (3n)!}z^{3n} $.
Find the radius of convergence of $\displaystyle{\sum_{n=0}^{\infty}} {(n!)^3 \over (3n)!}z^{3n} \ ?$

I applied Cauchy-Hadamard test and the result is coming $0$ (radius of convergence). To obtain the limit I also used Cauchy's first limit theorem. For a lot of messy calculation I didn't provide my work.
Please someone check whether I'm right or wrong.
Thank you..

A: By the ratio test the sum converges if $\lim \limits_{n \to \infty} \frac{a_{n+1}}{a_n}  = r$ and $|r| <1$ , special cases are when $|r|=1$ and have to be checked separately.
$a_n = \frac{(n !)^3}{(3n)!} z^{3n}$ so $\lim \limits_{n \to \infty} \frac{a_{n+1}}{a_n} =\frac{((n+1)!)^3 z^{3 n+3}}{\frac{(3 (n+1))! \left((n!)^3 z^{3 n}\right)}{(3
   n)!}} = \frac{z^3 (3 n)! ((1+n)!)^3}{(n!)^3 (3 (1+n))!} = \frac{(1+n)^2 z^3}{3 (2+9 n (1+n))}=|z^3| \lim \limits_{n \to \infty}{\frac{(1+n)^2}{3(2+9n(1+n))}} = |z^3| \frac{1}{27} $
So for $|\frac{z^3}{27}| <1 $ its obvious that $-3 < z < 3$ (if you are looking for the domain of convergence for complex $z$, from here you have to continue dealing with $z$ as complex number, the methods above works for real and complex).
So when $|\frac{z^3}{27}|=1$ we get that $z=-3,3$, we need to check them.
Just substitute instead of $z$ the numbers $-3$ and then $3$ in the sum, in both cases the sum diverges using other tests than the ratio test because its inconclusive when the ratio is exactly one.

A: Hint:
First find the radius of convergence of the series $\;\displaystyle\sum_{n=0}^{\infty} {(n!)^3 \over (3n)!}z^{n}$.
For this apply Cauchy-Hadamard's formula, combined with Stirling's formula:
\begin{align}
\biggl(\frac{(n!)^3}{(3n)!}\biggr)^{\!\tfrac1n}\sim_\infty&\frac{\Bigl(\sqrt{(2\pi n)^{3\mathstrut}}\Bigr)^{\!\tfrac1n}\Bigl(\dfrac n{\mathrm e}\Bigr)^{\!3}}{\Bigl(\sqrt{6\pi n\mathstrut}\Bigr)^{\!\tfrac1n}\Bigl(\dfrac{3n}{\mathrm e}\Bigr)^{\!3}}=\frac{1}{27}\sqrt{\Bigl(\frac 43\pi^2n^2\Bigr)^{_\tfrac1n}},
\end{align}
and we obtain a radius of convergence equal to $27$ for the auxiliary series.

A: If we represent the factorials everywhere as gamma-functions and Pochhammer symbols, this is actually a generalized hypergeometric function 4F3(...;;;z/3). According to wikipedia the radius of convergence is where the argument becomes 1, which means in our case, |z|=3.


text:
Q: Crear JsonResponse UTF-8 en Django ¿Hay alguna forma simple de anular DjangoJSONEncoder.ensure_ascii y ponerlo en False o imprimir texto diferente de ascii en django.http.JsonResponse de cualquier otra forma?

A: Si Ud tiende a usar el formato utf-8, en vez del JsonResponse() de Django use esta forma:
return HttpResponse(json.dumps(response_data, ensure_ascii=False),
content_type="application/json")

o esta forma:
return JsonResponse(json.dumps(response_data, ensure_ascii=False),
safe=False)

Más acerca del safe=False   ver AQUÍ


text:
Q: How to override footer template in a custom theme I'm trying to override the footer template from a custom theme:
vendor/magento/module-theme/view/frontend/templates/html/footer.phtml

Copying the file in my theme folder:
app/design/frontend/<Vendor>/<ThemeName>/Magento_Theme/templates/html/footer.phtml

Then I removed all the content leaving only this:
<div class="footer-container">
</div>

But still I see the whole footer from the Magento's module.
Where am I wrong?

A: I found out what was my problem.
Firstly I enabled the template path hints mode as described here:
http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/themes/debug-theme.html
Thanks to path hints, I understood that the theme was not using the footer.phtml file, but was using bugreport.phtml and copyright.phtml both from the magento-theme module.
So I created these two templates:
app/design/frontend/<Vendor>/<ThemeName>/Magento_Theme/templates/html/bugreport.phtml
app/design/frontend/<Vendor>/<ThemeName>/Magento_Theme/templates/html/copyright.phtml

And now I'm able to override them from my custom theme.

A: The configuration of the footer can be seen in this file:  vendor/magento/module-theme/view/frontend/layout/default.xml
I was able to modify the footer declaration by creating my own default.xml file at app/design/frontend/<Vendor>/<ThemeName>/Magento_Theme/layout/default.xml with this content:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="footer-container">
            <block class="Magento\Theme\Block\Html\Footer" name="footer" template="html/footer.phtml"/>
        </referenceContainer>
    </body>
</page>

Now my custom footer.phtml file is called instead of the containers/blocks defined in the original default.xml.


text:
Q: How to Serialize C# Class with class name as root element I have the following C# class
[XmlRoot("Customer")]
public class MyClass
{
    [XmlElement("CustId")]
    public int Id {get;set;}

    [XmlElement("CustName")]
    public string Name {get;set;}
}

I then use the following function serialise the class object to Xml
 public static XmlDocument SerializeObjectToXML(object obj, string sElementName)
 {
    XmlSerializer serializer =
          new XmlSerializer(obj.GetType(), new XmlRootAttribute("Response"));

    using (MemoryStream ms = new MemoryStream())
    {
       XmlDocument xmlDoc = new XmlDocument();
       serializer.Serialize(ms, obj);
       ms.Position = 0;
       xmlDoc.Load(ms);
    }
}

My current output to XML is like;
<Response>
  <CustId></CustId>
  <CustName></CustName>
</Response>

But how can I get the response to look like;
<Response>
  <Customer>
     <CustId></CustId>
     <CustName></CustName>
  </Customer>
</Response>

A: You can create a response object containing your customer, because that is what your desired xml shows as well.
[XmlRoot("Response")]
public class ResponseClass
{
  [XmlElement("Customer")]
  public Myclass Customer {get;set;}
}

A: You could define them like this:
public class MyClass
{
    [XmlElement("Customer")]
    public Customer cust { get; set; }

}
public class Customer
{
    [XmlElement("CustId")]
    public int Id { get; set; }

    [XmlElement("CustName")]
    public string Name { get; set; }
}

By the way, the [XmlElement("Customer")] is not valid on your example...

A: Change the XmlElementAttribute on MyClass (it's not actually valid there according to http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute(v=vs.110).aspx) to an XmlTypeAttribute:
    [XmlType("Customer")]
    public class MyClass
    {
        [XmlElement("CustId")]
        public int Id { get; set; }

        [XmlElement("CustName")]
        public string Name { get; set; }
    }

The serialization method can now be (identical to that in the question but without the second parameter in the constructor of XmlSerializer):
    public static XmlDocument SerializeObjectToXML(object obj, string sElementName)
    {
        XmlSerializer serializer = new XmlSerializer(obj.GetType());
        XmlDocument xmlDoc = new XmlDocument();
        using (MemoryStream ms = new MemoryStream())
        {

            serializer.Serialize(ms, obj);
            ms.Position = 0;
            xmlDoc.Load(ms);
        }

        return xmlDoc;
    }


text:
Q: How to access a shared/network folder using JavaScript? I have a requirement to develop a tool to backup certain folders and files present in a shared drive (Windows 7) using Client-Side technologies (HTML5, CSS3 and JavaScript) only. Below is the JavaScript function to copy the file.
function copyFile() {
    var myObject, f;
    myObject = new ActiveXObject("Scripting.FileSystemObject");
    f = myObject.GetFile("@\\Network_Name\Home$\User_Folder\Downloads\Folder_Name\Test.pdf");
    if(!f)
    {
        return alert("File Not Found");
    }
    f.copy("@\\Network_Name\Home$\User_Folder\Downloads\Backup_Folder");
}

Since I'm using ActiveXObject, the above code will work only in IE. But I'm getting the below error in the line @\\Network_Name\Home$\User_Folder\Downloads\Folder_Name\Test.pdf. Please help me to properly access the network folder using JavaScript.

A: The verbatim identifier (@) is for C# not JavaScript, you need to escape your slashes:
.GetFile("\\\\Network_Name\\Home$\\User_Folder\\Downloads\\Folder_Name\\Test.pdf");

A: Try to use Ajax request method type "GET" for this purpose.


text:
Q: opening the same dialog from a list in android I have a listActivity with many items.
For each item, I want to open the same popup while sending an item id\position\other
info object unique to that item.
But basically all the time I open the exact same popup.
Its buttons will send the extra unique data to the server.
I have read few tutorials, and saw a dialog is usually opened like this:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");

// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);

Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        dialog.dismiss();
    }
});

dialog.show();
}

I think it's more readable to create a different file to the dialog.
like this:
public class SocialActionsDialog extends Dialog {

public SocialActionsDialog(Context context) {
    super(context);
    mContext = context;
}

Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.social_actions);
    setTitle("Title...");
}

but then I get a syntax error on the OnCreate.
Is it common and good practice to create new file? and if so- how to do it properly?
is it more efficient somehow - just showing the same dialog instead of initializing a new one each time? or is both ways the same?

A: For the syntax error, make sure you are importing the R class from your app and not the Android SDK class R resources.
For an experienced programmer your instinct is to move the dialog to a separate file, especially if it contains a lot of code. And that can be the right decision at times.
However, it is often convenient to have the dialog as an embedded class or to just create it inline (as in your example) because then it is within the scope of your activity and can access your state variables and protected methods on the Activity itself.
So you end up passing all this information to the dialog if you have it in a separate file, and at some point it just isn't worth it because the code becomes more complex and less maintainable.


text:
Q: Could not find generator user I am using ruby version 2.0.0 and rails version 4.0.0
whenever i do
rails g model user email:string password_hash:string password_salt:string

I get error i;e
Could not find generator user.

A: make sure your model should be singular or first alphabet capitaql

A: You need to add a capital to the first letter of your model like:

rails g model User email:string password_hash:string password_salt:string


text:
Q: Separar contenido con String.Split() usando múltiples delimitadores en VB.Net Estoy evaluando el contenido que obtengo de un TextBox. Lo que deseo hacer es usar la función .Split (o alguna otra función de no poder ser) para separar dicho contenido y almacenar cada parte en un vector.
Dim vectoraux() As String
vectoraux= TextBox1.Text.Split("<")

Es sencillo cuando es un solo carácter, incluso si quiero puedo evaluar varios al mismo tipo.
 Dim vectoraux() As String
 vectoraux= TextBox1.Text.Split("<>+-/*")

El problema viene cuando quiero evaluar una cadena, digamos que quisiera hacer esto.
 Dim vectoraux() As String
 vectoraux= TextBox1.Text.Split("<=,>=,>,<,+,-,/,*")

Sé que el codigo esta mal escrito, pero es simplemente para que entiendan lo que quiero hacer, la coma seria el separador de cada valor que deseo evaluar.
Creo que con el .Split() no se puede hacer esto, pero no estoy del todo seguro.
Me gustaría que me dijesen si hay alguna otra función similar que pueda utilizar, o alguna recomendación que se les ocurra. Esta es una pregunta para VB.NET 2010.

A: 1. Con un array de elementos
La función String.Split(delimitadores(), opciones) acepta un array de delimitadores.

*

*En este caso es importante que <= y >= estén en el array de delimitadores antes que > y <, para que se separe correctamente.

Código:
Dim texto As String = "prueba+a-b<=c"

'Split con array de delimitadores
Dim delimitadores() As String = {"<=",">=",">","<","+","-","/","*"}
Dim vectoraux() As String
vectoraux = texto.Split(delimitadores,StringSplitOptions.None)

'mostrar resultado
For Each item As String In vectoraux
    Console.WriteLine("'{0}'", item)
Next

Resultado:
'prueba'
'a'
'b'
'c'

Demo:
http://rextester.com/IJBC7167

2. Con regex
Para usar una sintaxis más "avanzada" en el split, se pueden usar expresiones regulares (o regex), con la función Regex.Split(String).
El regex sería:
[-+/*]|[<>]=?

*

*Los corchetes definen una clase de caracteres (diferentes opciones para un mismo caracter).

*La barra vertical es un OR (alternancia).

*El ? del final hace que el = sea opcional (abreviando a <=|>=|[<>]).

Código:
Imports System
Imports System.Text.RegularExpressions

Dim texto As String = "prueba+a-b<=c"

'Split con expresión regular
Dim regex As Regex = New Regex("[-+/*]|[<>]=?")
Dim vectoraux() As String
vectoraux = regex.Split(texto)

'mostrar resultado
For Each item As String In vectoraux
    Console.WriteLine("'{0}'", item)
Next

Resultado:
'prueba'
'a'
'b'
'c'

Demo:
http://rextester.com/VZPDC6661

3. Con regex, pero incluyendo a los delimitadores
Además, las opciones con regex nos dan otras alternativas. Por ejemplo, si también queremos que aparezcan los delimitadores en el array, usamos un grupo (paréntesis):
([-+/*]|[<>]=?)

que nos devuelve el array:
{"prueba","+","a","-","b","<=","c"}

Demo: http://rextester.com/KDV25064


text:
Q: For loop generates no output nor errors I have the below For loop to generate Histograms for 16 values in my dataset but I have no historgam showing. What may I be doing wrong?
 For[i = 1, i < 17, i++,
  mycnr = StringJoin["CNR", ToString[i]];
  cnr[i] = newDataSet[All, mycnr];
  Histogram[cnr[i]]]

when I comment out lines 3 and 4 inside for loop to see the outcome of the StringJoin function, I do not see the mycnr simply showing the CNR1 to CNR16 I expect from such StringJoin
I apologize, I am new at Mathematica, so "be gentle" :-)

A: I simplified it and finally got it to work:
For[i = 1, i < 17, i++,
  Histogram[newDataSet[All, StringJoin["CNR", ToString[i]]]]
];


text:
Q: A statistical approach to the prisoners problem Two days ago, I found this problem on reddit (I didn't have access to reddit when I did the math, so I did it with 24 instead of 23, and I decided the warden picked someone every day, not "whenever he feels like it"):

A prison warden tells 24 prisoners he has a "game" for them. Once per day, the warden chooses one prisoner at random and leads them to the Switch Room. The aptly named Switch Room has two switches, both at the Off position at first, that are connected to nothing. The called prisoner has to toggle exactly one switch.
At any time, any prisoner can go to the warden and tell him that the 24 prisoners all went to the Switch Room at least once. If that's true, they're all freed. If not, they're going to be made into sausages for the other inmates or something.
The prisoners can come up with a plan now but won't ever be able to communicate again until someone tells the warden.

EDIT After some debating with @alex.jordan, I wanted to clarify my intent. My perspective is that this is a metaphor for "how would you tell that N distinct events, uniformly and randomly happening, all happened at least once if you only had 2 bits to spare", and has nothing to do with an actual warden (who could be biased in his random choices or use a different distribution model to screw up the prisoners), or actual prisoners.
I am solely interested in an answer that assumes a prisoner is selected randomly and uniformly once every day (not "from time to time" as stated in the reddit riddle), so you can safely ignore any assumption that the warden is out there to grind the prisoners to sausages or selects people with a bias or just won't ever select anyone.

The "classical" solution is that the prisoners designate one leader. When a prisoner enters the Switch Room (except the leader), if they've never been there and find the first switch in the Off position, they turn it on. Otherwise, they toggle the other switch. When the leader enters the Switch Room, if he sees the first switch in the On position, he knows that someone who's never been there before has been, so he counts one and turns off the switch. When he has counted to 23, he knows that everyone has been there at least one.
The thing is, this solution sucks. Assuming 24 prisoners again, and knowing they're picked at random, we can represent the whole thing as a series of geometric distributions (this also assumes I'm doing it right, which I may not be):
$$
X: \text{number of days before the Leader goes to the Switch Room}\\
X \sim Geom\left(\frac{1}{24}\right)\\
E(X) = 24, Var(X) = 552\\
$$
$$
Y_n: \text{number of days before one of the n remaining prisoner}\\
\text{goes to the Switch Room for the first time (n from 1 through 23)}\\
Y_n \sim Geom\left(\frac{n}{24}\right)\\
E(Y_n) = \frac{24}{n}, Var(Y_n) = \frac{24 (24-n)}{n^2}
$$
Since expected values and variance can be linearly added, we can expect that the Leader will tell the warden after on average 642 days, with a standard deviation of 116, by assuming the leader will go $E(X)$ days after any given prisoner went for the first time as modeled by $E(Y_n)$:
$$
Z: \text{Number of days before the Leader announces everyone's been to the Switch Room}\\
E(Z) = \sum_{n=1}^{23}E(X) + E(Y_n) = 552 + \sum_{n=1}^{23}E(Y_n) \approx 552 + 89.6229 \approx 641.6229\\
Var(Z) = \sum_{n=1}^{23}Var(X) + Var(Y_n) = 12696 + \sum_{n=1}^{23}Var(Y_n) \approx 12696 + 833.3521 \approx 13529.3521\\
\sigma = \sqrt{13529.3521} = 116.3157
$$
Very simple maths tell us that after 642 days, every prisoner's been on average 26 times to the Switch Room. This looks like a horrible waste of time.
I'm pretty sure it's possible to calculate how many days you would need to wait before you have 99% chances (or higher) that each prisoner has been there. Problem is, I'm only halfway through my college stats class, and we've only seen easy distributions where successes are independent, so I'm not too sure how to tackle that.
How would you calculate the chances that each prisoner has been to the Switch Room after $Z$ days?

EDIT I just made a quick and dirty program to run "simulations", and it takes on average 90.6 days until every prisoner has visited the Switch Room, with a standard deviation of 28.5. Making that into a normal distribution, it should be around 157 days before we can say with 99% certainty that each prisoner has visited the Switch Room at least once, and 179 days for 99.9% certainty. Needless to say, you're pretty safe after 641 days...
It's an empirical technique and it doesn't really feel mathematically satisfying, so the question is still open for better answers.

A: It is even worse than that.  On day $1$ some prisoner turns the switch on (unless the leader goes first).  Then all the prisoners that visit next can't turn it on, so those visits are wasted.
The page here has a good writeup.  Your solution is Solution 6:  Simple count and he claims with 100 prisoners you need 28 years.  There are some strategies, and I found a very nice paper that I can't find again.
For your question, we can pretend that each prisoner is independent of each other (which is a much better approximation than it sounds). After $d$ days the prisoner has $(\frac {23}{24})^d$ chance of not having visited the room.  To have a $99\%$ chance that they all have visited, we need $$(1-(\frac {23}{24})^d)^{24}=0.99
\\1-(\frac {23}{24})^d=0.99^{\frac 1{24}}\\(\frac {23}{24})^d=1-0.99^{\frac 1{24}}\\d=\frac {\log (1-0.99^{\frac 1{24}})}{\log \frac {23}{24}}\approx 182.76$$  You are right that this is much faster

A: To remove the independence assumption that Ross uses for simplification leaves you with a messy equation, but one that could be solved to arbitrary precision if you allow a computer.
After $d$ days, $24^d$ possible sequences may have come to pass. How many of these have each prisoner represented? Well, we could subtract the ones without prisoner #1, then those without #2 and so on. But we've overcounted what to subtract this way. We'd throw back in those with #1 and #2 missing. If you're familiar with the inclusion-exclusion principle, then what this leads to is
$$P(d) =\frac{24^d-\binom{24}{23}23^d+\binom{24}{22}22^d-\cdots\pm\cdots-\binom{24}{1}1^d}{24^d}$$
where $P(d)$ is the probability that all prisoners have visited the room by day $d$. An equation like $P(d)=0.99$ is not the nicest thing to try to solve, but you could get computer assistance. It may be helpful to recognize that you are only looking for integer $d$.
@Ross's result suggests $d$ should be close to $182.76\ldots$ for 99% certainty. Well, $P(182)=0.989655\ldots$ and $P(183)=0.990085\ldots$, so it's hard to argue that it is worth the effort to be more precise than making an independence assumption.

A: A problem with what you are trying to do is that you are not considering the sadism of the warden. Both your simulation and @Ross's estimation assume that prisoners are sent in a uniformly random way to the switch room. It's debatable whether or not "the warden chooses one prisoner at random" really means that. And I have heard versions of this problem that leave out the phrase 'at random'. The warden could thwart these strategies by choosing some prisoners with 1/100 the probability of others. The warden could be really sadistic and purposely never choose one particular prisoner. Or the warden could be using his human brain to "randomly" pick a prisoner, which will fail to be a truly uniformly random selection.
The classic solution that involves a leader counting is deterministic in that if the leader counts to 24 (23?), it's over for sure. If you were one of these prisoners, would you really bet that the warden is using a true uniformly random selection?

EDIT: OP asks "How would you calculate the chances that each prisoner has been to the Switch Room after Z days?"
My response is essentially that you cannot do this, until you explicitly assume a particular distribution for how prisoners are randomly selected. And why on earth would you do that if this or any similar situation was real?
I don't understand the down votes, unless someone

*

*thinks that "random" (which means 'cannot be predicted') means the same thing as 'uniformly random'

*and think I'm just being cheeky and that I might as well let the warden tamper with switches. But allowing the warden to use other random selection processes does not make them a liar, like tampering with the switches would.

Part of the beauty of the way I understand this problem and the 'leader' solution is that you find a strategy that thwarts the warden's human imperfections no matter how the selection process goes. We have to assume the warden is honest or else there is no point to any of it.

A: As multiple people already suggested (but no one actually answered), this is essentially the same as the coupon collector's problem: in a set of $n$ unique coupons that you draw with replacement, how many draws will it take until you have drawn each coupon at least once?
This kind of model is suited for combining multiple geometric distributions with equal probabilities (as is the case here). Per the two links above, letting $T_n$ be the number of trials to collect all $n$ coupons (or to send all $n$ prisoners to the Switch Room), then
$$
E(T_n) = n \cdot H_n\\
Var(T_n) = \frac{\pi^2 n^2}{6} - n\cdot H_n
$$
Therefore, reusing my $Z$ variable:
$$
Z: \text{Days before the Leader announces all prisoners been to the Switch Room}\\
E(Z) = E(T_{24}) = 24 \cdot H_{24} \approx 90.623\\
Var(Z) = Var(T_{24}) = 96\pi^2 - 24H_{24} \approx 856.859\\
\sigma = \sqrt{Var(Z)} \approx 29.2722
$$
Both values closely match what I got with my simulations.
It looks like it would be fairly hard to assess a probability between 0 and 1 for whether or not all the prisoners will have visited the room after $z$ days following exactly the distribution curve, seeing how it is left-biased. Approximating it as a normal distribution $N(856.859, 29.2722^2)$, there are 99% chances that all the prisoners will have visited the Switch Room after 158.72 days; 99.9% chances after 181.081 days; 99.99% after 199.487 days; and after 233.822 days, my venerable calculator can't handle a number small enough to distinguish the probability from 1.


text:
Q: What does average of log-transformed variable mean? In my bivariate regression model, I log-transformed the dependent variable. and the mean is now 2.77. and I got -0.186 for coefficient.
Could anyone tell me the interpretation of 2.77 here? and how can it compare with -0.186?

A: Before going into the details, the mean of a log-transformed variable is indeed the mean of the log-transformed variable. However, its exponential form has a special identity called geometric mean. This explanation will tap into this idea.
Let's assume your independent variable is continuous. Given
$$\ln(y) = 4.107 - 0.186x $$
for one unit increase in $x$, we then have:
$$\ln(y') = 4.107 - 0.186(x+1)$$
Solving the two equations, we have:
$$\ln(y') - \ln(y) = -0.186$$
Because $\ln(A) - \ln(B) = \ln(A/B)$:
$$\ln(y'/y) = -0.186$$
Now, let's take away the log, but doing so means $y'/y$ will not be interpreted as a ratio of two arithmetic means, but rather a ratio of two geometric means.
$$y'/y = 0.8303$$
So, the interpretation is then: corresponding to one unit increase in $x$, the geometric mean changes by a factor of 0.8303, a 17% decrease.
<><><><><><><><><><>
Now, for the mean: $\exp(2.77) = e^{2.77}$ is 15.96, and this is the geometric mean of $y$.
<><><><><><><><><><>
R code for reference:
set.seed(2208)
x <- sample(seq(1:10), 5, replace=T)
x

# This is geometric mean
(6*4*6*4*9)^(1/5)

# Mean of log(x)
mean(log(x))
# Exponent is the geometric mean
exp(mean(log(x)))

Output:
> set.seed(2208)
> x <- sample(seq(1:10), 5, replace=T)
> x
[1] 6 4 6 4 9
>
> # This is geometric mean
> (6*4*6*4*9)^(1/5)
[1] 5.532647
>
> # Mean of log(x)
> mean(log(x))
[1] 1.710666
> # Exponent is the geometric mean
> exp(mean(log(x)))
[1] 5.532647


text:
Q: Refactoring auto-detect file's encoding I need to check encoding files. This code work but it's a little bit long. How able to make any refactoring this logic.
Maybe can to use some another variant for this target?
Code:
class CharsetDetector implements Checker {

    Charset detectCharset(File currentFile, String[] charsets) {
        Charset charset = null;

        for (String charsetName : charsets) {
            charset = detectCharset(currentFile, Charset.forName(charsetName));
            if (charset != null) {
                break;
            }
        }

        return charset;
    }

    private Charset detectCharset(File currentFile, Charset charset) {
        try {
            BufferedInputStream input = new BufferedInputStream(
                    new FileInputStream(currentFile));

            CharsetDecoder decoder = charset.newDecoder();
            decoder.reset();

            byte[] buffer = new byte[512];
            boolean identified = false;
            while ((input.read(buffer) != -1) && (!identified)) {
                identified = identify(buffer, decoder);
            }

            input.close();

            if (identified) {
                return charset;
            } else {
                return null;
            }

        } catch (Exception e) {
            return null;
        }
    }

    private boolean identify(byte[] bytes, CharsetDecoder decoder) {
        try {
            decoder.decode(ByteBuffer.wrap(bytes));
        } catch (CharacterCodingException e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean check(File fileChack) {
        if (charsetDetector(fileChack)) {
            return true;
        }
        return false;
    }

    private boolean charsetDetector(File currentFile) {
        String[] charsetsToBeTested = { "UTF-8", "windows-1253", "ISO-8859-7" };

        CharsetDetector charsetDetector = new CharsetDetector();
        Charset charset = charsetDetector.detectCharset(currentFile,
                charsetsToBeTested);

        if (charset != null) {
            try {
                InputStreamReader reader = new InputStreamReader(
                        new FileInputStream(currentFile), charset);

                @SuppressWarnings("unused")
                int valueReaders = 0;
                while ((valueReaders = reader.read()) != -1) {
                    return true;
                }

                reader.close();
            } catch (FileNotFoundException exc) {
                System.out.println("File not found!");
                exc.printStackTrace();
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        } else {
            System.out.println("Unrecognized charset.");
            return false;
        }

        return true;
    }
}

Question:

*

*How does this program logic refactor?

*Which are another ways to detect encoding (as UTF-16 sequance etc.)?

A: the best way to refactor this code would be to bring in a 3rd party library that does character detection for you, because they probably do it better and it would make your code smaller.
see this question for a few alternatives

A: As has been pointed out, you can't "know" or "detect" the encoding of a file.  Complete accuracy requires that you be told, as there is almost always a byte sequence which is ambiguous with respect to several character encodings.
You'll find some more discussion about detecting UTF-8 vs ISO8859-1 in this SO question.. The essential
answer is to check each byte sequence in the file to verify its compatibility
with the encoding expected.  For UTF-8 byte encoding rules, see http://en.wikipedia.org/wiki/UTF-8.
In particular, there's a very interesting paper on detecting character encodings/sets
http://www-archive.mozilla.org/projects/intl/UniversalCharsetDetection.html
They claim they have extremely high accuracy (guesses!).  The price is a very complex detection system, complete with knowledge about character frequencies in different languages, that doesn't fit in the 30 lines OP has hinted as being the right code size.   Apparently the detection algorithm is built into Mozilla, so you can likely find and extract it.
We settled for a much simpler scheme: a) believe what you are told the character set is, if you are told b) if not, check for BOM and believe what it says if present, otherwise sniff for pure 7 bit ascii, then utf8, or iso8859 in that order. You can build an ugly routine that does this in one pass over the file.
(I think the problem is going to get worse over time. Unicode has a new revision every year, with truly subtle differences in valid code points.  To do that right, you need to check every code point for validity.  If we're lucky, they're all backwards compatible.)
[EDIT: OP seems to be having trouble coding this in Java.  Our solution and the sketch on the other page are not coded in Java so I can't copy and paste an answer directly.  I'm going to draft a Java version here based on his code; it isn't compiled or tested.  YMMV]
int UTF8size(byte[] buffer, int buf_index)
// Java-version of character-sniffing test on other page
// This only checks for UTF8 compatible bit-pattern layout
// A tighter test (what we actually did) would check for valid UTF-8 code points
{   int first_character=buffer[buf_index];

    // This first character test might be faster as a switch statement
    if ((first_character & 0x80) == 0) return 1; // ASCII subset character, fast path
    else ((first_character & 0xF8) == 0xF0) { // start of 4-byte sequence
        if (buf_index+3>=buffer.length) return 0;
        if (((buffer[buf_index + 1] & 0xC0) == 0x80)
         && ((buffer[buf_index + 2] & 0xC0) == 0x80)
         && ((buffer[buf_index + 3] & 0xC0) == 0x80))
            return 4;
    }
    else if ((first_character & 0xF0) == 0xE0) { // start of 3-byte sequence
        if (buf_index+2>=buffer.length) return 0;
        if (((buffer[buf_index + 1] & 0xC0) == 0x80)
         && ((buffer[buf_index + 2] & 0xC0) == 0x80))
            return 3;
    }
    else if ((first_character & 0xE0) == 0xC0) { // start of 2-byte sequence
        if (buf_index+1>=buffer.length) return 0;
        if ((buffer[buf_index + 1] & 0xC0) == 0x80)
            return 2;
    }
    return 0;
}

public static boolean isUTF8 ( File file ) {
    int file_size;
    if (null == file) {
        throw new IllegalArgumentException ("input file can't be null");
    }
    if (file.isDirectory ()) {
        throw new IllegalArgumentException ("input file refers to a directory");
    }

    file_size=file.size();
    // read input file
    byte [] buffer = new byte[file_size];
    try {
        FileInputStream fis = new FileInputStream ( input ) ;
        fis.read ( buffer ) ;
        fis.close ();
    }
    catch ( IOException e ) {
        throw new IllegalArgumentException ("Can't read input file, error = " + e.getLocalizedMessage () );
    }

    { int buf_index=0;
      int step;

      while (buf_index<file_size) {
         step=UTF8size(buffer,buf_index);
         if (step==0) return false; // definitely not UTF-8 file
         buf_index+=step;

      }

    }

   return true ; // appears to be UTF-8 file
}


text:
Q: How to include Logo in Reset password email in laravel I am trying to customize reset password blade.
So far,
I have put this code in User.php model.
public function sendPasswordResetNotification($token)
{
    $this->notify(new ResetPasswordNotification($token));
}

And,
php artisan make:notification MyOwnResetPassword
I used this command to publish custom notification
public function toMail($notifiable)
{

    return (new MailMessage)
                ->subject('Reset Password')
                ->line('You are receiving this email because we received a password reset request for your account.')
                ->action('Reset Password', url('admin/password/reset/'.$this->token, false))
                ->line('If you did not request a password reset, no further action is required.');
}

The question is how to add a Logo?
Any help or reference would be great
Thanks

A: In the documentation (https://laravel.com/docs/5.3/notifications#mail-notifications) It says that your new MailMessage is sending a formatted message.
Also you can customize your template :

in the resources/views/vendor/notifications directory

You probably need to run that command before : php artisan vendor:publish --tag=laravel-notifications
You can see all the documentation here : https://laravel.com/docs/5.3/notifications#customizing-the-templates


text:
Q: Static lookup on Rails Model I'm trying to figure out the best way to model a simple lookup in my rails app.
I have a model, Coupon, which can be of two "types", either Percent or Fixed Amount.  I don't want to build a database table around the "type" lookup, so what I'd like to do is just have a coupon_type(integer) field on the Coupon table which can be either 1 (for Percent) or 2 (for Fixed).
What is the best way to handle this?
I found this: Ruby on Rails Static List Options for Drop Down Box but not sure how that would work when I want each value to have two fields, both ID and Description.
I'd like this to populate a select list as well.
Thank you for the feedback!

A: If this is really unlikely to change, or if it does change it will be an event significant enough to require redeployment, the easiest approach is to have a constant that defines the conditions:
COUPON_TYPES = {
  :percent => 1,
  :fixed => 2
}

COUPON_TYPES_FOR_SELECT = COUPON_TYPES.to_a

The first constant defines a forward mapping, the second in a format suitable for options_for_select.
It's important to note that this sort of thing would take, at most, a millisecond to read from a database. Unless you're rendering hundreds of forms per second it would hardly impact performance.
Don't worry about optimizing things that aren't perceptible problems.


text:
Q: Not able to get access_token for Microsoft Graph API OAuth 2.0 using username & password I am trying to get access_token using
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
endpoint using username and password where tenant = {some tenant id}
The parameters that I am using to make the request are:
client_id:{client_id}
scope:https://graph.microsoft.com/Calendars.ReadWrite
client_secret:{client_secret}
username:{username}
password:{password}
grant_type:password

I am getting the following error in response:
error: invalid_request
error_description : AADSTS90002: Tenant '' not found. This may happen if there are no active subscriptions for the tenant. Check with your subscription administrator.

I have the following permissions for my application available on Azure:

The documentation for this is available here : https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc

A: On my side, it works. You should check your tenant whether your application is registered in this tenant.

A: I solved this issue by purchasing a subscription and adding my user as an administrator.
After that, I added two permissions to my application to get the delegate access for using ROPC (Resource Owner Password Credential)authentication method and granted them with the administrator consent.


text:
Q: Without using calculus, how can I find the formula for the area of the shaded region in the attached figure in terms of a and b? Note that the center of the larger circle is on the edge of the smaller.

A: To understand I recommend you open the picture here.
Lets denote :

*

*$A$ the center of the circle of radius $b$.

*$B$ the center of the circle of radius $a$.

*$C$ and $D$ the ontersection points betwin the two circles.

*$E$ the intersection point between the segments [CD] and [AB]

*$A_{shaded}$ the area of the shaded region.

*$A_{circle_A}$ the area of the circle of center A.

*$A_{circle_B}$ the area of the circle of center B.

*$\alpha$ the angle $\angle CAD$.

*$\beta$ the angle $\angle ABC$.

*$A_{Red}$ the area delimited by the arc (AC) and the segment [AC].

*$A_{Blue}$ the area delimited by the arc (AD) and the segment [AD].

*$A_{ACD}$ the area delimited by the arc (CD) and the segments [AC] and [AD].
We have two cases :
First case : $2a\leq b$ then $A_{shaded}=A_{circle_A} - A_{circle_B}= \pi b^2-\pi a^2 $
Second case $b<2a$ :
you can see that $A_{shaded}= A_{circle_A}-A_{ACD}-A_{Blue}-A_{Red}$
but $A_{Blue}=A_{Red}$ and $A_{circle_A}=\pi b^2$
So we get $A_{shaded}= \pi b^2-A_{ACD}-2A_{Blue}$
$A_{ACD}= \frac{b^2\alpha}{2}$
$A_{Blue} = \frac{a^2}{2}(\beta-sin(\beta))$ the difference between the area delimited by ( the segment [BC], the arc (CA) and the segment [AB] ) and (the area of the triangle BCA).
so finally we get $A_{shaded}= \pi b^2-\frac{b^2\alpha}{2}-a^2(\beta-sin(\beta))$. Now lets compute the angles $\alpha$ and $\beta$ :
applying the law of cosines on the triangle AED you get that
$cos(\frac{\alpha}{2}) = \frac{a^2+b^2-a^2}{2ab}=\frac{b}{2a}$ (notice the condition $b<2a$) and thus $\alpha=2 cos^{-1}(\frac{b}{2a})$
Now for $\beta$ notice that the triangle BCA is isosceles (BC=BA=a) so $\beta = \pi-\alpha$
Finally you get :
$A_{shaded}= \pi b^2-b^2 cos^{-1}(\frac{b}{2a})-a^2(\pi-2 cos^{-1}(\frac{b}{2a})-sin(\pi-2 cos^{-1}(\frac{b}{2a})))$

A:
If we consider the centers of both the circles on y axis, origin as the center of the bigger circle, then let the two circles intersect at $A=(x_1,y_1), B=(x_2,y_2)$
Equation of the bigger circle is $x^2+y^2=b^2...(I)$
Equation of the smaller circle $(x-h)^2+(y-k)^2=a^2$, here $h=0, k=-a$
$\therefore x^2+(y+a)^2=a^2...(II)$
$(II)-(I)$ gives $y=\frac{-b^2}{2a}$ and $x=\pm \frac{-b\sqrt{4a^2-b^2}}{2a}$
$\therefore x_1=-\frac{b\sqrt{4a^2-b^2}}{2a}$ and $x_2=\frac{b\sqrt{4a^2-b^2}}{2a}$
It can be proved that $AB=2CB$ and $\angle OCB=90$ by Pythagoras theorem.
$\ell(AB)=\frac{b}{a}\sqrt{4a^2-b^2}$
angle subtended by $AB$ at the center of the bigger circle$=\phi=2\cdot \sin^{-1}\left(\frac{\sqrt{4a^2-b^2}}{2a}\right)$
angle subtended by $AB$ at the center of the smaller circle$=\phi'=2\cdot \sin^{-1}\left(\frac{b\sqrt{4a^2-b^2}}{2a^2}\right)$
The isosceles triangles $AO'O$ and $BO'O$, both with equal sides length$=a$ and base$=b$ and area$=\frac{b}{4}\sqrt{4a^2-b^2}$
Area of the crescent shape region or segment = area of sector of the smaller circle formed by $AO$ or $BO$ - combined area of isosceles triangles $AO'O$ and $BO'O$
$=\frac{a^2}{2}\cdot 2 \sin^{-1}\left( \frac{b\sqrt{4a^2-b^2}}{2a^2} \right)-\left( \frac{b}{2}\sqrt{4a^2-b^2} \right)$
area of the bigger circle sector$=\frac{b^2}{2}\cdot 2 \sin^{-1} \left( \frac{\sqrt{4a^2-b^2}}{2a} \right)$
$\therefore$ area of the required region $\color{red}{= \pi b^2 - b^2\cdot \sin^{-1} \left( \frac{\sqrt{4a^2-b^2}}{2a} \right)-\left(  a^2\cdot  \sin^{-1}\left( \frac{b\sqrt{4a^2-b^2}}{2a^2} \right)-\left( \frac{b}{2}\sqrt{4a^2-b^2} \right)\right)}$
To check if the formula is correct, put $b=\sqrt2 a$, so that points $O'$ and $C$ coincide and the $\angle AOB=90$ and the required area is (area of bigger circle) - (area of sector $AOB$) - (area of two segments or crescent shaped regions), which is
$\frac{3\pi b^2}{4}-\frac{\pi a^2}{2}+\frac{b}{2}\sqrt{4a^2-b^2}=a^2(\pi+1)$
if we substitute $b=\sqrt2 a $ in the $\color{red}{red}$ formula, we get the same result
Check using calculus: $(b=\sqrt2 a)$

In the diagram consider only the region marked I, to the right of the dashed line
area I=$\int_0^a (\sqrt{b^2-y^2}-a)dy = \dfrac{\pi a^2}{4}-\dfrac{a^2}{2}$
In the diagram consider only the region marked II, to the left of the dashed line (note that axis are shifted vertically down by $a$ units)
area II=$\int_0^a(a-\sqrt{a^2-y^2})dy = a^2-\dfrac{\pi a^2}{4}$
area I + area II = $\dfrac{a^2}{2}$, two such areas = $a^2$, area of upper half circle with radius $ b = \dfrac{\pi b^2}{2}=\pi a^2$
adding everything together we get the required area = $\pi a^2+a^2=a^2(\pi+1)$, $\color{red}{voila!}$


text:
Q: How to Roll up duplicate IDs in a column into one row and display the results I have clickstream data from Google Analytics in R with the following
columns:
UserID, SessionID, TimeStamp, PagePath, PageViews

The UserIDs are duplicated throughout the data set like so because a UserID would have multiple pagepaths, timestamps, and even SessionIDs.
UserID Column    SessionID    TimeStamp   PagePath             PageViews
1                  1.1          12:01      google.com             1
1                  1.1          12:03      google.com/products    1
1                  1.1          12:06      google.com/info        1
1                  1.1          12:08      google.com/purchase    1
2                  2.1          09:07      google.com             1
2                  2.1          09:13      google.com/info        1

What I want to do is be able to do is find a package or some type of way
to put this in a dataframe where I can use with Clickstream Package in R
so the results would look like so :
UserID        PagePathBrokenOut
1             google.com,products,info
2             google.com,info

What function or package in R would accomplish this. I can't use c(
because there are literally thousands upon thousands of userIDs and
paths
I have explored the data.frame function and dplyr but haven't had much
luck ... there has to be a way to condense UserID to a singular row and
then display out the pagepaths.
I have tried dplyr and data.frame as well as reshape but again none of
those have worked so far
Again if there is a way to consolidate multiple user ids in one singular
column into 1 row with the respective paths that would be awesome.
I have tried to use dplyr but it hasn't worked
path <- ddply(mydata, "userID",function(df1)paste(df1$pagepath,collapse = ","))

A: Two solutions:
dplyr
library(dplyr)
dat %>%
  mutate(Page = gsub("/.*", "", PagePath),
         Path = trimws(gsub("^/|?$", "", gsub("^[^/]*", "", PagePath)))) %>%
  group_by(UserID, Page) %>%
  summarize(PagePathBrokenOut = paste(c(Page[1], Filter(nzchar, Path)), collapse = ",")) %>%
  ungroup()
# # A tibble: 2 x 3
#   UserID Page       PagePathBrokenOut
#    <int> <chr>      <chr>
# 1      1 google.com google.com,products,info,purchase
# 2      2 google.com google.com,info

data.table
(Note: I'm using the magrittr package only to break out the pipe-line of calls, not that it is required to do this. It is not.)
library(data.table)
library(magrittr)
datDT <- as.data.table(dat)
datDT %>%
  .[, c("Page", "Path") := .(gsub("/.*", "", PagePath),
                             trimws(gsub("^/|?$", "", gsub("^[^/]*", "", PagePath)))), ] %>%
  .[, .(PagePathBrokenOut = paste(c(Page[1], Filter(nzchar, Path)), collapse = ",")),
    by = c("UserID", "Page")]
#    UserID       Page                 PagePathBrokenOut
# 1:      1 google.com google.com,products,info,purchase
# 2:      2 google.com                   google.com,info

Data:

dat <- read.table(header = TRUE, stringsAsFactors = FALSE, text = "
UserID    SessionID    TimeStamp   PagePath             PageViews
1           1.1          12:01      google.com             1
1           1.1          12:03      google.com/products    1
1           1.1          12:06      google.com/info        1
1           1.1          12:08      google.com/purchase    1
2           2.1          09:07      google.com             1
2           2.1          09:13      google.com/info        1 ")

A: Here's another approach that could be useful for some cases:
#Remove non required columns and spread
df2 <- df %>%
  select(UserID, PagePath, PageViews) %>%
  spread(PagePath, PageViews)

#Temporal vector to store UserIDs and remove it from df2
UserIDTemp <- df2$UserID
df2$UserID <- NULL

#Populate data frame with URLs instead of page views. NAs will be generated
w <- which(!is.na(df2), arr.ind = TRUE)
df2[w] <- names(df2)[w[, "col"]]

#Paste/concatenate all paths into a single string
df_args <- c(df2, sep = ", ")
pastedPaths <-  do.call(paste, df_args)

#Create data frame with UserIDs and paths
PagePaths <- data.frame(UserIDTemp, pastedPaths)

data.frame(UserIDTemp,pastedPaths)
# UserIDTemp                                                  pastedPaths
# 1 google.com, google.com/info, google.com/products, google.com/purchase
# 2                                   google.com, google.com/info, NA, NA

Data:
#Replicate data frame
UserID <- c(1, 1, 1, 1, 2, 2)
SessionID <- c(1.1, 1.1, 1.1, 1.1, 2.1, 2.1)
TimeStamp <- c(1, 2, 3, 4, 5, 6)
PagePath <-
  c(
    "google.com",
    "google.com/products",
    "google.com/info",
    "google.com/purchase",
    "google.com",
    "google.com/info"
  )
PageViews <- c(1, 1, 1, 1, 1, 1)
df <- data.frame(UserID, SessionID, TimeStamp, PagePath, PageViews)


text:
Q: Using music in a java program I was trying out the method of creating a background music for a java program, but it displayed an IO excedption error when i clicked the play button.
package javaentertainment;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.*;
import sun.audio.AudioData;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

public class Music
{

    public static void main(String args[])
    {
        JFrame frame=new JFrame();
        frame.setSize(100,100);
        JButton button=new JButton("P L A Y");
        frame.add(button);
        button.addActionListener(new AL());
        frame.show();
    }

   public static class AL implements ActionListener
   {

        public void actionPerformed(ActionEvent e) {
            music();
        }
    }

    public static void music()
    {
        AudioPlayer MGP=AudioPlayer.player;
        AudioStream BGM;
        AudioData MD;
        ContinousAudioDataStream loop=null;

        try
        {
            BGM = new AudioStream(new FileInputStream("Vision.wmv"));
            MD=BGM.getData();
            loop=new ContinousAudioDataStream(MD);

        }
        catch (IOException ex)
        {
           System.out.println(ex);
        }

        MGP.start(loop); // word loop was underlined by netbeans
    }
}

When I run the program and click on play it displays the following error,
java.io.IOException: could not create audio stream from input stream

A: You should use JMF (Java Media Framework). For your interest: The list of accepted formats can be found here.
In short, it supports AIFF, AVI, GSM, MVR, MID, MPG, MP2, MOV, AU and WAV files.
But there is a workarond as stated here:

On a side note, if you add a
  mime-setting in JMFRegistry to map
  Windows Media content (such as .asf
  and .wmv) to the content-type
  "video/mpeg", JMF can actually play
  Windows Media or any other DirectShow
  file (and only file - http wont work).

A: I would be surprised if Java can hand Windows Media format samples - try converting the .wmv to a .wav file and see if it works then.

A: Just got this, as well.
java.io.IOException: could not create AudioData object

Appears from the source [1] that this means that "your audio file is size > 1 MB" and it doesn't like that for whatever reason.  Maybe a bug [?] that they don't accomodate for this.
One work-around might be to use JMF instead, as suggested, if you want looping to work for large files anyway.
[1] http://www.docjar.com/docs/api/sun/audio/AudioStream.html#getData


text:
Q: Find all the relative extrema of $f(x)=x^4-4x^3$ Find all the relative extrema of $f(x)=x^4-4x^3$

$Solution:$
Step 1: Solve $f'(x)=0$.
$f'(x)=4x^3-12x^2=0$
$\rightarrow$ $4x^2(x-3)=0$
$\rightarrow$ $x=0$ and $x=3$
Step 2: Draw a number line and evaluate the sign of the derivative on each section (I don't know how to draw a number line on the computer but I'll do what I can).
Lets pick a number in the region $(-\infty,0)$, how about $x=-1$:
$f'(-1)=4(-1)^2(-4)=-16<0$
Now lets pick a number in the region $(0,3)$, how about $x=2$:
$f'(2)=4(2)^2(2-3)=-1<0$
Now lets pick a number in the region $(3,\infty)$, how about $x=4$:
$f'(4)=4(4)^2(4-3)=64>0$
So our function is decreasing as $x$ increases towards $0$, then our function decreases as $x$ increases towards $3$, then our function increases as $x$ increases towards $\infty$. Therefore we have a relative minimum when $x=3$ and no relative maximum. Lets solve for the corresponding $y$ value:
$f(3)=3^4-4(3)^3 = 81-4(27)=-27$
So we have a relative minimum at $(3,-27)$ and our relative maximum DNE

A: Solution without derivative.
By AM-GM $$x^4-4x^3=3\cdot\frac{x^4}{3}+27-4x^3-27\geq4\sqrt[4]{\left(\frac{x^4}{3}\right)^3\cdot27}-4x^3-27=$$
$$=4|x^3|-4x^3-27\geq-27.$$
The equality occurs for $x=3,$ which says that we got a minimal value.
The maximum does not exist because $$\lim\limits_{x\rightarrow+\infty}(x^4-4x^3)=\lim_{x\rightarrow+\infty}x^4\left(1-\frac{4}{x}\right)=+\infty.$$

A: Once you have identified $x_0=0$ and $x_0=3$ you can also evaluate the sign of $f(x)-f(x_0)$.

*

*$x_0=0$ where $f(0)=0$
$$f(x)=x^3\underbrace{(x-4)}_{<0}$$
Thus the sign of $f(x)$ is determined by the sign of $x^3$ around $0$ which is not constant so $x_0=0$ is an inflexion point.

*

*$x_0=3$ where $f(3)=-27$
Let set $u=x-3$ then $$f(x)-f(3)=(u+3)^3(u-1)+27=18u^2+8u^3+u^4=\underbrace{u^2}_{\ge 0}\underbrace{(u^2+8u+18)}_{\Delta=-8\implies >0}\ge 0$$
Thus $f(3)$ is a global minimum.

A: More sophisticated is to take a second derivative which indicates the rate of change of the derivative when the derivative is zero.  (Assuming the second derivative exists)
A derivative $f(x)=0$ means to function has "flatlined" as $x$. Four things can/will occur. [For purpose of analogy, I was consider the graphs moving in time. And values $x'< 0$ I will use past tense.  $x' = x$ is "now" and I'll use present tense. And $x' > 0$ I'll use future tense.
1) The function could have been climbing, is now reaching a peak, and then will decline.  (In which case this is a local maximum.)
That means that the derivative was positive, hits zero, and will then be negative.
The will be the case if $f''(x) < 0$.  That would mean the derivative represented a positive steepness in the function but the steepness was decreasing, it decreases to $0$ steepness at which point the function plateaus, and then will become negatively step and and function will begin to go down.
However this could also be the case if $f''(x)=0$.  The function could have been raises, the steepness (derivative) decreasing but decreasing less and less, the function then plateaus while the rate of change in steepness sloughs to zero, then the rate of change in steepness becomes active again and the steepness becomes negative and the function will begin to drop.
So $f'(x)=0$ and $f'''(x) < 0$ means $x$ is a local maximum.  $f'(x)=0$ and $f''(x)=0$ means it could be, but isn't necessarily, a maximum.  If $f'(x)= f''(x)=0$ and $x$ is a local maximum  that is called an undulation point.
2) The function could have been dropping, is now flatlining, and will then raise.
This is the exact opposite as above for the same reasons.  And is a local minimum.
The will always by the case if $f''(x) > 0$.  If $f''(x)=0$ this could, but isn't nescessarily  the case.  If $f'(x)=f''(x) = 0$ and $f(x)$ is a local minimum this is another example of an undulation point.
3) The function was raising/dropping, is now flatling, but will then continue to raise and drop.
In this case the steepness (derivative) of the function was positive/negative, has leveled to zero, but rather than continuing to become negative/positive and will return to be positive/negative.  This would be a local min/max for the derivative.
IF the second derivative exist it will have to be that $f''(x) =0$ and this point.  (But it need not exist.  $f'$ could be making a "sharp turn" while $f$ is still differentiable).
But $f''(x) = 0$ will not assure this must be the case.
In this case this is called a  saddle point.
4) $f(x)$ have been, or will be, a constant for an interval.
If which case $f', f'', f'''$ etc so long as they actually are defined will be $0$.
====
$f''(x) = 12x^2-24x$.  $f''(3)=12*9-24*3 > 0$ so $x = 3; f(3)= -27$ is a local minimum.
$f''(0) = 0$ so it isn't clear what type of critical point $(0,0)$ is.  Taking point sample of $x=-1,2$ show you it is a saddle point.
If we have the patience and clear head  we could note that:
$f'''(x)=12x^2 - 24$ and $f'''(0)=-24 < 0$  So that means that $f'(0)=0$ was a local maximum for $f'$.  So the derivative had been less than $0$, so the function had been decreasing, the derivative is $0$ and $x=0$ and the function is flatlining, but the will drop down to being negative again, so the function will start to decrease againd.  SO $x=0; f(x)= 0$ is a saddle point.


text:
Q: Show/Hide submit button depending on selected value I would like to show/hide additional submit button depending on selected value in form.
I have no experience with JavaScript so I have only tried to modify examples found on web.
Unfortunately I couldn't find anything related with rails form_for.
Here is what I have tried so far:
<%= form_for @discount, url: {action: "create"} do |f| %>
    <%= f.label :name, "Name" %>

    <%= f.text_field :name, placeholder: "Name" %>

    <%= f.label :description, "Description" %>

    <%= f.text_area :description, placeholder: "Description" %>

    <%= f.label :with_codes, "Type" %>

    <%= f.select :with_codes, [['Without Codes', false],['With Codes', true]], :selected => :with_codes %>

        <%= f.submit "Manage Codes" %>

    <%= f.submit "Draft" %>
    <%= f.submit "Save" %>
<% end %>

This script only hides my submit button, but I think there is a problem with recognizing selected value in form.

A: First of all: are you sure that the select has id with_codes and not discount_with_codes?
Second thing, you should compare the value of the select as a string. Taking these two issues into account, the following code should work:

A: Or maybe like this (more concise):
$(function() {
  $("#row_dim").toggle($("#discount_with_codes").val() == 'true');
  $("#discount_with_codes").change(function() {
    $("#row_dim").toggle($(this).val() == 'true');
  });
});

EDIT: Whoops, looks like you've already accepted the answer. But I'll leave mine here anyway.

A: try this


text:
Q: extract data one row below based on specific condition have a very large data ~1GB and would like to extract summary data with such condition:
for loop:
 if(a[i] == 999) then extract b[i+1]
 else next
so that i can then table(b) to find the its distribution/composition, assuming column b is of class character, column a is of class integer
my R code:
summary123 <- data.frame()
j = 1
k = 1
for(i in 1:nrow(df1)){
  if(df1$a[i] == 999 & i != nrow(df1)){
    j = i + 1
    summary123[k,1] <- df1$b[j]
    k = k + 1
  }
  else{
    next
  }
}

however it is taking a long time, would like faster R-code equivalent

A: Use lead from dplyr:
output=lead(df1$b,1)[df1$a==999]

Then the answer you are looking for is:
output[-1]

(basically removing the last element, which is a NA introduced by the lead function)