text:
Q: on counting of special case of trees on a graph Lets define edge-cycle in a graph $G$ as a path where the first and the last node are adjacent.
(in contrast with the definition of cycle where first and last node are the same).
An edge-tree $T$ is a tree with the additional property that doesn't have an edge-cycle.
In a graph we can compute the number of spanning trees by using the Matrix-Tree theorem.

Is there any similar theorem for the computation of the number of edge-trees of a graph?

A: I'll answer a question raised in the comments:
Problem: Count the number of induced trees of size $k$.
According to this paper by Erdös, Saks and Sos, it is NP-complete to decide given a graph $G$ and an integer $k$, if $G$ contains an induced tree of size $k$.  So, it's probably pretty damn hard to count them.  Apparently, it remains NP-complete even for bipartite graphs.
Actually, the argument is pretty simple so I'll include it here.  Given a graph $H$ and an integer $k$, it is well-known that the problem of deciding if $H$ has an independent set of size $k$ is NP-complete.  Suppose that $H$ has $n$ vertices.  Let $G$ be the graph obtained from $H$ by first adding a disjoint copy of $P_n$ (a path on $n$ vertices), and then connecting one end of $P_n$ to all the vertices in $H$.  Clearly, $H$ has an independent set of size $k$ if and only if $G$ contains an induced tree of size $n+k$.

A: If I'm reading your definitions right, I believe the answer is that there are zero edge-trees of G if G has any cycle. And one if G is a tree itself (T=G)
Proof:
  If G has a cycle C, then for any spanning tree T of G there exist an edge E(u,v) of C that is not in T. Since T is a spanning tree, there is a path from u to v in T, and u and v are adjacent in G, thus the path from u to v is an edge-cycle, therefore there is always an edge-cycle in T. Therefore there are zero edge-trees of G.


text:
Q: Shredding XML Data into Tables I have an issue where I must shred multiple xml datasets from multiple providers into a single set of tables by mapping various elements in the sources to my own tables.  I can do this just fine when I am gathering the top level information, but some of my information is in a collection, such as the categories.  My first step is just to pull the data out of XML and put it into a few tables and then the next step is to merge the data into my real tables.
My XML Data looks like this:
<ArrayOfApiNewItemDetailInfo>
  <ApiNewItemDetailInfo>
    <categories>
      <ApiNavCategoryInfo>
        <count></count>
        <id></id>
        <name></name>
        <selected></selected>
      </ApiNavCategoryInfo>
      <ApiNavCategoryInfo>
        <count></count>
        <id></id>
        <name></name>
        <selected></selected>
      </ApiNavCategoryInfo>
    </categories>
    <item_id></item_id>
    <product_id></product_id>
   </ApiNewItemDetailInfo>
<ArrayOfApiNewItemDetailInfo>

I want to shred this data into a table with product id, item id, and category id, when multiple categories can be assigned to a single product
Firstly, I have my DataDictionary table
CREATE TABLE [dbo].[DataDictionary](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [Provider] [varchar](50) NOT NULL,
 [XmlColumn] [varchar](100) NOT NULL,
 [Datatype] [varchar](100) NOT NULL,
 [DestinationColumn] [varchar](100) NOT NULL
)

In this table I have these records:
88 Categories product_id int ProviderProductId
89 Categories item_id int ItemId
93 Categories categories/ApiNavCategoryInfo/id int CategoryId

Now, I have a sql statement that pulls in the data dictionary for my provider and shreds the data into a table.
CREATE TABLE #SQLWork (Row_Id INT IDENTITY,SQL varchar(500))

 INSERT #SQLWork (SQL) VALUES ('DROP TABLE TempCategories')
 INSERT #SQLWork (SQL) VALUES ('SELECT ')
 INSERT #SQLWork (SQL) SELECT 'Categories.value(''' + XmlColumn + '[1]''' + ',''' + Datatype + ''') as ' + DestinationColumn + ', '
     FROM DataDictionary WHERE UPPER(Provider) = 'CATEGORIES'

 UPDATE #SQLWork SET SQL = REPLACE(SQL,', ','') WHERE row_id = @@IDENTITY

 INSERT #SQLWork (SQL) VALUES ('  INTO TempCategories ')
 INSERT #SQLWork (SQL) VALUES (' FROM RawDetails CROSS APPLY Data.nodes(''' + '//ArrayOfApiNewItemDetailInfo/ApiNewItemDetailInfo' + ''') as NewTable(Categories)')

 DECLARE @SQL nvarchar(max)

 select @SQL = coalesce(@SQL + ' ',' ') + Sql from #SQLWork Order By Row_Id
 --SELECT @SQL
 exec sp_executesql @sql

 drop table #Sqlwork

The sql statement that is generated looks like this:
 DROP TABLE TempCategories
 SELECT
    Categories.value('product_id[1]','int') as ProviderProductId,
    Categories.value('item_id[1]','int') as ItemId,
    Categories.value('categories/ApiNavCategoryInfo/id[1]','int') as CategoryId
 INTO
    TempCategories
FROM
    RawDetails
CROSS APPLY
    Data.nodes('//ArrayOfApiNewItemDetailInfo/ApiNewItemDetailInfo') as NewTable(Categories)

When I run my statement, I get the error:

XQuery [RawDetails.Data.value()]:
  'value()' requires a singleton (or
  empty sequence), found operand of type
  'xdt:untypedAtomic *'

Any ideas?
Thanks.

A: I found out that my paths were wrong.
I changed
Data.nodes('//ArrayOfApiNewItemDetailInfo/ApiNewItemDetailInfo') as NewTable

to
Data.nodes('//ArrayOfApiNewItemDetailInfo/ApiNewItemDetailInfo/categories/ApiNavCategoryInfo') as NewTable

And I changed my records with this
88 Categories ../../product_id int ProviderProductId
89 Categories ../../item_id int ItemId
93 Categories id int CategoryId

And that worked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: webview onNavigationStateChange returns url of previous page In react native webview, when I navigate to a page the onNavigationStateChange returns url of the previous page? I think its an issue and posted it to github react native issues.
  <WebView
   ref={r => this.webview = r}
   style = {{marginTop : 0}}
   onNavigationStateChange=
   {this._onNavigationStateChange.bind(this)}
         startInLoadingState = {true}
         source = {{uri: 'https://www.youtube.com' }}
    />

   _onNavigationStateChange(webViewState)
     {
       this.setState(
            {
               youtube_video_url: webViewState.url
            })
         }

When I print this youtube_video_url, it is of the previous page or previous browsed video.

A: Sadly, all the webview methods like onNavigationStateChange, onLoad, onLoadStart etc are not working as expected in cases of single page application websites or websites that don't trigger a window.load event.
Normaly onNavigationStateChange gets triggered in the beginning of a request with {loading: true, url: "someUrl", ...} and once after the loading of the url with {loading: false, url: "someUrl", ...}.
There is no global workaround (to my knowledge) that will work correctly for all websites and for both iOs/Android but maybe this can help in your case:
https://snack.expo.io/H1idX8vpM
Basically you inject a custom javascript in the webview that notifies the WebView which is the loaded page. You can enhance it if you want to catch custom window.history manipulation events.


text:
Q: Function takes longer than expected to complete I've created a simple sliding function that should make an element appear or disappear in the amount of time given.
My formula for building this function is: ms = 1 pixel / (initial size / duration), essentially calculating how many milliseconds should pass before subtracting 1px from the element's height or width.
My math logic says that the function should complete in 1000ms, yet to me,  the time it takes to complete looks significantly more, without being sure how much.
Why does it take longer than 1s to complete and what may be causing it?
Code:

/* ----- JavaScript ----- */
function slide(el, duration, direction) {
  /* Default */
  duration = duration || 1000, direction = direction || "vertical";

  var
    dim = (direction === "horizontal") ? "width" : "height",

    /* Get how tall or wide el is in 'px' */
    size = initSize = parseFloat(
      getComputedStyle(el, null).getPropertyValue(dim) || el.style[dim]
    ),

    /* Get the previous size, so as to restore el to it */
    prevSize = el.style["prev" + dim] || 0,

    /* Calculating how many ms should pass before subtracting 1px*/
    ms = 1 / (initSize / duration),

    interval = setInterval(function() {
      /* If el is visible */
      if (initSize > prevSize && size > prevSize) el.style[dim] = --size + "px";

      /* If el is not visible */
      else if (prevSize > initSize && size <= prevSize) el.style[dim] = ++size + "px";

      /* Clear the interval when 0 is reached and cache the previous size */
      else {
        console.log("oops")
        el.style["prev" + dim] = initSize;
        clearInterval(interval);
      }
    }, ms);
}

slide(document.getElementById("a"));

A: you need to adjust your step size i.e number of pixel to be added/removed per iteration and adjust the delay time. following is a improved version which takes about around 1.1 sec.
function slide(el, duration, direction) {
  /* Default */
  duration = duration || 1000, direction = direction || "vertical";

  var dim = (direction === "horizontal") ? "width" : "height",

    /* Get how tall or wide el is in 'px' */
    size = initSize = parseFloat(
      getComputedStyle(el, null).getPropertyValue(dim) || el.style[dim]
    ),

    /* Get the previous size, so as to restore el to it */
    prevSize = el.style["prev" + dim] || 0;

    /* Calculating how many ms should pass before subtracting 1px*/
    var step = 1;
     var ms = 1 / (initSize / duration)
    if(ms<10){
        ms=10;
        step = 10*(initSize/duration);
        console.log(ms,step)
    }
      var now=new Date();
      var interval;var i=0;
    var animate = function() {
    i++;
        interval=setTimeout(animate,ms);
      /* If el is visible */
      if (initSize > prevSize && size > prevSize) el.style[dim] = (size=size-step) + "px";

      /* If el is not visible */
      else if (prevSize > initSize && size <= prevSize) el.style[dim] = (size=size+step) + "px";

      /* Clear the interval when 0 is reached and cache the previous size */
      else {
        console.log("oops", new Date()-now,size,step,i)
        el.style["prev" + dim] = initSize;
        clearInterval(interval);
      }
    };
    //var interval = setInterval(animate, ms);
    animate();
}
slide(document.getElementById("a"));

A: After some thoughts that reading Jaromanda X's comments made me have, I finally ended up using window.requestAnimationFrame(), as it's more efficient than setInterval() and it also doesn't force browser redraw.
This in turn made me change my formula from time-oriented (ms = 1 / (initial size / duration)) to pixel-oriented (px = frame * (initial size / duration)).
The sliding is smoother now and very close to 1000ms, with only 5-7ms difference which I believe occurs, because I have set the frame variable to 1000 / 60 not taking into consideration the frame rate drops that may occur.
Code:

/* ----- JavaScript ----- */
function slide(el, duration, direction) {
  /* Set Defaults and record starting date */
  var a = Date.now();
  duration = duration || 1000, direction = direction || "vertical";

  var
    dim = (direction === "horizontal") ? "width" : "height",

    /* Get how tall or wide el is in 'px' */
    size = initSize = parseFloat(
      getComputedStyle(el, null).getPropertyValue(dim) || el.style[dim]
    ),

    /* Get the previous size, so as to restore el to it */
    prevSize = el.style["prev" + dim] || 0,

    /* Calculating how many px should be added / subtracted each frame */
    frame = 1000 / 60,
    px = frame * (initSize / duration),
    step = (initSize > prevSize) ? -px : px;

  window.requestAnimationFrame(function transform() {
    el.style[dim] = (size > 0) ? (size += step) + "px" : (size = 0);
    if (size === 0) {
      el.style["prev" + dim] = initSize;
      //element.style.prevDisplay = initDisplay;
      console.log(Date.now() - a)
    } else window.requestAnimationFrame(transform);
  }, frame);
}

