text:
Q: wp_dropdown_categories custom taxonomy view all I've got a custom post type called 'projects'.
Attached to this is a custom taxonomy called 'type'.
On both the 'projects' and 'type' archive pages, I have a dropdown to filter the loop results by taxonomy term (type).
These work fine, except the 'view all' option at the top, which when clicked does not submit the form, so does nothing.
Any ideas?
Code in archive-projects.php & taxonomy-type.php…
                    <?php $args = array(
                        'show_option_all'    => 'All',
                        'hide_empty'         => 0,
                        'class'              => 'selectpicker',
                        'taxonomy'           => 'type',
                        'hide_if_empty'      => false,
                        'value_field'        => 'slug',
                    ); ?>

                    <?php wp_dropdown_categories( $args ); ?>
                    <script type="text/javascript">
                        var dropdown = document.getElementById("cat");
                        function onCatChange() {
                            if ( dropdown.options[dropdown.selectedIndex].value != -1 ) {
                                location.href = "<?php echo esc_url( home_url( '/projects/' ) ); ?>/"+dropdown.options[dropdown.selectedIndex].value;
                            }
                        }
                        dropdown.onchange = onCatChange;
                    </script>

functions.php…
  $projectLabels = array(
      'name' => _x('Projects', 'post type general name'),
      'singular_name' => _x('All Projects', 'post type singular name'),
      'all_items' => 'All Projects',
      'add_new' => _x('Add New', 'Project'),
      'add_new_item' => __("Add New Project"),
      'edit_item' => __("Edit Project"),
      'new_item' => __("New Project"),
      'view_item' => __("View Project"),
      'search_items' => __("Search Projects"),
      'not_found' =>  __('No Project(s) found'),
      'not_found_in_trash' => __('No Project(s) found in Trash'),
      'parent_item_colon' => ''
    );
    $projectArgs = array(
      'labels' => $projectLabels,
      'public' => true,
      'publicly_queryable' => true,
      'show_ui' => true,
      'query_var' => true,
      'rewrite' => array( 'slug' => 'projects', 'with_front' => false ),
      'capability_type' => 'post',
      'hierarchical' => true,
      'menu_position' => null,
      'supports' => array('title','editor','revisions','thumbnail','custom-fields'),
      'menu_icon' => 'dashicons-building',
      'has_archive' => true
    );
    register_post_type('projects',$projectArgs);

    // taxonomy
    add_action( 'init', 'create_project_tax' );

    function create_project_tax() {
        register_taxonomy(
            'type',
            'projects',
            array(
                'label' => __( 'Types' ),
                'rewrite' => array( 'slug' => 'projects' ),
                'hierarchical' => true,
            )
        );
    }


text:
Q: Bayes Theorem, intuitive analysis $P(A | B)=P(A \cap B)/P(B)$
Observation one: By dividing by the total outcomes of B we are assuming that events in $P(A \cap B)$ are equally-likely
Observation two: The commonly, sighted initutation for conditional probability is 'Assume B already happened and calculate probability of A'. To me this bit 'flimsy'.  I like to think about conditional probabiity as follows: "Constrain the possiblties in A by removing outcomes that are impossible due to the constraint/filter/condition B"
$P(A \cap B) = P(B \cap A)$
$P(B \cap A) = P(B | A) P(A)$
$P(A | B) = P(B | A)P(A)/P(B)$
$P(B | A) = P(B)P(A | B)/P(A)$
Observation three: since in my defination of conditional probability I am assuming equally likely events, doesn't that also mean that Bayes rule assumes equally likely events? What happens when this is not so?
My question is: are my observations correct and if not, why?

A: Your second set of observations is correct.  However, observations one and three exhibit a slight misconception.  You don't need to look at $P(A)$ and $P(B)$ as consisting of sums of probabilities of equally likely "events."
For example, let $X$ and $Y$ be iid standard normal variates on $(0,1)$.  Then if $A$ is "$X > 0.5$", $A$ is in no obvious way to view $A$ as the sum of equally likely "events."
Nor is $B$ defined as "$X-Y <1.0$.  Yet Bayes theorem still holds:
$$P(A|B) = P(A\wedge B)/P(B)$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is my free diagram of a spring stretched on one end and attached to the wall on the other end correct? Consider the following figures.

*

*The top one shows the construction of a spring where its left end is attached to the wall and its right end is stretched by a force.

*The bottom one is supposed to be the free diagram of the spring. Is it correct?

A: You have to understand the fact that the point on the wall where the spring is fixed is at rest. Hence, the so called free diagram applies there with the other force as the normal from the wall. Whereas, when you pull the rest of the spring, along with the normal you would have a force linearly proportional to the length that has been stretched.

A: consider a very little length of the string. (dl ) 2 forces act on it. they have the same magnitude and the opposite position. (consider that otherwise the part would be accelerating.) so, if we draw a diagram for every little part and then want to summarize the diagram by considering the hole string one body, then your diagram is completely right.it is helpful noting that the diagram shows the forces applied "on" the sting not "by" the string.


text:
Q: Vue2 router do not work when type manually I have such code:
created: function() {
    if(!localStorage.hasOwnProperty('auth_token')) {
        router.replace({name: 'login'});
    } else {
         if(router.history.current.name == 'login') {
             router.push({name: 'allVideos'});
         }
    }
}

inside my Vue root instance .
So when page is loading it checks the token. When I do not have a token I'm redirecting to login page. If I have a token redirect to allVideos if on login page, or do not redirect at all if on other pages.
All is work fine when I made refresh, go through some buttons etc. But when I manually type /#/login and press enter Vue render login page but auth_token exist. And when I type manually it do not get to created method at all. When I type again /#/login from login page again it start working.... Any ideas ??? Thanks
Update: Well I'm tried to use navigation guards
router.beforeEach((to, from, next) => {
    if(localStorage.hasOwnProperty('auth_token')) {
        if(to.name == 'login') {
            next({name: 'allVideos'});
        }
    } else {
        if(to.name != 'login') {
            next({path: '/login'});
        }
    }
        next();

});

Code now much cleaner as for me, but issue is still there when I'm typing manually

A: In your code, next() is called 2 times so it creates the problem. You can try this code:
router.beforeEach((to, from, next) => {
  if(localStorage.hasOwnProperty('auth_token')) {
    if(to.name === 'login') {
      next({name: 'allVideos'});
    }
  } else if(to.name !== 'login') {
    next({path: '/login'})
  } else {
    next();
  }
});


text:
Q: How to count same names in a Data Structure? I need to count the same names of students in Binary Search Tree and Singly linked list. But i couldn't find how to do that. Does someone have answer for it?
public class Student  {

   private int ID;
   private String name;
   private String surname;

   public Student(int id, String n, String s)
   {
      ID = id;
      name = n;
      surname = s;
   }

   public int getID()
   {
      return ID;
   }

   public String getName()
   {
      return name;
   }

   public String getSurname()
   {
      return surname;
   }

   public void setID(int newID)
   {
      ID = newID;
   }

   public void setName(String newName)
   {
      name = newName;
   }

   public void setSurname(String newSurname)
   {
      surname = newSurname;
   }

   public String ToString()
   {
      return "\nname : "+name+"\nsurname : "+surname+"\nid : "+ID+"\n";
   }
}

Student class above
public class NodeBST
{
   private Student s;
   private NodeBST left;
   private NodeBST right;
   private int index ;

   public NodeBST(Student newS)
   {
      s = newS;
      left = null;
      right = null;
      index = 0 ;
   }

   public int getIndex(){
      return index ;
   }

   public Student getStudent()
   {
      return s;
   }

   public NodeBST getLeft()
   {
      return left;
   }

   public NodeBST getRight()
   {
      return right;
   }

   public void setIndex(int idx){
      index = idx ;
   }

   public void setStudent(Student newS)
   {
      s = newS;
   }

   public void setLeft(NodeBST newLeft)
   {
      left = newLeft;
   }

   public void setRight(NodeBST newRight)
   {
      right = newRight;
   }

   public boolean hasLeft()
   {
       return (left != null);
   }

   public boolean hasRight()
   {
       return (right != null);
   }
}

node class for binary search tree above
import java.util.*;
public class BST
{
   private NodeBST root;
   int size ;
   String[] names ;

   public BST()
   {
      names = new String[50];
      root = null;
      size = 0 ;
   }

   public BST(NodeBST newNodeBST)
   {
      root = newNodeBST;
   }

   public boolean isEmpty()
   {
      return (root == null);
   }

   public void insert(NodeBST newNodeBST)
   {
      if(isEmpty())
      { // root is null
         root = newNodeBST;
         root.setIndex(size);
         names[size] = root.getStudent().getName() ;
         size++;
      }
      else
      {
         NodeBST tempNodeBST = root;
         while(true)
         {
            if(newNodeBST.getStudent().getID() < tempNodeBST.getStudent().getID())
            {
               if(tempNodeBST.getLeft() == null)
               {
                  tempNodeBST.setLeft(newNodeBST);
                  tempNodeBST.getLeft().setIndex(size);
                  size++;
                  break;
               }
               else
                  tempNodeBST = tempNodeBST.getLeft();
            }
            else
            {
               if(tempNodeBST.getRight() == null)
               {
                  tempNodeBST.setRight(newNodeBST);
                  tempNodeBST.getRight().setIndex(size);
                  size++;
                  break;
               }
               else
                  tempNodeBST = tempNodeBST.getRight();
            }
        }
    }

There is a method to insert student in binary search three. So how can i count the same names in this binary search tree. In below how i tried to do that but it didn't work.
    public void nameCounter(){
    String [] tempNames = names ;
    for(int element = 0 ; element < size ; element++){
        int contains = 1 ;
        for(int counter = element ; counter < size ; counter++){
            if(tempNames[element].equals(tempNames[counter]) && element != counter)        {
               contains++;
            }
        }
        System.out.println(tempNames[element] +" : "+contains);
    }
}

How can i fix that?


text:
Q: Handle a big api get call I currently working on an API call (in pure javascript) to get data from an extern server. Im kind of new to API calls and im stuck right now. The problem is that the file that im calling for is really big and the call takes forever.
So i was wondering if there is a way for me to only get like 50 000 rows at a time or something like that. Just to make it work.
Here is the API :
loadLibrary("cus:json3.js");

var buffer = new MemoryBuffer();
buffer.fromString("username:password", "utf-8");

var http = new HttpClientRequest();
http.header["Authorization"] = "Basic " + buffer.toBase64();
this.baseURL = "https://url...";
http.url = this.baseURL;

http.method = "GET";
http.execute();

var res = String(http.response.body);
var lines = res.split("\r");

var c = 0;
for each (var line in lines) {

  if (c == 100) {

  try {
    var json = JSON.parse(line);
    logInfo( "Address: " + json.Address + " id: " + json.id);
    }
  catch(e) { logInfo(e); }

  }
   c++;
}
logInfo(c);


text: Q: Is it possible to disable network only for current command session? I have a script that compiles a program, but it takes more than 2 hours to compile it. When I disable the network adapter of all the windows system, the compile time changes to 30 minutes and the compiling is still successful. This is because when compiling, the script accesses some network files, but actually those accesss are not strictly necessary to compile. So I would like to disable network access only for that CMD session so that I can continue using the network in the rest of my system. Is that possible?


text:
Q: How to perform pointer arithmetic? I'm new to the Carbon language, how to perform pointer arithmetic? Is this even possible?
p = p + 1;

=>

COMPILATION ERROR: <source>:11: type error in `+`:
could not find implementation of interface AddWith(U = i32) for i32*
Compiler returned: 1

A: Carbon does not support pointer arithmetic. The only two operations are

*

*dereference (*p gives the l-value p points to),

*address-of (&v gives the address of l-value v).

More detail is available in carbon design notes.


text:
Q: WP7 LINQ to SQL and Aggregate query I have added the following block of code to my WP7 app and not sure what the error means;
private void GetTodaysTotal()
{
    // Define the query to gather all of the to-do items.
            var boughtItemsToday = (from DBControl.MoneySpent
                                        bought in BoughtItemDB.BoughtItems
                                        select bought.ItemAmount).Sum();

    // Execute the query and place the results into a collection.
        BoughtItemsToday = new ObservableCollection<DBControl.MoneySpent> boughtItemsToday);
}

The error I am getting is on the line;
BoughtItemsToday = new ObservableCollection<DBControl.MoneySpent> boughtItemsToday);

