text:
Q: What would be the correct way to use the keyword USING in the following C# code? I'm trying to get this correct as I feel I'm missing something. I want to use the keyword using whenever I have an IDisposable object. Please note that the code works, I just want to optimize it.
I have two questions here:
1) For this code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
What does it mean to add (HttpWebRequest) like that? Am I converting WebRequest to HttpWebRequest?
Why can't I do this?
HttpWebRequest rq = new HttpWebRequest();
rq.Create(url);

2) In the functional code below, how would I go about using the keyword using where applicable?
public static int UploadFileToixLibrary(string url, string file)
{
    NetworkCredential credentials = new NetworkCredential();
    credentials.UserName = AppVars.Username;
    credentials.Password = AppVars.Password;

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    request.Credentials = credentials;
    request.Method = "POST";
    request.ContentType = "image/tiff";
    request.Headers.Add("X-Object-Key", Path.GetFileName(file));

    byte[] bytes = File.ReadAllBytes(file);
    Stream st = null;

    try
    {
        request.ContentLength = bytes.Length;
        st = request.GetRequestStream();
        st.Write(bytes, 0, bytes.Length);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return 1;
    }
    finally
    {
        if (st != null)
        {
            st.Close();
        }
    }

    try
    {
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        StreamReader sr = new StreamReader(response.GetResponseStream());
        response.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return 1;
    }

    return 0;
}

A: Question 1:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

The reason for the cast, is that the static Create method on WebRequest returns an instance of WebRequest which is most appropriate for the scheme you supply in the url (ie, http:// address will return an HttpWebRequest, ftp:// will return FtpWebRequest etc). As you know your url is http, you know you'll get back an HttpWebRequest, so you can explicitly cast to the right type to get access to the extra functionality HttpWebRequest over the abstract WebRequest.
Now, WebRequest is not IDisposable, so you cannot use it inside a using statement!
Question 2: In your functional code, the only place you could use a using statement is around the Stream access:
try
{
    request.ContentLength = bytes.Length;
    st = request.GetRequestStream();
    st.Write(bytes, 0, bytes.Length);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
    return 1;
}
finally
{
    if (st != null)
    {
        st.Close();
    }
}

Could be re-written:
request.ContentLength = bytes.Length;
using(var st = request.GetRequestStream())
{
    st.Write(bytes, 0, bytes.Length);
    st.Close();
}

A: *

*WebRequest is a abstract class, it does not expose most of the properties/methods that you're going to use. You must cast it to the appropriate type to use it. The static method Create will return the specialized WebRequest object according to your URL. As you know that this URL uses the HTTP protocol (http://), it's safe to cast it to HttpWebRequest. It could, however, be a FtpWebRequest.

*You can put the GetRequestStream initilization inside using(...) statements. Looks like WebRequest (and its children) does not implement IDisposable

A: 1.
The Webrequest.Create method returns a WebRequest reference, but the actual object has different types depending on what kind of request you want to do. In your case you are doing a HTTP request, so the actual object is an HttpWebRequest object. You cast the reference to the actual type of the object to get access to the members that are specific for the HttpWebRequest class.
2.
The HttpWebRequest is not disposable. Use a using block for the HttpWebResponse object:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
  ...
}


text:
Q: If condition not work regular in bash Code
if [ $setup==="y" ]
    then
        echo "kurulum:"$setup
        exit
        full_dir=$full_dir"/public"
    else
    echo "Sub-Public folder is exist? [public,web]"
        read folder_extend
        if [ $folder_extend ]
                then
                full_dir=$full_dir"/"$folder_extend
        fi
fi

Setup param $setup view as "n" after run sh but still condition firts part run. Where wrong code ?
Thanks.

A: Change it to:
if [ "$setup" = "y" ]
    then
        echo "kurulum:"$setup
        exit
        full_dir=$full_dir"/public"
    else
    echo "Sub-Public folder is exist? [public,web]"
        read folder_extend
        if [ "$folder_extend" ]
                then
                full_dir=$full_dir"/"$folder_extend
        fi
fi

It should just be a single =, and you need spaces around it. You should also quote variables in most contexts, in case they contain spaces.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get a type in Scala AST of underscored lambda function parameter? Not digging in details of DSL, I could write (based on that example):
def InputLine = rule { Number ~ zeroOrMore("+" ~ Number ~> ((x: Int, y: Int) => x + y)) ~ EOI }

I need to call lambda function from macro. Scala AST representation of it is as follows:
List(
   ValDef(Modifiers(PARAM), newTermName("x"), TypeTree().setOriginal(Select(Ident(scala), scala.Int)), EmptyTree),
   ValDef(Modifiers(PARAM), newTermName("y"), TypeTree().setOriginal(Select(Ident(scala), scala.Int)), EmptyTree))

Important to note is that both x and y has types in AST. This works fine.
Next step is to use type inference, and simplify lambda as follows:
def InputLine = rule { Number ~ zeroOrMore("+" ~ Number ~> ((_:Int) + _)) ~ EOI }

Scala AST for that lambda:
List(
    ValDef(Modifiers(PARAM | SYNTHETIC), newTermName("x$1"), TypeTree().setOriginal(Select(Ident(scala), scala.Int)), EmptyTree),
    ValDef(Modifiers(PARAM | SYNTHETIC), newTermName("x$2"), TypeTree(), EmptyTree))

Note that x$2 param has no explicit type. I need that to call the function. Where should I get it? The solution "just pass parameter of type Any to a function" will not satisfy scalac as it requires Int.
This question is logically followed by that one.
The code is available at parboled2@gihub.

A: Number ~> ((_:Int) + _)

is transformed to something like this
pimpActionOp[...](rule).~>.apply[...](function)

type classes of pimpActionOp and apply contain all necessary information to restore types.


text:
Q: Bluetooth Settings Issue After Updating? I've installed Ubuntu 21.04 in a dual boot configuration alongside an existing installation of Windows 10.
Since using it for about one week I've applied all offered official updates and then restarted.
I paired a set of bluetooth headphones in Ubuntu and then ever since a restart the 'Bluetooth Settings' window either does not load or crashes.
Is Ubuntu 20.04.2.0 LTS more stable vs Ubuntu 21.04 for basic things like 'Bluetooth Settings'?


text:
Q: How do I get "Back to My Mac" (using MobileMe) from Windows? I have a MobileMe subscription and a Mac at home with "Back to My Mac" enabled. When I'm away from home, this service lets me use another Mac to connect to my Mac back home and access file sharing, screen sharing, etc.
As far as I know, the service doesn't use any proprietary protocols, so in theory I should also be able to get "Back to My Mac" from a Windows PC. This MacWorld article explains how it works. Basically, it uses Wide-Area Bonjour to give your Mac a domain name like hostname.username.members.mac.com. Remote computers can find your Mac using that address, then connect to it using a private VPN. The "Wide Area Bonjour" part seems to make it a little more complicated than simply a regular domain name, though.
Note that I'm not interested in using the methods described by LifeHacker, which doesn't use the MobileMe service at all. I don't want to use a totally different dynamic DNS service. I'd like to use the one I'm already paying for, or at least find out why that's not possible from Windows.
Also, my primary problem is finding a network route back to my mac... once I've got that I know how to enable services so that Windows can talk to it.
UPDATE: Based on some additional research, it appears that Apple is only assigning IPv6 addresses to the hostname.username.members.mac.com names. So any solution will require enabling IPv6 support on Windows, if possible.

A: Have you had any success with this? I have been trying to figure this out for about a week now. I assume that there is some sort of authentication required which is why you can't just enter yourusername.members.mac.com. as a search domain to see a list of services on your computer/router.
I have been unsuccessful in "manually" connecting to my computer via back to my mac even from other macs (which presumably have all the required technologies installed and turned on).Once I connect via the back to my mac interface though the mDNS just "magically" works when I run lookups for the "right" addresses.
As far as I am aware, there isn't a way to authenticate mDNS lookups, so Apple must have some external way of knowing which lookups they respond to. If they would publish this it would be super helpful!

A: I'm taking a stab in the dark at this one since I don't have the Back To My Mac service or MobileMe. Someone should correct me if I'm wrong, but I'm guessing that based on that MacWorld article, the Back To My Mac service just creates an address that you can access from anywhere on the Internet.
Thus, from that LifeHacker article, if you set up your Screen Sharing preferences to include a password for VNC clients (under Computer Settings), you should be able to use a regular VNC client (like the LifeHacker-suggested TightVNC) to connect to hostname.username.members.mac.com at port 5900.

Like I said, this is a guess based on how I think it ought to work, but there may be some trickery involved with Back To My Mac to block regular VNC clients from connecting to the Wide-Area Bonjour domain name.


text:
Q: how do I determine the file type of a video file Sometimes I get the url of a video embedded in a webpage and download it, just to find the file has no extension name.
I can play the video with a player, so it must be legal.
How do I determine the extension name of the video file in such circumstance?

A: Use Mediainfo, it is the best tool out there for this job.

A: If you don't already, open up a folder and go to Tools -> Folder Options -> View -> and deselect 'Hide extensions for known file types'
If you are downloading from YouTube, the format is going to be a .flv (flash video) unless your downloader converts it.
If all else fails, just click on the webpage, view the source, and find out where the video was embedded on the page and find the format. If you are getting them all from the same site, they are more than likely all going to have the same format.
These are just a few things I could think of, I hope they might possibly help you.

A: Or Gspot. Reviews HERE. It allows you to see what container, internal codec etc that your video is using.


text:
Q: Copy the datavalidation of Existing row and apply it to newly inserted row using c# EPP Plus I am trying get the drop down list And conditional formatting of existing rows and applying it to newly added row using c# EPP Plus.
is there any way to it in using sheet.InsertRow(2,1) or  sheet.Cells[1,2].Copy(sheet.Cells[1,2]) any of the method .
I dont want to add new list in drop down which is already there like
var textValidation = sheet.DataValidations.AddListValidation("B:B");
textValidation.Formula.Values.Add("male");
I want to copy listvalidation which is already there.
Thanks !!!


text:
Q: incorrect return output in def() I'm supposed to:
"Write a function search(words, start_chs) that returns a list of all words in the list words whose first letter is in the list start_chs.
If either words or start_chs is empty, return an empty list.
Since the returned list can have many words in it, the words should be arranged in the order that they originally appeared in."
e.g.
words = ['green', 'grasses', 'frolicking', 'cats', '', 'kittens', 'playful']
start_chs = ['a', 'c', 'g']

new_words = search(words, start_chs)    # ['green', 'grasses', 'cats']

My code thus far is below, however, it doesn't return all the correct outputs, only some of them.
def search(words, start_chs):
    k=0
    p=[]

    if (len(words)== 0) or (len(start_chs)== 0):
        return ([])
    while k < len(start_chs):
        if start_chs[k][0] == words[k][0]:
            p.append(words[k])
        k+=1
    return(p)

A: You can try this:-
def search(words, start_chs):
    res = []
    for word in words:
        if word!='' and word[0] in start_chs:
            res.append(word)
    return res

search(words, start_chs)

output:
['green', 'grasses', 'cats']

A: It should looks like that. It's bad practice to use iterate list with index, use for element in list instead.
About your code, why it's not working. It's because you should iterate over whole list. In this example you only check if 'a' equal first letter in 'green', 'c' in 'grasses' and 'g' in 'frolicking'.
words = ['green', 'grasses', 'frolicking', 'cats', '', 'kittens', 'playful']
start_chs = ['a', 'c', 'g']

