text:
Q: Selenium Java - Chrome 83. 0 - Authentication required. Basic Authentication required. Unable to login Trying to login to my application. It shows authentication required pop up.

*

*How to avoid Authentication required pop up. Is there any way to avoid it.
tried options.addarguements.
 options.addArguments("disable-infobars");
 options.addArguments("--disable-notifications");
 options.addArguments("enable-automation");

*Also passed credentials thru https:username:password@url but did not work.
Is there any method which works. Whats best.

A: Can you try passing username and password as python f string.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC

chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome(chrome_options=chrome_options,executable_path="C://downloads//chromedriver.exe")

driver.get("url")
wait(driver, 5).until(EC.alert_is_present())

# "Switch" to the Alert browser
alert = Alert(driver)

# Send the username, TAB then password together
alert.send_keys(f'username{Keys.TAB}password')
alert.accept()


text:
Q: How do I login to my repo using gitbash? I have added my self to the git bash program but can't find on google how to login?
$ git config --global user.name "myname"
$ git config --global user.email myemail@example.com

A: The user.name and user.email have nothing to do with login credentials.
They are metadata attached to your commits.
To "login", you need to add a remote url which will use your credentials, either https or ssh one.
git remote add origin https://UserName:password@github.com/UserName/yourRepo.git
                                 ^
                                 |
                              (credentials)

Or ssh:
git remote add origin git@github.com/UserName/yourRepo.git

(which would means that you have in HOME/.ssh your id_rsa and id_rsa.pub private and public key, with the public key registered in your GitHub account: see "Generating SSH Keys")

See more at "Which remote URL should I use?".
As noted by paddymac in the comments, if origin already exists, use git remote set-url origin instead of git remote add origin

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot import AndroidHttpClient; I'm learning android restful web services using a 2014 tutorial by Lynda. The code uses this httpManager class :
   import android.net.http.AndroidHttpClient;

    public class HttpManager {

        public static String getData(String uri) {
            HttpClient client = AndroidHttpClient.AndroidHttpClient.netInstance("AndroidAgaent");
            HttpGet request = New HttpGet(uri);
            HttpResponse response;

            try {
                response = client.execute(request);
                return EntiyUtils.toString(response.getEntinity());
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                client.close();
            }
        }
    }

However, android studio says:

Cannot resolve symbol 'AndroidHttpClient'

I set minSdkVersion 8 but still could not solve the issue.
I'm wondering how to resolve this issue, or if the class has discarded, how to replace the code with a current class that is supported out of the box?

A: I think AndroidHttpClient is deprecated now, try out new HTTP which are available and very powerful than the former!

*

*http://square.github.io/retrofit/

*https://github.com/koush/ion

*https://developer.android.com/training/volley/index.html
Personally I would recommend Retrofit

A: If you are using Android Studio, add these dependencies in your gradle build:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'


text:
Q: regarding train-test split of data in spark scala I have a spark scala data frame like this
    val df = Seq(
  (10, 12),
  (44, 14),
  (32, 25),
  (31, 24),
  (75, 25),
  (80, 20),
  (35, 55),
  (32, 25),
  (67, 72),
  (32, 21)
).toDF("x1","x2")

df.show()

+---+---+
| x1| x2|
+---+---+
| 10| 12|
| 44| 14|
| 32| 25|
| 31| 24|
| 75| 25|
| 80| 20|
| 35| 55|
| 32| 25|
| 67| 72|
| 32| 21|
+---+---+

I need to split this data as training and testing where training data would be the first 8 rows (80%) and testing data would be the last 2 rows (20%).
I tried , val Array(train, test) = df.randomSplit(Array(0.8, 0.2)) But it is select 8 rows randomly (instead of choosing first 8 rows) as training and others as testing
So can anyone suggest how to select the partitions as i mentioned above ?
Thank you

A: Maybe there is a better way but nothing else comes to my mind as you require data to be ordered.
val cnt = df.count
val testSize = (0.2 * cnt).toInt
val trainSize = cnt - testSize

val trainDf = df.sort(monotonically_increasing_id).limit(trainSize)
val testDf = df.sort(monotonically_increasing_id.desc).limit(testSize)


text:
Q: Adding props condition in Styled component gives me an error of "Expression produces a union type that is too complex to represent" I'm trying to make a condition using the component's disabled prop. However, I'm getting this error Adding props condition in Styled component error Expression produces a union type that is too complex to represent. The code below works on other component, except for this one.
Can you please help me understand what the error means or what's the fix of it? TIA!
ListGroupItem is a react-bootstrap component.
My typescript version is 4.4.4
export const StyledListGroupItem = styled(ListGroupItem)`
  ${({ disabled }) => (disabled && `
    color: red;
  `)};
` as any;


text:
Q: Problems calling ServiceStack services in-process with Validation & Filters I need to be able to call my SS services from the controllers of an MVC application. Ideally i'd like to call them in-process to avoid the overhead of buiding a http request etc.
From scouring documentation I feel there are 2 suggested methods, but neither work fully.
1) ServiceGateway - Use the service gateway. This calls validation filters, but does not call other customer filters I've added. No option to applyFilters.
2) HostContext.ServiceController.Execute - There is a dedicated option on this method called applyFilters, and when I set it to true it works and applies filters and validation (though it only executes GlobalFilters, not TypedRequestFilters). However, if [CacheResponse] attribute is set on the service it overwrites and flushes a response to my client overriding the flow of the MVC controller and i don't know how to stop this. It does not do this if I set to applyFilters to false or if I take CacheResponse off. Changing the priority of the cache has no effect.
I'm calling the Execute method as follows from within an Action method on my controller:
HostContext.ServiceController.Execute(serviceRequest, HostContext.GetCurrentRequest(), true);

Before this method even returns control a response is flushed to the webpage on Chrome and then nothing/null is returned from method.
I feel there is regarding point 1) a feature missing and point 2) a bug in the implementation, though am not confident enough in my knowledge of SS to remedy either! Please help!
Thanks.

A: Filters are executed as part of the HTTP Request Pipeline and can terminate the current Request with a custom HTTP Response. You can check IRequest.IsClosed after executing the Request to check if it has been terminated by a Request Filter. They're behavior is incompatible with internal Gateway requests so there's no option to execute them in the Gateway.
I've marked these ServiceController methods as an In Process Request in this commit which should resolve the issue with the [CacheResponse] attribute which ignores In Process Requests.
This change is available from v4.5.13 that's now available on MyGet.


text:
Q: pass ref as function argument inside a ternary operator I have this function:
void TakeHit(ref Player player){
    //...
}

And I have 2 Players called red and blue. Suppose there is a boolean isRed that says if the Player that is going to take the hit is red (true) or blue (false):
bool isRed = //...
TakeHit( /* what do I write here in a ternary operator??? */ );

I tried some syntaxes and this one seemed to compile
TakeHit(ref isRed ? ref red : ref blue);

although I didn't test since it looks super wierd and I'm asking just out of curiosity since a simple if can replace the ternary operator option.


text:
Q: ¿Cómo obtener año anterior de una fecha en java? tengo una date de entrada con este formato yyyy-MM-dd y quiero obtener el año anterior a esa fecha, es decir si recibo 2020-03-23 quiero obtener 2019-03-23, cómo puedo hacer esto en java?

A: public static void main(String[] args) {
    String fecha_salida,fecha_entrada="2020-03-23";
    String[] aux=fecha_entrada.split("-");
    //Split separa el string fecha cada vez que encuentre un "-"
    //retornando { "2020", "03", "23" } ,que será asignado a la matriz aux
    int anio_anterior=Integer.parseInt(aux[0])-1;//Restamos una unidad al año actual

    fecha_salida=anio_anterior+"-"+aux[1]+"-"+aux[2];//tu respuesta
    System.out.println(fecha_salida);
}

A: Puedes realizarlo con el tipo Date el cual es algo raro el año comienza en "1900" así que si le insertas como año el valor "1" te lo toma como 1901 el mes comienza en "0" y el día es igual espero que la definición de este método de ayude. Suerte!!
Definicion:
public static Date getDateOneYearBefore(String date){
        Date one_year_before= new Date(); //It is the current date

        String [] separar=date.split("-");//Split yor date "2020-03-23" to ["2020","03","23"]
        int year=Integer.parseInt(separar[0])-1900; //we subtract the year and "1900" because Date begging in that year
        //for example the year "120" for Date is 2020
        int month=Integer.parseInt(separar[1])-1;// the month begging on "0" which is January
        int day=Integer.parseInt(separar[2]);//It is the same day
        int year_before=year-1;//get one year before

        one_year_before.setYear(year_before);//set the year that you want
        one_year_before.setMonth(month);//set month
        one_year_before.setDate(day);//set day

        //setting to hour 00:00
        one_year_before.setMinutes(0);
        one_year_before.setHours(0);

        return one_year_before;
    }


text:
Q: Notation in likelihood function For an assignment that asked "Compute the likelihood function when $Y=10$", I had written:
$$
L(\theta|n=30, y=10) = {30 \choose 10} \theta^{10} (1-\theta)^{20} ; \theta \in \left[0, \tfrac{1}{5}, \tfrac{2}{5}, \ldots, \tfrac{5}{5}\right]
$$
I will omit the context of the problem since my question is not about that. My professor then suggested to me that I should make a change in notation, specifically to change $\theta$ into $\theta_i$, but I don't see why it should be the case. As I understand, the likelihood function takes as an input the parameter and outputs a likelihood value. What I interpret from the expression that I wrote above is "the likelihood for a specific value of $\theta$ given the data is ..., and $\theta$ can only acquire these possible values". Is there anything wrong with this/why should I using $\theta_i$ ?

A: You normally use $\theta_i$ to indicate that the probability of
"success" depends on each observation, i.e. it is not constant across your sample. Logistic regression is a famous example of such practice. There you model each probability in terms of one or more explanatory variables:
$$\theta_i = \alpha + \beta x_i$$
Having said that, I don't see anything wrong with your notation. Beware, however, the likelihood can be a function of more than one parameter. In the above model, for example, the parameters you want to estimate are both $\alpha$ and $\beta$.


text:
Q: Как получить значение атрибута width в img? Я пытаюсь сравнить значение атрибута ширины у картинки, но получаю в консоль только undefined. Как мне получить значение атрибута ширины у картинки ?
var $img = $('.img-pr-medium');
$img.load(function(){
    var width = img.clientWidth;
    if(width === 1200) {
        console.log('test');
    }
});

A:

function testFunction() {
let image = $('.test-image');
let width = image.innerWidth();
if (width === 100) {
  image.innerWidth(1000);
}
}
.test-image {
  width: 100px;
  heigth: 80px;
}

<button onclick="testFunction()">Нажми меня для увеличения</button>


