text:
Q: How to store listview arrays in strings.xml im working on a project in which i have a listview and i have few arrays in my code but i want to load arrays from a separate xml file which is "strings.xml"
but i cannot figure out how to do it
here is my activity
package com.Example.myapk;

 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.text.Editable;
 import android.text.TextWatcher;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.AdapterView.OnItemClickListener;
 import android.widget.ArrayAdapter;
 import android.widget.EditText;
 import android.widget.ListView;

 public class MainActivity extends Activity {

 private ListView list1;

 private String array[] = { "Iphone", "Tutorials", "Gallery", "Android",

 "item 1", "item 2", "item3", "item 4", "item 1", "item 2", "item3", "item 4","item 1",       "item 2", "item3", "item 4"};

 EditText inputSearch;
 ArrayAdapter<String> adapter;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 inputSearch = (EditText) findViewById(R.id.inputSearch);
 list1 = (ListView) findViewById(R.id.listView01);
 adapter =new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array);
  list1.setAdapter(adapter);
  inputSearch.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}

@Override
 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
    int arg3) {
// TODO Auto-generated method stub

}

 @Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
list1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
 Intent myIntent = new Intent(MainActivity.this,WebViewActivity.class);
myIntent.putExtra("key",position);
startActivity(myIntent);
}
 });
}
}

A: Put below code in you string.xml
<string-array name="myArray">
   <item >Iphone</item>
   <item >Tutorials</item>
   <item >Gallery</item>
   <item >Android</item>
   <item >item 1</item>
</string-array>

Then getResources().getStringArray(R.array.myArray) will return those values as an array of strings. So in your main activity file
private ListView list1;
private String array[] = getResources().getStringArray(R.array.myArray);
EditText inputSearch;
ArrayAdapter<String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    inputSearch = (EditText) findViewById(R.id.inputSearch);
    list1 = (ListView) findViewById(R.id.listView01);
    adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array);
    list1.setAdapter(adapter);
}

A: To store your array in xml, you can do this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="myArray">
        <item>Iphone</item>
        <item>Tutorials</item>
        <item>Gallery</item>
        <item>Android</item>
    </string-array>
</resources>

Then in your code, you can access it:
Resources res = getResources();
String[] myArray = res.getStringArray(R.array.myArray);

Check here: http://developer.android.com/guide/topics/resources/string-resource.html#StringArray

A: In your strings.xml

    Iphone
    Tutorials
    Gallery
    Android

Add more items if you want.
In your code:
package com.Example.myapk;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {

    private ListView list1;

    EditText inputSearch;
    **ArrayAdapter<CharSequence> adapter;**

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        list1 = (ListView) findViewById(R.id.listView01);
        **adapter = ArrayAdapter.createFromResource(this,               R.array.menu, android.R.layout.simple_list_item_1);**
        list1.setAdapter(adapter);
        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                    int arg3) {
                // When user changed the Text
                MainActivity.this.adapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        });
        list1.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Intent myIntent = new Intent(MainActivity.this,
                        WebViewActivity.class);
                myIntent.putExtra("key", position);
                startActivity(myIntent);
            }
        });
    }
}


text:
Q: Find argmax $\frac{1}{2b}(\frac{x}{Na})^{\frac{N-1}{2}}e^{-\frac{1}{2b}(x+Na)}\frac{1}{\sqrt{2\pi(N-1)}}(\frac{\frac{e}{b}\sqrt{Nax}}{2(N-1)})^{N-1}$ I want to find an expression for:
$$ (1) \quad \underset{x}{argmax} \Big \{ \frac{1}{2b} \Big(\frac{x}{Na}\Big)^{\frac{N-1}{2}} e^{- \frac{1}{2b} (x+Na)} I_{N-1}\Big( \frac{\sqrt{Nax}}{b} \Big) \Big \} $$
Where $a,b,x \in \mathbb{R_{++}}$, $N \in \mathbb{N}$, and $I_{N-1}(\cdot)$ is the modified Bessel function of the first kind of order $N-1$.
Since this function is concave in $x$, all I need to do is take the partial derivative w.r.t $x$, set it equal to zero, and solve for $x$. Unfortunately, this seems like a pretty intractable problem. Try computing the $x$ partial in Wolfram to see what I mean.
So, I am going to approximate the answer instead. I know from NIST that for large orders:
$$I_{N-1}(z) \sim \frac{1}{\sqrt{2 \pi (N-1)}} \Big( \frac{e z}{2 (N-1)} \Big)^{N-1}$$
So then I have:
$$ (2) \quad \underset{x}{argmax} \Big \{ \frac{1}{2b} \Big(\frac{x}{Na}\Big)^{\frac{N-1}{2}} e^{- \frac{1}{2b} (x+Na)} \frac{1}{\sqrt{2 \pi (N-1)}} \Big( \frac{\frac{e}{b} \sqrt{Nax} }{2 (N-1)} \Big)^{N-1} \Big \} $$
This problem is easy. After taking the logarithm, expanding terms, taking the derivative, and setting it to zero, I get:
$$ x^{\ast} = 2b (N-1) $$
This is exact for (2), but nowhere near the truth for (1), especially as $N$ gets large and $a,b \approx 1$. This can be checked numerically. I think this is because the NIST expansion doesn't account for the argument growing as well.
Questions:

*

*How can I solve (1) analytically? Can you solve it exactly via the derivative?

*Is there an expansion, similar to the one used in (2), for when both the order and argument of the Bessel function are growing?

*Any other ideas on how I can approach this problem? Maybe approximate the log of the Bessel function directly?

Thanks!

A: We simplify slightly the expression by writing
\begin{align}
&\frac{1}{2b} \left(\frac{x}{Na}\right)^{\frac{N-1}{2}} e^{- \frac{1}{2b} (x+Na)} I_{N-1}\left( \frac{\sqrt{Nax}}{b}  \right)=\frac{1}{2b}\left( Na \right)^{\frac{1-N}{2}}e^{-\frac{Na}{2b}}f(x)\\
&f(x)=x^{\frac{N-1}{2}}e^{-\frac{x}{2b}} I_{N-1}\left( \frac{\sqrt{Nax}}{b}  \right)
\end{align}
Then, we want to obtain the solutions of $f'(x)=0$. The derivative reads
\begin{equation}
f'(x)=\frac{N-1}{2}\frac{f(x)}{x}-\frac{1}{2b}f(x)+\frac{\sqrt{Na}}{2b\sqrt{x}}\frac{I'_{N-1}\left( \frac{\sqrt{Nax}}{b}  \right)}{I_{N-1}\left( \frac{\sqrt{Nax}}{b}  \right)}f(x)
\end{equation}
The equation to solve is thus
\begin{equation}
\frac{N-1}{x}-\frac{1}{b}+\frac{\sqrt{Na}}{b\sqrt{x}}\frac{I'_{N-1}\left( \frac{\sqrt{Nax}}{b}  \right)}{I_{N-1}\left( \frac{\sqrt{Nax}}{b}  \right)}=0
\end{equation}
When both the order and the argument are large, a uniform asymptotic expansion can be used for $I_{N-1}$ and $I_{N-1}$:
\begin{align}
I_{N-1}\left((N-1) z\right)&\sim\frac{e^{(N-1)\eta}}{(2\pi(N-1))^{\frac{1}{2}}(1+z^{2%
})^{\frac{1}{4}}}\sum_{k=0}^{\infty}\frac{U_{k}(p)}{(N-1)^{k}}\\
I_{N-1}'\left((N-1) z\right)&\sim\frac{(1+z^{2})^{\frac{1}{4}}e^{(N-1)\eta}}{(2\pi%
(N-1))^{\frac{1}{2}}z}\sum_{k=0}^{\infty}\frac{V_{k}(p)}{(N-1)^{k}}
\end{align}
where
\begin{equation}
\eta=(1+z^{2})^{\frac{1}{2}}+\ln\frac{z}{1+(1+z^{2})^{\frac{1}{2}}}
\end{equation}
Here, we choose
\begin{equation}
z=\frac{\sqrt{Nax}}{b(N-1)}
\end{equation}
Keeping the term $k=0$ only, we find (with $U_0(p)=V_0(p)=1$)
\begin{equation}
\frac{I'_{N-1}\left( \frac{\sqrt{Nax}}{b}  \right)}{I_{N-1}\left( \frac{\sqrt{Nax}}{b}  \right)}=\frac{\sqrt{1+z^2}}{z}
\end{equation}
The equation to be solved becomes
\begin{equation}
\frac{N-1}{x}-\frac{1}{b}+\frac{\sqrt{Na}}{b\sqrt{x}}
\sqrt{1+\frac{b^2(N-1)^2}{Nax}}=0
\end{equation}
or
\begin{equation}
N-1-\frac{x}{b}+
\sqrt{\frac{Nax}{b^2}+(N-1)^2}=0
\end{equation}
which has a simple non-zero solution
\begin{equation}
x=Na+2(N-1)b
\end{equation}
which seems to be numerically correct. For $a=1,b=1,N=20$, the approximation gives $x=58$ while a numerical evaluation of the solution is $x=57.49$. For $a=1,b=1,N=50$ we find $148$ to be compared to $147.496$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL query - invalid column name and parameter - data.SE Not a programmer but using data.stackexchange.com. I'm querying the public SE data explorer and the column names that I'm specifying are invalid. Also, how do I specify Count (Posts) and Count (Votes)?
Is anyone who queried data.se and knows the db schema able to help me correct this code?
Select Count (u.Id)
From Users u
Left Join Posts p on u.Id = p.OwnerUserId
Left join SuggestedEdits e on u.Id = e.OwnerUserId
left join Votes v on u.Id = v.UserId
WHERE ((u.CreationDate BETWEEN 'qwerty' AND 'qwerty')
AND (p.CreationDate BETWEEN 'qwerty' AND 'qwerty')
AND (p.ClosedDate is null)
OR (e.CreationDate BETWEEN 'qwerty' AND 'qwerty'))
AND Count (Posts) = x
OR Count (Votes) = y
Group by u.CreationDate, p.OwnerUserId, UserTypeId, u.DisplayName, p.CreationDate

A: Did you try the Compose Query option found here. If you click that link it shows you the database schema on the right-hand side in the sidebar.
Note that the sidebar can be hidden, just click the link to show it again. Is that what you need?
EDIT
I am still not really sure what you are trying to do exactly.  If I were in your position I would start off by running some simple queries of each individual table first.  This way you can see what data is stored there.
Run this query and check out the results:
SELECT *
FROM Users
WHERE CreationDate BETWEEN '2012-06-01 08:00:00' AND '2012-06-02 09:00:00'

Run this query and check out the results:
SELECT *
FROM Posts
WHERE CreationDate BETWEEN '2012-06-01 08:00:00' AND '2012-06-02 08:10:00'

Run this query and check out the results:
SELECT *
FROM Votes
WHERE CreationDate BETWEEN '2012-06-01 08:00:00' AND '2012-06-02 08:10:00'

I'm not sure why you have included the SuggestedEdits table in your join as it does not appear you are using that table anywhere else.  So leave it out.
Now after seeing what the data looks like you should be able to piece them together to find what you are after.  Which I still don't know?  Hopefully something like this will help get you started.  This query will return some results but I'm not sure it is what you are after.
SELECT Count(u.Id), Count(p.Id), Count(v.Id)
FROM Users u
LEFT JOIN Posts p on u.Id = p.OwnerUserId
LEFT JOIN Votes v on u.Id = v.UserId
WHERE u.CreationDate BETWEEN '2012-06-01 08:00:00' AND '2012-06-02 09:00:00'
GROUP BY u.CreationDate, p.OwnerUserId, v.VoteTypeId, u.DisplayName, p.CreationDate


text:
Q: (Trusty problem)When installing Ubuntu 14.04 with WUBI shows me a error! Here's a screenshot with the error message:

Sorry, I am Romanian . That's why is written in Romanian, but the problem has a bit of English.

A: This is not the recommended way to install Ubuntu.
Installing via Wubi is known for generating issues.
Create a properly working installation media.
Create sufficient free space for Ubuntu OS.
Write the Ubuntu ISO file to a DVD or USB.
Boot from this media and install Ubuntu.
Learn more : Ubuntu installation guide

A: I suggest you to install Ubuntu O.S. outside Windows O.S. Because, after launch of Ubuntu 12.04 and later version installation with wubi.exe is not working perfectly.


text:
Q: How to start using Jemmy 3? I would like to use Jemmy v3 for GUI testing but I can't find any manual or user guide or even an examples of using it. I've found documentation only for Jemmy v2 and it looks like the library was completely rewritten and redesigned.
In Jemmy v2 I used:
new ClassReference(...).startApplication()

How can a similiar invocation can be done with Jemmy v3?

A: That depends on what UI library you are using it for.
App execution logic may be and is different for different libraries: AWT, FX, SWT.
For JavaFX you would do it like this: AppExecutor.executeNoBlock(TestApp.class);


text:
Q: Resume to last view controller from background I've got an iOS application that requires the user to log in before using its features. It uses Bluetooth and location services in the background after logging in. The typical use of the application is:

*

*User logs in -> transition to 'lobby' page

*Selects 'begin logging data' -> transition to 'logging' page

*Bluetooth and Location services run in the background

*User locks screen and app runs in the background (this needs to last for 8-10 hours)

The way the app handles logins is via a session token which times out after 12 hours.
If I leave the application running overnight, however, upon resuming the application it starts up the log in view controller (a.k.a. the root view controller). I need the application to resume on the page it was closed on and can't seem to find any reference online as to how to do this.
I did find something about saving and resuming state but could get a definitive answer. Any help?

A: UIStateRestoration is the mechanism that Apple provides for your application to be archived when it is backgrounded.  Even if the app is eventually terminated by the operating system, UIStateRestoration provides APIs to restore the state of your application to where the user left.
Resources:
State Preservation Programming Guide

A: If you didn't define a background task, the app will be killed once it stays over 20 minutes in background
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html


text:
Q: Nginx: Add $host to log How can I (or why can't I) add the $host variable to my nginx configuration file to see what domain (or subdomain) a client is requesting?
Current Format:
log_format   main '$remote_addr - $remote_user [$time_local]  $status '
                  '"$host" "$request" $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

Current Output:
10.7.2.104 - - [17/Feb/2017:14:31:15 -0600] "GET /crazystairs HTTP/1.1" 404 2327 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"

Desired Ouput:
    10.7.2.104 - - [17/Feb/2017:14:31:15 -0600] "GET example.com/crazystairs HTTP/1.1" 404 2327 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"

Notice the host in front of the request

A: I found the problem.  You must declare main after setting the directory where the log will be saved for the main format to be used.
access_log  logs/crazystairs/portal/access.log main;


text:
Q: How to click on a button until an element appears on a page in selenium I have a page with a dynamic table that periodically updates with new data. What I am trying to do is to click on a button and reload the page let's say every 3 seconds until the element from that table appears.
I know the xpath of the element I want to appear, but I just can't make it work using the FluentWait. I tried configuring as seen in the code below, but when I'm calling the method it keeps clicking on the button extremly fast disregarding the pollingEvery configuration and without giving the page enough time to fully reload itself. Code can be checked out below.
What I am not sure about is the return statement. I don't fully grasp what should it be if I only need to click on a button until that element appears.
What am I missing?
public void clickButtonUntilElementIsDisplayed(WebElement elementToBeClicked, String xPathOfElementToBeDisplayed){
    FluentWait<WebDriver> wait = new FluentWait<>(getDriver());
    wait.pollingEvery(Duration.ofSeconds(5));
    wait.withTimeout(Duration.ofSeconds(200));
    wait.ignoring(NoSuchElementException.class);
    Function<WebDriver,WebElement> clickUntilAppearance = webDriver -> {
        while(webDriver.findElements(By.xpath(xPathOfElementToBeDisplayed)).isEmpty())
            click(elementToBeClicked);

        return webDriver.findElement(By.xpath(xPathOfElementToBeDisplayed));
    };
    wait.until(clickUntilAppearance);
}

The class in which this method can be found extends Page

A: The return type of the Functional Interface need to be changed. There are 2 cases in which the functional interface will keep looping.

*

*Value returned is null.

*It threw an Exception mentioned as part of ignoring

Don't use while. Use if condition. For every pollingEvery this Functional Interface would get executed.
Function<WebDriver,WebElement> clickUntilAppearance = webDriver -> {
    List<WebElement> tableElements = webDriver.findElements(By.xpath(xPathOfElementToBeDisplayed));
    if(tableElements.isEmpty()) {
        click(elementToBeClicked);
        return null;
    } else {
        return tableElements.get(0);
    }
};

A: WebDriverWait w = new WebDriverWait(driver, 5);// 5seconds
w.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("element_location")));