and is;

The best overloaded method match for 'System.Collections.ObjectModel.ObservableCollection.ObservableCollection(System.Collections.Generic.List)' has some invalid arguments

I know this is something to with the LINQ query returning a decimal value, but I'm not sure how to fix it.  I am intending on binding the result into a XAML TextBlock.

A: You're right, it is the fact that you are returning a decimal from your first query and then trying to cast those decimals to DBControl.MoneySpent objects.  You will need 2 separate queries.
Consider this.  Your first query will only get the DBControl.MoneySpent objects:
var boughtItemsToday = (from DBControl.MoneySpent
                                        bought in BoughtItemDB.BoughtItems
                                        select bought);

Then, you can create your observable collection as follows:
var BoughtItemsToday = new ObservableCollection<DBControl.MoneySpent>(boughtItemsToday);

Finally, just get your sum separately:
var sum = boughtItemsToday.Sum(item => item.ItemAmount);


text:
Q: Create semantic url to redirect to section on frontpage I would like to create a semantic URL for my print material that should look something like mysite.com/newsletter.
However I do not have a specific page for my newsletter at the moment. Therefore I would like to redirect to a specific section on the frontpage. Is this possible

A: Either you just create a page called /newsletter and leave it empty and then set a URL rewrite from /newsletter to /thepageyouwant
Or you just set a URL rewrite from /newsletter to /thepageyouwant in the Magento URL rewrite management
So Requested Path is "newsletter" and target path the URL you want to link to.
Can be found in Catalog--> URL Rewrite Management


text:
Q: How to end FTP session in Chrome, to log in with different credentials? I've just opened an FTP site through Chrome which requires authentication, and I've logged in with some credentials.
Now I need to re-log in on that FTP with some different credentials. How can I make Chrome forget about the previous session and ask me for credentials again?

A: Opening a new incognito window worked for me.

A: The healthiest and the easiest way to end FTP session in Google Chrome might be only using Chrome Incognito mode for FTP processes, then closing it when finished those FTP processes.

You can launch incognito by pressing Ctrl + Shift + N, (or) Settings -> New incognito Window, (or) right mouse-click on a link from a regular Chrome session, and select "open link in incognito window".

Technically ending a FTP session in Google Chrome is complicated or maybe impossible. It only lets you keep connected to FTP server during a single browser session. In most of other browsers this situation is controllable. For example; You can resume to download a file from a FTP server even you have rebooted the system in Firefox FTP session.
Waiting a while to end the FTP session is not also a solution, because cache files are not deleted when Chrome returns ERR_TIMED_OUT. Refreshing page brings credentials of the FTP session back.
Unfortunatelly, there is no suitable solution yet for Google Chrome that I know.

A: It seems there's absolutely no way to do that - exactly logging off the FTP server - at least with versions between 2013 Q4 and 2018 Q1. There are some good workarounds anyhow listed in the answers below.

A: I faced the same problem and Just closed the chrome and re-open it.

A: It's better to use an Incognito Window (Ctrl+Shift+N), but if you forget, you can clear your credentials like this:
1) Clear all history and data (Ctrl+Shift+Del), e.g. from the last 24 hours
2) Restart Chrome
However, it's best to download a dedicated application for this, like FileZilla or WinSCP, because Chrome doesn't end FTP sessions.


text:
Q: Cannot convert Int32 to null when trying to add a row to table I'm trying to add a row to a table that has a foreign key pointing towards another location in the same table. This foreign key is defined as nullable.
When trying to add an entry to the table, I am getting the error
"errors": {
    "parentId": [
      "Error converting value {null} to type 'System.Int32'. Path 'parentId', line 4, position 18."
    ]
  },

If I try to pass a random int, I get The INSERT statement conflicted with the FOREIGN KEY constraint, which makes sense, since there are no other entries in the table.

As you can see, the foreign key is seen as nullable.
I've tried not passing the field at all, not passing any parameters in when passing the field, passing null, all of which generated the later error, with the exception of when I tried passing null, which gave me the converting error.
I am using swagger ui to pass the JSON.
Class in question:
public class
{
    public Country Country { get; set; }
    [Required]
    public int CountryId { get; set; }
    [Required]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public int? ParentId { get; set; }
    [ForeignKey("ParentId")]
    public Company Parent { get; set; }
}

I would like to create the first row on this table and set it's foreign key to null.
After implementing the fixes suggested in the answers, my error turned from a conversion error to the foreign constraint error stated above, even when passing a null.
Code, as per request:
DbContext:
public class ArtGalleriesContext:DbContext
{
    public ArtGalleriesContext(DbContextOptions<ArtGalleriesContext> options):base(options)
    {

    }

