text:
Q: Heat equation on a disc, only one side of boundary specified I've been working in 'Basic Partial Differential Equations' by Bleecker & Csordas' (Section 9.5, #5(a)) and I'm now having trouble with a this problem since the boundary conditions are left rather general. I'm not sure of how much more work I can do on the solution. The problem is as follows: Solve the heat equation in two dimensions
\begin{align*}
 u_t &= k[u_{xx}+u_{yy}], \quad x^2+y^2< r_0, t\geq 0\\
 u(r_0, \theta, t) &= 0, \quad -\pi \leq \theta \leq \pi\\
u(r,\theta,0) &= f(r,\theta)
\end{align*}
After transforming our PDE into polar form we may use separation to find
\begin{align*}
\frac{T'}{kT}=\frac{R''\Theta+\frac{1}{r}R'\Theta+\frac{1}{r^2}R\Theta''}{RH}&=-\lambda^2\\
\implies \frac{r^2R''+rR'+\lambda^2r^2 R}{R} = -\frac{H''}{H} &= m^2
\end{align*}
where $-\lambda^2$ and $m^2$ are our constants of separation. Hence,
\begin{align*}
T'+k\lambda^2T&=0\\
r^2R''+rR'+(\lambda^2r^2-m^2)R&=0\\
H''+m^2H&=0
\end{align*}
We have general solutions to these ODEs
\begin{align*}
T(t) &= e^{-\lambda^2 k t} \\
R(r) &= c_1 J_m(\lambda r) + c_2 Y_m(\lambda r) \quad \text{(Bessel functions)} \\
\Theta(\theta) &= a_{m,q} \cos(m\theta) + b_{m,q}\sin(m\theta)
\end{align*}
to form our general solution
\begin{equation*}
u(r,\theta,t) = \sum_q \sum_m u_{q,m}(r,\theta,t) = \sum_q \sum_m \left[a_{m,q} \cos(m\theta) + b_{m,q}\sin(m\theta)\right] \left[c_1 J_m(\lambda r) + c_2 Y_m(\lambda r) \right] e^{-\lambda^2 kt}
\end{equation*}
(i believe the indices range from $m = -\infty$ to $\infty$ and $q = 1$ to $\infty$, though I'm not quite sure why this is so)
Translating our boundary condition gives us
\begin{equation*}
 u(r_0, \theta, t) = 0 \implies R(r_0)\Theta(\theta) = 0, \quad -\pi \leq \theta \leq pi
\end{equation*}
Since it's not obvious to me that we know our problem is bounded (i.e. $|u(0)| < \infty$) to rule out second-kind Bessel functions $Y_m$, I don't know where to proceed in simplifying the solution any further, or what form our constants will take.
Thank you kindly!

A: Generally, the solution of a BVP must solve it at each point of domain. This in particular means that you should take the singular solution of your equation as a distribution. Neumann functions $Y_m$ don't solve the equation in polar coordinates in every point: they would only solve it if it had an additional (source) term proportional to Dirac delta with its singularity at the origin. See my answer at Physics.SE to a related question for extended discussion.


text:
Q: Create primary key with two columns I have two tables, bank_data and sec_data. Table bank_data has the columns id, date, asset, and liability. The date column is divided into quarters.
  id    | date     |  asset    | liability
--------+----------+--------------------
 1      | 6/30/2001|    333860 | 308524
 1      | 3/31/2001|    336896 | 311865
 1      | 9/30/2001|    349343 | 308524
 1      |12/31/2002|    353863 | 322659
 2      | 6/30/2001|    451297 | 425156
 2      | 3/31/2001|    411421 | 391846
 2      | 9/30/2001|    430178 | 41356
 2      |12/31/2002|    481687 | 46589
 3      | 6/30/2001|    106506 | 104532
 3      | 3/31/2001|    104196 | 102983
 3      | 9/30/2001|    106383 | 104865
 3      |12/31/2002|    107654 | 105867

Table sec_data has columns of id, date, and security. I combined the two tables into a new table named new_table in R using this code:
dbGetQuery(con, "CREATE TABLE new_table
         AS (SELECT sec_data.id,
         bank_data.date,
         bank_data.asset,
         bank_data.liability,
         sec_data.security
         FROM bank_data,bank_sec
         WHERE (bank_data.id = sec_data.id) AND
         (bank_data.date = sec_data.date)")

I would like to set two primary keys (id and date) in this R code without using pgAdmin. I want to use something like Constraint bankkey Primary Key (id, date) but the AS and SELECT functions are throwing me off.

A: First your query is wrong.. You say table sec_data but you assign table bank_sec and i am rephrase your query
CREATE TABLE new_table AS
    SELECT
       sec_data.id,
       bank_data.date,
       bank_data.asset,
       bank_data.liability,
       sec_data.security
    FROM bank_data
         INNER JOIN sec_data on bank_data.id = sec_data.id
                             and bank_data.date = sec_data.date

Avoid using Implicit Join and use Explicit Join instead.. And as stated by @ a_horse_with_no_name you can't define more than 1 primary key in 1 table. So what you do are Composite Primary Key
Define :

is a combination of two or more columns in a table that can be used to
  uniquely identify each row in the table

So you need to Alter Function because Your create statement base on other table..
ALTER TABLE new_table
   ADD PRIMARY KEY (id, date);

A: You may run these two separate statements ( create table  and Insert into  )
CREATE TABLE new_table (
       id int, date date, asset int, liability int, security int,
        CONSTRAINT bankkey PRIMARY KEY (id, date)
           ) ;

INSERT INTO new_table (id,date,asset,liability,security)
        SELECT s.id,
           b.date,
           b.asset,
           b.liability,
           s.security
         FROM bank_data b JOIN bank_sec s
         ON b.id = s.id AND b.date = s.date;

Demo

A: To create the primary key you desire, run the following SQL statement after your CREATE TABLE ... AS statement:
ALTER TABLE new_table
   ADD CONSTRAINT bankkey PRIMARY KEY (id, date);

That has the advantage that the primary key index won't slow down the data insertion.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add ellipses and angled bracket to a exponential number in Latex? I am currently working on a Latex assignment, and was wondering how to code the exponent below with the ellipses (...) and the angled bracket.

A: \documentclass{article}
\begin{document}
\begin{huge}
\[x^{\underbrace{1^{...^{1}}}_{n}}\]
\end{huge}
\end{document}

However, the result does not look exactly like the sketch. I hope it's helpful anyway.


text:
Q: Equilibrium points of a circuit with a diode The given circuit is shown in the first picture, whereas the characteristic curve of the diode in the second one. I want to calculate a model in the form of $$\frac{d\textbf{x}}{dt}=f(x,u) \\ \textbf{x}=\begin{bmatrix} i_L & u_c\end{bmatrix}^T$$ for the circuit and then calculate its equilibrium points. I am having problems with this task because I am not sure how to deal with the diode and its function only shown visually. Well, what I did up until now is first, apply Kirchhoff's circuit laws to get two differential equations:
$$
u_R+u_L+u_C=u\\
Ri_L+L\frac{di_L}{dt}+u_C=u\\
I: \frac{di_L}{dt}=\frac{1}{L}(u-u_C-Ri_L)
$$
$$
i_L=i_C+i_d \\
i_L=C\frac{du_C}{dt}+h(u_d) \\
II: \frac{du_C}{dt}=\frac{1}{C}(h(u_d)-i_L)
$$
Next, I tried to calculate the equilibrium points of the system (u=5V, L=1H, C=1F, R=1):
$$
I: 5V-u_C-i_L=0\\
II: h(u_d)-i_L=0 \\
I+II:5V-u_C+h(u_d)=0 \rightarrow 5V+h(u_d)=5V+h(u_C)=u_C
$$
But with this result I cannot find any solution, so I guess I did something wrong in my calculations, but what and where? Can someone help?

A: When you added \$I+II\$ you dropped the 2 \$i_L\$'s:
$$
I=5V-u_C-i_L=0\\
II=h(u_d)-i_L=0\\
I+II=5V-u_c+h(u_d)-2i_L=0
$$
If you are only interested in the steady-state solution, you can simplify the circuit a lot. In the steady-state, the inductor will behave like a short circuit and the capacitor will behave like an open circuit.

A: There are the two equilibrium equations:
$$ \text{I}:-u_c-R i_L+u=0 $$
and
$$ \text{II}:h(u_c)-i_L=0 $$
Eliminating \$i_L\$ from the two equations we get the following: $$h(u_c) = \frac{u-u_c}{R}$$
Now we need to choose pairs of \$(u,R, u_c)\$ that satisfy the above equations. These include (approximately) \$(0.5, 1, 3.5)\$ and \$(5, 0.01,5.06)\$, among others, which I have also plotted.


text:
Q: How do you normally layout a class's regions? I was wondering if there was a standard for laying out a class's regions.
I currently use
Fields
Constructor
Properties
Public Methods
Private Methods

Fields being Private Properties and Properties being the public ones. I'll normally use subregions within that if needed, or will occasionally add other regions below (such as interface or baseClass members).

A: It varies from language to language.  Since I'm a Delphi coder, I tend to follow the Delphi standard convention, which looks like this:
type
  TMyClass = class(TBaseClass)
  private
    private fields
    private methods
  protected
    protected fields
    protected methods
    protected properties
  public
    constructor(s)
    destructor
    public methods
    public properties
  end;

I find it a good way to organize information that's easy to read and understand.

A: Class-Related Enums or occasionally structs/pure-data classes (above actual class definition)
---Class definition---
Private members
CTORs/DTORs if the language has DTORs
Public properties
Utility methods (private or protected methods with small-scope)
Class functionality (May be divided into multiple regions depending on scope of class).

A: I tend to lay them out the following way:
Public fields (usually static constants)
Constructors
Public methods
Private methods
Private fields

Haven't used a language which uses Properties so that's why those are not laid out. I put private methods and fields at the bottom because if someone else is using this file in their code, they should only need to concern themselves with the API, which is the public stuff. And all text editors I know of, and even IDEs, sets the cursor at the top when opening files.

A: It's a judgement call for me.  I use regions when they are needed for readability.
I also use a different color in my Visual Studio color scheme (currently a dark red) to make them stand out from the rest of the code.

An example of where I might use a #region: If I write a test method for a unit test that requires a multi-line snippet of XML, the XML string will break the usual indentation (since it starts along the left-hand margin of the code window.  To hide the ugliness, I will wrap it in a #region, so that I can collapse it.

A: Bob Martin's Clean Code book dedicates the entire 5th chapter to formatting. There are a couple of key points that I feel summarize it nicely.

*

*Most attempts to group variables and methods by visibility and cleanliness Not make a lot of sense, and cause you to navigate around the code a lot.

*Keeping methods which call each other vertically close reduces the amount of navigation you need to do, and makes it easier to find things.

*Your train of thought isn't going to be broken if you have to stop and think "which region does this bit of code belong in?" every few minutes.

*Instance variables should usually be few, and likely to be used everywhere, therefore they belong at the top of the class where they will be easiest to locate. Variables and declarations that will only be used by one method need to exist inside that method. If used by only a couple of methods, then they should be vertically close but above the few methods that are using them.

Keeping your code arranged with commonly interacting elements vertically close together effectively removes any need to create specific regions. If your code is so long that it requires regions to hide a lot of code, then perhaps that is a code smell indicating that the class is trying to do too much. Perhaps some of the functionality can be moved out to a utility class, or pushed up to an ancestor.
If you need to "hide" the code because it's too long or too "ugly", then you've probably got bigger problems to worry about than whether or not to use regions. Personally I never need to use them, and when working on someone else's code, I find I always need to open them all up anyway, so why bother?

A: Sub Regions? Does your class have a Single Responsibility? (implicit in that ... my answer is "Rarely any regions, except maybe to group properties, constructors and methods"... but even then, I don't use it that much)

A: I just wanted to confirm that you meant "#regions" and not class layout in general.
I am surprised no one has mentioned to avoid using regions. I understand the OP wants to take a poll on laying out regions, but I'd like to raise an alternative view point.
I avoid regions. I like to see the code I am working with. If you find it difficult to find what you are looking for then use code folding and group similar class constructs together.
Why do I hate regions? CTRL+M,L and CTRL+M,O will toggle code folding. However, when collapsing it hides the entire region. I only need to collapse methods/properties/comments.
If there are too many regions maybe its a code smell and your class is doing too much work. Jeff Atwood provides a good post on regions which is worth a read.
My favourite quote on #regions:

No, I will not use #regions. And no, I DO NOT NEGOTIATE WITH TERRORISTS. Shut up.

-Jeff Atwood
That being said, I know many programmers insist on using them. This question is a subjective. I'd just thought I would offer an alternative.

A: I currently layout classes like this:
class types
constructors
destructor
accessors
methods
properties (where properties are present in the language)
member variables

and then prefix the access level to each declaration (sort of, sometimes group by access). I used to do top level grouping by access, but at somepoint, I don't know when, it didn't work quite as well as the above. For example in C++/CLI (which I'm forced to use at the moment :-( ) you can do this, which messes up the grouping-by-access:
public: property int SomeProperty
{
private: void set (int value) { ... }
public: int get () { ... }
}

A: Lunatic fringe answer: I don't, at least when it comes to C#. Between Visual Studio and R# I can magically navigate to any member or implementation so there isn't any point in obsessing about this stuff; just start typing where the cursor is.

A: Like Wyatt and a couple other answers, I also generally avoid the use of regions. Regions have one purpose; to hide code you don't want to have to look at. If you have a lot of code in a class you don't want to have to look at, and thus you need a lot of regions to allow you to collapse said code, then you probably have too much code in the class. ReSharper doesn't respect regions when deciding where to place new code, unless it created the region (which it does for interface implementations).
The one use of regions that I find acceptable is to hide "unavoidably ugly" code; code which deals with specific implementation details that can't be well-architected internally to current standards. This is usually advanced, esoteric code that should generally not be messed with by the average junior programmer once written. These are things like:

*

*Certain built-in interface implementations (IDisposable, IConvertible, sometimes IEnumerable or IComparable as they require generic and non-generic implementations)

*Embedded P/Invoke externs and related structures.

*Finalizers/destructors (usually goes with IDisposable)

*Hooks to unmanaged memory/pointers/"unsafe" code.


text:
Q: Auto Desk Infrastructure Map Studio 2013 Invoke Url Hi All I am making a map on Auto Desk Infrastructure Map Guide Studio. Now I created a small ASP.NET website and hosted in local machine, Now on click of different buttons in flexible layout toolbar, I invoke URL that asp.net page and it opens fine. I do some data querying on that page by selecting different options and execute query. The data changes in table in database and the effect is shown on the layer on map. Ok the issue is that I want to refresh the Auto desk map after invoke URL window is closed. And I want to do it by configuration in Map studio 2013. Does anyone have any idea how to refresh map automatically after invoke URL? Or in other sense if the data in the data source of layer is changed.
Addtional Info: the map always refresh when I click the refresh button from top or if I drag it or zoom it..Otherwise new layer data stays same. HELP !

A: If you want to update the map or a layer after calling an asp.net page, you must include a call to the Refresh method of the Viewer API linked OnClose event of your asp.net page.


text:
Q: Error 1045 on sum function in pig latin with an int The following pig latin script:
data = load 'access_log_Jul95' using PigStorage(' ') as (ip:chararray, dash1:chararray, dash2:chararray, date:chararray, date1:chararray, getRequset:chararray, location:chararray, http:chararray, code:int, size:int);

splitDate = foreach data generate  size as size:int , ip as ip,  FLATTEN(STRSPLIT(date, ':')) as h;

groupedIp = group splitDate by h.$1;

a = foreach groupedIp{
    added = foreach splitDate generate SUM(size); --
    generate added;
};

describe a;

gives me the error:
ERROR 1045:
<file 3.pig, line 10, column 39> Could not infer the matching function for org.apache.pig.builtin.SUM as multiple or none of them fit. Please use an explicit cast.

This error makes me think I need to cast size as an int, but if i describe my groupedIp field, I get the following schema.
groupedIp: {group: bytearray,splitDate: {(size: int,ip: chararray,h: bytearray)}} which indicates that size is an int, and should be able to be used by the sum function.
Am I calling the sum function incorrectly? Let me know if you would like to see any thing else, such as the input file.

A: SUM operates on a bag as input, but you pass it the field 'size'.
Try to eliminate the nested foreach and use:
a = foreach groupedIp generate SUM(splitDate.size);

A: Do some dumps of your data. I'll bet some of the stuff in the size column is non-integer, and Pig runs into that and dies. You could also code up your own isInteger udf to check this before the rest of your processing, and throw out any that aren't integers.

A: SUM, AVG and COUNT are functions that always work on a bag, therefore group the data and then join with the original set like below:
A = load 'nyse_data.txt' as (exchange:chararray, symbol:chararray,date:chararray, pen:float,high:float, low:float, close:float,volume:int, adj_close:float);
G = group A by symbol;
C = foreach G generate group, SUM(A.open);


text:
Q: SVN: how to update deep folder structure? I have a web app that uses a third party component made up of many files and directories (CKEditor). When a new version comes out, I copy/overwrite new files over existing ones. That takes care of added and modified content, but if the new distribution is missing a file that was there before, I'll end up keeping the stale copy. Since SVN relies on .svn folders for state, I can't just delete the old root folder and copy in the new.
Is there an easy/standard way to handle this sort of mass update with SVN?

A: I usually use rsync with a --exclude=.svn for this type of thing.
But i think CKEditor has a public svn repo so in that case I would use an svn:externals pegged to a particular release and then run the build script to the published directory thats on the web root so my repo might look like:
trunk/
  web/
    index.html
    js/
      ckeditor/
    images/
    css/
  lib/
    ckeditor/ (svn:externals to CK_EDITOR_SVN_URL/tags/some-version)

This way i cn just switch the external and do an svn up. This is particularly useful if the project your external is targeting does versioned branches where the continuously integrate BC updates. This way anytime you run an svn up you get the latest bug fixes and can just rebuild. Whether or not thats a good idea depend on the way the development of a particular project works so youll want to read through the developer docs before doing this.

A: Using svn:externals is one alternative. If you prefer to keep a snapshot of third party libraries in your own repository, however, you should read up on the concept of vendor branches in SVN. There is a standard Perl script (svn_load_dirs.pl) available for bulk loading third party code into your SVN repository that handles deletes properly.


text:
Q: Jobs spark failure When I want to launch a spark job on R I get this error :
Erreur : java.lang.IllegalStateException: Cannot call methods on a stopped SparkContext.
This stopped SparkContext was created at:
org.apache.spark.SparkContext.<init>(SparkContext.scala:82) ....

In spark logs (/opt/mapr/spark/spark-version/logs) I find a lot of theses exceptions :
ERROR FsHistoryProvider: Exception encountered when attempting to load application log maprfs:///apps/spark/.60135a9b-ec7c-4f71-8f92-4d4d2fbb1e2b
java.io.FileNotFoundException: File maprfs:///apps/spark/.60135a9b-ec7c-4f71-8f92-4d4d2fbb1e2b does not exist.

Any idea how could I solve this issue ?

A: You need to create sparkContext (or get if it exists)
import org.apache.spark.{SparkConf, SparkContext}

// 1. Create Spark configuration
val conf = new SparkConf()
  .setAppName("SparkMe Application")
  .setMaster("local[*]")  // local mode

// 2. Create Spark context
val sc = new SparkContext(conf)

or
SparkContext.getOrCreate()


text:
Q: Chain rule applies to Navier-Stokes Equations in polar coordinates Based on the fact that $p=p(r)$ only, consider the Navier-Stokes equations and show that the $e_\theta$ component reduces to

I can get to this if the following is true
$\frac {1} {r} \frac {\partial} {\partial r} ( r \frac {\partial u_\theta} {\partial r}) = \frac {1} {r} \frac {\partial u_\theta} {\partial r} + \frac {\partial ^2 u_\theta} {\partial r^2}$
But I have no clue as to how the left which I can get to from N-S equations in polar coordinates, can become the right

A: It's just a simple chain rule
$$ \frac{1}{r}\frac{\partial}{\partial r}\left(r\frac{\partial u_\theta}{\partial r}\right)=\frac{1}{r}\left(\frac{\partial r}{\partial r}\frac{\partial u_\theta}{\partial r}+r\frac{\partial}{\partial r}\frac{\partial u_\theta}{\partial r}\right)=\frac{1}{r}\left(\frac{\partial u_\theta}{\partial r}+r\frac{\partial^2 u_\theta}{\partial r^2}\right)=\frac{1}{r}\frac{\partial u_\theta}{\partial r} +\frac{\partial^2 u_\theta}{\partial r^2}$$


text:
Q: move_uploaded_file php I try to figure out how to resize an image (with a resize class) before proccesing it with GD. I posted here a short part off the code. What the idea behind this script is that GD images with big dimensions and/or to small server memory don't process. So i want to filter pictures bigger than 2500px width and only resize these pictures before upload. But i cannot figure out how and the right order to do this.
    require('resize_image_class.php');

    $file = $_FILES['bestand1']['tmp_name'];
    $bestanden = 'beeld_bestanden/nieuws-item-' . $item_id . '-foto1.' . $encode1 . '.' . $ext;
    $resized = 'beeld_bestanden/nieuws-item-' . $item_id . '-foto1.' . $encode1 . '.' . $ext;// overwrite somehow..
    move_uploaded_file($file,$bestanden);

    list($width, $height) = getimagesize($file);
    if($width > 2000){

    $resize = new ResizeImage($bestanden);
    $resize->resizeTo(2500, 2500, 'maxWidth');
    $resize->saveImage($resized);
    }

the output off $resized is the new basic image for me for further processing like with GD. The uploaded file resized or not must end up in: $bestanden.
Can somebody help me please with code example.
And this is the resize class:
class ResizeImage
{
private $ex;
private $image;
private $newImage;
private $origWidth;
private $origHeight;
private $resizeWidth;
private $resizeHeight;

/**
 * Class constructor requires to send through the image filename
 *
 * @param string $filename - Filename of the image you want to resize
 */
public function __construct( $filename )
{
    if(file_exists($filename))
    {
        $this->setImage( $filename );
    } else {
        throw new Exception('Image ' . $filename . ' can not be found, try another image.');
    }
}

/**
 * Set the image variable by using image create
 *
 * @param string $filename - The image filename
 */
private function setImage( $filename )
{
    $size = getimagesize($filename);
    $this->ex = $size['mime'];

    switch($this->ex)
    {
        // Image is a JPG
        case 'image/jpg':
        case 'image/jpeg':
            // create a jpeg extension
            $this->image = imagecreatefromjpeg($filename);
            break;

        // Image is a GIF
        case 'image/gif':
            $this->image = @imagecreatefromgif($filename);
            break;

        // Image is a PNG
        case 'image/png':
            $this->image = @imagecreatefrompng($filename);
            break;

        // Mime type not found
        default:
            throw new Exception("File is not an image, please use another file type.", 1);
    }

    $this->origWidth = imagesx($this->image);
    $this->origHeight = imagesy($this->image);
}

/**
 * Save the image as the image type the original image was
 *
 * @param  String[type] $savePath     - The path to store the new image
 * @param  string $imageQuality       - The qulaity level of image to create
 *
 * @return Saves the image
 */
public function saveImage($savePath, $imageQuality="100", $download = false)
{
    switch($this->ex)
    {
        case 'image/jpg':
        case 'image/jpeg':
            // Check PHP supports this file type
            if (imagetypes() & IMG_JPG) {
                imagejpeg($this->newImage, $savePath, $imageQuality);
            }
            break;

        case 'image/gif':
            // Check PHP supports this file type
            if (imagetypes() & IMG_GIF) {
                imagegif($this->newImage, $savePath);
            }
            break;

        case 'image/png':
            $invertScaleQuality = 9 - round(($imageQuality/100) * 9);

            // Check PHP supports this file type
            if (imagetypes() & IMG_PNG) {
                imagepng($this->newImage, $savePath, $invertScaleQuality);
            }
            break;
    }

    if($download)
    {
        header('Content-Description: File Transfer');
        header("Content-type: application/octet-stream");
        header("Content-disposition: attachment; filename= ".$savePath."");
        readfile($savePath);
    }

    imagedestroy($this->newImage);
}

/**
 * Resize the image to these set dimensions
 *
 * @param  int $width           - Max width of the image
 * @param  int $height          - Max height of the image
 * @param  string $resizeOption - Scale option for the image
 *
 * @return Save new image
 */
public function resizeTo( $width, $height, $resizeOption = 'default' )
{
    switch(strtolower($resizeOption))
    {
        case 'exact':
            $this->resizeWidth = $width;
            $this->resizeHeight = $height;
        break;

        case 'maxwidth':
            $this->resizeWidth  = $width;
            $this->resizeHeight = $this->resizeHeightByWidth($width);
        break;

        case 'maxheight':
            $this->resizeWidth  = $this->resizeWidthByHeight($height);
            $this->resizeHeight = $height;
        break;

        default:
            if($this->origWidth > $width || $this->origHeight > $height)
            {
                if ( $this->origWidth > $this->origHeight ) {
                     $this->resizeHeight = $this->resizeHeightByWidth($width);
                     $this->resizeWidth  = $width;
                } else if( $this->origWidth < $this->origHeight ) {
                    $this->resizeWidth  = $this->resizeWidthByHeight($height);
                    $this->resizeHeight = $height;
                }  else {
                    $this->resizeWidth = $width;
                    $this->resizeHeight = $height;
                }
            } else {
                $this->resizeWidth = $width;
                $this->resizeHeight = $height;
            }
        break;
    }

    $this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);
    imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight);
}

/**
 * Get the resized height from the width keeping the aspect ratio
 *
 * @param  int $width - Max image width
 *
 * @return Height keeping aspect ratio
 */
private function resizeHeightByWidth($width)
{
    return floor(($this->origHeight/$this->origWidth)*$width);
}

/**
 * Get the resized width from the height keeping the aspect ratio
 *
 * @param  int $height - Max image height
 *
 * @return Width keeping aspect ratio
 */
private function resizeWidthByHeight($height)
{
    return floor(($this->origWidth/$this->origHeight)*$height);
}

}


text:
Q: URLSession - optimal parallel tasks count What is optimal number of parallel URLSessionDownloadTask in URLSession?
I am trying to download multiple files (bigger files 10+MB) from different servers.
I tested downloading 10 files on 40Mbps connection. When I run single download task, speed is on average 21 Mbps. When I run 5 tasks in parallel, task speed is on average 6 Mbps. 10 tasks in parallel average speed 3 Mbps.
So 5 is faster then 1 but 5 and 10 are same.
Is there optimal parallel tasks count? Or is URLSession managing URLSessionDownloadTask and determines how many are executed based on network speed?


text:
Q: How to preserve Vaadin Tree container items order? I have Vaadin 7 Tree with HierarchicalCOntainer which contains items in some order (reordered through .moveAfterSibling().
When I try to get their ID collection I get them into order I have originally inserted, not the order they are shown.
I have checked both container.getItemIds() and .firstItemId() / .nextItemId(). Both do not match the order I see on the screen.
What do I do wrong way?

A: After looking to HierarchicalCOntainer source I have figured how .moveAfterSibling() works. The only remedy is to get root elements list:
container.rootItemIds()


text:
Q: How to view entire commit when log is filtered by file in tig If tig is invoked with tig log some/file.txt the log will show all commits affecting that file. Pressing Enter on a line like commit d5dd1d658e5d79701fb9d028479a0fcb26a033fa will open the diff view showing the changes to some/file.txt in that commit but only the changes to that file:

I would like to be able to view the entire contents of the commit, unfiltered by the filename. I.e. switch to a view that's the same as that generated if you run tig show d5dd1d658e5d79701fb9d028479a0fcb26a033fa:

I've tried all the views and read the manual but haven't found a way. Is it possible?

A: % toggles the file filter in any view and does what you're asking for. You can even switch back and forth between the file's history and the repository's history, or the file-constrained view of a commit and the commit in its entirety.


text:
Q: Dictionary GetHashCode Inconsistant i am using this hash for data retrival, but the data retrival is very uniform sometimes i get data under 200 millisecs and sometimes its over a sec..
can any give me some suggestions
public override int GetHashCode()

{

return
this.DomainID.GetHashCode() *(851) *
(this.A.HasValue ? this.A.GetHashCode() : 1) * (851) *
((this.C != null ? this.C.ToLower().GetHashCode() : 1)^
(this.Ap != null ? this.Ap.ToLower().GetHashCode() : 1) * (851) *
(this.Ks != null ? this.Ks.ToLower().GetHashCode() : 1)) *
(this.Le != null ? Le.ToLower().GetHashCode() : 1);

}

A: The code itself looks alright at a first glance, but there is a lot of things that we don't see. What types are DomainID, A, C, Ap, Ks and Le for example? And how are their GetHashCode-methods implemented?

A: It might suggest that one of your conditions is slower than the rest. Maybe the ToLower() is an expensive call dependant on which values in the the this are null


text:
Q: canvas.toDataURL() returns same dataURL Hi I'm currently developing ionic app with firebase.
I'm trying to upload multiple files with resizing.
It is weired that when I call resize method input image is different but once I finish my uploading, it ends up uploading duplicated images(last image of array).
I console.loged dataURL of it everytime it resize and found that DataURL is always the same.
following code is to upload multiple files.
    multipleUpload: function(key, folder, files, targetWidth) {
    var q = $q.defer();
    var ct = Date.now();
    var urls = [];

    var recursive = function (n, args) {
      var arg = args[n];
      ImageService.resize(arg.file, targetWidth)
      .then(function(file) {
        upload(ct + '' + n + key, folder + '/' + key, file, CONFIG.MESSAGE.FILE_UPLOAD + (n + 1) + '번 파일')
        .then(function(url) {
          urls.push(url);
          if (++n < args.length) {
            recursive(n, args);
          } else {
            q.resolve(urls);
          }
        }), function(error) {
          q.reject(error);
        };
      })
    }
    recursive(0, files);

    return q.promise;
  },

Following code is resizing method
  resize: function(file, targetWidth) {
    var q = $q.defer();
    // Resizing Image
    var img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.onload = function(){
      var canvas = document.createElement("canvas"),
      ctx = canvas.getContext("2d");
      canvas.width = targetWidth;
      canvas.height = canvas.width * (img.height / img.width);
      ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
      // Data URL to BLOB
      var dataURL = canvas.toDataURL();
      console.log(dataURL); // Returns same dataURL all the time.
      dataURLtoBlob(dataURL, Date.now())
      .then(function(blob) {
        q.resolve(blob);
      });
    };
    img.src = file;
    return q.promise;
  },

A: Firstly I found one thing weird that it worked fine on ios but android.
I started to digging plugin options and disabled allow-edit then it works fine. I believe it is an issue from the plugin.


text:
Q: Why does isInsideSecureHardware return true on an Android Emulator? Below is the code that I'm running on Android API 27:
KeyPairGenerator keyGen = null;
keyGen = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); // store the key in the Android KeyStore for security purposes
keyGen.initialize(new KeyGenParameterSpec.Builder(
        "key1",
        KeyProperties.PURPOSE_SIGN)
        .build()); // defaults to RSA 2048
KeyPair keyPair = keyGen.generateKeyPair();

KeyFactory factory = KeyFactory.getInstance(keyPair.getPrivate().getAlgorithm(), "AndroidKeyStore");
KeyInfo keyInfo = factory.getKeySpec(keyPair.getPrivate(), KeyInfo.class);
boolean secure = keyInfo.isInsideSecureHardware();
System.out.println("Is the private key backed in hardware: " + secure);

Since I'm running this code on an emulator I would expect it to return false, but somehow it is returning true. How is an emulator hardware-backed when it's completely in software? Is Android Studio somehow using the T2 chip on my Mac as its hardware backing?


text:
Q: How to prove this equation for moment generating function? Let $\mathcal{L}_I(s)$ be the Laplace transform of $I$ which is given by
$\mathcal{L}_I(s)=\left(\frac{2}{r_d^2-r^2}\int_r^{r_d}\mathbb{E}_H\left[r\exp\left(-sHr^{-\eta}\right)\right]dr\right)^k$
$\mathcal{L}_I(s)=\left(\frac{2}{r_d^2-r^2}\int_r^{r_d}\mathcal{L}_H(sr^{-\eta})dr\right)^k=\left(\frac{2}{r_d^2-r^2}\int_r^{r_d}\frac{r}{(1+sr^{-\eta})}dr\right)^k$
Here, $\mathbb{E}_H$ defines the expectation over variable $H$.
It is said that when $H$ is exponentially distributed with mean 1, (i.we., $\exp(-x)$), $\mathcal{L}_I(s)$ can be expressed as
$\mathcal{L}_I(s)=\left(\frac{\Phi(\eta,s,r_d)-\Phi(\eta,s,r)}{r_d^2-r^2}\right)^k$
where,
$\Phi(\eta,s,x)=x^2-x^2\hspace{1mm} _2F_1\left(1,\hspace{1mm}2/\eta,\hspace{1mm}1+2/\eta,\hspace{1mm} -x^{\eta}/s\right)$
Here, $_2F_1$ is the Gauss Hypergeometric function.
How to prove it?


text:
Q: WPF and user interface freeze In my main window, I have

*

*a navigation treeview on the left

*a content presenter on the right

*some kind of please wait panel (with width and height approximately 50) which displays a loading gif; this panel's visibility is binded to my main window's viewmodel bool property IsBusy.

The idea is showing this panel when the content presenter is initialized.

Selecting an item in the treeview:

*

*sets the bool property IsBusy to true (thus the wait panel with the
loading gif shows)

*sets the content presenter

To initialize this content, I use a task in my main window viewmodel so that the UI remains responsive. Within this task, when I need to update the UI, I use Application.Current.Dispatcher.BeginInvoke to manipulate my UI thread. This way, my loading gif plays smoothly when the task is processed in another thread.

Now, let's say I have a datagrid with twenty columns in my content presenter which is binded to an ObservableCollection in my main viewmodel. In my task, if I add 1000 items to this collection, when the UI updates to display the content, it becomes unresponsive for a few tenths of a second and my gif stop; basically the UI freezes.
How could I ensure that the wait panel always remains responsive and the gif keeps playing smoothly?

A: Alright, all I had to do was create the content presenter's content in another thread then assign the result to my content presenter after everything is done (in the bgw RunWorkCompleted for instance).


text:
Q: Force pip to skip or ignore bad hash on download cache Wondering if anyone knows a workaround to force pip to either completely skip hash checks or ignore bad sums when installing from a download cache? Install cmd is:
pip.exe install --target=C:\WHERE_I_WANT_INSTALLED --download-cache=C:\MY_DL_CACHE mitmproxy

Mitmproxy requires a specific version of pillow, and in that specific version there just happens to be a defined C function whos signature collides with another function in an include within Mingw x86_64. I'm not changing out my toolchain, as anyone who uses mingw on windows knows, it's a disgustingly painful process to find and keep a stable version.
Anyway, I've posted the question as a bug report on pips github but I thought I'd pose the question here. Thanks in advance.

A: Well, I found the answer in the very last place I would ever think to look: the documentation.
So basically you run a few commands to have pip download everything that is required for what you're trying to install. In this case, its was mitmproxy. So first I grabbed the requirements.txt file for mitmproxy, and dropped it into a dir. Commands to download packages were:
pip install --download C:\MY_SECRET_PATH\mitm\dl-cache six
pip install --download C:\MY_SECRET_PATH\mitm\dl-cache mock
pip install --download C:\MY_SECRET_PATH\mitm\dl-cache itsdangerous
pip install --download C:\MY_SECRET_PATH\mitm\dl-cache cryptography
pip install --download C:\MY_SECRET_PATH\mitm\dl-cache mitmproxy

Now, everything required for mitm-proxy is stored in the provided path. We then supply this path and a couple of other flags to the command for installing what we're after, again mitmproxy. To make things more interesting, I'm installing all of this stuff in a custom dir. So that command is as follows:
pip.exe install mitmproxy --no-index --target=C:\MY_SECRET_PATH\mitm --find-links=C:\MY_SECRET_PATH\mitm

So we're basically telling pip to install the selected package and all its deps offline, not checking pypy and therefore skipping hash checks. You're then obviously free to modify the sources of the packages you've downloaded, as I have.


text:
Q: Accessing Validation Errors in a UserControl I created a WPF (.Net 4) UserControl containing some ComboBoxes and a TextBox. In XAML, some ValidationRules are bound to the TextBox. If the TextBox contains invalid data, a red frame is shown, and the tooltip is set to the error description. Works well.
Next, I placed two instances of that UserControl on a form, and added a button. In XAML, the button is connected to a RelayCommand of the ViewModel. Now I want the button to be enabled only when both of the UserControls contain valid data only.
Not a problem, I thought, let me use a strategy which works elsewhere. I added a trigger:
    <Button Content="_OK" ... Command="{Binding Path=OKCommand}">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="IsEnabled" Value="false" />
                <Style.Triggers>
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition Binding="{Binding ElementName=cascadingComboFrom, Path=(Validation.HasError)}" Value="false" />
                            <Condition Binding="{Binding ElementName=cascadingComboTo, Path=(Validation.HasError)}" Value="false" />
                        </MultiDataTrigger.Conditions>
                        <Setter Property="IsEnabled" Value="true" />
                    </MultiDataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>

But there is a catch: Validation.HasError is always false for the UserControls - the Validation failed for an element inside the UserControl, not for the UserControl proper.
I know that I can register the Click event of the button, check the validity there using the method shown in Detecting WPF Validation Errors, and prevent the execution of the RelayCommand by setting the Handled property of the RoutedEventArgs to true. But that looks more like WTF than WPF.
What do you suggest? How can I retrieve the Validation Errors of the UserControl's children? Or how can I get them in the RelayCommand's CanExecute method? Or some other tricks?

A: You can set a property on the command binding called ValidatesOnDataErrors.
Implementation would look something like this:
 <Button Content="_OK" Command="{Binding, Path=OKCommand, ValidatesOnDataErrors=True}"/>

You can read more about it here.

A: The Button.IsEnabled property is already hard wired to the CanExecute method of your RelayCommand, so all you need to do is to set that return value to false when the form fields are invalid:
private bool CanExecute(object commandParameter)
{
    return areFormFieldsValid;
}

Now, how you set the bool areFormFieldsValid variable to true or false is up to you... there are several ways of doing that. Personally, I prefer to use the IDataErrorInfo interface, which has a handy Error property that you can check. There are many online tutorial on how to implement this, so I won't repeat that here... however, the end result is something like this:
private bool CanExecute(object commandParameter)
{
    return string.IsNullOrEmpty(yourDataObject.Error);
}


text:
Q: get selected "value" of declared text-field / BootstrapVue I have a b-form-select field and emit my value-field to my parent, but I need the selected text-field too..
Here is the needed code to show what I mean:
In my template:
<b-form-select v-model="selected" :options="getOptions" text-field="Name" value-field="Rank"></b-form-select>
but if I console.log(this.selected), I get of course the value Rank which I have selected. But is it also possible to get the text-field ?
Here is my script to show how my selected works:
computed: {
 getOptions() {
    const array = [];
    const person = this.data.find((i) => i.name === this.name);
    for (let key in person.persons) {
      array.push(person.persons[key]);
    }
    return array;
  },
}

my json data:
[
    {
        "name": "XXX",
        "persons": {
            "1": {
                "Name": "Max",
                "Rank": "1"
                },
            "2": {
                "Name": "Peter",
                "Rank": "2"
            },
            "3": {
                "Name": "Harry",
                "Rank": "1"
            },
            "4": {
                "Name": "Jake",
                "Rank": "0"
            }

        }
    },
]

A: As you have the value available, as well as the list of options you can simply add a new computed field to get the selected values text-field
computed: {
 getOptions() {
    const array = [];
    const person = this.data.find((i) => i.name === this.name);
    for (let key in person.persons) {
      array.push(person.persons[key]);
    }
    return array;
  },
  selectedOption() {
    if (!this.selected) {
      return null;
    }

    return Object.values(this.getOptions).find((option) => {
      return option.Rank === this.selected;
    });
  }
}

Then access selectedOption.Name or selectedOption.Rank. If you put the Name and Rank into variables / data attributes as well you can also make it more generic.
Update:
Changed to Object.values


text:
Q: Radio Buttons in ag-grid I am using ag-grid to display my data and i have below question:
1.Instead of check boxes i want radio buttons to be displayed when i expand the group and also my grouping is not working as expected.?
Plunkr link for the above grid what i tried so far https://plnkr.co/edit/KahAzPv6QEccaaRKlzCN?p=preview
  var gridOptions = {
        columnDefs: [
             {headerName: "Jobs",field: "job", width: 90,rowGroupIndex: 0 ,hide:true},
            // this tells the grid what values to put into the cell
            //showRowGroup: 'position'
            // this tells the grid what to use to render the cell
           // cellRenderer:'agGroupCellRenderer'

           //{field: 'position', rowGroup: true, hide: true},
           {headerName: "Name", field: "name"}

        ],
        rowData: [
            {position:'Developer',name:'Test1',job:'Position'},
            {position: 'Manager', name:'Test2',job:'Position'},
            {position: 'Musician',job:'Position'},
            {position: 'Manager',name:'Test4',job:'Position'},
            {position: 'Europe',job:'Location'},
            {position: 'Australia',name:'Test4',job:'Location'}
        ],
      /* autoGroupColumnDef:{
       headerName:'',
       cellRendererParams:{
        suppressCount: true,
        checkbox:true
    }
       }*/

       autoGroupColumnDef: {
headerName: "Jobs",
field: "position",
width: 250,
cellRenderer:'agGroupCellRenderer',
cellRendererParams: {
  checkbox: true
     }
     }
     };


text:
Q: Google Action does not have trained NLU model (No trained NLU model found.) I am currently in the process of migrating from an older Dialogflow agent to a new ActionBuilder agent. Going well so far (translated into a new action to wrap things up before I am gonna push the changes to the old action), but it suddenly stopped working in the Simulator.
It crashes after the initial welcome, no trace on any scene migrations and it doesn't hit the fulfillment.
The logs simply state:
No trained NLU model found.
Note: It did work for a few days before that.
I did rename a few intents and scenes and reorganized some transitions before that.
I already tried to trigger a new training process by changing some phrases but that didn't change anything (it did show the training indicator tho).
I wonder if anyone has any idea, maybe on how to retrain the whole agent/NLU model or something similar?


text:
Q: Login to a website and open it in web browser I am new to perl and i have started with mechanize.
I logged in to a website sucessfully but after that i wanted to open the website in
my browser in windows it just opens the website instead of after logging in.
#!/usr/bin/perl -w

use Win32::API;
use WWW::Mechanize;
use strict;
use diagnostics;
use warnings;

my $m = WWW::Mechanize->new(
 autocheck       => 1,
 onerror         => \&Carp::croak,);

my $Email = 'username';
my $Password = 'password';
my $url = 'http://www.gmail.com/';
my $response = $m->get($url);

if (!$response->is_success) {
    die "Login page unreachable $url: ",  $response->status_line, "\n";
}

    $m->submit_form(
        form_number => 1,
        fields      => {
                       'Username' => $Email,
                       'Password' => $Password,
                       },
    );

$response = $m->submit();

 $m->add_header(
  "Connection" => "keep-alive",
  "Keep-Alive" => "115");

#$response = $m->click();
if ($response->is_success) {
    print "Login Successful!\n";
} else {
    die "Login failed: ",  $response->status_line, "\n";
}

my $ShellExecute =
  new Win32::API( "shell32", "ShellExecute", [qw(N P P P P N)], 'N' );

my $GetDesktopWindow =
  new Win32::API( "user32", "GetDesktopWindow", [], 'N' );

my $hWnd = $GetDesktopWindow->Call();

$ShellExecute->Call( $hWnd, 'open', $url, '', '', 1 );

A: Argh. You can't just do that.
Do you ever log in to gmail using internet explorer, and then expect it to work in firefox?
...
If you need to log in with your browser, you should probably just get perl to log in with your browser.
If you really need to do it with just mechanize, then you probably need mechanize to store the same cookies your browser uses.


text:
Q: Kotlin: Curly braces around several expressions (or statements) I think this question is somewhat related to Kotlin function declaration: equals sign before curly braces
In Scala, every statement is an expression (possibly with Unit type). If we surround multiple expressions with braces, then the final expression is the actual value of the curly braced part. Therefore,
// Scala
val a = {
  val b = 1
  val c = b + b
  c + c
}
println(a)

The type of a is Int and the code prints the value 4.
However, in Kotlin, this is somewhat different.
If we do the same thing in the Kotlin,
// Kotlin
val a = {
  val b = 1
  val c = b + b
  c + c
}
println(a)

The type of a is () -> Int and the code prints the Function0<java.lang.Integer>, which means a 0-ary function object with result type Int.
So if we want to print the value 4, we need to do println(a()).
In fact, the expression {} in Kotlin is a function () -> ().
I cannot find an explanation about this in Kotlin official reference pages. Without a parameter list or ->, curly braces make a function?
When I use Scala, I write many codes like the first code. However, in Kotlin, it creates a function object and we have to call the function, which may be an overhead in a loop or recursion.

*

*Is there any document about this thing: just curly braces make a function object?

*Any way to workaround the overhead in the second code if it is used many times?
EDIT
Here is the actual code that iterates many times:
in Java
while ((count = input.read(data, 0, BYTE_BLOCK_SIZE)) != -1) {
    ....
}

in Scala
while {
  count = input.read(data, 0, BYTE_BLOCK_SIZE)
  count != -1
} {
  ....
}

in Kotlin
while ({
    count = input.read(data, 0, BYTE_BLOCK_SIZE)
    count != -1
}()) {
    ...
}

You can see, only Kotlin makes a lot of function objects and calls them.

A: If {} defines a function, you can just call the function upon declaring it, which will immediately evaluate it:
val a = {
  val b = 1
  val c = b + b
  c + c
}()
println(a)

prints 4. (Note the () at the end of the block)

A:
In Scala, every statement is an expression (possibly with Unit type)

That's not exactly true. Check: Is everything a function or expression or object in scala?
As Zoltan said {} defines functions so instead of:
// Kotlin
val a = {
  val b = 1
  val c = b + b
  c + c
}
println(a)

it should be:
// Kotlin
val a = {
  val b = 1
  val c = b + b
  c + c
}
println(a()) //you defined a function, which returns `4`, not expression

or
// Kotlin
val a = {
  val b = 1
  val c = b + b
  c + c
}() //note these braces
println(a)

If you would like to print a value, not function, you can try to declare the variable and then use one of Kotlin functions to change a value like in example below:
var sum = 0
ints.filter { it > 0 }.forEach {
  sum += it
}
print(sum)

Read: Higher-Order Functions and
  Lambdas

Hope it will help

A: In Kotlin {} are always a lambda expression or a part of a syntax construct like while(true) {}. Probably different from Scala, but easy to grasp, nonetheless.
What you probably want is:
val a = run {
  val b = 1
  val c = b + b
  c + c
}
println(a)

Kotlin has no build-in concept of "code blocks anywhere". Instead we use standard functions-helpers like run in the example above.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/run.html


text:
Q: Finite or infinite set? Due to my not-so-advanced math skills, this question may take a few attempts to state clearly:
Consider the unordered pair (2-tuple) partitions of n (e.g. with n=4, we have {{4,0},{3,1},{2,2}}).  Take the low value from each pair and add them together and call this total T1.  Take the high value from each pair and add them together and call this total T2.  Let r = T2 / T1.  For what values of n will r be an integer? What can we conclude about the minimum and maximum values of r, integer or not, for n={1,2,3,...,infinity)?
Clearly the sequence of ratios r is infinite, as is the subset of integer ratios r.  The minimum integer is either 0 or 1, depending upon whether or not we consider the null set equal to zero.  As for the maximum, it appears that for all r, r < 4 (?), and I assume this has to do with things like modular arithmetic, congruences, and the elements of T2 >= n/2 and the elements of T1 <= n/2.
(The real question)
Now restrict the pairs to just those composed of prime numbers (again, with n=4, we would toss out {{4,0},{3,1}} and end up with just {2,2} and 2/2=1.  By restricting the pairs in this way and requiring r be an integer, we get what appears to be a finite set of values for n: {4, 6, 16, 18, 20, 32, 52, 72, 102, 180, 3212}. I say "appears" because after 3212, no more terms are found for n < 10^7.  I suspect these are all the terms, because as n grows large, T2 will always contain elements that can't be canceled by elements in T1, thus the set is finite.  Is this true?  If not, is there a way to determine where the next term might be?
One more example with n=18:
Partitions are: {{9,9},{10,8},{11,7},{12,6},{13,5},{14,4},{15,3},{16,2},{17,1},{18,0}}.
{11,7} are both prime, and {13,5} are both prime, so T2 = 11+13 = 24, and T1 = 7 + 5 = 12.  r = T2 / T1 = 24 / 12 = 2.
One other observation:
If we generalize and let the elements of T2 >= n/x and the elements of T1 <= n/x, and restrict x to prime number, the integer value of r will tend to be 2x-1 (i.e. in the case above, x=2, 2 is prime, and the integer value of r tends to be 3 = 2(2)-1.
Thanks
Mathematica:
okQ[n_] := Module[{p, q}, p = Select[Prime[Range[PrimePi[n]]],
PrimeQ[2 n - #] &]; q = 2 n - p; Mod[Plus @@ q, Plus @@ p] == 0];
2*Select[Range[2, 5000], okQ]

A: When you talk about the partitions, all you're doing is representing $n$ as the sum of two other numbers. One will be $\geq \frac n 2$, and one will be $\leq \frac n 2$, as you've noticed. If both were bigger they'd add up to a number too large (similar situation for both being less). In fact you're just summing these. The upper sum is just the sum of the numbers $\geq n/2$ (since you'll get exactly one partition for each such number), and similarly for the lower sum. So your lower sum is always
$$\frac {n(n+2)}8, n \text{ even}$$
$$\frac{(n-1)(n+1)}8, n \text{ odd}$$
and your upper sum is always
$$\frac{3n(n+2)}8, n \text{ even}$$
$$\frac{3n^2+4n+1}8, n \text{ odd}$$
I can add derivations of these if you'd like; they're just applying the formula for $\sum_i i$ to $n$ and $n/2$. So when are these integers? For $n$ odd:
$$\frac{3n^2+4n+1}{n^2-1}=\frac{3(n^2-1)+4n+4}{n^2-1}=3+\frac{4}{n-1}$$
which is an integer for $n=3,5$ (remember, $n$ is odd in these formulas), giving you $5$ and $4$ as answers. For $n$ even:
$$\frac{3n(n+2)}{n(n+2)}=3$$
...well that's interesting. There might be a deeper reason for that, but as I don't know any number theory I'm afraid I can't enlighten you.
The prime question looks a lot harder, basically because primes are a lot harder. You're requiring both $x$ and $n-x$ to be prime in the pair ${x,n-x}$. Since we don't know how prime numbers are distributed (except asymptotically), you aren't going to have a closed formula here. Maybe someone with more expertise can shed light on any asymptotic results here, or whether or not there are actually finitely many solutions, but I'm kind of doubtful.

A: This was becoming a little too long to be a comment.
Some very simple observations on "the real question".
First $n$ will be even (because an odd number can be the sum of two primes in only one way $2+p$ and $p$ is not even unless it is 2).
Second, if you could find a prime pair $12x \pm 1$ then $$12x+4=3+(12x+1)=5+(12x-1)$$ while $$T_1=8 \text{ and } T_2=24x \text{ so } \frac {T_2}{T_1} = 3x$$
So, to show that the sequence comes to an end you would have to show (amongst other things) that every sufficiently large example of a number $12x+4$ with $12x \pm1$ being twin primes is the sum of at least one additional pair of primes. The same idea works with the numbers 5 and 7 and any pair of large odd primes (these are always of the form $6x\pm1$).

A: It seems to me that $T1$ is just the sum of all the integers less or equal than $\frac{n}{2}$ while $T2$ is the sum of the integers $\frac {n}{2} \le i \le n$, thus it should not be hard to find a closed formula for $r$, and also verifying when it is an integer.
As for the real question, I'll think about it. I suspect a closed formula is much harder to find because asking both numbers of the pair to be prime appears to be quite an unstable condition. Perhaps you should check if the numbers $n$ for which $r$ is an integer (you listed them above) have some number-theoretical significance.


text:
Q: How to set a program to startup on boot for all users in windows 10? I have to start some program when the computer boots, for all users, and possibly before the user login.
So how and where does I have to put them?

A: I see 3 ways

*

*Task Scheduler has support to run it both in startup and in login

*If the path I commented on OP exists you can drop an executable there

*Registry. Don't do this if you don't know what you're doing, but they're in HKEY_LOCAL_MACHINE>SOFTWARE>Microsoft>Windows>CurrentVersion>Run

For a beginner I'd recommend doing task scheduler since it's pretty and almost kinda debuggable.

A: In Windows 10 shell:common startup command in windows "run" can be used to open up startup folder and we can place script/batch files to be run during startup for all users.
Please check this link for more details starup and common startup details


text:
Q: Can i make a scheduled query to an API using php and save it locally? I made a page that retrieves information from an API. It is taking about 10-20 seconds to get the response from their server. The request is done fro js through a PHP proxy to avoid cross-domain issues.
I'm wondering, as the data is not like to be changing often (it is congressman's data) I might make a request daily and store it in my server so the page loads faster, I can provide a "refresh" button incase the user needs it. How can that be done? I'm just starting in web development and i see that is necessary knowledge of several different languages and frameworks, now I'm diving into js, but i got this PHP hack working for my requests, bottom line i know almost nothing of PHP yet.
[edit] ok I got the cron working! Now how do i save the document.xml from php script?
I tried:
$c_t = fopen('file.xml', 'ab+');
fwrite($c_t, date('Y-m-d H:i:s')."\n\n"); //add timestamp to theverbose log
fwrite($c_t,$xml);

inserted just before `curl_close($session);
The file was saved, but only with the timestamp...
here's what i got...
<?php
// PHP Proxy --- only 'GET'
// Based on script from yahoo's example @ http://developer.yahoo.com/javascript/samples/proxy/php_proxy_simple.txt
// tweaked by vk
//  hostname - just base domain
define ('HOSTNAME', 'http://www.camara.gov.br');

// Get the REST call path from the AJAX application - js;
$path = $_GET['yws_path1'];

// assign yo url
$url = HOSTNAME.$path;

//Open the Curl session
$session = curl_init($url);

// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_HTTPGET, true);

//set user agent, that did it!!! copied from browsers...
curl_setopt($session, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36');

// The web service returns XML. Set the Content-Type appropriately
header("Content-Type: text/xml");

// Make the call
$xml = curl_exec($session);

// done, shutDown.
curl_close($session);
?>

A: If you are on a Mac, or Linux; you can schedule your code to execute via cron.  PHP does not have to be run by a browser.
php -f yourcode.php > results.txt
'man php' for more information...
and
'man crontab -s 5' for details on scheduling using cron


text:
Q: Email Extraction in R I am trying to extract all the email id from description.
> string <- c("From : William KWANG (TLA) To : Melissa_FOO@nba.gov.sd,feedback@tla.gov.sd,Milly_YUEN@tla.gov.sd,Faridah_B_SALLEH@tla.gov.sd,
+ Muhamad_Rosli_MOKTAR@tla.gov.sd cc : Juzaidi_LASA@nba.gov.sd,Kamis_TAHIR@nba.gov.sd,TAN_Xiao_Wei@nba.gov.sd Bcc : Sent On : Wed Mar 04 16:46:29 SGT 2015")

> str_extract_all(string=string,pattern="\\b[-A-Za-z0-9_.%]+\\@[-A-Za-z0-9_.%]+\\.[A-Za-z]+ ")
[[1]]
[1] "Muhamad_Rosli_MOKTAR@tla.gov.sd " "TAN_Xiao_Wei@nba.gov.sd "

However i am not able to extract all the email ids.
My question is, there are alist of emails mentioned in to: list with comma, but the query fetches the last result.

A: The trailing space in your regex is the problem. The only addresses matching that condition are Muhamad_Rosli_MOKTAR@tla.gov.sd TAN_Xiao_Wei@nba.gov.sd because they're the only ones with tailing spaces. So just remove it:
string <- c("From : William KWANG (TLA) To : Melissa_FOO@nba.gov.sd,feedback@tla.gov.sd,Milly_YUEN@tla.gov.sd,Faridah_B_SALLEH@tla.gov.sd,Muhamad_Rosli_MOKTAR@tla.gov.sd cc : Juzaidi_LASA@nba.gov.sd,Kamis_TAHIR@nba.gov.sd,TAN_Xiao_Wei@nba.gov.sd Bcc : Sent On : Wed Mar 04 16:46:29 SGT 2015")
str_extract_all(string=string,pattern="\\b[-A-Za-z0-9_.%]+\\@[-A-Za-z0-9_.%]+\\.[A-Za-z]+")

[[1]]
[1] "Melissa_FOO@nba.gov.sd"          "feedback@tla.gov.sd"             "Milly_YUEN@tla.gov.sd"           "Faridah_B_SALLEH@tla.gov.sd"
[5] "Muhamad_Rosli_MOKTAR@tla.gov.sd" "Juzaidi_LASA@nba.gov.sd"         "Kamis_TAHIR@nba.gov.sd"          "TAN_Xiao_Wei@nba.gov.sd"

Note this might work for whatever you're doing here, but email addresses are notoriously difficult to interpret with regular expressions, so don't expect this method to work for every address you might come across.


text:
Q: Difference between mkdir and CreateDirectory Is there a difference between mkdir(<name>) and CreateDirectory(<name>, NULL) under Win32.
As I can see, both are working (in the same way ??)

A: mkdir (and the recommended _mkdir are runtime library functions. CreateDirectory is specific to Windows. If you want portable code, call _mkdir. If you're fine making your program Windows-specific, or you need the ability to add security descriptors, then call CreateDirectory.
Most likely, the _mkdir implementation for Windows calls CreateDirectory(name, NULL). So both end up doing the same thing.
Edit: The Visual Studio 12 implementation of _mkdir() calls _wmkdir(), which then calls CreateDirectoryW:
int __cdecl _wmkdir (
        const wchar_t *path
        )
{
        ULONG dosretval;

        /* ask OS to create directory */

        if (!CreateDirectoryW(path, (LPSECURITY_ATTRIBUTES)NULL))
            dosretval = GetLastError();
        else
            dosretval = 0;

        if (dosretval) {
            /* error occured -- map error code and return */
            _dosmaperr(dosretval);
            return -1;
        }

        return 0;
}


text:
Q: Setting Html.TextBoxFor value with jQuery is not reflected in Model POST I have an account page where a user can update his/her profile picture. I use Amazon S3 to store the images so after a successful upload, I return the image URL to populate the image src and a TextBoxFor with a value of the URL. However, when I submit my form, the model that is submitted to my POST still contains the desktop filename instead of the Amazon S3 URL.
Here's my ajax call that (upon success) populates an img field and a TextBoxFor field:
$.ajax
        ({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Account/UploadProfImageToS3Return",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (data) {
                $("#profile-image").attr("src", data);
                $("#profImage").attr("value", data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //TODO: Indicate Error
                console.log(jqXHR);
            }
        });
        });

Here is my Html.BeginForm:
 @using (Html.BeginForm("General", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {

       @Html.TextBoxFor(m => m.Artist.ImageURL, new { @name = "profImage", @id = "profImage", @type = "file" })

            <input type="submit" value="Save" class="btn btn-default btn-form" />

}

The file, when added to the @Html.TextBoxFor(m => m.Artist.ImageURL, new { @name = "profImage", @id = "profImage", @type = "file" })
is called: 20507471_10214.jpg and after the file is uploaded the value of that TextboxFor is now https://s3.amazonaws.com/unlink/profile-picture/xxxxxxx.jpg (because I update the field after AJAX success)
But when I set a breakpoint on my POST here:
[HttpPost]
public ActionResult General(Artist artist)

and I inspect the artist.ImageURL it still equals 20507471_10214.jpg
What can I do to fix this?
EDIT, image to prove that the value/src attribute of each is being set properly:

A: Well alright then, so a workaround is to not use:
@Html.TextBoxFor(m => m.Artist.ImageURL, new { @name = "profImage", @id = "profImage", @type = "file" })
and to instead use something like this, with a hidden form element to bind the value on submit...odd, but works:
<input name="profImage" id="profImage" type="file" />
@Html.HiddenFor(m => m.Artist.ImageURL)

I assign the S3 URL value to the hidden form upon AJAX success with:
$("#Artist_ImageURL").attr("value", data);

A: Try to add new image-url from received from Amazon S3 to formData like this
$.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Account/UploadProfImageToS3Return",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (data) {
            $("#profile-image").attr("src", data);
            $("#profImage").attr("value", data);

            //imageUrl corresponds to the Artist model property.
            formData.append("imageUrl",data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //TODO: Indicate Error
            console.log(jqXHR);
        }
    });
});

A: firstly, be very carefully if you are using Chrome, Chrome do not update the css and JS files inmediatly, I recomend to you, use firefox to develop.
Maybe, when you edit the ´name´ tag, you maybe edit some behavior and this is not how MVC wait the response, can you try to delete the ¨@name = "profImage"¨ part and then check the behavior


text:
Q: What's the rationle behind "directory mask" in smb.conf? Let's say have a directory 'myshare' with SGID enabled, just for testing I've set in smb.conf:
[myshare]
        comment = myshare
        path = /var/lib/samba/myshare
        create mask = 0664
        directory mask = 0770

As far I understand the directories should be created with 0770, but it don't, they are created with 2770 anyway. So what it's the purporse of that parameter, if it is ignored? Am I missing something?


text:
Q: FLUTTER How do I get rid of "FATAL EXCEPTION: ScreenDecorations"? I'm having a Problem with Android Studio. I updated it recently to Dolphin and since then I can't start my apps on the emulator.
I already tried a few things and my last was to delete everything (Android Studio, SDKs, Git) and install it again. I also tried flutter doctor but it shows no errors.
I'm getting following output from the console which is repeated till i stop the program:
Running Gradle task 'assembleDebug'...
E/AndroidRuntime(31480): FATAL EXCEPTION: ScreenDecorations
E/AndroidRuntime(31480): Process: com.android.systemui, PID: 31480
E/AndroidRuntime(31480): java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter bottomLeft
E/AndroidRuntime(31480):    at com.android.systemui.statusbar.events.PrivacyDotViewController.initialize(Unknown Source:22)
E/AndroidRuntime(31480):    at com.android.systemui.ScreenDecorations.setupDecorations(ScreenDecorations.java:315)
E/AndroidRuntime(31480):    at com.android.systemui.ScreenDecorations.startOnScreenDecorationsThread(ScreenDecorations.java:252)
E/AndroidRuntime(31480):    at com.android.systemui.ScreenDecorations.$r8$lambda$bRx4s-frKyGv-SmpobluoualBbQ(Unknown Source:0)
E/AndroidRuntime(31480):    at com.android.systemui.ScreenDecorations$$ExternalSyntheticLambda2.run(Unknown Source:2)
E/AndroidRuntime(31480):    at android.os.Handler.handleCallback(Handler.java:938)
E/AndroidRuntime(31480):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(31480):    at android.os.Looper.loopOnce(Looper.java:201)
E/AndroidRuntime(31480):    at android.os.Looper.loop(Looper.java:288)
E/AndroidRuntime(31480):    at android.os.HandlerThread.run(HandlerThread.java:67)

A: I was facing the same issue. I think it is a known issue in android emulator due to pinhole cutout (chick here for more details). I switched to a device without pin hole camera and the issue was resolved.


text:
Q: Autodesk Forge Viewer v7 - setThemingColor I hope somebody can help me with a question about the setThemingColor function for the Autodesk Forge Viewer.
Basically my issue is that when I run the
viewer.setThemingColor(dbId, new Vector4( 1, 1, 1, 1 ), null, true )
from within my code nothing happens, and the element does not get a new color.
What I have tried:
1) If I try to run exactly the same line of code in the browser on the NOP_VIEWER it works, but only if it is a new dbId and not the one which had just been run from within my code.
2) I have tried to make sure to find the leaf dbId and use this. Did not have any effect.
3) I have tried to add the model to the function call:
viewer.setThemingColor(dbId, new Vector4( 1, 1, 1, 1 ), model, true )
4) I have tried to run the function on the level of the model:
model.setThemingColor(dbId, new Vector4( 1, 1, 1, 1 ));
viewer.impl.invalidate(true);
5) I have from within my code tested viewer.isolate(dbId) to make sure I have access to the viewer instance. And this works.
Is anybody else experiencing the same issue or can replicate the bug?
I hope somebody can help us out.
EDIT: More infor after Petr Broz answer:
"What version of the viewer are you using?": We are using v. 7.*
"Do you see any error logs in the console after setting the theming color?": I see no error logs.
"At what point in time are you trying to set the color (for example, after the GEOMETRY_LOADED_EVENT)?": I use a onClick event on button, so it is after GEOMETRY_LOADED_EVENT
ANSWER:
I found the solution. I had to import THREE as a global.
/* global THREE */
instead of
import {Vector4d} from "three"

A: Here's a quick codepen setting the theming color on a pre-configured dbID (roof of the house), using viewer version 7.* (currently 7.10): https://codepen.io/petrbroz/pen/WNbYXWz.
It'd be helpful if we had some additional info, for example:

*

*What version of the viewer are you using?

*Do you see any error logs in the console after setting the theming color?

*At what point in time are you trying to set the color (for example, after the GEOMETRY_LOADED_EVENT)?

Alternatively, if you don't mind sharing a live link to your app or your Forge app config, please send us an email to forge (dot) help (at) autodesk (dot) com, and we'll investigate the issue from our end.


text:
Q: Read binary file from a generic path in java I am writing a library that takes a file path which can be either local or classpath or remote (simple http, no authentication). Is there any such generic utility that receives such string path and return the file binary content? The example paths are:

*

*c:/mydirectory/file.jpg

*classpath:com/example/file.jpg

*http://example.com/file.jpg
Thanks

A: you can use URL and create URLConnection to get the input stream from file or web link.
package ch.p1gu;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {

public static void main(String[] args) {
    try {
        URL fileUrl = new URL("file:///home/p1gu/tmp/test.txt");
        URL webUrl = new URL("http://pastebin.com/RdVdQVdC");
        URLConnection ucWeb = webUrl.openConnection();
        URLConnection ucFile=fileUrl.openConnection();

        DataInputStream disWeb  = new DataInputStream(ucWeb.getInputStream());
        DataInputStream disFile = new DataInputStream(ucFile.getInputStream());

        System.out.println(disFile.readUTF());
        System.out.println(disWeb.readUTF());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}


text:
Q: How can you enforce a setter method to be called on creating a object that can produce compile time warning or exception? Suppose I've a class A which looked like this before:
class A(str:String){
  // body
}

Now, I want to remove the parameter from the constructor instead I'll be using a setter for that value. Like below:
class A(){

 lateinit var str:String

 fun setStr(paramsString:String){
   str = paramsString
 }

}

As I am using a setter for assigning the value, it wont give me a compile time exception while creating the object of that class.
So, I tried something like below:
class A(){

 lateinit var str:String

 init{
  setStr(strValue:String)
 }

 fun setStr(paramsString:String){
   str = paramsString
 }

}

This init block will be executed after creating the object of the class A where the setter method will be called.
But still what I want is to warn or throwing an exception when the object of the following class is created for calling the setter method.

A: This here
class A(public str:String){
  // body
}

already has a setter, since yo can do
A("Bla"); println(a.str)

compile time errors would probably need some type checking (e.g. String? allows null, String checks for not null)
if you want to execute code on a.str="Blub" you do this:
class A(){
  var str:String = ""
    set(str) {
        // check some stuff here, throw Exception
        field = str  // if all is well
    }

}

you can also do similar for get() BTW.
Another method to do stuff on setting is using var a: String by Delegate.vetoable.... and other Delegate methods - giving you high control over what's happening on setting a new value.
class A {
    var str: String = ""
        set(str) {
            // check some stuff here, throw Exception
            field = str // if all is well
        }

    var observableDelegate: String by Delegates.observable("") { p, o, n ->
        println("property: [$p], Old: [$o], New [$n]")
    }

    var notNullValue: String by Delegates.notNull<String>()

    var vetoable: String by Delegates.vetoable("") { property, oldValue, newValue ->
        println("property: $property, old: $oldValue, new: $newValue")
        newValue != "bla" && oldValue < newValue
    }
}

fun main() {
    val a = A()

    a.observableDelegate = "blub"

    println("Set value ${a.observableDelegate}")

    runCatching { a.notNullValue }.onFailure {
        println("Like expected: value not set yet, exception: ${it.message}")
    }

    a.notNullValue = "fuddder"
    println("Now notNullValue is set: ${a.notNullValue}")

    println("Vetoable now: ${a.vetoable} - setting to \"a\"")
    a.vetoable = "a"
    println("Vetoable now: ${a.vetoable} - setting to \"b\"")
    a.vetoable = "b"
    println("Vetoable now: ${a.vetoable} - setting to \"a\" again - should not work")
    a.vetoable = "a"
    println("Vetoable now: ${a.vetoable}")
}

output:
property: [var com.savinggrains.mwh.web.rest.A.observableDelegate: kotlin.String], Old: [], New [blub]
Set value blub
Like expected: value not set yet, exception: Property notNullValue should be initialized before get.
Now notNullValue is set: fuddder
Vetoable now:  - setting to "a"
property: var com.savinggrains.mwh.web.rest.A.vetoable: kotlin.String, old: , new: a
Vetoable now: a - setting to "b"
property: var com.savinggrains.mwh.web.rest.A.vetoable: kotlin.String, old: a, new: b
Vetoable now: b - setting to "a" again - should not work
property: var com.savinggrains.mwh.web.rest.A.vetoable: kotlin.String, old: b, new: a
Vetoable now: b


text:
Q: could not find property on root project gradle for custom task I have written a custom task copyDocs to copy the build output to some other directory and have given this task in the dependsOn as following:
task doit(dependsOn: ['clean', 'build', 'copyDocs'])
build.mustRunAfter clean
copyDocs.mustRunAfter build
....
....
task copyDocs(type: Copy) {
     from 'build/libs'
     into 'build'
 }

Above is the custom task doit that has to execute clean, build and copyDocs in the order defined using mustRunAfter. But it gives an error during execution.
During execution (i.e. cmd>gradle doit), I am getting the following error:

* What went wrong:
A problem occurred evaluating script.
> Could not find property 'copyDocs' on root project 'gradle'.
BUILD FAILED

Please help in resolving this issue.

A: You get this error since there is no defined task called copyDocs when copyDocs.mustRunAfter executed.
You should put copyDocs task definition before copyDocs.mustRunAfter build statement.


text:
Q: Disable iOS keyboard (don't show it at all) in phonegap If I were writing a native app I would try the solution given here which says:
"Try to implement the following method in text view's delegate:"

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    return NO;
}

Unfortunately I need to use phonegap, so I don't have a text view to manipulate. It would be great if I could permanently suppress the keyboard in this app. We've got some custom on screen keyboard that people are supposed to use instead. So, any idea how to disable the popup keyboard completely?

A: Just put a transparent div over the input field, so the the click will be on that div and not on the input field. Now you can activate your own keyboard by click and fill in the characters with javascript.

*

*Update:

The following solution works:
The keyboard is directly linked to the focus on the input field. when you use readonly="true", you can get the click event and then you should be able to chamge the value. in jQuery something like this: $('myinputfield').click(function(){$(this).val(newinput);});


text:
Q: Upgrade JDK on Mac OSX I am using default JDK on my MacBook Pro which runs with 10.6.8. I want to upgrade my JDK version but I didn't find on Oracle web site. Where can I download for Mac?

A: Only Java JDK 7 comes from Oracle and requires OSX 10.7.3 or higher See Oracle's mac install info
Earlier OS and JDKs were released by Apple. Latest version is 1.6.0_37


text:
Q: Resizing the buttons in kivy import numpy as np
import kivy
kivy.require('1.0.6') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label

class myLayout(BoxLayout):
     def __init__(self, **kwargs):
         super(myLayout, self).__init__(**kwargs)

         btn1 = Button(text = "click 1", background_color=[0,0,1,0],pos=(200, 100))
         btn1.bind(on_press=self.clk1)
         btn2 = Button(text = "click 2", pos=(200, 100))
         btn2.bind(on_press=self.clk)
         btn3 = Button(text = "click 3", pos=(50, 100))
         btn3.bind(on_press=self.clk)

         self.add_widget(btn1)
         self.add_widget(btn2)
         self.add_widget(btn3)

    def clk(self, obj):
         print("Hello WOrld")

    def clk1(self, obj):
         dataset = np.genfromtxt(fname='data.txt',skip_header=1)
         print dataset

class NameApp(App):
     def build(self):
     mL = myLayout()
     return mL

if __name__ == '__main__':
    NameApp().run()

This program is running fine however i am not able to figure out why the size and position of buttons are not changing?
dataset contains numeric value say say two dimension
1 2
3 4
5 6
7 8
how can i plot these values inside the GUI?

A: You can work with Float Layout
add this in your main.py file
from kivy.uix.floatlayout import FloatLayout
...
btn1 = Button(text = "click 1",pos=(200, 200),size_hint = (.1,.1))
btn2 = Button(text = "click 2", pos=(200, 100),size_hint = (.1,.1))
btn3 = Button(text = "click 3", pos=(50, 100),size_hint = (.1,.1))

OR
btn1 = Button(text = "click 1",pos_hint= {'x': .1,'top': .2},size_hint = (.1,.1))
btn2 = Button(text = "click 2", pos_hint= {'x': .4,'top': .2},size_hint = (.1,.1))
btn3 = Button(text = "click 3", pos_hint= {'x': .66,'top': .2},size_hint = (.1,.1))

See here under layout section for more on layouts.
You might wanna checkout KivyCatalog and KivyShowcase.
EDIT: 1
Oops! I forgot to add this part.

how can i plot these values inside the GUI?

Use Label
self.lbl = Label(pos_hint= {'x': .73,'top': .6},size_hint = (.1,.1))
self.add_widget(self.lbl)

def clk1(self, obj):
....
self.lbl.text = str(dataset)

A: import kivy
kivy.require('1.0.6') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty
from kivy.garden.graph import Graph, MeshLinePlot
import math
from Tkinter import Tk
from tkFileDialog import askopenfilename
import os

class myLayout(FloatLayout):
   def __init__(self, **kwargs):
       super(myLayout, self).__init__(**kwargs)
       btn1 = Button(text = "click 1",pos_hint= {'x': .1,'top': .2},size_hint = (.1,.1))
       btn2 = Button(text = "click 2", pos_hint= {'x': .4,'top': .2},size_hint = (.1,.1))
       btn3 = Button(text = "click 3", pos_hint= {'x': .66,'top': .2},size_hint = (.1,.1))

       btn1.bind(on_press=self.clk1)
       btn2.bind(on_press=self.clk2)
       btn3.bind(on_press=self.clk3)

       self.add_widget(btn1)
       self.add_widget(btn2)
       self.add_widget(btn3)

   def clk1(self, obj):
       print("Hello World")

   def clk2(self, object):
       Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
       filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
       print(filename)

   def clk3(self, object):
       graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,x_ticks_major=25, y_ticks_major=1,y_grid_label=True, x_grid_label=True, padding=5,
     x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1)
       plot = MeshLinePlot(color=[1, 0, 0, 1])
       plot.points = [(x, math.sin(x / 10.)) for x in range(0, 101)]
       graph.add_plot(plot)
       self.add_widget(graph)

class NameApp(App):
   def build(self):
       mL = myLayout()
       return mL

if __name__ == '__main__':
   NameApp().run()

Here is the running code, however how can i use canvas to draw plots and option to change size and shape of it.


text:
Q: CakePHP 2.0: Odd Auth Login Issue I have a strange issue going on as I try to learn and program website using CakePHP 2.0. I have worked in the past with version 1.3 but never seen this problem before. I am running the Simple Authentication and Authorization Application tutorial from the Cookbook (p.638) and I have checked and doubled checked to make sure it is the same.
The issue I am having is that when I call /users/login and fill out the form with bogus info or simply leave it empty. Auth logs it in and if I do if($this->Auth->user()) I will receive true.
I have given up trying to understand why that is happening. It is strange....
/users/login
public function login(){
        if($this->request->is('post')){
            if($this->Auth->login($this->request->data)){
                $this->redirect($this->Auth->redirect());
            }else{
                $this->Session->setFlash('Wrong login credentials!', 'default', array('class' => 'notification error closeable'));
            }
        }
}

// Appcontroller.php ---- Auth configuration
class AppController extends Controller {

public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email')
            )
        ),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'home'),
        'authorize' => array('Controller')
    )
);

 public function isAuthorized($user){
    if(isset($user['role']) && $user['role'] === 'admin'){
        return true;
    }
    return false;
}

A: Ok.Seems like i know what the problem is. Try doing:
if($this->Auth->login())

instead of passing it CakeRequest object.
The reason is:
In 2.0 $this->Auth->login($this->request->data) will log the user in with whatever data is posted, whereas in 1.3 $this->Auth->login($this->data) would try to identify the user first and only log in when successful. Maybe thats why you are able to log in without any data.

A: public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email')
            )
        ),
        'loginAction' => array('admin' => false, 'controller' => 'users', 'action' => 'login')
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'home'),
        'authorize' => array('Controller')
    )
);

Also try putting a debug($user); in beginning your isAuthorized method in AppController to see if its not getting a false from there.


text:
Q: How to extract all words in a noun food category in WordNet? I am trying to get all the words in Wordnet dictionary that are of type noun and category food.
I have found a way to check if a word is noun.food but I need the reverse method:
import nltk
nltk.download('wordnet')
from nltk.corpus import wordnet as wn

def if_food(word):
    syns = wn.synsets(word, pos = wn.NOUN)
    for syn in syns:
        print(syn.lexname())
        if 'food' in syn.lexname():
            return 1
    return 0

A: So I think I have found a solution:
# Using the NLTK WordNet dictionary check if the word is noun and a food.
import nltk
nltk.download('wordnet')
from nltk.corpus import wordnet as wn

def if_food(word):

    syns = wn.synsets(str(word), pos = wn.NOUN)

    for syn in syns:
        if 'food' in syn.lexname():
            return 1
    return 0

Then using the qdapDictionaries::GradyAugmented R English words dictionary I have checked each word if it's a noun.food:
en_dict = pd.read_csv("GradyAugmentedENDict.csv")

en_dict['is_food'] = en_dict.word.apply(if_food)

en_dict[en_dict.is_food == 1].to_csv("en_dict_is_food.csv")

It it actually did the job.
Hope it will help others.


text:
Q: R readHTMLTable failed to load external entity When I run the line on my laptop,
table500 <- readHTMLTable('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[[1]]

it gets the data. When I run it on my desktop, I receive the error
Error: failed to load external entity "http://en.wikipedia.org/wiki/List_of_S%26P_500_companies".

So I'm guessing the problem has something to do with network settings in my desktop, I haven't the slightest idea what it could be though. Any suggestions?

A: In the link that I mentioned in the comment, you can find solutions using RCurl and httr package. Here, I provide the solution using rvest package.
   library(rvest)
    kk<-html("http://en.wikipedia.org/wiki/List_of_S%26P_500_companies")%>%
    html_table(fill=TRUE)%>%
    .[[1]] //table 1 only

head(kk)
  Ticker symbol            Security SEC filings            GICS Sector                GICS Sub Industry Address of Headquarters
1           MMM          3M Company     reports            Industrials         Industrial Conglomerates     St. Paul, Minnesota
2           ABT Abbott Laboratories     reports            Health Care Health Care Equipment & Services North Chicago, Illinois
3          ABBV              AbbVie     reports            Health Care                  Pharmaceuticals North Chicago, Illinois
4           ACN       Accenture plc     reports Information Technology   IT Consulting & Other Services         Dublin, Ireland
5           ACE         ACE Limited     reports             Financials    Property & Casualty Insurance     Zurich, Switzerland
6           ACT         Actavis plc     reports            Health Care                  Pharmaceuticals         Dublin, Ireland
  Date first added     CIK
1                    66740
2                     1800
3       2012-12-31 1551152
4       2011-07-06 1467373
5       2010-07-15  896159
6                   884629


text:
Q: EOFError error in dev_appserver.py for Google App Engine in python I run this in a clean virtual enviroment with no module installed on lib on my local machine. I have my app ready to run but I cannot start dev_appserver.py, I obtain this error
dev_appserver.py app.yaml

INFO 2018-06-20 11:24:01,578 devappserver2.py:120] Skipping SDK update check.
Traceback (most recent call last):
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\dev_appserver.py", line 96, in <module>
_run_file(__file__, globals())
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\dev_appserver.py", line 90, in _run_file
execfile(_PATHS.script_file(script_name), globals_)
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 454, in <module>
main()
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 442, in main
dev_server.start(options)
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\devappserver2.py", line 197, in start
configuration.modules[0].application_root)
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\api_server.py", line 640, in create_api_server
if options.support_datastore_emulator else None)
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\stub_util.py", line 255, in setup_stubs
simple_search_stub.SearchServiceStub(index_file=search_index_path))
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\api\search\simple_search_stub.py", line 700, in __init__
self.Read()
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\api\search\simple_search_stub.py", line 1214, in Read
read_indexes = self._ReadFromFile()
File "C:\Users\aris\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\api\search\simple_search_stub.py", line 1188, in _ReadFromFile
version, indexes = pickle.load(open(self.__index_file, 'rb'))
EOFError

These are the versions of google cloud, that is updated to last version.I try to update like is here specified
https://cloud.google.com/appengine/docs/standard/python/download
but it didn't work
gcloud --version

Google Cloud SDK 206.0.0
app-engine-python 1.9.70
app-engine-python-extras 1.9.69
beta 2018.06.12
bq 2.0.34
core 2018.06.18
gsutil 4.32

This is the version of python
python --version

Python 2.7.14

Please, any help with this?

A: It was solved like this:
Open:
c:\users\{your_pc_name}\appdata\local\temp

Delete the directory named:
appengine.{your_app_name}


text:
Q: How do i make this query more simple Is there a way to insert this data into access's table?
I use this code but I search about way to insert the same data into same columns.
How can I do that ?
cmd.CommandText = "INSERT INTO lab ([lname],dtnow,wbc,rbc,hb,hcv,[Field1],[Field2],[Field3],a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa,bb,cc,dd,ff,rr,hh) VALUES (@lname,@dtnow,@wbc,@rbc,@hb,@hcv,@f1,@f2,@f3,@a,@b,@c,@d,@e,@f,@g,@h,@i,@j,@k,@l,@m,@n,@o,@p,@q,@r,@s,@t,@u,@v,@w,@x,@y,@z,@aa,@bb,@cc,@dd,@ff,@rr,@hh)";
cmd.Parameters.AddWithValue("@lname", age.Text);
cmd.Parameters.AddWithValue("@dtnow", dt.ToString("MM/dd/yyyy"));
cmd.Parameters.AddWithValue("@wbc", age1.Text);
cmd.Parameters.AddWithValue("@rbc", age2.Text);
cmd.Parameters.AddWithValue("@hb", age3.Text);
cmd.Parameters.AddWithValue("@hcv", age4.Text);
cmd.Parameters.AddWithValue("@f1", age5.Text);
cmd.Parameters.AddWithValue("@f2", age6.Text);
cmd.Parameters.AddWithValue("@f3", age7.Text);
cmd.Parameters.AddWithValue("@a", age8.Text);
cmd.Parameters.AddWithValue("@b", age9.Text);
cmd.Parameters.AddWithValue("@c", age10.Text);
cmd.Parameters.AddWithValue("@d", age11.Text);
cmd.Parameters.AddWithValue("@d", age12.Text);
cmd.Parameters.AddWithValue("@f", age13.Text);
cmd.Parameters.AddWithValue("@g", age14.Text);
cmd.Parameters.AddWithValue("@h", age15.Text);
cmd.Parameters.AddWithValue("@i", age16.Text);
cmd.Parameters.AddWithValue("@j", age17.Text);
cmd.Parameters.AddWithValue("@k", age18.Text);
cmd.Parameters.AddWithValue("@l", age19.Text);
cmd.Parameters.AddWithValue("@m", age20.Text);
cmd.Parameters.AddWithValue("@n", age21.Text);
cmd.Parameters.AddWithValue("@o", age22.Text);
cmd.Parameters.AddWithValue("@p", age23.Text);
cmd.Parameters.AddWithValue("@q", age24.Text);
cmd.Parameters.AddWithValue("@r", age25.Text);
cmd.Parameters.AddWithValue("@s", age26.Text);
cmd.Parameters.AddWithValue("@t", age27.Text);
cmd.Parameters.AddWithValue("@u", age28.Text);
cmd.Parameters.AddWithValue("@v", age29.Text);
cmd.Parameters.AddWithValue("@w", age30.Text);
cmd.Parameters.AddWithValue("@x", age31.Text);
cmd.Parameters.AddWithValue("@y", age32.Text);
cmd.Parameters.AddWithValue("@z", age33.Text);
cmd.Parameters.AddWithValue("@aa", age34.Text);
cmd.Parameters.AddWithValue("@bb", age35.Text);
cmd.Parameters.AddWithValue("@cc", age36.Text);
cmd.Parameters.AddWithValue("@dd", age37.Text);
cmd.Parameters.AddWithValue("@ff", age38.Text);
cmd.Parameters.AddWithValue("@rr", age39.Text);
cmd.Parameters.AddWithValue("@hh", age40.Text);

Please don't care about age1, age2, age3, ..., agen they are just for testing.

A: Maybe you can use an array just to make your code looks simplier.
string[] table = {"Field1", "Field2", "Field3",...};
Control[] text = { textbox1.Text, textbox2.Text, textbox3.Text, ....};

    for(int i =0; i < table.Length; i++)
    {
        cmd.CommandText = "INSERT INTO lab(" + (table[i]) + ")";
        cmd.Parameters.Add("@" + table[i], text[i]);
    }


text:
Q: Tethering app code for iOS Many of you know there was a Flashlight app with a hidden feature that enabled tethering, that snuck into the App Store this week. It was removed very quickly, about 10 minutes before I found out so I wasn't able to snag it up. I have a developer account so I was thinking if I could get the code to a tethering app I could install it on my phone myself.
Are there any open source tethering apps out there?

A: Found the answer myself.
http://wiki.github.com/tcurdt/iProxy/
w00t!


text:
Q: A small line before the begin and end of example I have this example style:
\newtheoremstyle{example}{}{}{}{}{\bfseries}{\smallskip}{\newline}{}
\theoremstyle{example}
\newtheorem{example}{Example}

I want put a small and bold light green line before the "Example" title and after the end of the example. Is possible to do this?

A: It is possible. Something like
\documentclass{article}
\usepackage{amsthm}
\newtheoremstyle{example}{}{}{}{}{\bfseries}{\smallskip}{\newline}{}
\theoremstyle{example}
\newtheorem{example}{Example}
%%
\usepackage[nopar]{lipsum}
\usepackage{xcolor}
%%
\newenvironment{greenexample}{%
  \par\noindent{\color{green}\hrule height 1pt}\hfill\vspace*{-\baselineskip}
  \begin{example}%
  }{%
    \strut{\color{green}\hrule height 1pt\hfill}
  \end{example}
}
\begin{document}
\lipsum[2]

\begin{example}[Test]
  As an example \textit{e.g.} can be used.
\end{example}

\lipsum[2]

\begin{greenexample}[Test]
  As an example \textit{e.g.} can be used.
\end{greenexample}

\lipsum[2]
\end{document}

A: A simple solution with thmtools, which cooperates with amsthm:
\documentclass{article}
\usepackage{amsthm, thmtools}

\newtheoremstyle{example}{}{}{}{}{\bfseries}{\smallskip}{\newline}{}
%
\declaretheorem[%
style=example,%
preheadhook={\bigskip{\color{DarkSeaGreen3}\hrule height 0.8pt\vspace{-1ex}}},%
postfoothook={\vspace{-0.8ex}{\color{DarkSeaGreen3}\hrule height 0.8pt}\bigskip}]%
{Example}%
\usepackage{lipsum, graphicx}
\usepackage[x11names]{xcolor}

\begin{document}

\lipsum[2]
%
\begin{Example}[Test]
  As an example \textit{e.g.} can be used by Latin lovers ; o)
  \begin{center}
    \includegraphics[scale=0.5]{pepe-le-pew2}
  \end{center}
\end{Example}
%
\lipsum[11]

\end{document}


text:
Q: iOS SDK NSXMLParserDelegate Warning I have an application running SDK 3.2, I am using NSXMLParserDelegate for parsing XML.
I upgraded it to SDK 4.2 and my application keeps crashing when using the NSXMLParserDelegate, a warning said:
'Class' does not implement the 'NSXMLParserDelegate' protocol

I have tried the following:

*

*Add the protocol to my class NSObject <NSXMLParserDelegate>

*#import <Foundation/NSXMLParser.h>

But all my attempt had failed, please any help is so much appreciated.

A: Import the Foundation/NSXMLParser.h in header file and just put this line before your interface declaration:
@protocol NSXMLParserDelegate;
// ... and this code you already have but just to be sure it is written as:
@interface SomeYourClass <NSXMLParserDelegate> {

This is a forward declaration of protocol that is actually missing in newer version of NSXML parser.

A: You can ignore that warning and you even should otherwise it wont run on older OSes.
About the crashing:
Since the update to 4.2 i have the same problem when xmlparsing. The problem is that after the update the memory is getting filled and filled until the app crashes. The app had been working for months with no problem even with a hughe amount of data, those days are over.
Unfortunately I dont know how to solve it properly. Have tried to find something in here but people keep insisting thats a bug in my code and that there is no change in the memory management...me i dont think so. Maybe there is really no change in memory management but then its another bug of iOS 4.2. I have limited my records now to 50 and it works a bit better...but thats not really a solution.
Hints are mostly welcome :-)