text:
Q: Spring Security 3 with a login form for some URLs and an error page for others I'm using Spring Security 3 to protect access to a Spring-based Java Web application.  The security mechanism is all configured through a standard Spring Security bean definition file, using the "security" schema.   By default the user can access any URL and those that require a login are listed in the "http" element of the Spring configuration file.  The system is configured so that a user who has not performed a login will be redirected to a login form before they can access such a URL.
The problem that I have is that certain URLs in the system are intended for programmatic access and return XML rather than HTML.  For such URLs I need to be able to return a "user not logged in" XML instead of forcing a redirect to a login form.  How can I reconfigure my "http" element (and its associated elements in the configuration file) to allow me to have one set of controlled URLs that will redirect to a login form when the user isn't logged in and another set that will return an error?
Cheers, Adam.

A: Maybe an authentication filter helps you. Inside the doFilter() method of Spring's AbstractAuthenticationProcessingFilter you could check whether a XML file is requested. If yes, you interrupt the chain and return an error XML file if there's no active user session. See here for more details:
http://mark.koli.ch/2010/07/spring-3-and-spring-security-setting-your-own-custom-j-spring-security-check-filter-processes-url.html


text:
Q: How do I use a Canvas texture on a 3D polygon face that is not a rectangle I have a mesh with plane geometry that I texture with a 2D canvas element. This is working perfectly.
var landTexture = new THREE.Texture(land.canvas);  // animated canvas element
var material = new THREE.MeshLambertMaterial({map: landTexture});
var plane = new THREE.Mesh( new THREE.PlaneGeometry( this.land_width, this.land_height ), material );
landTexture.needsUpdate = true;
landObject.add(plane);

The 2D canvas has an animated pattern which I want to use as a texture on a pentagon instead of a plane. How do I go about texturing more complex polygons, e.g. a pentagon, with a 2D canvas texture?
Edit: how I generate the pentagon
var pentagon = new THREE.Mesh( new THREE.CircleGeometry(this.land_width, 5), material );

Screenshot of the animated texture on PlaneGeometry and the same texture on a CircleGeometry with 5 sides. Notice the "stretched" canvas texture on the pentagon, which is not what I want. It should fit proportionally.

A: I think that the UVs are already set so that code such as:
var grid = new THREE.ImageUtils.loadTexture( 'images/uvgrid01.jpg' );
var pentagon = new THREE.Mesh( new THREE.CircleGeometry(50, 5), new THREE.MeshBasicMaterial({map:grid}) );

when the grid is the image:

will produce an image like:

Is that what you're looking for? Then all that is left is to update the texture repeatedly, and each time this is done, set the flag to update the material.  I can go into more detail, but I would need to know how the canvas is being animated.