    public DbSet<ArtItem> ArtItems { get; set; }
    public DbSet<Artist> Artists { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<Country> Countries { get; set; }
    public DbSet<Floor> Floors { get; set; }
    public DbSet<Location> Locations { get; set; }
    public DbSet<Room> Rooms { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<UserLocation> UserLocations { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<UserLocation>()
            .HasKey(u => new {u.UserId, u.LocationId});
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(
                "Server=(localdb)\\mssqllocaldb;Database=GalleriesDB;Trusted_Connection=True;");
        }
    }
}

Controller:
[HttpPost("Companies")]
public IActionResult CreateCompany([FromBody]CreateCompanyRequest createCompanyRequest)
{
    try
    {
        if (createCompanyRequest==null)
        {
            return NotFound();
        }

        return CreatedAtRoute("CompanyById", _repository.Company.CreateCompany(createCompanyRequest),
            createCompanyRequest);
    }
    catch (Exception e)
    {
        return StatusCode(500, e.InnerException);
    }
}

Repository:
public int CreateCompany(CreateCompanyRequest createCompanyRequest)
{
    Company company = new Company()
    {
        CountryId = createCompanyRequest.CountryId,
        Name = createCompanyRequest.Name,
        ParentId = createCompanyRequest.ParentId
    };
    _context.Companies.Add(company);
    _context.SaveChanges();
    return company.Id;
}

Possibly related info: I tried populating the table using Microsoft SQL Server Manager. It was successful, however, this is the result:

There is clearly something wrong, since it started adding entried starting with PK 14.
After further inspection, I noticed that even if adding a row to the table fails, the primary key still increments.

A: The error is at the deserialization of the json to model, you have two options here:

*

*Add to your startup.cs class Json options to ignore null values like so:
.AddJsonOptions(options =>
 {
     options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore
 });

*Set on the property itself to ignore null values so it will initialize that int? as null
public class
{
   public Country Country { get; set; }
   [Required]
   public int CountryId { get; set; }
   [Required]
   public int Id { get; set; }
   [Required]
   public string Name { get; set; }
   [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
   public int? ParentId { get; set; }
   [ForeignKey("ParentId")]
   public Company Parent { get; set; }
}

A: Depending on your use case, you may also want to consider having the JSON Serializer ignore nulls
Or use "JsonProperty" attribute:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? ParentId { get; set; }

A: The issue could be solved by both above answers, but also, I noticed that I only declared ParentId as nullable int in my entity class, not in my model, CreateCompanyRequest; changing it's type inside the model solved the issue.
The conversion issue was because I tried passing a null value inside the model class, which contained an int prop, not a nullable int prop.


text:
Q: What is "Density of States" and how does one generally find it? I'm walking out of a graduate quantum midterm kicking myself because I was asked to compute density of states as a function of energy for a spin $1/2$ particle of mass $m$ in a hard wall box of length $L$, subjected to a magnetic field of strength $h^z>0$, and I just had no idea where to begin. I was given the eigenergies:
$$E(n,\sigma^z)=K_n-h^z\sigma^z$$
where $K_n=\frac{\pi^2\hbar^2n^2}{2mL^2}$. I was supposed to set $\sigma^z=1$ initially, then combine $\sigma^z=\pm 1$ results to get the full picture. I know that a state $n$ should have wave number:
$$k=\frac{n\pi }{L}=\sqrt{\frac{2m (K_n-h^z)}{\hbar}}$$
And that I can put each $k$ in a $1$-D box of size $L/\pi$, but I don't where to go from there and worse I don't actually know what I'm doing. I know this important for figuring out transition rates, but I just don't understand the reasoning presented by either my professor or Sakurai.
Ideally, if someone could explain what density of states is mathematically (every source I see just say its the number of states in the energy interval $(E,E+dE)$, which is a statement I understand from a physical perspective but means nothing to me mathematically since I'm fairly positive $dE$ is not a differential form in the sense that I'm used to), and how one generally finds it given that we know the energies as function of $n$, that would be amazing.
I apologize for my ignorance, or if anything I've said is incorrect, quantum mechanics seems especially difficult for me for some reason.

A: The $dE$ is meant to be a differential form, and if you define $\Omega(E)$ as the number of states below a given energy, then the density of states is simply $d\Omega/dE$. Which connects to the definition that you were given by the definition of a derivative as $$\lim_{dE\to0}\frac{\Omega(E+dE)-\Omega(E)}{dE}=\lim_{dE\to0}\frac{\text{definition you were given}}{dE} $$
This isn't a super clear way of describing the density of states in this case, because the number of states below a specific energy $E$ is a discontinuous function in quantum mechanics when the eigenenergies are discrete. Thus, $\Omega$ is formally not differentiable.
The kludge that is often used here is to notice that, for a one-dimensional system, the quantum number $n$ is related to $\Omega$, and then treating both as a continuous variable that can be differentiated. So, for instance, in the particle in a well without the electric field, the density of states would be found as such:
$$ E_n=\frac{\pi^2\hbar^2n^2}{2mL^2} $$
$$ E(\Omega)=\frac{\pi^2\hbar^2\Omega^2}{2mL^2} $$
$$ \Omega(E)=\sqrt{\frac{2mL^2E}{\pi^2\hbar^2}} $$
$$ \frac{d\Omega}{dE}=\sqrt{\frac{mL^2}{2\pi^2\hbar^2E}} $$
Note that in this case, $n$ is just $\Omega$, because there is one state for each value of the quantum number. In the case of the problem you were asked, there are two states for each value of the quantum number. Although since they have different energies, you can't simply set $\Omega=2n$ and run with it, you should simply find the density of states for the two spin states separately and combine them.

A: The number of states $\Omega$ below an energy $E$ in general is given by counting the states $i$:
$\Omega(E)=\sum_{i} U(E-E_i)$
Where $U$ is the Heaviside step function.
The density of states is the derivative of the number of states:
$\rho(E)=\frac{\partial\Omega(E)}{\partial E}=\sum_i \delta(E-E_i)$
The real meat of solving these problems is to find how to express the sum over the states in terms of the variables you are given for the energy.
For your problem, $\sum_i = \sum_{n=1}^{\infty}\sum_{\sigma=-1, 1} $
So we have:
$\rho(E)=\sum_{n=1}^{\infty}\sum_{\sigma=-1, 1}\delta(E-K_n+h\sigma)$
Which, if we make an approximation assuming L is large compared to our smallest wavelength, we can say $\sum_{n=1}^{\infty} \approx \frac{L}{\pi}\int dk$, and we know $k=n\pi/L$:
$\rho(E)=\frac{L}{\pi}\int dk \sum_{\sigma} \delta(E-k^2\hbar^2/2m+h\sigma)$
$\rho(E)=\frac{L}{\pi}\sum_{\sigma}\sqrt{{m}/{2\hbar^2(E-h\sigma)}}$
$\rho(E)=\frac{L}{\pi}\left(\sqrt{{m}/{2\hbar^2(E-h)}} + \sqrt{{m}/{2\hbar^2(E+h)}}\right)$
In general, there isn't a way to find the density of states. You can make complicated combinatorics problems, or sums that don't approximate into integrals in which you can evaluate the delta function.


text:
Q: How to calculate $\limsup_{n \rightarrow \infty} |\frac{x^n}{1+x^n}|$ I would like to show that the sequence $f_n = \frac{x^n}{1+x^n}$ is uniformly convergent on the interval $[0,1)$.
I know that the limiting function f of the sequence on this interval is $0$.
I would like to use the fact that $f_n$ is uniformly convergent if $\limsup_{n \rightarrow \infty}  |f_n(x) - f(x)| = 0$.
This leaves me needing to show that:
$\limsup_{n \rightarrow \infty} |\frac{x^n}{1+x^n}| = 0$
Intuitively i can see that the limit of the supremum of the sequence tends to $0$ as n tends to infinity. However, I am not sure how to prove this.
Is this the right approach or is there another way to show uniform convergence that is simpler and doesn't involve the limsup.
Thanks

A: For each $n\in\Bbb N$,$$\sup_{x\in[0,1)}\frac{x^n}{1+x^n}=\frac12,$$since you always have $\frac{x^n}{1+x^n}<\frac12$ and $\lim_{x\to1}\frac{x^n}{1+x^n}=\frac12$. So,$$\lim_{n\to\infty}\sup_{x\in[0,1)}\frac{x^n}{1+x^n}=\frac12.$$From this, together with the fact that$$\bigl(\forall x\in[0,1)\bigr):\lim_{n\to\infty}\frac{x^n}{1+x^n}=0,$$you can deduce that your sequence dos not converge uniformly.


text:
Q: Not able to retrieve the app object from global space I added two files to my index.html like this:
    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Marionette</title>
    <link rel="stylesheet" href="styles/bootstrap.min.css">

this is my routes.js file:
    (function(){
    Social = window.Social || {};
    Social.Routes = Backbone.Router.extend({
        initialize:function(){
            console.log('from routes');
        }
    });
}());

app.js:
jQuery(document).ready(function($) {
    Social = window.App || {};
    Social.App = new Backbone.Marionette.Application();

    Social.App.addInitializer(function(){
        console.log(Social);
    });

    Social.App.start();
});

initApp.js
(function(){
    Social = window.Social || {};
}())

I understand that, the way what i adding to global space is wrong here.. any one correct to add my variable to globally?
do i required to add a separate file before to these to files to make the app available to all?

A: At the minute you're just hiding the existing window.Social variable. You could easily have accessed it without the extra assignment. The correct way would be to pass window.Social in through the closure:
(function(social){
    social.mySocial = function() {

    };
}(window.Social));

Ensuring window.Social exists can be done either via an external JS file if you can be sure your file will be loaded in order, otherwise you will need to do window.Social || (window.Social = {}); each time.
Have a read here for some namespacing patterns.


text:
Q: Correct terraform syntax for adding permissions to AWS Lambda I'm learning Terraform and I'm trying to get the correct syntax to specify the IAM role permissions for it. I want these capabailities:

*

*Lambda can be invoked from an API Gateway that I also create in Terraform

*Lambda can write to Cloudwatch logs

I have the following which allows the API gateway to invoke the Lambda:
resource "aws_iam_role" "my_lambda_execution_role" {
  name = "my_lambda_execution_role"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": [
          "lambda.amazonaws.com",
          "apigateway.amazonaws.com"
        ]
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

I have seen the snippet below allows the Lambda to write to CloudWatch. I'm trying to combine these snippets to get all of the permissions but I can't get it right. What is the correct syntax to give all of these permissions to the role?
{
    "Statement": [
        {
            "Action": [
                "logs:CreateLogGroup",
                 "logs:CreateLogStream",
                 "logs:PutLogEvents"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:logs:*:*:*"
        }
    ]
}

A: https://www.terraform.io/docs/providers/aws/r/iam_role_policy_attachment.html
You need to create the policy and then attach it to your role.   The link above includes a more complete example than on the iam role page.

A: *

*IAM policy along with role.

# iam
data "aws_iam_policy_document" "policy" {
  statement {
    sid    = ""
    effect = "Allow"

    principals {
      identifiers = ["lambda.amazonaws.com"]
      type        = "Service"
    }

    actions = ["sts:AssumeRole"]
  }
}

resource "aws_iam_role" "iam_for_lambda" {
  name               = "iam_for_lambda"
  assume_role_policy = "${data.aws_iam_policy_document.policy.json}"
}

resource "aws_iam_role_policy" "frontend_lambda_role_policy" {
  name   = "frontend-lambda-role-policy"
  role   = "${aws_iam_role.iam_for_lambda.id}"
  policy = "${data.aws_iam_policy_document.lambda_log_and_invoke_policy.json}"
}

data "aws_iam_policy_document" "lambda_log_and_invoke_policy" {

  statement {
    effect = "Allow"

    actions = [
      "logs:CreateLogGroup",
      "logs:CreateLogStream",
      "logs:PutLogEvents",
    ]

    resources = ["*"]

  }

  statement {
    effect = "Allow"

    actions = ["lambda:InvokeFunction"]

    resources = ["arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:function:*"]
  }

}

*

*Please find the complete terraform code at my github

A: In a previous answer I wrote up some background information on how IAM roles work and what an "assume role policy" is. I'm going to assume that background information in this answer.
The policy you've given in your assume_role_policy argument in the resource "aws_iam_role" "my_lambda_execution_role" block is the policy governing which users and services are allowed to "assume" this role. In this case, you are allowing AWS Lambda and Amazon API Gateway to make requests using the privileges granted by this role.
However, by default the role doesn't grant any privileges at all. To address that, we need to attach one or more access policies to the role. The other policy JSON you shared here is an access policy, and to associate it with the role we need to use the aws_iam_role_policy resource type:
resource "aws_iam_role_policy" "logs" {
  name   = "lambda-logs"
  role   = aws_iam_role.my_lambda_execution_role.name
  policy = jsonencode({
    "Statement": [
      {
        "Action": [
          "logs:CreateLogGroup",
          "logs:CreateLogStream",
          "logs:PutLogEvents",
        ],
        "Effect": "Allow",
        "Resource": "arn:aws:logs:*:*:*",
      }
    ]
  })
}

Usually Terraform automatically infers dependencies between resource blocks by noticing references like the aws_iam_role.my_lambda_execution_role expression in the above, and indeed in this case Terraform will determine automatically that it needs to complete the creation of the role before attempting to attach the policy to it.
However, Terraform cannot see automatically here that the policy attachment must complete before the policy itself is operable, and so when you refer to the role from your API Gateway and Lambda resources you must use depends_on to tell Terraform that the policy attachment must complete before the policy will become usable:
resource "aws_lambda_function" "example" {
  filename      = "${path.module}/example.zip"
  function_name = "example"
  role          = aws_iam_role.my_lambda_execution_role.arn
  handler       = "example"

  # (and any other configuration you need)

  # Make sure the role policy is attached before trying to use the role
  depends_on = [aws_iam_role_policy.logs]
}

If you don't use depends_on like this, there is a risk that the function will be created and executed before the role attachment is complete, and thus initial executions of your function could fail to write their logs. If your function is not executed immediately after it's created then this probably won't occur in practice, but it's good to include the depends_on to be thorough and to let a future human maintainer know that the role's access policy is also important for the functionality of the Lambda function.


text:
Q: Database Design Puzzle: What's wrong with this diagram? I'm trying to polish up by database design skills. I've been working through a few IT-related puzzles today, most of which have been fairly straightforward. ...And then I came across this supposed 'oldie', which is frustrating the bezeejers out of me.
The premise is that there's an error with the class hierarchy in the diagram below. No further information regarding the nature of the classes/interface is given. I cannot find any logical issue with it. The best I can do is whimper that a point is not technically a shape, but I'd like to think the answer is a little less weaselly than that.
If anyone has any suggestions, I'd love to hear. It really is doing my head in.

A: Perhaps the question is giving us a hint:

No further information regarding the nature of the classes/interface is given.

We have absolutely zero information about the actual scope (i.e. business logic) of the problem. "Shape" could be a mathematical representation to be drawn on a grid. It could be a definition for a game engine modelling program. It could be an indicator of a person's fitness level. Who knows? Each of those variants would require different representations in both class diagrams and a relational data model.
It leaves us only to make assumptions about what might be semantically wrong. However, we can make observations about what might be technically wrong with the diagram itself.
I pose the problem is that the arrows are pointed in the wrong direction. In most class diagrams, inheritance is denoted by the child class having an arrow pointed at the base class.

This answer may seem nonsensical. However, it's actually meant as a jab at the puzzle question itself.  In real life, designing anything (databases, class diagrams, whatever) is about taking the business-specific needs of the problem and making the appropriate design decisions. Without knowing anything about the domain, all we can do is make assumptions about what might be semantically wrong with the design, which makes for a rather pointless puzzle problem.

A: I think the Polygon class is redundant. Is there any special reason why you'd have to separate rectangle and square? Going even further, why differentiate triangle from a rectangle? You could think of both as just a list of points; triangle has three, rectangle has four. And there's the thing you've mentioned yourself; point is not really a shape and maybe that's the most obvious answer you're looking for.

A: I'm stumped too.  The only thing I can come up with is that Polygon and Ellipse should be subordinate to Point.
A Polygon is three or more points.
An Ellipse has two focal points.
That would make the Shape interface a list or array of points.

A: Your question refers to database design and this is where I see the problem; The class hierarchy is far too deep and in my opinion could be modelled using a single shape class as all share similar properties E.G. all have sides. A circle has one, a triangle has 3 and a rectangle has 4.
As far as the class diagram itself goes I guess it could be argued that point, polygon and ellipse should be interfaces rather than classes.
I also agree that with the other comments about point not being a shape.
Out of interest where has this question originated from?

A: If I were to look at this from a rigid mathematical perspective, Point and Ellipse/Circle are Conic Sections, and should be in the same class.  I don't know that's the magical answer being looked for, but it is one.
Extending that, a Polygon consists of 3-N Lines, which aren't a portion of the data model.
I would agree with the other posters who point out that Circles, Rectangles, and Squares are simply special cases of Polygon, and I would not have broken them out specifically in a relational database model.  This may make sense for an object model, but it appears to be overkill for a relational one.

A: Given the vague nature of the question, this sounds like it could be a phrasing of the circle-ellipse problem. http://en.wikipedia.org/wiki/Circle-ellipse_problem.
Essentially the error would be defining sub-classes which have invariants that can't be defined in the super-classes:

*

*To define a valid square, you have to maintain a height-width ratio that isn't required in a rectangle (in the general case)

*Ditto (roughly) circle and ellipse

Related discussion at Is deriving square from rectangle a violation of Liskov's Substitution Principle?


text:
Q: How to design a personal messaging database? I wish to make a PM (personal messaging) system but have been struggling in setting up a fluid database that links the users of my 'user' table with the messages table.
In my PM system if you were to go to the interface, you will see the avatar of the sender, the name of the sender, and the message of the sender. The database however will have the names of the sender and recipient, the content of the message along with the timestamp the message(s) was sent. The database will also keep track if a message has been removed from a user's(s') inbox.
Here is what I've done: Three tables have been setup ('users' table, 'messages' table). The 'users' table contains all registered users with a primary auto_incremented id. The 'messages' table contains a primary auto_incremented message_id, a row that contains user_id, a row with the TIMESTAMP the message(s) was(were) sent, and a row with message_content. Is my setup correct in fulfilling what I want?
The issue I am having is that the messages of the sender are not linking with the intended recipient (in fact, I don't even know where the messages are even going).

A: When you're trying to write a database schema you have to think of tables like you would entities (things). The table's job is to describe a single thing or some part of a thing. That description is made up of attributes (columns). Each row can only describe one thing or one part of a thing (meaning multiple tables can represent individual parts of one thing). This is called database normalization.
So in your case you have 3 primary things you are concerned with.

*

*A User

*A Message

*An Inbox

If you think about the relationships described between these three things you can conclude that your schema is basically just the framework for a set of answers to question you know you will ask later.
For example, if every user must have an inbox and every inbox may have messages then the Inbox schema needs to have a user_id column that allows you to identify which inbox belongs to which user. Additionally, since an inbox may have one or more messages then it must also contain an inbox_id (this would be your auto increment id) which would allow you to identify a unique inbox in the table. Obviously the Message schema also needs a message_id column to uniquely identify each message. The schema also needs a user_id column that identifies which user the message belongs to (i.e. the author of the message).
However, since there is a one-to-many relationship between Inbox and Message and a many-to-many relationship between User and Message then you can't describe the relationship between them in the same table easily without creating logical inconsistencies. This is called 3NF or Third Normal Form.
So instead you create a fourth table that simply describes the relationship between an inbox and its messages. Let's call this the Recipient table for now.
The Recipient table needs to know about the inbox as well as the message and which user in the user table is the recipient of this message. That means you need 3 PKs or Primary Keys here.

*

*inbox_id

*message_id

*user_id // this will be the id of the recipient

Remember, number 3 on that list is the id of the user that the message was sent to, not the user that wrote the message (that is already identified by the Message table).
Now when you want to know which messages are in a given user's inbox you simply query the Recipient and join it on User and Message like so...
SELECT mesage.user_id AS Sender, message.contents, recipient.user_id AS Recipient
FROM recipient, inbox
JOIN message ON recipient.message_id = message.id
WHERE inbox.user_id = ?


text:
Q: Solutions of some diophantine equation How many solutions has the equation $x_1+x_2+\cdots+x_k=n$ in non-negative integers?

A: This problem can be easily solved by combinatorial tools. We have an equation $$x_1+x_2+\cdots+x_k=n \qquad (*)$$
1. We'll find number of solutions of above equation in $\mathbb{N}_0=\mathbb{N}\cup\{0\}$. With every solution $(x_1,x_2,\dots,x_k)$ of this equation we can associate a finite sequence consisting of $0$ and $1$. $$(x_1,x_2,\dots,x_k)\mapsto \underbrace{00\dots0}_{x_1}1\underbrace{00\dots0}_{x_2}1\dots 1\underbrace{00\dots0}_{x_k}.$$ It's easy to check that this mapping would be bijective. This sequence contains $x_1+x_2+\cdots+x_k=n$ zeros and $k-1$ ones.
So we must find the number of all different permutations of $n$ zeros and $k-1$ ones. It's equal to $$P(k-1,n)=\dfrac{(n+k-1)!}{(k-1)!n!}=C_{n+k-1}^{k-1}.$$ Hence it's the number of solutions of above equation in non-negative numbers.

*Now we'll find number of solutions of above equation in $\mathbb{N}$. Note that this equation has not solutions if $n<k$. Suppose that $n\geqslant k$. We'll do this transform: $(x_1-1)+\dots+(x_k-1)=n-k$ and put $y_i:=x_i-1$ and we must find the number of solutions of $y_1+\cdots+y_k=n-k$ in non-negative numbers. We can apply the first part of problem and we get the answer:$$C_{(n-k)+k-1}^{k-1}=C_{n-1}^{k-1}.$$
Q.E.D.


text:
Q: Print strings in a list that begin with a specific character Currently, I have this:
lst = ['Eleanor', 'Sammy', 'Owen', 'Gavin']

def partition(lst):
    if any('abcdefghijklm') in ([x[0] for x in lst]):
        print(lst)
    else:
        print('This still isn\'t working')

I am trying to examine the first character of each string in lst and only print the strings in lst that start with any letter A-M. I cannot seem to find any method that supports this. Is there any native method that I'm overlooking?

A: lst = ['Eleanor', 'Sammy', 'Owen', 'Gavin']
whitelist = set('abcdefghijklm')
for name in lst:
    if name[0].lower() in whitelist:
        print(name)

A: You're misunderstanding what any does. It returns True if any member of an iterable fed to it is True: print(any([False, [], 0, None, 'a'])) #outputs True Conversely, all only returns True if every member of an iterable passed to it is True.
It is a powerful tool, however, and you can use for this task:
from string import ascii_lowercase as lowercase #a-z

def partition(*names):
    if any(n[0].lower() in lowercase[:13] for n in names):
        print(*names)
    else:
        print("No names matched the criteria")

partition('Eleanor', 'Sammy', 'Owen', 'Gavin')

A: How about the plain and simple:
def partition(lst):
    print([ x for x in lst if x[0].lower() in 'abcdefghijklm' ])

Or what about the very clear:
def partition(lst):
    for word in lst:
        if word[0] in 'abcdefghijklm':
             print(word)


text:
Q: How to colour a single country in R maps package (worldhires) I am new here and I am trying to plot points on a map of a coastal region - therefore I would like to show a coastline and colour just one country, surrounded by adjoining countries.
My code is
library(maps)
library(mapdata)

map("worldHires", xlim=c(-90,-70), ylim=c(-20,-2), # Re-defines the latitude and longitude range
    col = "gray", fill=TRUE)

However I would like to colour in just Peru. I have so far managed to do this:
map('worldHires', 'Peru', col = "grey90", fill=TRUE, xlim=c(-90,-70), ylim=c(-20,-2))

but this doesn't show adjoining countries, and I would really like to show all adjoining countries and just colour Peru.
I have seen advice in another thread using the simple map tool - but there is slightly less detail (see below)
library(maptools)

data(wrld_simpl)
plot(wrld_simpl,
     col = c(gray(.80), "red")[grepl("Peru", wrld_simpl@data$NAME) + 1],
xlim=c(-90,-70), ylim=c(-20,-2))

Does anyone know how to do it using worldhires? It's probably really simple and I just haven't worked it out.

A: The trick is to use map() to extract the Peru boundaries, then overplotting the Peru fill on a worlmap outline.
library(maps)
library(mapdata)

peru <- map("worldHires", regions="Peru", plot=FALSE, fill=TRUE)

map("worldHires", xlim=c(-100,-30), ylim=c(-30,10))
map(peru, col="red", fill=TRUE, add=TRUE)

A: A Hadleyverse version via ggplot:
library(maps)
library(mapdata)
library(ggplot2)

coast_map <- fortify(map("worldHires", fill=TRUE, plot=FALSE))

gg <- ggplot()
gg <- gg + geom_map(data=coast_map, map=coast_map,
                    aes(x=long, y=lat, map_id=region),
                    fill="white", color="black")
gg <- gg + geom_map(data=data.frame(region="Peru"), map=coast_map,
                    aes(map_id=region), fill="steelblue")
gg <- gg + xlim(-90,-70) + ylim(-20,-2)
gg <- gg + coord_map()
gg <- gg + theme_bw()
gg


text:
Q: Convert partial function to method in python Consider the following (broken) code:
import functools
class Foo(object):
  def __init__(self):
    def f(a,self,b):
      print a+b
    self.g = functools.partial(f,1)
x=Foo()
x.g(2)

What I want to do is take the function f and partially apply it, resulting in a function g(self,b). I would like to use this function as a method, however this does not currently work and instead I get the error
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    x.g(2)
TypeError: f() takes exactly 3 arguments (2 given)

Doing x.g(x,2) however works, so it seem the issue is that g is considered a "normal" function instead of a method of the class. Is there a way to get x.g to behave like a method (i.e implicitly pass the self parameter) instead of a function?

A: This will work. But I'm not sure if this is what you are looking for
class Foo(object):
  def __init__(self):
    def f(a,self,b):
      print a+b
    self.g = functools.partial(f,1, self) # <= passing `self` also.

x = Foo()
x.g(2)

A: this is simply a concrete example of what i believe is the most correct (and therefore pythonic :) way to solve -- as the best solution (definition on a class!) was never revealed -- @MikeBoers explanations are otherwise solid.
i've used this pattern quite a bit (recently for an proxied API), and it's survived untold production hours without the slightest irregularity.
from functools import update_wrapper
from functools import partial
from types import MethodType

class Basic(object):

    def add(self, **kwds):
        print sum(kwds.values())

Basic.add_to_one = MethodType(
        update_wrapper(partial(Basic.add, a=1), Basic.add),
        None,
        Basic,
        )

x = Basic()
x.add(a=1, b=9)
x.add_to_one(b=9)

...yields:
10
10

...the key take-home-point here is MethodType(func, inst, cls), which creates an unbound method from another callable (you can even use this to chain/bind instance methods to unrelated classes... when instantiated+called the original instance method will receive BOTH self objects!)
note the exclusive use of keyword arguments! while there might be a better way to handle, args are generally a PITA because the placement of self becomes less predictable.  also, IME anyway, using *args, and **kwds in the bottom-most function has proven very useful later on.

A: functools.partialmethod() is available since python 3.4 for this purpose.
import functools
class Foo(object):
    def __init__(self):
        def f(a,self,b):
        print a+b
    self.g = functools.partialmethod(f,1)
x=Foo()
x.g(2)

A: There are two issues at hand here. First, for a function to be turned into a method it must be stored on the class, not the instance. A demonstration:
class Foo(object):
    def a(*args):
        print 'a', args

def b(*args):
    print 'b', args

Foo.b = b

x = Foo()

def c(*args):
    print 'c', args

x.c = c

So a is a function defined in the class definition, b is a function assigned to the class afterwards, and c is a function assigned to the instance. Take a look at what happens when we call them:
>>> x.a('a will have "self"')
a (<__main__.Foo object at 0x100425ed0>, 'a will have "self"')
>>> x.b('as will b')
b (<__main__.Foo object at 0x100425ed0>, 'as will b')
>>> x.c('c will only recieve this string')
c ('c will only recieve this string',)

As you can see there is little difference between a function defined along with the class, and one assigned to it later. I believe there is actually no difference as long as there is no metaclass involved, but that is for another time.
The second problem comes from how a function is actually turned into a method in the first place; the function type implements the descriptor protocol. (See the docs for details.) In a nutshell, the function type has a special __get__ method which is called when you perform an attribute lookup on the class itself. Instead of you getting the function object, the __get__ method of that function object is called, and that returns a bound method object (which is what supplies the self argument).
Why is this a problem? Because the functools.partial object is not a descriptor!
>>> import functools
>>> def f(*args):
...     print 'f', args
...
>>> g = functools.partial(f, 1, 2, 3)
>>> g
<functools.partial object at 0x10042f2b8>
>>> g.__get__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'functools.partial' object has no attribute '__get__'

There are a number of options you have at this point. You can explicitly supply the self argument to the partial:
import functools
class Foo(object):
    def __init__(self):
        def f(self, a, b):
            print a + b
        self.g = functools.partial(f, self, 1)

x = Foo()
x.g(2)

...or you would imbed the self and value of a in a closure:
class Foo(object):
    def __init__(self):
        a = 1
        def f(b):
            print a + b
        self.g = f

x = Foo()
x.g(2)

These solutions are of course assuming that there is an as yet unspecified reason for assigning a method to the class in the constructor like this, as you can very easily just define a method directly on the class to do what you are doing here.
Edit: Here is an idea for a solution assuming the functions may be created for the class, instead of the instance:
class Foo(object):
    pass

def make_binding(name):
    def f(self, *args):
        print 'Do %s with %s given %r.' % (name, self, args)
    return f

for name in 'foo', 'bar', 'baz':
    setattr(Foo, name, make_binding(name))

f = Foo()
f.foo(1, 2, 3)
f.bar('some input')
f.baz()

Gives you:
Do foo with <__main__.Foo object at 0x10053e3d0> given (1, 2, 3).
Do bar with <__main__.Foo object at 0x10053e3d0> given ('some input',).
Do baz with <__main__.Foo object at 0x10053e3d0> given ().


text:
Q: Jalopy comments indentation We use jalopy to format our code to the sun standard (well 99%).
I have 1 issue with it.  It keeps moving comments to the right of the line.
E.g
// Panel
"JPanel.border", new LazyValue(packageName + "PanelBorder"), //frozen

// Button
"Button.background", new ColorUIResource(251, 251, 251), //frozen
"Button.foreground", new ColorUIResource(0, 0, 0), //frozen

But jalopy always moves the // Button to the far right.
// Panel
"JPanel.border", new LazyValue(packageName + "PanelBorder"), //frozen
                                                             // Button
"Button.background", new ColorUIResource(251, 251, 251), //frozen
"Button.foreground", new ColorUIResource(0, 0, 0), //frozen

Is there any way to stop this?
Thanks
Neil

A: so we use jaloppy 1.9.2 (commercial version) and single-line comments are formatted correctly

A: This is due to comment association. You have //frozen followed by an empty line and then //Button. Jalopy thinks that these two comments are associated with each other, so brings them together.
Take a look at Section 2.8.13.2 Comment association of the manual for more information.


text:
Q: Losing connection to wifi randomly, Ubuntu 18.04 LTS on Dell XPS 15 9530 I have been having trouble with my wireless card. Here is what I get from dmesg:
A@B:~$ dmesg | grep iwlwifi
[    4.410812] iwlwifi 0000:06:00.0: loaded firmware version 17.948900127.0 op_mode iwlmvm
[    4.461558] iwlwifi 0000:06:00.0: Detected Intel(R) Dual Band Wireless AC 7260, REV=0x144
[    4.479921] iwlwifi 0000:06:00.0: base HW address: 90:2e:1c:4a:98:2c
[    4.695410] iwlwifi 0000:06:00.0 wlp6s0: renamed from wlan0
[  109.553413] iwlwifi 0000:06:00.0: iwlwifi transaction failed, dumping registers
[  109.553421] iwlwifi 0000:06:00.0: iwlwifi device config registers:
[  109.553482] iwlwifi 0000:06:00.0: 00000000: 08b18086 00100000 028000c3 00000000 00000004 00000000 00000000 00000000
[  109.553487] iwlwifi 0000:06:00.0: 00000020: 00000000 00000000 00000000 c0708086 00000000 000000c8 00000000 00000100
[  109.553491] iwlwifi 0000:06:00.0: iwlwifi device memory mapped registers:
[  109.553530] iwlwifi 0000:06:00.0: 00000000: ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
[  109.553534] iwlwifi 0000:06:00.0: 00000020: ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
[  109.553541] iwlwifi 0000:06:00.0: iwlwifi device AER capability structure:
[  109.553574] iwlwifi 0000:06:00.0: 00000000: 14010001 00100000 00000000 00462031 00002000 00002000 00000014 40000001
[  109.553577] iwlwifi 0000:06:00.0: 00000020: 0000000f f7900460 00000000
[  109.553581] iwlwifi 0000:06:00.0: iwlwifi parent port (0000:00:1c.2) config registers:
[  109.553614] iwlwifi 0000:00:1c.2: 00000000: 8c148086 00100407 060400d5 00810010 00000000 00000000 00060600 200000f0
[  109.553618] iwlwifi 0000:00:1c.2: 00000020: f790f790 0001fff1 00000000 00000000 00000000 00000040 00000000 00100303
[  109.553678] WARNING: CPU: 7 PID: 0 at /build/linux-60XibS/linux-4.15.0/drivers/net/wireless/intel/iwlwifi/pcie/trans.c:1973 iwl_trans_pcie_grab_nic_access+0xea/0xf0 [iwlwifi]
[  109.553679] Modules linked in: rfcomm ccm bnep arc4 pn544_mei mei_phy pn544 hci nfc joydev intel_rapl x86_pkg_temp_thermal iwlmvm intel_powerclamp coretemp dell_laptop kvm_intel dell_smbios_smm dcdbas mac80211 kvm irqbypass crct10dif_pclmul dell_wmi sparse_keymap crc32_pclmul ghash_clmulni_intel pcbc aesni_intel aes_x86_64 crypto_simd glue_helper cryptd intel_cstate dell_smbios_wmi intel_rapl_perf dell_smbios input_leds wmi_bmof dell_wmi_descriptor uvcvideo serio_raw videobuf2_vmalloc videobuf2_memops videobuf2_v4l2 rtsx_pci_ms videobuf2_core videodev iwlwifi memstick hid_multitouch btusb media btrtl btbcm btintel snd_hda_codec_hdmi bluetooth cfg80211 snd_hda_codec_realtek ecdh_generic snd_hda_codec_generic snd_hda_intel snd_hda_codec snd_hda_core snd_hwdep snd_pcm acpi_als kfifo_buf industrialio
[  109.553793] RIP: 0010:iwl_trans_pcie_grab_nic_access+0xea/0xf0 [iwlwifi]
[  109.553823]  iwl_read_prph+0x38/0x90 [iwlwifi]
[  109.553834]  iwl_trans_pcie_log_scd_error+0x125/0x1f0 [iwlwifi]
[  109.553848]  ? iwl_pcie_txq_build_tfd+0xe0/0xe0 [iwlwifi]
[  109.553856]  iwl_pcie_txq_stuck_timer+0x46/0x70 [iwlwifi]
[  109.608796] iwlwifi 0000:06:00.0: Queue 10 is active on fifo 2 and stuck for 10000 ms. SW [56, 65] HW [90, 90] FH TRB=0x05a5a5a5a

When I grep lsmod, this is what I get,
A@B:~$ lsmod | grep iwl
iwlmvm                364544  0
mac80211              778240  1 iwlmvm
iwlwifi               282624  1 iwlmvm
cfg80211              622592  3 iwlmvm,iwlwifi,mac80211

This is what I get when I run iwconfig,
A@B:~$ iwconfig
enxd8eb97b0f784  no wireless extensions.

wlp6s0    IEEE 802.11  ESSID:"my_internet"
      Mode:Managed  Frequency:5.745 GHz  Access Point:  3C:1E:04:DC:AA:9D
      Bit Rate=650 Mb/s   Tx-Power=22 dBm
      Retry short limit:7   RTS thr:off   Fragment thr:off
      Power Management:off
      Link Quality=59/70  Signal level=-51 dBm
      Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
      Tx excessive retries:0  Invalid misc:44   Missed beacon:0

lo        no wireless extensions.

When I look up the network manager state, this is what I get,
A@B:~$ cat /var/lib/NetworkManager/NetworkManager.state
[main]
NetworkingEnabled=true
WirelessEnabled=true
WWANEnabled=true

Finally, this is what I get when I look up the following,
A@B:~$ lspci | grep Network && uname -a
06:00.0 Network controller: Intel Corporation Wireless 7260 (rev c3)
Linux B 4.15.0-29-generic #31-Ubuntu SMP Tue Jul 17 15:39:52 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

Some information about my computer:
I run a Dell XPS 15 9530, with an intel i7 CPU and I guess an intel Wireless 7260 card.
Here is something important to note I think. Usually when my computer disconnects from the wireless card (at least I think that is what is going on), then when I run
dmesg | grep iwl, lsmod | grep iwl, and iwconfig, I get nothing, nothing, and "lo   no wireless extention" respectively.
I have tried unloading and reloading iwlconfig via the command modprobe, but it does not help. Furthermore, I tried using the linux kernel 4.15.24 to see if maybe it was an issue with the current kernel. This also did not help.
Searching on forums like this one has led me to try all of these different things. But so far I have not had any success. So this is a direct appeal for help. It is incredibly frustrating not being able to work since I rely on internet access to do my job. May I please get some help? Is there more information required to fix this issue?
Thank you very much!

Update (August 8, 2018)

I encountered a completely new issue with my computer. This is what I got from dmesg:
A@B:~$ dmesg --level=err
[   28.545162] iwlwifi 0000:06:00.0: Hardware error detected.  Restarting.
[   28.545249] iwlwifi 0000:06:00.0: HW error, resetting before reading
[   28.604079] iwlwifi 0000:06:00.0: iwlwifi transaction failed, dumping registers
[   28.604082] iwlwifi 0000:06:00.0: iwlwifi device config registers:
[   28.604137] iwlwifi 0000:06:00.0: 00000000: 08b18086 00100406 028000c3 00000000 f7900004 00000000 00000000 00000000
[   28.604140] iwlwifi 0000:06:00.0: 00000020: 00000000 00000000 00000000 c0708086 00000000 000000c8 00000000 00000100
[   28.604141] iwlwifi 0000:06:00.0: iwlwifi device memory mapped registers:
[   28.604187] iwlwifi 0000:06:00.0: 00000000: 40800000 80000000 00000000 00000000 00000000 00000000 00000000 00000000
[   28.604189] iwlwifi 0000:06:00.0: 00000020: 00000001 080003dc 00000144 00000000 80000000 803a0000 80008040 00080046
[   28.604194] iwlwifi 0000:06:00.0: iwlwifi device AER capability structure:
[   28.604222] iwlwifi 0000:06:00.0: 00000000: 14010001 00000000 00000000 00462031 00000000 00002000 00000000 00000000
[   28.604224] iwlwifi 0000:06:00.0: 00000020: 00000000 00000000 00000000
[   28.604226] iwlwifi 0000:06:00.0: iwlwifi parent port (0000:00:1c.2) config registers:
[   28.604240] iwlwifi 0000:00:1c.2: 00000000: 8c148086 00100407 060400d5 00810010 00000000 00000000 00060600 200000f0
[   28.604242] iwlwifi 0000:00:1c.2: 00000020: f790f790 0001fff1 00000000 00000000 00000000 00000040 00000000 00100303
[   30.796567] iwlwifi 0000:06:00.0: Access time out - failed to enable LP XTAL
[   30.841730] iwlwifi 0000:06:00.0: Failed to init the card
[   30.843234] wlp6s0: failed to remove key (0, 3c:1e:04:dc:aa:9d) from hardware (-5)
[   30.847718] iwlwifi 0000:06:00.0: iwl_trans_wait_tx_queues_empty bad state = 0
[   30.848028] wlp6s0: failed to remove key (2, ff:ff:ff:ff:ff:ff) from hardware (-5)


text:
Q: How to give different metrics tags for different controllers in Spring Boot In Spring Boot 2.0.2 is it possible to use one meterRegistry bean for all controllers while giving each controller its own set of commonTags. For example in my Application.java I define the following.
@Bean
public MeterRegistryCustomizer<PrometheusMeterRegistry> metrics() {
  return registry -> registry.config().commonTags("messageType", "x");
}

Then when I register any meters to the registry they will have this messageType = x. Is it possible to define within this bean what commonTags will register when any function gets executed within the scope of Controller?
If so how? Does this need to be done within controller itself?

A: There isn't really a way for meter's that are registered in a specific context to automatically get a tag. Short answer: you'll have to add the tag manually yourself.
You could use a MeterFilter to inspect Meters as they are registered and add tags there based on the meter's name.
Keep in mind that tags are best used to represent a subset of a measurement:
db.request.total{queryType=userLookup}
db.request.total{queryType=groupLookup}
db.request.total{queryType=userUpdate}

This is the recommended way to use tags because then you can determine how many of a given request are being made and which might be the path that needs to be optimized for speed.
db.request.total{caller=controller}
db.request.total{caller=notAController}

Breaking up metric by caller won't be useful in that case.


text:
Q: REACTJS Pass variable through const using fetch I have my function here to fetch some stuff from the openweather API that I'm using.
const [ForecastFind, setForecastFind] = useState(null)
useEffect(() => {
  fetch(
    'https://api.openweathermap.org/data/2.5/onecall?lat=22&lon=151&exclude=current,minutely,daily&APPID=TOKEN',
  )
    .then(response => response.json())
    .then(data => setForecastFind(data.hourly[0].dt))
}, [])

This works fine when i'm using it like this:

  {ForecastFind}

What I'm, after is to let this pass in a variable so I can access any index that I want through the function. (data.hourly[0] , me getting the first item)
What I've tried is this: It's obviously not the right syntax but I'm not sure what the correct syntax is.
const [ForecastFind, setForecastFind] = useState(null)
useEffect(choose => {
  var choose = 0
  fetch(
    'https://api.openweathermap.org/data/2.5/onecall?lat=22&lon=151&exclude=current,minutely,daily&APPID=TOKEN',
  )
    .then(response => response.json())
    .then(data => setForecastFind(data.hourly[choose].dt))
}, [])

Trying to use the const with a variable:

  {ForecastFind(1)}

A: useEffect doesn't pass any params in the callback function. what you can do is store the entire data in the ForecastFind state and call a function to access what you need
const [ForecastFind, setForecastFind] = useState(null);
  useEffect(() => {
      var choose = 0;
      fetch('https://api.openweathermap.org/data/2.5/onecall?lat=22&lon=151&exclude=current,minutely,daily&APPID=TOKEN')
          .then(response => response.json())
          .then(data => setForecastFind(data.hourly));

  }, []);

const getForecast = (choose) => {
    return ((ForecastFind || {})[choose] || {}).dt || null;
}
...

      {getForecast(1)}

A: ForecastFind is not a function so you cannot pass in parameters.
I would suggest to store the whole data.hourly array in ForecastFind like this setForecastFind(((data.hourly))).
Then you can access it like this -

   {ForecastFind[1].dt}


text:
Q: Is there an algorithm by which you can remove cells in Sudoku? I'm trying to make a sudoku generator. I have to remove some cells from sudoku field, but I can't remove more than 30 cells. I wrote an algorithm that removes random cell (if without this cell sudoku still has one solution). How to delete 40 or 50 cells from sudoku?
        createBaseField();
        mixField(15);
        int min = 0;
        int max = 8;
        GameModes.chooseMode(MODE);
        int freeCells = new GameModes().getFreeCells();

        for (int k = 0; k <= freeCells; ) {
            int i = randomI(min, max);
            int j = randomJ(min, max);
            if (field[i][j] == 0) {
                i = randomI(min, max);
                j = randomJ(min, max);
            }

            int temp = field[i][j];
            field[i][j] = 0;

            if (solver.isOneSolution(field)) {
                k++;
                field[i][j] = 0;
            }
            if (!solver.isOneSolution(field)) {
                field[i][j] = temp;
            }
        }


text:
Q: ILNumerics plot with 3 coordinates I have 3 arrays of Rx, Ry, Rz of type float.
I'm trying to plot a surface with following code:
        ILArray<float> y = Ry
        ILArray<float> x = Rx
        ILArray<float> z = Rz
        ILArray<float> Z = ILMath.zeros<float>(x.S[0], x.S[1], 3);

        Z[":;:;1"] = x;
        Z[":;:;2"] = y;
        Z[":;:;0"] = z;

        var scene = new ILScene {
            new ILPlotCube(twoDMode: false) {
                new ILSurface(Z) {
                    Wireframe = { Color = Color.FromArgb(50, Color.LightGray) },
                    Colormap = Colormaps.Jet,
                }
           }
        };
        panel.Scene = scene;

But it draw nothing.
Sample points:
z: 1 0,1111111 0,01111111 0,001010101 8,417508E-05 6,475007E-06 0,1111111 0,01388889 0,001984127
x: 3 4 5 6 7 8 2 1 0
y: 4 4 4 4 4 4 4 4 4

I'm trying to draw a surface like that
http://cs618230.vk.me/v618230086/7b18/Q2aQP0uMPUg.jpg

A: X, Y and Z must be matrices. Start with some regular grid and change it until you end up where you want to go. Your y looks really suspicious...
See: http://ilnumerics.net/surface-plots.html


text:
Q: Kibana Field Conversion - Transforming Unix Time into Date I was wondering if there is a way to convert a field that is being received in Unix Time (long) into a fully readable Date in the Kibana environment.
My application is sending JSON logs to Kibana. Two of the log fields are numbers representing a UnixTimeStamp. In this case, the begin and end dates of a procedure.
{
  beginDate: 1669734768,
  endDate: 1669734780
}

This means that when I try to access these fields in a Table Visualization, the data is represented as it shows.
Table View of the problem
Is there a way to parse this UnixTimeStamp into a more user-friendy date model so that it is easier to read in the Visualization?
Something like "May 25th 2016, 22:39:30.000" or similar.
Thank you!


text:
Q: I get an error when I try to deploy to Heroku with simpleJWT version 4.6.0 When I install djangorestframework-simplejwt 4.6.0 in Django and try to deploy it to Heroku, I get the following error:
remote:          Downloading djangorestframework-3.12.2-py3-none-any.whl (957 kB)
remote:        ERROR: Could not find a version that satisfies the requirement djangorestframework-simplejwt==4.6.0 (from -r /tmp/build_5927f5b0/requirements.txt (line 19)) (from versions: 1.0, 1.1, 1.2, 1.2.1, 1.3, 1.4, 1.5.1, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.1, 3.0, 3.1, 3.2, 3.2.1, 3.2.2, 3.2.3, 3.3, 4.0.0, 4.1.0, 4.1.1, 4.1.2, 4.1.3, 4.1.4, 4.1.5, 4.2.0, 4.3.0, 4.4.0)
remote:        ERROR: No matching distribution found for djangorestframework-simplejwt==4.6.0 (from -r /tmp/build_5927f5b0/requirements.txt (line 19))

I tried installing and deploying 4.4.0 to see if I could find 4.6.0, and I was able to deploy it, but when I tried to start and access it with python manage.py runserver, the 'str' object has no attribute 'decode'.
Why does this happen? I would appreciate it if you could tell me how to feed them.

A: Change your python runtime in heroku to version 3.7 or above. I had a similar issue, so create a runtime.txt file in your root folder of your django project and specify the version of python you want example for me its python-3.8.11.


text:
Q: How to set individual indices in Numpy arrays I am trying to use arrays to set values in other arrays. Unfortunately instead of setting a value it is somehow overwriting a bunch of values. What is going on, and how can I achieve what I want?
>>> target = np.array( [ [0,1],[1,2],[2,3] ])
>>> target
array([[0, 1],
       [1, 2],
       [2, 3]])
>>> actions = np.array([0,0,0])
>>> target[actions] #The first row, 3 times
array([[0, 1],
       [0, 1],
       [0, 1]])
>>> target[:,actions] #The first column, 3 times
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2]])
>>> values = np.array([7,8,9])
>>> target[:,actions] = values #why isnt this working?
>>> target
array([[9, 1],
       [9, 2],
       [9, 3]])