def search(words, start_chs):
    result = []

    if len(words)== 0 or len(start_chs)== 0:
        return []
    for word in words:
        if word and word[0] in start_chs:
            result.append(word)
    return result

print(search(words, start_chs))

A: The problem with the code that you wrote is that you are only checking with the character at the corresponding index of the word. So you can use in in place of this.
def search(words, start_chs):
   k=0
   p=[]
   if (len(words)== 0) or (len(start_chs)== 0):
       return []
   for i in words:
       if  i[0] in start_chs:
           p.append(i)
       k+=1
   return p

A: Try this:
def search(words, start_chs):
    start_chs = tuple(start_chs)
    return [word for word in words if word.startswith(start_chs)]

words = ['green', 'grasses', 'frolicking', 'cats', '', 'kittens', 'playful']
start_chs = ['a', 'c', 'g']

new_words = search(words, start_chs)
#['green', 'grasses', 'cats']


text:
Q: How to get keys of $data.Entity? I wanted to get the keys of an $data.Entity but I haven't found the solution on how to do it. I am not referring to the JSON keys but the Entity primary keys.
$data.Entity.extend("Kissa", {
      name: { type: 'int', key: true }
      , address : { type: 'int', key: true }
      , age : { type: 'int' }
});

$data.EntityContext.extend("KISSA_DB", {
                kissa: { type: $data.EntitySet, elementType: Kissa }
            });

Now, I have an object like this and I wanted to get the keys which are "name" and "address".
var temp = new Kissa({name: "Kim", address: "Mars", age: 20});

Is there an available API like :
temp.getType().getKeys()

A: If temp is just a plain Object, then you can just use Object.keys and pass temp to it.
console.log(Object.keys(temp));


text: Q: How to change the default weather provider in Windows 8 Weather Modern UI app? The Modern UI Weather app in Windows 8/8.1 uses 3 weather forecast providers - WDT, Foreca & AccuWeather. The default is WDT, and its info about the current weather conditions is displayed on the app's live tile. However, its data are enough incorrect - at least, for my home city - so I'd like to change it to something else. How can I change the default weather provider to Foreca in this Modern UI app?


