How to intercept upload requests when using ng6-file-man?

Question: I am creating file upload functionality for my application using the example ng6-file-man-test which uses ng6-file-man module to enable varies file/folder manipulation functionalities. According to my application requirements I am also using an interceptor for the requests to add a token to them. The interceptor works fine for most of the requests but not for the upload and download request.

jwt.interceptor.ts

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse }
  from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const duplicate = request.clone({ params: request.params.set('token', 'jwt-token') });

    return next.handle(duplicate);
  }
}

I haven't made any changes to the AppComponent which is given in the example.

The following is the app.module.ts with the interceptor added.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppComponent } from './app.component';
import { FileManagerModule } from 'ng6-file-man';
import { JwtInterceptor } from '../_helpers/jwt.interceptor';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    HttpClientModule,
    BrowserModule,
    FileManagerModule

  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

File Manager component is as follows
    export class FileManagerComponent implements OnInit, AfterContentChecked {
  tree: TreeModel;
  appLanguage = 'it';

  constructor() {
    let currentUser = JSON.parse(localStorage.getItem('currentUser'));
    const treeConfig: ConfigInterface = {
      baseURL: 'https://backend.com/',
      api: {
        listFile: 'api/file/list',
        uploadFile: 'api/file/upload?token=' + currentUser.access_token,
        downloadFile: 'api/file/download',
        deleteFile: 'api/file/remove',
        createFolder: 'api/file/directory',
        renameFile: 'api/file/rename',
        searchFiles: 'api/file/search'
      },
      options: {
        allowFolderDownload: false,
        showFilesInsideTree: true
      }
    };

    this.tree = new TreeModel(treeConfig);
  }

  itemClicked(event: any) {
    console.log(event);
  }

  ngAfterContentChecked() {
    console.log('after');
  }

  ngOnInit() {
    console.log('before');

    let container = document.querySelector('.file-manager-left');

  }

}

I would like to know if there is a possible way in which I can intercept the upload and download requests which are made to the backend by the module.
Answer: It should be caused because for all requests that you are intercepting you expect usage of HttpService.

Uplodad is using FineUploader library which seems not to be connected with HttpService
Download is made by opening new window with inserted parameters containing only path.id

We would be happy if you propose any solution on our GitHub issues


Can a time signature of a song be changed to a different time signature?