#Actually want
#array([[7, 1],
#       [8, 2],
#       [9, 3]])

>>> target = np.array( [ [0,1],[1,2],[2,3] ]) #reset to original value
>>> actions = np.array([0,1,0])
>>> target[:,actions] = values.reshape(3, 1)
array([[7, 7],
       [8, 8],
       [9, 9]])
#Actually want
#array([[7, 1],
#       [1, 8],
#       [9, 3]])

A: target[:,actions] selects the same column of target thrice.
When you say target[:,actions] = values, what you are doing is:

*

*Assign 7 to all the values in the column, three times.

*Assign 8 to all the values in the column, three times.

*Assign 9 to all the values in the column, three times.

So you end up with 9 in all the values in the column.
If you insist on this awkward triple-writing of data, you can fix it by transposing the write:
target[:,actions] = values.reshape(3, 1)

This will write [7,8,9] to the column, three times.  Obviously that's wasteful, and you could do this instead:
target[:,actions[-1]] = values

The effect should be the same, and it saves computation.

A: 2 ways to write [7,8,9] to the first column:
basic indexing (with slice):
In [396]: target[:,0] = [7,8,9]           # all rows, 1st column
In [397]: target
Out[397]:
array([[7, 1],
       [8, 2],
       [9, 3]])

Advanced indexing (with 2 lists)
In [398]: target[[0,1,2],[0,0,0]] = [7,8,9]   # pair [0,0],[1,0],[2,0]
In [399]: target
Out[399]:
array([[7, 1],
       [8, 2],
       [9, 3]])