text:
Q: Как передать в функцию параметры из объекта? Всем привет, я только начинаю изучать ООП и столкнулся вот с такой проблемой.
<?php
class Boss {

public $name;
public $lvl;
public $hp;
public $damage;
public $revardPay;
public $revardExp;
public $db;

public function __construct($name, $lvl, $hp, $damage, $revardPay, $revardExp, $db) {

$this->name = $name;
$this->lvl = $lvl;
$this->hp = $hp;
$this->damage = $damage;
$this->revardPay = $revardPay;
$this->revardExp = $revardExp;
}

public function EngineBoss ($name, $lvl, $hp, $damage, $revardPay, $revardExp, $db){

$LS = new LoginSystem();
$LS->init();

$detailsPay = $LS->getUser('pay'); // Деньги
$detailsExP = $LS->getUser('expirience'); // Опыт
$detailsManna = $LS->getUser('manna'); // Энергия
$detailsPower = $LS->getUser('power'); // Сила
$detailsSutenerHP = $LS->getUser($db); // Здоровье босса
$detailsLvL = $LS->getUser('lvl'); // Уровень
$detailsUmenieGold = $LS->getUser('umenieGold'); // Прибавка к баксам
$detailsUmenieExp = $LS->getUser('umenieExp'); // Прибавка к опыту
$detailsUmenieENG = $LS->getUser('umenieENG'); // Прибавка к энегрии

$pay     = $detailsPay;        // Деньги
$exp     = $detailsExP;        // Опыт
$power   = $detailsPower;      // Сила
$bossHP  = $detailsSutenerHP;  // Здоровье босса
$manna   = $detailsManna;      // Манна
$lvl     = $detailsLvL;        // Уровень
$prem    = $detailsUmenieGold; // Прибавка к баксам
$premExp = $detailsUmenieExp;  // Прибавка к опыту
$umENG   = $detailsUmenieENG;  // Прибавка к энергии

$mannaBoss = $damage;    // Цена энергии за удар
$sumEndPay = $revardPay; // Награда за победу, баксы
$sumEndExp = $revardExp; // Награда за победу, опыт
$endHP     = $hp;        // Возвращаем здоровье боссу после победы

return $mannaBoss;

}
}

 $gopnik = new Boss('Гопник', 15, 10000, 200, 10000, 4000, 'sutenerHp');

 echo $gopnik->EngineBoss(//сюда нужно как-то передать $gopnik);
?>

Что я делаю не так?

A: Так ва не надо ничего туда передавать. Во первых уберите все аргументы из метода EngineBoss, они задаются через конструктор класса при создании объекта. А во вторых зачем вам передавать объект в метод который и вызывает этот объект?


text:
Q: How to update surfaceview partially? I have a surfaceview in my activity. Initially some circles are drawn using
Canvas c = SurfaceView.getHolder().lockCanvas();

and
SurfaceView.getHolder().unlockCanvasAndPost(c);

Later on I want to draw on a very small part of the surfaceview. I do not want to redraw the whole surfaceview. Is it possible to update just the required part?

A: Use lockCanvas(Rect dirty) instead.  Pass in the area you want to redraw.
Note that dirty is an in-out parameter.  The Rect may be expanded to cover a larger area, and you need to set every pixel it covers.  So if (for example) SurfaceView no longer has access to the previous pixels, it'll expand Rect to cover the entire surface.
Because SurfaceView is double- or triple-buffered, the implementation will copy chunks of pixels from the previous buffer.  Since the Canvas you get from a SurfaceView is never hardware-accelerated, specifying a dirty rect is often a performance win.


text:
Q: Retain Caret (cursor) Position in a ContentEditable "div" after updating the child elements through javascript I'm having difficulties in retaining the caret position in a content editable div after I update it through javascript.
I have a div with a contenteditable attribute.

Let's say the user typed "Bacon is so good! I want more" I update the html inside the div where I wrapped certain words with a span. From the html above, it would turn into this:

   Bacon is so good! I want more!

I do this by updating the html using jQuery...
$('#form').html(...here I put the updated html...)

However after this, the caret (cursor) returns to the start of the div. I want to keep the caret in the same position as before I update the div in order for the user to continue typing without any hitch.
Currently, I have the following code:
I first save the caret position prior to updating the div.
if(window.getSelection) {
    window.savedRange = window.getSelection().getRangeAt(0);
} else if(document.selection) {
   window.savedRange = document.selection.createRange();
}

And then I try to return the caret position by
$('#form').get(0).focus();
if (window.savedRange != null) {
    if (window.getSelection) {

        var s = window.getSelection();

        if (s.rangeCount > 0)
            s.removeAllRanges();

        s.addRange(window.savedRange);
    } else if (document.createRange) {
        window.getSelection().addRange(window.savedRange);
    } else if (document.selection) {
        window.savedRange.select();
    }
}

I need to retain the caret because this should all happen while the user is typing. The code above didn't do anything. It still returns to the start of the div.


text:
Q: How to make a setInterval() stop using clearInterval() work? Well, I am trying to make a setInterval() to stop using clearInterval(), here is the code:

let submitBPMkeeper = document.getElementById("submitBPMkeeper");

function startStopBPMkeeper(sr) {
  let bpmKeepTrack = document.getElementById("bpmSet");
  var test1 = 0;
  var t = setInterval(bpmKTcounter, 60000 / bpmKeepTrack.value);

  function bpmKTcounter() {
    test1 += 1;
    document.getElementById("testInput").innerHTML = test1;
  }
  if (sr == "start") {
    submitBPMkeeper.innerHTML = "Stop";
  } else if (sr == "stop") {
    submitBPMkeeper.innerHTML = "Start";
    clearInterval(t);
  }
}

submitBPMkeeper.addEventListener("click", function() {
  if (submitBPMkeeper.innerHTML == "Start") {
    startStopBPMkeeper("start");
  } else if (submitBPMkeeper.innerHTML == "Stop") {
    startStopBPMkeeper("stop");
  }
});

Tempo Keepper:

  BPM:
  <input type="number" id="bpmSet" name="bpmSet" style="width:40px;" value="80">
  <button id="submitBPMkeeper">Start</button>

As you can see you can't stop the thing from counting up, I would really like it to stop when you press stop.

A: Just define the interval variable in the upper scope.
const submitBPMkeeper = document.getElementById("submitBPMkeeper");
const bpmKeepTrack = document.getElementById("bpmSet");

let interval = null;

function toggleBPMKeeper() {
  let test1 = 0;

  function bpmKTcounter() {
    test1 += 1;
    document.getElementById("testInput").innerHTML = test1;
  }

  if (interval) {
    clearInterval(interval);
    interval = null;
    submitBPMkeeper.innerHTML = "Start";
  } else {
    interval = setInterval(bpmKTcounter, 60000 / bpmKeepTrack.value)
    submitBPMkeeper.innerHTML = "Stop";
  }
}

submitBPMkeeper.onclick = toggleBPMKeeper;

A: Thanks to Teemu's comment, I have fixed my problem:

let submitBPMkeeper = document.getElementById("submitBPMkeeper");
var t;

function startStopBPMkeeper(sr) {
  let bpmKeepTrack = document.getElementById("bpmSet");
  var test1 = 0;

  function bpmKTcounter() {
    test1 += 1;
    document.getElementById("testInput").innerHTML = test1;
  }
  if (sr == "start") {
    submitBPMkeeper.innerHTML = "Stop";
    t = setInterval(bpmKTcounter, 60000 / bpmKeepTrack.value);
  } else if (sr == "stop") {
    submitBPMkeeper.innerHTML = "Start";
    clearInterval(t);
  }
}

submitBPMkeeper.addEventListener("click", function() {
  if (submitBPMkeeper.innerHTML == "Start") {
    startStopBPMkeeper("start");
  } else if (submitBPMkeeper.innerHTML == "Stop") {
    startStopBPMkeeper("stop");
  }
});

Tempo Keepper:

  BPM:
  <input type="number" id="bpmSet" name="bpmSet" style="width:40px;" value="80">
  <button id="submitBPMkeeper">Start</button>

By creating the interval in the same if block that I set the button text to "Stop", and pull the t declaration outside of the function, I had fixed it so that it works.


text:
Q: Rails gem for Twitter Streaming API I was wondering if there is a gem for using the Twitter Streaming API (https://dev.twitter.com/docs/streaming-api)?
Thanks
I found this gem (https://github.com/jnunemaker/twitter) which looks really good, but does not support the streaming api, does it?

A: I have done this in the past using a combination of the OAuth gem and EventMachine.
require 'eventmachine'
require 'em-http'
require 'json'
require 'oauth'
require 'oauth/client/em_http'

# Edit in your details.
CONSUMER_KEY = your_key
CONSUMER_SECRET = your_secret
ACCESS_TOKEN = your_token
ACCESS_TOKEN_SECRET = your_token_secret

def twitter_oauth_consumer
  @twitter_oauth_consumer ||= OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, :site => "http://twitter.com")
end

def twitter_oauth_access_token
  @twitter_oauth_access_token ||= OAuth::AccessToken.new(twitter_oauth_consumer, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
end

EventMachine.run do
          toFollow=[twitter_id1, twitter_id2]
         http = EventMachine::HttpRequest.new('http://stream.twitter.com/1/statuses/filter.json'
).post(:body=>{"follow"=>toFollow.join(",")},
            :head => {"Content-Type" => "application/x-www-form-urlencoded"},
            :timeout => -1) do |client|
            twitter_oauth_consumer.sign!(client, twitter_oauth_access_token)
        end

        buffer = ""

        http.stream do |chunk|
            buffer += chunk
            while line = buffer.slice!(/.+\r?\n/)
                puts "handling a new event:"+line
            end
        end
        http.errback { puts "Error" }
        http.disconnect { puts "Lost Connection" }

 end

EDIT
I modified my code based on this blog post.

A: You can use this one : Tweetstream which sits on top of em-twitter


text:
Q: Creating a userdefined datatype giving problems I have created a datatype with two fields, time and measurement. I create an array of these datatypes. When i then attempt to assign a value to one of the fields of array[0] I get a null pointer exception. can anyone tell me what is wrong?
Public class MeasurementPoint{

private int time;
private double  measurement;

public MeasurementPoint(){
this.time =0;
this.measurement =0;}}

public void setMeausurement(double value){
this.measurement = value;}
public double getMeasurement (){
return this.measurement;}

public void setTime(int value){
this.time = value;}
public int getMeasurement (){
return this.time;}
}

The code that I use to create the Array is below
MeasurementPoint [] controlValues = new MeasurementPoint [points];
System.out.println(controlValues.length(); // this gives me 16 so I know the array is created

controlValues[0].setMeasurement(aCtivity);// this is where I get the exception.

A: You initialized your array but you never initialized your Array Elements, thus you get NullPointerException when you try to acess the zero'th index of your array as yourarray[0] returns null and you try to call setMe...() on null.. you have to actually initialize your array elements.
MeasurementPoint [] controlValues = new MeasurementPoint [points];
controlValues[0] = new Measurementpoint(val1,val2);


text:
Q: Is it allowed to place a capacitor between the LISN and the DUT using CISPR25 spec? I am very new to the EMC world (co worker quit Friday and now its my problem) I was asked by my supervisor to check the CISPR25 spec to see if it is allowed to put a 1000 uf cap between HV+ and HV- between the LISN and the DUT. I have the CISPR25 (2016 version) spec and I have spent the last hour searching through it for the answer but so far I have found nothing that says if it is allowed or not.
We are concerned with CE420 and RE310 testing specifically.
I am hoping someone with a lot more experience then me can point me in the right direction.
I really appreciate any help you can provide.

A: The test using a LISN uses high inductance coils on the AC input in order to simulate long transmission lines with a more balanced impedance for Line and Neutral at the RF range of interest.
The purpose is to measure the conducted emissions to the grid without load effects. Adding a cap would cheat this measurement for testing the DUT.
This is the job for the DUT using  one or two CM chokes with a Pi filter cap to earth to suppress common and differential mode conducted noise in both directions.


text:
Q: An algorithm to calculate the square numbers for the middle four squares on a game board? I am creating a program that creates a console version of othello or reversi on python 3.3. I am in the process of creating the board which requires the user to input an EVEN row number between 4-16 and an EVEN column number between 4-16. How can I make a function or algorithm that determines the four square numbers on the user defined grid that places the initial four pieces in the middle  the board? Thanks!

A: Supposing the numbers of rows and columns are the values of rows and cols, the row numbers to use are rows/2-1 and  rows/2.  (Eg, if rows==12 the values are 5 and 6.)  Similarly, the column  numbers to use are cols/2-1 and  cols/2.
Note, if the board is represented as a linear array, and if cells of a row are stored adjacently, you can say lr =(rows+1)*cols//2, and initialize cells 'lr', lr-1, lr-cols, and lr-cols-1 as the center cells.  This is equivalent to the formulas above.  For example:
for rows in (4,6,8):
    for cols in (4,6,8):
        lr = (rows+1)*cols//2
        r = rows//2
        c = cols//2
        print rows, cols, ':\t', r,c, '\t', lr-cols-1, '\t', lr-cols, '\t', lr-1, '\t', lr, '\t', r*cols+c

produces
4 4 :   2 2     5   6   9   10  10
4 6 :   2 3     8   9   14  15  15
4 8 :   2 4     11  12  19  20  20
6 4 :   3 2     9   10  13  14  14
6 6 :   3 3     14  15  20  21  21
6 8 :   3 4     19  20  27  28  28
8 4 :   4 2     13  14  17  18  18
8 6 :   4 3     20  21  26  27  27
8 8 :   4 4     27  28  35  36  36

That is, the subscripts for the (4,6) case are  (8,     9,  14,     15)   and for the (6,4) case are  (9,   10,     13,     14).
For even integers, 2 is an exact divisor, so I think the result with / will be the same in both Python 2 (where integer division truncates) and  Python 3 (where it doesn't).  Or you can use the // operator to be sure of  truncating division.
Note, you can test that rows and cols are even by an expression like (rows|cols)&1, which is 1 if either is odd, else is 0.


text:
Q: GAE: API serving not allowed for this application I am attempting to follow the tutorial at: http://www.youtube.com/watch?v=v9TG7OzsZqQ
My Cloud Endpoint REST API works well on my local development machine, but when I deploy to App Engine, I receive errors in my Admin Log that "API serving not allowed for this application".
Is this a paid feature that I must enable billing to receive? If not, is there documentation that explains this issue and how to fix this error?

A: To use Endpoints in production you need to be accepted into the trusted tester program. You can apply here. Mention this Stack Overflow post in your request and I'll see if I can expedite approval.


text:
Q: How can I make part of regex optional? Suppose I have the following regex that matches a string with a semicolon at the end:
\".+\";

It will match any string except an empty one, like the one below:
"";

I tried using this:
\".+?\";

But that didn't work.
My question is, how can I make the .+ part of the, optional, so the user doesn't have to put any characters in the string?

A: To make the .+ optional, you could do:
\"(?:.+)?\";

(?:..) is called a non-capturing group. It only does the matching operation and it won't capture anything. Adding ? after the non-capturing group makes the whole non-capturing group optional.
Alternatively, you could do:
\".*?\";

.* would match any character zero or more times greedily. Adding ? after the * forces the regex engine to do a shortest possible match.

A: As an alternative:
\".*\";
Try it here: https://regex101.com/r/hbA01X/1


text:
Q: Order on Euclidean space In $1D$ case, $\mathbb{R}^1$ as a typical case of $1D$ Euclidean space is totally ordered. I was wondering if any $1D$ Euclidean space $E^1$ is ordered as well? What is it
For higher dimensional case, are both $\mathbb{R}^n$ and $E^n$ ordered? What are the orders?
Thanks and regards!

Update:
I meant for an order for an Euclidean space:
that can induce or be compatible with the topology of the Euclidean space;
or that is defined in their definition, for example, the order of $\mathbb{R}^1$ is the one defined in one of $\mathbb{R}^1$'s definition as an ordered field with supreme property;
or that is used by default or most commonly.

A: I think the OP is asking whether, for $n > 1$, the topology on $\mathbb{R}^n$ is an order topology.
The answer is no.  Here is one simple way to see this: recall that a point $x$ in a topological space $X$ is a cut-point if $X \setminus x$ is disconnected.  For $n > 1$, $\mathbb{R}^n$ has no cut-points.  However, for any order topology, all but at most two points are cut-points, namely the points corresponding to the largest and smallest elements of the order, if any.  [To be clear, these points may still be cut points, as for instance with $\mathbb{Q} \cap [0,1]$.] Otherwise $(-\infty,x)$, $(x,\infty)$ gives a separation of $X$.  Since $\mathbb{R}^n$ has more than two points (!), for $n > 1$ the Euclidean topology is not an order topology.

A: If you are meaning a locally Euclidean whose topology is the one given by a linear order then $S^1$ is a counter-example.


text:
Q: How to use ruby on rails to construct a scaffold that also contains a different scaffold that can be added to it multiple times? I'm new to ruby on rails and in the efforts of "not repeating myself" in my code, I am trying to create a scaffold that contains one or more (decided by user) of a different scaffold.  But I am lost and Im not sure that it can be done.
Example:
1. There is an "article" scaffold that contains "sections" along with standard information (title, date of article, main image, main topics, etc)
2. The "article" type can has_many "sections".  Each section contains an order reference, header text and body text of the section.  But the sections are small.
3. In this example, the article will be displayed with it's overview text AND each section that is assigned to it.
I am trying to construct this through ruby but do not know how to architect it.  What is the best practice?  Creating an article that has many sections built into it (some not used) would be a waste of memory for the article.  Creating the "section" data point would allow me to easily create sections, but they would not be visibly connected and the editor would have to do a lot of work to make sure that it makes sense.
The best idea I had, which ruby does not seem to support, is the create an "article" type that has as many "sections" as the editor see's fit.  Theoretically this would allow the editor to create a new article and while filling in the article information, be able to write the individual sections one at a time, with the ability to add additional sections on the same screen.  But again I am new and not sure if that is even possible...
Thanks

A: Copied from my comment:

This can be done but not as a "scaffold" which is a rails generator for quickly building a controller, model and views in 1 shot. What you are looking for is a rendered partial. Take a look at nested_form Or cocoon gems to get an idea of how to implement these dynamically.


text:
Q: Scrapy: why use pipelines? I have a working crawler in Scrapy+Splash. It launchs a spider on many pages. Each page contains a list of links. For each page the spider download the page then, some of the pages linked from that(not recursively).  All the pages are saved on the file system. The system works flawlessy. At the moment I'm refactoring it to add some DB interaction.
I'm not using items, nor Item Pipelines.
What are the benefits of using them?
Adding some info:
The purpose of my crawler is to download entire pages (in html, png, or converted to txt using a library). As soon as the spider has the response to save, it passes it to a library that encapsulate all the io ops(File system and DB). So in this way, it is simpler than use items(with boilerplate for conversion) and pipelines.
So where is my doubt?
I don't know the way scrapy works internally well enough. The way the crawler is implemented the io ops are executed into the thread of the spider. So each spider takes longer to execute. As opposite if I move the io ops into the pipeline, maybe(?) scrapy can schedule its jobs better, executing them separately from the crawling job. Will there be any real performance difference?

A: In my opinion, using pipelines is just following the separation of concerns principle. Your spider can do many things, but it's core function is to extract information from web pages. The rest can (and possibly should) be refactored into a pipeline or an extension.
It might not be such an issue if you have one spider for one web site. But imagine you have a Scrapy project with hundreds of spiders for semantically similar web sites and you want to apply the same logic for each item -- take a page snapshot, check for duplicates, store in database etc. And now imagine the maintenance hell if you had all the logic in each of the spiders and had to change that logic.


text:
Q: How to Get Null in a mySQL Result when a Database Row Is Blank I start off with a query like this:
$query_price = "SELECT price_id, dt FROM lh_dates WHERE (dt BETWEEN '$firstdate' AND '$lastdate') AND hid = '$hid'";

Then manipulate the result like this:
$i = 0;
$price_id_list = array();
while ($row_price = mysql_fetch_assoc($price)) {
$price_id_list[$i] = $row_price['price_id'];
$date_list[$i] = $row_price['dt'];
$i++;
}

I later use $i again to construct a table with date columns. The problem I have is that some dates in the range $firstdate to $lastdate may not exist in the lh_dates table. This reduces the number of iterations of $i and messes up the resulting table.
Is there any way that I can get a NULL or zero or nothing result in the query when the date doesn't exist in the database table?
UPDATE
Having looked at the similar questions, I realise that I need to create an array from $query_price and then loop through the array for each date in the date range and add in any missing dates. So I've got to this point:
$firstdate = date('Y-m-d',$startdate);
$lastdate = date('Y-m-d',strtotime('+17 days',strtotime($firstdate)));
$query_price = "SELECT price_id, dt FROM lh_dates WHERE (dt BETWEEN '$firstdate' AND '$lastdate') AND hid = '$hid'";
$price = mysql_query($query_price, $MySQL) or die(mysql_error());
$alldates = array(); // Array of all rows within the date range
while ($row_price = mysql_fetch_assoc($price)) {
$alldates[]=$row_price;
}
//Now loop through the date range and fill in any empty dates in the array
$thisdate = $firstdate;
while (strtotime($thisdate) <= strtotime($lastdate)){
// WHAT GOES IN HERE?
$thisdate = date('Y-m-d',strtotime('+1 day',strtotime($thisdate)));
};

Now I am struggling to add the necessary code to fill in the missing dates.

A: $price_id_list = array();
  while ($row_price = mysql_fetch_assoc($price)) {
  $price_id_list[$row_price['price_id']] = $row_price['price_id'];
  $date_list[$row_price['price_id']] = $row_price['dt'];
}


text:
Q: Sprite Kit Physics - Wrong behaviour on collision I'm working a on retro arcade game in Sprite Kit. I'm new to this framework so I discover new things every minute but having a hard time to solve this issue i've tried to solve for the past hours.
First a screendump of the game and the physics bodies outlined by red.
http://i.imgur.com/KcbMVn4.png?1
When you hit the boxing glove button the big guy performs a punch by this method
-(void)performPunch {
SKTexture *punch1 = [SKTexture textureWithImageNamed:@"punch1"];
SKTexture *punch2 = [SKTexture textureWithImageNamed:@"punch2"];
SKTexture *punch3 = [SKTexture textureWithImageNamed:@"punch3"];
SKTexture *punch4 = [SKTexture textureWithImageNamed:@"punch4"];
SKTexture *punch5 = [SKTexture textureWithImageNamed:@"punch5"];

NSArray *animationObjects = [NSArray arrayWithObjects:punch1, punch2, punch3, punch4, punch5, nil];

SKAction *punch = [SKAction animateWithTextures:animationObjects timePerFrame:0.1];
[_tusk runAction:punch withKey:@"punch"];

}
My collision delegate looks like this
    - (void)didBeginContact:(SKPhysicsContact *)contact
{
if([_tusk actionForKey:@"punch"]) {
    NSLog(@"DAT HIT");
}
}

My issue here is the only way to make didBeginContact to log the hit is when the punch is being made upon the first contact with the other units. I know it's pretty easy to understand as the method name says "didBeginContact" but I need something between this and the other "didEndContact" as I want to be able to punch the guys when I stand next to them :)

A: If your Glove and (thing that gets punched) are both sprites with physics bodies, you must set their collision categories and your didBeginContact would look more like:
- (void)didBeginContact:(SKPhysicsContact *)contact{

SKPhysicsBody *firstBody, *secondBody;

if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
    firstBody = contact.bodyA;
    secondBody = contact.bodyB;
}
else
{
    firstBody = contact.bodyB;
    secondBody = contact.bodyA;
}
if (firstBody.categoryBitMask==gloveCategory && secondBody.categoryBitMask == monsterCategory)
{
   NSLog(@"DAT HIT");
}

}


text:
Q: Rest Easy Multipart Form data get files length for multiple files I have requirement to create a service using rest easy which will consule multipart form data and I'm sending multiple files while calling this service and @HeaderParam("Content-Length") int length is giving total size of all files in the request . Is there any way to find seperately the size of all files coming in the request.
For example : If I'm sending two files in the request with 20 kb and 50 kb size , at present @HeaderParam("Content-Length") int length is giving me 70000 . Can I get size of two files seperately .

A: I have done it by getting inputStream from MultipartFormDataInput  and then converted it into byte of array and hence lenght of array gives me the size of the file.


text:
Q: Removing duplicate names in FeaturePopups cluster tooltips and popups I am using FeaturePopups control to show tooltips and popups for clusters.
I have features connected (ends of road segments) with the same names.
Is it possible to remove them from tooltips and popups, so to have a list with unique names?

A: It is necessary to rewrite the html list popup preparation using event "beforepopupdisplayed" on option popupListOptions.eventListeners as:
var fpControl = new OpenLayers.Control.FeaturePopups({
  popupListOptions: {eventListeners: {
    "beforepopupdisplayed": function(e){
        var html = [],
            htmlAux = [];
        for (var i = 0, iLen = e.selection.length; i < iLen; i++) {
            var sel = e.selection[i],
                layerObj = sel.layerObj;
            for (var ii = 0, iiLen = sel.features.length; ii < iiLen; ii++) {
                // ******** FILTER DUPLUCATES HERE ******************
                if (true) {
                    htmlAux.push(layerObj.renderTemplate(
                        layerObj.templates.item, sel.features[ii])
                    );
                }
            }
        }
        html.push(layerObj.renderTemplate(
            layerObj.templates.list, {
                layer: sel.layer,
                count: sel.features.length,
                html: htmlAux.join('\n')
            }
        ));
        e.html = html.join('\n');
    }
  }},
  ...

For tooltips it is a bit more simple, not much.
WARNING: To use this trick you should update the control, today it has made a small adjustment.

A: You can remove popups with some basic coding.
var allpps = map.popups;
for(var i=0; i < allpps.length; i++){
   if(allpps[i].id.indexOf('blabla') > -1){ // You write what you want to put here.
      map.removePopup(map.popups[i]);
   };
};


text:
Q: Rotating a Polygon to its Minimal Height I need to rotate a concave polygon to minimize its height. I've thinking about finding a line which is the minimal diameter of that polygon, then rotate it so that line is parallel with Y axis.
My question is how to find such a line? Or, is there any other algorithm to rotate a polygon to so that its height is minimized?
Thanks in advance.

A:  ARRAY points := {P1, P2, ..., PN};

 points.delete(middle vertices of any collinear sequence of three points);

 REAL p_a := index of vertex with minimum y-coordinate;
 REAL p_b := index of vertex with maximum y-coordinate;

 REAL rotated_angle := 0;
 REAL min_width := INFINITY;

 VECTOR caliper_a(1,0);    // Caliper A points along the positive x-axis
 VECTOR caliper_b(-1,0);   // Caliper B points along the negative x-axis

 WHILE rotated_angle < PI

   // Determine the angle between each caliper and the next adjacent edge in the polygon
   VECTOR edge_a(points[p_a + 1].x - points[p_a].x, points[p_a + 1].y - points[p_a].y);
   VECTOR edge_b(points[p_b + 1].x - points[p_b].x, points[p_b + 1].y - points[p_b].y);
   REAL angle_a := angle(edge_a, caliper_a);
   REAL angle_b := angle(edge_b, caliper_b);
   REAL width := 0;

   // Rotate the calipers by the smaller of these angles
   caliper_a.rotate(min(angle_a, angle_b));
   caliper_b.rotate(min(angle_a, angle_b));

   IF angle_a < angle_b
     p_a++;  // This index should wrap around to the beginning of the array once it hits the end
     width = caliper_a.distance(points[p_b]);
   ELSE
     p_b++;  // This index should wrap around to the beginning of the array once it hits the end
     width = caliper_b.distance(points[p_a]);
   END IF

   rotated_angle = rotated_angle + min(angle_a, angle_b);

   IF (width < min_width)
     min_width = width;

   END IF
 END WHILE

 RETURN min_width;

See http://en.wikipedia.org/wiki/Rotating_calipers
Also check out: http://www.mathworks.com/matlabcentral/fileexchange/7844-geom2d/content/geom2d/polygons2d/minimumCaliperDiameter.m
Note: Both of these problems solve the convex case. To solve the concave case, you merely transform your inputs from conave to convex by doing the following:
1. Compute convex hull of your concave polygon.
2. Run algorithm above on convex polygon.
3. Once minimum height found, rotate.
4. Transform back to concave polygon.

The convex hull is very common in Python. You can use: http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.spatial.ConvexHull.html
If you aren't comfortable using this library, you can use this algorithm to convert your concave shape to convex: (this is not meant to be used, just really bad pseudocode for you to understand how convex hull is computed)
Traverse vertices of concave polygon in clockwise order
_prev = starting vertex of traversal
_middle = second vertex in traversal
FOR _next vertex in traversal:
  IF _prev -> _middle -> _next make right turn (i.e. concave part)
     Connect _prev and _next and set _middle = _next
  ELSE
     Shift _prev to _middle and _middle to _next.

In other words, you just remove concave parts :)


text:
Q: Creating a hexagonal star with webgl I have started learning to create more complex polygons with webgl recently however I am currently unable to create a hexagonal star polygon. I have tried using gl.TRIANGLES however it is creating unusual shapes which is not at all what I want to make.
By hexagonal star I mean a 2D hexagon with triangles comming outside each edge.

  var InitDemo = function(){
var canvas = document.getElementById('polygon-surface');
var gl = canvas.getContext('webgl');

//geometry
var vertices = [];
var indices = [];
vertices.push(0,0);
indices.push(0);

                      //start by creating the hexagon vertices
for(var i = 0; i <= 6; i++){
  var degree_offset = i * 60.0;
  var radian_offset = degree_offset * (Math.PI / 180.0);
  var x_pos = 0.5*Math.cos(radian_offset);
  var y_pos = 0.5*Math.sin(radian_offset);

  vertices.push(x_pos);
  vertices.push(y_pos);
  indices.push(i+1);
}

var index = 1;
var inner_poly_vert = indices.length -1;
                      //find the outer vertices needed for the star
for(var i = 1;i<inner_poly_vert;i++){
  var c_x = vertices[2*i+0];
  var c_y = vertices[2*i+1];
  var n_x = vertices[2*i+2];
  var n_y = vertices[2*i+3];
  var x_mp = (c_x + n_x);
  var y_mp = (c_y + n_y);
  vertices.push(x_mp,y_mp);
  indices.push(indices.length);
}
var temp = [];
                      //create the star from the hexagon and outer vertices
for(var i = 0;i<6;i++){
  temp.push(0,i+1,i+2);
  temp.push(i+1,i+8,i+2);
}

indices = temp;
console.log(indices);
console.log(vertices);

//create VBO
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

var indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);

//create shader
var vertShader = gl.createShader(gl.VERTEX_SHADER);
var vertSrc = 'attribute vec2 coordinates;'+
        'void main(){'+
        'gl_Position = vec4(coordinates,0.0,1.0);'+
        '}';
gl.shaderSource(vertShader, vertSrc);
gl.compileShader(vertShader);
gl.compileShader(vertShader);
if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) {
  console.error('ERROR compiling vertex shader!', gl.getShaderInfoLog(vertShader));
  return;
}

var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
var fragSrc = 'void main(){'+
        'gl_FragColor = vec4(0.0,0.7,0.9,1.0);'+
        '}';
gl.shaderSource(fragShader, fragSrc);
gl.compileShader(fragShader);
if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) {
  console.error('ERROR compiling fragment shader!', gl.getShaderInfoLog(fragShader));
  return;
}

var program = gl.createProgram();
gl.attachShader(program, vertShader);
gl.attachShader(program, fragShader);

gl.linkProgram(program);
gl.useProgram(program);

//association
var coord = gl.getAttribLocation(program, 'coordinates');
gl.vertexAttribPointer(coord, 2, gl.FLOAT, false, 2*Float32Array.BYTES_PER_ELEMENT, 0);
gl.enableVertexAttribArray(coord);

//draw
gl.clearColor(0.9, 0.2, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, vertices.length/2);// change back to /2 find out what draw arrays does

  }

InitDemo();
body{
  background-color: black;
}
<canvas id="polygon-surface" width="200px" height="200px"></canvas>

I think the problem has to do with my VBO and how I reference my vertices with the Element Array Buffer.

A: You need to call gl.drawElements to draw with indices
gl.drawElements(gl.TRIANGLES, temp.length, gl.UNSIGNED_SHORT, 0);

  var InitDemo = function(){
var canvas = document.getElementById('polygon-surface');
var gl = canvas.getContext('webgl');

//geometry
var vertices = [];
var indices = [];
vertices.push(0,0);
indices.push(0);

                      //start by creating the hexagon vertices
for(var i = 0; i <= 6; i++){
  var degree_offset = i * 60.0;
  var radian_offset = degree_offset * (Math.PI / 180.0);
  var x_pos = 0.5*Math.cos(radian_offset);
  var y_pos = 0.5*Math.sin(radian_offset);

  vertices.push(x_pos);
  vertices.push(y_pos);
  indices.push(i+1);
}

var index = 1;
var inner_poly_vert = indices.length -1;
                      //find the outer vertices needed for the star
for(var i = 1;i<inner_poly_vert;i++){
  var c_x = vertices[2*i+0];
  var c_y = vertices[2*i+1];
  var n_x = vertices[2*i+2];
  var n_y = vertices[2*i+3];
  var x_mp = (c_x + n_x);
  var y_mp = (c_y + n_y);
  vertices.push(x_mp,y_mp);
  indices.push(indices.length);
}
var temp = [];
                      //create the star from the hexagon and outer vertices
for(var i = 0;i<6;i++){
  temp.push(0,i+1,i+2);
  temp.push(i+1,i+8,i+2);
}

indices = temp;
console.log(indices);
console.log(vertices);

//create VBO
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

var indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);

//create shader
var vertShader = gl.createShader(gl.VERTEX_SHADER);
var vertSrc = 'attribute vec2 coordinates;'+
        'void main(){'+
        'gl_Position = vec4(coordinates,0.0,1.0);'+
        '}';
gl.shaderSource(vertShader, vertSrc);
gl.compileShader(vertShader);
gl.compileShader(vertShader);
if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) {
  console.error('ERROR compiling vertex shader!', gl.getShaderInfoLog(vertShader));
  return;
}