slide(document.getElementById("a"), 1000);


text:
Q: How can I determine what flash player version a swf was published for? I have a SWF of unknown origin, and I need to know which flash player version it was targeted at when it was published. How do I get this info?

A: Most - all? - of the answers so far are incorrect, which is unfortunate as I was hoping to find an answer to this question :).
Byte 4 of the SWF indicates what version of the SWF file format is used by the SWF. That is not the same as the target player version.
The minimum player version is set at compile time through the compiler option target-player, while the SWF file format version is set through the option swf-version.
The default values for these options can be found inside FLEX_SDK/frameworks/flex-config.xml. For the SDK version I'm using (4.5.1), the defaults are as follows:
    <!-- Specifies the minimum player version that will run the compiled SWF. -->
   <target-player>10.2.0</target-player>

    <!-- Specifies the version of the compiled SWF -->
    <swf-version>11</swf-version>

This means swfversion.com shows 11 for my SWF, even though I only require users to have 10.2. And according to http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7a92.html, Flex 4.6 sets target-player to 11.1 and swf-version to 14. So I'm not clear how swfversion.com is at all useful.

A: The 4th byte in the SWF file carries the version number, for example 0A is for Flash Player 10.
EDIT: Because of the high interest this question got I've decided to give more feedback
The first 8 bytes of any SWF file are not compressed, the rest of the file could be compressed (or not) by zlib compression.

*

*1st byte: 'F' (not compressed) OR 'C' (compressed).

*2nd byte: 'W' always.

*3rd byte: 'S' always.

*4th byte: version number (09 means this file is targeted at Flash Player 9 and so on...)

*5th to 8th: Length of entire file in bytes.

A: You could use DoubleClick's Flash Validator tool:
https://flashval-temp.appspot.com/validator/
It will provide information such as SWF name, version, file size, dimensions, frames per second, compression, and total frames.

A: Take a gander at the SWF spec from http://www.adobe.com/devnet/swf.html
Then do a hex dump or open the SWF in an editor that can display hex.  The SWF version is one of the first few bytes and is before the compressed data starts.  I want to say it is byte 4, but I don't totally recall.  The value is the version number.  IIRC, the point version is not encoded in the SWF.
GNU file may also tell you.  I may have edited my rules to do this, though.

A: The Flex SDK contains a tool called swfdump that displays all of the metadata inside of a SWF file.  Here is the beginning of the output when I run "swfdump foo.swf":
<swf xmlns='http://macromedia/2003/swfx' version='9' framerate='24' size='10000x7500' compressed='true'>

A: This adds on what brian sharon said.
Yes the 1-to-1 mapping of swf-version and Flash Player version is no longer there.
What the 4th byte depicts is the -swf-version, and what's good about this is that there is now a one to one relation with point releases.
Look at these references:
http://blogs.adobe.com/airodynamics/2011/08/16/versioning-in-flash-runtime-swf-version/
http://sleepydesign.blogspot.in/2012/04/flash-swf-version-meaning.html
From the second link:
Compiler Option     Flash Player Version
-swf-version=9      9
-swf-version=10     10, 10.1
-swf-version=11     10.2
-swf-version=12     10.3
-swf-version=13     11.0
-swf-version=14     11.1
-swf-version=15     11.2
-swf-version=16     11.3

I am using this information from flash game files to warn users that their flash player might be outdated on my flash games portal. And this works just fine.


text:
Q: Referencing xml file with dynamic file name I need to be able to Reference an xls file name which has a dynamic date at the end that changes.  The file name is made up of 2 parts.  The first part is the static name that doesn't change but the second part which is in date format does change. The format of the file name is as follows
stock_newupdated__16-03-2013_10-41-58.xls
Not sure how to go about this one.
$filename = 'staticpartofilename_dynamicdateontheend'

$file_handle = fopen($filename . "xls", "r");

while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 1024);

$sku = $line_of_text[0];
$sql   = "UPDATE mytable SET quantity = 0 WHERE SKU = '" . $sku . "'";
$result = dbQuery($sql);
}


text:
Q: How to pass filename to Heroku pg:sql command? I want to load schema from structure.sql file to my Heroku database. On my localhost machine I do as follows and all works just fine, all tables are created:
C:\> psql -U postgres -a -d MyApp_development -f C:\MyApp\db\structure.sql

I pass a local file name as -f option: -f C:\MyApp\db\structure.sql
When I do the same on Heroku, it complains that the app is not found. I think that it doesn't understand -f option. It cannot find file C:\MyApp\db\structure.sql on its server.
So how do I need to provide correct path relative to Heroku? structure.sql has to be located here on Heroku:
MyApp\db\structure.sql

So I need to do something like this:
heroku pg:psql -U ... -a -d MyHerokuDB -f MyHerokuAppRoot\db\structure.sql

What is MyHerokuAppRoot? What with may substitute it?

A: I found a solution. I think that the problem is that Postgresql takes only forward slash (/) as a directory separator. So when I provide Windows style paths, it doesn't work.
I did as follows. I connected to DB first:
C:\MyApp>heroku pg:psql DATABASE

Then I ran this command:
d17q2hrd89o9cu=> \i C:/MyApp/db/structure.sql

And all tables mentioned in local structure.sql file were created on Heroku hosting.


text:
Q: Routing issue with my controller action I have a populate form method in my user controller.. the problem is when I fill in the text field in my view and click it wants to go trough show in my controller I don't have a show action in my user controller. any help would be greatly appreciated...
This is my errror
Started GET "/user/populate_form&emp_id=BILL" for 127.0.0.1 at 2015-03-23 17:39:17 -0400

AbstractController::ActionNotFound (The action 'show' could not be found for UserController):

This is my User controller
class UserController < ApplicationController

def populate_form
  @visual = Visual.find_by_id(params[:emp_id])
     render :json => {

        :emp_first_name => @emp_first_name
     }
  end
end

def show
  @visual = Visual.find_by_id(params[:emp_id])
     render :json => {

         :emp_first_name => @emp_first_name
     }
  end
end

This is my view..

   <%= f.text_field :emp_id, tabindex: 1, id: 'emp_id', autofocus: true, placeholder: t( 'login_label' ), class: 'form-control' %>

   <%= f.text_field :emp_first_name, tabindex: 1, id: 'emp_first_name', autofocus: true, placeholder: t( 'login_label' ), class: 'form-control' %>

This is my app.js
 $('#emp_id').change(function() {
      var url = '/users/populate_form/';
      $.getJSON(url, function(data) {
        if(!(data.emp_first_name === undefined))
        $('#emp_first_name').val(data.emp_first_name);
      });
     }
   );
 });

This is my routes
Rails.application.routes.draw do

 devise_for :users, controllers: { sessions: 'sessions' }

 root to: 'entry#index'

 resources :entry do
 end

 resources :user do
    collection do
      get :populate_form
    end
  end

 # Routes for API calls only.

 namespace :api do

 end
end

Extra this is what I get when I rake my routes
              Prefix Verb     URI Pattern                    Controller#Action
            teaspoon          /teaspoon                      Teaspoon::Engine
    new_user_session GET      /users/sign_in(.:format)       sessions#new
        user_session POST     /users/sign_in(.:format)       sessions#create
destroy_user_session DELETE   /users/sign_out(.:format)      sessions#destroy
       user_password POST     /users/password(.:format)      devise/passwords#create
   new_user_password GET      /users/password/new(.:format)  devise/passwords#new
  edit_user_password GET      /users/password/edit(.:format) devise/passwords#edit
                     PATCH    /users/password(.:format)      devise/passwords#update
                     PUT      /users/password(.:format)      devise/passwords#update
 cancel_user_registration GET      /users/cancel(.:format)        devise/registrations#cancel
  user_registration POST     /users(.:format)               devise/registrations#create
  new_user_registration GET      /users/sign_up(.:format)       devise/registrations#new
  edit_user_registration GET      /users/edit(.:format)          devise/registrations#edit
                     PATCH    /users(.:format)               devise/registrations#update
                     PUT      /users(.:format)               devise/registrations#update
                     DELETE   /users(.:format)               devise/registrations#destroy
                root GET      /                              entry#index

          entry_index GET      /entry(.:format)               entry#index
                     POST     /entry(.:format)               entry#create
           new_entry GET      /entry/new(.:format)           entry#new
          edit_entry GET      /entry/:id/edit(.:format)      entry#edit
               entry GET      /entry/:id(.:format)           entry#show
                     PATCH    /entry/:id(.:format)           entry#update
                     PUT      /entry/:id(.:format)           entry#update
                     DELETE   /entry/:id(.:format)           entry#destroy
 populate_form_user_index GET      /user/populate_form(.:format)     user#populate_form
          user_index GET      /user(.:format)                user#index
                     POST     /user(.:format)                user#create
            new_user GET      /user/new(.:format)            user#new
           edit_user GET      /user/:id/edit(.:format)       user#edit
                user GET      /user/:id(.:format)            user#show
                     PATCH    /user/:id(.:format)            user#update
                     PUT      /user/:id(.:format)            user#update
                     DELETE   /user/:id(.:format)            user#destroy
                     GET|POST /entry(.:format)               entry#index

now I get this its not picking up what I have in my text box and it querying null...
Started GET "/user/populate_form&emp_id=BILL" for 127.0.0.1 at 2015-03-23 17:52:29 -0400
Processing by UserController#show as JSON
Parameters: {"id"=>"populate_form&emp_id=BILL"}
Visual Load (2.2ms)  SELECT  "EMPLOYEE".* FROM "EMPLOYEE"  WHERE "EMPLOYEE"."ID" IS NULL AND ROWNUM <= 1

A: It might be a bit confusing, but let's go through it together!
You have routes configured like this:
resources :user do
  collection do
    get :populate_form
  end
end

You've been expecting to visit some URL, to call proper action in your controller - populate_form, but for some reason it tries to route your request to show.
Let's check how your URL loos like:
/user/populate_form&emp_id=BILL

This causes the whole request to "fall" into route recognised as:
user GET /user/:id

which corresponds to show action. Whole string "populate_form&emp_id=BILL" falls into params[:id] in your show action. Why didn't it use proper action? We've been expecting to reach populate_form!
Try changing the URL you're visiting slightly from:
/user/populate_form&emp_id=BILL

to:
/user/populate_form?emp_id=BILL

This is easy change, but it should solve your problem!
Hope that helps!


text:
Q: How do you factor: $2x^4+x^3-7x^2-x+5$ I don't know how factor this, I've never factored something with a degree higher than 3.

A: In this case, we can start by applying the rational root theorem to determine possible rational roots. In this case there are 4 total roots.
You can study the rational root theorem here https://en.wikipedia.org/wiki/Rational_root_theorem.
The possible root combinations in this case are $-1,1,-\frac{1}{2},\frac{1}{2},-5,5,-\frac{5}{2}$, and $\frac{5}{2}$.
A look at this function's graph reveals that $x=-1$ is a root with a multiplicity of 1. The graph also reveals that the function's 4 roots are real. This can also be confirmed analytically by Descarte's Rule of signs.
Since we know that $x=-1$ is a root, we can divide the function synthetically by $-1$ to get a cubic function. From there, you can either factor the cubic or perform synthetic division on the cubic with another factor to reduce it to a quadratic.

