autocomplete [displayWith] doesn't display name

Question: I'm using autocomplete material for my project but I don't understand how to use [displayWith]. I try  some example but not display name in html, only id.
My html code:
<form [formGroup]="editClientForm">
  <input formControlName="city_id" id="city_id" matInput placeholder="Select City*" aria-label="State" [matAutocomplete]="auto1"
    autoActiveFirstOption [formControl]="city">
  <mat-autocomplete #auto1="matAutocomplete" [displayWith]="displayFnCity">
    <mat-option (onSelectionChange)="updateForm($event, city.city_id, 'city_id')" *ngFor="let city of filteredOptionsCity | async"
      [value]="city.name">
      {{ city.name }}
    </mat-option>
  </mat-autocomplete>
</form>

My ts component:
  cityid = 0;
  filteredOptionsCity: any;
  city: FormControl = new FormControl();
  editClientForm: FormGroup;
    this.editClientForm = this.fb.group({
      'city_id': new FormControl('', Validators.required),
         });
  ngOnInit() {
    this.filteredOptionsCity = this.city.valueChanges.pipe(
      startWith(''),
      map(value => this.filterCity(value))
    );
}

  populateForm() {
    this.activatedRoute.params.subscribe(
      params => {
        this.clientService.getClientById(params['id']).subscribe(
          client => {
            this.client = client;
            console.log(client)
            this.editClientForm.controls['city_id'].setValue(client.city);
            console.log(client.city);
          }
        );
      }
    );
  }
  // City
  filterCity(val: string): City[] {
    if (val) {
      let filterValue = val.toLowerCase();
      console.log(this.cityes)
      return this.cityes.filter(city => city.name.toLowerCase().startsWith(filterValue));
    }

    return this.cityes;
  }

  updateForm(ev: any, idd: any, componentid: any) {

    if (ev.isUserInput) {
      if (componentid === 'city_id') {
        this.cityid = idd;
        this.editClientForm['controls']['city_id'].setValue(ev.source.value);
      } else {
        console.log('test');
      }
    }
  }

My class Client:
export class Client {
city: City[];}

My class City:
export class City {
  city_id: string;
  name: string; }

In html show me clity_id, I want city name.
I try to use this code, but nothing happends:
   getName(productid: string) {
      const [filteredProdG] = this.cityes.filter(pt => pt.city_id === productid);

   if (typeof filteredProdG !== 'undefined' && productid === filteredProdG.city_id) {
       return filteredProdG.name;
     }
   }

1.   displayFnCity(city?: City): string {
         console.log(city ? city.name : undefined) //show undefined
     return city ? city.name : undefined;
      }
2.  displayFnCity(city) {
    console.log(city.name) //show undefined
    return city.name;
  }

3. If I try [displayWith]="displayFn" or [displayWith]="displayFnCity"   show in html only  id_city
Please any idea how to solve this issue?
Answer: The [displayWith] function will be passed the [value] object. Since in your case you used [value]="city.name" you don't need to use [displayWith] because by default the autocomplete will display whatever [value] is. Normally one would use [displayWith] when [value] is bound to an object that is not a human-recognizable string. For example if you used [value]="city", then you would also want to use [displayWith]="displayFnCity" (your #1).
Comment: Replace
``
with
``
Comment: Yes, but that I want is, how to show in my page client.name, not client_id.
Comment: You can't display Client when the option values are City.
Comment: Sorry, I  was wrong. How to show in my page city.name, not city_id.
Comment: Once again, based on the code you already have using `[value]="city.name"`, you only need to remove `[displayWith]="displayFnCity"`. So replace `` with ``.
Comment: Please create a stickblitz example.
Comment: Please can you look this https://stackblitz.com/edit/angular-g2hcvs?file=app%2Fautocomplete-overview-example.html  In this exp. I want to show my country, like my name and email.
Comment: You do not have country defined anywhere. Do you mean state? Right now it works perfectly - select a state and it shows the state name. Please explain clearly what isn't working and what you want it to do.
Comment: I used populateForm() to populate my form, in this example, I populate only email and client_name, not name of city_id. That I want is to display automaticly and Florida, name of city ( city_id: '3',) for client MyName.


Can I register an additional namespace to point to the modules folder

Question: In Drupal 8 is it possible to register an additional namespace which points to the modules folder in addition to the \Drupal namespace?
e.g.: MyOwnNamespace\{module_name} to point to $path_to_module/src? I am asking this, because I would like to better understand how today's class design will affect my migration process to Drupal 8 one day.
This was a follow up question from my original thread regarding namespacing.
As suggested by another user I split this off into a separate question thread, but the question has been answered in the original thread already.
Answer: Splitting my comment over there into a separate answer then ;)
You can, yes, see system_register() and drupal_classloader_register(). Those helper functions hardcode "Drupal\" as they are all about modules, but you could get the class_loader service directly.
As @Clive said there, I would not recommend doing it for your own classes, there isn't really a reason to do so, unless you're including an external library.
External libraries is a different story, that can be useful. As already commented in How to autoload classes from a 3rd party PHP library in Drupal 8, if you do not want to depend on Composer Manager, then you can implement your own autoloader service and register them either by loading a composer-style autoload.php, or if you have it available in a different way, by directly registering it in the cloassloader service.


Java 8: How to get a value from a list contained as a map value?

Question: I have the following situation:
I have a LinkedHashMap<> where the key type is a String and the values types varies: double, String, LinkedHashMap, etc.
I am trying to extract a value from a key of one of the LinkedHashMaps values which are a value of the main map.
For example, I'd like to get the result 1 from the following code (obviously it is a mess since it doesn't even compile):
Map<String, Object> input = new HashMap<>();
input.put("a", "1234");
input.put("b", "2345");
input.put("c", "3456");
input.put("d", new HashMap<String, String>());

HashMap<String, Object> input2 = (HashMap<String, Object>)(input.get("d"));
input2.put("d1", 1);
input2.put("d2", 2);

Optional<Integer> result = input.entrySet().stream()
            .filter(e -> e.getKey().equals("d"))
            .map(Map.Entry::getValue)
            .filter(e -> e.getKey().equals("d1"))
            .findFirst();

Where do I go wrong, and of course, what is the best way to get the result?
Thanks.
Comment: `Integer result = ((Map)input.getOrDefault("d", Collections.emptyMap())).get("d1");`
Comment: @Holger That's great! I only needed to add an Integer casting to the right hand expression. Thanks!
Comment: Why are you expecting more than one keys of the map to equal "d"?
Answer: Once you use a Map with different value (and even key) types (and worse, nested maps). Then I suggest taking a step back and try to analyse what you've done. It seems that you're way better with a class than a Map. An example with your keys:
class YourClass {
    String a;
    String b;
    String c;
    YourOtherClass d;
}

class YourOtherClass {
    Integer d1;
    Integer d2;
}

I've omitted getters, setters and constructors for simplicity.
You can then create instances of those objects, like this:
YourOtherClass yoc = new YourOtherClass(1, 2);
YourClass yc = new YourClass("1234", "2345", "3456", yoc);

And then call the specific getter to receive a value with typesafety:
String a = yc.getA(); // works
Integer i = yc.getA(); // doesn't work

Or setting a new value via the setter:
yoc.setD1(4); // works
yoc.setD1("4"); // doesn't work

Answer: You're overcomplicating things imo. You could do it in a very straightforward manner. One liners are not always the ideal solutions.
I don't have the possibility to compile it, but it should be ok.
public Optional<Integer> getInnerValue(Map<String, Object> map, String outerKey, String innerKey) {
    Object o = map.get(outerKey);
    if (!(o instanceof Map)) {
        return Optional.empty();
    }
    return Optional.ofNullable(((Map)o).get(innerKey));
}

Using a one-liner
public Optional<Integer> getInnerValue(Map<String, Object> map, String outerKey, String innerKey) {
    return Optional.ofNullable(map.get(outerKey))
                   .filter(Map.class::isInstance)
                   .map(Map.class::cast)
                   .map(m -> m.get(innerKey))
                   .findFirst();
}


Recuperar nome das tabelas mysql

Question: Gostaria de recuperar o nome das minhas tabelas em java com banco mysql. Não sei se está correto eu recebo uma hashcode: (1) model.Campanhas@b5cca49 (2) model.Campanhas@5c369e04
 public ArrayList<Object>  nameTables(){
    try {
        String SQL = "SHOW tables";
        PreparedStatement ps = dataSource.getConexao().prepareStatement(SQL);
        ResultSet rs = ps.executeQuery();
        System.out.println("TABELAS CONSULTADAS COM SUCESSO");
        ArrayList<Object> lista = new ArrayList<>();
        while(rs.next()){
           Pedidos pedidos = new Pedidos();
           pedidos.setNomePedidos(rs);
           lista.add(pedidos);
        }
        rs.close();
        return lista;
     } catch (SQLException ex) {
        System.err.println("ERRO AO PESQUISAR TABELAS: "+ex);
    }
    catch (Exception ex){
        System.err.println("ERRO GERAL AO PESQUISAR TABELA: "+ex);
    }
    return null;
}

Answer: Ao escrever a lista você está exibindo a referência ao ResultSet, não o nome da tabela, porque no trecho pedidos.setNomePedidos(rs); você está passando por parâmetro todo o objeto. Para funcionar, você deve fazer pedidos.setNomePedidos(rs.getString(1));.
Para entender melhor o comando getString, acesse a documentação do java https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getString(int)
Comment: Obrigado, graças a sua resposta consegui a solução. já que outras coisas também estavam errados. Ai quando eu coloquei o que você falou já acusou o erro. Ai só fui consertando.  Vlw mesmo.

Recuperar nome das tabelas mysql


Fixing Microsoft Application DLL Spoofing Vulnerability via GPO

Question: With a metasploit module and POC code available, there's a growing concern about the DLL path-searching vulnerability in an increasing number of Microsoft and 3rd party applications.  It appears that ensuring SafeDLLSearchMode is enabled mitigates the vlunerability, and I would like to enforce this on a network via Group Policy.  While it's enabled by default in XP SP2+ and requires a registry edit to disable, I'd like to find an ADM file (or perhaps there's an existing policy setting I'm missing) that will let me ensure it remains active.
Does anyone know if anything like this is out there, or could anyone suggest how such an ADM file should look?  The key in question is:
HKLM\System\CurrentControlSet\Control\Session Manager\SafeDllSearchMode