var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
var fragSrc = 'void main(){'+
        'gl_FragColor = vec4(0.0,0.7,0.9,1.0);'+
        '}';
gl.shaderSource(fragShader, fragSrc);
gl.compileShader(fragShader);
if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) {
  console.error('ERROR compiling fragment shader!', gl.getShaderInfoLog(fragShader));
  return;
}

var program = gl.createProgram();
gl.attachShader(program, vertShader);
gl.attachShader(program, fragShader);

gl.linkProgram(program);
gl.useProgram(program);

//association
var coord = gl.getAttribLocation(program, 'coordinates');
gl.vertexAttribPointer(coord, 2, gl.FLOAT, false, 2*Float32Array.BYTES_PER_ELEMENT, 0);
gl.enableVertexAttribArray(coord);

//draw
gl.clearColor(0.9, 0.2, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawElements(gl.TRIANGLES, temp.length, gl.UNSIGNED_SHORT, 0);// change back to /2 find out what draw arrays does

  }

InitDemo();
body{
  background-color: black;
}
<canvas id="polygon-surface" width="200px" height="200px"></canvas>


text:
Q: AngularJS - Shared state between controllers? I know there are other similar questions on how to pass data between Angular controllers.
What I wonder is how to deal with this in a view..
Lets say I have a UserController for login, registration etc.
And an AppController for the actual app functionallity .
The UserController would be fairly easy, its sort of standalone from the rest.
But what if the app needs to know about stuff from the user controller?
Lets say the app view needs to hide/show stuff depending on if the user is logged in or not.
Or it could be if the user is male or female etc.
Should the app model keep its own copy of the user model state?
e.g. appModel.isLoggedIn , appModel.gender etc ?
feels a bit redundant, but at the same time more testable.
So what is the correct way to do this?