A: Hint $\ $ It is $\ (2x^4-7x^2+5)  + (x^3-x)\, $ and both clearly have roots $\,x = \pm 1$

A: Hint:
This polynoial is divisible by $x^2-1$:
\begin{align}
2x^4+x^3-7x^2-x+5&=(2x^4-2x^2)+x^3-5x^2-x+5\\
&=2x^2(x^2-1)+ x^2(x-5)-x+5 \\
&= (x^2-1)(2x^2+x-5).
\end{align}+

A: Starting with $2 x^4+x^3-7 x^2-x+5$ and using the insight that $x=1$ must be a factor:
Divide out:
$${2 x^4+x^3-7 x^2-x+5 \over x-1} = 2 x^3+3 x^2-4 x-5$$
Notice again, from the sum of coefficients that $x = -1$ is a root, so divide out again:
$${2 x^3+3 x^2-4 x-5 \over x+1} = 2 x^2+x-5.$$
So:
$$(x-1)(x+1)(2 x^2+x-5)$$
Use the quadratic equation:
$$(x-1)(x+1)(x - 1/4 (-1 - \sqrt{41}))(x+1/4 (-1 - \sqrt{41}))$$


text:
Q: Laravel 4 Cascading Soft Deletes Is there a modular way to perform cascading soft deletes in L4?
My database is already designed to do this with hard deletes because all tables are related to another.. however, I'm using soft deletes and really do not want to have to overload the delete() method in my models - simply due to (A) the amount of models, and (B) having to edit the delete() method in all models when other models change.
Any pointers or tips would be appreciated.

A: I do know this is possible from within my models:
public function delete() {
  ChildTable::where('parent_id', $this->id)->delete();
  ChildTable2::where('parent_id', $this->id)->delete();
  parent::delete();
}

But any update to models or table structure would cause this to be appended/edited.. including other models.

A: I've got cascading deletes working using model events, for example in a Product model I bind to the deleted event so I can soft-delete all relations:
    // Laravel's equivalent to calling the constructor on a model
    public static function boot()
    {
        // make the parent (Eloquent) boot method run
        parent::boot();

        // cause a soft delete of a product to cascade to children so they are also soft deleted
        static::deleted(function($product)
        {
            $product->images()->delete();
            $product->descriptions()->delete();
            foreach($product->variants as $variant)
            {
                $variant->options()->delete();
                $variant->delete();
            }
        });
    }


text:
Q: Offline PWA not behaving as expected on phones. Asks for connectivity despite caching all relevant files I am trying to make an offline PWA planner targeted to phones and I have no need at all for user data or interaction with my home page after installation.
Everything works fine on my PC and Lighthouse gives a clean bill of health, but on my phone (S8) the PWA does not work as expected in Chrome and Firefox when I am offline.
Minimizing the app and tapping the installed icon works in Chrome as long as I am online, but occasionally gives a black screen in Firefox, especially if the app has lost focus for a while.
Going offline causes Chrome to ignore the cached files and complain about lack of connectivity if reloaded, for example after a phone restart or closing all apps.
Firefox just hangs with a white or black screen.
I cache my index.html file and have a suspicion that reinstalling the service worker on reload will flush the cache if offline, but despite extensive searches I haven't been able to find a way around this - or even a mentioning.
I experience the same problem on a  Samsung S5 and on an iPad.
Included below is the script in my html header:
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register('/FuzzyPlan_serviceWorker.js', { scope: '/' }).then(function(registration) {
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
          console.log('ServiceWorker registration failed: ', err);
        });
      });
    }
    </script>

And my service worker code:
let CACHED_URLS = [
  '200px-A_SVG_semicircle_heart_empty.svg.png',
  '200px-A_SVG_semicircle_heart.svg.png',
  '200px-Flag_of_Denmark.png',
  '200px-Flag_of_the_United_Kingdom.png',
  'FuzzyPlan20211002.css',
  'FuzzyPlan20211002.js',
  'apple-touch-icon.png',
  'favicon.ico',
  'favicon.png',
  'icon.svg',
  'index.html',
  'instructions_dk.html',
  'instructions.html',
  'manifest.json',
  'favicons/maskable_192.png',
  'favicons/favicon-512.png'
];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(FP_CACHE).then(function(cache) {
      return cache.addAll(CACHED_URLS);
    })
  );
});

self.addEventListener('fetch', function(event) {
  console.log('Fetch request for: ', event.request.url);
  event.respondWith( caches.match(event.request, {ignoreVary: true}).then( // ignoreVary should make the cache match ignore flags and stuff that can make a mathc fail unintentionally
    function(response) {
      return response || fetch(event.request);
    }).catch(function(error) {
      console.log('FuzzyPlan serviceWorker responded with error', error);
    })
  );
})

I'd appreciate an explanation of where I have made a rookie mistake :-)
The full project is at https://github.com/HappyDustbunny/FuzzyPlan