text:
Q: ActiveResource NoMethodError when using 'new' action without schema in RoR I'm unable to add 'new' RESTful entities without defining a schema in my RoR ActiveResource model, even though I've read this is optional. When omitting the schema (I've included it in the code below for clarity), I receive the following error:
NoMethodError in Pages#new

undefined method `author' for #<Page:0x4823dd8>

When I include the scheme, everything works as expected. I'd really rather not have to keep track of the schema every time it changes, and I've seen examples that don't require it. The other RESTful verbs (read, update & delete) all work without the scheme. Where am I going wrong? I used rails generate scaffold to create the scaffolding, if that's important.

Controller:
class PagesController < ApplicationController

  around_filter :shopify_session, :except => 'welcome'

...snip...

  def new
    @page = Page.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @page }
    end
  end

  def edit
    @page = Page.find(params[:id])
  end

  def create
    @page = Page.new(params[:page])

    respond_to do |format|
      if @page.save
        format.html { redirect_to @page, notice: 'Page was successfully created.' }
        format.json { render json: @page, status: :created, location: @page }
      else
        format.html { render action: "new" }
        format.json { render json: @page.errors, status: :unprocessable_entity }
      end
    end
  end

...snip...

end

Model:
class Page < ShopifyAPI::Page    #Note: ShopifyAPI::Page extends ActiveResource::Base
    schema do
        string :author
        string :body_html
        string :title
        string :metafield
        string :handle
    end
end

View: (cut for brevity)
...
<%= form_for(@page) do |f| %>
    <% if @page.errors.any? %>

<%= pluralize(@page.errors.count, "error") %> prohibited this page from being saved:

            <% @page.errors.full_messages.each do |msg| %>

<%= msg %>

            <% end %>

    <% end %>

        <%= f.label :author %>

        <%= f.text_field :author %>

...

A: You're missing attr_accessible:
http://apidock.com/rails/ActiveRecord/Base/attr_accessible/class


text:
Q: Adobe Presenter CMI Data Model I want to build an e-learning LMS using Adobe Presenter 7 as content authoring tools. I recently read the SCORM 2004 user guide. It says we have to access CMI data model to track user performance. But, I can't find any files with name containing cmi in the zip file the Adobe Presenter 7 created.
Any idea where I can find it?

A: You can read the RTE book to understand the CMI data model. CMI data model is NOT a file in the content package. It is a data model provided by the LMS. In fact, the SCO can communicate with LMS through the use of this data model elements. For example, the SCO can get learner's name with the following JavaScript code:
var learnerName = GetValue("cmi.learner_name");
Or, the SCO can set the activity's success status to passed with the following JavaScript code:
SetValue("cmi.success_status", "passed");
You can download the RTE book with the following link:
http://www.adlnet.gov/wp-content/uploads/2011/07/SCORM_2004_4ED_v1_1_Doc_Suite.zip


text:
Q: SPFieldLookupValue in Linq Query I'm trying to the the value of a lookup field in SharePoint using Linq and a collection of SPListItem - something like this:
   int totalDepts = (from SPListItem itm in hourEntries select ((SPFieldLookupValue)itm["Level1"]).LookupValue).Distinct().Count();

But that doesn't seem to work (and it strikes me as missing some steps)
Has anyone done this before?

A: I wasn't able to figure out to do it directly in the Linq query, so I ended up creating WorkHoursEntries object, and populating it with all my SPListItems
List<WorkHourEntry> workHourEntries = new List<WorkHourEntry>();
                foreach (SPListItem hourEntry in hourItems)
                {
                    //Collect entries that are in the current Fiscal Year reporting period
                    if (fiscalYearMonths.Contains(hourEntry["Reporting_x0020_Month"].ToString()))
                    {

                    WorkHourEntry curEntry = new WorkHourEntry();
                    string Level1 = (string)hourEntry["Level1"];
                    SPFieldLookupValue val = new SPFieldLookupValue(Level1);
                    curEntry.organization = val.LookupValue;
                    SPFieldCalculated cf = (SPFieldCalculated)hourEntry.Fields["WECSCHours"];
                    curEntry.WECSCHours = cf.GetFieldValueForEdit(hourEntry["WECSCHours"]);
                    workHourEntries.Add(curEntry);

                    }
                }

This allowed me to run Linq queries directly on the WorkHourEntry collection
var uniqueDeptNames = (from itm in workHourEntries select itm.organization).Distinct().ToArray();


text:
Q: iPhone 4s not activating fully with AT&T sim I bought a used iPhone 4s from eBay and, of course, when I recieved it, it was inactivated.  I put in an old At&t sim I had in the house (not sure where it came from as I've never had At&T), and I was able to get past the activation screen and enter some info and set up Siri and iCloud.
However, it never actually gave me the message that is was now activated and when I try to put my sim from another carrier in, it reverts back to the inactive screen. It is not currently unlocked (I am attempting to complete that but must get past the inactive screen).
I have the latest iTunes installed and I have tried doing a backup and restore from backup and also just a hard restore all after fully rebooting the device.
Is it the sim or am I doing something wrong?

A: What you describe is consistent with an iPhone that is still locked to AT&T as the sole carrier. You can go to the AT&T websites and fill out a form to see if the phone could be unlocked. If you can't get AT&T to unlock the phone, then you could take that up with the seller of the phone or perhaps see about jailbreaking the device and unlocking it by force as opposed to by social convention.


text:
Q: Why won't thin start on the port I specify? I'm [mis]managing thin workers with god, and getting an unexpected result that I'm having trouble diagnosing. My god watch block is fairly straightforward:
(1..4).each do |index|
  God.watch do |w|
    name     = "thin-#{index}"
    port     = 8300 + index
    pid_name = "thin.#{port}.pid"
    pid_path = God.pid_file_directory.join pid_name

    # General settings.
    w.name     = name
    w.interval = 5.seconds
    w.pid_file = pid_name

    # Configuration for thin instances.
    start_options = {
      address:     '0.0.0.0',
      environment: RAILS_ENV,
      only:        index,
      port:        port,
    }.inject("") { |s,(k,v)| s << " --#{k}=#{v}" }

    # Process management commands.
    bin       = "/vagrant/bin/thin -c #{RAILS_ROOT}"
    w.start   = "#{bin} #{start_options} start"
    w.restart = "#{bin} --pid #{pid_path} restart"
    w.stop    = "#{bin} --pid #{pid_path} stop"

    # Management conditions.
    w.start_if do |start|
      start.condition(:process_running) do |c|
        # Ensure the worker is running.
        c.interval = 5.seconds
        c.running  = false
      end
    end

  end
end

And it will fire up 4 thin servers, but on the wrong ports. Here's output from running god in debug mode:
vagrant@localhost:/vagrant$ RAILS_ENV=development god -c config/app.god -D
I [2014-04-30 18:27:05]  INFO: Loading config/app.god
I [2014-04-30 18:27:05]  INFO: Syslog enabled.
I [2014-04-30 18:27:05]  INFO: Using pid file directory: /vagrant/tmp/pids
I [2014-04-30 18:27:06]  INFO: Started on drbunix:///tmp/god.17165.sock
I [2014-04-30 18:27:06]  INFO: thin-1 move 'unmonitored' to 'up'
I [2014-04-30 18:27:06]  INFO: thin-1 moved 'unmonitored' to 'up'
I [2014-04-30 18:27:06]  INFO: thin-3 move 'unmonitored' to 'up'
I [2014-04-30 18:27:06]  INFO: thin-4 move 'unmonitored' to 'up'
I [2014-04-30 18:27:06]  INFO: thin-4 moved 'unmonitored' to 'up'
I [2014-04-30 18:27:06]  INFO: thin-2 move 'unmonitored' to 'up'
I [2014-04-30 18:27:06]  INFO: thin-3 moved 'unmonitored' to 'up'
I [2014-04-30 18:27:06]  INFO: thin-2 moved 'unmonitored' to 'up'
I [2014-04-30 18:27:06]  INFO: thin-1 [trigger] process is not running (ProcessRunning)
I [2014-04-30 18:27:06]  INFO: thin-3 [trigger] process is not running (ProcessRunning)
I [2014-04-30 18:27:06]  INFO: thin-4 [trigger] process is not running (ProcessRunning)
I [2014-04-30 18:27:06]  INFO: thin-1 move 'up' to 'start'
I [2014-04-30 18:27:06]  INFO: thin-3 move 'up' to 'start'
I [2014-04-30 18:27:06]  INFO: thin-4 move 'up' to 'start'
I [2014-04-30 18:27:06]  INFO: thin-4 start: /vagrant/bin/thin -c /vagrant  --address=0.0.0.0 --environment=development --only=4 --port=8304 start
I [2014-04-30 18:27:06]  INFO: thin-2 [trigger] process is not running (ProcessRunning)
I [2014-04-30 18:27:06]  INFO: thin-2 move 'up' to 'start'
I [2014-04-30 18:27:06]  INFO: thin-1 start: /vagrant/bin/thin -c /vagrant  --address=0.0.0.0 --environment=development --only=1 --port=8301 start
I [2014-04-30 18:27:06]  INFO: thin-3 start: /vagrant/bin/thin -c /vagrant  --address=0.0.0.0 --environment=development --only=3 --port=8303 start
I [2014-04-30 18:27:06]  INFO: thin-2 start: /vagrant/bin/thin -c /vagrant  --address=0.0.0.0 --environment=development --only=2 --port=8302 start

But instead of my thin servers listening on 830{1,2.3.4}, they're listening on 830{2,4.6.8} instead:
vagrant@localhost:/vagrant$ ps aux | grep thin
vagrant   4535 49.8  2.3 113712 83936 ?        Sl   18:27   0:03 thin server (0.0.0.0:8306)
vagrant   4541 51.4  2.3 113464 83716 ?        Sl   18:27   0:03 thin server (0.0.0.0:8304)
vagrant   4547 55.5  2.3 113276 83504 ?        Sl   18:27   0:03 thin server (0.0.0.0:8302)
vagrant   4553 54.2  2.3 113740 83928 ?        Sl   18:27   0:03 thin server (0.0.0.0:8308)
vagrant   4569  0.0  0.0   3912   828 pts/0    S+   18:27   0:00 grep --color=auto thin

All of my pid files, log entries, etc show the {2.4.6,8} numbers. Given my code and debug output from god, I'm thinking there's something wrong on thin's end, but I have no idea what to look for.
Also, this pattern (base + 2,4,6,8 instead of base + 1,2,3,4) is repeatable - e.g. if I set the port base to 5555, the results are not 5556, 5557, 5558, and 5559 but instead 5557, 5559, 5561, and 5563.
Am I missing something from the thin documentation? Is there some conflict and I need to tell god to stagger the start commands by a few seconds? Are there additional diagnostic tools I could be using? I'm stuck in the mud here.

EDIT1
If try to "go with the flow" and change
(1..4).each do |index|

to
[2,4,6,8].each do |index|

then instead of {2,4,6,8}, I get {4,8,12,16} which leaves me just as confused as before.

EDIT2
I'm now pretty certain this has nothing to do with god, so I'm changing the question title. Here's new evidence:
vagrant@localhost:/vagrant$ /vagrant/bin/thin -c /vagrant  --address=0.0.0.0 --environment=development --only=1 --port=8301 --servers=1 start
Starting server on 0.0.0.0:8302 ...

Why does thin refuse to start on the port which I request?

EDIT3
Breaking this down to the simplest case, I find the culprit:
vagrant@localhost:/vagrant$ /vagrant/bin/thin -c /vagrant --port=8301 start
Using rack adapter
Thin web server (v1.6.2 codename Doc Brown)
Maximum connections set to 1024
Listening on 0.0.0.0:8301, CTRL+C to stop
^CStopping ...
vagrant@localhost:/vagrant$ /vagrant/bin/thin -c /vagrant --only=1 --port=8301 start
Starting server on 0.0.0.0:8302 ...
vagrant@localhost:/vagrant$ ^C

So for some reason the --only directive causes misbehavior vis a vis port binding. The problem now is that I lose control over where thin is placing its pid file when I don't specify --only=1.

A: Found the answer somewhere in between all the things I'd tried. In final form, I've got the following:
# Configuration for thin servers.
start_options = {
  address:     '0.0.0.0',
  chdir:       RAILS_ROOT,
  environment: RAILS_ENV,
  port:        port,
}.inject("") { |s,(k,v)| s << " --#{k}=#{v}" }

# Process management commands.
bin       = "/vagrant/bin/thin"
# NOTE: pid not specified during start
w.start   = "#{bin} #{start_options} start"
# NOTE: pid specified for restart and stop
w.restart = "#{bin} --pid tmp/pids/thin-#{index}.pid restart"
w.stop    = "#{bin} --pid tmp/pids/thin-#{index}.pid stop"

Setting God.pid_file_directory = 'tmp/pids' while omitting w.pid_file allows god to place pid files "naturally" (e.g. based on process name like tmp/pids/thin-1.pid). Also it's important in w.start to omit --pid, --daemonize, and --only to prevent thin from daemonizing and clustering itself. In this setup, god is handling all of those details so I need to keep thin from trying outsmart itself.
My previous configurations bungled this clean separation, and the result was that god was trying to manage thin, but thin was also trying to manage itself. Much like an overbearing parent in a screaming match with a rebellious teenager, the more control each attempted to exert over the situation, the more twisted and unstable the overall system became.
The last piece of the puzzle - which enables full process control via god - is that --pid (while unspecified during start) must be passed to thin during restart and stop - thin doesn't know which process to signal at that point without a PID since god is (rightly) managing the daemonization.


text:
Q: Use numpy arrays as arguments in odeint I am trying to solve a system with differential equations using odeint. I have 4 txt files (that look like the picture below). I read them and I save them in numpy arrays (length:8000) (maby not with the most effective way, but anyway...). I want to pass these 4 arrays as arguments in my odeint and solve the system. For example, at every time step the odeint takes (one from the 8000) to solve the system, I want it to use a different value from these arrays. Is there any way to do it automatically without getting lost in for loops? I tried to do it like this (see code below) but I get the error:
if g2>0: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

g2 supposed to be 1x1 size at every loop of odeint. So it has to be something with the way I use the 4 arrays (xdot,ydot,xdotdot,ydotdot).
I am new to python and I use python 2.7.12 on Ubuntu 16.04 LTS.
Thank you in advance.

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

added_mass_x = 0.03 # kg
added_mass_y = 0.04
mb = 0.3 # kg
m1 = mb-added_mass_x
m2 = mb-added_mass_y
l1 = 0.07 # m
l2 = 0.05 # m
J = 0.00050797 # kgm^2
Sa = 0.0110 # m^2
Cd = 2.44
Cl = 3.41
Kd = 0.000655 # kgm^2
r = 1000 # kg/m^3

c1 = 0.5*r*Sa*Cd
c2 = 0.5*r*Sa*Cl
c3 = 0.5*mb*(l1**2)
c4 = Kd/J
c5 = (1/(2*J))*(l1**2)*mb*l2
c6 = (1/(3*J))*(l1**3)*mb

theta_0 = 10*(np.pi/180) # rad
theta_A = 20*(np.pi/180) # rad
f = 2 # Hz

###################################################################

t = np.linspace(0,100,8000) # s

###################################################################

# Save data from txt files into numpy arrays
xdot_list = []
ydot_list = []
xdotdot_list = []
ydotdot_list = []

with open('xdot.txt', 'r') as filehandle:
    filecontents = filehandle.readlines()

    for line in filecontents:
        current_place = line[:-1]
        xdot_list.append(current_place)

xdot = np.array(xdot_list, dtype=np.float32)

with open('ydot.txt', 'r') as filehandle:
    filecontents = filehandle.readlines()

    for line in filecontents:
        current_place = line[:-1]
        ydot_list.append(current_place)

ydot = np.array(ydot_list, dtype=np.float32)

with open('xdotdot.txt', 'r') as filehandle:
    filecontents = filehandle.readlines()

    for line in filecontents:
        current_place = line[:-1]
        xdotdot_list.append(current_place)

xdotdot = np.array(xdotdot_list, dtype=np.float32)

with open('ydotdot.txt', 'r') as filehandle:
    filecontents = filehandle.readlines()

    for line in filecontents:
        current_place = line[:-1]
        ydotdot_list.append(current_place)

ydotdot = np.array(ydotdot_list, dtype=np.float32)

def inverse(k,t,xdot,ydot,xdotdot,ydotdot):
    vcx_i = k[0]
    vcy_i = k[1]
    psi_i = k[2]
    wz_i = k[3]
    theta_i = k[4]
    theta_deg_i = k[5]

    # Subsystem 4
    vcx_i = xdot*np.cos(psi_i)-ydot*np.sin(psi_i)
    vcy_i = ydot*np.cos(psi_i)+xdot*np.sin(psi_i)
    psidot_i = wz_i
    vcxdot_i = xdotdot*np.cos(psi_i)-xdot*np.sin(psi_i)*psidot_i-ydotdot*np.sin(psi_i)-ydot*np.cos(psi_i)*psidot_i
    vcydot_i = ydotdot*np.cos(psi_i)-ydot*np.sin(psi_i)*psidot_i+xdotdot*np.sin(psi_i)+xdot*np.cos(psi_i)*psidot_i

    g1 = -(m1/c3)*vcxdot_i+(m2/c3)*vcy_i*wz_i-(c1/c3)*vcx_i*np.sqrt((vcx_i**2)+(vcy_i**2))+(c2/c3)*vcy_i*np.sqrt((vcx_i**2)+(vcy_i**2))*np.arctan2(vcy_i,vcx_i)
    g2 = (m2/c3)*vcydot_i+(m1/c3)*vcx_i*wz_i+(c1/c3)*vcy_i*np.sqrt((vcx_i**2)+(vcy_i**2))+(c2/c3)*vcx_i*np.sqrt((vcx_i**2)+(vcy_i**2))*np.arctan2(vcy_i,vcx_i)

    A = 12*np.sin(2*np.pi*f*t+np.pi) # eksiswsi tail_frequency apo simulink
    if A>=0.1:
        wzdot_i = ((m1-m2)/J)*vcx_i*vcy_i-c4*wz_i**2*np.sign(wz_i)-c5*g2-c6*np.sqrt((g1**2)+(g2**2))
    elif A<-0.1:
        wzdot_i = ((m1-m2)/J)*vcx_i*vcy_i-c4*wz_i**2*np.sign(wz_i)-c5*g2+c6*np.sqrt((g1**2)+(g2**2))
    else:
        wzdot_i = ((m1-m2)/J)*vcx_i*vcy_i-c4*wz_i**2*np.sign(wz_i)-c5*g2

    # Subsystem 5
    if g2>0:
        theta_i = np.arctan2(g1,g2)
    elif g2<0 and g1>=0:
        theta_i = np.arctan2(g1,g2)-np.pi
    elif g2<0 and g1<0:
        theta_i = np.arctan2(g1,g2)+np.pi
    elif g2==0 and g1>0:
        theta_i = -np.pi/2
    elif g2==0 and g1<0:
        theta_i = np.pi/2
    elif g1==0 and g2==0:
        theta_i = 0

    theta_deg_i = (theta_i*180)/np.pi

    return [vcxdot_i, vcydot_i, psidot_i, wzdot_i, theta_i, theta_deg_i]

# initial conditions
vcx_i_0 = 0.1257
vcy_i_0 = 0
psi_i_0 = 0
wz_i_0 = 0
theta_i_0 = 0
theta_deg_i_0 = 0
#theta_i_0 = 0.1745
#theta_deg_i_0 = 9.866
k0 = [vcx_i_0, vcy_i_0, psi_i_0, wz_i_0, theta_i_0, theta_deg_i_0]

# epilysi systimatos diaforikwn
k = odeint(inverse, k0, t, args=(xdot,ydot,xdotdot,ydotdot), tfirst=False)

# apothikeysi apotelesmatwn
vcx_i = k[:,0]
vcy_i = k[:,1]
psi_i = k[:,2]
wz_i = k[:,3]
theta_i = k[:,4]
theta_deg_i = k[:,5]

# Epanalipsi tu Subsystem 5 gia na mporun na plotaristun ta theta_i, theta_deg_i
theta_i = [inverse(k_i, t_i)[4] for t_i, k_i in zip(t, k)]
theta_deg_i = [inverse(k_i, t_i)[5] for t_i, k_i in zip(t, k)]

# Ypologismos mesis gwnias theta kai platus talantwsis
mesi_gwnia = sum(theta_i)/len(theta_i) # rad
platos = (max(theta_i)-min(theta_i))/2

UPDATE:
The most relevant solution I found so far is this:
Solving a system of odes (with changing constant!) using scipy.integrate.odeint?
But since I have only values of my variables in arrays and not the equation of the variables that depend on time (e.g. xdot=f(t)), I tried to aply an interpolation between the values in my arrays, as shown here: ODEINT with multiple parameters (time-dependent)
I managed to make the code running without errors, but the total time increased dramatically and the results of the system solved are completely wrong. I tried any possible type of interpolation that I found here: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html but still wring outcome. That means that my interpolation isn't the best possible, or my points in the arrays (8000 values) are too much to interpolate between them and solve the system correctly.


text: Q: Browser Manual refreshing showing JSON data in webpage using angular js routing .config(['$routeProvider',function($routeProvider,$routeParams){$routeProvider.when('/mainpage',{templateUrl :'/views/index.html',controller :'mainpage'})


text:
Q: If ${ x }^{ 4 }+{ y }^{ 2 }=1$ then $x$ and $y$ can be both rational numbers? Can you give two numbers $x,y\in\mathbb{Q}$ such that  ${ x }^{ 4 }+{ y }^{ 2 }=1$?
I don't know if exists or not. I derived this equation questioning that if $\sin { \alpha  } ={ x }^{ 2 }$ for $x\in \mathbb{Q}$ then for which $\alpha$, $\cos{ \alpha  }=y$ and $y\in \mathbb{Q}$?
Edit: $x,y\neq0$

A: Consider $\dfrac{p}{q}=x$ and $y=\dfrac{m}{n}$, such that $\gcd (p,q)=(m,n)=1$ and $n \neq 1$, $q \neq 1$
$(\dfrac{p}{q})^4=1-(\dfrac{m}{n})^2=(1-\dfrac{m}{n})(1+\dfrac{m}{n})$
$=(\dfrac{n-m}{n})(\dfrac{n+m}{n})=\dfrac{(n-m)(n+m)}{n^2}$, here $n^2 \nmid (n-m)(n+m)$ since $q \neq 1$.
Let $d$ be a divisor of $n$, note that $d \nmid(n+m)$ and $d \nmid (n-m)$, Using the fact: $\gcd(m,n)=1$
Now this implies $(n-m)(n+m)=p^4, n^2 =q^4$, which isn't possible.(Recalling Area of right angled triangle can't be a square, it doesn't exist as proven by Fermat)

A: Denote $x=\dfrac{b}{a},y=\dfrac{d}{c},a,b,c,d>0,$ then $(\dfrac{b}{a})^4-(\dfrac{d}{c})^2=1,$ hence $a^4=c^2,c=a^2,b^4-d^2=a^4,$ this equation has no positive integer solution, see Solving $x^4-y^4=z^2$


text:
Q: Download file using WorkManager I am working/trying with download a file with pause and resume functionality using WorkManager with MVVM.
Here I am seeking pause/resume and download percentage progress update with use of WorkManager. So I am sharing my classes here.
MainActivity.kt
class MainActivity : AppCompatActivity() {

    lateinit var downloadViewModel : DownloaderViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this,R.layout.activity_main)
        downloadViewModel = ViewModelProviders.of(this).get(DownloaderViewModel::class.java)
        binding.viewmodel = downloadViewModel
        download_button.setOnClickListener({
                startDownload()
        })

        cancel_button.setOnClickListener({
            downloadViewModel.cancelDownloadWork(Constants.TAG_OUTPUT)
            WorkUtils.deleteFile(WorkUtils.getIsbn(Constants.TAG_OUTPUT))
        })

        downloadViewModel.mSavedWorkStatus.observe(this, Observer {

            it?.let {

            }
            if(it?.size!! > 0){
                val workStatus = it.first()
                val workState =  workStatus?.state
                downloadViewModel.updateDownloadWorkState(workState.toString())
                WorkUtils.makeStatusNotification(workState.toString(),this.applicationContext)
            }
        })

        pause_button.setOnClickListener({
            downloadViewModel.cancelDownloadWork(Constants.TAG_OUTPUT)
            val pausedAt = WorkUtils.getFileSize(WorkUtils.getIsbn(DOWNLOAD_URL))
            Log.d("paused at","paused at $pausedAt")
        })

        resume_button.setOnClickListener({
            val resumeFrom = WorkUtils.getFileSize(WorkUtils.getIsbn(DOWNLOAD_URL))
            Log.d("paused at","resumed at ${resumeFrom+1}")
            startDownload()
        })

    }

    fun startDownload() {
        downloadViewModel.downloadUrl =  DOWNLOAD_URL
        downloadViewModel.makeDownloadRequest()
    }

    fun isFileExists(url : String) : Boolean {

        return File(WorkUtils.getAbsolutePath(WorkUtils.getIsbn(url))).exists()

    }
}

Constants.kt
class Constants {
    companion object {

        val DOWNLOAD_URL = "download_url"
        // Notification Channel constants

        // Name of Notification Channel for verbose notifications of background work
        val VERBOSE_NOTIFICATION_CHANNEL_NAME: CharSequence = "Verbose WorkManager Notifications"
        var VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION = "Shows notifications whenever work starts"
        val NOTIFICATION_TITLE: CharSequence = "WorkRequest Starting"
        val CHANNEL_ID = "VERBOSE_NOTIFICATION"
        val NOTIFICATION_ID = 1

        // The name of the image manipulation work
        internal val IMAGE_MANIPULATION_WORK_NAME = "image_manipulation_work"

        // Other keys
        val OUTPUT_PATH = "blur_filter_outputs"
        val KEY_DOWNLOAD_URL = "KEY_DOWNLOAD_URL"
        internal val TAG_OUTPUT = "OUTPUT"

        val DELAY_TIME_MILLIS: Long = 3000

        // Ensures this class is never instantiated
        private fun Constants() {}
    }
}

DownloaderViewModel.kt
To make download request and notify the UI using binding. Cancelling the download(work) using WorkManager instance.
class DownloaderViewModel : ObservableViewModel() {
    var  mWorkManager : WorkManager = WorkManager.getInstance()

    var   mSavedWorkStatus: LiveData<List<WorkStatus>>
    @Bindable
    var currentDownloadState : MutableLiveData<String> = MutableLiveData()
    init {
        mSavedWorkStatus = mWorkManager.getStatusesByTagLiveData(Constants.TAG_OUTPUT)
    }

    lateinit var  downloadUrl: String
    /**
     * Creates the input data bundle which includes the Uri to operate on
     * @return Data which contains the Image Uri as a String
     */
    private fun createInputData(): Data {
        val builder = Data.Builder()
        if (downloadUrl != null) {
            builder.putString(KEY_DOWNLOAD_URL, downloadUrl)
        }
        return builder.build()
    }

    fun makeDownloadRequest() {

        // Create charging constraint
        val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresCharging(true)
                .build()

        // Add WorkRequest to download the epub to the filesystem
        val save = OneTimeWorkRequest.Builder(DownloadWorker::class.java)
                .setConstraints(constraints)
                .setInputData(createInputData())
                .addTag(TAG_OUTPUT)
                .build()
        mWorkManager.enqueue(save)
    }

    fun cancelDownloadWork(tag : String) {
        mWorkManager.cancelAllWorkByTag(tag)
    }

    fun getDownloadWorkState()  {
        getOutputStatus()
    }

    fun updateDownloadWorkState(state: String){
        currentDownloadState.value = state
        notifyPropertyChanged(BR.currentDownloadState)
    }

    internal fun getOutputStatus(): LiveData<List<WorkStatus>> {
        return mWorkManager.getStatusesByTagLiveData(TAG_OUTPUT)
    }
}

Worker class : DownloadWorker.kt
This class used to start the download work . As the server supports range request, every OneTimeWorkRequest started with this work range to download the file.
class DownloadWorker(context : Context,workerParameters: WorkerParameters) : Worker(context,workerParameters) {
    override fun doWork(): Result {

        val applicationContext = applicationContext

        // Makes a notification when the work starts and slows down the work so that it's easier to
        // see each WorkRequest start, even on emulated devices

        lateinit var result : Result
        val inputData : String? = inputData.getString(KEY_DOWNLOAD_URL)
        inputData?.let {
             result =  downloadFile(inputData)

        }
        return result
    }

    fun downloadFile(url : String) : Result {
        var input: InputStream? = null
        var output: OutputStream? = null
        var connection: HttpURLConnection? = null
        lateinit var result : Result

        val isbnFileName = WorkUtils.getIsbn(url);
        val filePathToWrite = WorkUtils.getAbsolutePath(isbnFileName)

        //val path = "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).path}${File.separator}${"file.zip"}"
        Log.d("Download file path :","Download file path :"+filePathToWrite)
        val targetFile = File(filePathToWrite)
        if(!targetFile?.exists()){
            targetFile.createNewFile()
        }

        try {
            val urlConnection = URL(url)
            connection = urlConnection.openConnection() as HttpURLConnection
            val range = WorkUtils.getFileSize(isbnFileName)+1
            connection.setRequestProperty("Range","bytes=${range}-")
            Log.d("Range","Request header Range is $range")
            connection.connect()

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.responseCode != HttpURLConnection.HTTP_OK) {
                Log.e("","Server returned HTTP ${connection.responseCode} ${connection.responseMessage}")
                result =  Result.FAILURE
            }

            // download the file

            input = connection.inputStream

            input?.let {
                output = FileOutputStream(targetFile, false)

                val data = ByteArray(1024 * 4)
                var count: Int

                do {
                    count = input.read(data)
                    if (count != 1) {
                        output!!.write(data, 0, count)

                    } else {
                        break
                    }

                } while (count != -1)
            }

            result = Result.SUCCESS

        } catch (e: Exception) {
            Log.e("Exception occured:",e.message)
            result =  Result.FAILURE
        } finally {
            try {
                output?.close()
                input?.close()
                connection?.disconnect()
            } catch (e: IOException) {
                Log.e("Exception occured:",e.message)
            }
        }
        return result
    }
}

Utilities used in this sample
Utils.kt
class WorkUtils {

    companion object {
        private val TAG = WorkUtils::class.java.getSimpleName()

    fun makeStatusNotification(message: String, context: Context) {

        // Make a channel if necessary
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Create the NotificationChannel, but only on API 26+ because
            // the NotificationChannel class is new and not in the support library
            val name = Constants.VERBOSE_NOTIFICATION_CHANNEL_NAME
            val description = Constants.VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION
            val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(Constants.CHANNEL_ID, name, importance)
            channel.description = description

            // Add the channel
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            notificationManager?.createNotificationChannel(channel)
        }

        // Create the notification
        val builder = NotificationCompat.Builder(context, Constants.CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(Constants.NOTIFICATION_TITLE)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setVibrate(LongArray(0))

        // Show the notification
        NotificationManagerCompat.from(context).notify(Constants.NOTIFICATION_ID, builder.build())
    }

        /**
         * Method for sleeping for a fixed about of time to emulate slower work
         */
        fun sleep() {
            try {
                Thread.sleep(Constants.DELAY_TIME_MILLIS, 0)
            } catch (e: InterruptedException) {
                Log.d(TAG, e.message)
            }

        }

        fun getIsbn(url: String) : String {
            return url.substring(url.lastIndexOf("/")+1)
        }

        fun getAbsolutePath(isbnFileName: String): String {
            return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/"+isbnFileName+".zip";
        }

        fun getFileSize(isbn:String) : Long {

            val file: File = File(getAbsolutePath(isbn))
            if(!file?.exists())
            {
                return 0
            }else{
                return file?.length()
            }
        }

        fun deleteFile(isbn: String) {
            val file = File(getAbsolutePath(isbn))
            if(file.exists() && file.isFile) {
                file.delete()
            }
        }

    }
}

For the UI part with databinding
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    >
    <data>

        <import type="com.pkonf.downloadebook.viewmodels.DownloaderViewModel" />

        <variable
            name="viewmodel"
            type="com.pkonf.downloadebook.viewmodels.DownloaderViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

        <TextView
            android:id="@+id/download_status"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:text="@{viewmodel.currentDownloadState}"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="368dp"
            android:layout_height="50dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:orientation="horizontal"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent">

            <Button
                android:id="@+id/pause_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="pause_button"
                tools:text="Pause" />

            <Button
                android:id="@+id/resume_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="resume_button"
                tools:text="Resume" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="377dp"
            android:layout_height="157dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="28dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:gravity="center_horizontal|center_vertical"
            android:orientation="vertical"
            app:layout_constraintBottom_toTopOf="@+id/linearLayout"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/download_status"
            app:layout_constraintVertical_bias="0.95">

            <Button
                android:id="@+id/download_button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="-1dp"
                android:text="Download"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="@id/linearLayout2"
                app:layout_constraintTop_toTopOf="@+id/linearLayout2" />

            <Button
                android:id="@+id/cancel_button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                android:text="Cancel"
                app:layout_constraintBottom_toBottomOf="@+id/linearLayout2"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/download_button" />

        </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

I have tried with - starting the download - pausing the download (here pausing means cancelling the current OneTimeWorkRequest) and resuming by creating new OneTimeWorkRequest and start/resume with downloaded file length+1 as bytes range in request header.
But the cancel is not working in my case. Don't know what I am doing wrong.
And my questions are,
1. Can we do pause and resume download using WorkManager?
2. Can we update progress bar using WorkManager?
3. Ref : link is this is the only way to update the progress bar?

A: Try an object lock like this:
private Object lock = new Object();
new Thread() {
        @Override
        public void run() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            callApi();
        }
    }.start();

The task will hang forever until user click resume button:
 synchronized (lock) {
                    lock.notify(); // Will wake up lock.wait()
                }

A: You can do this, override the onStopped() method of DownloadWorker class and then execute, connection.disconnect()
Something like this:
class DownloadWorker(context : Context,workerParameters: WorkerParameters) : Worker(context,workerParameters) {
    private val connection: HttpUrlConnection? = null

    override fun doWork(): Result {
        connection = ...

        ...
    }

    override fun onStopped() {
        super.onStopped()
        connection.disconnect()
    }
}


text:
Q: How to plot two curves with the same area under? I doubt this is doable in tikz/pgfplots but maybe some expert could give me an idea.
I would like the area under the second graph to be the same as the one under the first graph (they are probability density function, the area under them should be equal to 1).
Moreover, I would like the gray zones to have the same area.
The second graph can have a slightly different shape, of course, the important thing is it has a "fat" right tail.
\documentclass[11pt, border=3cm]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usetikzlibrary{calc, intersections}
\usetikzlibrary{arrows.meta}
\usetikzlibrary{positioning}
\usetikzlibrary{backgrounds}

\begin{document}
\begin{tikzpicture}[
    declare function={gammapdf(\x,\alfa,\lambda)=
      (\lambda^\alfa)*(\x^(\alfa-1))*exp(-\lambda*\x)/factorial(\alfa-1);}
      ]
\begin{axis}[
    axis lines=middle,
    axis line style={-Stealth},
    ticks=none,
    samples=300,clip=false,
    enlarge x limits={value=.04,upper},
    enlarge y limits=.12,
    name=gamma
]
\addplot[thick, smooth, domain=-9:9, name path=curva] {gammapdf((x+10),8,1)};
\begin{scope}[on background layer]
\addplot [fill=gray!30, draw=none, domain=3:9] {gammapdf((x+10),8,1)} \closedcycle;
\end{scope}
\draw (3,-.005) node[below] {$q_\alpha$} |- (axis cs: 3, {gammapdf(13,8,1)});
\node (unomenoalfa) at (axis cs:6.5,0.04)  {$1-\alpha$};
\draw[-Stealth] (unomenoalfa) -- (axis cs:4,0.007);
\node (unomenoalfa) at (axis cs:-2.5,0.04)  {$\alpha$};
\end{axis}
\begin{axis}[
    axis lines=middle,
    axis line style={-Stealth},
    ticks=none,
    samples=300,clip=false,
    enlarge x limits={value=.04,upper},
    enlarge y limits=.12,
    at=(gamma.below south west),
    anchor=north west,
]
\addplot[thick, smooth, domain=-9:9, name path=curvastrana] coordinates {
    (-9,0) (-5,1) (.5,.1) (7,.1) (9,0)
    };
\draw (3,-.005) node[below] {$q_\alpha$} -- (3,1);
\begin{scope}[on background layer]
\clip (axis cs: 3, 0) rectangle (axis cs: 9, 3);
\addplot [fill=gray!30, smooth, draw=none]  coordinates {
    (-9,0) (-5,1) (.5,.1) (7,.1) (9,0)
    } \closedcycle;
\end{scope}
\node (unomenoalfa) at (axis cs:6.5,0.4)  {$1-\alpha$};
\draw[-Stealth] (unomenoalfa) -- (axis cs:7,0.03);
\node (unomenoalfa) at (axis cs:-4,0.4)  {$\alpha$};
\end{axis}
\end{tikzpicture}
\end{document}

A: Here's a sample sagetex solution. The standalone environment is used so the 2 pictures are side by side. Note that the value of $q_{\alpha}$ is computed by SAGE and placed into tikzpicture environment.:
\documentclass{standalone}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{pgfplots}
\usepackage{sagetex}
\usetikzlibrary{spy}
\usetikzlibrary{backgrounds}
\usetikzlibrary{decorations}
\pgfplotsset{compat=newest}% use newest version
\begin{document}
\begin{sagesilent}
sigma1 = 1
alpha = .75

zeta = 0
sigma2 = 1
T1 = RealDistribution('gaussian', sigma1)
Q1 = T1.cum_distribution_function_inv(alpha)
T2 = RealDistribution('lognormal', [zeta, sigma2])
Q2 = T2.cum_distribution_function_inv(alpha)

####### SCREEN SETUP #####################
LowerX = -4.0
UpperX = 4.0
LowerY = -.250
UpperY = 1.0
step = .01
Scale = 1.0
xscale=1.0
yscale=1.0
#####################TIKZ PICTURE SET UP ###########
output = r""
output += r"\begin{tikzpicture}"
output += r"[line cap=round,line join=round,x=8.75cm,y=8cm]"
output += r"\begin{axis}["
output += r"grid = none,"
#Change "both" to "none" in above line to remove graph paper
output += r"minor tick num=4,"
output += r"every major grid/.style={Red!30, opacity=1.0},"
output += r"every minor grid/.style={ForestGreen!30, opacity=1.0},"
output += r"height= %f\textwidth,"%(yscale)
output += r"width = %f\textwidth,"%(xscale)
output += r"thick,"
output += r"black,"
output += r"axis lines=center,"
#Comment out above line to have graph in a boxed frame (no axes)
output += r"domain=%f:%f,"%(LowerX,UpperX)
output += r"line join=bevel,"
output += r"xmin=%f,xmax=%f,ymin= %f,ymax=%f,"%(LowerX,UpperX,LowerY, UpperY)
#output += r"xticklabels=\empty,"
#output += r"yticklabels=\empty,"
output += r"major tick length=5pt,"
output += r"minor tick length=0pt,"
output += r"major x tick style={black,very thick},"
output += r"major y tick style={black,very thick},"
output += r"minor x tick style={black,thin},"
output += r"minor y tick style={black,thin},"
#output += r"xtick=\empty,"
#output += r"ytick=\empty"
output += r"]"
##############FUNCTIONS#################################
##GRAPH OF FUNCTION 1
t1 =  var('t1')
x1_coords = srange(LowerX,UpperX,step)
y1_coords = [(T1.distribution_function(t1)).n(digits=6) for t1 in x1_coords]
output += r"\addplot[thin, NavyBlue, unbounded coords=jump] coordinates {"
for i in range(0,len(x1_coords)):
    if (y1_coords[i])<LowerY or (y1_coords[i])>UpperY:
        output += r"(%f,inf) "%(x1_coords[i])
    else:
        output += r"(%f,%f) "%(x1_coords[i],y1_coords[i])
output += r"};"

s=var('s')
for s in srange(Q1,3,step):
    output += r"\draw[color=gray] (axis cs:%f,0)--(axis cs:%f,%f){};"%(s,s,T1.distribution_function(s).n(digits=6))

output += r"\node at (%s,-.1) {$q_\alpha= %s$};"%(Q1.n(digits=3)+.4,Q1.n(digits=3))
output += r"\addlegendentry{$T_1$}"
output += r"\end{axis}"
output += r"\end{tikzpicture}"

##FUNCTION 2 #########################################
output2 = r""
output2 += r"\begin{tikzpicture}"
output2 += r"[line cap=round,line join=round,x=8.75cm,y=8cm]"
output2 += r"\begin{axis}["
output2 += r"grid = none,"
#Change "both" to "none" in above line to remove graph paper
output2 += r"minor tick num=4,"
output2 += r"every major grid/.style={Red!30, opacity=1.0},"
output2 += r"every minor grid/.style={ForestGreen!30, opacity=1.0},"
output2 += r"height= %f\textwidth,"%(yscale)
output2 += r"width = %f\textwidth,"%(xscale)
output2 += r"thick,"
output2 += r"black,"
output2 += r"axis lines=center,"
#Comment out above line to have graph in a boxed frame (no axes)
output2 += r"domain=%f:%f,"%(LowerX,UpperX)
output2 += r"line join=bevel,"
output2 += r"xmin=%f,xmax=%f,ymin= %f,ymax=%f,"%(LowerX,UpperX,LowerY, UpperY)
#output += r"xticklabels=\empty,"
#output += r"yticklabels=\empty,"
output2 += r"major tick length=5pt,"
output2 += r"minor tick length=0pt,"
output2 += r"major x tick style={black,very thick},"
output2 += r"major y tick style={black,very thick},"
output2 += r"minor x tick style={black,thin},"
output2 += r"minor y tick style={black,thin},"
#output += r"xtick=\empty,"
#output += r"ytick=\empty"
output2 += r"]"
t2 =  var('t2')
x2_coords = srange(LowerX,UpperX,step)
y2_coords = [(T2.distribution_function(t2)).n(digits=6) for t2 in x2_coords]
output2 += r"\addplot[thin, Orchid, unbounded coords=jump] coordinates {"
for i in range(0,len(x2_coords)):
    if (y2_coords[i])<LowerY or (y2_coords[i])>UpperY:
        output2 += r"(%f,inf) "%(x2_coords[i])
    else:
        output2 += r"(%f,%f) "%(x2_coords[i],y2_coords[i])
output2 += r"};"
s=var('s')
for s in srange(Q2,4,step):
    output2 += r"\draw[color=gray] (axis cs:%f,0)--(axis cs:%f,%f){};"%(s,s,T2.distribution_function(s).n(digits=6))

output2 += r"\node at (%s,-.1) {$q_\alpha= %s$};"%(Q2.n(digits=3),Q2.n(digits=3))
output2 += r"\addlegendentry{$T_2$}"
output2 += r"\end{axis}"
output2 += r"\end{tikzpicture}"
\end{sagesilent}
\sagestr{output}
\sagestr{output2}
\end{document}

The output running in Cocalc is shown below with alpha at .75:

The documentation for sagetex on CTAN is here. Sage is not part of the LaTeX distribution so it needs to be installed on your machine or open a free Cocalc account (the easiest way). The sample solution is using SAGE built in probability density functions here to do the calculation. Of course, SAGE can handle integration to deal with probability density functions that are not built in.

A: You can deform functions without changing their normalization by convoluting them. Unfortunately pgfplots cannot do integrals, so all I can offer is a poor cat's convolution. I just multiply the function by a linear combination of functions where one has the peaks at the "right" place and then adjust the coefficients in such a way that the integrals fulfill your requirements. The integrals are done by Mathematica. Different functions will lead to different plots. The following also uses the fillbetween library, which allows you to avoid having to plot the functions twice.
\documentclass[11pt, border=3cm]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usepgfplotslibrary{fillbetween}
\usetikzlibrary{calc}
\usetikzlibrary{arrows.meta}
\usetikzlibrary{positioning}
\usetikzlibrary{backgrounds}

\begin{document}
\begin{tikzpicture}[
    declare function={gammapdf(\x,\alfa,\lambda)=
      (\lambda^\alfa)*(\x^(\alfa-1))*exp(-\lambda*\x)/factorial(\alfa-1);
      h(\x)=1.62*pow(sin(\x*18),2)-0.07*\x;}
      ]
\begin{axis}[
    axis lines=middle,
    axis line style={-Stealth},
    ticks=none,
    samples=300,clip=false,
    enlarge x limits={value=.04,upper},
    ymax=0.28,
    %enlarge y limits=.12,
    name=gamma
]
\addplot[thick, smooth, domain=-9:9, name path=curva] {gammapdf((x+10),8,1)};
\path [name path=B] (-10,0) -- (10,0);
\addplot [gray!30] fill between [of=curva and B,
        soft clip={domain=3:9}];
% \begin{scope}[on background layer]
% \addplot [fill=gray!30, draw=none, domain=3:9] {gammapdf((x+10),8,1)} \closedcycle;
% \end{scope}
\draw (3,-.005) node[below] {$q_\alpha$} |- (axis cs: 3, {gammapdf(13,8,1)});
\node (unomenoalfa) at (axis cs:6.5,0.04)  {$1-\alpha$};
\draw[-Stealth] (unomenoalfa) -- (axis cs:4,0.007);
\node (unomenoalfa) at (axis cs:-2.5,0.04)  {$\alpha$};
\end{axis}
\begin{axis}[
    axis lines=middle,
    axis line style={-Stealth},
    ticks=none,
    samples=300,clip=false,
    enlarge x limits={value=.04,upper},
    ymax=0.28,
    %enlarge y limits=.12,
    at=(gamma.below south west),
    anchor=north west,
]
\addplot[thick, smooth, domain=-9:9, name path=curvastrana] {h(x)*gammapdf((x+10),8,1)};
\draw (3,-.005) node[below] {$q_\alpha$} -- (3,{h(3)*gammapdf((3+10),8,1)});
\path [name path=B] (-10,0) -- (10,0);
\addplot [gray!30] fill between [of=curvastrana and B,
        soft clip={domain=3:9}];
\node (unomenoalfa) at (axis cs:6.5,0.04)  {$1-\alpha$};
\draw[-Stealth] (unomenoalfa) -- (axis cs:4,0.007);
\node (unomenoalfa) at (axis cs:-4,0.1)  {$\alpha$};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Laravel: Passing array from routes to views without mapping it to some keys? Is it possible?
I can do:
Route::get('passit',
    function()
    {
        $data['arr'] = array(1,2,3);
        return View::make('aview', $data);
    });

in the view I do:
foreach ($arr as $a){
    echo $a;
}

The array is mapped with the 'arr'.
What I want instead is just to :
 Route::get('passit',
        function()
        {
            $data = array(1,2,3);
            return View::make('aview', $data);
        });

But this doesn't work because $data in :
foreach ($data as $a){
        echo $a;
    }

Is undefined. I also tried :
Route::get('passit',
            function()
            {
                $data = array(1,2,3);
                return View::make('aview')->with($data);
            });

No luck.
PHP 5.6, Laravel 5.1
Note : By the way, I don't bother, not at all just curious if any.

A: In your route define the variable as.
return View::make('aview', compact($data));

A: Try
 Route::get('passit',
        function()
        {
            $data = array(1,2,3);
            return View::make('aview', ['data' => $data]);
        });


text:
Q: Class name & Function name in Java I'm studying Swing in Java at first.
above thing is correct and another thing is incorrect code.
Correct
public class Example extends JFrame{
    public Example() {
    }

Incorrect
public class Example extends JFrame{
    public Othor() {
    }

Despite it's not Constructor, why function name should be same with class name?

A: I am not sure what you mean with "Despite it's not Constructor" - in the first snippet, public Example() is a constructor, means it will be executed when the object is created with new Example(). In the second snippet, public Othor() would be a normal method of the class, even though it is missing the return type, so this does not compile (this is probably the error message you get, something like Return type is missing).
The correct code for the second snipped would be something like
public class Example extends JFrame{
    public void othor() {
    }
}

(note that methods usually start with a non-capital letter). In this case, a default constructor would implicitly be created, but void othor() is a normal method of the class.
Also note that this is just normal Java behaviour, and completely independant of Swing or any other toolkit or framework.
See also Purpose of a constructor in Java?


text:
Q: How to convert multiple dimension list into one dimension list If I have this JSON data that is from the original file.
[{"food": {"spicy": "spicy","sweet": "sweet"},
  "water": {"sweet": "sweet","sour": {"cold": "ice lemon","hot": "lemon tea"}}
}, {"food": {"spicy": "spicy","sweet": "sweet"},
  "water": {"sweet": "sweet","sour": {"cold": "ice lemon","hot": "lemon tea"}}
}]

how do I convert into a one-dimensional list like this?
[{
    "food-spicy": "spicy",
    "food-sweet ": "sweet",
    "water-sweet ": "sweet",
    "water-sour-cold ": "ice lemon",
    "water-sour-hot ": "lemon tea"
}, {
    "food-spicy": "spicy",
    "food-sweet ": "sweet",
    "water-sweet ": "sweet",
    "water-sour-cold ": "ice lemon",
    "water-sour-hot ": "lemon tea"
}]

Please help.

A: You could write a function that flatten an object recursively. Then map the array using that function:
function flatten(oldObj) {
    return Object.keys(oldObj).reduce(function(newObj, oldKey) {   // for each key "oldKey" in oldObj
        var value = oldObj[oldKey];                                // get the value of the current oldKey from oldObj
        if(value && typeof(value) === "object") {                  // if the value is also an object (add "&& !Array.isArray(value)" to exclude arrays)
            value = flatten(value);                                // then flatten it first
            Object.keys(value).forEach(function(key) {             // and for each key in the new flattened value object
                newObj[oldKey + "-" + key] = value[key];           // add a key-value to newObj where key is "oldKey-key" and the value is value[key]
            });
        } else {
            newObj[oldKey] = value;                                // otherwise (if the value is not an object), just copy the key-value to newObj as it is
        }
        return newObj;
    }, {});
}

Then use it like this:
var newArray = oldArray.map(flatten);

Example:

function flatten(oldObj) {
    return Object.keys(oldObj).reduce(function(newObj, oldKey) {
        var value = oldObj[oldKey];
        if(value && typeof(value) === "object") {
            value = flatten(value);
            Object.keys(value).forEach(function(key) {
                newObj[oldKey + "-" + key] = value[key];
            });
        } else {
            newObj[oldKey] = value;
        }
        return newObj;
    }, {});
}

var oldArray = [{"food":{"spicy":"spicy","sweet":"sweet"},"water":{"sweet":"sweet","sour":{"cold":"ice lemon","hot":"lemon tea"}}},{"food":{"spicy":"spicy","sweet":"sweet"},"water":{"sweet":"sweet","sour":{"cold":"ice lemon","hot":"lemon tea"}}}];

var newArray = oldArray.map(flatten);

console.log(newArray);

A: try this:

var data = [{
    food: {
      spicy: 'spicy',
      sweet: 'sweet'
    },
    water: {
      sweet: 'sweet',
      sour: {
        cold: 'ice lemon',
        hot: 'lemon tea'
      }
    }
  },
  {
    food: {
      spicy: 'spicy',
      sweet: 'sweet'
    },
    water: {
      sweet: 'sweet',
      sour: {
        cold: 'ice lemon',
        hot: 'lemon tea'
      }
    }
  }
]

var res = data.map(obj => {
  return Reflect.ownKeys(obj).reduce((re, key) => {
    Reflect.ownKeys(obj[key]).reduce((r, k) => {
      if (typeof obj[key][k] === 'object') {
        Reflect.ownKeys(obj[key][k]).reduce((r2, k2) => {
          r2[key + '-' + k + '-' + k2] = obj[key][k][k2]
          return r2
        }, r)
      } else {
        r[key + '-' + k] = obj[key][k]
        return r
      }
    }, re)
    return re
  }, {})
})
console.log(res)

And here is a more universal version which applicable for more nested obj

var data = [{
    food: {
      spicy: 'spicy',
      sweet: 'sweet'
    },
    water: {
      sweet: 'sweet',
      sour: {
        cold: 'ice lemon',
        hot: 'lemon tea'
      }
    }
  },
  {
    food: {
      spicy: 'spicy',
      sweet: 'sweet'
    },
    water: {
      sweet: 'sweet',
      sour: {
        cold: 'ice lemon',
        hot: 'lemon tea'
      }
    }
  }
]

function customReduce(obj, subObj, lastReduceObj = {}, lastKey = '') {
  let res = Reflect.ownKeys(subObj).reduce((re, key) => {
    if (lastKey === '') {
      customReduce(obj, obj[key], re, key)
    } else if (typeof subObj[key] === 'object') {
      customReduce(obj, subObj[key], re, lastKey + '-' + key)
    } else {
      re[lastKey + '-' + key] = subObj[key]
    }
    return re
  }, lastReduceObj)
  return res
}

var res = data.map(obj => {
  return customReduce(obj, obj)
})

console.log(res)

A: Try this :

var jsonObj = [{
 "food": {
  "spicy": "spicy",
  "sweet": "sweet"
 },
 "water": {
  "sweet": "sweet",
  "sour": {
   "cold": "ice lemon",
   "hot": "lemon tea"
  }
 }
}, {
 "food": {
  "spicy": "spicy",
  "sweet": "sweet"
 },
 "water": {
  "sweet": "sweet",
  "sour": {
   "cold": "ice lemon",
   "hot": "lemon tea"
  }
 }
}];

var newObj = {};

for (var i in jsonObj) {
  for (var j in Object.keys(jsonObj[i])) {
    for (var k in Object.keys(jsonObj[i])[j]) {
    newObj[Object.keys(jsonObj[i])[j]+'-'+Object.keys(jsonObj[i][Object.keys(jsonObj[i])[j]])[k]] = jsonObj[i][Object.keys(jsonObj[i])[j]][Object.keys(jsonObj[i][Object.keys(jsonObj[i])[j]])[k]];
    }
  }
}

console.log([flatJSON(newObj)]);

function flatJSON(obj) {
  if(typeof obj != 'object') {
    return;
  }
  for (var l in Object.keys(obj)) {
    if (typeof obj[Object.keys(obj)[l]] == 'object') {
      for (var m in Object.keys(obj[Object.keys(obj)[l]])) {
        newObj[Object.keys(obj)[l]+'-'+Object.keys(obj[Object.keys(obj)[l]])[m]] = obj[Object.keys(obj)[l]][Object.keys(obj[Object.keys(obj)[l]])[m]];
      }
    }
    if (typeof obj[Object.keys(obj)[l]] == 'object') {
      delete obj[Object.keys(obj)[l]];
    }
    if (obj[Object.keys(obj)[l]] === undefined) {
      delete obj[Object.keys(obj)[l]];
    }
  }
  return newObj;
}


text:
Q: Securely redirect to page not in intranet? In an application we are writing we need to have a page that is essentially public but should only be available to certain people.. yep i know very paradoxical!
Its basically a "Submit a support ticket" style page that is hosted outside of a customers intranet but should only be available to users on that intranet.
Naturally making the user sign up for an account is the usual course of action but in this case it isn't really an option..
Is there any way of doing a "secure redirect" to that page?
My initial though would be to use an internal page which redirects appending a unique one time hash to the url which expires and then although its not 100% airtight it is only valid for about 1 min..

A: "Secure Redirect" is meaningless. What you want to do is make sure your ticket submit system will only accept clients connecting from your users' network. This would be a web site configuration thing.

A: Two ways come to mind.
1) Deploy IP restrictions on the web server for the off-network resource. If the request is coming from one of the exit points from your network (proxy server, other public-facing egress points, etc) then allow the connection, otherwise do not.
2) Deploy mutually authenticated SSL on both the web server and a reverse-proxy server on your internal network. Clients connect to the internal reverse-proxy and that proxies them back to the external resource over an SSL connection that is mutually authenticated (so the external web server will only connect over SSL and it will only connect to a client (the reverse-proxy in this case) that has a recognized/accepted client certificate).


text:
Q: Is there a programming language with built-in state machine construct? I am just curious if there is a programming language which has state machines (similar to boost::statechart) as primary language construct.
Analogies - c# has delegates  where java uses the observer pattern and C has callbacks. Perl and python have built-in hashes while C++ and java needs a library.
Update:
This should be general programming language in the sense of C++, C#, Java, Lisp ...
I mean "mature" state machines with all bells and whistles on the level of Harel formalism or UML state diagrams or boost::statechart.

A: Ragel is a state machine language. IOW, it's not a language that also supports state machines, it's a language that only supports state machines. Which obviously means that it's not Turing-complete, but who needs that?
More precisely, Ragel is a state machine compiler, which takes a description of a state machine in a regexp-like language and generates an implementation of that state machine in C, C++, Objective-C, D, Java or Ruby. (Think yacc but for state machines instead of LALR(1) table parsers.) The primary purpose of Ragel is parsing binary protocols (such as networking protocols or also on-disk file formats), but it can just as well be used for text.
One famous example of using Ragel is the Mongrel webserver for Ruby: its HTTP kernel is written in Ragel, which makes it extremely fast and secure. The HTTP kernel is so good in fact, that it has been reused a number of times in different applications: Thin, Unicorn and Rainbows are also webservers, and in fact direct competitors to Mongrel. Ebb is a reverse HTTP proxy. RFuzz is a fuzz testing tool for web applications. Also, some security tools use it.
Ragel also allows embedding code in the host language into the state machine, thus making it Turing-complete, and able to not only recognize but also interpret protocols.
In general, every language with support for advanced user-defined control-flow via either coroutines (e.g. Lua) or continuations (e.g. Scala) or GOTO (e.g. PHP) or proper tail calls (e.g. Scheme) can be used to easily implement state machines. (Generators (Python) aka iterators (C#), which are basically "crappy coroutines" might or might not work, depending on your definition of "work".) And any language which has flexible syntax (e.g. Ruby) or supports metasyntactic abstraction (e.g. Clojure) can be used to describe state machines. (Support for non-ASCII identifiers helps, too, so that you can use actual arrows for your state machine.)
Which means that if you combine the two, and use a language that supports both tail calls and metasyntactic abstraction, you get very nice state machines, without requiring native language support. Shriram Krishnamurthi gave a now (in)famous talk titled "The Swine before Perl" at the inaugural Lightweight Languages Conference, in which he demonstrated an FSM implementation in Scheme. (Here are the slides, an audio recording and a paper explaining the code). The code itself is a 26 line (very short lines, actually) macro, that allows you to write code like this:
(define my-regex
  (automaton init
             [init : (c → more)]
             [more : (a → more)
                     (d → more)
                     (r → end)]
             [end : accept]))

This is a specification of the state machine corresponding to the regular expression c(a|d)*r. And it is not only a specification, but also a runnable program implementing that state machine.
I can call it like this:
(my-regex '(c a d a d d r))

And in this case get the result #t (which is Scheme-speak for true).

A: The Plaid Programming Language introduce "Typestate-Oriented Programming, a paradigm that extends object-oriented programming with typestates."
Here is the doc: http://www.cs.cmu.edu/~aldrich/plaid/
E.g:
state File {
    public final String filename;
}

state OpenFile extends File {
    private CFilePtr filePtr;
    public int read() { ... }
    public void close() [OpenFile>>ClosedFile]
        { ... }
}

state ClosedFile extends File {
    public void open() [ClosedFile>>OpenFile]
        { ... }
}

A: SMC is a compiler for a simple domain specific language that will generate state machines for many popular languages.  I have used it to generate maintainable state machines for a wide variety of things such as complex user interfaces and custom network protocols.

A: I have just found one: AsmL (Abstract State Machine Language).
Here is the page with more info on it at CodePlex.
Interesting enough, it is developed by Microsoft.

A: Erlang's OTP supports state machine constructs via 'gen_fsm'.  It's been a couple of years since I last looked at it, so I'm a bit rusty, but you can Google for 'Erlang gen_fsm' and find loads of reference material

A: Microsoft Research recently released the P language on GitHub.  They also have the PSharp framework which provides a C# extension library and a high-level syntax with compiler for the language.
I am looking forward to trying it out.
Here is a portion from one of their examples for the C# extensions:
internal class Server : Machine
{
    MachineId Client;

    [Start]
    [OnEntry(nameof(InitOnEntry))]
    class Init : MachineState { }

    void InitOnEntry()
    {
        ...
        this.Goto(typeof(Active));
    }

    ...

Here is a portion of their high-level syntax:
using System;

namespace TheStateMachine
{
  internal machine Client
  {
    private machine Server;
    private start state Init
    {
      entry
      {
        this.Server = (trigger as Config).target;
        jump(Playing);
      }
    }

    private state Playing
    {
      entry
      {
        //execute logic
      }
      on AnotherEvent goto AnotherState;
      on SomeEvent do ProcessSomeLogic;
    }

  ...

A: Not quite, but there is a state machine module for Python that lets you use decorators to support implementing Harel style statecharts, including contexts with multiple states, nesting substates with and without history. The code winds up looking something like below.
Module is at http://wiki.python.org/moin/State%20Machine%20via%20Decorators
 #!/bin/env/python
"""
This example now works. The state pattern module
allows defining states which are their their own context for
implementing substates.  Substate Medium (class Medium) shows this here.
"""
"""
Example with 5 buttons. Two ,'up','down' cause state to rotate among the
several states.  The other three, bx,by,bz, invoke state dependent behavior.

Switching into a state causes the labels of the three buttons bx,by,bz to
change.  Pressing one of the buttons causes associated text to appear in
corresponding static text box. An 'onEnter' method changes the text.
"""
import wx
import DecoratorStateMachine as dsm

class MyFrame(wx.Frame, dsm.ContextBase):

   xtable = dsm.TransitionTable('pstate')

   def __init__(self):
      MyFrame.xtable.initialize(self)

      wx.Frame.__init__(self, None, -1, "My Frame", size=(470,220))

      family = wx.SWISS
      style = wx.NORMAL
      weight = wx.BOLD
      font = wx.Font(11,family,style,weight, False, "Verdana")
      self.SetFont(font)

      panel = wx.Panel(self, -1)

      b = wx.Button(panel, -1, "Up", pos=(50,20), size=(80,35))
      self.Bind(wx.EVT_BUTTON, self.OnUp, b)
      b.SetDefault()

      b = wx.Button(panel, -1, "Down", pos=(50,60), size=(80,35))
      self.Bind(wx.EVT_BUTTON, self.OnDown, b)

      self.bx = wx.Button(panel, -1, "xxx", pos=(50,100), size=(110,35))
      self.Bind(wx.EVT_BUTTON, self.OnBA, self.bx)
      self.tx = wx.StaticText(panel, -1, "", pos=(50,140), size=(110,35))

      self.by = wx.Button(panel, -1, "yyy", pos=(180,100), size=(110,35))
      self.Bind(wx.EVT_BUTTON, self.OnBB, self.by)
      self.ty = wx.StaticText(panel, -1, "", pos=(180,140), size=(110,35))

      self.bz = wx.Button(panel, -1, "zzz", pos=(310,100), size=(110,35))
      self.Bind(wx.EVT_BUTTON, self.OnBC, self.bz )
      self.tz = wx.StaticText(panel, -1, "", pos=(310,140), size=(110,35))

   @dsm.transition(xtable)
   def OnUp(self, event):
      pass

   @dsm.transition(xtable)
   def OnDown(self, event):
      pass

   @dsm.event(xtable)
   def OnBA(self, event):
      pass

   @dsm.event(xtable)
   def OnBB(self, event):
      pass

   @dsm.event(xtable)
   def OnBC(self, event):
      self.tz.SetLabel("Bossy")

class Off(MyFrame):
   "This is state Off "

   def onEnter(self):
      self.bx.SetLabel("Chase")
      self.by.SetLabel("Onry")
      self.bz.SetLabel("Cow")

   def OnBA(self, event):
      self.tx.SetLabel("Chase the")

   def OnBB(self, event):
      self.ty.SetLabel("Onry")

class Low(MyFrame):
   "This is state Low "
   items = ["Walk", "Green", "Llama"]

    def onEnter(self):
      self.bx.SetLabel(self.items[0])
      self.by.SetLabel(self.items[1])
      self.bz.SetLabel(self.items[2])

   def OnBA(self, event):
      self.tx.SetLabel("Walk the ")

   def OnBB(self, event):
      self.ty.SetLabel(self.items[1])

   def OnBC(self, event):
      self.tz.SetLabel(self.items[2])

class Medium(MyFrame):
   "This is state Medium "
   ytable = dsm.TransitionTable('qstate')

   def onEnter(self):
      if not hasattr(self, 'qstate'):    #unconditionally initialize for no history
         self.ytable.initialize(self)
      self.doEnter()

   @dsm.event(ytable)
   def doEnter(): pass

   @dsm.transitionevent(ytable)
   def OnBA(self, event):
      pass

   @dsm.transitionevent(ytable)
   def OnBB(self, event):
      pass

   @dsm.transitionevent(ytable)
   def OnBC(self, event):
      pass

class High(Low):
   "This is state High "

   items = ["Pet","Tame", "Dog"]

   def OnBA(self, event):
      self.tx.SetLabel("Pet his")

class MedBlue(Medium):
   """State med blu"""

   items = ["Med BLue","Checkered", "Tractor"]

   def onEnter(self):
      self.bx.SetLabel(self.items[0])
      self.by.SetLabel(self.items[1])
      self.bz.SetLabel(self.items[2])

   def doEnter(self):
      self.onEnter()

   def OnBA(self, event):
      self.tx.SetLabel("Med Blue")
   def OnBB(self, event):
      self.ty.SetLabel("Chekered")
   def OnBC(self, event):
      self.tz.SetLabel("Tractor")

class MedRed(Medium):
   """State med red"""

   items = ["Med Red","Striped", "Combine"]

   def onEnter(self):
      self.bx.SetLabel(self.items[0])
      self.by.SetLabel(self.items[1])
      self.bz.SetLabel(self.items[2])

   def doEnter(self):
      self.onEnter()

   def OnBA(self, event):
      self.tx.SetLabel("Med Red")
   def OnBB(self, event):
      self.ty.SetLabel("Striped")
   def OnBC(self, event):
      self.tz.SetLabel("Combine")

MyFrame.xtable.nextStates(Low, (Medium,Off))
MyFrame.xtable.nextStates(Medium, (High,Low))
MyFrame.xtable.nextStates(High, (Off,Medium))
MyFrame.xtable.nextStates(Off, (Low,High))
MyFrame.xtable.initialstate = Off

Medium.ytable.nextStates(MedBlue, (MedBlue, MedRed, MedRed))
Medium.ytable.nextStates(MedRed,  (MedBlue, MedBlue, MedRed))
Medium.ytable.initialstate = MedBlue

if __name__=='__main__':
   app = wx.PySimpleApp()
   frame = MyFrame()
   frame.Show(True)
   app.MainLoop()

A: There's a new W3C XML-based state machine language called SCXML, based on David Harel's StateChart formalism (which supports hierarchical and parallel state machines).
Apache Commons has a Java based implementation of SCXML:

Commons SCXML is an implementation aimed at creating and maintaining a Java SCXML engine capable of executing a state machine defined using a SCXML document, while abstracting out the environment interfaces.

A: In C#, iterators (with 'yield return' and 'yield break') are a language construct that directly translates to state machines. I haven't actually ever used it as such, but I actually think it could be usable in practice.
There happens to be a stackoverflow question about it here. The highest voted answer discourages it though ...

A: Apart from Ragel there is a technically interesting,but quite obscure language called SL1.
See http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=1095580. It was created by Iskratel in Slovenia in order to develop telecom systems where state machines are the basic blocks.

A: Shriram Krishnamurthi has a talk and a paper about using macros to add an embedded sublanguage for automata to Scheme. I'm not sure if any Schemes include his macros as a standard library, though.

A: I'm almost a decade late to the party but I recently stumbled upon an obscure language which borrows ideas from FSMs called Hume
I'm not sure if it's still actively maintained, but you can at least download the compiler and play around with it. Information is hard to come by, but there's a few papers and articles online that show the essentials.

A: This work has evolved further into something very nice, see https://microsoft.github.io/coyote.

A: In Sep 2015 the xstate project was launched. It implements SCXML and aims to provide JavaScript and TypeScript finite state machines and statecharts for the modern web. link to the documentation

A: In C++, there is also the Macho (very small) framework created in 2005 by Eduard Hiti.
Macho stands for "C++ Machine Objects".
Available here : https://github.com/yattom/macho
Very small, does the job for HSM, without requiring boost.


text:
Q: Android - How can i show more than one line in a TextView and also show it from bottom to top im trying to do an application to send messages between 2 people, so i need to show a lot of text in the TextView. The problem is that i dont know how to show a lot of text from different people in a textview, also how can i make so the text can go from bottom to top instead of from top to bottom?

A: First get the current text From the text view like
String current = tv.getText().toString();

Second Append the new line to the current string lik
current+="\n Alice: Hello , Jim";

Third,Set it to the textView
tv.setText(current);

A: *

*singleLine = false

*gravity= bottom

Set it to the textview , you try
other way , append "\n"  in you textstring


text:
Q: Unable to animate both geom_line and geom_point with gganimate I'm doing an animated graph with ggplot2 and gganimate where geom_line and geom_point represent the same numeric data. It is a scatterplot in which I want the point data appear with animated transition, as well as displaying an underlying line connecting the data points which is also animated.
Currently, 'geom_line' is correctly animated by  transition_reveal(Año), but from there, I don't know how to animate geom_line.
I've tried adding transition_states (which I've used previously to successfully animate a geom_point element before), but I don't understand how to add two different types of transition to two different geoms on the same graph. Every time I try, I get errors. Elements such as enter_growdon't seem to do anything.
Here is the data:
Año = c(1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008)
Nacimientos= c(4571,4782,4834,4701,4787,4467,4571,4583,4776,4761,5017,5287)
Defunciones= c(889,946,946,916,991,1026,1040,1127,1092,1070,1156,1199)
TasaNatalidad= c(20.8, 21.0, 20.4, 19.1, 19.0, 17.2, 17.2, 16.8, 17.1, 16.6, 17.1, 17.6)
TasaMortalidad= c(4.0, 4.1, 4.0, 3.7, 3.9, 3.9, 3.9, 4.1, 3.9, 3.7, 3.9, 4.0)
TasaFecundidad= c(2.61, 2.63, 2.58, 2.43, 2.42, 2.21, 2.22, 2.18, 2.23, 2.17, 2.23, 2.29)

Tarapaca <- data.frame(Año,Nacimientos,Defunciones,TasaFecundidad,TasaMortalidad,TasaNatalidad)

This is the code that renders an animated graph with moving lines, but the circles just "appear" without animation:
library(ggplot2)
library(gganimate)

n0 <- ggplot(Tarapaca, aes(x = Año, y = Nacimientos)) +
            geom_line(color ="#BA3C11", alpha=0.6) +
                  transition_reveal(Año) +
            geom_point(aes(group = seq_along(Año),
                           size = TasaNatalidad,
                           alpha=TasaFecundidad),
                           color ="#DD4814") +
                  enter_grow() +
                  enter_fade() +
                  scale_size(range = c(4, 10)) +
                  scale_alpha(range = c(0.2, 1)) +
            ease_aes('cubic-in-out') +
            labs(x = "Años", y = "Nacimientos") +
            theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
            scale_x_continuous("Año", labels = as.character(Año), breaks = Año) +
            labs(size="Tasa de natalidad", alpha ="Tasa de fecundidad") +
            theme(panel.grid.major = element_line(Año, color = "white"),
                panel.grid.minor = element_blank(), # borrar líneas menores
                panel.background = element_rect(fill = "#F2E9E6"),
                legend.key = element_rect(fill = "#F2E9E6"))

n0

[Resulting animation of first code chunk]
Running the previous code gives an graph that only animated lines, but I want to achieve both animated lines and points, and everything I've tried gives errors or doesn't work.
On the other hand, the following code renders an animated graph with animated circles or points, but I can't add lines to it, because as soon as I add a second geom it just returns errors:
NF <- ggplot(Tarapaca, aes(x = Año, y = Nacimientos)) +
      geom_point(aes(size = TasaNatalidad, alpha=TasaFecundidad), color ="#DD4814") +
      transition_states(Año, transition_length = 2, state_length = 1, wrap=FALSE) +
      shadow_mark() +
      ease_aes('cubic-in-out') +
        ggtitle('Año {closest_state}') +
        scale_size(range = c(4, 10)) +
        scale_alpha(range = c(0.2, 1)) +
        theme(axis.text.x = element_text(angle = 45, vjust = 0.5)) +
        scale_x_continuous("Año", labels = as.character(Año), breaks = Año) +
        labs(size="Tasa de natalidad", alpha ="Tasa de fecundidad") +
        theme(panel.grid.major = element_line(Año, color = "white"),
              panel.grid.minor = element_blank(),
              panel.background = element_rect(fill = "#F2E9E6"),
              legend.key = element_rect(fill = "#F2E9E6"))

NF

Resulting animation of second code chunk
It seems that geom_point requires transition_states and geom_line requires transition_reveal, but transition_states and transition_reveal are not compatible with each other.
How can I get both animations together (i.e., moving lines and animated circles) in a single graph?


text:
Q: DrawerLayout must be measured with MeasureSpec.EXACTLY, I tried the other solutions but not worked I have a problem with adding a drawer navigation with the bottom navigation, the bottom navigation requires the coordinatorLayout and the drawer navigation requires the drawerLayout, so I tried to nest the CoordinatorLayout inside the DrawerLayout but I'm getting the error java.lang.IllegalArgumentException: DrawerLayout must be measured with MeasureSpec.EXACTLY. !!
Could someone help in this because I tried many solutions provided on the internet that doesn't work with me!
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusableInTouchMode="true">

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <!-- -->
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <include layout="@layout/activity_navigation_drawer"/>
    </android.support.design.widget.AppBarLayout>

    <ScrollView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/activity_vertical_margin"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginRight="@dimen/activity_horizontal_margin"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:text="@string/title_break_news" />

    </ScrollView>

    <android.support.design.widget.BottomNavigationView
        android:layoutDirection="rtl"
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemIconTint="@drawable/selector"
        app:itemTextColor="@drawable/selector"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/navigation" />

</android.support.design.widget.CoordinatorLayout>

<android.support.design.widget.NavigationView

    android:id="@+id/drawerNav"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_navigation_drawer"
    app:menu="@menu/activity_navigation_drawer_drawer"/>


text:
Q: Passing a map location variable to other view in SwiftUI I was able to get the location using CLLocationManager() and the city information is able to display in the Text(config.text). Can someone help how to pass that "config.text" to other view (mainView())
struct CityLocationView2 : View {
let location: Location
@State var config = CityLocationView2Config()

var body: some View {

 Text(config.text)

    mainView().   // How to pass the city ?????
        .task(id: location.id) {
            await config.reverseGecode(location: location)
        }
}

}
Thanks,

A: try this:
struct CityLocationView2 : View {
    let location: Location
    @State var config = CityLocationView2Config()

    var body: some View {
        Text(config.text)
        MainView(text: config.text)   // <-- here
            .task(id: location.id) {
                await config.reverseGecode(location: location)
            }
    }
}

struct MainView: View {
    @State var text: String  // <-- here

    var body: some View {
        Text(text)
    }
}

You can of course also use let text: String or var text: String, etc...
I recommend you read and do the tutorial at: https://developer.apple.com/tutorials/swiftui/
Knowing how to pass values to other Views is essential to use SwiftUI.


text:
Q: Typescript does not seem to work, no errors in code but component does not display I have done a small test angular2 application with typescript. I do not have any errors but my generated js file is not loading. Here is my code;
in default.aspx page I have my selector:
 <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
 <app-main>Loading...</app-main>
 </asp:Content>

boot.ts
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './app.component'
bootstrap(AppComponent)

app.component.ts
import {Welcome} from './app.module'
import {Component} from 'angular2/core'
@Component({
selector: 'app-main',
template: `<h1>${Welcome.GetWelcome()}</h1>`
}) export class AppComponent { }

app.module.ts
export class Welcome {
static GetWelcome(): string {
    return "Hello World";
}
}

tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"watch":  true,
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "ES5",
"module": "system",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true
 },
 "exclude": [
 "./node_modules",
 "./typings/main",
 "./typings/main.d.ts"
 ]
 }

The code is compiling but the Welcome message is not loading in the app-main. What am I doing wrong here? I am working with Visual Studio 2015, Version 14.0

A: I've made a plunkr for you http://plnkr.co/edit/oMOvCgFzqtnYYPcE2U6j?p=preview
As @toskv suggested binding a string does not work like that. You define the string as a field in your component. And use it with double {{msg}} tags in your template. Here's the short version:
@Component({
selector: 'app-main',
template: `<h1>{{msg}}</h1>`
})
export class AppComponent {
  msg = Welcome.GetWelcome();
}