A: To further specify the answer @GoloRoden gave, this is an example of how you can share state values across all controllers taking the service as a dependency.
App.factory('formState', formState);

function formState() {

    var state = {};

    var builder = "nope";
    var search = "nope";

    state.builder = function () {
        return builder;
    };

    state.search = function () {
        return search;
    };

    state.set = {
        'builder': function (val) {
            builder = val;
        },
        'search': function (val) {
            search = val;
        }
    };

    return {
        getStateManager: function () {
            return state;
        }
    };
}

App.controller('builderCtrl', builderCtrl);

builderCtrl.$inject = ['formState']
function builderCtrl(formState) {
    var stateManager = formState.getStateManager();

    activate();

    function activate() {
        console.log("setting val in builder");
        stateManager.set.search("yeah, builder!");

        console.log("reading search in builder: " + stateManager.search());
        console.log("reading builder in builder: " + stateManager.builder());
    }
}

App.controller('searchCtrl', searchCtrl);

searchCtrl.$inject = ['formState']
function searchCtrl(formState) {
    var stateManager = formState.getStateManager();

    activate();

    function activate() {
        console.log("setting val in search");
        stateManager.set.search("yeah, search!");

        console.log("reading search in search: " + stateManager.search());
        console.log("reading builder in search: " + stateManager.builder());
    }
}