The 2nd method also works for a mix of columns:
In [400]: target = np.array( [ [0,1],[1,2],[2,3] ])
In [401]: target[[0,1,2],[0,1,0]] = [7,8,9]
In [402]: target
Out[402]:
array([[7, 1],
       [1, 8],
       [9, 3]])

Broadcasting comes into play.  In a case like this the are 3 potential arrays to broadcast - the 2 dimensions and the source array.
Advanced indexing like this produces a 1d array.  So the source array has to match:
In [403]: target[[0,1,2],[0,1,0]]
Out[403]: array([7, 8, 9])

A (1,3) can broadcast to (3,), but a (3,1) can't:
In [404]: target[[0,1,2],[0,1,0]] = np.array([[7,8,9]])
In [405]: target[[0,1,2],[0,1,0]] = np.array([[7,8,9]]).T
...
ValueError: shape mismatch: value array of shape (3,1) could not be broadcast to indexing result of shape (3,)

This sort of indexing is unusual.  Note that the result is (3,3).
In [412]: target[:,[0,0,0]]
Out[412]:
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2]])

A (3,1) source:
In [413]: np.array([[7,8,9]]).T
Out[413]:
array([[7],
       [8],
       [9]])
In [414]: target[:,[0,0,0]] = _
In [415]: target
Out[415]:
array([[7, 1],
       [8, 2],
       [9, 3]])