A: The original question is answered: the PWA part is working just fine.
A kind person tried the PWA on his phone and found no problem, which prompted me to test more thoroughly on phones other than my own, and it seems that the PWA part is working as it should.
What tricked me was having tested older versions on other phones that did not work.
The PWA part of latest update do work, but it has another – yet unidentified – glitch.
This glitch is not readily reproducible, but after encountering a white screen in Chrome, I connected the phone to the computer via USB and used Chrome DevTools (by typing chrome://inspect/#devices in the address line) to pick apart the innards of the app.
Everything was there (service worker, manifest, cache, DOM, …) and I could interact with the javascript in the console, but the screen was white. Both on the phone and in DevTools. (Suggestions welcome!!!)
It even logged swipe events to the console, an earler debugging effort I have forgotten to remove.
I suspect the culprit is me trying to take over navigation via the back-button at the bottom at every phone (the triangle) and messing it up somehow.
I'll have to test this more on my own and open a new question if I get stuck.


text:
Q: What mask should I apply to get all green pixels? I am currently trying a code which I saw in a youtube tutorial(I specified it in my Github link from above). I see that there are two masks applied but I tried several RGB values and I still can`t get the lighr green pixels(which are exposed to more light). I would like to know what masks should I apply in my code and how can I tell which one is good in any given color extraction.
   image_blur = cv2.GaussianBlur(image, (7, 7), 0)
   #t unlike RGB, HSV separates luma, or the image intensity, from
   # chroma or the color information.
   #just want to focus on color, segmentation
   image_blur_hsv = cv2.cvtColor(image_blur, cv2.COLOR_RGB2HSV)

   # Filter by colour
   # 0-10 hue
   #minimum red amount, max red amount
   min_green = np.array([36, 0, 0])
   max_green = np.array([70, 255,255])
   #layer
   mask1 = cv2.inRange(image_blur_hsv, min_green, max_green)

   #birghtness of a color is hue
   # 170-180 hue
   min_green2 = np.array([188,0,0])
   max_green2 = np.array([208,243,139])
   mask2 = cv2.inRange(image_blur_hsv, min_green2, max_green2)

   #looking for what is in both ranges
   # Combine masks
   mask = mask1 + mask2

Here is my link to Github where you can find the pictures and the entire code:
https://github.com/andreyy03/PlantsRecognition
Thank you!

A: There is not such a thing like "the perfect filter" you just try. I've made a tool some months ago to do exactly that. Although I'm pretty sure there are better ones out there, but this can do the trick, and help you select the range/s. Of course it is not perfect. Hope it helps.
You can use it like python tool.py name_of_your_image.jpg or in a secuence python tool.py path/to/your/secuence although you'll have to play with the code a little bit in the second form.


text:
Q: c++ jump lines while debugging I'm doing some coding in c++ and while debugging it jumps some lines, like constructors and many more. Someone have an idea how this could happen?
Here are the most important class declaration:
This is the declaration of the class for my GUI
#include "VisiTest.h"
#include "List.h"

class MonInterface : public VisiTest
{
public:

This is constructor where the skip line problem appears
MonInterface(char *theName);
public slots:
    virtual void testSuivant();
    virtual void demarrer();
    virtual void arreter();
    virtual void vider();
    virtual void premier();
    virtual void dernier();
    virtual void precedent();
    virtual void suivant();
private:
    Donnee donnee;
    List<Donnee> listDonnee;
    bool m_Started;
    int getIntCurrent();
};

This is the definition of the class's constructor
MonInterface::MonInterface(char * theName) : VisiTest(theName)
{
  donnee.typeTest = 0;
  donnee.registreSW = 0;
  donnee.retourSW = 0;

  donnee.registreLD = 0;
  donnee.valeurLD = 0;

  donnee.etatLD = 1;
  donnee.etatSW = 1;

  resetTest();
  resetArchive();
  m_Started = false;
}

Then in this constructor is skips many lines the object "donnee" contains many junk and my list too
Finally, this is the definition of the struct Donnee
struct Donnee
{
  int typeTest;

  int registreSW;
  int retourSW;
  int etatSW;

  int registreLD;
  int valeurLD;
  int etatLD;
};

A: Did you compile with some optimization level (-Ox)?
It happened to me when having optimization in gcc as well as debugging options.
If that is the case, removing of any optimization option will make your code to debug well.


text:
Q: Логин в sqlcmd через jenkins использую Windows Authentication Я настраиваю CI. Настраиваю через jenkins pipline. Мне нужно запускать sql скрипт в ms sql. Использую я для этого sqlcmd команду которую прописываю в jenkinsfile. Вот так выглядит команда bat
sqlcmd -e -S \"someserver\" -i \"D:\\somefile.sql\" -E

В данной команде -E говорит, что для логина в sql server нужно использовать windows authentication, т.к я запускаю это на сервере должно работать(но пока я тестирую локально), это нужно для того что бы не хранить credentials от бд в репозитории (jenkinsfile лежит в репозитории). Когда в jenkins запускаю билд получаю вот такое сообщение

The server principal "CS\xxxxxxxx$" is not able to access the database
  "xxxx" under the current security context.

Я так понимаю через jenkins я не могу воспользоваться windows authentication т.е если запустить эту команду через командную строку, то тогда мой sql скрипт выполняется.

A: Я уже давно решил эту проблем, хочу поделиться решением. Jenkins запускается как Windows Service поэтому нужно выставить ему права пользователя который имеет доступ к базе и тогда вам будет доступна windows authentication. Надеюсь это кому-нибудь поможет)


text:
Q: ASCII to Json in go im kinda new to programming but i found that python didnt have the speed i needed so i switched to go, im building a scraper and i need to convert a what looks like to be a ASCII formated string to json but i cant find any good documentation on how to do this in go.
the string i need converted looks something like this: debug%22%3Afalse%2C%22pageOpts%22%3A%7B%22noBidIfUnsold%22%3Atrue%2C%22keywords%22%3A%7B%22no-sno-finn-object_type%22%3A%22private%22%2C%22no-sno-finn-car_make%22%3A%22796%22%2C%22aa-sch-publisher%22%3A%22finn%22%2C%22aa-sch-inventory_type%22%3A%22classified%22%2C%22aa-sch-country_code%22%3A%22no%22%2C%22no-sno-finn-section%22%3A%22car%22%2C%22no-sno-finn-ad_owner%22%3A%22false%22%2C%22no-sno-publishergroup%22%3A%22schibsted%22%2C%22aa-sch-supply_type%22%3A%22web_desktop%22%2C%22no-sno-finn-subsection%22%3A%22car_used%22%2C%22aa-sch-page_type%22%3A%22object%22%7D
Thanks in advance!

A: As mentioned by a commenter, your string is URL encoded and can be decoded using url.QueryUnescape(...):
package main

import (
  "fmt"
  "net/url"
)

func main() {
  querystr := "debug%22%3Afalse%2C%22pageOpts%22%3A%7B%22noBidIfUnsold%22%3Atrue%2C%22keywords%22%3A%7B%22no-sno-finn-object_type%22%3A%22private%22%2C%22no-sno-finn-car_make%22%3A%22796%22%2C%22aa-sch-publisher%22%3A%22finn%22%2C%22aa-sch-inventory_type%22%3A%22classified%22%2C%22aa-sch-country_code%22%3A%22no%22%2C%22no-sno-finn-section%22%3A%22car%22%2C%22no-sno-finn-ad_owner%22%3A%22false%22%2C%22no-sno-publishergroup%22%3A%22schibsted%22%2C%22aa-sch-supply_type%22%3A%22web_desktop%22%2C%22no-sno-finn-subsection%22%3A%22car_used%22%2C%22aa-sch-page_type%22%3A%22object%22%7D"

  // Parse the URL encoded string.
  plainstr, err := url.QueryUnescape(querystr)
  if err != nil {
    panic(err)
  }
  fmt.Println(plainstr)
  // debug":false,"pageOpts":{"noBidIfUnsold":true,"keywords":{"no-sno-finn-object_type":"private","no-sno-finn-car_make":"796","aa-sch-publisher":"finn","aa-sch-inventory_type":"classified","aa-sch-country_code":"no","no-sno-finn-section":"car","no-sno-finn-ad_owner":"false","no-sno-publishergroup":"schibsted","aa-sch-supply_type":"web_desktop","no-sno-finn-subsection":"car_used","aa-sch-page_type":"object"}

}

Your example string appears to be incomplete but eventually it can be decoded into a struct or map using json.Unmarshal(...).


text:
Q: Program Structure -- Simple Commandline To Do List App -- What's the Haskell way? Background: I am working on my first complete program in Haskell, a simple to do list application on the command line.
My question is one of structure and has two levels: (1) What is the best way to do it? and (2) What is the Haskell (functional) way to do it? The reason I phrase it this way is because I suspect that there may be a faster or easier way to do it that ignores the principles of functional programming. I'd like to do it in the more elegant and clear way, as it is more of a learning exercise than anything else.
Keep in mind that I'd (obviously) like the application to be somewhat persistent. The two options on the table right now are to store information in a flat text file or alternately in a Sqlite database.
The first structure that came to mind was something like this, where a ToDoList type object is simply a list of ToDo items:
import Data.List
import Data.Time

data ToDo = ToDo {
        todoId       :: Int,
        todoDue      :: ZonedTime,
        todoCreated  :: UTCTime,
        todoItem     :: String,
        todoPriority :: Priority,
        todoStatus   :: Status
        }
        deriving (Show, Read)

type ToDoList = [ToDo]

data Priority = Low | Medium | High
        deriving (Show, Read, Eq, Ord)

data Status = Complete | InProgress | Open
        deriving (Show, Read, Eq, Ord)

But then I began to wonder how best to store objects of this type. Would this imply that I store them in a flat file? Is there some way to relate objects of highly specified types like this to fields/columns in a database?
When I think about using a Sqlite database, it seems that all of the work will be done in the database calls, and Haskell types will have comparatively little to do with it. This seems bad.
In summary, the question is how best can I model the data structure of my simple to do list application in keeping with the notions of functional programming and Haskell ideals that I am seeking to practice with this project?

A: The Show/Read combination is a tremendously easy way of serializing and deserializing the internal state of your application, and because of purity it basically always works too. Furthermore, you'll get good practice writing functions that slice and dice lists, since you'll be able to treat the list as if it is entirely loaded into memory (and maybe if you want to play with some more efficient data structures, you can look at ways to optimize different queries.)
For example, if I want to find all items that are due before some date, I can write this using a filter on due:
dueBefore (ToDoList ts) d = ToDoList (filter (\t -> due t <= d) ts)

Some style nitpicks on your pseudocode:

*

*Since all accessor functions (id, die. created...) get dumped into the module-wide namespace, it's good style to prefix/suffix them with the name of the record, such as todoId, todoDie. In this particular case, id is a real function, so you shouldn't shadow it!

*ToDoList is a single constructor datatype with one value; you probably actually just want a newtype or type synonym. (Exercise: rewrite the above snippet to work with a type synonym.)

*You probably want an Ord instance on Priority and Status

A: I think that a flat file will make your life easier, and will work just as well, unless you have such a  terrible backlog of work that you need a database to hold it all ;P
I would recomend reading Learn You a Haskell for Great Good, or at least, this chapter.  It even contains a short TODO application similar to what you are trying to write.
Now, you should have no problems writing and reading all your values to a file, so long as they all derive Show and Read.


text:
Q: Chrome no longer applies anti-aliasing to canvas I really don't know where to start with this. I recently updated Chrome to 85.0.4183.102 and suddenly the game I was making keeps turning anti-aliasing for canvas on and off - mostly off.
I just have some 2D canvas-es that are drawn 20 times a second (really simple code) with the basic canvas geometric and image drawing functions. If I try an old backup of the game, the problem persists, so it must be something that changed in Chrome.
I asked to a friend and he says Chrome disables anti-aliasing when it's too busy, and I admit my code is so far from being efficient, but then the old backup should have no problems. Also, everything that happens in each frame requires only 2ms of the 50ms duration of each frame.
I really don't know where to start to solve this problem and I couldn't find anything on Google.


text:
Q: OCR of text and numbers of a Draws - using Tesseract and Java I have a little general question about OCR of draws (tables), because I want to analyze these images and extract data.
I use Java (but if you suggest other, this is not a problem) and I tried Tesseract with javacpp library with not so much luck.
Sample code used:
    BytePointer outText;

    TessBaseAPI api = new TessBaseAPI();
    // Initialize tesseract-ocr with English, without specifying tessdata path
    if (api.Init(null, "ita") != 0) {
        System.err.println("Could not initialize tesseract.");
        System.exit(1);
    }

    // Open input image with leptonica library
    PIX image = pixRead("image.jpg");
    api.SetImage(image);
    // Get OCR result
    outText = api.GetUTF8Text();
    System.out.println("OCR output:\n" + outText.getString());

From the image uploaded I obtain only the names:
1) Quintavalle Gianluca - 4.NC
1) Quintavalle Gianluca - 4.NC
Barelli Paolo - 4NC :

I think the problem is the particular layout because the image is very clear, but I need to find out event the results (60 61).
I tried a lot of different draws and different Tesseract options and pagesegmode but I couldn't get the data needed.

My final purpose is to obtain from the draws a list of matches:
- winner1- loser1- result1
- winner2- loser2- result2
etc

from a draws like this:

Thanks a lot for all the help, it's for a research project.


text:
Q: React JS to add Validation to individual input feild which are dynamically generated I am working on react project and I have a button which will generate two dynamic inputs which will be key value pair. I want to validate them before user add one more field.
The validation will be, it should not be duplicate value and no special characters should be allowed. But the validation should appear below its individual field.
Stack blitz demo :https://stackblitz.com/edit/react-helloworld-gamgmo
Below is my code,

const App = () => {
  const [defaultTags, setDefaultTags] = useState({});
  const [formValues, setFormValues] = useState([{ name: '', email: '' }]);
  const [isEmpty, setIsEmpty] = useState(true);

  let handleChange = (i, e) => {
    let newFormValues = [...formValues];
    newFormValues[i][e.target.name] = e.target.value;
    setFormValues(newFormValues);
  };

  let addFormFields = () => {
    setFormValues([...formValues, { name: '', email: '' }]);
    setIsEmpty(true);

  // Some validation for feilds
  };

  validateAndAdd(){

 }
  let removeFormFields = (i) => {
    let newFormValues = [...formValues];
    newFormValues.splice(i, 1);
    setFormValues(newFormValues);
    setIsEmpty(false);
  };

  return (
    <>
      {formValues.map((element, index) => (

          Name
          <input
            type="text"
            name="name"
            value={element.name || ''}
            onChange={(e) => handleChange(index, e)}
          />
          Email
          <input
            type="text"
            name="email"
            value={element.email || ''}
            onChange={(e) => handleChange(index, e)}
          />
          {index ? (
            <button
              type="button"
              className="button remove"
              onClick={() => removeFormFields(index)}
            >
              Remove
            </button>
          ) : null}

      ))}

        <button
          disabled={isEmpty}
          type="button"
          onClick={() => addFormFields()}
        >
          Add
        </button>

    </>
  );
};

export default App;


text:
Q: SMTP Error: Could not connect to SMTP host in php On sending emails from Gmail through SMTP I got this error:

SMTP Error: Could not connect to SMTP host

I tried:
require_once('mailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug  = 0;
$mail->SMTPAuth   = true;
$mail->SMTPSecure = "ssl";
$mail->Host       = "smtp.gmail.com";
$mail->Port       = 465;
$mail->AddAddress($email);
$mail->Username="mail@gmail.com";
$mail->Password="password";
$mail->SetFrom('mail@gmail.com','Store');
$mail->AddReplyTo("mail@gmail.com","Store");
$mail->Subject    = $subject;
$mail->MsgHTML($message);
$mail->Send();

Gmail account setting for "Less secure apps" is turned on
Update:
After trying this answer, I am getting:

Fatal error: Class 'SMTP' not found in C:\wamp64\www\project\mailer\class.phpmailer.php on line 1522

A: I am using below code for setting my values.. and it is working fine for me.
        $mail = new PHPMailer;
        //Tell PHPMailer to use SMTP
        $mail->isSMTP();
        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $mail->SMTPDebug = 0;
        $mail->Debugoutput = 'html';
        $mail->Host = "smtp.gmail.com";
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->SMTPAuth = true;
        $mail->Username = "mail@gmail.com";
        //Password to use for SMTP authentication
        $mail->Password = "password";

        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        $mail->setFrom("mail@gmail.com",$from);
        $mail->addAddress("mail@gmail.com");
        //Set the subject line
        $mail->Subject = "subject";
        $mail->Body = "body";
        $mail->send();


text:
Q: Not accessible 'Side' field in DocuSign Rooms API There is a field named 'Side' (transactionSide) in DocuSign room UI.
It has one of these values: buy, sell, listbuy, refi.
Unfortunately, I cannot get this field by using API endpoints:
GET /restapi/v2/accounts/{accountId}/rooms/{roomId}

GET /restapi/v2/accounts/{accountId}/rooms/{roomId}/field_data

*

*Is there a way to get this field by using API?

*Can I update this field using update field data endpoint (PUT /restapi/v2/accounts/{accountId}/rooms/{roomId}/field_data) ?

A: It is called transactionSideId in the JSON.
Did you know we also have SDKs for the Rooms API? you can use them in C#, Java, Node, PHP, Python and Ruby. That should help find properties names I would think...
(here is a recent blog post with some examples)
UPDATE:
As a workaround, Room's side is defined by Room Owner's side. So to identify RoomSide user would need to call following endpoint:
/v2/accounts/{accountId}/rooms/{roomId}/users

If calling user knows who the owner of the room is, transactionSideId defined for that user, i.e. the Room Owner is Room's transactionSide. Unfortunately, I didn't see a way to identify Room Owner's userId.


text:
Q: Is Heat Death the only inevitable end? I have heard about heat death being the most probable end of the universe. But what are the other possible ends of the universe. I also came across a video stating that due to some effect called as "quantum tunelling" the universe could start again. But wouldnt that be a contradiction of the Second Law of thermodynamics?

A: The discussion on the universe's death was addressed initially when physicist started using Einsteins' field equations (EFQ) to describe the whole universe. Once the cosmological principle was adopted, stating that at large scales the universe should be homogeneous and isotropic, one is led to the FLRW type of solutions for for EFQ. Within this solutions you can have an open, flat or closed universe. In the first case the universe would expand forever, in the second it will slow down its expansion for ever but won't ever stop, while in the last case, the universe would stop its expansion at some point and collapse back by means of the gravitational attraction.
So an alternative, for the end of the universe, (back then) was this last scenario. Now the community currently believes after observations made on the expansion of the universe (and more over accelerated expansion) that our universe falls in the first case. It seems it will expand for ever driven by the so-called dark energy, meaning that energy will be just more and more diluted leading to the heat-death of the universe.
Some other studies point perhaps to what you mentioned on tunnelling. When one studies the vacuum fluctuations from the point of view of quantum field theory in particular within the Standard Model framework, one finds that the behaviour of the Higgs field subject to a potential that suffers symmetry breaking can lead to the nucleation of bubbles of a different vacuum state. The original observations are due to Coleman in the 70s (See Fate of the False Vacuum I and Fate of the False Vacuum II). If it was the case that one of these bubbles is nucleated by tunnelling, anything consumed by this bubble would probably be turned into energy (the energy difference between its state and the new vacuum state) driving the expansion of the bubble as described in the papers. Current values of the parameters of the standard model point to the Higgs potential being metastable. There are also estimates on the decay rates of our false vacuum into true vacuum (see https://arxiv.org/abs/1707.08124).


text:
Q: How can I get a continuous piecewise polynomial curve, with a turning point (not differentiable)? I would like to make a curve which has turning point(x,y).
 y= x^2*2 for x<= 0.5

 y= 1-(1-x)^2*2 for x> 0.5

and still have a smooth S-shaped curve, where the slope is continuous on both sides of the turning point.
How can I make the equation as simple and straightforward as possible?

A: Differentiating your first function $y=2x^2$ gives $y'=4x$. Evaluating at $x=1/2$, gives $y'=2$.
Differentiating your second function $y=-2x^2+4x-1$ gives $y'=-4x+4$. Evaluating at $x=1/2$, gives $y'=2$.
You picked a pair of curves whose derivatives are lines and only intersect at the point you have chosen.
Choose simpler functions and pick a point of intersection; check the derivatives.
Edit: There are infinitely many lines that will work. Consider $y=x$ and $y=-x$. They have derivatives 1 and -1 everywhere. They intersect at (0,0). According to what you have said, this is a "turning point."


text:
Q: Error: object and replacement value have different dimensions [enter image description here][1]I am a student who is learning how to do microarray analysis. I ran into the following error and was hoping someone has guidance on how to troubleshoot the issue. Thank you.
Update: I was trying to post a picture but it wouldn't let me because my reputation value is low.
exprs(my.rma) <- exprs(my.rma)[present >= [enter image description here][2]4,]
Error in .validate_assayDataElementReplace(obj, value) :
 object and replacement value have different dimensions


text:
Q: geom_label_repel() above geom_line() So I have this ggplot where labels are positioned by the geom_label_repel() method. It's fairly okay, but I woud like the labels to be, all of them, above the geom_line(), not below, which is what happens in some cases.

This is the code that produces the graph:
    ggplot(data,
   aes(x=daydelta,y=day1ret)
   ) +
  geom_line(color='steelblue',size=2) +
  geom_label_repel(aes(label = paste0(round(day1ret*100,2),"%")),box.padding = unit(0.6, "lines"),label.size = 0.1)+
  scale_x_continuous(limits = c(1,15),breaks=1:15,minor_breaks = 1:15) +
  scale_y_continuous(limits = c(0,1),breaks=seq(0,1,0.1),minor_breaks = seq(0,1,0.1),labels = paste0(seq(0,1,0.1)*100,"%")) +
  ggtitle("RETENTION BY USERID") +
  theme(plot.title = element_text(hjust = 0.5))+
  xlab("Days from Register\n (baseline: Day 1)")+
  ylab("Retention as % of returning users from Day 1")+
  geom_segment(mapping=aes(x=daydelta,y=0,xend=daydelta,yend=day1ret),size=0.5,color="red",linetype=2)

A: Instead of cluttering up the plot with labels offset from the data line, why not place the labels at their actual x and y values? This is visually much cleaner and won't distract or mislead viewers by placing labels in locations other than the data values they represent. For example:
library(ggplot2)
library(scales)

dat = data.frame(x=1:10, y=c(1, seq(.3,.1,length=9)))

ggplot(dat, aes(x,y)) +
  geom_line() +
  geom_label(aes(label=paste0(sprintf("%1.1f",y*100),"%")), size=3, label.padding=unit(2,"pt")) +
  scale_y_continuous(labels=percent, limits=c(0,1)) +
  scale_x_continuous(breaks=dat$x) +
  theme_classic()


text:
Q: How to compile a Linux program with Mingw? I have a Linux program that I want to run on Windows. I want to compile it for Windows using Mingw?
I am new to this Mingw thingy. So, I have no idea if it will work.
I installed Mingw and I have a make file. What's next? I have a bunch of exe files in Mingw. I don't even know how to start the compiler.
So, my question is: What are the steps necessary to compile the program I have?

UPDATE:
I figured out in the end what are the steps necessary to compile a Linux program for Win using Mingw.
I posted the solution below (solution is 7 steps), maybe it will be useful to others also.

A: To compile a Linux program on Win:

*

*Install MingW

*Edit the c:\MinGW\msys\1.0\etc\fstab file (it should contain this line: c:/mingw  /mingw )

*Start Wingw shell by running c:\MinGW\msys\1.0\msys.bat

*In shell go to the folder where your Make file is (use cd command for this).

*Type 'make'. This will compile your program.

*Put the generated EXE and the required DLLs (libgcc_s_dw2-1.dll and libstdc++-6.dll) in the same folder

*Run the exe file and enjoy it....


text:
Q: Changing dropdown values with jQuery doesn't work with only one value I have a page with a number of dropdown boxes and some jQuery that will change the values of the proceeding dropdown menus based on the selection of the preceding dropdown box.
The code I have is here:
function changeDropDown(select, options) {
            var dropdown = $("select#" + select + "");
            dropdown.empty();
            dropdown.load("changeDropdown.php?dd=" + select + "&id=" + $('#' + options + '').val());
            }

Then to call it I simply do this:
$('#pdi-Process').change(function() {
            changeDropDown('pdi-Condition','pdi-Process');
            });

This works and will change the options in the specified dropdown list based on the value of the option selected in the preceding dropdown menu.
My problem is that there is a chain of these dropdown menus and this code will only work if someone changes the value of a dropdown menu. Sometimes the option a user wants is the first one presented, or might be the only one available. In cases like these where the user cannot change the option, the code fails to work.
Using my years of experience in web development I have concluded the problem is probably due to .change() but what could I use to provide the same functionality but also allow it to work when the options cannot be changed? Is there an elegant way of doing this or shall I simply go with adding a blank option to every list so users can always change the values?

A: Just trigger a change on the .load() callback :
dropdown.load("changeDropdown.php?dd=" + select + "&id=" + $('#' + options + '').val(), function(){
    dropdown.trigger('change');
});


text:
Q: How to add Superscript string in Localization file in iOS I have localizable English and French. I want display Registered symbols as a part of word i.e "MyApp®". English part of localization file shows this symbol correct in iOS APP UI. Same needs to display for French version i.e "MyAppᴹᴰ" but space comes in between 'M' and 'D'.
I also tried using unicode like MyApp\u{1D39}\u{1D30}. This gets worked in Swift playground but if I try it through Localization file it doesn't work.
iOS version: 11.4
I need to make changes in localization file only and not to use NSAttributed string every where in code.
If anyone came across same problem, and found solution please post.
"MyApp®" = "MyApp\u{1D39}\u{1D30}" // Localization file

print(String(describing: "MyApp\u{1D39}\u{1D30}" // swift playground
print(String(describing: "ᴹᴰ")) // swift playground

"MyApp®" = "MyApp\u{1D39}\u{1D30}" // Localization file
"MyApp®" = "MyAppᴹᴰ" // Localization file- on UI space comes b/w ᴹ and ᴰ

print(String(describing: "MyApp\u{1D39}\u{1D30}")) // swift playground
print(String(describing: "ᴹᴰ")) // swift playground

"MyApp®" = "MyApp\u{1D39}\u{1D30}" // Localization file

On iOS app UI component should render MyApp® as MyAppᴹᴰ and no space between ᴹ and ᴰ.

A: Instead of using the separate superscript ᴹ and ᴰ characters, why not use the actual  (U+1F16B) character?
In your localization file, put:
"MyApp®" = "MyApp"


text:
Q: ESX servers in a DMZ I have two ESX 3.5 servers in a DMZ. I can access these servers on any port from my LAN via a VPN. Servers in the DMZ are unable to initiate connections back to the LAN, for obvious reasons. I have a vCenter server on my LAN and can initially connect to the ESX servers fine. However, the ESX servers then try to send a heartbeat back to the vCenter server on UDP/902 - obviously this will not get back to the vCenter server, which then marks the ESX servers as not responding and disconnects.
There are two broad solutions I can think of:
1) Try to tell vCenter to ignore not getting heartbeats. The best I can do here is delay the disconnect by 3 mins.
2) Try some clever network solution. However, again I am at loss.
Note: The vCenter server is on a LAN, and cannot be given a public IP, so firewall rules back will not work. Also, I cannot setup a VPN from the DMZ to the LAN.
**I am adding the following, explanation that I added to the comments
OK, maybe this is the bit that I not explaining well. The DMZ is on a remote site, an entirely independent network (network 1). The vCenter server is on our office LAN (network 2). Network 2 can connect to any machine on any port on network 1. But network 1 is not allowed to initiate a connection to network 2. Any traffic destined to network 2 from network 1 gets dropped by the firewall as it is traffic to a non-routable address. The only solution I can think of is setting up a VPN from network 1 to network 2, but this is not acceptable.
So any clever folk out there any ideas?
J

A: James, why not configure the ESX hosts at the remote location so that their guests are in a DMZ, but the ESX service console etc are in a back-zone subnet that you can establish a VPN with? That way, your hosts are isolated from web connectivity (a good thing) but your guests can continue to operate front-facing.
As for the remote site problem... you really need a site-to-site VPN link going on here, between your internal LAN and the remote (non-DMZ if possible) subnet.

A: Your firewall will not allow a port forward from a specific IP (the ESX servers) to a specific internal IP (vCenter)? Most firewalls I've seen (other than home-grade) will do this. Or will accmoplish the same thing by doing the port forwarding then setting an ACL (or the like) to only allow that traffic under certain conditions (being from the ESX servers).

A: Also if this is a "DMZ" then it should be possible to have internal (but firewalled by the inner firewall) addresses for the service console ports (and VMKernel etc) and only have the externally connected uplinks connected to the external firewall (for VM NIC's with public IPs). It should be safe to then open up the relevant port for the UDP 902 traffic to the ESX Service console.
Even in an internal only environment your Service Console uplink NICs should be separated from  production VM port uplinks, in a scenario like this that "should" really becomes a "must".
I'm assuming that you have multiple NICs on the ESX servers and have a DMZ rather than a situation with ESX servers sitting outside a single firewall. If that is the case then Chris S's answer should be possible.

A: Ok I have a solution that works, its a little brittle but works none the less.  It requires you to use a host on the local lan as a "proxy"
on esx server (remote lan) IP: 10.XX.XX.XX
1) /sbin/iptables -t nat -I OUTPUT -p udp -s 10.XX.XX.XX --dport 902 -j DNAT --to 127.0.0.1
this re-routes the udp to the vCenter back to the loopback interface.
2) nc -u -l -p 902 | nc 127.0.0.1 1002
This converts the udp to tcp and sends it to the localhost on port 1002
On esx-proxy (local lan)
Set up you outbound ssh tunnels
ssh -Nf -g -L 902:localhost:902 -L 903:localhost:903 -L 443:localhost:443 10.XX.XX.XX
set up a reverse tunnel to capture the udp you have converted to tcp
ssh -Nf -R 1002:127.0.0.1:1002 10.XX.XX.XX
now convert the tcp on port 1002 back to udp
nc -l -p 1002 | nc -u 10.YY.YY.YY 902
Where 10.YY.YY.YY is the vCenter server.
On the vCenter server (local lan)
connect to the proxy as if you are connecting to the real host.
And this ladies and gentlemen allows you to connect to a esx server on a remote lan, using an ssh tunnel
Also I have extended instruction that allows you to connect to many remote esx servers using the same proxy.
J
(Can I give myself 50 points? :) )


text:
Q: Cannot get response headers into JSON format I am making a call to a third-party vendor my company works with, I am trying to send a request and receive my session API token. The problem is, the session id value I need is returned through the response headers. I can see it come back but I cannot get it as a JSON to parse through later.
headers = {'Authorization': 'Basic madeUpKey'}

response = requests.get('theThirdPartyURL/api/login', headers=headers, verify=false)

data = response.headers

If I just print data here and don't run the below line I get a string that looks like a JSON with the values I want
data=data.json()

I then get this error: AttributeError: 'CaseInsensitiveDict' object had no attribute 'json'
I have tried everything on StackOverflow and have not had any luck.
I have also tried json.dumps(dict(response.headers))) and a few other suggestions.

A: The problem is that response.headers is of type:
type(data) == requests.structures.CaseInsensitiveDict

which is not serializable.
Not sure about how you want to save your data to "parse through later", but you could use dict() and save it to a file.
This is what works for me:
import json
import requests

response = requests.get('https://www.google.com')

with open("file1.json", "w") as file:
    json.dump(dict(response.headers), file)


text:
Q: FullCalendar check if resize is from Start or End I need to detect if resize is starting from the START (left) or from the END (right).
I tried this solution but didn't work FullCalendar: Detect if resize was on Start or on End.
I need to implement this code. Basically now It works if I resize an event from END, but not if I change from START cause i can't detect if I change from START or END.
events: [
            { id: '1', resourceId: 'a', start: '2017-09-07T02:00:00', end: '2017-09-07T04:00:00', title: 'Carico su camion', id_eventi_prima: "", id_eventi_dopo: "2,3,4,5,6,7", id_evento_collegato: "2,3,4,5,6,7", backgroundColor: "green" },
            { id: '2', resourceId: 'a', start: '2017-09-07T04:00:00', end: '2017-09-07T13:00:00', title: 'Viaggio', id_eventi_prima: "1", id_eventi_dopo: "3,4,5,6,7", id_evento_collegato: "1,3,4,5,6,7", backgroundColor: "red" },
            { id: '3', resourceId: 'a', start: '2017-09-07T13:00:00', end: '2017-09-07T15:00:00', title: 'Scarico', id_eventi_prima: "1,2", id_eventi_dopo: "4,5,6,7", id_evento_collegato: "1,2,4,5,6,7", backgroundColor: "grey", editable: false },
            { id: '4', resourceId: 'a', start: '2017-09-07T15:00:00', end: '2017-09-07T19:00:00', title: 'Produzione', id_eventi_prima: "1,2,3", id_eventi_dopo: "5,6,7", id_evento_collegato: "1,2,3,5,6,7", backgroundColor: "orange" },
            { id: '5', resourceId: 'a', start: '2017-09-07T19:00:00', end: '2017-09-07T21:00:00', title: 'Pulizia impianto', id_eventi_prima: "1,2,3,4", id_eventi_dopo: "6,7", id_evento_collegato: "1,2,3,4,6,7", backgroundColor: "blue" },
            { id: '6', resourceId: 'a', start: '2017-09-07T21:00:00', end: '2017-09-07T22:00:00', title: 'Smontaggio', id_eventi_prima: "1,2,3,4,5", id_eventi_dopo: "7", id_evento_collegato: "1,2,3,4,5,7",  backgroundColor: "green" },
            { id: '7', resourceId: 'a', start: '2017-09-07T22:00:00', end: '2017-09-08T06:00:00', title: 'Ritorno in azienda', id_eventi_prima: "1,2,3,4,5,6", id_eventi_dopo: "", id_evento_collegato: "1,2,3,4,5,6", backgroundColor: "pink" },
            { id: '8', resourceId: 'b', start: '2017-09-07T04:00:00', end: '2017-09-07T06:00:00', title: 'Viaggio', id_eventi_prima: "", id_eventi_dopo: "", id_evento_collegato: "", backgroundColor: "green" }
        ],
        eventDrop: function( event, delta, revertFunc, jsEvent, ui, view ) {
            var arrayEventiCollegati = event.id_evento_collegato;
            var newResourceId = event.resourceId;
            var relatedEvents = $("#calendar").fullCalendar("clientEvents", function(evt) {
                for (var i = 0; i < arrayEventiCollegati.length; i++)
                {
                    if (evt.id == arrayEventiCollegati[i]) return true;
                }

                return false;
            });

            for (var i = 0; i < relatedEvents.length; i++)
            {
                relatedEvents[i].resourceId = newResourceId;
                relatedEvents[i].start.add(delta);
                relatedEvents[i].end.add(delta);
            }

            $("#calendar").fullCalendar("updateEvents", relatedEvents);
        }, //eventDrop
        eventResize: function( event, delta, revertFunc, jsEvent, ui, view ) {
            var id_eventi_prima = event.id_eventi_prima;
            var id_eventi_dopo = event.id_eventi_dopo;

            var arrayEventiCollegati = event.id_evento_collegato;
            var relatedEvents = $("#calendar").fullCalendar("clientEvents", function(evt) {
                for (var i = 0; i < arrayEventiCollegati.length; i++)
                {
                    if ( evt.id == arrayEventiCollegati[i] ) {
                        return true;
                    }
                }

                return false;
            });

            for (var i = 0; i < relatedEvents.length; i++)
            {
                for (var k = 0; k < id_eventi_dopo.length; k++) {
                            if ( relatedEvents[i].id == id_eventi_dopo[k] ) {
                relatedEvents[i].start.add(delta);
                relatedEvents[i].end.add(delta);
                            }
                }
            }

            $("#calendar").fullCalendar("updateEvents", relatedEvents);
        } //eventResize


text:
Q: {Cannot run program "octave"} in Windows Eclipse Peace be upon you,
In the following page, a user had a problem in executing his JavaOctave code (my problem is similar to his)
https://kenai.com/projects/javaoctave/lists/general-discussion/archive/2009-12/message/1
I saw that the JavaOctave responsible has spoken about "Configuring the PATH variable to include a path to Octave". But I do not have access to any "Octave.class" file (in their site download part it seems that there is no access to *.class files) so I cannot set the path for pointing out to that object; also, when I set the path to ";...\backups" (the folder containing the "javaoctave-0.6.4.jar"), my problem would not be solved and again I receive
Exception in thread "main" dk.ange.octave.exception.OctaveIOException: java.io.IOException: Cannot run program "octave": CreateProcess error=2, The system cannot find the file specified
at dk.ange.octave.exec.OctaveExec.<init>(OctaveExec.java:102)
at dk.ange.octave.OctaveEngine.<init>(OctaveEngine.java:65)
at dk.ange.octave.OctaveEngineFactory.getScriptEngine(OctaveEngineFactory.java:49)
at edu.udg.agentlab.moviervkb.Test.main(Test.java:12)
Caused by: java.io.IOException: Cannot run program "octave": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at dk.ange.octave.exec.OctaveExec.<init>(OctaveExec.java:100)
... 3 more
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 6 more

I also used the suggestion in this question:
javaoctave jar file has failed in Mac OSX Eclipse
but it couldn't help me and a similar error repeated (the asked question was not occurred in Windows):
Exception in thread "main" dk.ange.octave.exception.OctaveIOException: java.io.IOException: Cannot run program "path_to_octave_executable": CreateProcess error=2, The system cannot find the file specified

Can anyone help me run my JavaOctave program in my editor (Eclipse) or in any other editor?

A:
But I do not have access to any "Octave.class"

The mentioned link is not about a *.class file, but some kind of binary for the Windows function CreateProcess. You need some kind of binary and make that available using either PATH in your Eclipse run configuration or to your user in general or whatever. That's surely your real problem, that you are either missing an *.exe or that's CreateProcess can*t find it. You can read the documentation for CreateProcess where it looks for binaries.
CreateProcess in the MSDN


text:
Q: info.plist preferences for application search on iPhone My application name is TestApplication which is my bundle display name and my application PRODUCTNAME is MyTestApplication.
When I search my application on Simulator/Device with keyword "My" it doesn't search the application.
How can I make searchable my application with keyword "My"?

A: After an hours research I have found that The iPhone Spotlight searches the applications with 2 names
1- Bundle Display Name
2- Apple Store Name
So If we set the name in appstore MyTestApplication then searching with word "My" would also search the app TestApplication.


text:
Q: Using HTTP to request an html file, why TCP sequence number not continuous? I used wireshark to sniff TCP packets when I access an HTTP html. The first four TCP packets are briefly described as follows. I wonder why in the fourth packet, the sequence number is 1 instead of 2? I think now that the sequence number in the third packet is 1, the fourth should be 2.
Src to Dst: 192.168.1.104   128.119.245.12  TCP     Port: 52721 → 80 [SYN] Seq=0
Src to Dst: 128.119.245.12  192.168.1.104   TCP     Port: 80 → 52721 [SYN, ACK] Seq=0 Ack=1
Src to Dst: 192.168.1.104   128.119.245.12  TCP     Port: 52721 → 80 [ACK] Seq=1 Ack=1
Src to Dst: 192.168.1.104   128.119.245.12  HTTP    Port: 52721 GET /wireshark-labs/TCP-wireshark-file1.html HTTP/1.1    Seq=1 Ack=1

A: Sequence numbers don't count packets; they count bytes, plus the SYN and FIN flags which take one "tick" each of sequence number space, even though they do not appear in the data.

*

*.104 sends the SYN flag, with sequence number 0.

*.12 acknowledges the SYN, and sends its own SYN, also with sequence number 0.

*.104 acknowledges the SYN from .12. It does not send any data, so its sequence number stays at 1.

*.104 starts sending data, starting at sequence number 1.

In reality, the sequence numbers have a random offset to make them harder to predict, but Wireshark subtracts this offset before displaying the packets..


text:
Q: How many rows/columns are there in a tkinter Frame? Using tkinter we can use either widget.grid(row,col) or widget.pack() to place a widget.
Since row,col corresponds to the row/col-index in a given Frame/Window - how do we know how many columns the Frame/Window consists of? E.g if I want to place a widget in the midle or to the very right

A: Rows and columns are just concepts, not actual things.  There is effectively an infinite number of rows and columns, all with a width or height of zero until they contain a widget or are configured to have a minimum width or height. From a practical standpoint, there are as many rows and columns as there are pixels in the window.
In reality, the number of rows and columns is entirely up to you. A widget can have a single row and column or it can have several. It all depends on what you add to the window.
A frame starts out with nothing in it, so there are no rows and columns, just empty space. When you add a widget to a row and column, it now has one row and one column plus maybe some empty space. Even if you place your first widget at row 50 and column 20, there is still just one row (50) and one column (20).
There are simple techniques to put something in the middle, or along the right size. For example, because you can define how many columns, you can configure the master to use three columns and the place your widget in the middle column. You can use columnconfigure to cause the last column to take up all extra space with the weight option. This will move any widgets in the last column to the right edge.


text:
Q: Evaluating $\sum_{t=1}^{50}\frac{t^{2}}{\left(1 + \frac{1}{10}\right)^t}$ $$\sum_{t=1}^{50}\frac{t^{2}}{\left(1 + \frac{1}{10}\right)^t}$$
I am getting no clue on how to approach this type of problem since no simple type of sequence techniques seems to work here.

A: HINT
You are looking at the series of the form $f(x) = \sum_t t^2 x^t$. Note that if we start with a geometric series $g(x) = \sum_t x^t$ then
$$
\begin{split}
g'(x)  &= \sum_t tx^{t-1}\\
xg'(x) &= x \sum_t tx^{t-1} = \sum_t tx^t
\end{split}
$$
Can you apply this trick again to $xg'(x)$ to get $f(x)$?

A: Set
$$
f(x)=\sum_t t^2e^{-axt}
$$
where $a=\ln 1.1$.
Then
$$
\int_x^\infty dx'\int_{x'}^\infty  f(x'')dx''=\sum_t \frac{e^{-axt}}{a^2}
$$
You can then sum the right hand side (geometric series in $t$) and differentiate it twice to get $f(x)$

A: Hint: The required sum is $$S=\sum_{k=1}^{n} k^2 x^k,~~ x=(1+1/10)^{-1}$$
$$x+x^2+x^3+...x^n=x\frac{x^n-1}{x-1}=f(x)=\sum_{k=1}^{n} x^k $$
differentiating it w.r.t. x both sides
$$xf'(x)=\sum_{k=1}^{n} k x^k$$ diferentiating again we get
$$x[f'(x)+xf''(x)]=\sum_{k=1}^{n} k^2 x^k$$
Where $f(x)=x(x^n-1)/(x-1)$ and $x=(1+1/10)^{-1}.$.


text:
Q: How can I call a navigated Fragment's function in the Activity hosting the fragment via JetPack's Navigation component? I switched from FragmentManager's transactions to JetPack's Navigation architecture component. In doing so I can no longer call: findFragmentById(int) so that I can get a reference to the instantiated fragment and thus call it's functions from within the Activity that hosts it.
The reason for this is that I am unable to get my custom DialogFragment's to implement listeners inside the fragments themselves so I have them implemented in Main Actiity. When the DialogFragment is interacted, I want it to notify the fragment to call some functions. But because I can not register listeners in Fragment itself, it is completely unaware that the user has clicked the "cancel" or "confirm" buttons.
The activity is aware of the user's actions from the DialogFragment, it should be able to then notify the Fragment so that Fragment may call it's functions.
How do I get a reference to the navigated fragment so that I may call its functions?

A: First please check my understanding of your question as that's baseline for my answer:

*

*You have activity

*It hosts fragment

*That fragment opens dialog fragment and would like to know user's dialog result

If the above is correct, then I don't think navigation currently supports something like this out of the box however you can:

*

*Use shared view model (at the activity level for example), that has some sort of one time live data, to which fragment is subscribed and dialog fragment sends its choice. So basically when dialog fragment changes live data, hosting fragment (or any other subscribers) automatically receives the change

*Use plain old event bus like Otto and just subscribe to event at the fragment level and emit event inside your dialog fragment?

PS.: here is possible one time data structure:
class OneTimeLiveData<T> : MutableLiveData<T>() {

    private val pending = AtomicBoolean(false)

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, Observer { t ->
            if (pending.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        })
    }

    @MainThread
    override fun setValue(t: T?) {
        pending.set(true)
        super.setValue(t)
    }

    @MainThread
    fun call() {
        value = null
    }
}

A: I just had to call the function in fragment from activity in an application works with navigation component. I call the code below like that.
val searchFragment = supportFragmentManager.fragments[0].childFragmentManager.fragments[0] as SearchFragment
searchFragment.setSearchText(obj.getOriginalValue())


text:
Q: Find the bigger number out of two numbers stored as strings in C# I am working with a very large input (trying to solve Next Palindrome problem in SPOJ). I need to compare large numbers and find out which is larger.All this without using BigInteger class other i could i have simply parsed BigInteger from the string and compared to get a result.
I tried string.compare(a,b) but the outputs produced suggest that it doesnt support sorting "numeric strings"

A: *

*Find out which string is longer.

*Fill the beginning of the shorter string with zeroes to match the length of the first string:

shorterString = shorterString.PadLeft(longerString.Length, '0');

*Compare.

Update: I assumed that the numbers are integers. If they can be floating-point/decimal, then the algorithm will not be as simple.


text:
Q: How to use "&" in a "spanish-english" document I am writing my thesis in Spanish, but i have 2 chapters in English. What I need is:
Use "&" in all references in both languages.
My problem is that all my chapters (English and Spanish) are using "y" instead of "&"
I'm using biblatex:
\documentclass[11pt, spanish, singlespacing, headsepline,]{PhDDoctoralThesis}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{palatino}
\usepackage[maxbibnames=99,backend=bibtex,style=authoryear,natbib=true]{biblatex} %
\DefineBibliographyStrings{spanish}{%
andothers        = {et\addabbrvspace al\adddot},
andmore          = {et\addabbrvspace al\adddot},
}
\addbibresource{/Users/Me/Documents/Bibtex/library.bib}

NOTE:
In myfile.cls appears \RequirePackage{babel} but I'm not using \usepackage{babel} in my main.text
NOTE2:
I wrote my English chapters by using \renewcommand{\chaptername}{Chapter}.

A: \DeclareDeliFormat{finalnamedelim}{\addspace\&\space}

will make the delimiter between the last two names an &. But because Spanish is special with 'y' and 'e' you will also need to reset \lbx@finalnamedelim with
\makeatletter
\DefineBibliographyExtras{spanish}{\restorecommand\lbx@finalnamedelim}
\makeatother

This is an answer for biblatex v3.8 and above. See the edit history for an answer for older versions.


text:
Q: How to detect a non-standard USB device on android phone? Here is my schematic
schematic

*

*My device is a non-standard USB device

*I only use the 5V power of
cellphone to supply my device by connecting the ID pin to ground

*I connect the D- pin to 5V with a 1.5k pull-up resistor in order to tell the phone there is a voltage change on the D- pin when my device plugged in

*I don't use the D+/D- pin to communicate with the phone

My question: how to detect the device when it attached to an android phone?
I have tried to read the both variable
UsbManager.ACTION_USB_DEVICE_ATTACHED
android.hardware.usb.action.USB_STATE

both have no change.
but weird is when I insert a USB wire the android.hardware.usb.action.USB_STATE =connected

A: USB is a complex protocol. USB devices are organized in device classes like mass storage class, communication device class ( CDC ), ... ( http://www.usb.org/developers/docs/devclass_docs/ , https://www.kernel.org/doc/html/v4.13/driver-api/usb/power-management.html  ) when a USB device is attached to a host it reports its class to the host ( via the data D- D+ lines ) and the host loads the appropriate kernel modules / drivers and configuration
the device class and USB type also determines how much power is the output of the USB port, when simply connecting a USB cable a standard configuration for output power is used ( i think 500 mA ) however i do not know the mechanism of how the host detects an attached USB cable, maybe use a multimeter and measure the resistance and capacitances between the various lines of an USB cable ...
possibly attach your device to an USB cable and attach it to the android because the cable is detected and power output enabled ...


text:
Q: Asp.Net Sending large amounts of data from view to controller I'm working on a Asp.net MVC application. In my project, I'm using a third party JavaScript library called Dhtmlx Scheduler.
There is a function in this library then writes all the data on the scheduler into XML format.
I then need to manipulate this data, and write in back onto a <textarea> on my view page.
as of now this is what I have:
View:
function save() {
    var url = "/Home/Save"

    var xml = scheduler.toXML();

    $.ajax({
        url: url,
        Type: "POST",
        dataType: 'json',
        async: false,
        data: { xmlString: xml },
        contentType: 'application/json; charset=utf-8',
        success: alert("File Saved in C:\\ Drive as Tasks.xml")
    });
}

Controller:
public ActionResult Save(string xmlString)
{
    XmlDocument doc = new XmlDocument();
    try
    {
        doc.LoadXml(xmlString);
    }
    catch(Exception e)
    {
        Console.WriteLine(e);
    }
    doc.Save(@"C:\\Tasks.xml");

    W6ViewModel viewModel = new W6ViewModel();
    viewModel.engineers = db.W6ENGINEERS.ToList();
    viewModel.tasks = db.W6TASKS.ToList();
    viewModel.skills = db.W6TASKS_REQUIRED_SKILLS1.ToList();
    viewModel.categories = db.W6TASKTYPECATEGORY.ToList();

    gatherInfo(viewModel);

    return View("Index", viewModel);
}

When trying to save three events (Dhtmlx objects) it works flawlessly, when trying to add more data to the XML I get this error (read form FireBug):

The length of the query string for this request exceeds the configured
  maxQueryStringLength value.

Any help would be greatly appreciated.
Thanks!
Firebug Console:

A: I believe jQuery.ajax uses type and not Type. This is case sensitive. If you look at your Firebug it is doing a GET request instead of a POST:
$.ajax({
    url: url,
    Type: "POST",
    dataType: 'json',
    async: false,
    data: { xmlString: xml },
    contentType: 'application/json; charset=utf-8',
    success: alert("File Saved in C:\\ Drive as Tasks.xml")
});

should be
$.ajax({
    url: url,
    type: "POST",
    dataType: 'json',
    async: false,
    data: { xmlString: xml },
    contentType: 'application/json; charset=utf-8',
    success: alert("File Saved in C:\\ Drive as Tasks.xml")
});

A: Grr I can't comment yet, I seem to recall if you pass one primitive value you do
data: xml

rather than
data : { xmlString: xml }

A: has explained in this post -> request exceeds the configured maxQueryStringLength when using [Authorize]
you should change the configuration setting in your web.config to allow more that the 2048 character of the default value.
so basicly you need to change the
<httpRuntime maxRequestLength = "" maxQueryStringLength ="">
to the number you find acceptable.
Edit: have you tried to change your Type: "POST" to type: "POST" ?
since javascript is a case sensitive language.
As for the invalid Json primitive try this :
    $.ajax({
            url: url,
            type: "POST",
            dataType: 'json',
            async: false,
            data: 'xmlString='+ xml,
            contentType: 'application/json; charset=utf-8',
            success: alert("File Saved in C:\\ Drive as Tasks.xml")
        });


text:
Q: Агрегация и ранжирование по DataFrame со смещением Есть DataFrame:
demo = pd.DataFrame({'date': ['2009-06', '2009-06', '2009-06', '2009-06',
                              '2009-07', '2009-07', '2009-07', '2009-07',
                              '2009-08', '2009-08', '2009-08', '2009-08'],
                     'group': [1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2],
                     'value_1': [10, 15, 20, 25, 30, 25, 20, 15, 35, 30, 25, 20],
                     'value_2': [45, 40, 35, 30, 100, 110, 120, 130, 10, 20, 30, 40],
                    })
demo
    date  group value_1 value_2
0   2009-06 1   10  45
1   2009-06 1   15  40
2   2009-06 2   20  35
3   2009-06 2   25  30
4   2009-07 1   30  100
5   2009-07 1   25  110
6   2009-07 2   20  120
7   2009-07 2   15  130
8   2009-08 1   35  10
9   2009-08 1   30  20
10  2009-08 2   25  30
11  2009-08 2   20  40

На выходе нужно получить:
demo_full = pd.DataFrame({'date': ['2009-06', '2009-06', '2009-06', '2009-06',
                              '2009-07', '2009-07', '2009-07', '2009-07',
                              '2009-08', '2009-08', '2009-08', '2009-08'],
                     'group': [1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2],
                     'value_1': [10, 15, 20, 25, 30, 25, 20, 15, 35, 30, 25, 20],
                     'value_2': [45, 40, 35, 30, 100, 110, 120, 130, 10, 20, 30, 40],
                     'rank_1': [np.NaN, np.NaN, np.NaN, np.NaN, 0, 0, 1, 1, 1, 1, 0, 0],
                     'rank_2': [np.NaN, np.NaN, np.NaN, np.NaN, 1, 1, 0, 0, 0, 0, 1, 1],
                    })
demo_full

    date group value_1 value_2 rank_1 rank_2
0   2009-06 1   10  45  NaN NaN
1   2009-06 1   15  40  NaN NaN
2   2009-06 2   20  35  NaN NaN
3   2009-06 2   25  30  NaN NaN
4   2009-07 1   30  100 0.0 1.0
5   2009-07 1   25  110 0.0 1.0
6   2009-07 2   20  120 1.0 0.0
7   2009-07 2   15  130 1.0 0.0
8   2009-08 1   35  10  1.0 0.0
9   2009-08 1   30  20  1.0 0.0
10  2009-08 2   25  30  0.0 1.0
11  2009-08 2   20  40  0.0 1.0

Где значение для rank_{i} считается следующим образом: мы группируем по дате (с точностью до месяца), группе, смотрим, например среднее и далее присваиваем ранг каждой группе - чем выше среднее, тем выше ранг и наоборот. Далее данный ранг нужно присвоить не текущему месяцу, а следующему, то есть у нас сдвиг на 1 месяц.
Ранг считаю следующим образом:
demo.groupby(['date', 'group'])['value_1'].mean().groupby('date').apply(lambda x: np.argsort(x))

date     group
2009-06  1        0
         2        1
2009-07  1        1
         2        0
2009-08  1        1
         2        0

*

*Как это реализовать?

*Можно ли реализовать при помощи методов groupby и shift?

*Можно ли задать гибкость в реализации, чтобы была возможность использовать разные промежутки для смещения, например неделя, 2 месяца, год и тд?

*Можно ли это распараллелить? У меня есть 8 ядер.

A: Можно преобразовать столбец date --> Period[M], это позволит использовать +1, чтобы сдвинуться на месяц вперед:
demo["date"] = pd.to_datetime(demo["date"]).dt.to_period("M")

grp = demo.assign(date=demo["date"]+1).groupby(['date', 'group'])

r1 = grp['value_1'].mean().groupby("date").apply(np.argsort).to_frame(name="rank_1")
r2 = grp['value_2'].mean().groupby("date").apply(np.argsort).to_frame(name="rank_2")

res = demo.set_index(["date", "group"]).join(r1).join(r2).reset_index()

результат:
In [96]: res
Out[96]:
       date  group  value_1  value_2  rank_1  rank_2
0   2009-06      1       10       45     NaN     NaN
1   2009-06      1       15       40     NaN     NaN
2   2009-06      2       20       35     NaN     NaN
3   2009-06      2       25       30     NaN     NaN
4   2009-07      1       30      100     0.0     1.0
5   2009-07      1       25      110     0.0     1.0
6   2009-07      2       20      120     1.0     0.0
7   2009-07      2       15      130     1.0     0.0
8   2009-08      1       35       10     1.0     0.0
9   2009-08      1       30       20     1.0     0.0
10  2009-08      2       25       30     0.0     1.0
11  2009-08      2       20       40     0.0     1.0


text:
Q: How do I validate input without exiting my do while loop? I'm working on a program that prompts the user to select from 3 different options by inputing an integer from 1-3 (4 to quit). I need to write a code that validates that the input is an integer, and reprompts them if it is not an integer. Here's the basic idea of my code (it is too long to post in entirety).
do
{
cout << "Menu: Please select one of the following options:" << endl;
    cout << " 1 - Drop a single chip into one slot." << endl;
    cout << " 2 - Drop multiple chips into one slot." << endl;
    cout << " 3 - Drop 5 chips into each slot." << endl;
    cout << " 4 - Quit the program." << endl;
    cout << "Enter your selection now: ";
    cin >> first_input;
}while (first_input!=4)

I then have multiple if statements that execute expressions based on which option the user chooses. I also prompt them to enter other integer values later in the code.
How do I send the user back to the menu, if the user inputs fails to input an integer and instead inputs characters? Constraints: Cannot use continue or break
Thanks in advance.

A: If you want to go back to the start in case of non-integer input, perhaps something like this would work?
// Insert after "cin >> first_input;"
if (cin.fail()) {
    // Handle non-int value.

    // Clear error flag.
    cin.clear();

    // Empty buffer up to next newline.
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    // Complain & restart.
    cout << "Invalid input.  Please try again." << endl;
    continue;
}

What this does is clear the error flag, purge the buffer, and go back to the start.  cin.ignore() doesn't explicitly need to be passed std::numeric_limits<std::streamsize>::max() as its first parameter; however, in case of error, I prefer to do so to make sure that the erroneous input is gone.  Note that std::numeric_limits is defined in the standard header <limits>, and requires its inclusion.

A: You are looking for the continue keyword.

A: do
{
    cout << "Menu: Please select one of the following options:" << endl;
    cout << " 1 - Drop a single chip into one slot." << endl;
    cout << " 2 - Drop multiple chips into one slot." << endl;
    cout << " 3 - Drop 5 chips into each slot." << endl;
    cout << " 4 - Quit the program." << endl;
    cout << "Enter your selection now: ";
    cin >> first_input;
    //lets say if user enters value out of range. then want to show menu again.
    if(first_input > 4) {
        cout << "Invalid input "<<endl;
        continue;
    }
    // you can do other stuff here.
    // ...
}while (first_input!=4)

A: You can try using goto label.

do{
   label:
        // your code
if(check) goto label;
}while(check);


text:
Q: Curl issue retrieving passed back GET parameters I am working with an OAuth API. Originally, I was making a header redirect once I received my $token than aggregating all of theGET parameters that were passed back to me. I'm trying to implement curl instead so I don't have to redirect back and forth. My problem is, I don't know how to retrieve the returned GET parameters after making my curl request. Here's my code
        $qry_str = "?oauth_token=" . $token;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, GSAPI_AUTHORIZE_ENDPOINT . $qry_str);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, '3');
        $content = trim(curl_exec($ch));

I've realized I don't need $content. What I need is the GET parameters which should be passed back when I imagine occurs when initiating curl_exec. How do I retrieve these?

*
-

A: What you need to do is get the curl request to return the headers as part of the return string. You then need to parse them for the "Location:" tag and use some of the built in parse functions within PHP to get the data you want. Try the below.
$qry_str = "?oauth_token=" . $token;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GSAPI_AUTHORIZE_ENDPOINT . $qry_str);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));

if(!$content) echo 'Curl error: ' . curl_error($ch);

preg_match('/Location\:\s(.*)\s/',$content,$matches);
$urlParts = parse_url(trim($matches[1]));
parse_str($urlParts['query'],$queryArray);

The $queryArray variable should now contain all of the query string parameters from the URL in the "Location:" field of the header.
EDIT:
This will work if you hitting a script at http://www.someurl.com/oauth.php and it's then redriecting to http://www.someotherurl.com/somescript.php?param1=x&param2=y.
The result of $queryArray will be array("param1" => 1, "param2" => 2), although I may have completely mis-understood your question...


text:
Q: ¿Cómo filtrar datos de un dataframe? Mejorar performance Python cómo están?
Mi consulta es la siguiente: tengo dos DataFrames (df1 y df2), en ambos tengo clientes con sus respectivos códigos. Necesito reducir el df1 de modo que me queden solo los clientes que aparecen en el df2.
Lo que hice es, primero, creo una lista con todos los clientes que tengo en el df2:
lista_clientes_df2 = list(df2["CLIENTE"].value_counts().index)

Luego, hago un for loop para que, vaya comprobando si cada cliente del df1 está en el df2, de lo contrario, que elimine dicha fila del df1:
for i in range(len(df1)):
    if (df1["Cliente"][i] in lista_clientes_df2) == False:
        df1 = df1.drop([i], axis = 0)

El problema me surge ya que los df tienen aproximadamente 2 millones de filas cada uno, y el tiempo de procesamiento es muy extenso.
Una aclaración: el df1 tiene mas filas que el df2, ya que, además de tener mas clientes, los mismos aparecen repetidas veces (en el df1 las filas no son UN CLIENTE, sino que cada fila es UN PRODUCTO). No se si me explico.
¿Qué sugerencia me podrían dar para mejorar este código?
Muchas gracias desde ya!
Saludos

A: la primera parte no se que tan necesaria sea con la función que te comentaré pero creo si es requerida, sin embargo para la segunda sección, basta usar la función .merge y emplear los parametros apropiados, segun me parece tu codigo quedaría así.
#Esa parte dices ya te funciona y es rápida
lista_clientes_df2 = list(df2["CLIENTE"].value_counts().index)
lista_clientes_df1 = list(df1["CLIENTE"].value_counts().index)
lista_nueva=lista_clientes_df1.merge(lista_clientes_df2, on='key', how='inner')

Creo con eso quedaría mucho mas rápido, y te quedarían en lista_nueva solo los que están en ambos df. Sin embargo, lo que deseas es botar de df1 a todos aquellos que no estén en ambos df, depende de como este estructurado, creo puedes modificar las lineas de arriba para hacerlo de forma directa, sin embargo hace tiempo no uso estas funciones y puedo cometer algún detalle, por lo que te recomendaría continuases investigando de la funcion .merge y por allí creo esta la solución.
Creo esto puede ser un buen inicio:
https://stackoverflow.com/questions/53645882/pandas-merging-101