With a value of 1 for enabled and 0 for disabled.
Comment: Do you have Client-Side Preferences available on your workstations?
Comment: No, [you don't need 2008 Server](http://blogs.technet.com/b/mkleef/archive/2008/11/19/reducing-confusion-group-policy-isnt-dependant-on-schema-versions-or-server-version.aspx). You will need [RSAT on Vista](http://www.microsoft.com/downloads/details.aspx?FamilyId=9FF6E897-23CE-4A36-B7FC-D52065DE9960&displaylang=en) or [Windows 7](http://www.microsoft.com/downloads/details.aspx?FamilyID=7d2f6ad7-656b-4313-a005-4e344e43997d&displaylang=en) to manage the CSPs in Group Policy though. Your clients will also need the CSP extension installed.
Comment: Our Windows Servers are all 2003 and 2003 R2.  My understanding is you need at least one 2008 server to administer Client-Side Preferences.  Sounds like a pretty useful feature, though.
Comment: That's great, thanks for the info -- will look into this.
Answer: Here is an ADM you can use to apply this preference.  If you had Client-Side Preferences you could better manage this setting.
CLASS MACHINE
CATEGORY "Extras"
  CATEGORY "Software Settings"
    CATEGORY "Safe DLL Search Mode"
        POLICY "Safe DLL Search Mode"
          KEYNAME "System\CurrentControlSet\Control\Session Manager"
              EXPLAIN "Enable safe DLL search mode."
          VALUENAME "SafeDllSearchMode"
            VALUEON  NUMERIC 1
            VALUEOFF NUMERIC 0
        END POLICY
    END CATEGORY
  END CATEGORY
END CATEGORY

You can also change this value with a simple script:
REG ADD "HKLM\System\CurrentControlSet\Control\Session Manager" /v "SafeDllSearchMode" /t REG_DWORD /d "1" /f


How to run npm install from Github Actions while deploying to Azure?

Question: I have a .Net Core Web application with some npm packages. Therefore I have a package.json file in the root of my project and if I run npm install locally a folder called node_modules is created. The needed files from this folder are provided by UseStaticFiles. So far so good, everything works fine locally.
Now I'm deploying this app to a Azure App Service automatically from GitHub Actions. I use a workflow yaml file created in the Azure Deployment Center. The workflow do two things:

Build, publish and upload the artifact for the .Net application
Download the artifacts on Azure and deploy to my Azure Web App

Everything works fine, except of the npm packages of course.
So I add another build step to the workflow to run npm install after deployment directly on Azure:
- name: npm install
  run: npm install

If the GitHub Action is executed I can see that npm install is executed and installed some packages:

But if I open my application in the browser I get errors in the console because the resources from node_modules not found. I check the wwwroot of my App Service by Kudo (<myapp>.scm.azurewebsites.net/wwwroot) and indeed there is no node_modules folder. I guess that npm install is executed in the wrong directory and I know that I can specify a working-directory for npm-install build step, but I don't know to which directory I need to set it.
Does anybody had the same problem or knows how to successfully run npm install from a GitHub Action while deploying to Azure?
Comment: Do you have any node modules in  your .Net Core Web application
Comment: Could you show how do you configure .net app to use static content?
Comment: @Alexander Vogt Could you please share your `pacakge.json` file and `.yml` file.
Answer: Iam able to push the node_modules folder when I deploy App using GitHub Actions.
Make sure the node_modules folder is pushed to GitHub repo.
Refer Git Commands from SO to push the local directory to Git.

When I add the GitRepo ,in the default yml file the path is set to ${{env.DOTNET_ROOT}}/myapp ,
Change the path to . and re-run the job.

I know that I can specify a working-directory for npm-install build step, but I don't know to which directory I need to set it.

The working-directory for npm-install has to be set to the path where package.json resides, i.e.., the root folder of the Application.
So, you need to set  . , which indicates the root directory.

To make sure to push the node_modules folder to root directory you can even use the copy command cp along with path.

KUDU
Refer the SO Thread to install npm-install in yml file.


$\gcd(m^2,n^2)$ = $(\gcd(m,n))^2$

Question: Let $\gcd(m,n)=d$ and $\gcd(m^2,n^2)=d'$.
It means $d|m$ and $d|n$ which implies $d^2|m^2$ and $d^2|n^2$
Thus $d^2|d'$.
How to prove reverse $d'|d^2$
Answer: Another way:
Let $\dfrac nN=\dfrac mM=d$
so that $(M,N)=1$
In that case, $N^2,M^2$ cannot share a common factor $>1$
$\implies(M^2,N^2)=1$
Method$\#:2$
Let the highest exponent of prime $p$ that divides $m,n$ be $a,b$ respectively
So, the highest exponent of $p$ in $(m,n)$ will be min$(a,b)=c$(say)
Similarly the highest exponent of prime $p$ in $(m^2,n^2)$ will be min$(2a,2b)=2c$
This will hold true for any prime that divides $mn$
Answer: Perhaps overkill but a handy concept is that for any $m,n$ there are $d =\gcd(m,n)$ and $n', m'$ so that $m = dm'$ and $n = dn'$ and it's not difficult to prove $m', n'$ are relatively prime.
(Because if $\gcd(n', m') = k>1$ then $kd|n$ and $kd|m$ and $kd > d$ so $d\ne \gcd(m,n)$ after all.)
SO let $m = dm'$ and $n = dn'$.  Then $m^2 = d^2m'^2$ and $n^2 = d^2n'^2$.  $d^2|m^2, n^2$ but then $m'^2$ and $n'^2$ have no factors in common. So there is no common divisor greater than $d^2$ that $d^2$ divides.  So $d^2$ is greatest common divisor.
(Remember the Theorem: if $k|m,n$ then $k|\gcd(m,n)$.

$\gcd(m^2,n^2)$ = $(\gcd(m,n))^2$


SQL código não funciona queria uma explicação do porque do erro no código?

Question:
Recebi essas duas tabelas num exercício, porém meu código não tá funcionando e eu queria saber se alguém poderia me explicar. eu tenho que apresentar todas as ordens criadas nos últimos 10 dias.
Meu código:
Select id-order, createdDate
From Date
Where Date = 'createDate' in <10 days

Só que não funciona.
Comment: Qual o `SGBD`? `MySQL`, `SQL Server`, `Oracle`?
Comment: SQL server.....
Answer: Pelo visto o que precisa fazer é algo assim:
SELECT
    ID-ORDER, CREATEDDATE
FROM
    ORDER
WHERE
    DATEDIFF(DAY,CREATEDDATE,GETDATE()) < 10

Comment: Então preciso usar DateDiff em todos os casos assim?
Comment: Na maioria dos casos, que faz comparação de período entre datas acredito que seja a melhor opção.


How do I take out the caching and bandwidth optimizations sections out of the performance window for a user?

Question: How do I take out caching and bandwidth optimizations sections out of the performance window for a user?
Answer: You can use the #access property to do this.  You would just need to wrap things up in your own logic.
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  if (user_cant_access_this_stuff()) {
    $form['caching']['#access'] = FALSE;
    $form['bandwidth_optimization']['#access'] = FALSE;
  }
}

I am not 100% sure on those $form elements (this was taken from something similar I have on a site), so you may need to dpm() the $form.


Arrays.asList vs. Arrays.stream to use forEach()

Question: If you have an Array and you want to use the Java8 forEach() method, which approach is better or more efficient:
Arrays.asList(new String[]{"hallo","hi"}).forEach(System.out::println);

or
Arrays.stream(new String[]{"hallo","hi"}).forEach(System.out::println);

Is the difference significant or are there any better solutions to solve this?
Comment: And you can write `Arrays.asList("hello","hi")` you don't need to create an array if you don't already have one
Comment: Probably `asList`, which seems to involve fewer objects. But still nothing you'll notice in program execution.
Answer: Neither. If you already had an array,
String[] array;

I would use:
Arrays.stream(array).forEach(System.out::println);

because you leave the conversion of the array to a stream to the JDK - let it be responsible for efficiency etc.
But, since you don't have an array, I would use Stream.of()'s varargs to create a stream of the values:
Stream.of("hallo","hi").forEach(System.out::println);

Which again lets the JDK take the responsibility of efficiently streaming the values as it sees fit.
Comment: @SotiriosDelimanolis "already has an array" means "not coding literal elements in-line" - ie the array was declared and populated externally to the code in question
Comment: To make the decision even harder, I throw in that, if you don't have an existing array, you can also say `Stream.of("hallo","hi").forEach(System.out::println);`. That will be more efficient in the special case of length `1` as in that case, no array will be created.
Comment: I don't understand your _If you already had an array_. One way or another they need an array. `stream` takes an array and `asList` does as well.
Comment: @SotiriosDelimanolis Yes, readability (always high on the design radar, and I believe in "less code is good") *and* performance - it hands more over to the JDK (which we tend to trust is "well written").
Answer: It seems to make almost absolutely no difference. I created a test class for this. Over the course of five runs, my output was this:
Run 1:
Arrays.asList() method................: 3231 ms
Arrays.stream() method................: 3111 ms
Stream.of() method....................: 3031 ms
Arrays.asList() (premade array) method: 3086 ms
Arrays.stream() (premade array) method: 3231 ms
Stream.of() (premade array) method....: 3191 ms

Run 2:
Arrays.asList() method................: 3270 ms
Arrays.stream() method................: 3072 ms
Stream.of() method....................: 3086 ms
Arrays.asList() (premade array) method: 3002 ms
Arrays.stream() (premade array) method: 3251 ms
Stream.of() (premade array) method....: 3271 ms

Run 3:
Arrays.asList() method................: 3307 ms
Arrays.stream() method................: 3092 ms
Stream.of() method....................: 2911 ms
Arrays.asList() (premade array) method: 3035 ms
Arrays.stream() (premade array) method: 3241 ms
Stream.of() (premade array) method....: 3241 ms

Run 4:
Arrays.asList() method................: 3630 ms
Arrays.stream() method................: 2981 ms
Stream.of() method....................: 2821 ms
Arrays.asList() (premade array) method: 3058 ms
Arrays.stream() (premade array) method: 3221 ms
Stream.of() (premade array) method....: 3214 ms

Run 5:
Arrays.asList() method................: 3338 ms
Arrays.stream() method................: 3174 ms
Stream.of() method....................: 3262 ms
Arrays.asList() (premade array) method: 3064 ms
Arrays.stream() (premade array) method: 3269 ms
Stream.of() (premade array) method....: 3275 ms

From the output, It looks like the Stream.of() method is very marginally (but consistently) the most efficent, and
Stream.of("hallo","hi").forEach(System.out::println);

is very readable code. Stream.of has the advantage in that it doesn't have to convert the array into a list, or create an array and then create a stream, but can create a stream directly from the elements. What was mildly surprising to me, was that because of the way I did my tests, it was faster to instantiate a new array stream each time with Stream.of() than it was to pass in a pre-made array, probably because "capturing" lambdas - those that reference an external variable - are a little less efficient.
Here's the code for my test class:
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.stream.Stream;

public class StreamArrayTest {

    public static void main(String[] args){
        System.out.println("Arrays.asList() method................: " + arraysAsListMethod() + " ms");
        System.out.println("Arrays.stream() method................: " + arraysStreamMethod() + " ms");
        System.out.println("Stream.of() method....................: " + streamOfMethod() + " ms");
        System.out.println("Arrays.asList() (premade array) method: " + presetArraysAsListMethod() + " ms");
        System.out.println("Arrays.stream() (premade array) method: " + presetArraysStreamMethod() + " ms");
        System.out.println("Stream.of() (premade array) method....: " + presetStreamsOfMethod() + " ms");
    }

    private static Long timeOneMillion(Runnable runner){
        MilliTimer mt = MilliTimer.start();
        for (int i = 0; i < 1000000; i++){
            runner.run();
        }
        return mt.end();
    }

    private static Long timeOneMillion(String[] strings, Consumer<String[]> consumer){
        MilliTimer mt = MilliTimer.start();
        for (int i = 0; i < 1000000; i++){
            consumer.accept(strings);
        }
        return mt.end();
    }

    public static Long arraysAsListMethod(){
        return timeOneMillion(()->Arrays.asList(new String[]{"hallo","hi","test","test2","test3","test4","test5","test6","test7","test8"}).forEach(StreamArrayTest::doSomething));
    }

    public static Long arraysStreamMethod(){
        return timeOneMillion(()->Arrays.stream(new String[]{"hallo","hi","test","test2","test3","test4","test5","test6","test7","test8"}).forEach(StreamArrayTest::doSomething));
    }

    public static Long streamOfMethod(){
        return timeOneMillion(()->Stream.of("hallo","hi","test","test2","test3","test4","test5","test6","test7","test8").forEach(StreamArrayTest::doSomething));
    }

    public static Long presetArraysAsListMethod(){
        String[] strings = new String[]{"hallo","hi","test","test2","test3","test4","test5","test6","test7","test8"};
        return timeOneMillion(strings, (s)->Arrays.asList(s).forEach(StreamArrayTest::doSomething));
    }

    public static Long presetArraysStreamMethod(){
        String[] strings = new String[]{"hallo","hi","test","test2","test3","test4","test5","test6","test7","test8"};
        return timeOneMillion(strings, (s)->Arrays.stream(s).forEach(StreamArrayTest::doSomething));
    }

    public static Long presetStreamsOfMethod(){
        String[] strings = new String[]{"hallo","hi","test","test2","test3","test4","test5","test6","test7","test8"};
        return timeOneMillion(strings, (s)->Stream.of(s).forEach(StreamArrayTest::doSomething));
    }

    public static void doSomething(String s){
        String result = s;
        for (int i = 0; i < 10; i++){
            result = result.concat(s);
        }
    }
}

And the MilliTimer class I used:
public class MilliTimer {
    private long startTime = 0L;

    private MilliTimer(long startTime){
        this.startTime = startTime;
    }

    public static MilliTimer start(){
        return new MilliTimer(System.currentTimeMillis());
    }

    public long end() throws IllegalArgumentException {
        return System.currentTimeMillis() - startTime;
    }
}

Comment: The optimizer prefers local values. So a code using a temporary array might indeed be as fast or even faster than that using a prepared array, however, it's not clear whether this applies to your benchmark as it's flawed. Your method `doSomething` may look complicated but actually does nothing as everything inside it has no real effect. A modern JVM is able to recognize that. Besides that, you should use `System.nanoTime()` rather than `System.currentTimeMillis()` as the latter returns a value that is not guaranteed to move constantly forward.
Comment: the doSomething method actually does do something... it instantiates a number of String objects and concatenates them together. . If you don't believe it does, then blank out those four lines and watch how the execution time changes from about 3200ms to about 30ms.
Comment: And if you adjust the number of iterations in the loop inside the doSomething method, that will also affect the execution time.
Answer: Arrays.asList() method................: 22 ms
Arrays.stream() method................: 26 ms
Stream.of() method....................: 26 ms
Arrays.asList() (premade array) method: 8 ms
Arrays.stream() (premade array) method: 30 ms
Stream.of() (premade array) method....: 17 ms

When you change doSomething to actually do nothing as follows:
public static void doSomething(String s){
}

Then you're measuring the actual speed of these operations instead of the operation String = String + String;  This is what doSomething was doing, and of course it is about the same speed consistently.  However, the actual speed isn't the same and asList with a premade array is much faster.
The real result here has already been noted by others that you should beware of the stream as it is typically 4 times slower than the plain old java (non-lambda) approach.
Comment: If you remove the body of doSomething, you're not taking into account input/output of the various processing methods. Yes, a list can be instantiated using `Arrays.asList()` faster than `Stream.of()` or `Arrays.stream()` but if you don't actually DO anything with the values in the array, there's no processing overhead because the optimizer will recognize the noop method and cut it out. The times for doSomething() should be consistent because they're the exact same operations, and what's left should mostly be overheads from invoking the various processing methods.


Slurs within slurs

Question:
How do I play the slurs with in the larger slur? Can you play this two ways? One big slur or individual slurs?
Comment: What's interesting is that even the staff is "slurred" ;-)
Answer: The outer/larger slur is a phrase marking, letting you know that the entire passage constitutes a single musical idea. The inner slurs are similar, but indicating smaller units. One could think of the inner slurs as indicating words, and the outer slur as denoting a sentence.
Part of the reason there are two sets is that there are some places in the phrase which demand re-articulation (tonguing), which would otherwise break up a true legato. For example, the passage starts with two Es, so the second one needs to be articulated. The accented A toward the end of the passage also requires articulation. The outer slur, then, is a reminder to play legato overall.
There are also implications for breathing. The outer slur suggests the entire passage should be played in one breath. However, if one breath isn't possible, then the inner slurs provide a guide to where a breath could happen (between them, not during, of course).
The way I would play this passage is that I would make the small/inner slurs true legato, and I would use a legato/gentle tonguing technique for notes within the larger slur but not themselves connected by smaller ones. I would play the entire passage in a single breath.
So, for example, I would tongue the initial note and the gently re-articulate the second, slur to the third, then gently re-articulate the fourth and fifth, slur the sixth and seventh, and gently re-articulate the eighth. If necessary, I would sneak a breath in before that note as well.
Comment: Any chance the phrase mark is there to request that everything under it be played with a single breath? If this were clarinet music, that's how I would read it, but I would also ask my teacher
Comment: @ToddWilcox Great point! I've updated the answer with remarks on breathing.
Answer: Whilst they all look like slurs, they're not. Some are ties, which means they're making one long note out of two written. Bar 4, the E notes are as such.
But, there's one phrase mark over bars 1 to 4, which is more likely what you're questioning. Imagine speaking, and splitting your sentence into four separate little bits - mini-phrases. That's what's happening here. There's a sort of short break after each mini-phrase, but the whole four bars need articulating as one longer sentence.
Comment: @Jazzfess Thanks for the thanks. Just know, if you haven't already, upvoting helpful answers is the way to say "thank you" here on Stack Exchange. The voting arrows appear to the left of the corresponding post.

Slurs within slurs


Php Array - Associando dados

Question: Olá,
Gostaria de associar os dados de escolhidos em checkbox, com os de um input.
Tenho de um lado, uma lista de resultados, onde irei selecionar em um checkbox, e cada um receberá um novo valor escolhido pelo usuário.
Por exemplo:
Na tela aparece Carro1,carro2 e carro3.
O usuario escolhe carro1 e carro2, e define que o carro1 vai se chamar volks, e o carro2 vai se chamar ford.
então ao fazer o submit, terei o seguinte código para realizar essa operação:
No layout assim:
<input type="checkbox" name="carro[]" />
<input type="text" name="nome_definido_usuario[]" />

E no processamento:
    <?php
        $carro = $_POST['carro'];
        $nome_definido_usuario= $_POST['nome_definido_usuario'];

        $carro_implode = implode("",$carro);
        $nome_definido_usuario_implode = implode("",$nome_definido_usuario);
    ?>

Se eu fizer um echo em $carro_implode e $nome_definido_usuario_implode,
consigo visualizar o resultado de forma aleatória, como Carro1,Carro2,Volks,Ford. Mas como faço para que o resultado apareça de forma associada, como:
Carro1: Volks
Carro2: Ford
Algúem saberia?
Answer: Pra fazer a associação, creio que fica melhor dessa maneira. Porque se algum checkbox não for marcado, não perde-se o índice:
<?php
if( $_POST ) {
    foreach( $_POST['carro'] as $key => $value ) {
        echo 'Carro '.$value.': ' . $_POST['nome_definido_usuario'][$value].'
';
    }
}
?>

<form method="post">
    <input type="checkbox" name="carro[]" value="1" />
    <input type="text" name="nome_definido_usuario[1]" />

    <input type="checkbox" name="carro[]" value="2" />
    <input type="text" name="nome_definido_usuario[2]" />

    <input type="checkbox" name="carro[]" value="3" />
    <input type="text" name="nome_definido_usuario[3]" />

    <input type="submit" value="Enviar" />
</form>

Comment: Quase.. O nome_definido_usuario, está chegando vazio... como se não houvesse nada informado no campo pelo usuário..
Comment: Você colocou o numero entre os colchetes? O número que está no value do carro[] tem que estar no colchete do nome_definido_usuario. Tipo isso: name="nome_definido_usuario[2]"
Comment: Não coloquei, porque estou utilizando dados vindos do BD, com while
Answer: Você pode fazer essa associação usando a função array_combine. Essa função vai retornar um novo array associativo a partir de dois arrays reccebido como parametro, onde o primeiro vai ser usados como chaves e o segundo como valor das chaves do primeiro. Emplementando fica:
<?php
//exemplo de dados submetidos pelo formulario
$_POST['carro'] = ['Carro 1', 'Carro 2'];
$_POST['nome_definido_usuario'] = ['Volks', 'Ford'];

$carros = $_POST['carro'];
$nomes = $_POST['nome_definido_usuario'];

//essa função vai criar um novo array associativo, usando
//como chave o primeiro e o segundo como os valores de cada chave do primeiro
$carrosNomes = array_combine($carros , $nomes);

//mostrando o conteudo
var_dump($carrosNomes);
echo $carrosNomes['Carro 1'] . '
';
echo $carrosNomes['Carro 2'] . '
';

//ou de forma mais completa
foreach($carrosNomes as $carro => $nome){
    echo '
' . $carro . ': ' . $nome . '
';
}

?>

Isso gera como saida:
//saida do var_dump
array(2) { ["Carro 1"]=> string(5) "Volks" ["Carro 2"]=> string(4) "Ford" }

//acessando chaves do aray $carrosNomes
Volks
Ford

//imprimindo chave e valor de cada elemento do array $carrosNomes
Carro 1: Volks

Carro 2: Ford

Sugestão: você poderia unir os input com name carro e nome_definido_usuario em um só. Algo como:
<input type="checkbox" name="carro[]" value="Volks">
<input type="checkbox" name="carro[]" value="Ford">

Exemplo funcionando
Em um arquivo qualquer coloque o codigo abaixo:
<?php

if(isset($_POST['carro'])){

$carros = $_POST['carro'];
$nomes = $_POST['nome_definido_usuario'];

//essa função vai criar um novo array associativo, usando
//como chave o primeiro e o segundo como os valores de cada chave do primeiro
$carrosNomes = array_combine($carros , $nomes);

//mostrando o conteudo
var_dump($carrosNomes);
echo $carrosNomes['Carro 1'] . '
';
echo $carrosNomes['Carro 2'] . '
';

//ou de forma mais completa
foreach($carrosNomes as $carro => $nome){
    echo '
' . $carro . ': ' . $nome . '
';
}

}
?>

<form method="post">

    <input type="checkbox" name="carro[]" value="Carro 1" />
<input type="text" name="nome_definido_usuario[]" />
    <input type="checkbox" name="carro[]" value="Carro 2" />
<input type="text" name="nome_definido_usuario[]" />
    <input type="submit">
</form>

Ao subter o formulario o mesmo arquivo será executado, e o trecho em php será interpretado, gerando a saida esperada.
Solução para deixar de unir esses dois arrays
Basta usar um pouco de javascript para copiar (o value) o conteudo de um input para outro.
<?php

if(isset($_POST['carro'])){

$carros = $_POST['carro'];

//mostrando o conteudo
var_dump($carros);

//ou de forma mais completa
foreach($carros as $carro => $nome){
    echo '
' . $carro . ': ' . $nome . '
';
}

}
?>

<form method="post">

        <input type="checkbox" name="carro[]" value="" class="carros"/>
        <input type="text" name="nome_definido_usuario[]" class="nomes" />

        <input type="checkbox" name="carro[]" value="" class="carros"/>
        <input type="text" name="nome_definido_usuario[]" class="nomes"/>

    <input type="submit">
</form>

Basicamente foi dada uma classe para cada input (nome definido usuario), adicionado um evento de change (quando algo for escrito no input e o foco mudar), então o valor digitado no input será setado como valor do input checkbox.
Comment: coloquei assim:   $carros = $_POST['carro'];
$nomes = $_POST['nome_definido_usuario'];

$carrosNomes = array_combine($carros , $nomes);

foreach($carrosNomes as $carro => $nome){
    echo '' . $carro . ': ' . $nome . '';
}                                                                                Mas não veio nenhum resultado.. nada aparece na tela.                                 E sobre a sugestão de unir, creio q não seria ideal, porque a idéia é permitir que o usuário modifique os nomes conforme escolha.
Comment: e com o var_dump($carrosNomes) apareceu bool(false)
Comment: @Neo Editei a pergunta para colocar um exemplo completo e funcionamento. Basta colocar em um arquivo .php e executar. Além disso coloquei um exemplo onde não é necessario usar dois arrays no servidor.
Comment: Preciso dos 2arrays como no exemplo.. mas coloquei aqui e continua sem obter nenhum resultado, nada aparece na tela.
Comment: @Neo Então você não esta executando corretamente, o codigo de "Exemplo Funcionando", nesse link do [phpfiddle](http://main.xfiddle.com/code_78149148.php). O arquivo `code_78149148.php` tem exatamente o conteudo colocado na resposta, com a saida esperada (após preencher, claro).
Comment: O link não abre
Comment: http://main.xfiddle.com/code_78149148.php ...pagina não encontrada.. =/
Comment: =(...alguém aí?
Comment: @Neo Acho que o link expirou. Tenta esse [novo](http://main.xfiddle.com/06969926/associando.php) (em até 48 horas).
Comment: Consegui testar somente hoje, já expirou. Mas dentro do contexto que montei considerando o exemplo inicial, não consigo reproduzir aqui. Deve ser algum detalhe minimo..
Answer:     $carro = $_POST['carro'];
    $nome_definido_usuario= $_POST['nome_definido_usuario'];

    $arrayCarros = array($carro => $nome_definido_usuario);

Comment: Assim retorna apenas Array
Answer: A maneira correta seria usar um array associativo ou criar um objeto
<?php
     $carro = $_POST['carro'];
     $nome_definido_usuario= $_POST['nome_definido_usuario'];

     $arrayCarros = array($carro => $nome_definido_usuario);
?>

Comment: Tentei fazer algo assim: $names2 = array('vw'=>'Volks','FD'=>'Ford','CH'=>'Chevro'); Mas não Ocorreu o desejado..

Php Array - Associando dados


Multidimensional graph representation

Question: I would like to know how to plot the following 30 observations on a graph, with 1 color for each country, using Kmeans or other methods on R.
Each of the 40 independent variables can take value from 0 to 100 (100 means the data point shows strongly the attribute).

Thank you
Comment: See [this question](https://stackoverflow.com/questions/14604439/plot-multiple-boxplot-in-one-graph).
Comment: Aside from the 30 graphs of 40 boxplots which Ami suggest (which can be nice... *if* you have a very big screen) you may reduce the dimensionality a bit by exploiting the possible correlations (hoping that the variables are not completely independent) with principle component analysis (PCA).
Comment: What do you mean by "using Kmeans"? Clustering first and then plotting the clusters?
Answer: You would use a parallel coordinate plot for multivariate analysis. Combine it with the following additional aesthetics:

Variables 1-40 on the x axis
0-100 on the y axis
Line by Observation number
color or trellis/facet by Country

Using PCA or k-means would be a good solution if all your variables had differing scales or different data types. But since the observations follow similar scales and are fewer groups (2 countries), the Parallel coordinate plot is pretty easy to read, so no need for dimensionality reduction.
You should use boxplots if it is important to compare the summary or overall behavior of country 1 to country 2 for all variables. PCP is better at giving you insights at the level of each individual point or observation.
Also side note on terminology: graph as a term is often interpreted as network data type of graph, you would get better search results if you use plot for relational data.

Multidimensional graph representation


Include full words in string slicing

Question: here's some code i have:
def breakUp(x,chunk_size):
    return [ x[i:i+chunk_size] for i in range(0, len(x), chunk_size) ]

here's how it works:
In [8]: breakUp('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!',10)

Out[8]:
['This is a ',
 'cool sente',
 'nce... How',
 ' about eat',
 'ing it??? ',
 'Whats more',
 '?? pepper ',
 'is availab',
 'le all for',
 ' free!!!']

but as you see in the second element the word sentence is not taken completely, it says "sente"...
I know that this is because i've asked python to split it afer every 10 characters... is there anyway of specifying that i want to split after every 10 characters but if the 10th char. ends in a word, take the whole word...?
Comment: This sounds like homework, but I would split the line up into words (defined as letters separated by space) and then add words and space until I am >= chunk_size.
Comment: no but i want the chunk to be *x* **characters** long... i know that the mentioned constraint will cause the half-words. but what i now want is the chunk should be approx. *x* **characters** long. i can afford moving some characters the either side to engulf the word that is not fitting
Comment: Then figure out how much fuzziness you can allow as a number, add together the words to a string and then check the `len` and see if it falls within your +-`chunk_size`.
Answer: Batteries included:
>>> import textwrap
>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 15)
This is a cool
sentence... How
about eating
it??? Whats
more?? pepper
is available
all for free!!!

This does almost all you have asked for.  Except that if you specify 10 as a second parameter, it will still split sentence... since there is no way to fit it in 10 characters.  However, if you want to do this, you can customize textwrap with break_long_words=False:
>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 10, break_long_words=False)
This is a
cool
sentence...
How about
eating
it???
Whats
more??
pepper is
available
all for
free!!!

Comment: @tenstar I used `textwrap.fill` for the demo.  If you don't need newlines, just use `textwrap.wrap` - see the doc http://docs.python.org/2/library/textwrap.html
Comment: man, you solved my problem...!! except that `print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 15).split('\n')` would give me what i want..!! now edit you answer for an accept!!!

Include full words in string slicing


SED: Removing last character before EOL and adding some text using the old one

Question: I have the following line:
env JAVA_OPTS="-Djava.library.path=/the_path/:/the_path/:/the_path/:/the_path:"$LIBRARY_PATH" -Xms2g -Xmx4g -XX:MaxPermSize=256M -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000 -Dspring.profiles.active=release"

I want to add new variable before the last quotation mark (something like a new_fancy_variable=yes). So this line should be look like that:
env JAVA_OPTS="-Djava.library.path=/the_path/:/the_path/:/the_path/:/the_path:"$LIBRARY_PATH" -Xms2g -Xmx4g -XX:MaxPermSize=256M -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000 -Dspring.profiles.active=release new_fancy_variable=yes"

The question is how can I do that? At present I have a command:
sed 's/^env JAVA_OPTS=\".*$/& new_fancy_variable=yes\"/' myfile.conf

...but I don't know how I can remove the last question mark before new variable.
Answer: sed '/^env JAVA_OPTS=/s/"$/ new_var=yes"/' ...
Answer: You do not need the env. You can postfix values to a var with myvar+="additopnal=value".
Your originalJAVA_OPTS` can be constructed like
JAVA_OPTS="-Djava.library.path=/the_path/:/the_path/:/the_path/:/the_path:$LIBRARY_PATH"
# Add mem setings
JAVA_OPTS+=" Xms2g -Xmx4g -XX:MaxPermSize=256M"
# add Timeouts
JAVA_OPTS+=" -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000"
# Add profile
JAVA_OPTS+=" -Dspring.profiles.active=release"

Do not forget to add a space between the words.
Now adding something fancy is easy:
JAVA_OPTS+=" new_fancy_variable=yes"

When you want to add it to a file, you can try
echo '# Fancy support
JAVA_OPTS+=" new_fancy_variable=yes"' >> myfile.conf

You only need to check that adding this on the last line is correct (no flow control or sections in your config)


Safari clipboard permissions checking

Question: I have the following code that works in Chrome:
navigator.permissions
    .query({ name: "clipboard-write" })
    .then((result) => {
        if (result.state === "granted" || result.state === "prompt") {
            navigator.clipboard.writeText(data.payload).then(console.log).catch(console.error);
        }
    })
    .catch((err) => {
        console.log("ToSystemClipboard", err);
    });

But in Safari it hits the catch with TypeError: Type error.
In Webstorm I get an underlining of { name: "clipboard-write" } to the effect that clipboard-write is not a recognised keyword. And yet on https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/read clipboard-read is used in an example - I can't recall where I found clipboard-write.
If I remove the permissions test, my code -  navigator.clipboard.writeText - works in Safari anyway, but that doesn't feel like the safest code to write for production. Am I missing something?
I have since found that "[t]he clipboard-write permission is granted automatically to pages when they are the active tab". This explains why my code works without the permissions check, but does not answer my question about syntax to use
Answer: clipboard-read and clipboard-write are unavailable to Firefox or Safari via the navigator.permissions.query function.
However you can access Safari's clipboard via navigator.clipboard instead.
You'll find that only the more recent versions of Safari supports query so make sure you check for availability: navigator.permissions && navigator.permissions.query({ ...

Safari clipboard permissions checking


For a given matrix $X$, find two linearly independent vectors in $C(X)^{\perp}$.

Question: Let $$X = \begin{pmatrix}
1 & 1 & 4 \\
1 & 2 & 1 \\
1 & 3 & 0 \\
1 & 4 & 0 \\
1 & 5 & 1 \\
1 & 6 & 4 \end{pmatrix}$$
Is there an easy way to calculate the form of a vector in $C(X)^{\perp}$, $C(X)$ being the column space of $X$?
What is unfortunate is that $C(X) \neq \mathbb{R}^6$ (of course that would be too easy...).
I mean, I could start by noticing that
$$C(X) = \left\{\left.\begin{pmatrix}
a_1 + a_2 + 4a_3 \\
a_1 + 2a_2 + a_3 \\
a_1 + 3a_2 \\
a_1 + 4a_2 \\
a_1 + 5a_2 + a_3 \\
a_1 + 6a_2 + 4a_3
\end{pmatrix}\right\vert a_i \in \mathbb{R}\right\}$$
but this doesn't seem to be at all helpful since I would have to dot this with some fixed vector in $\mathbb{R}^4$, impose some conditions on the $a_i$ since they are arbitrary, and use those conditions to solve for the components of the fixed vector. [Unless, for some reason, this is actually how you are supposed to solve it!]
If helpful at all, I have an orthogonal basis for $X$, found here.
Comment: I take it that $C(X)$ is the column space of the matrix $X$.
Comment: @MathNewbie Yes.
Comment: You can find the nullspace of $X^T$.
Answer: Hint:
Do you know how to find a basis for the null space of a given matrix?  If so, it is a fact that $C(A)^\perp = N(A^T)$ for any matrix $A$.  That is, take the transpose of your matrix and find a basis for its null space, and the result will give you what you are looking for.
For troubleshooting purposes, I have gone through some of the process below.

So if we have the matrix: $$X = \begin{pmatrix}
1 & 1 & 4 \\
1 & 2 & 1 \\
1 & 3 & 0 \\
1 & 4 & 0 \\
1 & 5 & 1 \\
1 & 6 & 4 \end{pmatrix}$$
Then: $$X^T = \begin{pmatrix}
1 & 1 & 1 & 1 & 1  & 1 \\
1 & 2 & 3 & 4 & 5 & 6 \\
4 & 1 & 0 & 0 & 1 & 4\end{pmatrix}$$
If we wish to find a basis for the null space of $X^T$, we consider the system $X^T \mathbf{x} = 0$.  The first step to finding a solution set to such homogeneous systems is, of course, to put $X^T$ into reduced row echelon form:
$$\operatorname{rref}(X^T) = \begin{pmatrix}
1 & 0 & 0 & 1/2 & 3/2 & 7/2 \\
0 & 1 & 0 & -2 & -5 & -10 \\
0 & 0 & 1 & 5/2 & 9/2 & 15/2 \end{pmatrix}$$
This tells us that the components of the vector $\mathbf{x}$ satisfy the following system:
\begin{align}
& x_1 = (-1/2)x_4 - (3/2)x_5 - (7/2)x_6 \\
& x_2 = 2x_4 + 5x_5 + 10x_6 \\
& x_3 = -(5/2)x_4 - (9/2)x_5 - (15/2)x_6
\end{align}
And $x_4, x_5, x_6$ are so-called free variables.  Now there's just one more step to finish up.


Martingale that is not a Markov process

Question: 1. On the internet, it is suggested that
$$
X_t=\left(\int_0^t X_s \;ds\right)\;dW_{t}
$$
is a martingale, but not a Markov process. I understand that the process
$$
I_t(C)=\int_0^t C_s \; dW_s$$
is a martingale, but I don't see $X_t$ as an Ito's integral. In order to show it is a martingale but not a Markov process, I want to show that
$$
E(X_t\mid\mathcal{F}_{t-1})=X_{t-1}\neq E(X_t\mid\sigma(X_{t-1})).
$$
I don't know how to take the expecation in this case.
Other counterexamples available online might be wrong. (Or, I could
be wrong.)

2. Invalid counterexample: Let $e(t)$ be a random variable which is not independent of
$y(0)$ and
$$
y(t)=y(t-1)+e(t)-E{[}e(t)|F(t-1){]}.
$$
Then y(t) is a martingale but it is not a Markov process.
I will show that it is both a martingale and a Markov process. Define $X_{t}$ as
$$
X_{t}=X_{t-1}+e_{t}-E\left(e_{t}|\mathcal{F}_{t-1}\right)
$$
Then, $\{X_{t}\}$ is a martingale because
$$
E(X_{t}|\mathcal{F}_{t-1})  =  E\left(X_{t-1}+e_{t}-E\left(e_{t}|\mathcal{F}_{t-1}\right)\bigg|\mathcal{F}_{t-1}\right)
  =  E(X_{t-1}|\mathcal{F}_{t-1})+E\left(e_{t}|\mathcal{F}_{t-1}\right)-E\left(e_{t}|\mathcal{F}_{t-1}\right)
 = E(X_{t-1}|\mathcal{F}_{t-1})
  =  X_{t-1}
$$
However, it is also a Markov process.
$$
E(X_{t}|\sigma(X_{t-1})) =  E\left(X_{t-1}+e_{t}-E\left(e_{t}|\mathcal{F}_{t-1}\right)\bigg|\sigma(X_{t-1})\right)
  =  E(X_{t-1}|\sigma(X_{t-1}))+E\left(e_{t}|\sigma(X_{t-1})\right)-E\left(E\left(e_{t}|\mathcal{F}_{t-1}\right)\bigg|\sigma(X_{t-1})\right)
$$
Since $\sigma(X_{t-1})\subset\mathcal{F}_{t-1}$, by the towering property,
$$
E\left(\left(e_{t}|\mathcal{F}_{t-1}\right)\bigg|\sigma(X_{t-1})\right)=E\left(e_{t}|\sigma(X_{t-1})\right).
$$
Thus
$$E(X_{t}|\sigma(X_{t-1}))  =  E(X_{t-1}|\sigma(X_{t-1}))+E\left(e_{t}|\sigma(X_{t-1})\right)-E\left(e_{t}|\sigma(X_{t-1})\right)
  =  E(X_{t-1}|\sigma(X_{t-1})
$$
Since $X_{t-1}$ is $\sigma(X_{t-1})$-measurable, $E(X_{t-1}|\sigma(X_{t-1}))=X_{t-1}$. Thus $$
E(X_{t}|\sigma(X_{t-1}))=X_{t-1}=E(X_{t}|\mathcal{F}_{t-1})
$$
Hence $\{X_{t}\}$ is also a Markov process.

3. Invalid counterexample from the textbook answer key. Alison Etheridge's textbook gives an example:
$$
S_{n+1}=S_{n}+\xi_{n+1}
$$
where $\xi_{n}\in\{-1,1\}$ and $\{\xi_{n}\}_{n\geq0}$ are iid. Then, $$
P\left(S_{n+1}=k+1\bigg|S_{n}=k\right)=p \text{and }P\left(S_{n+1}=k-1\bigg|S_{n}=k\right)=1-p.
$$
The author claims that $\left\{ S_{n}\right\} $ is a Markov process.
Then in the homework answer key, someone gives $\left\{ Z_{n}\right\}$ as a counterexample of a martingale not being a Markov process:
$
\displaystyle{Z_{n}=\sum_{i=1}^{n}\xi_{i}}
$
where $P(\xi_{i}=1)=\frac{1}{2}=P(\xi_{i}=-1)$.
Obviously, $Z_{n+1}=Z_{n}+\xi_{n+1}.$ So what's the difference between this counterexample and the example? Moreover, given $P(\xi_{i}=1)=\frac{1}{2}=P(\xi_{i}=-1)$, I think
is both $\left\{ Z_{n}\right\}$ is both a martingale and a Markov process.
Comment: **1.** the definition of $X$ is incorrect - it seems that there should be $dX_t$. Could you give a link for this example?
$$ $$
**2.** and **3.** - I think you are right and your calculations are correct (in **2.** I assume that $\mathcal F_t$ is a natural filtration of $y$ or $X$ in your notation). In **3.** you have a random walk which is a Markov process, and a martingale if its jump has a zero mean.
Comment: @Ilya, Thanks for the editing. The link is here http://www.wilmott.com/messageview.cfm?catid=8&threadid=11322
Comment: Here is another example I mentioned: http://mathforum.org/kb/thread.jspa?forumID=231&threadID=496916&messageID=1519517  I need a valid counterexample. Thank you!
Answer: There is a pervasive mistake in your post, possibly explaining your trouble, which is to believe that $(X_t)_{t\geqslant0}$ being a Markov process means that $\mathrm E(X_t\mid \mathcal F_{t-1})=\mathrm E(X_t\mid X_{t-1})$ for every $t\geqslant1$, where $\mathcal F_t=\sigma(X_s;0\leqslant s\leqslant t)$ for every $t\geqslant0$.
This is not the definition of the Markov property. The Markov property is the assumption that, for every $t\geqslant1$, the conditional distribution of $X_t$ conditionally on $\mathcal F_{t-1}$ depends on $X_{t-1}$ only. Obviously, if the conditional distribution of $X_t$ conditionally on $\mathcal F_{t-1}$ is the conditional distribution of $X_t$ conditionally on $X_{t-1}$ (Markov), then the same is true for the conditional expectations (the property you think is Markov), but the converse is not true.
For a counterexample, assume that $(Z_t)_{t\geqslant2}$ is independent, integrable, centered, non constant (say, with a standard normal distribution), and independent on $X_0$. Let $X_1=X_0=1$ and $X_t=X_{t-1}+Z_tX_{t-2}$ for every $t\geqslant2$.
Then $\mathrm E(X_t\mid \mathcal F_{t-1})=\mathrm E(X_t\mid X_{t-1})=X_{t-1}$ for every $t\geqslant1$ (hence, if $X_0$ is integrable, $(X_t)_{t\geqslant0}$ is a martingale)  but $(X_t)_{t\geqslant0}$ is not a Markov process since the conditional distribution of $X_t$ conditionally on $\mathcal F_{t-1}$ does not depend on $X_{t-1}$ only but on $(X_{t-1},X_{t-2})$.
Comment: By the way, rereading your comments, I wonder whether you would know how to prove the property you declared *true for sure*. In my opinion, to prove it in details would be highly enlightening.
Comment: Thanks for the reply. Could you please show more details? I don't understand how to show $E(Z_tX_{t-2}|X_{t-1})=0$. I did use the definition of Markov property: $E(X_{t}|\mathcal{F}_{t-1})=E(X_{t}|\sigma(X_{t-1}))$. Following your own link of wiki, you can see this under "Alternative Formulations".
Comment: No, you forgot *for all $f$ bounded and measurable*. So I was right, this is really the point where there is a deep misconception in your view of Markovianity.
Comment: Re your question about $E(Z_tX_{t-2}\mid X_{t-1})$, a general result you might wish to use is that if $U$ is independent on $(V,W)$, then $E(UV\mid W)=E(U)E(V\mid W)$.
Comment: Thanks. Yes, that property is true for sure. However, $E(Z_tX_{t−2}∣X_{t−1})=Z_tE(X_{t−2}∣X_{t−1})=0$ ? I guess, since your assumption is about the $Z_t$ being symmetric Bernoulli, you would in the end use the expectation of $Z_t$ to get the zero.
Comment: Please read my comment again: the RHS has a factor E(U), not U.
Comment: OK. That explains. Thank you.
Comment: Oh, I don't know how to do it. I just know that when they are independent then we have $E(UV)=E(U)E(V)$. If it is conditional on the $\mathcal{F}$, I don't know how to show $E(UV|\mathcal{F})=E(U)E(V|\mathcal{F})$.
Comment: "Oh, I don't know how to do it." Wow. What can one say...

Martingale that is not a Markov process


Splitting large XML files into manageble sections for Hadoop

Question: Is there a input class to deal with [multiple] large XML files based on their tree structure in Hadoop? I have a set of XML files that are of the same schema, but I need to split them into sections of data, as opposed to breaking the sections up.
For example the XML file would be:
<code><root>
  <parent> data </parent>
  <parent> more data</parent>
  <parent> even more data</parent>
</root>
</code>
I would define each section as:
/root/parent.
What I'm asking is: Is there a record input reader already included for Hadoop to do this?
Comment: How important is the performance? record input reader would be ok, but very slow... would that be acceptable?
Comment: eh.. its a school assignment so performance is not a big deal ... but it would be preferable
Comment: Shouldn't that be listed as an answer instead of comment?
Comment: wasn't sure it answers your question or not :)
Answer: I think the Cloud9 project at UMD might help you with this.
The library provides has an XMLInputFormat class which might be of use.
Also of interest is this page in the Cloud9 documentation which looks at how you can deal with an XML dump of Wikipedia in MapReduce.


Create Custom events in Namespaces

Question: I need to create custom events in a javascript NameSpace, but i dont know if its possible.
I have a namespace like this:
NAMESPACE = {

   var1 : 'value',
   var2 : 'value',

   initiate : function() {
      console.log('initiate');
   },

   clear : function(arg) {
      console.log('clear');
   }

   fail : function() {
       // Here i need to trigger the error event..
   }

}

That creates events using this method:
var myEvent = new CustomEvent("errorX", {
  data: {
    param: "value"
  }
});

document.dispatchEvent(myEvent);

// In document.ready...
$(document).on('errorX', function(e) {
   console.log(e);
});

This works, but I need to attach the addEventlistener to the document and I would like to attach this to the namespace object, like:
$(NAMESPACE).on('errorX', function(e) {
    console.log(e);
});

It this possible?
Answer: You can use the .triggerHandler method:
$(NAMESPACE).on('errorX', function(e) {
    console.log(e);
});

$(NAMESPACE).triggerHandler("errorX");

demo: http://jsfiddle.net/Enq9h/
Comment: @Zenth you don't need `.dispatchEvent` at all, jQuery doesn't use it. It uses `.triggerHandler`/`.trigger`
Comment: I update your example trying to make similar to my code, but dont get the event params.. possible reason?
Comment: @Zenth you can pass arguments in the second argument as an array: http://jsfiddle.net/Enq9h/3/ I also recommend `.triggerHandler` over `. trigger` because it's optimized for custom events on normal objects.
Comment: OK, its possible to do this without jQuery? (Using only jquery in the "$(NAMESPACE).on('errorX..")
Comment: @Zenth yes if you make your custom event library or use existing one. But if you are already using jQuery you might as well use it.

Create Custom events in Namespaces


PyQt5 Change progress bar backround of Cells to transparent and adjust text properties

Question: I have a table with cells that have percentage values and the corresponding progress bar updating every 2 seconds.  I don't know if it is the most efficient way to do it, but it seems to be working ok.  But I am trying to get the background of the cells transparent (at the moment it is a light grey) and I want to align the text to the right and vertically central) and be able to set the text colour.  The code is below but the section that changes the text and background isn't working.  If someone could explain the issue that would be great thanks.
main.py
import sys
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QApplication
from table_layout import TableExample
from PyQt5.QtCore import QTimer
import random

def generate_data(rows, columns):
    data = []
    for _ in range(rows):
        row = [random.randint(1, 100) for _ in range(columns)]
        data.append(row)
    return data

def update_data():
    global ex  # Access the TableExample instance
    rows = 50
    columns = 6
    new_data = generate_data(rows, columns)
    ex.updateTable(new_data)

def main():
    app = QApplication(sys.argv)
    # Generate initial data
    rows = 50
    columns = 6
    generated_data = generate_data(rows, columns)
    # Specify colors for each column
    column_colors = [
        QColor(255, 0, 0),  # Red
        QColor(0, 255, 0),  # Green
        QColor(0, 0, 255),  # Blue
        QColor(255, 255, 0),  # Yellow
        QColor(255, 0, 255),  # Magenta
        QColor(0, 255, 255),  # Cyan
    ]

    global ex  # Make ex accessible from update_data function
    ex = TableExample(generated_data, column_colors)
    # Set up QTimer to update data every 2 seconds
    timer = QTimer()
    timer.timeout.connect(update_data)
    timer.start(2000)  # 2000 milliseconds = 2 seconds
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

table_layout
from PyQt5.QtWidgets import QMainWindow, QTableWidget, QTableWidgetItem, QProgressBar
from PyQt5.QtGui import QColor
from PyQt5.QtCore import Qt

class TableExample(QMainWindow):
    def __init__(self, data, column_colors):
        super().__init__()
        self.data = data
        self.column_colors = column_colors
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Progress Bars')
        self.setGeometry(100, 100, 600, 400)

        rows = len(self.data)
        columns = len(self.data[0])

        self.table = QTableWidget(self)
        self.setCentralWidget(self.table)  # Set the table as central widget

        self.table.setRowCount(rows)
        self.table.setColumnCount(columns)

        # Set column titles
        column_titles = ["ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX"]
        self.table.setHorizontalHeaderLabels(column_titles)

        for col in range(columns):
            color = self.column_colors[col]
            for row in range(rows):
                progress = QProgressBar()
                value = self.data[row][col]
                progress.setValue(value)

                style = f"QProgressBar::chunk {{background-color: {color.name()};}}"
                progress.setStyleSheet(style)

                #####below isn't aligning text and changing background colour of cells to transparent)
                item = QTableWidgetItem()
                item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)  # Align text to the right and center vertically
                item.setForeground(QColor("blue"))  # Set text color to blue
                item.setBackground(QColor(0, 0, 0, 0))  # Set transparent background
                self.table.setItem(row, col, item)  # Set the QTableWidgetItem
                item.setText(str(value))

                self.table.setCellWidget(row, col, progress)

        self.show()

    def updateTable(self, new_data):
        rows = len(new_data)
        columns = len(new_data[0])

        for col in range(columns):
            for row in range(rows):
                new_value = new_data[row][col]

                # Update QTableWidgetItem
                item = self.table.item(row, col)
                item.setText(str(new_value))

                # Update QProgressBar
                progress = self.table.cellWidget(row, col)
                progress.setValue(new_value)

Answer: The text and color is properly set, but it's not visible because the progress bar occupies the whole cell (the gray you see is the background of the progress bar), and cell widgets are stacked on top of item cells, so you should theoretically make the progress bar background transparent in the stylesheet:
style = f'''
    QProgressBar {{
        background: transparent;
    }}
    QProgressBar::chunk {{
        background: {color.name()};
    }}
'''

This won't be acceptable, though: the value would be shown twice (the item and the progress bar), and even if you hide the progress bar text (by calling QProgressBar.setFormat() with an empty string), the filled region will eventually cover the item text as soon as the value is closer to 100.
In general, using widgets for such a purpose is discouraged, and proper item delegates should be used instead. Not only they require much less resources (you don't need a widget for each cell), but they make value updates much more direct and consistent.
To achieve this, the value should be set as a number (not a string), and a custom user role must be used in order to show different progress bar colors.
ProgressColorRole = Qt.UserRole + 1

class ProgressDelegate(QStyledItemDelegate):
    def paint(self, qp, opt, index):
        progress = index.data()
        if isinstance(progress, (int, float)):
            color = index.data(ProgressColorRole)
            if not isinstance(color, QColor) or not color.isValid():
                color = QApplication.palette().highlight()
            rect = QRectF(opt.rect)
            rect.setWidth(rect.width() * progress / 100)
            qp.save()
            qp.setPen(Qt.NoPen)
            qp.setBrush(color)
            qp.drawRect(rect)
            qp.restore()
        super().paint(qp, opt, index)

class TableExample(QMainWindow):
    ...
    def initUI(self):
        self.setWindowTitle('Progress Bars')
        self.setGeometry(100, 100, 600, 400)

        self.table = QTableWidget(self)
        self.setCentralWidget(self.table)
        self.table.setItemDelegate(ProgressDelegate(self.table))

        self.updateTable(self.data)

    def updateTable(self, data):
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(data[0]))

        column_titles = ["ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX"]
        self.table.setHorizontalHeaderLabels(column_titles)

        for row, rowData in enumerate(data):
            for col, value in enumerate(rowData):
                item = self.table.item(row, col)
                if item is None:
                    item = QTableWidgetItem()
                    item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
                    item.setForeground(Qt.blue)
                    item.setData(ProgressColorRole, self.column_colors[col])
                    self.table.setItem(row, col, item)

                item.setData(Qt.DisplayRole, value)

I strongly recommend you to carefully read through the Qt Model/View Programming documentation, and look for resources about delegates, including posts here on StackOverflow.
Comment: Thanks for the correct working solution, detailed information and suggestion, I really appreciate it :)


How to summarise the ordering pattern of a set of four stimuli by participants?

Question: I did an experiment where I asked 13 participants to order 4 stimuli (let's call them stimulus A, B, C and D), so there are 24 possible ways to order 4 items.
Now I would like to know how to analyze this data in the correct way.
Indeed I would like to say that on average a certain order configuration has been preferred.
For example I would like to say that considering all the configurations
expressed by a participant, the following represents better the order preference of the participants

stimulus D
stimulus B
stimulus C
stimulus A
Comment: Paired-preference models have been discussed on these related threads: [Testing the importance of an item among a finite set of items](http://bit.ly/qGJQtn), [Multinomial choice with binary observations](http://bit.ly/pMt0Lr). The problem here, as pointed out by @whuber in his comment, is the sample size.
Answer: One approach would be to think in terms of pairwise comparisons and apply the Bradley Terry model.  A person who ranks the items as D,B,C,A would be equivalent of saying D beats B, D beats C, D beats, A, B beats C, B beats A, and C beats A.  Then another person with a different order would result in a different set of pairwise comparisons.  You would then combine all the pairwise comparisons and get a set of rankings of the 4 choices.
Comment: Let me add to Greg Snow's answer that, doing pairwise comparisons, you ought probably to recognize psychological exponentiality of ranking. Usually, drop from 1st place to 2nd is steeper than from 2nd to 3rd, and so on. So, in ranking D,B,C,A you might let distance D-B be 1, B-C be, say, 0.5, C-A be 0.25.
Comment: Yes, I see the point. Actually the distance between stimuli in my case is identical.
Answer: You would want to convert the orderings into a categorical variable that takes 24 values, and analyze that variable. The test whether all combinations are equally likely will be given by a Pearson test with the null that all proportions are equal to 1/24. (By a rule of thumb of having an expected count of at least 5, you need at least 120 total participants.) For fancier analysis, you can formulate this as a multinomial logit model, again with 24 categories. (You would have to have all the possible combinations in the data set for this to work out.) An intercept-only model your model will tell you the relative probabilities (or rather log odds ratios against a selected baseline alternative), and you can test that all the coefficients (plus the baseline of zero) are smaller than the selected alternative. This is a difficult test per se, mind you, since you are talking about a multivarate one-sided alternative, so the distribution of the test statistic is a non-standard sum of $\chi^2$ with different degrees of freedom. (I am not sure you even want to mess with that; an extremely conservative approximation is to use $\chi^2_{23}$ or whatever the degrees of freedom of the test would come to be.)
Note that if you first pick the most frequently preferred combination in your data, and then test against, it would be data snooping with no control over type I error. The only way this test would work if your most preferred ordering came from some sort of substantive consideration (e.g., brandy is better than wine, which in turn is better than beer, which in turn is better than milk).
Comment: It appears this technique effectively ignores the information about preferences encoded by the 24 categories.  Obviously it's not going to work with just 13 observations.  But even in general it doesn't seem to address the question.
Comment: Ok, thanks to everybody for your precious answers and comments. The question now is: what I can say with only 13 participants? And If I had even less participants? Should I apply the techniques you suggested or maybe it does not make too much sense to have such a small sample?
Comment: 13 isn't great sample but there's no reason to discard it. You could, for example, do what Greg recommended and obtain 13 rectangular matrices which you may cluster or multidimensionally scale. Also, Kemeny median could be computed, showing central tendency for your 13 rankings.
Comment: Oh. I was not paying attention. With 13 subjects, there's not much you can do, analytics-wise: there is not enough power for anything. MDS or some sort of profile analysis might help seeing the structure in the data, but that's about it.
Comment: Ok, thanks a lot to everybody for the precious help.


Simplest way to let writers edit Views headers/titles without Views UI access?

Question: What's the simplest* way to enable non-technical writers, editors etc to edit the text in Views headers, titles, footers etc, without needing to enable Views UI on a production site, train these non-technical staff to use some of it, and grant them Views UI permissions?

It's common for content staff - writers etc - to have nothing to do with site building tools like Views UI. It's not their remit or expertise. Also, they'll usually be editting content on the production site, while site builder UI tools like Views UI are often disabled on production sites to reduce unnecessary memory consumption (less PHP files to parse for hooks).
But, the text content of the title fields, view headers, etc is within their remit and expertise. What's the simplest way to bring these text snippets - but not the whole Views UI - within their reach?
*Here, 'simplest' means minimal extra modules, minimal complexity in workflow, minimal overheads) Options using Panels are fine in my case. Ideally, I'd prefer to avoid needing to use Display Suite.

The workaround I'm using at the moment, which just about works (but I'm sure there's a simpler way) is this:

I have a custom taxonomy vocabulary, 'Text Snippets'
Each Text Snippet has a name describing to editors where in the interface it is used
Each Text Snippet description contains the HTML to be used
The views' headers are set to 'Render entity' with the ID of the appropriate Text Snippet term written in
To stop the internal-use-only term name being displayed, I have a custom template in my theme templates folder, taxonomy-term--text_snippets.tpl.php, containing nothing but <?php print preg_replace("/
]*>[\s| ]*<\/p>/", '', $description ); ?> (the preg_replace regex removes empty paragraphs)

I'm aware of a module, Snippets, which seems to have a similar idea, but it's not at all clear what the intended usage is, there's very little information - blank readme file, documentation is only placeholders - and the very low usage stats and queue history don't fill me with confidence.
Answer: You can use the  Views UI: Edit Basic Settings module:

"Views UI: Edit Basic Settings" places edit tabs on Views pages, similar to node pages, and allows users with the correct permission to modify their header, footer, title, empty text, or number of items to display. This module also provides a separate interface that displays a list of views. All Views are defined by you, so you can exclude certain Views.
Answer: Make a Taxonomy Vocabulary "Views Title", add terms. Each term represents a 'view'. Taxonomy is entity, so it is field-able. For example, you can use the description field as View's Header; Term name as view's title.
Assign permission to manage "Views Title" Taxonomy for your editor.
Within you module, use "hook_views_pre_render", alter the view title/header to be term's name/description.
Comment: Pretty much the same as the workaround I'm currently doing that I described in the question - good to know I'm not the only one to think that's a good approach though.
Comment: perhaps, use a "helper" content type.


Java: method takes a string and constructs a program that puts out the same string using a for-loop

Question: This is an experiment. My friend is trying to get a grasp on java and writes text outputs like the following example. I wanted to test myself if I could provide a program that could generate them.
For a String, the program should count each character and save how often and at what index it occurred and then generate a for-clause with an if-clause for each character like the following:
I want to put in e.g. "1234123412341234"
and get something like
public class ClauseText {
public static void main(String[] args) {
    for(int i = 0; i < 16; i++) {
        if (i == 0 || i == 4 || i == 8 || i == 12) {
            System.out.print("a");
        }
        if (i == 1 || i == 5 || i == 9 || i == 13) {
            System.out.print("b");
        }
        if (i == 2 || i == 6 || i == 10 || i == 14) {
            System.out.print("c");
        }
        if (i == 3 || i == 7 || i == 11 || i == 15) {
            System.out.print("d");
        }
    }
}
}

What I've come up with is so far is the following. I convert the input String to a char array and iterate through the array. I maintain three array lists, one for the character, one for how often it occurred, and one saves an ArrayList of Integers containing the index position where the character occurred.
To make it simpler, I decided to make all ArrayLists the size 128 and put each character to the index equalling its respective ASCII value.
But it doesn't seem to work, it's a simple Indexoutofboundsexception, however, I don't know what is wrong. Here:
The output only goes this far and then it crashes:
public class ClauseText {
public static void main(String[] args) {
    for(int i = 0; i < 6; i++) {
        if (i == 0 || i == 3) {
            System.out.print("a");
        }
        if (i == 1 || i == 4) {
            System.out.print("b");
        }
        if (i == 2 || i == 5

The program is:
import java.util.ArrayList;

public class StringToProgram {

public static void main(String[] args) {
    // define and create program
    String className = "ClauseText";
    String program = makeProgram("abcabc", className);
}

public static String makeProgram(String myWord, String className) {
    String program = "public class " + className + " {\n";
    program += "    public static void main(String[] args) {\n";
    program += "        for(int i = 0; i < " + myWord.length()
            + "; i++) {\n";
    char[] myWordChar = myWord.toCharArray();

    // For each character, we have to save the index where it occurs and how
    // often. We want to hash it into the ArrayLists by ASCII value.
    ArrayList<Character> characters = new ArrayList<Character>();
    ArrayList<ArrayList<Integer>> indices = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> amounts = new ArrayList<Integer>();

    // Initialize three lists with the size of the ASCII table
    for (int i = 0; i < 128; i++) {
        characters.add(null);
        indices.add(new ArrayList<Integer>());
        amounts.add(0);
    }

    // Now we iterate through each occurrence. We use the ASCII code to hash
    // and find specific letters.
    for (int i = 0; i < myWordChar.length; i++) {

        int index = (int) myWordChar[i]; // the hash value of the char

        if (amounts.get(index).equals(0)) {
            // create new entries and append them to the
            // given index of the lists
            characters.add(index, myWordChar[i]);
            indices.add(index, new ArrayList<Integer>());
            indices.get(index).add((Integer) i);
            amounts.add(index, 1);
        } else {
            // there is already an entry. modify it.
            amounts.add(index, amounts.get(index) + 1); // ++
            indices.get(index).add((Integer) i);
        }
    }

    // Now, we iterate through the occurrences list. First, we check for
    // each index if an object is saved there.
    for (int i = 0; i < amounts.size(); i++) {
        if (amounts.get(i) > 0) {
            // When this is the case, we append an if clause.
            program += "            if (i == ";
            for (int j = 0; j < amounts.get(i); j++) {
                // The amount of options in the if clause depends on how
                // often the character occurred in the string.
                program += indices.get(i).get(j);
                if (j + 1 < amounts.get(i)) {
                    // we still have to append an option
                    program += " || i == ";
                }
            }
            program += ") {\n";
            program += "                System.out.print(\""
                    + characters.get(i) + "\");\n";
            program += "            }\n";
        }
    }
    program += "        }\n";
    program += "    }\n";
    program += "}";

    System.out.println(program);
    return program;
}

}

The error is the following:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at StringToProgram.makeProgram(StringToProgram.java:60)
at StringToProgram.main(StringToProgram.java:8)

Comment: This is kind of Lisp macro. Java is not the best choice for sort of operations. Could you write more about what problem you try to solve?
Comment: Added the error message. This is for a friend who is new to Java. I want her to guess the output of the programs.
Comment: I remember trying to teach my wife Java when we first met...
Comment: Can you please post the error?
Comment: @Vash-DamianLeszczyński: "What problem you try to solve..." almost certainly homework.
Comment: which line is line 60 in your code?
Comment: Line 60: in the third for-loop, in its nested for-loop:     program += indices.get(i).get(j);
Comment: Input "abcabc" as written in main(). I think the error is in the second for-loop when trying to add to the Arraylist indices. It doesn't seem to work very well adding ArrayLists of Integers to an ArrayList.
Comment: @user3788181, If you try to learn someone Java, use examples that you comprehend. IF you create so complex that you can not implement it. How you will explain to 3rd person.
Comment: I don't want to use this to explain something, I want to use its output.
Answer: You get this exception because in some cases list returned in this line does not contain elements.
You need following code:
List<Integer> numbers = indices.get(i);
for (Integer number : numbers) {
    program += number;
    program += " || i == ";
}

instead your code:
program += indices.get(i).get(j);
if (j + 1 < amounts.get(i)) {
   // we still have to append an option
   program += " || i == ";
}

Comment: Thank you. Almost there … the output is
Comment: Tried it. Works most of the time, but sometimes it doesn't enter the loop when it should.
Comment: It enters in the loop always when the list has elements. In your code you are trying to take element from empty list.
Answer: Perhaps you should start simpler:
public class StringToProgram {

    public static void main(String[] args) {
        // define and create program
        String className = "ClauseText";
        String program = makeProgram("a\nbca\rbc", className);
    }

    public static String makeProgram(String myWord, String className) {
        myWord = myWord.replace("\\", "\\\\");
        myWord = myWord.replace("\t", "\\t");
        myWord = myWord.replace("\b", "\\b");
        myWord = myWord.replace("\n", "\\n");
        myWord = myWord.replace("\r", "\\r");
        myWord = myWord.replace("\f", "\\f");
        myWord = myWord.replace("\'", "\\\'");
        myWord = myWord.replace("\"", "\\\"");
        myWord = myWord.replace("\t", "\\t");
        String program = "public class " + className + " {";
        program += "    public static void main(String[] args) {";
        program += "        System.out.println(\"" + myWord + "\");";
        program += "    }";
        program += "}";
        System.out.println(program);
        return program;
    }

}

I didn't use org.apache.commons.lang.StringEscapeUtils for clarity.


Calculate transform horizontal/vertical skew and scale from 2d coordinate

Question: I'm currently working on a javascript which allows to create a 3D rotating cube. I successed to create the 3D cube thanks to 8 points coordinates.
However, I need to add an image on one the cube face. However, I have some difficulties to transform 4 points (p0: {x, y}, p1: {x, y}, p2: {x, y}, p3: {x, y}) in a transform matrix (Horizontal scaling, Horizontal skewing, Vertical skewing, Vertical scaling, Horizontal moving, Vertical moving).
I think I'm not to close of the solution because I success to have the image at the same perspective as a face of the cube. However, the image is not bound to the last point because my calculations doesn't take it into account.
For example I have these 2d coordinate and I calculated the transformation matrix like this (where width is the width of the cube):
<code>Horizontal_scaling = (p0.X - p1.X) / width;
Horizontal_skewing = (p0.Y - p1.Y) / width;
Vertical_skewing   = (p2.X - p1.X) / width;
Horizontal_moving  = (p2.Y - p1.Y) / width;
Horizontal_moving  = p1.X;
Vertical_moving    = p1.Y;
</code>
Here the result of my calculations to better understand my issue: https://fiddle.jshell.net/d749ndLL/
Hope someone could help me with this problem. I didn't make math like this since a long time ago now.
Comment: You might have to compute a *planar perspective transformation* to map the image rectangle onto the cube face. There are various ways to do this that can be found with a web search. I outline one [here](http://math.stackexchange.com/a/1682515/265466).
Comment: Thank you for your answer. I'm not sure to fully understand the whole explanation from your link. I need a practical example because I really not comfortable with these calculation to be honest...
Answer: Without delving into your code, I'm going to assume that you build a cube in a three-dimensional space and have some projection transformation that maps this onto a two-dimensional viewport. If so, then you can take advantage of this projection to simplify the problem to one of mapping a rectangle onto the face of your cube. Once you have that mapping, you then apply the same projection to the three-dimensional points of the mapped image, that is, compose the two transformations.
Computing the rectangle-to-cube-face mapping is a fairly simple task. I assume that the image to be mapped is a rectangle of width $W$ and height $H$ with its lower-left corner at the origin and sides parallel to the coordinate axes. Let $V_0(x_0,y_0,z_0)$, $V_1(x_1,y_1,z_1)$, $V_2(x_2,y_2,z_2)$ and $V_3(x_3,y_3,z_3)$ be the vertices of the cube face to which the lower-left, lower-right, upper-left and upper-right corners of the image, respectively, are to be mapped. Note that we must have $V_3=V_1+V_2-V_0$ for these points to define a face of a cube. So, we want an affine transformation that makes the following mappings:$$\begin{align} (0,0)&\mapsto V_0 \\ (W,0)&\mapsto V_1 \\ (0,H)&\mapsto V_2 \\ (W,H)&\mapsto V_1+V_2-V_0. \end{align}$$ The last constraint is redundant, so we won't be making explicit use of it. A straigforward way to compute this mapping is via homogeneous transformation matrices. Recalling that each column of a transformation matrix is the image of a basis vector, we can construct the matrix of the image-to-cube-face mapping: $$M=\pmatrix{x_0&x_1&x_2\\y_1&y_2&y_3\\z_1&z_2&z_3\\1&1&1}\pmatrix{0&W&0\\0&0&H\\1&1&1}^{-1}=\pmatrix{{x_1-x_0\over W}&{x_2-x_0\over H}&x_0\\{y_1-y_0\over W}&{y_2-y_0\over H}&y_0\\{z_1-z_0\over W}&{z_2-z_0\over H}&z_0\\0&0&1}.$$ The columns of the second matrix in the product on the left are the homogeneous coordinates of the three image corners and the columns of the first matrix are the homogeneous coordinates of the corresponding cube vertices. So, a point $(X,Y)$ on the image is mapped to the point in the cube's 3-D space with $$x=(x_1-x_0)\frac X W+(x_2-x_0)\frac Y H+x_0$$ (and similarly for $y$ and $z$). You can then apply the view projection to these coordinates to get the resulting coordinates of the image point in the viewpoort.
Note that if you're applying some transformation to the cube in order to rotate or otherwise move it (or the camera), then you can include that transformation in the pipeline. Compute the image-to-cube-face map once for the cube in its "home" position, and then compose this fixed mapping with the cube transformation to get the mapping of the image onto the transformed cube.

If instead you need to compute the mapping from the image to the viewport directly, the calculations are a bit messier, but still conceptually pretty simple. Here I assume that the projection from the 3-D model space to the viewport is a perspective projection, which will map the square face of a cube onto a convex quadrilateral. Given two convex quadrilaterals, it is possible to find a planar perspective transformation that maps one to the other. In particular, one can compute a planar perspective map that takes the unit square to an arbitrary convex quadrilateral. This is essentially what you need to map the original image onto the view of the cube face. The image is mapped onto the unit square by dividing image $x$- and $y$-coordinates by its width and height, respectively, as was done above, and then the resulting normalized coordinates mapped to the quadrilateral in the viewport. The coefficients of this planar perspective transformation can be computed by solving a bunch of linear equations, or by pluggin the viewport (projected) coordinates of the cube face into the formulas given here.
Comment: Thank you for your answer. I successed to convert my 4 points into a matrix3D. And the calculation are fine because now the perspective of the image is perfect. However, I need to transform the matrix3d in 3d transform to get the skew in x/y and scaling in X/Y...


Can squid block an access to the specific IP-address which is resolved with a domain name?

Question: I have a .pac file like below.
if (dnsDomainIs(host, ".example.com")) {
    hostip = dnsResolve(host);
    if (isInNet(hostip, "184.108.40.206", "255.255.255.0")) {
        return "DIRECT";
    }
}

Now I'd like to convert this into squid.conf.
A client wants to access to example.com whose IP address would be changed everyday. If the destination IP is in the range 126.96.36.199/24, I need to change the proxy routing(Direct, proxy-A, proxy-B and so on).
I know how to change the proxies with squid.conf but I don't know how to define the access which would access into the IP range from just a domain name. I think squid knows only the destination domain name.
If the client accesses with IP, I can distinguish it. Though if the client accesses with a domain name, I can't.
Does anybody know a squid option for this?
Answer: You can achieve this by setting up combined ACLs that only trigger on a match on dstdomain and dst.
acl addom dstdomain example.com
acl addst dst 18.104.22.168/24
always_direct allow addst addom

Comment: That's perfect for me. I appreciate you so much!


Redirection or Name server addresses

Question: I asked my new webhost:
"I need my domain languagematerial.com to point to my new host: http://languagematerial.altervista.org/ so I must know which are the name server addresses in altervista. I asked my previous host (ipage) where my domain languagematerial.com is parked to do the change or to allow me to do it. Apparently they made a modification, but it's not working right, because my Android cellphone cannot resolve www.languagematerial.com and now takes me to a Internal Server Error page. What can I do?"
The AlterVista staff answered: "you can't point directly via DNS to an AlterVista account.
You can only use a redirect from your domain."
I no longer have an ipage web hosting account... so how to achieve this redirection (and preferably, with address masking)? Could I ask ipage to enable a redirect for free? Or I will be forced to pay ipage or some other company to enable a permanent redirect (with address masking?). Anyway, isn't redirection a behavior included when you "buy" a domain?
So how to proceed? What's the best way to get what I need with the minimal cost? Thanks. Carlos Botero
Comment: proabaly you could have a subdomain A record for languagematerial.altervista.org in your altervista.org control panel with a valid static IP. Use that static IP for languagematerial.com in your control panel @ A record , and create a CNAME record for www that points to langugagematerial.com - Its a wild guess.
Answer: First of all, you still should be able to access your domain's DNS settings if you bought it.
Or you can ask your previous hosting provider to initiate domain transfer to your new hosting provider. Most likely it will cost you, the price will be the same as you would renew your domain for 1 year or so.
To be honest, this is your best option because you will be able to create/edit/delete DNS records for your domain as much as you like or need.
Cheers!

Redirection or Name server addresses


unable to call $stateProvider, twice to update the view (it is only working for the first time)

Question: I have a search books page, in which when I click the search tab, depending on the search criteria, it will display the results in the adjacent block. But when I click it second time, it is not working!
The relevant html code of the page:
<form action="#" method="post" ng-controller = "OptionsController as oCtrl">

         <select class="selectpicker btn btn-default" name="SearchCriteria" id ="sOptions">
                <option value="1">Title</option>
                <option value="2">Author</option>
         </select>

               <textarea id="searchBox" name="searchBox" value="" type="text" autocomplete="on" placeholder="search books"></textarea>

         <input type="button" value="Search" id = "bsearch" class="submit button" ui-sref = ".searchResults">

        </form>

My angular js code for routing
routerApp.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/home');

$stateProvider
.state('books.searchResults', {
    url: '',
    templateUrl: 'html/searchResults.html',
    controller: 'BookController',
});

So, when I click the search button, the results are popped out as expected. Then If I change the options and click the search button again, it is not routing the view (updating the results). Am I doing anything wrong over here?
Comment: Your form should not have an action or method ....
Comment: Removing the action and method didn't resolve the issue. Anyway, I got it and posted the answer
Answer: Reload
Just set your state reload to be true example below
$state.go($state.current, {}, {reload: true}); //second parameter is for $stateParams

Taken from here please give original author props.
Comment: Can you explain this?
Comment: Yeah sure, you can use this on a button click. So try it with that first and then move it to everywhere you change state to get every page to refresh.
Comment: I'm getting an error saying that $stateProvider.go is not a function
Comment: You're just using `$state.go` though right? and you've injected it into the controller right?
Comment: I'm loosing the scope of $stateProvider in the controller (I defined it as $stateProvider instead of $state in the beginning)
Comment: That reloads the complete state
Comment: $state.reload() does reload the resolves, but doesn't reinitialize the controller with the newly resolved values. Since the whole point of reloading the resolves is to refresh the scope with the new data, reinitializing the controller is a requirement for $state.reload() to be of any use.
Answer: I got the answer! By using $state.go in a different state, we can explicitly ask the router to reload the content based on the event triggered.
Then my angularjs code is modified to
routerApp.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/home');

$stateProvider
.state('books.searchResults', {
url: '',
templateUrl: 'html/searchResults.html',
controller: 'BookController',
})

$stateProvider
.state('books.reloader', {
controller: function($state) {
      $state.go('^.searchResults');
    }
});

and in the form,
<input type="button" value="Search" id = "bsearch" class="submit button" ui-sref = ".reloader">

This answer was taken from this post