The (3,1) can broadcast to (3,3).  It works, but ends up assigning [7,8,9] 3 times, all to the same 0 column.

Another way of assigning the 1st column:
In [423]: target[np.ix_([0,1,2],[0,0,0])]
Out[423]:
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2]])

Again a (3,3), with accepts a (3,1):
In [424]: target[np.ix_([0,1,2],[0,0,0])] = np.array([[7,8,9]]).T
In [425]: target
Out[425]:
array([[7, 1],
       [8, 2],
       [9, 3]])

ix_ makes 2 arrays that can broadcast against each other, in this case a column vector and a row one:
In [426]: np.ix_([0,1,2],[0,0,0])
Out[426]:
(array([[0],
        [1],
        [2]]), array([[0, 0, 0]]))

I can select all elements of target with:
In [430]: target[np.ix_([0,1,2],[0,1])]
Out[430]:
array([[0, 1],
       [1, 2],
       [2, 3]])

and in a jumbled order:
In [431]: target[np.ix_([2,0,1],[1,0])]
Out[431]:
array([[3, 2],
       [1, 0],
       [2, 1]])

A: I couldn't get it to work using : indexing, however the following is functional by using an array of indices. Not sure why the : method is not working, if someone can come up with a way to fix that I will accept it instead.
>>> target = np.array( [ [0,1],[1,2],[2,3] ])
>>> rows = np.arange(target.shape[0])
>>> actions = np.array([0,1,0])
>>> values = np.array([7,8,9])
>>> target[rows,actions] = values
>>> target
array([[7, 1],
       [1, 8],
       [9, 3]])