text:
Q: Cox-Stuart vs Augmented Dickey Fuller Given a time series, suppose I wish to determine if trend is present. I understand I can use the Cox-Stuart test (https://www.r-bloggers.com/trend-analysis-with-the-cox-stuart-test-in-r/), but I have also read that the Augmented Dickey Fuller test can be done for this (https://machinelearningmastery.com/time-series-data-stationary-python/). More specifically, the last link says:
"The Augmented Dickey-Fuller test is a type of statistical test called a unit root test.The intuition behind a unit root test is that it determines how strongly a time series is defined by a trend."
But I have also read from (https://kourentzes.com/forecasting/2017/03/30/can-you-spot-a-trend-in-a-time-series/):
"I do not think it is an exaggeration to suggest that even experts often can be confused on the exact definition (and effect) of a unit root and a trend."
So my questions are thus:

*

*What does it mean for a time series to have a unit root? Does that automatically mean there is a trend in the time series?

*What is the difference between the Cox-Stuart and Augmented Dickey Fuller Tests? Which should I definitely use for trend detection?

A: There are two types of trend: stochastic and deterministic.  Unit roots are a type of stochastic trend that the augmented Dickey-Fuller tests for.  The Cox-Stuart test is for deterministic trends.


text:
Q: Sequential logging in concurrent JavaScript I have a block of async code that runs concurrently which also contains logging statements.
async function processItems(item) {
   console.log("Start", item)
   await doSomethingAsync(item)
   console.log("First")
   await doSomethingAsync(item)
   console.log("Second")
   await doSomethingAsync(item)
   console.log("Stop", item)
}

await Promise.all(someItems.map(processItems));

Since the blocks run concurrently, the log messages of a single function call are not in sequence anymore.
How could I show a sequential log while still letting the code run in parallel?


text:
Q: Laravel, simplifying relationships: multiple sortable models As I was working on a Laravel project I noticed a recurring pattern in my models:

*

*Model A hasMany Model B

*Model B can optionally be hidden

*Model B can optionally be sorted

Examples:
A gallery has pictures. You can choose not to display a picture or you can choose to sort them.
A "view our team" page. You can choose not to display certain employees or you can choose to sort them.
A slider on the home page. You can choose not to display certain images or you can choose to sort them.
I've been implementing all of these as follows:
class ModelA extends Model {
    function modelBs() {
        $this->hasMany('modelB');
    }
}

class modelB extends Model {
    protected $fillable = ['visible', 'order'];
    function modelA() {
        $this->belongsTo('modelA');
    }
}

I'm also repeatedly re-implementing (copying/pasting) the code for displaying these in blade templates:
@foreach( $modelA->modelBs()->sortBy('order') as $modelB )
    @if( $modelB->visible )

{{ $modelB->output() }}

    @endif
@endforeach

And in the admin panel I have to repeatedly re-implement (copy/paste) the the jQuery-UI sortable widget for modifying the order, serializing your decision, and submitting it to the server then saving this order (via updating every Model B's order appropriately)
It's getting out of hand, and I remembered the adage from Laracasts:

If you find yourself using copy and paste, there's probably a better way to do it

As I tried to think of a better solution, this is the first relationship that I imagined:

*

*Model A hasMany SortThing

*SortThing morphsTo sortable

*Model B hasOne sortable
This way I know that any SortThing can be sorted or hidden, and a SortThing can reference any sortable object (pictures, employees, slider panels, etc)
The problem is doing this doesn't really make my code any more DRY:
class ModelA extends Model {
    function modelBs() {
        $this->hasMany('SortThing');
    }
}

class modelB extends Model {
    function sortable() {
        $this->morphsOne('SortThing', 'sortable');
    }
}

class SortThing extends Model {
    protected $fillable = ['visible', 'order'];
    function sortable() {
        $this->morphTo();
    }
}

@foreach( $modelA->modelBs()->sortBy('order') as $modelB )
    @if( $modelB->visible )

{{ $modelB->sortable->output() }}

    @endif
@endforeach

I've added an extra class and necessitated the sortable-> in my output and I'm still copying/pasting code.
Any advice on how to clean up my code would be appreciated. Still a bit of a Laravel newb.
Bonus points if the resulting relationship doesn't require me to update 18 database rows when objects are re-ordered as this could potentially lead to some ugly overhead as the lists get really long.
Update
Attempting @gpopoteur's answer below (after fixing the typo in his declaration of the renderItems function) I got the following error:
[2015-03-24 13:08:52] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'App\Slider and App\HasSortableItemsTrait define the same property ($sortItemClass) in the composition of App\Slider. However, the definition differs and is considered incompatible. Class was composed' in /var/www/example.com/app/Slider.php:26

Slider.php looks like so:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Slider extends Model {

    use HasSortableItemsTrait;

    protected $sortItemClass = 'App\SliderPanel';

    //
    public function sliderable() {
        return $this->morphTo();
    }

    public function panels() {
        return $this->hasMany('App\SliderPanel');
    }

    public function output() {
        $panels = $this->panels();
        return "Test?";

    }

} // Line 26

and HasSortableItemsTrait.php looks like so:
<?php namespace App;

trait HasSortableItemsTrait {

    protected $sortItemClass; // Also tried $sortItemClass = ''; and $sortItemClass = null;

    public function items() {
        $this->hasMany($this->sortItemClass)->sortyBy('order')->where('visible', '=', true);
    }

    public function renderItems($htmlTag = '
:item
') {
        $render = '';
        foreach( $this->items() as $item ){
            $render .= str_replace($item->render(), ':item', $htmlTag);
        }

        return $render;
    }

}

Update 2
I've figured out that commenting out the following line fixes my issue:
protected $sortItemClass;

Of course I still have to make sure anything using the trait defines $sortItemClass or it will fail when calling items()
Now I'm getting a new error:
[2015-03-24 13:34:50] production.ERROR: exception 'BadMethodCallException' with message 'Call to undefined method Illuminate\Database\Query\Builder::sortBy()' in /var/www/example.com/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:1992

I double-checked the Laravel docs and I'm like 90% sure that sortBy should be a valid method on query builders...

A: You could try adding everything in a trait, and then just use SortableTrait; on your Model. And then setting the class as a protected attribute of the other Sortable items that it has many.
!!! Code below is not tested !!!
Lets define a trait for the Class that has sortable Items.
    trait HasSortableItemsTrait {

        // define this in your class
        // protected $sortItemClass

        public function items() {
            $this->hasMany($sortItemClass)->orderBy('order');
        }

        public function renderItems($htmlTag = '
:item
']) {
            return $this->items->map(function($item) use ($htmlTag) {
                if( $item->visible ){
                    return str_replace($item->render(), ':item', $htmlTag);
                }
            });
        }

    }

Another trait to use on the items that are sortable.
    trait IsSortableTrait {

        // define this in your class
        // protected $sortItemParent

        function items() {
            $this->belongsTo($sortItemParent);
        }

        function render(){
            return $this->output();
        }

    }

Lets do an example with a Gallery that has Sortable Photos. This is how the App\Gallery should look like:
    class Gallery extends Model {
        use HasSortableItemsTrait;

        protected $sortItemClass = 'App\Photo';
    }

And this is how the App\Photo class would look like:
    class Photo extends Model {
        use IsSortableTrait;

        protected $sortItemParent = 'App\Gallery';
    }

Then you just need to fetch the Item that has many sortable items, in this case the gallery.
    $gallery = Gallery::find(1);

And in the view you just need to call the  renderItems() method of the view.
    {{ $gallery->renderItems() }}

I made the renderItems method be able to receive how you want to wrap what the $item->render() will be giving as output. For example, between

 you just have to call the method like this:
    {{ $gallery->renderItems('
:item
') }}


text:
Q: How to make SVN ADD ignore binaries Binaries (under Linux) don't have an extension so I cannot exclude them using patterns. Thus when I use SVN add to add a directory I will get something like
$ svn add recursion_vector/
A         recursion_vector
A         recursion_vector/rec_vec.cxx
A         recursion_vector/rec_vec.h
A  (bin)  recursion_vector/rec_vec

Here rec_vec is the executable I would like to exclude. SVN obviously recognizes it as binary. Now can I tell Subversion to ignore all binary files?

A: This is a bit verbose because it uses find:
find [TARGET-DIRECTORY] \( -executable -type f \) -prune -o -print | xargs svn add --depth empty
Passing the target-directory to find, find will recurse the directory printing out all the contents except for executable files (\( -executable -type f \) -prune).  Without -type f find would also prune directories since these usually have the execute bit or "search bit" set.
The --depth empty option on add tells svn not to itself recurse a file object, since find is handling the recursion.
If you like the result, you can put this in a shell function that would allow you to pass in arguments for [TARGET-DIRECTORY].
Thank you,
Zachary

A: Can you set up a pattern match to exclude filenames that don't have a . in them?

A: This is not exactly what you want (and you might already know this answer)... but anyway :
You can set exclude patterns to ignore some files based on the filenames. More info in the great SVN book :
http://svnbook.red-bean.com/en/1.1/ch07s02.html#svn-ch-7-sect-2.3.3
Other than that, it might be possible to do something with commit hooks, but I have no experience with those ...
Good luck !


text: Q: Getting 403 access denied for bitbucket webhook to jenkins I've configured a bitbucket webhook to trigger a jenkins build. The jenkins is running in a docker container hosted in a private cloud. I'm getting a 403 status code with access denied error when I view the results of the request in bitbucket. Not sure what the issue is because bitbucket is able to hit the endpoint, just that it's saying access denied. Not sure where I'm supposed to change such permissions so it can work.


text:
Q: Circuit for voltage division and DC shift doesn't work I've connected the circuit below on a breadboard and tested it in the lab:

Components:

*

*\$R_{1}=1\,M\Omega,\;R_{2}=40\,k\Omega,\;R_{3}=R_{4}=R_{5}=R_{7}=R_{8}=20\,k\Omega,\;R_{6}=49.9\,k\Omega\thickapprox50\,k\Omega,\;R_{9}=R_{10}=10\,k\Omega,\;R_{11}=5.1\,k\Omega\thickapprox5\,k\Omega,\;R_{12}=1\,k\Omega,\;R_{13}=R_{14}=R_{16}=R_{17}=R_{18}=R_{19}=2\,k\Omega,\;R_{15}=5\,k\Omega\$

$$$$

*

*\$C_{1}=470\,\mu F,\;C_{2}=1\,\mu F\$

$$$$

*

*\$V_{CC}=15\,V,\;V_{EE}=-15\,V\$
$$$$

*op-amps are of the type LM358P.
$$$$

The upper part takes the DC component of an input signal through a passive low-pass filter, divide it by 5 through the voltage-divider network (note that R3 and R4 are in parallel), then add 2.5 V to it.
The lower part take the AC component of an input signal through capacitor, divide it by approximately 10 through the voltage-divider network (note that R12 and R13 are in parallel), then add 2.5 V to it.
The problem is that the output appears completely different from the theoretical values:

*

*For the upper circuit, when the input was a DC voltage of 5 V, the
output was around 10 V instead of 3.5.

*For the bottom circuit, when the input was a sine wave, the output
was completely distorted. It couldn't be recognized as a sine wave.

I don't know where the problem could be. The simulation results of the circuit give results as expected.


text:
Q: Reusing Prepared Statements, Transactions and Connection Pool I am doing a school project in which my team has to ensure consistency and integrity of data, as well as to improve performance for a trading website. The website is coded in JSP and JAVA. We are also using MySQL and its ndb cluster for our project.
Firstly, I have done experiments on prepared statements with load test of 100, 175 and 250 virtual users. The results show that reusing prepared statements improves response time and throughput. By improvement, I meant that average response time decreases and maximum throughput increases.
Secondly, I have also done experiments using connection pool with the same load test of 100, 175 and 250 virtual users. Similarly, the results show an improvement in performance. Just an additional information, I used c3p0 for the connection pool.
With these results, I am planning to use prepared statements and connection pool for the trading website. At the same time, we would also use transactions to ensure consistency and integrity of data.
Currently, the way that I have implemented prepared statements and transaction are as follows:
public class ExchangeBean {
private PreparedStatement psSelectFromBuy = null;
private PreparedStatement psSelectFromSell = null;
private PreparedStatement psInsertBuy = null;
private PreparedStatement psInsertSell = null;
private Connection tranDbConnection = null;

public ExchangeBean() {
    reusePreparedStatements();
}

public void reusePreparedStatements() {
    tranDbConnection = DbBean.getDBConnection();
    dbConnection.setAutoCommit(false);

    try {
        psSelectFromBuy = dbConnection.prepareStatement("SELECT * FROM buy WHERE stock = ?" FOR UPDATE);
        psSelectFromSell = dbConnection.prepareStatement("SELECT * FROM sell WHERE stock = ?" FOR UPDATE);
        psInsertBuy = tranDbConnection.prepareStatement("INSERT INTO buy (userid, date, price, stock) VALUES (?, ?, ?, ?)")
        psInsertSell = tranDbConnection.prepareStatement("INSERT INTO sell (userid, date, price, stock) VALUES (?, ?, ?, ?)");
    } catch (Exception e) {
    }
}

public boolean buy(//some parameters) {
    try {
        selectFromBuy(); //a method that contains psSelectFromBuy
        psInsertBuy.clearParameters();
        psInsertBuy.setInt(1, buy.getUserId());
        psInsertBuy.setLong(2, buy.getDate().getTime());
        psInsertBuy.setInt(3, buy.getPrice());
        psInsertBuy.setString(4, buy.getStock());
        psInsertBuy.executeUpdate();

        //some other codes
        psInsertBuy.commit();
    } catch (Exception e) {
        dbConnection.rollback();
    }
}

public boolean sell(//some parameters) {
    try {
        selectFromSell(); //a method that contains psSelectFromSell
        psInsertSell.clearParameters();
        psInsertSell.setInt(1, sell.getUserId());
        psInsertSell.setLong(2, sell.getDate().getTime());
        psInsertSell.setInt(3, sell.getPrice());
        psInsertSell.setString(4, sell.getStock());
        psInsertSell.executeUpdate();

        //some other codes
        psInsertSell.commit();
    } catch (Exception e) {
        dbConnection.rollback();
    }
}
}

Note: This code sample is incomplete for brevity's sake; quite a fair bit of the codes and logic not in it.
So basically, my approach is to declare the prepared statements as class variables and then instantiate them when the class is being called the very first time.
Questions

*

*Is my approach correct? I feel that it is not exactly correct because all my prepared statements are tied to one connection. I am worried that if multiple users try to buy and sell at the same time, there may be issues since only one connection is used. However, I cannot close the connection else my prepared statements would be closed after each deal and hence would not be reused. Furthermore, when I commit, all the prepared statements involved in the transaction should be committed together and hence it would be easier if I only used one connection.

*Do you have any suggestions on how I should use connection pooling with prepared statements and transactions? I was thinking of caching all the prepared statements into the connection each time it is created from the pool. When the connection is being used for buy or sell, the method itself will disable auto commit on that connection and enable auto commit again at the end of the method. Would this approach be appropriate? Or should I have two connection pools (one for non-transaction connections and one for transaction connections)?
Thanks!


text:
Q: understanding of vector and point I just have some confusions about basic understandings in vectors and points. For example, if $$\alpha(t)=(x(t),y(t),z(t))$$ is a parametrized curve from $I$ to $\mathbb{R^3}$, then for a specific point $t_0 \in I$ ,  $\alpha(t_0)$ represents a vector or a point in $\mathbb{R^3}$ ? Why? I think $\alpha(t_0)$ is a point on $\mathbb{R^3}$, but I saw $\alpha(t_0)$ described as a position vector in Do Carmo's book.
Thank you!

A: Assuming you are given a coordinate system in $R^3$, there exist a "one to one correspondence" between the set of all points in $R^3$ and the set of three dimensional vectors.  So we can interpret the $\alpha(t)= (x(t), y(t), z(t))$, for each t, to be either a point or the vector that, if we were to have its base at (0, 0, 0) would have its tip at the point (x(t), y(t), z(t)).
I am not saying that points and vector are the same thing!  For example, given the vector (x, y, z), which would represent the vector with end at (0, 0, 0) and tip at the point (x, y, z), we can [b]move[/b] that vector so that its end is at (a, b, c) and its tip is at (a+ x, b+ y, c+ z) but it is the same vector.  You can move vectors but you can't move points.
(Some texts use  for vectors specifically to distinguish vectors from points (x, y, z).)

A: The idea is that some things are essentially the same in mathematics -- isomorphic is the term of art.
This is also the case with vectors and points in Euclidean space. In particular, if we always take the position vector (i.e., those originating at the origin of coordinates) as the representative of each equivalence class of vectors, then there is an isomorphism between the points and vectors of that space, so that we may regard them as essentially the same thing.
How we think of them in a particular case would depend on which is more convenient for the problem at hand.
By the way, note that there is a difference between a curve and its trace.


text:
Q: How to extract content from link url and save it sqlite in android I am trying to connect to a linkUrl in the code snippet below, then get content from it which is suppose to be in text format and finally save that content in sqlite database using the variable*(linkData)*.
Someone help me with how can carry out those steps in my android app.
Thanks in advance.
for (int i = 0; i < li.size(); i++) {

            /* These are the values that will be collected */
            String title;
            String date;
            String imageUrl;
            String linkUrl;
            String linkData;

            // Extract the value for the keys called "post-title", "date", "post-footer-author",
            // "img", "abs:src", "a" and "href".
            title = li.get(i).getElementsByClass("post-title").text();
            date = li.get(i).getElementsByClass("date").text();
            imageUrl = li.get(i).getElementsByTag("img").attr("abs:src");
            **linkUrl = li.get(i).getElementsByTag("a").attr("abs:href");**

            **linkData = ??????;**

            ContentValues newsValues = new ContentValues();
            newsValues.put(NewsContract.LatestNewsEntry.COLUMN_TITLE, title);
            newsValues.put(NewsContract.LatestNewsEntry.COLUMN_DATE, date);
            newsValues.put(NewsContract.LatestNewsEntry.COLUMN_IMAGE, imageUrl);
            newsValues.put(NewsContract.LatestNewsEntry.COLUMN_LINK, linkUrl);
            newsValues.put(NewsContract.LatestNewsEntry.COLUMN_DATA, linkData);

            newsContentValues[i] = newsValues;
        }


text:
Q: Get image height via JavaScript In a JavaScript function, I want to get the height of an image. I do:
var image_height = $(image).height();

Turns out image_height is 0, but I'm sure my image doesn't have height 0. Is there a way to extract this height?

A: Calculate height after image load.
$(document).ready(function(){
    $(image).load(function(){
      var image_height = $(this).height();
    } );
});

A: try outerHeight() as well
var image_height = $(image).outerHeight();

A: Make sure the dom has been rendered prior to retrieving the height.
$(document).ready(function(){
   var image_height = $(image).height();
}):

A: You can also use regular JS:
var image_height = img.clientHeight


text:
Q: Cant receive actual error message on client I have asp net project, i tried call .asmx web service from .aspx page via ajax js. When my web.config file is configured to customErrors mode = On, i receive default error message like "There was an error processing the request".. When customErrors mode = Off i receive real correct business error message.
To Be: i need to configure customErrors mode = On to redirect for custom error pages for our users, but at the same time i really need to receive actual error from asmx services..
Help, please!
Thanks
i tried set customErrors mode = RemoteOnly but it doesnt work: on local host everything is ok but on dev env - the same problem


text:
Q: What is the proper ember.js-way to react to a changing checkbox I have a checkbox like this:
{{input type="checkbox" checked=property}}

When I click the checkbox the property is changed. Now I like to call a function to persist the property. But what is the best way to do this?

*

*I could bind an observer to property, but this is consindered bad.

*I could bind an action to input oder click.
{{input ... input=(action "actionName") click=(action "actionName")}}

This doesn't work because the property has still the old value when the action is called.

*Extending the class Checkbox:
import Checkbox from '@ember/component/checkbox';
Checkbox.reopen({
    onChange: null,
    change() {
        this._super();
        if (this.onChange) this.onChange();
    }
});
...
{{input ... onChange=(action "actionName")}}

But the function change is not documented, even though the source code  indicates that it is feasable to override.

*I could bind an action to didUpdate or didUpdateAttrs, but the action is called twice. In my case this wouldn't be a problem, because the property is part of a model, so I could call model.get('hasDirtyAttributes') in the action.
[Update] In my test case the action was called twice but in my real code it is only called once, so this seems to be the best solution?[/Update]
So what is the proper ember.js-way to do this?

A: I personally prefer one way binding with checkboxes. I use the native input like so:
<input type="checkbox" checked={{myValue}} onclick={{action (mut myValue) value="target.checked"}}>

Check this twiddle to see it live in action. This is the easiest, non-library approach for 1-way bound checkboxes, which I would argue is the "ember-way" as of 2.x (although I do know people that still like and use the 2-way bound input which more requires observers in cases like what you described as far as I can tell).
In one of my projects, I use ember-paper which uses a nicely displayed checkbox without input and I believe the correct aria-bindings for a11y. They leverage click to invoke onChange
click() {
    if (!this.get('disabled')) {
      invokeAction(this, 'onChange', !this.get('value'));
    }
    // Prevent bubbling, if specified. If undefined, the event will bubble.
    return this.get('bubbles');
}

such that you can use with the following api
{{#paper-checkbox value=value1 onChange=(action (mut value1))}}
    A checkbox: {{value1}}
{{/paper-checkbox}}

You can see the example and how the template and component js are implemented for inspiration should you want a better looking checkbox than native

A: Have a look at my ember-twiddle example.
I would suggest using input helper,
({input type="checkbox" click=(action "setProperty") checked=my_property}}

toggle the property inside the action
setProperty() {
  // toggle the property on click
  this.toggleProperty("my_property");
  console.log(this.get('my_property')); // returns true or false based on the checked value
  .. // do whatever stuff you want
}

If your at the most recent version of ember 3.9, have a look at this


text:
Q: sending push notification to multiple users using Parse in android I want to send push notification to multiple users using parse backend. can i target a friends with Facebook id without creating channel?(in my app i integrated Facebook)
if not possible send me code with creating channel

A: Parse has different possibilities depending on which kind of account you have. I assume you have the free one so you CANNOT send push notifications to specific or multiple users with this kind of account. BUT you can send them through the website controller to just iOS or Android users which is the only option you have with the free account.
I actually encourage you to use channels to do so. I assume you already have the correct initializations as explained in the parse website (https://parse.com/docs/android_guide)
// Create our Installation query
ParseQuery pushQuery = ParseInstallation.getQuery();
pushQuery.whereEqualTo("channels", "Giants"); // Set the channel
pushQuery.whereEqualTo("scores", true);

// Send push notification to query
ParsePush push = new ParsePush();
push.setQuery(pushQuery);
push.setMessage("Giants scored against the A's! It's now 2-2.");
push.sendInBackground();

I ultimately reccomend you to read this guide: https://parse.com/docs/push_guide#sending-queries/Android


text:
Q: How can I call a function within a website? I've been looking at the source HTML for various websites, and it would make my life much easier if I could call functions from the website I'm accessing on will. I'm using Python, but please keep in mind I am somewhat of a novice.

A: If you're looking to access someone else's website using Python, you'll need to look into something like Python's urllib and beautifulsoup.
If you want to execute functions inside that website (that require Javascript), you'll need to use a Python browser emulator like enter link description here which is described here. Hope this helps! It's quite a complex question.
If you're looking to create a webpage that runs Python code, that's unreasonable, as all Python code in web development is run server-side, and you'll have to rely on something like Javascript for that.


text:
Q: Where can I find node.js interpreter In WebStorm to get karma.conf running I need to configure it in a pop up window and enter the "path to the node.js interpreter".
(for some reason this information vanished after a restart)
Questions:

*

*What is the path to the needed file?

*Where is the node interpreter on Mac/Linux/Windows by default?

(I am on OS X)

A: On OSX if you've installed Node.js with brew:
/usr/local/bin/node
You can check the exact folder on your machine with the command which node
Important
When the finder opens on OSX, you won't be able to navigate to this path initially. You'll first need to navigate to the root folder e.g. Macintosh HD and then perform the keyboard shortcut Command + Shift + . (. = dot = period) to be able to select hidden files and folders.

A: Ubuntu:
sudo apt install nodejs

whereis nodejs

nodejs: /usr/bin/nodejs /usr/lib/nodejs /usr/include/nodejs /usr/share/nodejs /usr/share/man/man1/nodejs.1.gz

Configuring NodeJS Intepreter in IntelliJ:
File | Settings | Languages & Frameworks | Node.js and NPM
Node interpreter: Add... (select from the above path or add it)
/usr/bin/nodejs

Then, click on Enable button and select the modules.

A: Generally, on OSX and Linux, you can find any program with which program. In your case, type
which node

in terminal.

A: On windows command prompt
where node

A: On OSX:

/usr/local/bin/node

well I got it by myself, but wanted to share the answer, as I couldn't find it on google / stack overflow and hope to save somebody some time

A: This can be useful for someone. I tried all the previous methods on Linux Ubuntu 19.10, none worked, neither reinstalling nodejs. So I installed Webstorm via snap, with:
sudo snap install webstorm
sudo snap install webstorm --classic

And surprise, Nodejs was already configured in this version. Then I erased the webstorm version that I installed from Ubuntu Softwared.
That worked for me and was easy. Hope that can give you a clue.


text:
Q: If Peter Petrelli can heal like Claire, why does he have a scar on his face? In Heroes...
Peter Petrelli adopts powers of those he comes in contact with. Eventually we learn he keeps those powers even when not in proximity to the person he's absorbing from. He encounters Claire pretty early on and gets her ability to heal.
In the episode 5 years gone we see future Hiro and future Peter join up and Peter has this slash across his face. We see this slash in other episodes, like in Season 3 when he is caught looking for a gun after his brother is shot.
So much as I can tell, the slash is only there so the viewer can distinguish present day Peter from Future Peter and I don't recall any point where he took damage that sliced his face and didn't heal.
Anyone know how this scar got there and why it doesn't heal?

A: As stated on heroeswiki.com there are several references to at least two scar varieties on Peter Petrelli's face.
Alas we'll never know what caused it and why he did not heal it:

Writers Joe Pokaski and Aron Coleite said about Peter's scar, "First, it is not a mistake, Peter can regenerate, but he still has the scar. Secondly, we'll show you how later on in the series. We promise".

Heroes being cancelled this promise now is void.
References:
http://heroeswiki.com/Peter%27s_scar
https://www.cbr.com/behind-the-eclipse-heroes-week-21/ (origin of the writer's quote)

A: It's a cautionary reminder
Future Peter's facial scar runs from the right side of his forehead to his left cheek:

— Image source: heroeswiki.com

In "I Am Become Death", Future Gabriel (a repentant Sylar) cautions Present-day Peter against following the Sylar path.  Gabriel explains that he keeps his broken Sylar watch as a scar to remind himself of his past misdeeds.  The watch has a cracked face, with the crack positioned similarly to Future Peter's scar:

— Image source: www.writeups.org

Gabriel's son Noah is happy to see present-day Peter and is surprised that Peter doesn't have his scar.  Since the Peter of this future timeline has earned the trust of Gabriel and his family, Peter and Gabriel likely have similar opinions about the potential dangers of their abilities.
If Future Peter has any conscious or subconscious control over his healing ability, he may have chosen to keep his scar for the same reason that Gabriel keeps his broken watch.


text:
Q: CUDA: Thread-block Level Broadcast on K40 using Shuffle instrutions indirectJ2[MAX_SUPER_SIZE] is a shared array.
My cuda device kernel contains following statement (executed by all threads in the thread block):
int nnz_col = indirectJ2[MAX_SUPER_SIZE - 1];
I suspect this would cause bank conflicts.
Is there any way I can implement the above  Thread-block level broadcast efficiently using new shuffle instructions for the kepler GPUs? I understand how it works at warp level. Other solutions, which are beyond shuffle instruction (for instance use of CUB etc.), are also welcome.

A: There is no bank conflict for that line of code on K40.  Shared memory accesses already offer a broadcast mechanism.  Quoting from the programming guide

"A shared memory request for a warp does not generate a bank conflict between two threads that access any sub-word within the same 32-bit word or within two 32-bit words whose indices i and j are in the same 64-word aligned segment (i.e., a segment whose first index is a multiple of 64) and such that j=i+32 (even though the addresses of the two sub-words fall in the same bank): In that case, for read accesses, the 32-bit words are broadcast to the requesting threads "

There is no such concept as shared memory bank conflicts at the threadblock level.  Bank conflicts only pertain to the access pattern generated by the shared memory request emanating from a single warp, for a single instruction in that warp.
If you like, you can write a simple test kernel and use profiler metrics (e.g. shared_replay_overhead) to test for shared memory bank conflicts.
Warp shuffle mechanisms do not extend beyond a single warp; therefore there is no short shuffle-only sequence that can broadcast a single quantity to multiple warps in a threadblock.  Shared memory can be used to provide direct access to a single quantity to all threads in a warp; you are already doing that.
global memory, __constant__ memory, and kernel parameters can also all be used to "broadcast" the same value to all threads in a threadblock.


text:
Q: Memoir appendix At the moment I have Appendix A when I start the appendix page. In the table of contexts I see the item A. How can I replace the "A" by "Appendix". I'm using the memoir class and I'm also using babel but I was already able to change the appendix name as follows.
\addto\captionsdutch{%
  \renewcommand{\appendixname}%
    {Appendix}%
}

A: If I understood your question correctly, to add the word "Appendix" in the ToC, you can redefine \cftappendixname; if you also want to suppress the numbering for the appendix (both in the ToC and in the body of the document), you can redefine \thechapter just before the appendix (and adjust \cftchapternumwidth). Here's a little example:
\documentclass{memoir}
\usepackage[dutch]{babel}

\addto\captionsdutch{%
  \renewcommand{\appendixname}%
    {Appendix}%
}
\renewcommand*\cftappendixname{\appendixname}

\begin{document}

\tableofcontents*
\chapter{Test Regular Chapter}
\appendix

\addtocontents{toc}{\setlength\cftchapternumwidth{1em}}
\renewcommand\thechapter{}
\chapter{Test Appendix}

\end{document}


text:
Q: Boot ubuntu in my macbook pro I have Ubuntu 14.04 installed in my macbook pro. It was working normally for a week. Then I got this problem saying 'efi is not ready yet'.
I tried to run boot-repair, but it does not help.
Here is the pastebin link:
http://paste.ubuntu.com/11696373/
Please help me!!


text:
Q: Pdf of a normal variable accepted with probability dependant on the normal variable Assume $z$ is a standard normal variable. If $z<0$, then we accept it with probability 1. if $z\ge0$, we accept it with probability $e^{-mz}$, where $m>0$. I'm trying to figure out the pdf of this new r.v. $\hat{z}$ that is sampled using this procedure.
So far I've defined
$M^p = \int_{-\infty}^{0}z^p\frac{e^{-\frac{z^2}{2}}}{\sqrt{2\pi}}dz + \int_{0}^{\infty}z^p\frac{e^{-\frac{z^2}{2}}}{\sqrt{2\pi}}e^{-mz}dz$
$E(\hat{z}) = \frac{M_1}{M_0}$
$Var(\hat{z}) = \frac{M_2}{M_0} - (\frac{M_1}{M_0})^2$
This is essentially saying that the pdf is
$f(\hat{z}) = \frac{\begin{cases}
    \frac{e^{-\frac{\hat{z}^2}{2}}}{\sqrt{2\pi}},& \text{if } \hat{z} < 0\\
    \frac{e^{-\frac{\hat{z}^2}{2}}}{\sqrt{2\pi}}e^{-m\hat{z}},& \text{if } \hat{z} \ge 0
\end{cases}}{M_0}$
Is what i'm doing correct? For what it's worth, sampling points using the described procedure and calculating the mean and the variance of the sample, they agree with the analytical ones.

A: Sort of.  It looks like your math is correct, you're taking the total probability ($M_0$) and dividing each portion by that probability, normalizing it.  I'm assuming you have to find the expectation and variance for other parts of your problem, and those look fine as well.  The only thing I can see to look out for is that you say "accepting" and "rejecting" are the outcome states of your new random variable, $\hat{z}$, which leads me to think that the outcome states are $\{0,1\}$.  If that's the case, then you have to write the pdf in terms of whether or not the outcome is indeed $0,1$, not the outcome of your original standard normal, $z$.  This is probably easier, as you only have to take the probability that the result is accepted $(1/2 + \int_0^\infty\frac{e^{-\frac{z^2}{2}}}{\sqrt{2\pi}}e^{-mz}dz)$, and the probability that the result is rejected, which looks similar but without the 1/2, normalize that if needed (I don't think you will have to though), and call it a day by setting the resulting bernoulli variable to have those probabilities.
As an aside, this is my first answer so sorry if formatting or conventions are not up to par.


text:
Q: Kendo Scheduler - Event not showing I'm trying to show the events in the Kendo Scheduler but it's not working. I think it's because the JSON date format that is coming from the server is not in the correct format. Any help is appreciated.
@(Html.Kendo().Scheduler<TaskViewModel>()
.Name("Scheduler")
.Date(DateTime.Today)
.Views(views =>
{
    views.DayView();
    views.WeekView();
    views.MonthView();
})
.Timezone("Etc/UTC")
.DataSource(d => d
    .Model(m =>
    {
        m.Field(f => f.Title);
        m.Field(f => f.Start);
        m.Field(f => f.End);
        m.Field(f => f.IsAllDay);
    })
.Read(read => read.Action("GetScheduleEvent", "DataSource"))
)
)

JSON response
[{"RecurrenceRule":null,
  "RecurrenceException":null,
  "IsAllDay":true,
  "Start":"\/Date(1455775200000)\/",
  "StartTimezone":null,
  "End":"\/Date(1456034400000)\/",
  "EndTimezone":null,
  "Title":"Test Event"
}]

A: @Ram: There is no problem with the date format. Your JSON response is not in the correct format. It should be in this format
{"Data":[],"Total":55,"AggregateResults":null,"Errors":null}

My Guess is you might have forgotten to call ToDataSourceResult method as shown below
public virtual JsonResult Read([DataSourceRequest] DataSourceRequest request)
        {
            return Json(taskService.GetAll().ToDataSourceResult(request));
        }

I have created raw JsonData with the help of your JSON response. Below is the code snippet I used for testing and it is working. Hope this helps you!!
public ContentResult GetScheduleEvent([DataSourceRequest] DataSourceRequest request)
        {
            //string jsonString = "{\"Data\":[{\"RecurrenceRule\":null, \"RecurrenceException\":null,  \"IsAllDay\":false,  \"Start\":\"Sat Feb 20 2016 01:17:07 GMT-0700 (PDT)\",  \"StartTimezone\":null,  \"End\":\"Sat Feb 20 2016 04:17:07 GMT-0700 (PDT)\",  \"EndTimezone\":null,  \"Title\":\"Test Event\"}],\"Total\":1,\"AggregateResults\":null,\"Errors\":null}";
            string jsonString = "{\"Data\":[{\"RecurrenceRule\":null, \"RecurrenceException\":null,  \"IsAllDay\":true,  \"Start\":\"\\/Date(1455775200000)\\/\",  \"StartTimezone\":null,  \"End\":\"\\/Date(1456034400000)\\/\",  \"EndTimezone\":null,  \"Title\":\"Test Event\"}],\"Total\":1,\"AggregateResults\":null,\"Errors\":null}";
            return new ContentResult { Content = jsonString, ContentType = "application/json" };
        }


text:
Q: About the harmonic coordinate condition I'm trying to understand the alternative form of the harmonic coordinate condition, and I have two questions:
Why $(g^{{\mu \nu }}{\sqrt  {-g}})_{{;\rho }}=0$, and why do we obtain the term
$-g^{{\mu \nu }}\Gamma _{{\sigma \rho }}^{{\sigma }}{\sqrt  {-g}}$?

A: It is assumed that the metric satisfies the metric postulate, $\nabla_{\mu} g_{\nu \sigma} = 0$, or, in other words, the connection is metric compatible. This also implies $\nabla_{\mu} \sqrt{-g }= 0 = \nabla_{\mu} g^{\nu \sigma}$.
Remember that $\sqrt{-g }$ is actually a tensor density. We must be careful when expanding its (vanishing) covariant derivative. Let's try to not repeat the argument in the link you provided, instead let's use the old useful argument $\delta (\det M)= (\det M )\, \mathrm{Tr}[M^{-1}\delta M]$, for a matrix $M$. Extrapolating this for the case of a covariant derivative and considering the metric we have $\nabla_{\sigma} g = g \, g^{\mu \nu} \nabla_{\sigma} g_{\nu \mu} = - g \, g_{\mu \nu} \nabla_{\sigma} g^{\nu \mu}$, where we used $\nabla_{\sigma} (g_{\mu \nu} g^{\nu \mu}) = 0$. We have then
\begin{eqnarray}
0 &=& \nabla_{\sigma} \sqrt{-g} = - \frac{1}{2} \sqrt{-g} \, g_{\mu \nu} \nabla_{\sigma} g^{\nu \mu} = - \frac{1}{2} \sqrt{-g} \, g_{\mu \nu} (\partial_{\sigma} g^{\nu \mu}+\Gamma^{\nu}_{\sigma \alpha} g^{\alpha \mu}+\Gamma^{\mu}_{\sigma \alpha} g^{\nu \alpha})
\\
&=& - \frac{1}{2} \sqrt{-g} \, (g_{\mu \nu}  \partial_{\sigma} g^{\nu \mu}+2\Gamma^{\mu}_{\mu \sigma}) = - \frac{1}{2} \sqrt{-g} \,g_{\mu \nu}  \partial_{\sigma} g^{\nu \mu} - \sqrt{-g} \, \Gamma^{\mu}_{\mu \sigma}
\\
&=& \partial_{\sigma}\sqrt{-g} - \sqrt{-g} \, \Gamma^{\mu}_{\mu \sigma} \, .
\end{eqnarray}
In general we have then $0 = \nabla_{\sigma} \sqrt{-g}^W = \partial_{\sigma}\sqrt{-g}^W - W \sqrt{-g}^W \, \Gamma^{\mu}_{\mu \sigma}$ .


text:
Q: Memory use if multiprocessing queue is not used by two separate processes I have a thread in my python program that acquires images from a webcam and puts them in a multiprocessing queue. A separate process then takes these images from the queue and does some processing. However, if I try to empty the queue from the image acquisition (producer) thread I do not free any memory, and the program eventually uses all the available memory and crashes the machine (Python 3.6.6 / Ubuntu 18.04 64bit / Linux 4.15.0-43-generic)
I have a simple working example that reproduces the problem.
import multiprocessing
import time
import numpy as np

queue_mp = multiprocessing.Queue(maxsize=500)

def producer(q):
    while True:
        # Generate object to put in queue
        dummy_in = np.ones((1000,1000))

        # If the queue is full, get the oldest object (FIFO),
        # to make space for the latest incoming object.
        if q.full():
            __ = q.get()
        q.put(dummy_in)

def consumer(q):
    while True:
        # Get object from queue
        dummy_out = q.get()

        # Do some processing on the object, which we simulate here by time.sleep
        time.sleep(3)

producer_process = multiprocessing.Process(target=producer,
                                           args=(queue_mp,),
                                           daemon=False)

consumer_process = multiprocessing.Process(target=consumer,
                                           args=(queue_mp,),
                                           daemon=False)

# Start producer and consumer processes
producer_process.start()
consumer_process.start()

I can rewrite my code to avoid this problem, but I'd like to understand what is happening. Is there a general rule that producers and consumers of a multiprocessing queue must be running in separate processes?
If anyone understands why this happens, or what exactly is happening behind the scenes of multiprocessing queues that would explain this memory behavior I would appreciate it. The docs did not go into a lot of detail.

A: I figured out what was happening, so I'll post it here for the benefit of anyone that stumbles across question.
My memory problem resulted from a numpy bug in numpy version 1.16.0. Reverting to numpy version 1.13.3 resolved the problem.
To answer the basic question: No, there is no need to worry which thread/process is doing the consuming (get) and which thread/process is doing the producing (put) for multiprocessing queues. There is nothing special about multiprocessing queues with respect to garbage collection. As kindall explains in response to a similar question:

When there are no longer any references to an object, the memory it occupies is freed immediately and can be reused by other Python objects

I hope that helps someone. In any case, the numpy bug should be resolved in the 1.16.1 release.


text:
Q: Preparing data for deeplearning4j I want to predict classifications of data that has the form:
classifier;a textual description
e.g.

*

*car;a vehicle with 4 wheels

*house;a building with a roof

*mouse;gray animal that frightens my mother

I started with the following, but this gets me to a number format exception
    RecordReader recordReader = new CSVRecordReader(1, ';');
    recordReader.initialize(new FileSplit(new File(csvFilePath)));

    DataSetIterator iterator = new RecordReaderDataSetIterator(recordReader,batchSize,labelIndex,numClasses);
    return iterator.next();

Apparently I need to prepare that data first to create a numerical representation.
The DL4j samples are build on already prepared data.
Is there a sample that starts with a setting similar to mine?

A: You typically use our ETL library datavec for that.  I'm not sure where you were looking, but the examples have numerous examples of pre processing data in csv, image and text. It depends on what you're doing.
For CSV, you found the right starting point. That will load from a directory of CSVs.
In our case with one of the examples in there I'm citing:
 int numLinesToSkip = 0;
 char delimiter = ',';
  String localDataPath = DownloaderUtility.IRISDATA.Download();
RecordReader recordReader = new CSVRecordReader(numLinesToSkip,delimiter);
recordReader.initialize(new FileSplit(new File(localDataPath,"iris.txt")));
int labelIndex = 4;
int numClasses = 3;
DataSetIterator iteratorA = new RecordReaderDataSetIterator(recordReaderA,10,labelIndex,numClasses);

This will setup a record reader for parsing the data, you initialize it to point that reader at a particular file or directory (that's data that can be anything)
If you want something more complex, you typically either hand code the pipeline yourself or use datavec's transform process.
It really depends on your use case.
As for your specific problem with a NumberFormatException, I'm not really sure what to say.
As anyone on here would ask for, I'd need the complete context (the stack trace, full error message not a partial description,..)
Going on what I have, it's probably because you're tossing in words or something that's not a number. All machine learning involves converting everything (doesn't matter what) to numbers. I don't want to do a whole ML course in 1 post, but if you can be more specific I can give you hints as to what you need to do for your particular case.


text:
Q: Pre-requisites for learning CRM Dynamics I am not sure if this is a valid question here but couldn't find an answer elsewhere. I am just about to starting training on Microsoft Dynamics CRM and with just over an year of experience with asp.net, a little bit of JavaScript, HTML and CSS, I am not sure if I am headed the right way.
Is this sufficient? What skills should I try to sharpen up before starting with Dynamics?

A: Dynamics CRM is probably the most flexible system I have ever worked on. You can extend it and make it do just about anything. So the first thing you will want to learn about is the different vectors or customization. You can customize CRM in several different ways and each has it merits and drawbacks:

*

*Javascript [Client side only]. Note that CRM doesn't support customization by directly accessing the DOM, rather you work through XRM exposed interfaces. It allows practical GUI and data manipulation though through REST and FetchXML queries.

*Workflows. These are rules you can program via the "point and click" interface. It allows you to monitor when certain actions happen and then react accordingly. These run server side so it is independent of the client. The system ships with lots of rules, but custom rules can be written to extend these almost infinitely.

*Plugins. Similar to workflows but these fire immediately after subscribed to events. You can do things here like perform validation (which you can also do in Javascript, but plugins are server side) and manipulate data on or after saves.

For custom workflows and plugins, you will definitely need to be familiar with .NET (at least 4.0). You can use either C# or VB.NET, but the Visual Studio integration (which is really nice) is limited to C#. You can use VB.NET but it requires a lot of manual configuration so I wouldn't recommend it given the choice between the two. At the time of this writing, however, the Visual Studio integration is limited to VS 2010 and VS 2012 Professional.
This is just a primer, there is lots more info on MSDN and there are tons of blogs available to help you get started. Of course you can always post your specific questions here on SO for help...
Good luck to you.


text:
Q: .Net Matrix Is there a standard .Net matrix class? I cannot find it if there is.
If not, why not? It sounds like something people would need very frequently. Are there any non-standard libs you could recommend?

A: The XNA Framework has a Matrix structure. I'm not aware of any part of the main framework that has a Matrix class though.
http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.matrix.aspx

A: I don't believe there is, partially because any array can technically be called a "Matrix" if it is a single dimension array of length n, it is an n x 1 matrix.  There is also the question of whether you'd want the matrix to hold integers, doubles, or other numerical values that may play a role in some Matrix functions.
There do exist various places like here and here that may bundle some Matrix classes with other Linear Algebra functions.

A: You can find a Matrix class in the Lydos.MatLab library (documentation), which is distributed as open source project under the zlib/libpng license.
Example usage in C#:
using Lydos.Matlab;
using System;

public class Example
{
    static void Main()
    {
        Engine e = new Engine();
        Matrix m = new Matrix(2, 2), n;

        m[0, 0] = 0;
        m[0, 1] = 1;
        m[1, 0] = 2;
        m[1, 1] = 3;

        e.SetMatrix("m", m);
        e.Evaluate("m = m + 1");
        n = e.GetMatrix("m");

        Console.WriteLine(m); // [0 1; 2 3]
        Console.WriteLine(n); // [1 2; 3 4]

        m.Dispose();
        n.Dispose();
        e.Close();
    }
}


text:
Q: Angular 2 form elements' attributes - correct syntax? I was reading this artcle and in the article I see:

<input type="search" [formControl]="seachControl">

and

<input type="text" formControlName="street">

I am wondering what the correct syntax is for stating formControl and formGroup. Can I do something like
<input type="text" [formControlName]="street">
or
<input type="text" [attr.formControlName]="street">
or
<input type="text" [formControl]="street">? And more specifically how do the three instances differ?

A: [formControl]="seachControl" is what we call model binding, it's binding to the main form element i.e. search.
When you have a single form Element, i.e. search you're just simply model binding it to whatever variable you created inside your class and do keep in mind the type of the variable you bind to.
and as for the
<input type="text" formControlName="street">

since street here was created inside the main formControl element you don't have direct access to street variable. so what this directive is doing is telling that the main/parent element that this tag is should bind to the street you created inside the main formControl.
As for
<input type="text" [formControlName]="street">

I don't know but I think the formControlName doesn't actually do the binding it is sort of telling what this tag needs to bind to. And the syntax suggests that it will try to look for street variable inside your class bind it.
as you can see he says.

This is where the formControlName directive comes into play. It's pretty much the equivalent of an ngModel and name attribute combination in template-driven forms. Each form control gets a formControlName directive applied so we can register the controls on the outer form

So you only need to bind the outer model since that exists/instantiated in your class and formControlName and formGroupName will take care of the inner elements.


text:
Q: Swift/ios wave fill animation inside custom layer/shape I am trying to achieve a fill animation similar to the GIF below but inside a non circular boundary similar to the second image. Can this be done over a UIImage of just the drop?

A: Sure, you could do that with a CAShapeLayer where you animate the path that draws the shape. You'd then add a mask layer to the shape layer that masks it to the shape of the drop, (which would be another shape layer in the shape of your drop.)
You should be able to get the shape of the wave with a single cubic bezier curve, as wide as the widest part of the area you're filling. You'd create a closed shape that was your wave curve, then the sides and bottom of a rectangle to create a closed shape.
For the wave animation I would suggest a closed UIBezierPath that is 3 sides of a rectangle, followed by a cubic bezier curve who's start and end where on the top corners of your rectangle, and the middle two control points were at 1/4 and 3/4 of the way along the rectangle in the X dimension. Make one of those control points above the top line of your box, and the other below the top line. The animation would just be switching the Y positions of the 2 middle control points of the bezier curve.
Here is what the shape looks like in Photoshop:

Make that bezier path wider than your drop shape, so the ends of the top curve that don't move are out of view.
You'd install the CGPath of that bezier path into a CAShapeLayer. You'd then add a repeating, auto-reversing CABasicAnimation to the shape layer that would swap the Y positions of the two middle control points of the top curve, so the wave peaks and troughs would switch.
Next, you'd create a second CAShapeLayer that would contain a closed drop shape, and install the drop shape layer as a mask on the wave layer.
Finally, as you change your slider, you'd shift the Y position of your entire wave shape layer up and down.


text:
Q: Driver not loaded mySql Estoy usando Pycharm con Python3.9 y PyQt 5.15.2 y QSqlDatabase
He seguido las instrucciones en https://doc.qt.io/qt-5/sql-driver.html#qmysql How to Build the QMYSQL Plugin on Windows. He usado el compilador mingw81_64
El fichero qsqlmysql.dll se ha generado y lo he copiado a  PyQt5/Qt/plugins/sqldrivers a mi entorno virtual.
También he copiado el fichero libmydql.dll a PyQt5/Qt5/bin a mi entorno virtual.
Si ejecuto database.drivers() obtengo lo siguiente
['QSQLITE', 'QMARIADB', 'QMYSQL', 'QMYSQL3', 'QODBC', 'QODBC3', 'QPSQL', 'QPSQL7']
Me da el siguiente error
"Driver not loaded"
También he intentado descargar el fichero qsqlmysql.dll de https://github.com/weldermarcosxd/pyqt5-mysql/blob/master/Lib/site-packages/PyQt5/Qt/plugins/sqldrivers/qsqlmysql.dll
pero me da el mismo error
Estoy usando esta base de datos https://remotemysql.com/
class Login(QWidget):
def __init__(self):
    super().__init__()
    self.init_widgets()
    self.set_styles()
    self.connect()

def connect(self):
    server = 'remotemysql.com'
    database_name = '****'
    user_name = '****'
    password = '****'

    self.database = QSqlDatabase.addDatabase("QMYSQL")
    self.database.setHostName(server)
    self.database.setDatabaseName(database_name)
    self.database.setUserName(user_name)
    self.database.setPassword(password)
    ok = self.database.open()
    if ok:
        print('Success')
    else:
        print(self.database.lastError().text())

app = QApplication(sys.argv)
window = Login()
window.show()
app.exec_()


text:
Q: kivy or something else for android UI I am learning to program (python 3.x) and was wondering what would be best to learn for making android apps/games. I dont know anything about UI really but have heard that kivy? Is on android. Is that worth learning or should i use something else.
Thanks
Edit:
I am using sl4a and py34a on my android device.

A: Kivy is good, and will run on Android, but you can't make Android apps with it. It has no way of interacting with the Android API. You can run a kivy app on the device, but can not read sensors or anything like that. They have a project called pyjnius, which allows you to access Java classes from Python, but not with Python3, and it's not very easy to use unless you know Java.
You have SL4A installed, so you can use web technology to do UIs, including games, which can be rendered on the device using webviews. That said, Kivy is a much more mature and well maintained project.

A: I'm loving kivy. The irony is, that I found this topic here looking for help with python 3. Python 2 works perfectly, but 3 is still being made compatible. Other than that Kivy is great for beginner coders. Especially, because you don't have to code the complex stuff.


text:
Q: Need help with an inverse function $$g(x) = \frac{100}{1+2^{-x}}$$
Ok, i have this expression and my task is to find the inverse. My answer to that is -ln2((100-x)/x). Which is wrong when i test it. Can someone help me with this?

A: $g(x)=\frac{100}{1+2^{-x}}\implies$
$g(x)\cdot(1+2^{-x})=100\implies$
$1+2^{-x}=\frac{100}{g(x)}\implies$
$2^{-x}=\frac{100}{g(x)}-1\implies$
$-x=\log_2(\frac{100}{g(x)}-1)\implies$
$x=-\log_2(\frac{100}{g(x)}-1)$

A: $$g(x) = \frac{100}{1+2^{-x}}$$
$$\frac{100}{g(x)} = 1+2^{-x}$$
$$\frac{100}{g(x)} -1 = 2^{-x}$$
$$\ln\left(\frac{100}{g(x)} -1\right) / \ln(2) = -x$$
$$-\ln\left(\frac{100}{g(x)} -1\right) / \ln(2) = x$$

A: I can let $y=\frac{100}{1+2^{-x}}$.
$$ 1+2^{-x} = \frac{100}{y}$$
$$ 2^{-x} = \frac{100}{y}-1$$
$$ 2^{-x} = \frac{100-y}{y}$$
$$2^x = \frac{y}{100-y}$$
$$x = \log_2 \left ( \frac{y}{100-y}\right)$$


text:
Q: How does a probability density function of a random variable is induced due to Radon-Nikodyn derivative? If someone can please clarify the following for me:
Given a probability space $(\omega,\Sigma,P)$ and a continous random variable $X:w \rightarrow \mathcal{R}$.
I have read the statement of the Radon-Nikodyn Theorem, but I still can't see how does one relate it to the existance of a probability density function. Can someone please elaborate on this?
Thanks

A: Let $\mathbb P_X$ the measure on $\mathbb R$ defined by $$\mathbb P_X(B):=\mathbb P\{X\in B\},$$
for all Borel set $B\subset \mathbb R$.

Definition Let $m$ denote the Lebesgue measure on $\mathbb R$. Then, $X$ is continuous if $\mathbb P_X$ is absolute continuous with respect to $m$.

Therefore, by Radon-Nikodym, there is $f:\mathbb R\to \mathbb R$ s.t. $$\frac{\mathrm d \mathbb P_X}{\mathrm d m}=f,$$
i.e. $$\mathbb P_X(B)=\int_B f(x)m(\mathrm d x).$$
Therefore, $X$ has a density $f$.


text:
Q: $this->getUser() in Symfony controller functional test returns null I'm trying to test a controller that uses $this->getUser()->getUsername(). It complains that getUsername() is called on null.
Here is my client login code from the test class
protected function logInAsAdmin(Client $client): void
    {
        $session = $client->getContainer()->get('session');

        $firewallName = 'main';
        $firewallContext = 'main';

        $roles = [
            'ROLE_USER',
            'ROLE_ADMIN',
        ];

        $token = new UsernamePasswordToken('admin', null, $firewallName, $roles);
        $session->set('_security_' . $firewallContext, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $client->getCookieJar()->set($cookie);
    }

And here is what the controller does:
public function home(EmployerRepository $employerRepository, AuthorizationCheckerInterface $authorizationChecker): Response
    {
        if ($authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
            $jobs = [];

            foreach ($employerRepository->findBy(['owner' => $this->getUser()->getUsername()]) as $employer) {
                $jobs = array_merge($jobs, $employer->getJobs()->toArray());
            }

            return $this->render('home.html.twig', ['jobs' => $jobs]);
        }

        return $this->redirectToRoute('login');
    }

Can anyone tell me why this does not work? I tried instantiating a user object and passing that into the UsernamePasswordToken, but no luck with that either.
using Symfony 4.
The test:
/**
     * @test
     */
    public function indexPageIsRenderedWhenLoggedIn(): void
    {
        $client = static::createClient();
        $this->logInAsAdmin($client);
        $client->request('GET', '/');
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertRegExp('/Your jobs/', $client->getResponse()->getContent());
    }

A: Wanted to let everyone know that I solved my problem by injecting the TokenStorageInterface into my controller, and getting the username via $tokenStorage->getToken()->getUsername()

A: Try to return $client from logInAsAdmin function
protected function logInAsAdmin(Client $client): Client
{
    $session = $client->getContainer()->get('session');

    $firewallName = 'main';
    $firewallContext = 'main';

    $roles = [
        'ROLE_USER',
        'ROLE_ADMIN',
    ];

    $token = new UsernamePasswordToken('admin', null, $firewallName, $roles);
    $session->set('_security_' . $firewallContext, serialize($token));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $client->getCookieJar()->set($cookie);
    return $client;
}

and use in test:
 /**
 * @test
 */
public function indexPageIsRenderedWhenLoggedIn(): void
{
    $client = static::createClient();
    $client = $this->logInAsAdmin($client);
    $client->request('GET', '/');
    $this->assertEquals(200, $client->getResponse()->getStatusCode());
    $this->assertRegExp('/Your jobs/', $client->getResponse()->getContent());
}


text:
Q: ffmpeg does not recognize audio stream in video I have these flv files that exported from Adobe Connect and I want to extract their audio with ffmpeg. ffmpeg does not recognize the audio on some of them. This log is from one file that has issues:
>ffmpeg.exe -i r7anupl75gl_0_1965937.flv test1.mp3
ffmpeg version N-76123-g002b049 Copyright (c) 2000-2015 the FFmpeg
built with gcc 5.2.0 (GCC)
configuration: --enable-gpl --enable-version3 --disable-w32threads
libavutil      55.  4.100 / 55.  4.100
libavcodec     57.  7.100 / 57.  7.100
libavformat    57.  8.102 / 57.  8.102
libavdevice    57.  0.100 / 57.  0.100
libavfilter     6. 11.100 /  6. 11.100
libswscale      4.  0.100 /  4.  0.100
libswresample   2.  0.100 /  2.  0.100
libpostproc    54.  0.100 / 54.  0.100
[flv @ 0000000000522140] Could not find codec parameters for stream 1

(Audio: none, 0 channels): unknown codec
Consider increasing the value for the 'analyzeduration' and 'probesize'
options
Input #0, flv, from 'r7anupl75gl_0_1965937.flv':
Metadata:
lasttimestamp   : 5026
lastkeyframetimestamp: 5022
audiodelay      : 0
canSeekToEnd    : false
creationdate    : unknown
metadatacreator : Manitu Group FLV MetaData Injector 2
videosize       : 251586025
audiosize       : 55776880
datasize        : 516
Duration: 01:23:47.75, start: 0.000000, bitrate: 489 kb/s
Stream #0:0: Video: vp6f, yuv420p, 1184x704, 1k tbr, 1k tbn, 1k tbc
Stream #0:1: Audio: none, 0 channels
Output #0, mp3, to 'test1.mp3':
Output file #0 does not contain any stream

Note: audio codec is Nellymoser Asao and this command works successfully for some files.

A:
Consider increasing the value for the 'analyzeduration' and 'probesize'

The problem is in first 10-15 min the flv file doesn't actually have any audio. By increasing probesize and analyzeduration it looks further in the file to find audio and detect it.
In my scenario I have to set analyzeduration bigger than 5000000 (5 seconds).


text:
Q: Add an integer to a key of an array PHP let's say we have the following array:
Array ( [0] => 123456 [1] => Rothmans Blue [2] => 40 [3] => RB44 [4] => 1 )

I want to reprint this array, with the [4]th key having an additional +1, like so:
Array ( [0] => 123456 [1] => Rothmans Blue [2] => 40 [3] => RB44 [4] => 2 )

Then again:
Array ( [0] => 123456 [1] => Rothmans Blue [2] => 40 [3] => RB44 [4] => 3 )

EDIT: The solutions given below work, however, my code does not increment the 4th key:
$filew = 'databases/stocktakemain.csv';
$getfilecont = file_get_contents($filew);
$writes = explode(",", $getfilecont);
++$writes[4];

Is there an issue with this code? Does this not apply when creating arrays through explode?

A: You can use end($array) function and get the last element and then add.

A: At the end of your code, you can put
Array[4] == Array[4] + 1;

A: you can use the ++ to incremente in 1 your 4th array value
<?php

$array[0] = 123456;
$array[1] = 'Rothmans Blue';
$array[2] = 40;
$array[3] = 'RB44';
$array[4] = 1;

echo ++$array[4] . "
\n";
echo ++$array[4] . "
\n";
echo ++$array[4] . "
\n";
?>

A: This will print out 10 arrays with that last key being an incrementing number, change the $max to make it bigger/smaller.
$max = 10;

for( $i=1; $i<=$max; $i++ ) {
    print_r( array(
        123456,
        'Rothmans Blue',
        40,
        'RB44',
        $i
    ));
}

A: In this case, you don't actually need to declare the key values as PHP considers the index of a value in an array to be its key.
You might try something like this if you want to print the values, then increment:
$myArray = array(123456, "Rothmans Blue", 40, "RB44", 1);
for ($i= 0; $i < 3; $i++)
{
  foreach ($myArray as $key => $value)
  {
    print $key . " : " . $value;
    if ($key == 4)
    {
      print "\n";
      $myArray[$key] += 1; // Make sure to modify the original array, not the one you passed in as it is passed by reference.
    }
  }
}

If you want to increment and then print, move the print statement to the bottom of the foreach loop.


text:
Q: Convert Recursive to Closed Formula I got a particular sequence defined by the following recursive function:
$$T_n = T_{n-1} \times 2 - T_{n-10}$$
I need help converting it to a closed form so I can calculate very large values of n efficiently.
The sequence that I produced this recursive formula from is:
n = 1 to 10:    1,1,2,4,8,16,32,64,128,256
n = 11 to 15:   511,1021,2040,4076,8144
The formula is "quirky" for 1 to 10, but works exactly as stated for all n > 10;

A: ok. There is a general way to solve linear recursions as yours, see for starting the Wikipedia article. The basic idea is to look for solutions of the form $T_n = \lambda^n$. Inserting this ansatz into the equation we obtain
$$
  \lambda^n = 2\lambda^{n-1} - \lambda^{n-10}
$$
and after dividing by $\lambda^{n-10}$
$$
  \lambda^{10} - 2\lambda^9 + 1 = 0
$$
Now you have to find all $\lambda_i$, $i = 1,\ldots, 10$ which solve this equation. Wolfram|Alpha helps. Now one can show, that $\{(\lambda_i^n)_{n\ge 0}\mid 1 \le i \le 10\}$ is a basis of the space of all sequences which fulfill your recursion. Now we put your initial values into the ansatz $T_n = \sum_{i=1}^{10} a_i \lambda_i^n$. We obtain (with $\lambda_1 = 1$)
\begin{align*}
  a_1 + a_2\lambda_2 + a_3\lambda_3 + \cdots + a_{10}\lambda_{10} &= 1\\\
  a_1 + a_2\lambda_2^2 + a_3\lambda_3^2 + \cdots + a_{10}\lambda_{10}^2 &= 1\\\
  \vdots &= \vdots\\\
  a_1 + a_2 \lambda_2^{9} + a_3 \lambda_3^{9} + \cdots + a_{10}\lambda_{10}^{9} &= 128\\\
  a_1 + a_2 \lambda_2^{10} + a_3 \lambda_3^{10} + \cdots + a_{10}\lambda_{10}^{10} &= 256
\end{align*}
a linear system for $a_1, \ldots, a_{10}$. You have to solve this for $a_1, \ldots, a_{10}$.
The problem is, as suggested by Wolfram|Alpha, the roots of your equation besides $\lambda_1 = 1$ are diffucult, if not ipossible, to write in closed form.
Hope this helps,

A: For what it's worth,
$$T_n = 2^n - 2^{n-10} \sum _{k = 0} ^{\lfloor \frac n 9 - 1 \rfloor} \binom {n-9k-8} {k+1} 2^{-10k} (-1)^k \frac {n-8k-7} {n-9k-8}$$


text:
Q: line breaks after Java annotations in Scala code I have a code that compiles successfully:
import javax.ws.rs.Path

trait DescriptionHandler extends ServiceAwareHandler {
  @Path("/descriptions")
  def getDescriptionsRoute: Route = ...
}

and it would not compile if I add a line break after Path annotation like this:
import javax.ws.rs.Path

trait DescriptionHandler extends ServiceAwareHandler {
  @Path("/descriptions")

  def getDescriptionsRoute: Route = ...
}

In IntelliJ IDEA it look like javax.ws.rs.Path is absent in class path.
Compiler telling me this:
Error:(19, 1) expected start of definition
  def getDescriptionsRoute: Route =

What's the problem with line breaks between Java annotations and Scala methods / fields? I tried to google the issue but didn't found anything useful.

A: In Scala Spec/Lexical syntax/1.2 Newline characters there is an explicit statement about this case:

A single new line token is accepted

*

*...

*after an annotation.

And when there is an empty line:

if two tokens are separated by at least one completely blank line (i.e a line which contains no printable characters), then two nl tokens are inserted.

Thus blank lines are not accepted between annotation and definition.


text:
Q: Prove that the sequence is bounded (proof verification) Problem
Let $f:\mathbb{R}\to\mathbb{R}$ be a differentiable function such that its derivative $f'$ is a continuous function. Moreover, assume that for all $x\in\mathbb{R}$, $$0\leqslant \vert f'(x)\vert\leqslant \frac{1}{2}$$Define a sequence of real numbers $\{a_n\}_{n\in\mathbb{N}}$ by :$$a_1=1~~\text{and}~~a_{n+1}=f(a_n)~\text{for all}~n\in\mathbb{N}$$Prove that there exists a positive real number $M$ such that for all $n\in\mathbb{N}$, $$\vert a_n\vert \leqslant M$$
My Proof
Notice that $$|a_{n}-a_{n-1}|=|f(a_{n-1})-f(a_{n-2})|=|f'(\xi)||a_{n-1}-a_{n-2}|\leq \frac{1}{2}|a_{n-1}-a_{n-2}|,$$where $n=3,4,\cdots$, and $a_{n-1} \gtrless \xi \gtrless a_{n-2}.$ Hence, $$|a_{n}-a_{n-1}|\leq \frac{1}{2}|a_{n-1}-a_{n-2}|\leq \frac{1}{2^2}|a_{n-2}-a_{n-3}|\leq \cdots \leq \frac{1}{2^{n-2}}|a_2-a_1|.$$Therefore,\begin{align*}|a_n-a_1|&=|(a_n-a_{n-1})+(a_{n-1}-a_{n-2})+\cdots+(a_2-a_1)|\\&\leq |a_n-a_{n-1}|+|a_{n-1}-a_{n-2}|+\cdots+|a_2-a_1|\\&\leq \left(1+\frac{1}{2}+\frac{1}{2^2}+\cdots+\frac{1}{2^{n-2}}\right)|a_2-a_1|\\&\leq 2|a_2-a_1|.\end{align*}Hence, $$|a_n|\leq 2|a_2-a_1|+|a_1|$$for $n=3,4,\cdots$. But we can verify that it also holds for $n=1,2$. Now, take $M=2|a_2-a_1|+|a_1|$. We obtain $$|a_n|\leq M$$ for $n=1,2,\cdots$.This is exactly what we want to prove.


text:
Q: What is the best way to do this in ASP.NET MVC3? I want to have a form which has a simple 2 step process:
(If a person on has one school assigned to them then skip straight to step 2)
Step 1 - Select a school from a drop-down list
Step 2 - Enter the required data from a data-entry form. Certain fields are disabled based on which school was selected.
I have had a look at the various methods for creating 'wizards' and at using partial Views. What is the best way to handle this? I was wondering if using AJAX is worthwhile considering or just having a two step process in the form.
James :-)

A: You should absolutely do this via ajax so your options are either

*

*use small partial views. your view logic determines what to disable/enable

*(probably easier and more lightweight) use json to get a list of property names to disable.Then you can simply disable them via jQuery ideally by iterating through each item with the .each() call.
See: looping through JSON array in a jQuery list
for a use of the each call.
got jQuery getJson, see: http://api.jquery.com/jQuery.getJSON/
so:
1. getJson to get the results from a controller
2. enumerate using .each() and set the property
 $("#" + yourFieldName).attr("disabled","disabled");


text:
Q: How to split up embedded Ruby string in shell command Writing a web2py on Cloud SQL boon using Gitbookl. It contains the following line of OSX bash shell code:
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Would like to shorten the display to 40-60 characters per line while still allowing the user to copy and paste the code in. All of my experiments are failing, but obviously I want to do something like this:
$ ruby -e "$(curl -fsSL\
https://raw.githubusercontent.com/\
Homebrew/install/master/uninstall)"

No longer a Ruby guy and am at wit's end. Can someone tell me how to get a copy/pasteable line like this into my markdown?
(The general problem is that ebooks are limited to 40-60 columns in code printouts, and I need a way to handle long paths and long paths.)

A: Something like this should to the trick..
domain="raw.githubusercontent.com"
url="Homebrew/install/master/uninstall"

ruby -e "$(curl -fsSL https://${domain}/${url})"

A: steeldriver nailed it. The answer was to insert a space before the slash at the end of the first line, so:
ruby -e "$(curl -fsSL \
https://raw.githubusercontent.com/\
Homebrew/install/master/uninstall)"

That can indeed be copy and pasted right into the shell prompt.
As soon as the Nobel committee sees fit to make me one of their own I am going to nominate steeldriver for something.

A: You can also do:
$ curl -fsSL https://raw.githubusercontent.com/\
Homebrew/install/master/uninstall|ruby


text:
Q: Choosing Dense sets More than one option can be correct.

Which of the following sets are dense in $R^2$ with respect to the usual topology.
(a) $\{(x,y)\in R^2:x\in N\}$
(b) $\{(x,y)\in R^2:x+y$ is a rational number$\}$
(c) $\{(x,y)\in R^2:x^2+y^2=5\}$
(d) $\{(x,y)\in R^2:xy\ne0\}$

Natural numbers are not limit points of real numbers. So, (a) is rejected.
Rational numbers can be limit points to irrational numbers, so (b) is selected.
We can draw a circle of radius $\sqrt5$ anywhere in the plane. So, I assume every point can be covered by this circle. So I would say it is also a dense set. If it is not then which set of points is it not covering?
$xy=c$ is a hyperbola with coordinate axes as its asymptotes. So, it will not cover all the points of the plane. So, (d) is rejected.
But answer is given as (b) and (d).

A: Option (c) cannot possibly be a dense set since it is bounded. For example, its intersection with the non-empty open set $\;\{(x,y)\in\Bbb R^2\;;\; (x-10)^2+(y-10)^2<1\}\;$  is the empty set...
And (d) is not a hyperbola but, in fact, the union of all the possible hyperbolas on the plane! Or, in other words, (d) d is the set of all points on the plane which are not on any of the two axis. It intersects every non-empty open set in the planes and it is thus dense there.

A: Your answers to (a) and (b) are correct, but your reasons aren't really sufficient, especially for (b). I'll come back to those.
The set in (c) is specifically the circle of radius $\sqrt5$ centred at the origin: it's a closed set in $\Bbb R^2$, and it's not all of $\Bbb R^2$, so it cannot be dense in $\Bbb R^2$.
The set in (d) contains every point $\langle x,y\rangle$ such that $x\ne 0$ and $y\ne 0$: that's the whole plane except the coordinate axes. Every point on the coordinate axes is the limit of a sequence from this set, so the closure of this set is $\Bbb R^2$, and this set is therefore dense in $\Bbb R^2$.
The points of (b) are the ones that lie on lines with slope $-1$ and rational $x$- and $y$-intercepts. This set is dense in $\Bbb R^2$, but in order to show that you must show that its closure is all of $\Bbb R^2$; it's not enough to say that the rationals are dense in the reals.
Finally, the set in (a) is $\Bbb N\times\Bbb R$; since $\Bbb N$ is closed in $\Bbb R$, this set is closed in $\Bbb R^2$. It clearly isn't all of $\Bbb R^2$, so it cannot be dense in $\Bbb R^2$.


text:
Q: How do I plug in a usb-drive? Problem
After using the following command on my usb-drive (/dev/sdd):
# physically plugging usb-drive in at /dev/sdd
> umount /dev/sdd1
> eject /dev/sdd

I am unable to undo this last action. How do I mount the drive again, programmatically?
Physical access to the device is not an option, and neither is rebooting.

What did you try?
As you will see, the regular stuff won't work.
> mount /dev/sdd1
mount: /dev/sdd1: can't find in /etc/fstab.

We can see /dev/sdd1 does not exist anymore:
> ls /dev/sdd*
/dev/sdd

So let's try to undo eject by using the same utility again:
> eject --trayclose /dev/sdd
> ls /dev/sdd*
/dev/sdd

This does not seem to do anything, so let's bind the usb-drive to the driver.
> udevadm info /dev/sdd | grep DEVPATH
E: DEVPATH=/devices/pci0000:00/0000:00:14.0/usb1/1-1/1-1:1.0/host6/target6:0:0/6:0:0:0/block/sdd
> echo -n "1-1:1.0" > /sys/bus/usb/drivers/usb-storage/unbind
> ls -d /sys/bus/usb/drivers/usb-storage/1-1\:1.0
ls: cannot access '/sys/bus/usb/drivers/usb-storage/1-1:1.0': No such file or directory
> echo -n "1-1:1.0" > /sys/bus/usb/drivers/usb-storage/bind
> ls -d /sys/bus/usb/drivers/usb-storage/1-1\:1.0
1-1:1.0

Ok, so the unbind and bind worked. This is not the problem nor solution. Also, the device still seems to be powered. Let's try to trigger something.
> udevadm trigger --name-match=/dev/sdd

This does not seem to solve the problem either. Now let's try to read the partition table again, because /dev/sdd exists but /dev/sdd1 not. I found three different methods of achieving this:
> partprobe /dev/sdd
Error: Error opening /dev/sdd: No medium found
> hdparm -z /dev/sdd

/dev/sdd:
 re-reading partition table
> partx -u /dev/sdd
partx: cannot open /dev/sdd: No medium found
> ls /dev/sdd*
/dev/sdd

Still no /dev/sdd1. Maybe try some rescan:
> echo 1 > /sys/block/sdd/device/rescan
> ls /dev/sdd*
/dev/sdd

Still nothing, let's verify what fdisk says about this:
> fdisk -l | grep sdd

Okay, nothing. Let's try to reset the usb-drive then.
> echo 0 > /sys/bus/usb/devices/1-1\:1.0/authorized
> echo 1 > /sys/bus/usb/devices/1-1\:1.0/authorized
> ls /dev/sdd*
ls: cannot access '/dev/sdd*': No such file or directory

This made it worse, trial and error failed. I give up. What am I missing here?

*facepalm* why eject at all?!
Well, I need this solution for actually another problem, in which Linux does not want to mount the usb-drive anymore after i/o errors occurred. Since physically plugging the usb-drive back in works for that problem, I need to know how to do this programmatically. And even if this will not solve my original problem, I want to know how to undo eject.

EDIT: More details
Here is an additional source from kernel.org on usb hotplugging, telling what should be happening:

*

*Find a driver that can handle the device. That may involve loading a kernel module; newer drivers can use module-init-tools to publish their device (and class) support to user utilities.

*Bind a driver to that device. Bus frameworks do that using a device driver's probe() routine.

*Tell other subsystems to configure the new device. Print queues may need to be enabled, networks brought up, disk partitions mounted, and so on. In some cases these will be driver-specific actions.

It seems that the last step may still need to be done. Backed by further info on the state of the usb-drive after it is "ejected", showing that the usb-drive is powered and Linux can communicate with it:
> cat /sys/block/sdd/device/state
running
> cat /sys/block/sdd/device/power/runtime_status
active
> cat /sys/block/sdd/device/power/runtime_suspended_time
0
> cat /sys/block/sdd/device/power/control
on

A: If the device is not a CDROM drive, eject falls back to a generic SCSI "START STOP" command, with option "eject" set.
It's possible to send the reverse, "START STOP" with the "start" option, using sg_start -s.  sg_start is available as part of the sg3_utils package on most distributions.
Apparently sg_start -s was sufficient to restart the drive in this case.  sg_start --load was not required.  (This makes sense to me, because I don't see this as an eject having taken place).
Other users have claimed that this doesn't work.  USB drive controllers particularly for small flash drives can be a bit weird, so I wouldn't be surprised if some drives refused this command.
https://unix.stackexchange.com/a/394961/29483

The USB controller in a flash ROM stick usually reacts by powering down the device and preventing any further interaction. That means it disappears completely from the USB subsystem, and must be re-enumerated to be able to accessed again.
The same command when send e.g. to a CD/DVD drive will eject the disk, and the also existing "load" option of the "START STOP" command will load it again. But this interpretation only applies to devices with removable media.


text:
Q: Shortest way to generate 20 random numbers with specific range I need to generate an array containing 20 random numbers between 1 and 200. Is there a shorter/cleaner code I can use?
<?php
$x= array (rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200),rand(1,200));
echo '<pre>'; print_r($x); echo '</pre>';
?>

A: No loops needed.
Use range to create all numbers between 1-200, shuffle it and grab the first 20 items in the array with array_slice.
$range = range(1,200);
shuffle($range);
$random = array_slice($range,0,20);
var_dump($random);

https://3v4l.org/fI9WZ

A: <?php
$arr = array();
for($i=0; $i<20; $i++){
  $random_num = rand(1,200);
  array_push($arr, $random_num);
}

?>


text:
Q: Oracle: How to Rewrite UNION for Performance I have ORACLE UNION SQL which is working fine.
Can you please help me find alternatives of rewriting the SQL:
SELECT *
FROM (
  select app_id, org_id, emp_id, name, name_id,
  from TableA AAA, TableC CCC, TableB BBB
  where BBB.ID=CCC.ID
  AND AAA.ID=BBB.ID
UNION
  select app_id, org_id, emp_id, name, name_id,
  from TableA AAA, TableC CCC,TableD DDD
  where DDD.ID=CCC.ID
  AND AAA.ID=DDD.ID
) MYTABLE
WHERE MYTABLE.app_id = '1234'
AND MYTABLE.org_id = '5678';

I tried to convert the UNION SQL into a Scalar query as some suggests but I'm getting error: "too many values"
SELECT
(select app_id, org_id, emp_id, name, name_id,
from TableA AAA, TableC CCC, TableB BBB
where BBB.ID=CCC.ID
and AAA.ID=BBB.ID
and app_id = '1234'
and org_id = '5678'
) q1,

(select app_id, org_id, emp_id, name, name_id,
from TableA AAA, TableC CCC,TableD DDD
where DDD.ID=CCC.ID
and AAA.ID=DDD.ID
and app_id = '1234'
and org_id = '5678'
) q2
) from dual;

What may be the problem in my Scalar query?
Or are there other ways I can rewrite this query with better performance?
Thank you very much.

A: A start would be to do the filtering in the individual selects. Limit the data set you are working with as  early as possible. What you are doing now is get all the rows from the tables, get the unique values from that big data set (you are using UNION not UNION ALL), filter the records.
  select app_id, org_id, emp_id, name, name_id,
  from TableA AAA, TableC CCC, TableB BBB
  where BBB.ID=CCC.ID
  AND AAA.ID=BBB.ID
  AND app_id = '1234'
  AND org_id = '5678'
  UNION
  select app_id, org_id, emp_id, name, name_id,
  from TableA AAA, TableC CCC,TableD DDD
  where DDD.ID=CCC.ID
  AND AAA.ID=DDD.ID
  AND app_id = '1234'
  AND org_id = '5678';

PS your selects are syntactically incorrect. The select list ends with a comma.

A: SELECT app_id, org_id, emp_id, name, name_id
FROM
(
SELECT app_id, org_id, emp_id, name, name_id
FROM TableA AAA
JOIN TableB BBB ON AAA.ID = BBB.ID
JOIN TableC CCC ON BBB.ID = CCC.ID

UNION

SELECT app_id, org_id, emp_id, name, name_id
FROM TableA AAA
JOIN TableC CCC ON AAA.ID = CCC.ID
JOIN TableD DDD ON CCC.ID = DDD.ID
) MYTABLE

WHERE MYTABLE.app_id = '1234'
AND
MYTABLE.org_id = '5678';


text:
Q: Condition for positive Determinant If we have that for any non-zero vector $x$ that $Ax\cdot x$ is a positive, why is determinant of $A$ positive?

A: Proof for the complex case (where the hypothesis applies to any non-zero vector, real or complex): the determinant is the product of the eigen values. If $\lambda$ is an eigen value then there exists a non-zero vector $x$ such that $Ax=\lambda x$ This gives $Ax.x=\lambda \|x\|^{2}$. LHS is positive by hypothesis and $\|x\|^{2}>0$. Hence $\lambda >0$. Hence determinant of $A$ is a product of positive numbers.
Real case: if $A$ is  a real matrix then eigen values can only occur in pairs $\lambda, \overline {\lambda}$ and the product of these is $|\lambda|^{2}$. Hence it is enough to see that the product of real eigen values is positive which follows by above argument since any eigen vector leads to a real eigen vector by taking real parts of its components.