A: Short answer
Create a service, see Creating Services for details.
Long answer
Services are - per se - application-wide singletons, hence they are perfect for keeping state across views, controllers & co.:
app.factory('myService', [ function () {
  'use strict';
  return {
    // Your service implementation goes here ...
  };
}]);

Once you have written and registered your service, you can require it in your controllers using AngularJS' dependency injection feature:
app.controller('myController', [ 'myService', '$scope',
  function (myService, $scope) {
  'use strict';
  // Your controller implementation goes here ...
}]);

Now, inside your controller you have the myService variable which contains the single instance of the service. There you can have a property isLoggedIn that represents whether your user is logged in or not.


text:
Q: Using celery to send tasks from component A to component B The technology I would like to use in this example is Celery for queueing and python for component implementation.
Imagine a simple project hat exists of 2 components. One is a web app that connects to an API and gathers data. Component 2 is a processor that can then process the data. When the web app has gotten a piece of data from the API it is supposed to send a task into a task queue including the just crawled data which is then consumed by the processor to process the Data.
Whether or not this is a sensible way to go about a task like this is debatable and not the point of my question.
My question is, the tasks to process things are defined within the processor since they state what processing function shall be executed and the definition of that function is obviously within the processor. Now that the web app doesn't have access to the task definition how does he communicate the task to the processor?
Do you have to hold a copy of the source code of the processor within the web app?
Do you make the processor a dependency of the web app?
What is the best practice approach to handle such a scenario?

A: What you are describing is probably one of the most common use-cases for Celery. Just look how many people are asking Django/Flask + Celery questions here on StackOverflow... If you are a Django user, there is an entire section in the Celery documentation describing how to do exactly what you want. Things should be similar with other frameworks.

Do you have to hold a copy of the source code of the processor within the web app?

As far as I know you do not have to (I do not use any web framework) but it could be that you do need to because of some deeper integration with Celery. If your web application knows the Celery task name, and its parameters, it can schedule it to run without actually having access to the Python code. This is accomplished using send_task(task_name, ...).

Do you make the processor a dependency of the web app?

As I wrote above there are several ways to use it. If you want tighter integration then yes. If you just want to run task and get result using the send_task() than your web application should only depend on Celery.

What is the best practice approach to handle such a scenario?

Follow the Django guide. I advise you to run Celery independently, run some tasks, just so you learn about basic principles how it distributes the work, etc.


text:
Q: Access denied when using Directory.Move() in impersonation with UserLogon with Interactive When I try to perform Directory.Move() I get error

System.IO.IOException  ... Access Denied

Steps to reproduce:

*

*Run Visual Studio 2013 at console with PsExec.exe -s -d -i which could assign system privilege to my program. (When running System.Security.Principal.WindowsIdentity.GetCurrent().Name gives NT AUTHORITY\\SYSTEM)

*LogonUser with LOGON32_LOGON_INTERACTIVE and invoke ImpersonateLoggedOnUser() - no error returned

*Directory.Move(myfolderAtProgramData,myfolderAtProgramData+"_")

*VS throws a System.IO.IOException - 'Access Denied'

If LogonUser with LOGON32_LOGON_NEW_CREDENTIALS then it works. Why??
Below are references for my implementation:

*

*What is the difference: LoadUserProfile -vs- RegOpenCurrentUser

*Impersonation to get user HKEY_CURRENT_USER does not work?

*Access CurrentUser Registry Key for Impersonated User - Compatibility with .NET 3.5

*https://social.msdn.microsoft.com/Forums/vstudio/en-US/fd531413-1ea9-4141-bba8-c1c5e9270001/access-currentuser-registry-key-for-impersonated-user-compatibility-with-net-35?forum=csharpgeneral
Environment:

Win10 Pro 64bit ,EN ,Visual Studio 2013 , .Net4.0 , c#
  A folder at ProgramData (allow modification only with administrator privilege)


text:
Q: Finding the Big O complexity for ascending sorting code I need help to check whether my ascending sorting code has correct time complexity measurement or not.
Here is my code
for (int i = 0; i < 4344; i++)
{
    for (int j = i + 1; j < 4344; j++)
    {
        if (array_dist[index_arr[i]] > array_dist[index_arr[j]])
        {
            x = index_arr[i];
            index_arr[i] = index_arr[j];
            index_arr[j] = x;
        }

    }
}

We have two nested loops so N^2 and if statement with 3 operations, so N^2 + 3 then we got O(N^2).
I am not sure if O(N^2) is the correct time complexity for my code. I want to know if the if statement could change my answer?


text:
Q: AngularJS, Rails and ui-router not showing template after switch from ngRoute Hi I am trying to switch over from ngRoute to ui-Router but after I made the switch, the templates are not loading anymore.
I added ui-Router in my application.html.erb:
<%= javascript_include_tag 'application' %>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>

This is the code in my app.js
var app = angular.module("alliance",['ui.router', 'ui.bootstrap']);

app.config(['$stateProvider','$urlRouterProvider',function($stateProvider,

$urlRouterProvider) {

  $stateProvider
    .state('dashboard', {
      url:'/',
      templateUrl: "<%= asset_path('pages/dashboard.html') %>",
      controller:   "DashboardController"
    });

  $urlRouterProvider.otherwise("dashboard");
}]);

Original ngRoute code that was working.
var app = angular.module("alliance",['ngRoute', 'ui.bootstrap']);