text:
Q: Why a sleep 300 (5 minutes) can last several hours some time? I have a MiniMac with the OSX system.
My script is:
while true
  do echo "Sleep 300 seconds = 5 minutes"
  date
  sleep 300
  echo "end of sleep"
  date
done

I want it to repeat every 5 minutes; but some time it is suspending for several hours when it does this "sleep 300", here is the result:
Sleep 300 seconds = 5 minutes
Fri Nov  8 15:52:49 CET 2013
end of sleep
Fri Nov  8 15:57:49 CET 2013
Sleep 300 seconds = 5 minutes
Fri Nov  8 15:57:49 CET 2013
end of sleep
Fri Nov  8 16:02:49 CET 2013
Sleep 300 seconds = 5 minutes
Fri Nov  8 16:02:49 CET 2013
end of sleep
Fri Nov  8 16:20:59 CET 2013
Sleep 300 seconds = 5 minutes
Fri Nov  8 16:20:59 CET 2013
Sleep 300 seconds = 5 minutes
Fri Nov  8 15:52:49 CET 2013
end of sleep

A: This sounds like a process that either has or is having it's nice level set to a lower level. I'd confirm this with the command:
$ ps -eo "%p %y %x %c %n" | less

The last column is the nice value and should be 0 in most cases. If it's some other value between -20 (most favorable scheduling) to 19 (least) then something is setting the nice value to this different value.
Example
$ ps -eo "%p %y %x %c %n"| head -10
  PID TTY          TIME COMMAND          NI
    1 ?        00:00:01 init              0
    2 ?        00:00:00 kthreadd          0
    3 ?        00:00:02 ksoftirqd/0       0
    4 ?        00:00:03 migration/0       -
    5 ?        00:00:00 watchdog/0        -
   15 ?        00:00:06 events/0          0
   19 ?        00:00:00 cpuset            0
   20 ?        00:00:00 khelper           0
   21 ?        00:00:00 netns             0

Other things

*

*Something else that @derobert's pointed out. The time is skewed strangely in some of your output. Might be something is wrong with your clock.
Specifically this block:
Fri Nov  8 16:20:59 CET 2013
Sleep 300 seconds = 5 minutes
Fri Nov  8 15:52:49 CET 2013
end of sleep

Looks like we went back in time here!

*Several people in comments have indicated that your system may have gone to sleep or may have hibernated. This idea would seem to be the best lead, since sleep typically uses little CPU time, as indicated by @Gilles in my answer's comments, so would be typically unaffected by the nice level being changed.


text:
Q: Unable to instantiate application com.android.tools.fd.runtime.BootstrapApplication I've got this error and tried some solutions I found here but they didn't work.
I don't know why and how to solve this.
Please help.
Android Studio 2.1.2
07-12 18:28:46.742 642-642/com.vuforia.samples.VuforiaSamples E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vuforia.samples.VuforiaSamples, PID: 642
java.lang.RuntimeException: Unable to instantiate application com.android.tools.fd.runtime.BootstrapApplication: java.lang.ClassNotFoundException: Didn't find class "com.android.tools.fd.runtime.BootstrapApplication" on path: DexPathList[[zip file "/data/app/com.vuforia.samples.VuforiaSamples-2/base.apk"],nativeLibraryDirectories=[/data/app/com.vuforia.samples.VuforiaSamples-2/lib/arm, /data/app/com.vuforia.samples.VuforiaSamples-2/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]
    at android.app.LoadedApk.makeApplication(LoadedApk.java:676)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6294)
    at android.app.ActivityThread.access$1800(ActivityThread.java:222)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1861)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7229)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Caused by: java.lang.ClassNotFoundException: Didn't find class "com.android.tools.fd.runtime.BootstrapApplication" on path: DexPathList[[zip file "/data/app/com.vuforia.samples.VuforiaSamples-2/base.apk"],nativeLibraryDirectories=[/data/app/com.vuforia.samples.VuforiaSamples-2/lib/arm, /data/app/com.vuforia.samples.VuforiaSamples-2/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at android.app.Instrumentation.newApplication(Instrumentation.java:1004)
    at android.app.LoadedApk.makeApplication(LoadedApk.java:666)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6294)        at android.app.ActivityThread.access$1800(ActivityThread.java:222)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1861)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7229)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Suppressed: java.lang.ClassNotFoundException: com.android.tools.fd.runtime.BootstrapApplication
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
    ... 12 more

Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

A: After a few search i came up this sollution,
Its because of the android studio tries to instant run.
to turn off this feature

*

*Go to file

*click setting

*select Build,Execution development on left

*side menu  disable instant run to hotswap by unchecking it.

*select apply and its all done

setting Secreenshot for reference. Thanks hopefully it may help you.


text:
Q: RAILS Time Zone - Show time based on web user's locaton I have developed online examination system, and while creating exam i submit "exam start time", this is stored in the database as UTC,
for example say exam start time "Sun Jan 29 15:30:00 UTC 2012",
Student from India should see the exam start time in his local time i.e "Sun Jan 29 21:00:00 +0530 2012"
Student from France should see the exam start time in his local time,
please guide me how i can acheive this,
Thanks in advance

A: Before I read this thread on Stackoverflow I used the information from another SO thread to resolve this one:
new Date().getTimezoneOffset()/60;

It is a javascript function but can easily be put in application.html.erb or elsewhere if you want a less obtrusive form.

A: If you already know where the student is from, you can use:  http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html#method-i-in_time_zone
Otherwise, go with Scott's suggestion.