Question: As an example, can you change a time signature from standard 4/4 time to waltz 3/4 and can you change a waltz to standard 4/4 time? Or more generally, can ANY time signature of a song be changed to any other time signature (even unusual ones like 7/4, 9/8) and not completely ruin the song?
Comment: See: https://music.stackexchange.com/questions/36411/how-can-a-non-musician-recognize-anacrusis/36415#36415
Answer: I believe you're asking a different question from the one Todd answered. Yes, often. A simple example would be 'Fly Me to the Moon'. Written in 3/4, most commonly played in 4/4. Sometimes for fun, I play 4/4 numbers in 5/4. 'Lullaby of Birdland' is a goody. Care needs to be taken with the phrasing and timing (obviously!) but a lot of numbers can be changed about.
It does change some drastically, especially vocals, but it can be and is done. But not all songs will benefit...
There's a version of Take Five that's been recorded in 4/4. Somewhat destroys the point...
Comment: I find that gospel tunes sound great in 7/8 as jazz arrangements.
Comment: Yeah, I just noticed he edited it after my answer.
Answer: The time signature can vary throughout a song, but it sounds like you are asking if, for example, you can play a 4/4 song in 3/4. That depends on how compatible the signatures are and what you consider "completely ruining the song."
4/4 and 2/2 are interchangeable. 6/8 and 3/4 are usually interchangeable. 12/8 can be compatible with 6/8 and 4/4 swing. Beyond that, you'll likely have to make some adjustments (e.g., to play a 3/4 song in 4/4, you will have to add 1 beat to every measure), and those adjustments could make the song very awkward.
Answer: The beatles "with a little help from my friends" is in 4/4 and joe cocker's version is in 12/8. I think both were hits, if that is any indication of not ruining a song. The song is wildly different in style so how much of a change does one need to make before it is considered a different song is up to interpretation that i will leave up to you (and the copyright lawyers).
Comment: Unless there's evidence to the contrary, Cocker's version is probably a 12/8 slow blues (just because that's so much more common than 3/4 or 6/8).
Comment: @scottm. Agreed. Edited to reflect that.
Comment: I tend to think of 12/8 as 4/4 with triplets on each beat.
Comment: @tim I might think of it that way for internalizing the groove while playing but for analysis or transcriptions I would never use 4/4 with triplets. There is a reason 12/8 exists.
Comment: True, but I meet 4/4 with 'swing feel' written, so it's effectively 12/8, but easier to write, and read.
Comment: @tim with swing feel is good for swing 8th. But once you start playing all three notes in the span of a beat swing 8ths don't really work. At best you will wind up with a mix of 8ths that should be swung and triplets written out.
Comment: Seems to work fine when I play like that. There's no contradiction between swing feel 2/1  in a triplet, and playing all three triplet notes. It's all over the place in jazz and swing.
Answer: Listen to the flecktones play the 12 days of Christmas for a definite "yes". Each day is a different key and time signature.
Comment: Although the original moves about a fair bit.
Answer: In addition, it's possible to change time signatures to whatever you want, so long as you make the apporpriate use of tempo changes and tuplets. Basically, you can change the time signature to whatever you want, and it's possible to undo its effect by making notation that makes people's eyes bleed. If you want to change the feel of the music (change relative note durations), yes it's possible, for example "What a Wonderful World" done by Louis Armstrong is in 12/8, but commonly the song is played in 4/4, and it just feels like all the swing has been traded for a faster feel.


How to increment value of a Column based on previous Row's value in SQL

Question: I'm using SQL Server 2008.
I have two Tables: User_master and Item_master.
There is a User with user_id = 10.
|---------|
| user_id |
|---------|
|   10    |
|---------|

There are 5 Items with item_id = 20 to 24.
|---------|---------|------------|
| item_id | user_id | item_order |
|---------|---------|------------|
|   20    |    10   |     0      |
|---------|---------|------------|
|   21    |    10   |     0      |
|---------|---------|------------|
|   22    |    10   |     0      |
|---------|---------|------------|
|   23    |    10   |     0      |
|---------|---------|------------|
|   24    |    10   |     0      |
|---------|---------|------------|

There is one more column in Item_master that is item_order(int).
I want to place item_order = 0 to 4 in all these rows with only single query.
Is it possible?
EDIT :
item_id is not supposed to be in order.
For example, instead of 20,21,22,23,24; it could be 20,25,31,47,58.
Comment: @RAS: Yeah, thought so. That's why I posted a comment and not an answer. It shows however, how important it is to define your constraints when asking a question.
Comment: A very simple solution would be to subtract 20 from the item_id and use that: `update item_master set item_order = item_id - 20`.
Comment: is {`item_id` `user_id`} guaranteed to be unique?
Comment: @Ic, yes those are the primary keys of respective tables.
Answer: You can use the row_number() window function to assign an increasing number to each row with the same user_id.  A subquery is required because you cannot use window functions directly in the set clause.
update  im
set     im.item_order = im.rn
from    (
        select  row_number() over (partition by user_id
                                   order by item_id) - 1 as rn
        ,       *
        from    item_master
        ) as im;

Live example at SQL Fiddle.
Answer: Extrapolating a little bit and since {item_id, user_id} is unique in the table, here is a generic solution:
UPDATE m
SET item_order = x.new_item_order
FROM item_master m
INNER JOIN (
  SELECT [item_id], [user_id],
      (ROW_NUMBER() OVER (PARTITION BY [user_id]
                          ORDER BY [item_id]))-1 AS [new_item_order]
  FROM item_master
) x ON m.item_id = x.item_id AND m.user_id = x.user_id

SQL Fiddle example
This will set the item_order column in order of item_id for each user, starting at 0.
Comment: @RAS Yes Andomar's answer will be one step simpler than this one because the join is apparently not necessary
Comment: @Ic. Thanks for answering but Andomar's answer is much simpler.
Answer: I've assumed you'd want to group by user to generate the number and that item_order column is already there, just needs updating?
update IM
    set item_order = t.RowNumber
FROM Item_master IM
INNER JOIN
    (select item_id , user_id , ROW_NUMBER() over(PARTITION BY user_id order by item_id ) -1 as 'RowNumber' from Item_master) T
    ON T.item_id = IM.item_id


First order logic. Describe that a set has more than 2 elements.

Question: I would like to describe that a set has at least 3 elements using first order logic, would this be a valid way to do that?
$\forall x\exists y\exists z(\neg(x=y)\wedge\neg(x=z)\wedge\neg(y=z))$
I can't find this example anywhere in my book, but it seems to do what I want, comments?
Comment: No, not at all. What is this $x$ about?
Comment: It means that for any element in the set I can find at least 2 other elements which are different from each other and from x, wouldn't that mean the set has 3 elements or more?
Comment: I see now I wrote 2 in the topic question, where I meant to write 3, is it correct now?
Answer:
You need to assert the existence of three elements $x, y, z$ (so $\forall x$ is incorrect), and
you need to assert something about those existent elements, otherwise you are only saying "there exists at least three elements $x, y, z$". Presuming you want to assert that they all belong to some set we'll call $A$, then
you need a proposition, e.g., $A(x)$ to denote $x \in A$, where $A$ is some set.
Without the proposition, you are claiming only the existence of at least three elements, but nothing about their being contained in some set.

$$\exists x \,\exists y\, \exists z\,\Big(A(x) \land A(y) \land A(z) \land \;\lnot(x= y )\;\land \;\lnot (y= z) \;\land\; \lnot(x= z)\Big)$$
Or, simply, $$\exists x \,\exists y \,\exists z\,\Big(x\in A \;\land\; y\in A\; \land \;z\in A\;\land\; \lnot(x= y )\;\land \;\lnot (y= z) \;\land\; \lnot(x= z)\Big)$$
Comment: Clear and Complete + 1
Answer: This sentence would be true in the empty domain. Provided you've excluded that via convention, it is fine, though quite laborious to prove directly from the definition of truth. An easier example would be to replace the universal quantifier with an additional existential one.
Answer: You want to claim the existence of three elements that are not equal.  Then $\exists x\exists y\exists z$ claims they exist.  You already seem to have a handle on claiming they are not equal.
Answer: If we may use universal and existential quantifiers in FOL, then here are some fun axiomatizations.
<code>#import: written-on(word,paper).

my-minus-one(N,M) <->  (N > 1)  &  (M = N-1)

forall x. same(x,x)

% confirms non empty domain.
legal-pad(paper) <-> min-elements(1, paper)

exactly-n-elements(1,paper) <->
(exists paper word.
    (   written-on(word,paper)
      & ~(exists other-word.
           (  written-on(other-word,paper)
             & ~same(other-word,word)))))

exactly-n-elements(2,paper) <->
(exists paper word1 word2.
  (  written-on(word1,paper)
   & written-on(word2,paper)
   & ~same(word1,word2)
   & ~ (exists other-word.
         (   written-on(other-word,paper)
          & ~same(other-word,word1)
          & ~same(other-word,word2)))))

exactly-n-elements(N,paper) <->
   range-elements(N,N,paper)

range-elements(N,M,paper) <->
 (exists paper.
  ( min-elements(N,paper)
    & max-elements(M,paper)))

min-elements(1,paper) <->
 (exists paper word1.
     (written-on(word1,paper)))

min-elements(2,paper) <->
 (exists paper word1 word2.
   (  written-on(word1,paper)
    & written-on(word2,paper)
    & ~same(word1,word2)))

max-elements(2,paper) <->
(exists paper word1 word2.
   (  written-on(word1,paper)
    & written-on(word2,paper)
    &  ~(exists other-word.
          (  written-on(other-word,paper)
            & ~same(other-word,word1)
            & ~same(other-word,word2)))))

% exists a paper with no elements
exactly-n-elements(0,paper) <->
  (exists paper
     ~(exists word1. written-on(word1,paper)))

max-elements(1,paper) <->
 exactly-n-elements(0,paper) v exactly-n-elements(1,paper)

containsAtLeastOneUnique(paper1,paper2) <->
  (exists word. (written-on(word,paper1) -> ~written-on(word,paper2)))

disjoint(paper1,paper2) <->
  ~(exists word. (written-on(word,paper1) & written-on(word,paper2)))

subset(paper1,paper2) <->
    (forall word.
      written-on(word,paper1) -> written-on(word,paper2) )

union(paper1,paper2,paper) <->
 (forall word.
   (written-on(word,paper) <->
       (written-on(word,paper1) v written-on(word,paper2))))

union(paper1,paper2,paper) <->
  (exists scratchpad.
      union(paper1,paper2,scratchpad)
     & ~containsAtLeastOneUnique(paper,scratchpad))

union-disjoint(paper1,paper2,paper) <->
   (   union(paper1,paper2,paper)
     & disjoint(paper1,paper2))

min-elements(4,paper) <->
  (exists paper1 paper2.
     min-elements(2,paper1)
   & min-elements(2,paper2)
   & union-disjoint(paper1,paper2))

min-elements(N,paper) <->
  (exists paper1 paper2.
     min-elements(1,paper1)
   & min-elements(M,paper2)
   & legal-pad(paper2)
   & union-disjoint(paper1,paper2)
   & my-minus-one(N,M))

max-elements(N,paper) <->
  (exists paper1 paper2.
     max-elements(1,paper1)
   & max-elements(M,paper2)
   & legal-pad(paper1)
   & legal-pad(paper2)
   & union-disjoint(paper1,paper2)
   & my-minus-one(N,M))

equal_papers_v2(paper1,paper2) <->
   ( ~containsAtLeastOneUnique(paper1,paper2)
     & ~containsAtLeastOneUnique(paper2,paper1)
     & legal-pad(paper1)
     & legal-pad(paper2))

equal_papers_v1(paper1,paper2) <->
 ( legal-pad(paper1)
   & (forall word.
      (written-on(word,paper1) <-> written-on(word,paper2))))
</code>
Comment: As you introduce your post with "use universal and existential quantifiers in FOL", you might make the content clearer by [introducing mathematical notation](https://math.stackexchange.com/help/notation) with $\LaTeX$ syntax.


What is the best way to load data to the following structure from database?

Question: The database schema is as follows
Employee

EmployeeID(int, pk)
FirstName(nvarchar)
LastName(nvarchar)
Email(nvarchar)
EmployeeType(int)
Salary(decimal)
HourlyRate(decimal)

Benefits

BenefitID (int, pk)
Benefit (nvarchar)
EmployeeID (int, fk)

Employee table holds all the employee data. Salary field applies to fulltime employee and the hourly rate applies to hourly employee. Benefits only apply to Full Time employee.
I have setup a service class that will return all the employees.
I also want to initialize all the benefits to the Salaried Employee object. I have setup a check for employee-type using a switch statement and then create the instance of the object and add it to the collection.
This will work perfectly.
The issue I have is every time I add a new type of employee then I will have to modify the Employee service and add logic to switch statement to handle the new type of employee. This breaks the open close principle.
My question is what is the best way to load data from the database to the objects in this type of scenario?
public enum EmployeeType
{
    FullTime =1,
    PartTime =2
}

public class EmployeeBenefit
{
    private string _benefit;
    private Employee _employee;

    public int EmployeeId { get { return Employee.Id; } }
    public Employee Employee { get { return _employee; } }
    public string Benefit { get { return _benefit; } }

    public EmployeeBenefit(Employee emp, string benefit)
    {
        _benefit = benefit;
        _employee = emp;
    }
}

public abstract class Employee
{
    public int Id { get; set; }
    public abstract EmployeeType Type { get; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

public class SalariedEmployee: Employee
{
    private ICollection<EmployeeBenefit> _benefits;

    public SalariedEmployee()
    {
        _benefits = new List<EmployeeBenefit>();
    }

    public IEnumerable<EmployeeBenefit> Benefits { get {return _benefits;} }
    public double Salary { get; set; }

    public override EmployeeType Type
    {
        get { return EmployeeType.FullTime; }
    }

    public void AddBenefit(string benefit)
    {
        EmployeeBenefit ebenefit = new EmployeeBenefit(this, benefit);

        if (Benefits.Contains(ebenefit))
            _benefits.Add(ebenefit);
    }

    public void RemoveBenefit(string benefit)
    {
        EmployeeBenefit ebenefit = new EmployeeBenefit(this, benefit);

        if(_benefits.Contains(ebenefit))
            _benefits.Remove(ebenefit);
    }
}

public class PartTimeEmployee : Employee
{
    public override EmployeeType Type
    {
        get { return EmployeeType.PartTime; }
    }

    public double HourlyRate { get; set; }
}

public class EmployeeService
{
    public IEnumerable<Employee> GetAll() {
        List<Employee> _lst = new List<Employee>();

        using(var db = new EmployeeContext)
        {

            foreach(Employee e in db.Employees)
            {

                switch(e.Type){
                    case EmployeeType.PartTime:
                        PartTimeEmployee pt = new PartTimeEmployee();
                        //initialize the values of parttime employee like hourly rate

                        _lst.Add(pt);
                        break;
                    case EmployeeType.FullTime:
                        SalariedEmployee se = new SalariedEmployee();
                        //initialize the value of salaried employees like benefits, salary
                        _lst.Add(se);
                        break;
                }

            }

        }

        return _lst;
    }
}

Comment: you can move this logic in factory class....class will have job to check type and create instance of appropriate type..Basically you are moving switch statements in that class and have to modify only that class every time
Comment: I thought about using factory method which will return a proper instance of the Employee but how do i set all the relative properties like benefits, hourly rate and salary as they are based on child objects. I am confused here.
Comment: how about adding interface like IPartTimeEmployee, ISalariedEmployee etc
Comment: I can move the Salary and Benefits to ISalariedEmployee and the HourlyRate to IPartTimeEmployee but still the question remains how can do i load the data to respective properites. I can check if the object returned from the factory class is a type of ISalariedEmployee or IPartTimeEmployee and set the values but again i introduce a logic that  checks for the type of object being returned in the service class. Am I thinking the right way?
Answer: What you can do is simply keep the employee type as String attribute in the Employee class , and add the types dynamically to the Employee class. I don't see the actual need of an Employee Type class here.
If you absolutely need such a class, declare it as a class and not an enum, and have a string attribute which will be the name of the type. After that with every new type you get from the query, initialize an new EmployeeType() and add that string with a setter. Then set that EmployeeType to the Employee class.
According to me that is a much better design because you won't need to hard code the string values in the enums.
And for the benefit thing, what you can do is have a benefits attribute to the concrete Employee class(or name it something else as you already have an abstract Employee). And set a value to the benefit only if the type of employee is salaried. That's how I would do it.
Comment: Thank you for your response. But I have a question. Since Benefits only apply to the salaried employee, I have to query the database to load the benefits of an employee and call the AddBenefit function; where as for hourly employee i do not have to do anything as benefits do not apply.  So if my service class has a function that returns all the employee how do i set all the values from the database. Employee being a abstract class so I need to pass the instance of Salaried or Hourly,
Comment: The code that I have is using a switch statement to check the instance works but I am looking for a better way to load the data as If I have to add more types of employee then I have to come back and modify the switch statement to handle it . Do this make sense?
Comment: What you can do is have a benefits attribute to the concrete Employee class(or name it something else as you already have an abstract Employee). And set a value to the benefit only if the type of employee is salaried. That's how I would do it.
Comment: Thank you Pritam but that is a work around. As for HourlyEmployee there are no benefits so moving benefits to abstract class does not make sense from a OOP stand point. If I move the benefit to abstract class then this property will be accessible to any class that inherits from Employee class. :-(
Comment: I see what you are saying. Then the only way is to create separate concrete classes for each of the types.
Comment: As I mentioned before the code I have works but I feel like some thing is missing here or can be improved. Lets say if I add ContractorEmployee as a type of employee  then I have to edit the service class to handle this type of employee by altering the switch statement. There has to be a better way to do this.
Comment: Instead of using switch you can use traditional factory patterns by changing it to if else loop. Otherwise I guess your approach is correct if you don't want to have the benefits attribute in the abstract class.


Expand {product.variations}

Question: In the product detail page I would like to display the price at the BOTTOM of the {product.variations}
Where can we alter the {product.variations} ?
Comment: Likely in a [preprocess function](https://drupalize.me/tutorial/what-are-preprocess-functions#:~:text=Preprocess%20functions%20allow%20Drupal%20themes,exposed%20through%20a%20preprocess%20function.)
Comment: @Clive, thanks. Can you guide on this particular issue? How would I move the price lower within {product.variations} using preprocess. See image https://drive.google.com/file/d/1fjxNTasnzMlivH9rmrJ9Wyo0FP597Tg7/view
Answer: Go to /admin/commerce/config/product-variation-types, click Edit on your product variation type, click the Manage Display tab, here you can change the order of the fields on whichever display mode you are using.
Comment: Thanks. But Moving the price at the bottom in Manage Display does not put it where I need. See this image: https://drive.google.com/open?id=1fjxNTasnzMlivH9rmrJ9Wyo0FP597Tg7&usp=drive_fs

Expand {product.variations}


YUI Compressor 2.4.7 - No class def error ErrorReporter

Question: I have a problem with the YUI Compressor for js: I've added version 2.4.7 to my build path in Eclipse ( tried with rhino jar and also without) - no effect whatsoever. I dont get compile errors, I can see the class I've created that implements org.mozilla.javascript.ErrorReporter, but when I try to run the compressor, I get:

java.lang.ClassNotFoundException: org.mozilla.javascript.ErrorReporter from BaseClassLoader@1d81fd2
Comment: How do you run the compressor?
Comment: I'm using it like this: JavaScriptCompressor compressor = new JavaScriptCompressor(br,new SystemOutErrorReport() );
compressor.compress(output, 1 << 20, false, false, false, false);
Comment: So you run it in eclipse project?
Comment: yes, this is what I am trying. I want to minify scripts on the fly, at runtime
Comment: The yuicompressor-2.4.7.jar I built contains org.mozilla.javascript.ErrorReporter class. So it you can use JavaScriptCompressor, you can use ErrorReporter too. Could you please check yuicompressor-2.4.7.jar?
Comment: yes, it is there. and yet i still get the error
Comment: tried also with 2.4.7. Same problem
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/26105/discussion-between-lhuang-and-iulia-muntianu)
Answer: I know this is an old question but I'm going to add an answer in case anyone else comes across this in a search.
I had the exact same problem.  The issue was that yuicompressor-2.4.7.jar wan't in our shared maven repository and so wasn't getting downloaded by the yuicompressor maven plugin.  To verify this check your local maven repository for the yuicompressor-2.4.7.jar (usually C:\Users\.m2\repository\com\yahoo\platform\yui\yuicompressor\2.4.7).  If it's there then you have a different issue if it's not then this could well be your issue.  To fix just upload yuicompressor-2.4.7.jar to your shared repository.


Consider the sequence 01110100...

Question: Consider the sequence 01110100 as being arranged in a circular pattern. Notice that every
one of the eight possible binary triples: 000, 001, 011, . . . , 111 appear exactly once in the circular list. Can you construct a similar list of length 16 where all the four binary digit patterns appear exactly once each?
Any ideas would be greatly appreciated.
Thank's.
Comment: Look for DeBruijn sequences or Huffman code.
Comment: Can you answer the first part of the question yourself? It just means writing out a list...
Comment: Induction?[filler]
Comment: @Thomas Andrews - yes, for the sequence 01110100 I've build already the list/table, but can't find a way how to construct a similar list of length 16...
Comment: @i. m. soloveichik - A Very Big Thank You  :)
Answer: This is called a De Bruijn sequence. Your example contains all possible 3-tuples of 2 symbols. De Bruijn sequences exist which contain all possible $n$-tuples of $k$ symbols.
Answer: How about this:
0000111101011001000|00001111...
where the bar is where it hooks back to itself.
Comment: Just looked up MJD link to DeBruijn. Seems there are lots, and the one Nikola gave is a bit different from that in my answer.
Answer: The following extremely straightforward C program can perhaps provide some insight into how these sequences are constructed. It first constructs the graph $G$ on $2^n$ vertices (the pattern is $n$ bits wide) of all possible patterns with a forward edge between two vertices $u$ and $v$ if the lower $n-1$ bits of $u$ match the upper $n-1$ bits of $v.$ Next the program builds Hamiltonian paths of $G$ and whenever it finds one, the sequence of nodes and of bits is displayed. Not difficult to adapt to different pattern sizes and alphabets. Compile with GCC and run from the command line with a single argument ($n$).

#include <stdio.h>
#include <stdlib.h>

typedef struct{
  unsigned int nb0, nb1;
} adjpair;

void backtrack(unsigned int n, unsigned int count,
               unsigned int *path,
               unsigned char *marks,
               adjpair *nbs, unsigned int pos)
{
  unsigned int m;

  if(pos==count-1){
    for(m=0; m<count; m++){
      printf("%d ", path[m]);
    }

    for(m=0; m<count; m++){
      printf("%c", ((path[m])>>(n-1))>0 ? '1' : '0');
    }

    printf("\n");

    return;
  }

  unsigned int cur = path[pos];
  if(!(marks[nbs[cur].nb0])){
    path[pos+1] = nbs[cur].nb0;

    marks[nbs[cur].nb0] = 1;
    backtrack(n, count, path, marks, nbs, pos+1);
    marks[nbs[cur].nb0] = 0;
  }
  if(!(marks[nbs[cur].nb1])){
    path[pos+1] = nbs[cur].nb1;

    marks[nbs[cur].nb1] = 1;
    backtrack(n, count, path, marks, nbs, pos+1);
    marks[nbs[cur].nb1] = 0;
  }
}

int main(int argc, char **argv){
  unsigned int n;

  if(argc!=2 || sscanf(argv[1], "%u", &n)!=1 ||
     n<1 || n>=256){
    fprintf(stderr, "positive integer expected\n");
    exit(-1);
  }

  unsigned int count = 1<<n;
  adjpair *nbs = (adjpair *)malloc(count*sizeof(adjpair));
  if(nbs == NULL){
    fprintf(stderr, "first malloc failed\n");
    exit(-2);
  }

  unsigned char *marks =
    (unsigned char *)malloc(count*sizeof(unsigned char));
  if(marks == NULL){
    fprintf(stderr, "second malloc failed\n");
    exit(-3);
  }

  unsigned int *path =
    (unsigned int *)malloc(count*sizeof(unsigned int));
  if(path == NULL){
    fprintf(stderr, "third malloc failed\n");
    exit(-4);
  }

  unsigned int m;
  for(m=0; m<count; m++){
    marks[m] = 0;
  }

  for(m=0; m<count; m++){
    nbs[m].nb0 = (m & ((1<<(n-1))-1))<<1;
    nbs[m].nb1 = nbs[m].nb0+1;
  }

  marks[0] = 1; path[0] = 0;
  backtrack(n, count, path, marks, nbs, 0);

  free(nbs);
  free(marks);
  free(path);

  exit(0);
}

Consider the sequence 01110100...


PostgreSQL Performance check

Question: I have heard PostgreSQL being used in cases where the tables run into billion of rows and having satisfactory response times too. But here's my simple experiment to check this out. I have a table with 6 columns and has 4255700 entries exactly. I have used pgtune to tune the configuration according to my setup. Now, when I run a simple "*select * from tab1*", it is taking 173.425 seconds to fetch all the rows. Is this the normal behavior? I have this single table in the DB.
The table definition is as follows -
CREATE TABLE file_group_permissions
(
  fgp_id serial NOT NULL,
  file_id integer NOT NULL,
  pg_id integer NOT NULL,
  policy_id integer,
  tag_id integer,
  inst_id integer,
  CONSTRAINT file_group_permissions_pkey PRIMARY KEY (fgp_id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE file_group_permissions
  OWNER TO sa;

-- Index: fgp_file_idx

-- DROP INDEX fgp_file_idx;

CREATE INDEX fgp_file_idx
  ON file_group_permissions
  USING btree
  (file_id);
ALTER TABLE file_group_permissions CLUSTER ON fgp_file_idx;

-- Index: fgp_inst_idx

-- DROP INDEX fgp_inst_idx;

CREATE INDEX fgp_inst_idx
  ON file_group_permissions
  USING btree
  (inst_id);

-- Index: fgp_tag_idx

-- DROP INDEX fgp_tag_idx;

CREATE INDEX fgp_tag_idx
  ON file_group_permissions
  USING btree
  (tag_id);

-- Index: pgfgp_idx

-- DROP INDEX pgfgp_idx;

CREATE INDEX pgfgp_idx
  ON file_group_permissions
  USING btree
  (pg_id);

Output of EXPLAIN (ANALYZE, BUFFERS) select * from file_group_permissions -
"Seq Scan on file_group_permissions  (cost=0.00..69662.00 rows=4255700
width=24) (actual time=0.019..580.273 rows=4255700 loops=1)"

"  Buffers: shared hit=2432 read=24673"

"Planning time: 0.070 ms"

"Execution time: 903.325 ms"

I have a MacBook Pro with 16 Gigs of RAM and 512 Gigs of SSD. I have configured the PostgreSQL to use 2Gigs of RAM.
Edit
EXPLAIN (ANALYZE, BUFFERS) select pg_id, count(distinct file_id) from file_group_permissions where pg_id in (6117,6115,6116,6113,6114) group by 1;

"GroupAggregate  (cost=0.44..102028.21 rows=208 width=8) (actual time=4970.884..5013.423 rows=3 loops=1)"
"  Group Key: pg_id"
"  Buffers: shared hit=50891, temp read=4824 written=4824"
"  ->  Index Scan using pgfgp_idx on file_group_permissions (cost=0.44..85511.31 rows=3302964 width=8) (actual time=0.062..1080.926 rows=3323389 loops=1)"
"        Index Cond: (pg_id = ANY('{6117,6115,6116,6113,6114}'::integer[]))"
"        Buffers: shared hit=50891"
"Planning time: 0.219 ms"
"Execution time: 5013.495 ms"

EDIT1
I separated this table into a new DB and followed the suggestions (composite indices and postgresql conf), here's the new plan -
"GroupAggregate  (cost=478307.10..502996.67 rows=209 width=8) (actual
time=7500.426..7528.021 rows=3 loops=1)"

"  Group Key: pg_id"

"  Buffers: shared read=27105, temp read=12137 written=12137"

"  ->  Sort  (cost=478307.10..486536.26 rows=3291664 width=8) (actual
time=2944.597..3647.248 rows=3323389 loops=1)"

"        Sort Key: pg_id"

"        Sort Method: external sort  Disk: 58488kB"

"        Buffers: shared read=27105, temp read=7311 written=7311"

"        ->  Seq Scan on file_group_permissions  (cost=0.00..96260.12
rows=3291664 width=8) (actual time=0.016..1516.743 rows=3323389 loops=1)"

"              Filter: (pg_id = ANY
('{6117,6115,6116,6113,6114}'::integer[]))"

"              Rows Removed by Filter: 932311"

"              Buffers: shared read=27105"

"Planning time: 0.514 ms"

"Execution time: 7540.243 ms"

This table is simply jinxed and it is hurting the performance everywhere it is being joined.
Comment: Transferring 4255700 rows from the server to the client **will** take some time. After all that's roughly 200MB that need to be sent, received and processed (and potentially displayed) by your client software.
Comment: Doing a "SELECT * FROM TABLE" is definitively the worst way of bench-marking a Postgres server. It tells you absolutely nothing about hardware performance or database tuning.  pgtune website is a good start, but you surely have to read more about all postgresql.conf parameters. A good example is the `random_page_cost` when your database fits entirely into RAM or when using fast SSD hard-disks.
Comment: This question seems more suited for [dba.se].
Comment: @a_horse_with_no_name I understand, but 173 seconds?? There must be an answer for that.
Comment: Those could be a lot of reasons, slow network, slow client, slow harddisk. There is not enough information to be able to answer your question. Please read: http://wiki.postgresql.org/wiki/SlowQueryQuestions and supply the missing information
Comment: @a_horse_with_no_name Sorry, for the incomplete info, I am using the local machine to do this and updated all other details.
Comment: All you are testing with this, is the performance of your SQL client. It says absolutely nothing about the performance of the Postgres server (plus: a `select * from some_table` is hardly a meaningful test in itself anyway).
Comment: @ChristianB.Almeida I did this preposterous benchmark test using a "select *" because I tried so many things, but queries around this table return in more than 5 seconds, included a sample query in the question. I already have the random_page_cost set to 1.0
Answer: I have created a test table, just like yours, and I have populated it with exactly same amount of records:
insert into file_group_permissions (file_id,pg_id,policy_id,tag_id,inst_id)
select
  trunc(random()*10000) as file_id,
  trunc(random()*10000) as pg_id,
  trunc(random()*10000) as policy_id,
  trunc(random()*10000) as tag_id,
  trunc(random()*10000) as inst_id
from generate_series(1,4255700) g

When I run your query, it executes pretty fast:
EXPLAIN (ANALYZE, BUFFERS)
select pg_id, count(distinct file_id)
from file_group_permissions
where pg_id in (6117,6115,6116,6113,6114) group by 1;

GroupAggregate  (cost=0.43..8.32 rows=5 width=8) (actual time=0.339..1.608 rows=5 loops=1)
  Buffers: shared hit=2158
  ->  Index Scan using pgfgp_idx on file_group_permissions  (cost=0.43..8.24 rows=5 width=8) (actual time=0.018..1.170 rows=2147 loops=1)
        Index Cond: (pg_id = ANY ('{6117,6115,6116,6113,6114}'::integer[]))
        Buffers: shared hit=2158
Total runtime: 1.633 ms

I have notice this line in your execution plan:
Buffers: shared hit=50891, temp read=4824 written=4824

temp read=4824 written=4824 tells us that the database is "using" disk somehow to perform the scan operation. Perhaps you have to tweak some other postgresql.conf parameters, like these of mine:
shared_buffers       = 1GB
temp_buffers         = 32MB
work_mem             = 32MB
effective_cache_size = 1GB

Comment: Posted my new results with all the suggestions in mind.
Comment: And guys, you don't have any data matching in the table, so the query is super fast.
Comment: I do have matching data. Try to cluster the table to the pg_id index.

PostgreSQL Performance check


Object undefined in jquery, plus my links are pointing elsewhere

Question: I asked this question on stackoverflow earlier, not realizing this site existed.  Seems that this would be a better place for it.
In a nutshell, I've restored an existing drupal 7 site under the public_html/migrated_site folder on my hosted site.
When I browse that URL however I'm getting errors from jquery that the Drupal object doesn't exist, and all my links and images point to public_html/migrated_site/sites/someothersite...
..where someothersite is the name of the old subdierctory under public_html on the prior host.
I changed my settings.conf values to point to the migrated MySQL database, and that bit appears to have worked, in that the site is coming up, albeit unstyled and with the above jQuery and links errors.
However I'm not sure what could be going on above?  I've tried a few RewriteBase settings in .htaccess in both public_html and public_html/migrated_site (particularly, adding RewriteBase /~hisusersite/migrated_site) but nothing seems to have made a difference.
Comment: In addition to the RewriteBase, you'll want to set $base_url in settings.php. Note that for RewriteBase, it's relative to the URI, so you'd just use RewriteBase /migrated_site , and $base_url = '//whatever.com/migrated_site';
Answer: The Drupal JS object not being defined is a symptom of it not loading core JS files. His previous site probably enabled JS aggregation that places the aggregated file in sites/someothersite/files/XXX.js. The same goes for the missing images. Have you copied over sites/someothersite/ from the previous host?
It sounds like sites/someothersite/settings.php was what his original host was using and configured for DB & files. Since you're now viewing the site on  gator1111.hostgator.com Drupal is using sites/default/settings.php.
This primer on drupal multi-site settings might help to also explain what's going on.
Comment: Another thing I would check is .htaccess rules for **RewriteBase**, since you're moving the site to a subdir. Drupal gets wonky sometimes when you do that. Try setting it to **/~hisusername/migrated_site**
Comment: Thanks for your help.  The 'CSS/JS aggregated file gzip compression' setting in `settings.php` is set to 'off' and I did copy all the js files (in `files/js`) from the previous host over to this one.
I also renamed the folder from 'migrated_site' to 'default' but that didn't change anything.


I have a points and I need to find the function

Question: I have these points:
<code>(1,      256071764)
(6,      71020138)
(1469,   582701)
(1550,   421823)
(50752,  8546)
(65031,  5282)
(94961,  5341)
(411573, 2670)
</code>
I need to find a function satisfying this like f(x)=....
Thank you very much.
Comment: There are infinite functions that go through those points. You need to give more context. The numbers are weird, I take it this is statistics related. That's important context...
Comment: Chebycheff-interpolation should give a good result.
Comment: In the concrete case, hyperbel functions of the form $\frac{c}{x}$ might be a better approach.
Comment: Must the points be hit exactly, or only approximately ?
Comment: The points are exactly, I need the function f(x)=... for find more points.
Answer: Denote $(x_i, y_i)$ with $(i=1,2,...,8)$ the 8 points in the main text.
Following the suggestions in the comments, for 8 points $(\ln x_i, \ln y_i)$, we may fit with a straight line (using Mathematica for example):
$$\ln y= 19.6533 - 0.947791 \ln x$$
Thus one candidate of the function $f(x)$ that you are searching for is:
$$y(x)= \exp(19.6533 - 0.947791 \ln x)$$
Here is a snapshot $\ln x_i$ vs.\ln y_i$ plot of the data with the resulting fit fucntion.
Comment: Thanks very much! Is that what I needed! Thanks a lot!
Answer: I think that you want to use a Fit-Function. This requires that you have some knowledge about your data. What do you expect the data to be? This defines you the Trial-Function, and your free parameters which will be optimized. You will get a $\chi^2$-value, which tells you the quality of the fit.
Another method is to use Interpolation, which will find a (polynomial) function that goes through all off your data-points.
If you explain better what you want, you might get better answers here.
Comment: I need the function f(x)=... for find more points, but I don't know how...
Comment: Do you require that your function f(x) goes exactly through all of your data-points, or do you want a nice function that is approximatively defined by the data-points. If thats the case, you can use Interpolation (see the link I posted). The second option (fitting) requires you to have previous knowledge about your data-points (like their distribution).
Answer: Your question, as it stands, has infinitely many solutions that we can't distinguish unless you explain what you have in mind. Just plot your points, pick a pen and connect them with straight lines; then draw any function on the left of the first point and on the right of the last point. Et voilà, you have a function!
Interpolation is useful only if you have some additional constraints. Consider the three points $(0,1)$, $(1,1)$ and $(2,1)$. The constant function $x \mapsto 1$ interpolates them, but you can also change it arbitrarily for $x<0$ and $x>2$. Which interpolating function should you choose? The answer usually comes from concrete expectations.


iOS - Overlay UIImage with color on non-transparent area only?

Question: I have a white image with transparent area in the middle like this:

I want to overlay it with colour (non-transparent area only) so it looks like this:

How can I do this?
I have looked into this answer but it overlay the whole image including the non-transparent area.
Answer: So your image is effectively a "mask". Play around with the "CGContextClipToMask" call and the above code that you referenced.
Answer: Try the following code and it gives the exact what you want.
<code>    UIGraphicsBeginImageContextWithOptions(imgView.image.size, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
    CGContextFillRect(context, (CGRect){ {0,0}, imgView.image.size} );

    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, imgView.image.size.height);
    CGContextConcatCTM(context, flipVertical);
    CGContextDrawImage(context, (CGRect){ {0,0}, imgView.image.size }, [imgView.image CGImage]);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [imgView setImage:image];
</code>


Solving $Y_t$ = $e^{-\alpha t}X_t$ using Ito's lemma

Question: G'day
I am trying to solve $Y_t$ = $e^{-\alpha t}X_t$, where $dX_t = \alpha X_tdt + \sigma_tdW_t$ using Ito's lemma.

Defining f(t, X) = $e^{-\alpha t}X$. $\frac{df(t,X)}{dt}$ = $-\alpha e^{-\alpha t}X$;  $\frac{df(t,X)}{dX}$ = $e^{-\alpha t}$.
Using Ito's lemma:
$dY_t = -\alpha e^{-\alpha t}X_t(dt) +  e^{-\alpha t}(dX_t)$
Substituting dt and dXt gives:
= $-\alpha e^{-\alpha t}X_t( \alpha X_tdt) + e^{-\alpha t}(\alpha X_tdt + \sigma_tdW_t$)
Calculating: $e^{-\alpha t}(\alpha X_tdt + \sigma_tdW_t)$ = $\alpha e^{-\alpha t}dt + \sigma_t e^{-\alpha t}dW_t$
Moving in to the first part where I think the problem lies in finding the solution:
$-\alpha e^{-\alpha t}X_t( \alpha X_tdt)$ = $- \alpha^2 e^{-\alpha}X^{2}_tdt$. I think that this step is wrong because no matter what I do, I can't seem to conclude with the given solution:
= $\sigma_t e^{-\alpha t}dW_t$

Can someone explain the last steps and finish what I started?
Answer: I'm not quite following your derivation, but on the fourth line, I don't see how/why you are replacing $dt$ with $\alpha X_{t} dt$ and on the fifth line, when you multiply out the factor, it looks like $X_{t}$ is lost in the first term.  I hope this helps.
Comment: @sc_ams: The answer to your first question is 'Yes'. I don't understand your second question. In the line you say: "Using Ito's lemma", you only have to substitute $dX_t,$ the term 'dt' is just 'dt'.
Comment: @sc_ams: yes, exactly.
Comment: Yes: $-\alpha e^{-\alpha t}X_t( \alpha X_tdt)$ should be only $-\alpha e^{-\alpha t}X_t(dt)$ right? Can you explain why we don't need to to multiply with the first term as there is a dt in it? Yes, regarding the lost term X, it helps. If you can explain my misconception of $\alpha X_tdt$ versus $dt$ this question is solved.
Comment: @UBM, so when taking the derivative with respect to t, you don't have to substitute any term? Ever? Just multiple with ${dt}$ and that's it?


Partial derivatives chain rule (calculus II)

Question: I was doing some exercises and I came upon this one. I have been thinking about for quite some time, but I'm still not sure about the answer. Any help would be gladly appreciated.

This is what I have tried:

Is this correct?
Comment: You are more likely to get an answer if you type out the question and your solution using [mathjax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: I've voted to reopen your question, because you're a new user, but next time use MathJax as you were instructed to on the ask-a-question page.
Comment: What have you tried Mr. Creeper?
Comment: Hey, I just uploaded what I have tried so far
Comment: A reference for MathJax for what it's worth - https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: Rewrite $$\frac{\partial z}{\partial x}=\frac{\partial z}{\partial u}\frac{\partial u}{\partial x}+\frac{\partial z}{\partial v}\frac{\partial v}{\partial x}=2x \frac{\partial z}{\partial u}+2y \frac{\partial z}{\partial v}.$$
(Similarly for $\frac{\partial z}{\partial y}$.)
This results in $$2(x^2-y^2)\frac{\partial z}{\partial u}=0.$$
So, the transformed differential equation is $$\frac{\partial \, z(u,v)}{\partial u}=0.$$
Comment: Because you want to transform the differential equation from $x, y$ to $u, v$. So at the end, there should be an expression only containing $u$ and $v$.
Comment: Yes, I did try that. But I do not know for certain if its the right approach. Its that correct?
Comment: Yes. I have edited my answer and included one more step. What can you conclude?
Comment: Yes I reached that same conclusion, so I guess its correct right?
Comment: You still have to get rid of the $x$ and $y$ :) I have edited the post and included the answer. Can you explain why we can leave out the $2(x^2-y^2)$?
Comment: Yes, I understand what you did. But why exactly do I have to get rid of x and y?
Comment: Ohh, okay. Thank you very much!


Difference between left censoring and interval censoring

Question: I'm dealing with some medical data which is made up of all admissions to hospital in a certain area, where each row is one patient admission alongside the various tests and demographic data done. Also some patients have multiple admissions.
To model the data I am using a joint model for survival analysis, with the outcome being a patient being diagnosed with dementia. I have two questions regarding the correct use of censoring in mainly Cox regression. For each patient I class $time = 0$ as their first admission to hospital.

If a patient turns up on their first admission, and already has dementia, I currently just exclude them from the analysis. Does this however count as left censoring, and can I include them if I change the way I measure time? Currently this would be assuming that they got dementia at negative time. I'm only considering old age patients, so I thought I could maybe choose time = 0 to be 65 years of age etc. That would avoid the negative time problem but feels wrong or just a quick fix.

What is the difference between interval and left censoring? As far as I understand, interval censoring assumes the event happens within an interval $[t_{1},t_{2}]$ but we don't know exactly when. Whereas left censoring assumes we just know the event happens before a time $t$. However isn't this just the same as knowing the event happened within the interval $[0,t]$?

Most sources seem to say the same things about left and interval censoring, so any advice would be great.
Answer: With respect to Question 2, Klein and Moeschberger explain in Section 3.3:

Of course, interval censoring is a generalization of left and right censoring because, when the left end point is 0 and the right end point is $C_l$ we have left censoring and, when the left end point is $C_r$ and the right end point is infinite, we have right censoring.

With respect to Question 1, when you omit individuals who first present with the dementia diagnosis you are effectively left truncating your observations. Your analysis is conditional on an individual not already having experienced the event. You are including no information about those who already had the event. From the perspective of that analysis, it's like such individuals didn't even exist.
From your description, using a fixed chronological age* as the time reference instead of the first hospital admission would seem to make a lot of sense. Then you can include those who first present with dementia as having left-censored event times and include them in the analysis. There's nothing wrong with that, and a strong argument could be made that it would be preferable in a situation like this. There's a good deal of interest in the age at which dementia is diagnosed, while I don't see a reason to care so much about how soon it occurs after a first hospital admission (of possibly several), an admission that might be for an unrelated condition.
Note, however, that even then you are analyzing the dementia diagnosis time conditional upon an individual being admitted to the hospital. You are omitting anyone with dementia in the study area who doesn't happen to be admitted to a hospital.

*Even a reference of time = 0 at birth would be OK for a Cox model, as a Cox model only evaluates the order of event times, not the event times per se. Then you don't have to worry about someone with early-onset dementia forcing you to re-set the time reference later on.
Comment: @JPiekos I haven't thought this through completely, but you might still include age at first admission as a predictor. You probably _should_ include the calendar date/year of first admission as a predictor, to allow for changes in incidence/diagnosis rates over calendar time. Whenever I get confused about censoring/truncation, I find that Klein and Moeschberger point me in the correct direction. Read their sections on left truncated survival times for further guidance.
Comment: I actually went to that exact book and found said section 3.3, so thank you for that. The issue with my dataset, is that it is only made up of hospital admissions. I get rid of 10,000+ patients by my current pipeline, so it's good to know I can include them.

I think I'll try out a fixed age, and also birth as a reference time and see what happens. Thank you!
Comment: If I used time from birth, would that mean I am no longer able to use age as a predictor anywhere? Although would this be fine, since that is all now contained in the survival time?
Comment: thanks a lot, and yes the Klein and Moeschberge book I'm realising is very good.


Merge ascii char using C

Question:
I tried the following code but couldn't get the desired output.
Result should be AB and it should come from single variable C

int main()
{
  int a = 'A';
  int b = 'B';
  unsigned  int C = a << 8 | b;
  printf(" %c\n",C);
  return 0;
}```
</code>
Comment: Don't ask the same question twice!
Comment: Please do not post images of code - [reasoning](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question). Please post it as formatted text.
Comment: `%c` will only ever read one char/byte. Do you really need/want to use bit shifting for this? `int C = 'AB'` is not valid code. So it is not clear exactly what is the desired result.
Comment: NOTE: 01000001 is 0x41  Not 0x1000 and   01000010 is 0x42 NOT 0x2000
Comment: regarding: `int a = 'A';
  int b = 'B';`  these should be declared as `unsigned` not `int`
Comment: @jonathan, the answer wasn't satisfactory and this maybe be quite similar question but it's not.
Comment: @user3229249, the output should be taken out from one variable otherwise i would've done something like ```printf("%c%c", a,b);```
Answer: <code>%c</code> will print a single character. If you want to print a string, you have to use <code>%s</code> and provide a pointer to this string. Strings in C have to be null-terminated, meaning they require one additional character after the text and this character carries the value <code>\0</code> (zero).
You could do this in an <code>int</code>, but you'd have to understand some concepts first.
If you are using a computer with Intel architecture, integer variables larger than one byte will store data in reverse order in memory. This is called little-endianness.
So a number like <code>0x11223344</code> (hexadecimal) will be stored in memory as the sequence of bytes <code>44 33 22 11</code>.
<code>'A'</code> is equivalent to the number 65, or <code>0x00000041</code>, and if put in a 32-bit integer will be stored as <code>41 00 00 00</code>.
When you do <code>'A' << 8 | 'B'</code> you create the number <code>0x00006566</code>, but in memory it is actually <code>66 65 00 00</code> (equivalent to string <code>"BA\0\0"</code>). It's in the opposite order of what you're trying to do, but since it is technically null-terminated, it's a valid string.
You can print this using <code>sprintf("%s", &C);</code>
If you're in a big-endian architecture (such as ARM), you will have to work out the null-terminator, but I think I already gave you enough information to figure out what is going on for yourself.
Comment: using ```%s``` giving me segmentation fault.
Comment: You are probably providing an invalid pointer. You have to pass `&C` as parameter (a pointer to `C`), not `C` itself.
Comment: ```#include
int main()
{
  int a = 'A';
  int b = 'B';
  unsigned  char C = a << 8 | b;
  printf(" %c",C);
  return 0;
}```
Comment: Again, use `sprintf("%s", &C)` instead.
Answer: you're trying to print only single byte located at &C, so depending on if you're machine is little endian you'd get "66" as output or if you're machine is big endian you'd get 0 as output.
Comment: Your answer does not address this part of the question: "Result should be AB and it should come from single variable C"
Comment: I want ```AB``` in the output. Please tell me required changes.
Comment: one way to get AB as output would be to use something like printf("%c%c", *((unsigned char *)&C)+1), C);
Comment: @raqeeb, the output should be taken out from one variable otherwise i would've done something like ```printf("%c%c", a,b);```
Comment: C = b << 8 | a; printf("%s",&C); that would work.
Comment: No it's not working

Merge ascii char using C


Como executar um comando VBA numa folha com nome especifico?

Question: Tenho um documento de Excel com várias folhas. Nesse documento preciso executar um comando numa folha especifica, ou seja pelo nome da folha. Mas se essa folha não existir executar outro comando numa outra folha com nome especifico até acabar as folhas.
Exemplo:
Sub adicionar_categorias()

folhas = Array ("FOLHA 1", "FOLHA 2", "FOLHA 3")

For i = LBound(folhas) To UBound(folhas)
Worksheets(folhas(i)).Activate

Range("X2").Select
ActiveCell.FormulaR1C1 = "Computadores>Portáteis"
Lastrow = Range("A" & Rows.Count).End(xlUp).Row
Range("X2").AutoFill Destination:=Range("X2:X" & Lastrow)

Next i
End Sub

Se a folha não estiver no livro vai dar erro Worksheets(folhas(i)).Activate! Como resolver o erro?
RESOLVIDO: On Error Resume Next
Sub adicionar_categorias()

folhas = Array ("FOLHA 1", "FOLHA 2", "FOLHA 3")
On Error Resume Next
For i = LBound(folhas) To UBound(folhas)
Worksheets(folhas(i)).Activate

Range("X2").Select
ActiveCell.FormulaR1C1 = "Computadores>Portáteis"
Lastrow = Range("A" & Rows.Count).End(xlUp).Row
Range("X2").AutoFill Destination:=Range("X2:X" & Lastrow)

Next i
End Sub

Obrigado "dot.Py!
Answer: De acordo com a documentação, pode chamar o método .Activate, que é equivalente a clicar na guia da planilha nomeada como "Plan1" na sua pasta de trabalho.
Worksheets("Plan1").Activate

Ao invés de referenciar pelo nome, pode referenciar pela posição da aba na sua pasta de trabalho, como por exemplo:
Worksheets(0).Activate
Worksheets(1).Activate
Worksheets(2).Activate

Onde numa pasta de trabalho recém-criada, a Worksheets(0) equivale à Plan1, a Worksheets(1) à Plan2 e a Worksheets(2) à Plan3.
Lembrando que se alterar a ordem das abas manualmente, apesar de o nome não mudar, a posição mudará...

Pode também criar uma array com os nomes das planilhas que deseja ativar, e rodar um for para cada item dentro desse array.
planilhas = ("plan1", "plan2", "plan3", "plan4")

For i = 1 to UBound(planilhas)
    Worksheets(planilhas(i)).Activate
Next i

Para melhorar esse código, você pode acoplar um try/catch/finally ou um On Error Resume Next p/ que o programa saiba o que fazer quando a aba existe, e o que fazer quando não.
Comment: Obrigado pelo seu comentário dot.Py!
Comment: Sim, mas e se a folha não existir. Como é que resolvo o erro e continuo o loop?


What number of minimum overs bowled makes an ODI cricket match goes in record books?

Question: For example, a scheduled ODI 50 overs match has been reduced to 10 overs or 15 overs due to rain, and a bowler takes a hat trick in those reduced overs. Will that record or any other made or achieved such a record will go on to the record books or not?
So my basic question remains, how many minimum overs are required for a one day match to be recorded as a full one day international match?
Answer: From Toss (cricket) - Wikipedia

If the match is abandoned at any time after the toss, it stands as a match played and enters official statistical records. If a match is abandoned before the toss, it is not considered to have been played at all, and does not count for records.

So in cricket once the coin is tossed, the match is considered as a match played and enters official statistics. So if the match is abandoned after few overs say 10 or 15 it goes to official records. And there is no minimum overs requires to enter official statistics.
For a match to be considered as a completed match (unlike draw), each team must face 20 overs in One Day matches and 5 overs in Twenty20 matches before D/L method decide the result.
(Source: Duckworth-Lewis method - Wikipedia)
Answer: The minimum that needs to be bowled for the game to constitute an official match is one ball. If the toss is completed but one ball is not bowled, the game is recorded as 'match abandoned without a ball bowled', but players still get credited with an appearance. Games called off before the toss are also recorded as 'abandoned without a ball bowled', but the players do not get awarded with an appearance.
The 20-over figure thrown around is the minimum number of overs required for a result, ie win, loss, tie or draw, using Duckworth-Lewis in one day internationals, however 'no-result' (games lasting under the required 20 overs) and 'abandoned' matches are both legitimate ways to end a match and therefore count in official records.
Comment: Welcome to SE.Sport. The answer is interesting when you are able to add any official references
Answer: 20 overs per side for an ODI match,  6 overs per side for a T20 match.
Comment: @hims056 - particularly for a (potential) new user that is rather poor.
Comment: Why the downvote?  It would be nice to have a reference, but to drop a downvote without a comment?
Comment: @iandotkelly: Basically downvote means wrong/unresearched answer. Not every downvote requires a comment. #NotMyDownvote
Comment: @iandotkelly - You are correct. At least downvote on new user's post requires a comment since they may not know how things work on Stack Exchange.


Why is this definition of probability well defined

Question: Let $A=\bigcup_{i=1}^n (a_i,b_i]\subset(0,1]$ where $(a_i,b_i]$ are disjoint. I define a function $P (A)=\sum_{i=1}^n (b_i-a_i) $. I wish to prove that $P (A )$ is well defined in the sense that if there is some other way to represent $A $ as a finite union of disjoint intervals the same value of $P (A) $ results.
My book claims that this follows from the fact that if $A,B $ are disjoint then $P (A\cup B) =P (A)+P (B) $. I don't quite see how though.
Comment: @JackM $A$ represents a general input; for any $A=\bigsqcup (a_i,b_i]$, $P(A)$ is defined as written, and you must show $P$ is well defined.
Comment: Your question doesn't make sense. You haven't defined a function $P$, you just wrote down the value of $P$ for one input, $A$.
Comment: Exactly. We have to prove that given any other input for the same A the same value of P results.
Answer: I think I have discovered the answer: Given any representation of $A$ as a finite disjoint union of intervals (all of the type (a,b]) the Riemann integration of the indicator function will be the sum of the interval lengths and hence $P(A)$. For any other such representation since the Riemann integration of the indicator function would not change so  $P(A)$ would not either.


Prove : $\arctan(x)>\tanh(x)$ for $0< x\leq 1$

Question: It's a classical inequality that I want to propose :
Claim:

Let $0< x\leq 1$ then we have :
$$\arctan(x)>\tanh(x)$$

My proof :
We introduce the function :
$$f(x)=\arctan(x)-\tanh(x)$$
We differentiate :
$$f'(x)=\frac{1}{(x^2+1)}+\frac{-4}{(e^{-x} + e^{x})^2}$$
Remains to show :
$$\frac{(e^{-x} + e^{x})^2}{4}\geq x^2+1\quad \quad (0)$$
Or :
$$-\frac{1}{2}+\frac{e^{-2x}}{4}+\frac{e^{2x}}{4}-x^2\geq 0$$
We introduce the function :
$$g(x)=-\frac{1}{2}+\frac{e^{-2x}}{4}+\frac{e^{2x}}{4}-x^2$$
We differentiate twice :
$$g''(x)=e^{-2x}+e^{2x}-2\geq 0$$
We deduce that the first derivative of $g(x)$ is increasing and $g'(0)=0$ so $g(x)$ is increasing but $g(0)=0$ so we establish the inequality $(0)$ . We conclude that the function $f(x)$ is increasing and $f(0)=0$ wich prove the claim .
My question :
Have you one or more alternative proof (using integration by example)?
Thanks in advance !
Erik
Comment: The Taylor series of $\tan\tanh x$ is $x-x^5/15+\mathcal O(x^7)<x$ so $\tanh x<\arctan x$.
Comment: @TheSimpliFire: That proves the inequality only for small $x$, unless you have an quantitative estimate for the error term.
Comment: @TheSimpliFire Well I don't think to that but it's a very direct way . Thanks !
Answer: Note $\sinh t-t>0$ and
\begin{align}
\arctan x-\tanh x & =\int_0^x \left(\frac{1}{t^2+1}-\frac{1}{\cosh^2 t}\right)dt\\
&= \int_0^x \frac{(\sinh t +t)(\sinh t-t)}{(t^2+1)\cosh^2 t}dt>0
\end{align}
Thus, $\arctan x>\tanh x$.
Answer: For all $u$,
$$
\sin^2(u)\le u^2\implies\cos^2(u)\ge1-u^2\implies\sec^2(u)\left(1-u^2\right)\le1\tag1
$$
Set $u=\tanh(x)$:
$$\newcommand{\sech}{\operatorname{sech}}
\begin{align}
\frac{\mathrm{d}}{\mathrm{d}x}\tan(\tanh(x))
&=\sec^2(\tanh(x))\sech^2(x)\tag{2a}\\
&=\sec^2(\tanh(x))\left(1-\tanh^2(x)\right)\tag{2b}\\[3pt]
&\le1\tag{2c}
\end{align}
$$
Thus, for $x\ge0$, the Mean Value Theorem says
$$
\tan(\tanh(x))\le x\tag3
$$
Therefore, because $\arctan(x)$ is increasing,
$$
\tanh(x)\le\arctan(x)\tag4
$$


Train listening to notes coming out of my trumpet

Question: I'm with an old trumpet that sold me in Si Bemol(Bb), I'm still learning, and my biggest difficulty in music is being able to be constant in the sounds that come out of me, to reproduce them when I want and not randomly, that is, my ear does not make a difference very well the notes, and with that I can not reproduce, so I decided to train my problem using an online tuner:
https://www.flutetunes.com/tuner/
The problem is that I do not know if training with him is according to my trumpet, and I may be training wrong, which would be bad. If not is  according, can recommend me one so that I can train to hear the sounds coming out of me.
Comment: Si bemol is what the French call Bb.
Answer: It is not the way forward. You need to train your ears to listen to the notes properly. Get a cheap keyboard - which will be in tune, and listen to the different notes, and how they work with each other. It will take some time to get good, pure, in tune notes on your trumpet, but using an app or tuner is not the normal way to go.
Comment: I'm following your tip, using https://virtualpiano.net/, I was able to be constant in 3 notes with my voice, which I could not before, training listening to them and checking on https://www.flutetunes.com/tuner/ if I'm doing it right. Thanks for the tip.
Comment: but how do I check if they are correct? I can be making a sound and another coming out and hearing wrong.
Answer: you absolutely MUST take some lessons.  You don't even know, right now, whether you are breathing correctly, setting your lips correctly, etc.  Without someone to observe and teach, you may end up generating the incorrect over-or under-tones.


To find actors who were never unemployed for more than 3 years in a stretch

Question: I'm suppose to find the actors that were never unemployed for more than 3 years at a stretch. (Assume that the actors remain unemployed between two consecutive movies).
The M_cast represents the actors and person table has the name of the actor and the movie table has the year column.
SQL code:

SELECT a.Name, c.year
FROM Person a
Inner Join M_cast b
ON a.PID = b.PID
Inner Join Movie c
ON c.MID = b.MID

This would give us all the actor name and the various years they worked , however, I'm not sure how to check if the an actor worked for 3 years in a row or not. Would appreciate your insights on this. If a similar question was asked anywhere else, please point me in the right direction.
Comment: So can you see that you're effectively looking for all actors missing from a certain query
Comment: if you don't have mysql 8 You have to loop through all all Sorted byanme and year  results and check the years of every actor. This you can do in a stored procedure or in php javasript and so on
Answer: So you've got the Actors, Movies (Work), and the Year for each of the Movies. My approach to this would be to use the LEAD() function to add a new column next_year.
A bit of background on the function:

LEAD() is a window function that provides access to a row at a specified physical offset which follows the current row.
For example, by using the LEAD() function, from the current row, you can access data of the next row, or the row after the next row, and so on.
The LEAD() function can be very useful for comparing the value of the current row with the value of the following row.
The following shows the syntax of the LEAD() function:

LEAD(return_value ,offset [,default])
OVER (
    [PARTITION BY partition_expression, ... ]
    ORDER BY sort_expression [ASC | DESC], ...
)

Example use:
SELECT *
, LEAD(year, 1, 0) OVER (PARTITION BY Name ORDER BY year ASC) AS next_year
FROM (yourJoinedTable)

Using (next_year - year) AS gap you can create a column of gaps between movies (years unemployed). Finally, find the MAX(gap) for each actor and filter those actors out which have a MAX(gap) of ≤ 3. This should leave you with only actors that have no more than 3 years between movies.
Hope this helps!


Drupal 8 missing filter view schema

Question: After run unit tests i am getting fail
Schema errors for views.view.example_form_element with the following errors: views.view.example_form_element:display.default.display_options.filters.my_module.expose.example_element missing schema

I understand the error but i can't solve it. I tried a lot of combinations of schema.yml file name and content but without success result.
I will point out, that module name is

my_modules

but

example_element

is under

my_module

current file looks like
file config/schema/my_modules.views.schema.yml
views.filter.views_example_element:
  type: views_filter
  label: 'xxx'
  mapping:
    expose:
      type: mapping
      label: 'Exposed'
      mapping:
        example_element:
          type: integer
          label: 'xxx'

file Plugin/views/filter/ViewsExampleElement
@ViewsFilter("views_example_element")

What is wrong with it?
Answer: Try change in my_modules.views.schema.yml type on views.filter.many_to_one
Comment: Still doesn't work. Of course i rebuild cache after each iteration.
Comment: can this option work for you [custom-views-filter](https://www.webomelette.com/creating-custom-views-filter-drupal-8)?
Comment: I read this article before and comments bellow containing informations about schema, but without success, so after many tries i decided to wrote this topic to get an solution dedicated for me, because i am stuck without any ideas...

Drupal 8 missing filter view schema


How to understand each optimization step of Jacobi Iterative

Question: Q:

I saw Yousef Saad said "The Jacobi iteration determines the i-th component of the next approximation so as to annihilate the i-th component of the residual vector" in his book <<Iterative Methods for SAparse Linear System>>. But actually, it's not. Take the example in this notes, we could simply find $(b-Ax_1)_1$, which is the first element of the residual produced after the first iteration, is not $0$, which means we did not annihilate the $1th$ component of the residual vector after the first iteration. So my question is, what does Yousef Saad mean here?
What I found:

I saw other articles that described Jacobi iteration derive the Jacobi Method by simply using Linear Algebra to get iterative formula: $$ x_{(k+1)} = D^{-1}(E+F)x_k + D^{-1}b $$ where $x_{k+1}$ is the $(k+1)th$ solution and $A=D-E-F$.
Yousef try to derive this formula by giving us what Jacobi iteration does in each iteration just like what I mentioned above, he said: $$(b-Ax_{k+1})_i = 0$$ which means after $k+1$ iteration, then corresponding $i-th$ residual element of current solution $x_{k+1}$ is $0$. (Actually I can't understand this, I mean, what is the relation between $k+1$ and $i$). Then Yousef derive this formula: $$ a_{ii} x_i^{(k+1)} = - \sum _{j=1,j\neq i}^n a_{ij}x_j^k + b_i$$ I can't either understand this, how does Yousef link $x^{k+1}$ and $x^{k}$? Then he sum up these component-wise form to get the final formula: $$ x_{(k+1)} = D^{-1}(E+F)x_k + D^{-1}b $$.
Answer: I get the point of Yousef in this sector, But what he said really confused me at the beginning, Yousef really needs to add "TEMPORARILY" in his book...

Original: "The Jacobi iteration determines the $ith$ component of the next approximation so as to annihilate the $ith$ component of the residual vector"

Response: this is true but not entirely true since this method doesn't annihilate the $ith$ residual component forever. The residual component we discarded would be introduced again when we approximate the next solution element of the current iteration.
Take the first two beginning steps as an example, Initiative solution is $x_0$ (NOTATION: $x_i^j$ is the $ith$ component after $jth$ iteration). So the first equation of linear system is $$a_{11}x_1^0 + a_{12}x_2^0 + \dots + a_{1n}x_n^0 = \hat{b_1}$$
where $\hat{b_1}$ is the value of left-hand side formula.
Now we rectify $x_1^0$ to $x_1^1$(the element of $x^1$ after the first iteration) so that the left-hand side formula equals $b_1$.
Taking $(x_1^1, x_2^0, \dots, x_n^0)$ as a temporary solution we "annihilate the $i-th$ component of the residual vector" TEMPORARILY since we would introduce it again when we update $x_2^1$. So after the first iteration completely (which means we get the current answer $(x_1^1, x_2^1, \dots, x_n^1)$). Not a single residual component was eliminated.
As a result, we CAN'T use this derivative process as an intuitive understanding at all, it's useless in my view...


Showing a sequence in $\mathbb{N}$ is Cauchy

Question: For a metric $d(x,y) =\left| \frac{x}{1+|x|} - \frac{y}{1+|y|} \right|$
Where $d: \mathbb{R} \times \mathbb{R} \to \mathbb{R}$.
Prove that $\{ x_n \}$ in $\mathbb{R}$ given by $x_n = n$ is a Cauchy sequence with respect to $d$.
I am not sure of what would be a smart way to prove / disprove this. Here, since $n \in \mathbb{N}$, then we know that as the sequence continues the points $x_n$ and $x_m$ won't get closer than $1$, thus it is not Cauchy?
Comment: It isn't Cauchy in the *usual* metric on $\mathbb{R}$ but you have been given a different one.
Answer: Consider $d(m,n)$:
$$
d(m,n)=\left|\frac{m}{1+m}-\frac{n}{1+n}\right|=
\left|\frac{m-n}{(1+m)(1+n)}\right|
$$
By the triangle inequality,
$$
d(m,n)\le \frac{m}{1+m}\frac{1}{1+n}+\frac{n}{1+n}\frac{1}{1+m}
\le\frac{1}{1+n}+\frac{1}{1+m}
$$
If $\varepsilon>0$, take an integer $N$ such that $N>2/\varepsilon$; if $m,n>N$ then
$$
d(m,n)\le\frac{1}{1+n}+\frac{1}{1+m}<
\frac{\varepsilon}{2}+\frac{\varepsilon}{2}=\varepsilon
$$
Slow motion
\begin{align}
d(m,n)
&=\left|\frac{m}{1+m}-\frac{n}{1+n}\right|
\\[6px]
&=\left|\frac{m-n}{(1+m)(1+n)}\right|
\\[6px]
&=\left|\frac{m}{(1+m)(1+n)}+\frac{-n}{(1+m)(1+n)}\right|
\\[6px]
&\le\left|\frac{m}{(1+m)(1+n)}\right|+\left|\frac{-n}{(1+m)(1+n)}\right|
&&\text{triangle inequality}
\\[6px]
&=\frac{m}{1+m}\frac{1}{1+n}+\frac{n}{1+n}\frac{1}{1+m}
\\[6px]
&\le\frac{1}{1+n}+\frac{1}{1+m}
&&\text{because }\frac{k}{1+k}\le1
\end{align}
Comment: @Fredrik I added the steps
Comment: I don't understand how you deduce that at the triangle inequality. Why do you multiply with $1/(1+n)$ and $1/(1+m)$ ? I don't understand :(
Comment: That is really great. Thanks for adding the middle steps. It is very clear to me now :)
Answer: You have that $\frac{n}{1+n}=1-\frac1{1+n}<1$. Hence, for any $m>n$, we have: $$d(n,m)=|\frac{n}{1+n}-\frac{m}{1+m}|=|\frac1{1+m}-\frac1{1+n}|=\frac1{1+n}-\frac1{1+m}<\frac1{1+n}$$
Hence, for any $\epsilon>0$, choose $N$ such that $\frac1{N+1}<\epsilon$, then you have that $|x_n-x_m|<\epsilon$ for all $m,n>N$. Therefore, the sequence is Cauchy
Comment: It is a good observation at the beginning. Thanks for the response!
Answer: You need to show that, for any small $\epsilon > 0$ given, there is some $N = N(\epsilon)$ such that for any $n, m > N$, you have $d(n,m) < \epsilon $ where $d$ is the distance that you have defined. This is simply the definition of the Cauchy sequence.
You need to do an explicit calculation with the metric to show that this is indeed the case.


Como criar um simples interpretador?

Question: Sempre tive vontade de criar uma linguagem (algo simples) para mim mesmo mas não tenho ideia de como.
A pergunta é: Como criar um simples interpretador ?
Comment: Essa pergunta me parece ampla demais. Você quer uma visão geral dos passos necessários pra se criar um interpretador? Ou sua dúvida é em uma etapa mais específica? (tipo, como fazer a análise sintática do texto, ou como criar um código intermediário que o interpretador possa executar, etc)
Comment: [Este artigo do CodeProject ensina a criar um interpretador em .NET](http://www.codeproject.com/Articles/220042/Easily-Create-Your-Own-Parser). Ele basicamente é feito usando muita expressão regular. Indo mais fundo na dor, [há este manual que ensina a criar uma linguagem de programação](http://nathansuniversity.com/). Ainda não substitui um curso de compiladores, mas é um começo.
Comment: Pena que às vezes a pessoa pergunta, some, e recebe feedback quase que imediato que fica sem resposta... @Math, não seria o caso de chuchar diretamente essa tag e tirar aquela sopa que só aumenta a confusão? :)
Comment: @brasofilo hecho
Comment: Depende, você pode criar um interpretador pra uma linguagem que rode em um webbrowser como nesta resposta http://pt.stackoverflow.com/a/5358/3635 -- No entanto se quer criar um "linguagem" que compile ou interprete sem o browser, será necessário um outra linguagem primeiro, por exemplo c++ e você então irá criar um executável que irá fazer um "parse" na teu script (com linguagem inventada por ti) e irá executar ou compilar e depois executar :)
Comment: Essa técnica de usar expressões regulares para transformar uma linguagem em outra é simples, mas surpreendentemente poderosa! O projeto [processing.js](http://processingjs.org/) (do John Resig, autor do jQuery) por exemplo conseguiu portar a linguagem [Processing](https://processing.org/) para JavaScript simplesmente [usando uma série de regexes para traduzir uma linguagem pra outra](http://ejohn.org/blog/processingjs/), na sua primeira versão pelo menos, e então fazendo a interpretação de fato (usando Canvas).
Comment: É verdade. Tive muito sobre expressão regular numa matéria chamada Teoria da Computação. Era a introdução para Compiladores.
Answer: Há uns anos atrás eu precisei permitir que o usuário configurasse espécies de rótulos.
Basicamente ele escrevia um texto mais ou menos assim:

    Valor medido: {valor_medido}, Valor considerado: {valor_medido * 0.9}
    Data da medição: {formatar(data_medicao, "dd/mm/aaaa")}

Enfim, usando variáveis do sistema e funções previamente definidas, ele configurava diversos rótulos para serem usados em situações específicas, e no final o sistema imprimia algo como:

    Valor medido: 80, Valor considerado: 72
    Data da medição: 23/09/2015

Os recursos eram bastante amplos: formatação de datas e números, informações condicionais (usando if), etc.
No final, acabamos entregando um verdadeiro interpretador de linguagem de programação, embora tenhamos feito muito pouco por conta própria.
Para implementar este recurso, usamos o projeto ANTLR, e como ponto de partida usamos o projeto State of the Art Expression Evaluation (que usa o ANTLR).
Em poucas palavras, o ANTLR lê uma definição de linguagem escrita em Backus-Naur Form (BNF) e gera um parser para códigos escritos naquela linguagem.
O parser gerado então é capaz de interpretar um código e entregar uma árvore de objetos (espécie de tokens) que descreve o código interpretado. E então você percorre a árvore e vai executando o que foi determinado pelo código que você acabou de interpretar.
Estes dois projetos que linkei devem te ensinar muito sobre interpretadores de linguagem de programação.
Comment: Achei a pergunta ótima, pena que exige algum trabalho pra ser pertinente pro site.
Comment: A pergunta é ampla demais e não pretendi respondê-la integralmente, mas achei que valia a pena uma referência a estes projetos tão valiosos que têm muito a ensinar.

Como criar um simples interpretador?


R=X*Y is the relationship. Is predicting R and X and obtain Y same as predicting X and Y to obtain R?

Question: Of course the numbers will be different, I mean more in terms of relationship. I know that X affect R and Y affects R . X and Y are independent but since R is a product of X and Y , I dont think that I can calculate Y just by dividing R estimate by X estimate ? I dont know why, but it feels like a wrong approach . Can you help me to understand why or why not it is a wrong approach?
Comment: If $R=X \times Y$ is exact and you know any two of them then you can calculate the third using multiplication or division (at least when $R$ is non-zero).  But if you are only estimating two of them then this may not be the best estimate of the third.
Comment: Yes, that is indeed what I think. How can I answer the question, why estimating Y from estimated of R and X is a bad idea? Is estimating R from estimate of X and Y equally bad idea?
Comment: What are these "estimates" and how are they computed, from what kinds of data?  What might cause an estimate to differ from some "true" value and how would you characterize the possible distribution of such differences?
Comment: lets say R is revenue, X is the number of items sold and Y is the price (time varying) of items sold. Lets say time varying Y is hard to forecast. I have historical Revenue figures, thus i can create an ARIMA model say, for R, and lets say a Random Forest Regression for X. At the end of the day, I want to have both R , X, and Y forecasts. Is it fair to say that Y forecasted via some model is more trustworthy than Y deducted from R forecast/ X forecast?
Answer: The equation states equality, not causality
The equals sign gives you equality, nothing more, nothing less. You have three numbers that are in some relation to one another that's defined by the equation. There is no notion of causality there. In causal models, one typically uses assignment operators like $\leftarrow$ or $:=$ to differentiate between causal definitions and conventional equations. That said, your point is a common question and in fact one of the examples for how humans tend to think causally in Judea Pearl's "Book of Why".


Matplotlib global legend for lots of subplots

Question: i have some problem figuring out how to force matplotlib to add a legend where i want.
The figures i currently have look like this:

I generate this 2 paged plot with the following script:
n = 1
trn = True
for i in diff.keys():
    plt.subplot(8, 4, n)
    plt.xlim([0, rounds + 1])
    plt.locator_params(axis='y', nbins=5)
    if PEPTIDE_KD[i] == 1e-2:
        plt.plot(x_cord, [x[0] for x in diff[i]], 'ro--', label='asd')
        plt.plot(x_cord, [x[1] for x in diff[i]], 'rv--', label='bsd')
    else:
        plt.plot(x_cord, [x[0] for x in diff[i]], 'bo--', label='asd')
        plt.plot(x_cord, [x[1] for x in diff[i]], 'bv--', label='csd')
    plt.title(i)
    n += 1
    if n == 33 and trn:
        n = 1
        trn = False
        plt.suptitle('Ligand energies')
        plt.locator_params(axis='y', nbins=5)
        plt.subplots_adjust(hspace=0.35)
        plt.show()

plt.legend(bbox_to_anchor=(-0.05, 1), loc=1)
plt.locator_params(axis='y', nbins=5)
plt.subplots_adjust(hspace=0.35)
plt.show()

However i would like to place the legend at the left side of the very first subplot, or to the right side of last subplot in the first line.
I can do this with an if line == 0 bla bla, but the problem is as you can see in the plots i attached that for example the last plot only contains blue data, hence only the blue legend will show. I would like to place a full legend (red and blue) as well to the very same place. I dont even know where blue and red plot will be placed beforehand.
Is this possible?
Answer: Try using a figure legend which will let you create a legend for any of the lines plotted in your figure and position it relative to the figure.


Martingales and different definitions

Question: Are there any differences between the following definitions of Martingales and if so what are they?

Let $(X_{i})_{i=1}^{n}$ and $(Z_{i})_{i=1}^{n}$ be sequences of random variables then $(X_{i})$ is a martingale if $\mathbb{E}(X_{i}|Z_{1}...Z_{i})=X_{i-1}$ for all $i$.
Let $\mathcal {F}_{0} \subseteq \mathcal{F}_{1} \subseteq...\subseteq \mathcal{F}_{n}$ be a sequence of $\sigma$-subfields. Then $(X_{i})$ is a martingale with respect to $\mathcal{F}_{i}$ if $\mathbb{E}(X_{i}|\mathcal{F}_{i})=X_{i-1}$ for all $i$

In addition i was wondering what $\mathbb{E}(X_{i}|\mathcal{F}_{i})$ actually means, as it combines two notions of probability that are usually distinct from my previous experience in the sense that a random variable is a function defined on a probability space. I appreciate any help thanks!
Answer: (1) is the definition of the martingale in the special case where the filtration $\mathscr{F}_i$ is the $\sigma$-algebra generated by the random variables $Z_1,\ldots,Z_i$. (2) is the "general" case.

Martingales and different definitions


hangman game trying to count down user attempts

Question: here is my code below I am trying to make it count down from 6 to 0 every time the user enters wrong letter but it will only come up as 1 for me.
 private void UserAttempt(string letter)
    {
        if(Active_Word.Wrong_Guess < 6 && lbGuessWord.Text.Contains("*"))
        {
            int Mask = 1 << (letter[0] - 'A' + 1);

            if((Active_Word.Number_of_Letters & Mask)==0)
            {
                Active_Word.Number_of_Letters |= Mask;

                if (!Active_Word.Guess_Word.Contains(letter))
                {
                    listBIncorrectTrys.Items.Add(letter);

                    Active_Word.Wrong_Guess++;

                    int[] counter = new int[6];
                    counter[0] = 1;
                    counter[1] = 2;
                    counter[2] = 3;
                    counter[3] = 4;
                    counter[4] = 5;
                    counter[5] = 6;
                    for(int i = counter.Length - 1; i >= 0; i --)
                    {
                        string count = counter[i].ToString();
                        lbGuessesLeft.Text = (count);
                    }
                }
                lbGuessWord.Text = GetMaskedWord();

                Attempts_Made++;

Answer: Your counter.Length is never changing, so each time this loop is run, it will always terminate at i = 0, and counter[0] = 1. So, lbGuessesLeft.Text will always be 1.
for(int i = counter.Length - 1; i >= 0; i --)
{
   string count = counter[i].ToString();
   lbGuessesLeft.Text = (count);
}

Instead, do something like: guesses left = 6 - attempts made.
I'm not super eloquent with C#, but do something like this instead:
...
if (!Active_Word.Guess_Word.Contains(letter))
            {
                listBIncorrectTrys.Items.Add(letter);

                Active_Word.Wrong_Guess++;

                // Something similar to this
                // But try not to hard code constants like '6'
                lbGuessesLeft.Text = 6 - Active_Word.Wrong_Guess;
            }
            lbGuessWord.Text = GetMaskedWord();

            Attempts_Made++;
...

Comment: do i take out the loop and the array or put that in there with it ??
Comment: No loop needed at all :)
Comment: i did my best to clean it up


Save changes from dataGridView to SQL Server DB

Question: I have a form with dataGridView to display content of table Attendance
    TagID      SessionID       ScanningTime
    ---------------------------------------
    4820427      Test1       14/08/2013 18:12

I would like to add a record manually to the table to look like this....
    TagID      SessionID       ScanningTime
    ---------------------------------------
    4820000      Test1       14/08/2013 18:12
    0000001      Test2       15/08/2012 17:00

...and save changes to SQL Server database after button has been clicked.
I have tried creating UPDATE query:
command.Text = "UPDATE Attendance
SET TagID= @tagNo, SessionID= @sessionNo, ScanningTime= @scantime";

But I'm not sure how to assign values from DGV to parameters.
What is the correct way to save changes from dataGridView to SQL Server database?
Please note that I do not use DataSet or TableAdapter when working with DGV.
Comment: The correct way is open ended question but to answer your question the correct way would be to start writing some code and testing out if what you have written yields the expected results.. show some `initiative / effort`
Answer: You're going to want to consume the RowsAdded method of the DataGridView and cache the necessary information to INSERT the data:
// new form field for caching
private List<DataGridViewRow> _addedRowsCache = new List<DataGridViewRow>();

private void dataGridView1_RowsAdded(object sender,
    DataGridViewRowsAddedEventArgs e)
{
    for (int i = e.RowIndex; i < e.RowIndex + e.RowCount; i++)
    {
        _addedRowsCache.Add(dataGridView.Rows[i]);
    }
}

and then when you're ready to submit the data to the database:
// new class field to store the INSERT sql
private string _insertSQL = "INSERT INTO tbl (field1, field2) VALUES (@field1, @field2)";

// this block goes inside the click event
if (_addedRowsCache.Count > 0)
{
    using (SqlConnection c = new SqlConnection(connString))
    {
        c.Open();

        foreach (DataGridViewRow r in _addedRowsCache)
        {
            using (SqlCommand cmd = new SqlCommand(sql, c))
            {
                // add any parameter values, I don't know where `val(n)`
                // comes from here. Maybe from the `DataBoundItem`
                // off the `DataGridViewRow`, or maybe from a `Cell`
                // out of the `Cells` collection of the `DataGridViewRow`
                cmd.Parameters.AddWithValue("@field1", val1);
                cmd.Parameters.AddWithValue("@field2", val2);

                cmd.ExecuteNonQuery();
            }
        }
    }
}

Comment: This is really helpful thanks. I'm looking for a way to update the table if ANY changes been made (not only adding a row, but also modifying existing records)
Comment: @jaspernorth, a couple things. First, if you find `RowsAdded` doesn't work for the caching, you can also try `UserAddedRow`. Second, as far as updates, cache the `DataGridViewRow` using the `CellBeginEdit` event. The event args will let you get back to the row. However, cache those rows in a different list so you know the difference.


Allignment of ext3 partition on LVM RAID volume group

Question: I'm trying to add a partition on a LVM that resides on a RAID6 volume group and fdisk is complaining about the partition not residing on a physical sector boundry.
My question is, how do you calculate the correct starting sector for a partition on a LVM?  This partition will be formated ext3.  Would it be better to just format the LVM directly instead of creating a new partition?

Disk /dev/dedvol/backup: 2199.0 GB, 2199023255552 bytes
255 heads, 63 sectors/track, 267349 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 1048576 bytes / 8388608 bytes
Disk identifier: 0x4e428f49

                     Device Boot      Start         End      Blocks   Id  System
/dev/dedvol/backup1              63      267349  2146982827+  83  Linux
Partition 1 does not start on physical sector boundary.

lvdisplay /dev/dedvol/backup
  --- Logical volume ---
  LV Name                /dev/dedvol/backup
  VG Name                dedvol
  LV UUID                OV2n5j-7LHb-exJL-t8dI-dU8A-2vxf-uIicCt
  LV Write Access        read/write
  LV Status              available
  # open                 0
  LV Size                2.00 TiB
  Current LE             524288
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     32768
  Block device           253:1

vgdisplay dedvol
  --- Volume group ---
  VG Name               dedvol
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  3
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               1
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               14.55 TiB
  PE Size               4.00 MiB
  Total PE              3815448
  Alloc PE / Size       3670016 / 14.00 TiB
  Free  PE / Size       145432 / 568.09 GiB
  VG UUID               8fBcOk-aXGx-P3Qy-VVpJ-0zK1-fQgy-Cb691J
Answer:
I'm trying to add a partition on a LVM

You're doing it wrong. man lvcreate
Comment: +1. I was just in the middle of a much longer answer that was going to say the same thing.
Comment: The logical volume was created using "lvcreate -L2T -nbackup dedvol", so basically used all the defaults.  Are you saying you should not partition an LVM?  Or the LVM should have been created using custom chunk and strip sizes?
Comment: @John P, Dear John, why would one need partitioning a block device which is already a part of volume group? Since you're messing up basic concepts, I gently suggest you reading some intro to LVM-2. I hope en.Wikipedia.org's article could explain it quite well.
Answer: "Would it be better to just format the LVM directly instead of creating a new partition?"
Yes!
Unless something is badly messed up, LVM autoaligns the LV start on the boundary but you also need to give the correct stripe and stride values for a Raid6 to achieve reasonable performance.
There's an online calculator for those values which you need to give during the filesystem format.
http://busybox.net/~aldot/mkfs_stride.html
The performance improvement can be worth doing it all over again.
exception: when the array is just lightly used, then there's no improvement.
It's also possible to put them in the /etc/mk2efs.conf and then i.e. give the --fsprofile option during the kickstart install for RedHat / CentOS.
If you have the same kind of raid box everywhere it'll make sense. Otherwise no :)


Proxying packets back using iptables

Question: Problem: requests from web-application server to main server should be proxied back to web-application server. So if I perform a request from web-application server to application's domain (or public ip of main server) I expect to get an actual web-application as well as I getting it when I'm performing requests from the internet.
the picture with the network diagram
When the request comes from the outside, everything is OK.
Requests from the Internet to ports 80, 443 are proxied to the server with the web application. Firewall now looks like this:
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 80 -j DNAT --to-destination 184.108.40.206:80
iptables -t nat -A PREROUTING -p tcp --dport 80 -s 184.108.40.206 -d 10.10.10.10 -j DNAT --to-destination 18.104.22.168:80
iptables -A FORWARD -p tcp -d 220.127.116.11 --dport 80 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

As I understand it, I need to add a rule to iptables so that requests from 126.96.36.199 to 10.10.10.10 are also proxied to 10.10.10.10.
If I am right, please tell me how to do this, or how to fix this problem.
Answer: You're doing something strange. It is possible to do what you want, but you likely have a XY problem, i.e. this is not the root problem you're need to solve, but you're trying to fix a faulty solution to some other problem.

I suppose 3rd rule is your attempt to solve this problem.
Your 3rd rule works, it turns a packet (src=184.108.40.206:x dst=10.10.10.10:80) into a packet (src=184.108.40.206:x dst=220.127.116.11:80), and then routes it towards new destination.
When packet reaches 188.8.131.52, it is immediately dropped, because reverse path filter considered this spoofing. Let's suppose it was accepted nevertheless, but to whom we reply? A packet was (src=220.127.116.11:x dst=22.214.171.124:80), so a reply will be (src=184.108.40.206:80 dst=18.104.22.168:x). Even if created, such reply packet will never leave web box to reach a NAT box and be translated back.
The resolution is to translate both destination and source for these packets, so the 18.104.22.168 will not see it's a packet from itself. Packet must be changed so reply will get routed back to the NAT box. It is possible to do with the following additional rule:
iptables -t nat -A POSTROUTING -s 18.104.22.168 -d 126.96.36.199 --dport 80 -j SNAT --to-source 10.10.10.10

Notes:

it is doing a SNAT and therefore is in the POSTROUTING chain
it matches packet by its destination address already translated with DNAT (your 3rd rule - it is still needed!)
source address is changed to some address of NAT box. 126.96.36.199 in place of 10.10.10.10 also will work equally good.

The 126.96.36.199 will see this as a new packet (src=10.10.10.10:x dst=126.96.36.199:80), so it'll accept and a reply will properly reach the NAT box. Then NAT will replace both addresses back and return translated packet to web server box. So communication will succeed.

As I said, this is a very strange situation. While this will work, avoid it. Unusual firewall rules, hard to understand, inefficient design.
Why the 188.8.131.52 must coummunicate with itself via address it doesn't own, through another system? A DNS issue? You have some hostname, for which some (outside) DNS server answers 10.10.10.10? Then you better make either internal DNS server which will answer 18.104.22.168 just for local network, or make 184.108.40.206 never do such DNS query and "just know" a hostname is served by 22.214.171.124, by adding a line into its /etc/hosts file. That solution is solid (some name is served by me? Then that name belongs to me); it is easy to understand. Also it will bypass network hardware and create less system load, and it will work much faster, because local packets skip many layers of network stack.

Last note: if that's really a complete firewall and filter FORWARD policy is ACCEPT (the default), your fourth rule does nothig. In either case better is to remove it. Even if it's not a complete firewall, last rule looks strange. To give better suggestions, I need to see a complete firewall (an output of iptables-save).

Proxying packets back using iptables