app.config(['$routeProvider',function($routeProvider) {
   $routeProvider
     .when('/', {
       templateUrl:  "<%= asset_path('pages/dashboard.html') %>",
       controller:   "DashboardController"
     })

It is now showing the default rails view.
I checked that the ui router script is loaded. Does order matter?
I have also played about with the state name, url but that didn't seem to be it.
Any help is appreciated. Thanks a lot in advance.
EDIT:
I changed the load order from application.js
//= require jquery
//= require jquery_ujs
//= require angular
//= require angular-ui-router
//= require angular-ui-bootstrap-tpls
//= require_tree .

and I changed the url in the config to /dashboard but it's still giving me the default rails view.

A: Order matters, you need to load ui-router after angular and before your app.
Also the $urlRouterProvider.otherwise("dashboard"); is wrong, your state is called dashboard but the url is /.
You need to define the url of dashboard as /dashboard and then $urlRouterProvider.otherwise("/dashboard");


text:
Q: How can I guarantee a pooled AKKA actor only sends and receives from it's own child actor? I have several actors in a pool.  I want each of these actors to create child actor.  The problem is that when I create the child actor and save the reference, I never know which child is going to get messages the pooled actor sends to it. The pool was created as a smallestMailBox pool.
In the constructor of the pooled actor I do:
documentReaderActor = this.getContext().actorOf(Props.create(DocumentReaderActor.class ));

This is it's child.
I do some pattern.asks and some tells, but they don't end up on the same child.
First I do a:
documentReaderActor.tell(startReading, getSelf());

later I do over and over:
     Future<Object> future = Patterns.ask(documentReaderActor, adSend,
                timeout);
     adReceive = (AkkaDocument) Await.result(future, timeout.duration());

(adReceive and adSend are a AkkaDocument class object)
When I am all done I send:
documentReaderActor.tell(documentDone, getSelf());

So I have 10 of these pooled actors each creating a child actor but the messages don't go to the same child each time.  How can I guarantee the pooled actor only talks to it's child?

A: The way Akka's SmallestMailBox router works is that it will redirect any message sent to its ActorRef to one of the routees based on the following rules in the order shown:

*

*pick any idle routee (not processing message) with empty mailbox

*pick any routee with empty mailbox

*pick routee with fewest pending messages in mailbox

*pick any remote routee, remote actors are consider lowest priority,
since their mailbox size is unknown

What this means from your perspective is that you can't guarantee that the response to one of your Asks will end up at the same actor that created it.
If you want to use a pool you may need to roll your own Custom Router.


text:
Q: Guitar Tab API? I was just curious if anyone has heard of any sort of API for guitar tabs?  The thought passed through my mind that it would be really neat if I could grab guitar tabs from the internet to bring into my C# app, but haven't been able to find anything.
Thanks,
Chris

A: You can use System.Net.WebRequest to read the repository of your choice.
You can also use System.ServiceModel.Syndication.SyndicationFeed to read RSS feeds.
EDIT: Try scraping http://www.mxtabs.net/guitar_tabs/ using WebRequest.
You can write code that sends requests to the pages of that (or any other) website and parses the responses to extract information.
However, you might want to get their permission first.  They might even offer you an API.

A: You should approach it from another angle.. Why isn't there a good data format to transfer guitar tab data? I mean, ASCII art is good but it is easily damaged, and it doesn't convery timing information well.
If you could come up with a format that could reach critical mass, that would be a good thing.

A: To scrape a web page, first figure out exactly which data you want to extract.
Visit the relevant pages with Fiddler running, and look at the HTTP requests and responses that you get.
You can then write C# code that requests the relevant page and reads through the response, line by line, looking for lines that you're interested in.
If the web page is XHTML compliant, you can also parse it using XDocument, but most web pages aren't.

A: http://www.911tabs.com/ seems to have a large selection, and they appear to all be a variant of ASCII-art, so it would be relatively easy to write an HTML- or text-scraping routine.  They don't appear to use a very standardized format, however, so this might be more work than I think.


text:
Q: Linkbutton Not working in Google chrome In the below code i have link button inside datagrid when i click linkbutton it is not opening a popup window in chrome whereas in IE and mozilla it is working fine.Pls help me to solve the issue.
 <asp:TemplateColumn HeaderText="From Quote" ItemStyle-Width="200px">
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkQuote" runat="server" CommandName="Quote" Text="Quote" />
                            </ItemTemplate>
                          </asp:TemplateColumn>

 if (e.CommandName.Equals("Quote"))
                {
  Label KK = (Label)dgPOD.Items[e.Item.ItemIndex].Cells[1].FindControl("TXT1");
                    Label lbl = (Label)dgPOD.Items[e.Item.ItemIndex].Cells[1].FindControl("LBL1");
                    str1 = KK.Text.ToString();
                    str2 = lbl .Text.ToString();

                    ScriptManager.RegisterStartupScript(this, GetType(), "ShowPopUp", "ShowPopUp()", true);
                }

A: Add this code. it will work fine.
      <!DOCTYPE html>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org
       /TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<meta http-equiv="X-UA-TextLayoutMetrics" content="natural" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>

If helpful then please vote it.

A: Try adding surrounding script-tags
ScriptManager.RegisterStartupScript(this, GetType(), "ShowPopUp", "<script type=\"text/javascript\">ShowPopUp();</" + "script>", true);

A: ClientScript.RegisterStartupScript(this.GetType(), "ShowPopUp", "ShowPopUp()", true);


text:
Q: How can I control a sequence of outputs via a single input? Ok, so I'm making a map which needs a level system.  By level system I mean:

*

*Push the button first time,output A lights up.

*Push the button second time,output B lights up.

*Push the button third time,output C lights up.

*And so on.

Essentially, each button press makes the next output in the sequence activate.

A: As far as I understand your question, you want the first button to light A up, the second to light B up but only if A is on, and the third to light C up but only if B is on.
Basically you need to make three T-flip flops. A flip-flop is basically a single on/off memory which is swapped every time you power the input.
ie if it's on and you power it, it goes off. If it's off and you power it, it goes on.
For the first output, A, you only need to use the button to power the flip flop and A will change.
For the second output, B, you need to build an AND gate (you can find various tutorials on this) which has two inputs. The first comes from the output from A, the second from the button, and the output goes to the flip flop which changes the state of B.
The third output, C, is the same as B but uses the third button and B's output instead of A's output.
This will allow you to light the outputs up in the order A->B->C, but will mean you need to turn the outputs off again using C->B->A. You could reverse this, but I won't over-complicate this answer with the method for that. You could, however, simply turn all 3 back off again by powering all three flip flops again manually with a 4th button.

A: You have three basic options as shown below:

First you have a hopper/dropper chain, next a piston and block ribbon, and finally, a T flip-flop counter and binary decoder.  There are other options, but these are the most straight forward and stick to generic principles that allow for easy expansion and, except for the counter, incredible flexibility.
Let's start with the hopper/dropper chain.

With a hopper/dropper chain, each hopper faces a dropper, and each dropper faces a hopper to form, well, a single continuous chain.  A single item is placed in one of the hoppers in the chain, and a comparator is used to determine if a hopper has the item, which forms the output.  Everything is powered from below with redstone torches, keeping the item in one of the hoppers, but when those torches are deactivated, the item flows to the next dropper.  When the power is restored, all of the droppers activate, pushing the item along to the next hopper.  Longer chains and single sided output can be achieved by filling a pair of hoppers opposite each other with a single item each.

The piston and block ribbon uses four pistons to push a set of blocks, called the ribbon, containing two blocks of redstone.  There's an alternative version that uses glass and a non-transparent block, and there are trade-offs between the two, but we'll stick with this version.  This selector is effectively limited to 15 outputs, which is the smallest of the three, but is also the easiest to implement as an unbroken line of redstone lamps, and may very well be the cheapest.  In this configuration, the horizontal (sticky) pistons push the two rows in opposing directions, followed by the vertical (sticky) pistons to fill the gap left by the previous operation.

Lastly, we have the T flip-flop with a binary decoder.  Knowing how to build one of these is important because it's the basis for all decoders and encoders, and you can build cool things like 7-segment displays with them.  However; for this application it doesn't really make sense for a few reasons.  First, it's the slowest of the bunch, having significant input lag, especially when needing more options.  Second, it's the largest of the bunch in terms of area or volume.  Third, it's the hardest to get right.  Forth, and probably most importantly, without some complex wiring, it only works with n=2m outputs, whereas the other designs work with an arbitrary number of outputs.


text:
Q: MYSQL - No se logra la exportación excel de una consulta hecha con UNION Por alguna razón que no entiendo, no puedo realizar la exportación de una consulta hecha con UNION.
Esta consulta es una que me dieron en esta pregunta: https://es.stackoverflow.com/a/483518/131662
Al momento de ejecutarla en PHPMYADMIN, funciona perfecto.
Al momento de exportarla a EXCEL, esto es lo que arroja.


text:
Q: SSIS with Sql Server 2005 express Can we use SSIS with SQL Server (2005) Express as database?

A: SQL Server Express editions don't come with SSIS package. Please check this http://www.microsoft.com/Sqlserver/2005/en/us/compare-features.aspx
One way to get around it is to build SSIS packages on Standard Edition and copy them. Here, this might be handy http://daron.yondem.com/PermaLink.aspx?guid=c44d040b-ed02-4330-a662-4cd9d6fb1bf3
cheers


text:
Q: Adjusting the mic sensitivity while recording audio in android I am developing an android application which records audio in PCM using the AudioRecord API. I want to adjust the mic sensitivity to low, medium and high as the user chooses it in the settings.
Is it possible to adjust the mic sensitivity? Your answers will be highly appreciated  :)

A: Not really. It's usually possible to get at least two different "sensitivities" (acoustic tunings used by the platform) implicitly by using different AudioSources.There should at least be one tuning for handset recording and one for far-field recording. On some devices you might also have different far-field tunings, e.g. one for recording audio a few decimeters away and one for recording audio a few meters away.
The problem is that you can't really know which AudioSource corresponds to which tuning, as there's no standard for it. CAMCORDER typically means far-field, and VOICE_RECOGNITION often means handset mode, but there's no guarantee for it. You should also keep in mind that vendors typically apply automatic gain control, noise reduction, etc that you as a user / app developer can't disable, in order to meet acoustic requirements for their products.
Your best bet would probably be to use a single AudioSource and then do attenuation of the signal in your app to simulate a lower mic sensitivity. You could do amplification as well, but that would be akin to using digital zoom in the camera app (it works, but doesn't look all that good because you're just scaling the existing data).


text:
Q: How to add item in List? How to add item in this list?
var cl = (from cls in obj.Classes
                   where cls.isDelete != true
                   select new
                   {
                       cls.ID,
                       cls.Name,
                   }).ToList();

A: To add an item to the list, you can construct a new instance of the anonymous type. The parameter names and types of the new item must exactly match the types in the list:
cl.Add(new { ID = 123, Name = "abc" });

However, this will not add a record to the database. In order to do that you'd need something like this:
obj.Classes.Add(new MyClass()
{
   Name = "abc"
});

db.SaveChanges();


text:
Q: WCF Service returning "bad" response - Client gets data different than what the server sent I'm getting a strange issue with my WCF Service.
I am able to submit a message, and return the result.  The issue I"m having is what the server shows as the response, the client gets a different version.
The client software cannot be changed for this to work. It's based on a WSDL contract, which is what the WCF services were created from.
Update:
It seems that all default NameSpaces we use in our XML are being overwritten by a new default one on the outbound data.
Service
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
 [WebServiceBindingAttribute(Name = "QUPA_AR101102_Binding", Namespace = "urn:hl7-org:v3")]
GetDemographicsResponse1 IQUPA_AR101102.HCIM_IN_GetDemographics(Message request)
        {
            HCIM.HIALServices.QUPA_AR101102_Service service = new HIALServices.QUPA_AR101102_Service();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(request.GetReaderAtBodyContents().ReadOuterXml());

            HCIM.HIALMessaging.GetDemographics gd = new HIALMessaging.GetDemographics(System.Web.HttpContext.Current);
            XmlNode gdr = gd.HIALRequest(doc);
        //These 2 lines produce the same data on the server, but the client sees this totally different.
        //HCIM.HL7v3.Objects.QUPA_AR101102.HCIM_IN_GetDemographicsResponse response = this.getMessageObject<HCIM.HL7v3.Objects.QUPA_AR101102.HCIM_IN_GetDemographicsResponse>(gdr.OuterXml, "urn:hl7-org:v3");
        HCIM_IN_GetDemographicsResponse1 r1 = new HCIM_IN_GetDemographicsResponse1(gd.wcfObjectResponse as HCIM.HL7v3.Objects.QUPA_AR101102.HCIM_IN_GetDemographicsResponse);
       //the above line is a serialized version of the XML - I just packaged it up to` test

        return r1;
    }

Contract
[ServiceContract(Namespace = "urn:hl7-org:v3")]
public interface IQUPA_AR101102
{
    [OperationContract(Name = "HCIM_IN_GetDemographics", Action = "urn:hl7-org:v3/QUPA_IN101101")]
    HCIM_IN_GetDemographicsResponse1 HCIM_IN_GetDemographics(Message request);

...
}

(The code is just mocking the functionality right now until I get the proper response.)
When I look at the XML that is generated on the server, or the object that is living on the server.
Sample of the XML on the server side it looks like this - I can serialize and deserialize it to and from the HCIM_IN_GetDemograhpics type without any issue or degrading of the data.
XML/Data from the server I am expecting (not getting)
<HCIM_IN_GetDemographicsResponse xmlns="urn:hl7-org:v3">
    <id root="2.16.840.1.113883.3.51.1.1.1" extension="404002d6-3978-413d-a49d-b11e240bbf26" />
    <creationTime value="20150204185920" />
    <versionCode code="V3PR1" />
    <interactionId root="2.16.840.1.113883.3.51.1.1.2" extension="HCIM_IN_GetDemographicsResponse" />
    <processingCode code="P" />
    <processingModeCode code="T" />
    <acceptAckCode code="NE" />
    <receiver typeCode="RCV">
...

When my client recieves this it comes out as something totally different.
Data I am receiving in XML
<HCIM_IN_GetDemographicsResponse xmlns="urn:hl7-org:v3" xmlns:a="http://schemas.datacontract.org/2004/07/HCIM.HL7v3.Objects.QUPA_AR101102" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <a:acceptAckCode>
        <a:nullFlavor>NI</a:nullFlavor>
        <a:nullFlavorSpecified>false</a:nullFlavorSpecified>
        <a:code>NE</a:code>
        <a:codeSystem i:nil="true" />
        <a:codeSystemName i:nil="true" />
        <a:codeSystemVersion i:nil="true" />
        <a:displayName i:nil="true" />
        <a:originalText i:nil="true" />
        <a:qualifier i:nil="true" />
        <a:translation i:nil="true" />
    </a:acceptAckCode>
    <a:creationTime>
        <a:nullFlavor>NI</a:nullFlavor>
        <a:nullFlavorSpecified>false</a:nullFlavorSpecified>
        <a:value>20150204185920</a:value>
    </a:creationTime>
    <a:id>
        <a:nullFlavor>NI</a:nullFlavor>
        <a:nullFlavorSpecified>false</a:nullFlavorSpecified>
        <a:assigningAuthorityName i:nil="true" />
        <a:displayable>false</a:displayable>
        <a:displayableSpecified>false</a:displayableSpecified>
        <a:extension>404002d6-3978-413d-a49d-b11e240bbf26</a:extension>
        <a:root>2.16.840.1.113883.3.51.1.1.1</a:root>
    </a:id>
    <a:interactionId>
        <a:nullFlavor>NI</a:nullFlavor>
        <a:nullFlavorSpecified>false</a:nullFlavorSpecified>
        <a:assigningAuthorityName i:nil="true" />
        <a:displayable>false</a:displayable>
        <a:displayableSpecified>false</a:displayableSpecified>
        <a:extension>HCIM_IN_GetDemographicsResponse</a:extension>
        <a:root>2.16.840.1.113883.3.51.1.1.2</a:root>
    </a:interactionId>
    <a:nullFlavor i:nil="true" />
    ...

Current web config:
<bindings>
      <basicHttpBinding>
        <!-- Secure Bindings -->
        <binding name="secureHttpBinding">
          <security mode="Transport">
            <transport clientCredentialType="Certificate" />
          </security>
        </binding>

        <binding name="httpBinding">
          <security mode="None" />
        </binding>
      </basicHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <services>
      <!--Synchronous Services-->
      <!--Get Demographics/FindCandidates/GetRelatedIdentifiers Service-->
      <service name="HCIM.Services.Synchronous.QUPA_AR101102" behaviorConfiguration="ServiceBehaviour">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="HCIM.Services.Synchronous.Contracts.IQUPA_AR101102"></endpoint>
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="httpBinding" contract="HCIM.Services.Synchronous.Contracts.IQUPA_AR101102" />
      </service>

Cut-Down WSDL original is 19,000 lines long. the Elements that have xsd:anyType point to a concrete element in the schema. One client modified this as such so they could use XML in that section. If I could get this WCF working with a WSDL like this it would suffice.
<wsdl:types>
        <xs:schema elementFormDefault="qualified" attributeFormDefault="unqualified" targetNamespace="urn:hl7-org:v3" xmlns="urn:hl7-org:v3" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:b="http://schemas.microsoft.com/BizTalk/2003" xmlns:hl7="urn:hl7-org:v3">
            <xs:element name="GetDemographics" type="xsd:anyType"/>
            <xs:element name="GetDemographicsResponse" type="xsd:anyType"/>
            <xs:element name="FindCandidates" type="xsd:anyType"/>
            <xs:element name="FindCandidatesResponse" type="xsd:anyType"/>
            <xs:element name="GetRelatedIdentifiers" type="xsd:anyType"/>
            <xs:element name="GetRelatedIdentifiersResponse" type="xsd:anyType"/>
        </xs:schema>
    </wsdl:types>
    <wsdl:message name="GetDemographicsSoapIn">
        <wsdl:documentation>HCIM Get Person Demographics Query (localized QUPA_IN101101) </wsdl:documentation>
        <wsdl:part name="body" element="tns:GetDemographics"/>
    </wsdl:message>
    <wsdl:message name="GetDemographicsSoapOut">
        <wsdl:documentation>HCIM Get Person Demographics Response (localized QUPA_IN101102)</wsdl:documentation>
        <wsdl:part name="body" element="tns:GetDemographicsResponse"/>
    </wsdl:message>
    <wsdl:message name="FindCandidatesSoapIn">
        <wsdl:documentation>HCIM Find Candidates Query (localized QUPA_IN101103) </wsdl:documentation>
        <wsdl:part name="body" element="tns:FindCandidates"/>
    </wsdl:message>
    <wsdl:message name="FindCandidatesSoapOut">
        <wsdl:documentation>HCIM Find Candidates Response (localized QUPA_IN101104)</wsdl:documentation>
        <wsdl:part name="body" element="tns:FindCandidatesResponse"/>
    </wsdl:message>
    <wsdl:message name="GetRelatedIdentifiersSoapIn">
        <wsdl:documentation>HCIM Get Related Identifiers Query (localized QUPA_IN101105) </wsdl:documentation>
        <wsdl:part name="body" element="tns:GetRelatedIdentifiers"/>
    </wsdl:message>
    <wsdl:message name="GetRelatedIdentifiersSoapOut">
        <wsdl:documentation>HCIM Get Related Identifers Response (localized QUPA_IN101106)</wsdl:documentation>
        <wsdl:part name="body" element="tns:GetRelatedIdentifiersResponse"/>
    </wsdl:message>
    <wsdl:portType name="QUPA_AR101102_PortType">
        <wsdl:operation name="GetDemographics">
            <wsdl:input message="tns:GetDemographicsSoapIn"/>
            <wsdl:output message="tns:GetDemographicsSoapOut"/>
        </wsdl:operation>
        <wsdl:operation name="FindCandidates">
            <wsdl:input message="tns:FindCandidatesSoapIn"/>
            <wsdl:output message="tns:FindCandidatesSoapOut"/>
        </wsdl:operation>
        <wsdl:operation name="GetRelatedIdentifiers">
            <wsdl:input message="tns:GetRelatedIdentifiersSoapIn"/>
            <wsdl:output message="tns:GetRelatedIdentifiersSoapOut"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="QUPA_AR101102_Binding" type="tns:QUPA_AR101102_PortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="GetDemographics">
            <soap:operation soapAction="urn:hl7-org:v3/QUPA_IN101101"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
        <wsdl:operation name="FindCandidates">
            <soap:operation soapAction="urn:hl7-org:v3/QUPA_IN101103"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
        <wsdl:operation name="GetRelatedIdentifiers">
            <soap:operation soapAction="urn:hl7-org:v3/QUPA_IN101105"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>

I have tried changing the return types, container types etc. Nothing is working.  I tried to implement my WCF service to just accept and return XMLNodes but that failed.
The data is being sent out properly, but .NET is changing it somehow and I'm not sure how/why.
The default namespace of the incoming message is:  urn:hl7-org:v3
The output that is being sent is using the wrong namespace: xmlns:a="http://schemas.datacontract.org/2004/07/HCIM.HL7v3.Objects.QUPA_AR101102"
I added:
[System.Runtime.Serialization.DataContract(Namespace = "urn:hl7-org:v3")]

To the HCIM_IN_GetDemograhpicsResponse object, but now the result in the client is just null for every attribute.
Is there a way to have a string type as the input/output typeof this WCF service where connecting devices don't need to change their binding/code (They're bound to the WSDL contract).

A: WCF .NET uses DataContractSerializer by default. You can override this by adding the [XmlSerializerFormat()] annotation.
Instead of adding the annotation to generated file you can generate using the /serializer:XmlSerializer switch.
So when generating the classes do this to use XMLSerializer rather than the DataContract serializer:
svcutil QUPA_AR101102.wsdl /serializer:XmlSerializer /fault

A: This Stack OVerflow question answered this one:
.NET WCF serialization issues
When generating from a WSDL (SOAP) for WCF I needed to use the serializer command:
svcutil QUPA_AR101102.wsdl /serializer:XmlSerializer /fault


text:
Q: splunk regex eliminate final quote I have:
Row 114005: Requester Name: "RETAIL\S2343W01$" Issued Common Name: "S2343W01.retail.fakename.com" User Principal Name: "S2343W01.retail.fakename.com" Serial Number: "4c22be0100010002d317" Certificate Template: Client Authentication - Retail Desktops Certificate Effective Date: 12/1/2011 10:38 AM Certificate Expiration Date: 11/30/2012 10:38 AMMaximum Row Index: 114005

And I have regex:
(?i)Serial Number: "(?P<cert_SN>.+?\n)

Result is like:
cert_SN = 4c22be0100010002d317"

How can I eliminate the final quote?

A: you can replace .+?\n by [^"]+
[^"] is a character class that doesn't contain the double quote.

A: Try:
(?i)Serial Number:\s\"(?P<cert_sn>\w+)

Or if need to capture empty fields:
(?i)Serial Number:\s\"(?P<cert_sn>[^\"]*)\"


text:
Q: Dynamic property setter via expressions is not working Hi I have following perfectly working code when I run it in console application but it fails in real app with exeption  "Specified cast is not valid."  at lambda_method(Closure , Object , Object ), do any one knows that is root cause for this ?
    public class Base
    {

    }

    public class Test:Base
    {
        public string TestProp { get; set; }
    }

    static void Main(string[] args)
    {
        Base test = new Test();
        var prop=test.GetType().GetProperty("TestProp");
        var method = BuildSetAccessor(prop.SetMethod);
        method(test, "sa");
    }

    static Action<object, object> BuildSetAccessor(MethodInfo method)
    {

        var obj = Expression.Parameter(typeof(object), "o");
        var value = Expression.Parameter(typeof(object));

        Expression<Action<object, object>> expr =
            Expression.Lambda<Action<object, object>>(
                Expression.Call(
                    Expression.Convert(obj, method.DeclaringType),
                    method,
                    Expression.Convert(value, method.GetParameters()[0].ParameterType)),
                obj, value);

        return expr.Compile();
}

A: This is not the answer at the moment, but I would recommend you to change your code to something like this:
static Action<TOb, TPar> BuildSetAccessor<TOb, TPar>(MethodInfo method)
{
    var obj = Expression.Parameter(method.DeclaringType, "o");
    var value = Expression.Parameter(method.GetParameters()[0].ParameterType);

    if (method.GetParameters().Length > 1)
        throw new ArgumentException("Method with more than 1 parameters is not supported");

    LambdaExpression expr =
        Expression.Lambda(
            Expression.Call(
                obj,
                method,
                value),
            obj, value);

    var compiled = expr.Compile();
    return new Action<TOb, TPar>((o, p) => compiled.DynamicInvoke(o, p));
}

And usage:
var method = BuildSetAccessor<Base, object>(prop.SetMethod);
method(test, "1");

I think this approach is better then casting parameters in LINQ query because generated exception info is more detailed.


text:
Q: How to properly change output interval from model text When I inlcude annotations for setting the output interval into a model, these settings seem to be assumed only for the first time the model is simulated in an OpenModelica session. For example if I create this model
model IntervalTest
  Real y(start = 1, fixed = true);
  Real v(start = 1, fixed = true);
equation
  der(y) = v;
  der(v) = -100 * y;
  annotation(
    experiment(StartTime = 0, StopTime = 67, Tolerance = 1e-06, Interval = 0.01),
    __OpenModelica_simulationFlags(lv = "LOG_STATS", outputFormat = "mat", s = "dassl"));
end IntervalTest;

and simulate it for the first time, the output interval is correctly set to 10 milliseconds. But when I change Interval to 0.001, save the model and simulate, the output interval stays at 10ms. Neither closing all results and plot windows, nor closing the model window, nor even unloading the whole project file from OpenModelica and subsequently reloading it does change the output interval to the value I have set in the model.
Only after closing OpenModelica and reopening it, will the new output interval be respected. Of course when using the simulation settings dialogs, the output interval can be changed manually, but I would rarely want to use it because it is not permanent.
So what is the correct way of immediately changing the simulation settings from the model text? If I change in the model text the stiffness value of the above oscillator model from 100 to 25 (der(v)=...), the simulation results will change accordingly (i.e. to half the oscillator frequency), but if I do the same with Interval, it will not. Am I misunderstanding the logic behind annotations?

A: This issue is now fixed. See https://trac.openmodelica.org/OpenModelica/ticket/5359.