text:
Q: Qt WebView - intercept loading of JS/CSS Libraries to load local ones I've been looking for a while through documentation to find a way to accomplish this and haven't been successful yet. The basic idea is, that I have a piece of html that I load through Qt's webview. The same content can be exported to a single html file.
This file uses Libraries such as Bootstrap and jQuery. Currently I load them through CDN which works when online just fine. However, my application also needs to run offline. So I'm looking for a way to intercept loading of the Libraries in Qt and serve a locally saved file instead. I've tried installing a https QWebEngineUrlSchemeHandler, but that never seems to trigger the requestStarted method on it.
(PyQT example follows)
QWebEngineProfile.defaultProfile().installUrlSchemeHandler(b'https', self)

If I use a different text for the scheme and embed that into the page it works, so my assumption is that it doesn't work as Qt has a default handler for it already registered. But that different scheme would fail in the file export.
Anyway, back to the core question; Is there a way to intercept loading of libraries, or to change the url scheme specifically within Qt only?
Got Further with QWebEngineUrlRequestInterceptor, now redirecting https requests to my own uri, which has a uri handler. However, the request never gets through to it, because: Redirect location 'conapp://webresource/bootstrap.min.css' has a disallowed scheme for cross-origin requests.
How do I whitelist my own conapp uri scheme?
Edit: For completeness sake, it turns out back when I originally stated the question, it was impossible to accomplish with PySide 5.11 due to bugs in it. The bug I reported back then is nowadays flagged as fixed (5.12.1 I believe) so it should now be possible to accomplish this again using Qt methods, however for my own project I'll stick to jinja for now which has become a solution for many other problems.

A: The following example shows how I've done it.  It uses the QWebEngineUrlRequestInterceptor to redirect content to a local server.
As an example, I intercept the stacks.css for stackoverflow and make an obvious change.
import requests
import sys
import threading
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineProfile
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptor, QWebEngineUrlRequestInfo
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn

# Set these to the address you want your local patch server to run
HOST = '127.0.0.1'
PORT = 1235

class WebEngineUrlRequestInterceptor(QWebEngineUrlRequestInterceptor):
    def patch_css(self, url):
        print('patching', url)
        r = requests.get(url)
        new_css = r.text + '#mainbar {background-color: cyan;}'  # Example of some css change
        with open('local_stacks.css', 'w') as outfile:
            outfile.write(new_css)
    def interceptRequest(self, info: QWebEngineUrlRequestInfo):
        url = info.requestUrl().url()
        if url == "https://cdn.sstatic.net/Shared/stacks.css?v=596945d5421b":
            self.patch_css(url)
            print('Using local file for', url)
            info.redirect(QtCore.QUrl('http:{}:{}/local_stacks.css'.format(HOST, PORT)))

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    """Threaded HTTPServer"""

app = QtWidgets.QApplication(sys.argv)

# Start up thread to server patched content
server = ThreadingHTTPServer((HOST, PORT), SimpleHTTPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()

# Install an interceptor to redirect to patched content
interceptor = WebEngineUrlRequestInterceptor()
profile = QWebEngineProfile.defaultProfile()
profile.setRequestInterceptor(interceptor)

w = QWebEngineView()
w.load(QtCore.QUrl('https://stackoverflow.com'))
w.show()
app.exec_()

A: So, the solution I went with in the end was, first, introduce jinja templates. Then, using those the template would have variables and blocks set based on export or internal use and from there I did not need the interceptor anymore.


text:
Q: Printing to USB Thermal printer with Python, Failed to open/win error: The device does not recognize the command I am very new to Python and I cant seem to get a small script to run as intented.
Here is the code
from escpos.printer import Usb

p = Usb(0x0519, 0x0003)
p.text('Hello World!\n')

I got the code to run without the p.text() but when i try to send data to the printer with USB interface I get the following error:
Traceback (most recent call last):
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 236, in get_interface_and_endpoint
    return self._ep_info[endpoint_address]
KeyError: 1

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\SSK\PycharmProjects\printer\main.py", line 8, in <module>
    p.text('Hello World!\n')
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\escpos\escpos.py", line 506, in text
    self.magic.write(txt)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\escpos\magicencode.py", line 244, in write
    self.write_with_encoding(encoding, to_write)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\escpos\magicencode.py", line 263, in write_with_encoding
    self.driver._raw(
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\escpos\printer.py", line 99, in _raw
    self.device.write(self.out_ep, msg, self.timeout)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 986, in write
    intf, ep = self._ctx.setup_request(self, endpoint)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 113, in wrapper
    return f(self, *args, **kwargs)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 228, in setup_request
    intf, ep = self.get_interface_and_endpoint(device, endpoint_address)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 113, in wrapper
    return f(self, *args, **kwargs)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 238, in get_interface_and_endpoint
    for intf in self.get_active_configuration(device):
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 113, in wrapper
    return f(self, *args, **kwargs)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 249, in get_active_configuration
    self.managed_open()
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 113, in wrapper
    return f(self, *args, **kwargs)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\core.py", line 131, in managed_open
    self.handle = self.backend.open_device(self.dev)
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\backend\libusb0.py", line 501, in open_device
    return _check(_lib.usb_open(dev))
  File "C:\Users\SSK\PycharmProjects\printer\venv\lib\site-packages\usb\backend\libusb0.py", line 447, in _check
    raise USBError(errmsg, ret)
usb.core.USBError: [Errno None] b'libusb0-dll:err [os_open] failed to open \\\\.\\libusb0-0001--0x0519-0x0003: win error: The device does not recognize the command.\r\n'

Process finished with exit code 1

The printer I am using is a "Star TSP100", if anybody has any idea or suggestion I would really appreciate the help.


text:
Q: Stuff a lead developer for an Objective-C team should know Advice on being a lead developer is welcome.  Advice on being a lead developer of an Objective-C team more so.  Unfortunately, I don't have experience in Objective-C (I suppose the first thing to do is to learn it).  Also, I've never been a lead developer before.  I do have about 6 years experience in developing applications in Java, Flex and C#.

A: The best thing you can do as a leader is to stay out of other people's way.
Your job as lead is to maintain an overall "big picture" view of the project, while being able to drop down to any level. The best leads I've seen are always available to help, always try to be involved, but don't step on their team member's toes. Some ways to achieve this:

*

*Expect team members to make decisions about the implementation of their area. This should help them to take pride in their work, which will make the project better.

*Be aware of what is happening on the project at all times. This means communication. You could have a scrum-type daily meeting, or just chat with the individuals every now and then; whatever works for you and your team.

*Don't micromanage — once you've handed off a project facet, let the person assigned handle it unless they need your help. But don't force help on them. I had a team leader who was the most approachable person I've ever known. He somehow made it plain that he would always help, without forcing himself on us. Not sure how he did it, though.

I wouldn't worry too much about the choice of languages. You can learn any language you need to; experience on other projects (even in other languages) will only help you. Just remember that's it's more likely that your team knows the language better than you, and be prepared to defer if necessary. You will have to work hard to bring your own skills up to par.


text:
Q: Recfactoring duplication of codes without adding complexity? I have the following simple methods of very similar code, I like to extract out the common bits, but not if it adds complexity to the method, can someone give me an example or even links on how this can be achieved?
Here are two examples:
public function findRecipeById($id)
{
   $query = "SELECT * FROM assets WHERE asset_type = 'recipe' AND asset_id = $id";
   ...fetch query data ...
}

public function findArticleById($id)
{
   $query = "SELECT * FROM assets WHERE asset_type = 'article' AND asset_id = $id";
   ...fetch query data ...
}

As you can see, these two are just some very simple methods to illustrate my problem, they have almost identical query string, and the only option I can think of is to convert them into the following method:
public function findAssetById($assetType, $assetId)
{
   $query = "SELECT * FROM assets WHERE asset_type = '".$assetType."' AND asset_id = $id";
   ...fetch query data ...
}

So the problem I see is that I now have reduced duplication of code and reduced 2 methods into 1, but at the same time I have also created a method with higher complexity than needed by introducing more parameter.
a few key things that are not illustrated here:

1) the query could be much bigger and
2) the complexity of the refactored method could be much higher with many more params added.

My question for the experts out there is if there's a better way to reduce code duplication in this case without introducing complexity?  Or is it better to just leave it as 2 simpler methods instead?
Thanks!

A: Try to make your code more OOP. This is why Data Mappers or Active Record patterns are so popular. Otherwise, your code violates Single Responsibility principle, it tries to make too much.
Your class should either work with articles or recipes, but not both of the same time. This is typical mistake made, cause people think that each table in DB should have single class that represents it, but your objects are not represenation of DB tables, they should be representation of simple objects or processes.
For the same reason, it is wise to break down code into even more classes, one that works with single object, second that works with collection, in your example that would be Article, Recipe, ArticleCollection, RecipeCollection plus maybe interfaces for those 2 groups.
You might want to make a base class, but only if one type might be polymorphically switched with another somewhere in your app. Don't do it just to remove code duplication, instead use composition.


text:
Q: Force a textarea input to begin with default text I have a textarea (or editable DIV) input that I always want to start with default text AND is not editable by the user. So for example:
Textbox would always begin with the default value: My name is
Users would be able and required to add their name, such as: My name is David
They would not be able to delete the My name is default text. Ideally, if the user would click anywhere on that default text, the cursor would jump to the end of that text, so they wouldn't have a chance to even attempt to type something, except after the default. Same goes for backspace, the default text (My name is) could not be deleted.
Any suggestions? I have the ability to use Javascript/Jquery.

A: Why not just stick a label (i.e.: span) right next to the text area and style it so that they look like it's one text area. Just line them up and set a background image (or css borders) behind both of them using css to create the appearance of the text area. Then turn the normal borders off of the textarea also using css. Should be fairly easy to code. Tricky part is just getting it styled correctly. If you don't mind the text being on a different line you could do this (from another post):
http://jsfiddle.net/eAW2U/
Or if you want them on the same line (which would only work for a text box really, not a textarea, you could float them
<div style="float:left">etc...

Or alternatively you could use the keypress/keyup events to check and see if the keypress will end up changing the beginning of the overall text and if so cancel it.


text:
Q: what is the appropriate inner product
I dont know what would be the inner product and how can I show the inequality by that

A: First define $f(u):=(u^2-1)e^{-u^4/2},\,g(u):=(u^3+2)e^{-u^4/2}$, so the inequality we want to prove is$$\int_{\Bbb R}f(x)g(x)dx\int_{\Bbb R}f(y)g(y)dy\le\int_{\Bbb R}f^2(x)dx\int_{\Bbb R}g^2(y)dy.$$In terms of the usual inner product $\langle h_1,\,h_2\rangle:=\int_{\Bbb R}h_1(u)h_2(u)du$, this becomes $\langle f,\,g\rangle^2\le\langle f,\,f\rangle\langle g,\,g\rangle$, which is just the result we were asked to use.