Q:

Determine if a number is prime without using arithmetic

Write a program which determines if a given number is prime.
The catch: No digits or arithmetical operators. This means:

No digits from 0 to 9, anywhere in the program, and whatever the meaning
No using any built-in operators for addition (and incrementing), subtraction (and decrementing), multiplication, division, exponentiation, or modulus, anywhere in the program
This includes symbols like + and functions like num.add()
All other operations are permitted
You may define your own functions for the forbidden operations
You may use symbols like - when they mean things other than the forbidden operations

Shortest code wins - any language permitted.
Example solution
An ungolfed solution in Java can be found here.

A:

PHP, 117 characters
This one is based on regular expressions. If a string containing $n characters can be split into chunks of equal length, then $n must be composite.
(Assumes $n is a positive integer.)
function p($n){$u=true;$s=str_repeat('x',$n);return($s!='x'&&!preg_match('/^(xx{'.$u.',})\\'.$u.'{'.$u.',}$/U',$s));}

Output:
for ($i=1; $i<=100; $i++) if (p($i)) echo "$i ";

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

A:

Sage, 18
Looks like this is allowed.
input()in Primes()

3 gives True, 4 gives False

A:

PERL 53 54 52 48
('a'x($_=pop))=~/^a?$|^(?<a>aa+?)\g{a}+$/||print

Thanks to reddit: http://www.reddit.com/r/programming/comments/crmhe/regular_expression_to_check_for_prime_numbers_1111/


Q:

Wiki search options

For example I have 2 wiki pages. First page includes such keywords as AD.180, AD.159, AD.200, second page includes keywords AD.300, AD.180, AD.159. If I search for AD.300 it displays me all pages which have AD before the number. Search doesn't take the AD.300 as a whole word, it searches for everything what has AD, not only AD.300.
How do I solve it?
Thanks.

A:

Use double quotes to find exact phrases. If you want to learn about "AD.300" and don't want a bunch of results that include documents that include the word. This tells the search engine to find the exact phrase inside the quotes.
Look about more nice tips about search http://www.networkworld.com/article/2222853/microsoft-subnet/10-essential-sharepoint-search-hints.html


Q:

Proof of Jensen's theorem on roots and circles

Show that if a polynomial $P(z)$ is a real polynomial not identically constant, then all nonreal zeros of $P'(z)$ lie inside the Jensen disks determined by all pairs of conjugate nonreal zeros of $P(z)$.
I found some sources that call it "Jensen's theorem".
I tried to prove it using logarithmic derivative and finding a contradiction but I don't find it.
Could you please provide me some hints (without use of Gauss Lucas theorem) ?

A:

If $z$ lies outside the closed Jensen disc between $\alpha$ and $\overline{\alpha}$ then the angle between $z-\alpha$ and $z-\overline{\alpha}$ is acute.  That is, $$\operatorname{Re}\left((z-\alpha)(\overline z - \alpha)\right)> 0.$$ If you also take $\operatorname{Im}(z) > 0$ then
$$\begin{eqnarray}
\operatorname{Im}\left(\frac1{z-\alpha} + \frac1{z-\overline{\alpha}}\right) &=& \operatorname{Im}\left(\frac1{z-\alpha} - \frac1{\overline z-\alpha}\right) \\[1ex]
&=& \operatorname{Im} \left( \frac{\overline z - z}{(z - \alpha)(\overline z - \alpha)} \right) \\[1ex]
&=& \operatorname{Im} \left( \frac{-2 \mathrm i \operatorname{Im}(z)}{(z - \alpha)(\overline z - \alpha)} \right) \\[1ex]
&=& -2 \operatorname{Im}(z) \operatorname{Re} \left( \frac1{(z - \alpha)(\overline z - \alpha)} \right) \\[1ex]
&<& 0.
\end{eqnarray}$$
(Where we use the fact that $\operatorname{Re}(w) > 0$ if and only if $\operatorname{Re}(w^{-1}) > 0$.) Now apply this to the logarithmic derivative of $P$.


Q:

Angular 2 Select/unselect all checkbox

i want to select/unselect all checkbox. i tried refering other code but nothing worked for me
below is my code. selecting unseleting particular unit is working for me. basically when i clicks on div it selects/unselects checkbox and adds color to it. but i am confused with select all/unselect all
please help me to do it with my code

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { ReactiveFormsModule, FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
  <form [formGroup]="form">

    <input type="checkbox" />Select all
    <input type="checkbox" />unSelect all

          <input type="checkbox" formControlName="{{i}}"/>

{{ unit.num }}

{{ unit.desc }}

  </form>
  `,
  styles: [`.unit-selected { color: red; }`]
})
export class App implements OnInit{
  private units = [
    {num: 1, desc: 'Decription'},
    {num: 2, desc: 'Decription'},
    {num: 3, desc: 'Decription'},
  ];
  private form: Form;

  constructor (private fb: FormBuilder) {}

  ngOnInit () {
    this.form = this.fb.group({
      unitArr: this.fb.array(
        this.units.map((unit) => {
          return this.fb.control(false); // Set all initial values to false
        })
      )
    });
  }

  // Shorten for the template
  get unitArr (): FormArray {
    return this.form.get('unitArr') as FormArray;
  }

  onClick(i) {
    const control = this.unitArr.controls[i];
    control.setValue(!control.value); // Toggle checked
  }
}

@NgModule({
  imports: [ BrowserModule, ReactiveFormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

A:

Making a combination of the comments provided by Rahul and ncohen we can use patchValue here.
As for the unselecting all checkboxes, I changed it to a button in this answer, to me it seemed that a checkbox wasn't really suitable (?) because of handling the tick in the checkbox. But that is up to you if you rather use a checkbox :)
As for checking if the "Select All" checkbox should be checked or not, you can do:
[checked]="checkAllSelected()"

and then in TS:
checkAllSelected() {
  return this.form.controls.unitArr.controls.every(x => x.value == true)
}

Here we then must remember that this is run on each change detection. So perhaps you'd want to use a variable instead, that is of course depending on the case, i.e how costly this would be for you, but I don't think it would be in this case.
So this is how your template could look like:

   <input type="checkbox" [checked]="checkAllSelected()"
         (click)="selectAll($event.target.checked)"/>Select all

<button (click)="unselectAll($event.target.checked)">Unselect All</button>

where we pass the status of the checkbox to template and evalate to either check all or uncheck all:
selectAll(isChecked) {
  if isChecked
     this.form.controls.unitArr.controls.map(x => x.patchValue(true))
  else
     this.form.controls.unitArr.controls.map(x => x.patchValue(false))
}

And of course when user clicks the uncheck button:
unselectAll() {
  this.form.controls.unitArr.controls.map(x => x.patchValue(false))
}

DEMO: http://plnkr.co/edit/O194WEimjf3XzfiIrWF0?p=preview


Q:

Why is it not standard practice to run password-based KDF's client-side?

In most protocols I have encountered in which a passphrase is used for authentication it is stored not in plaintext, but a PBKDF digest of it instead. This is obviously good.
However what does not seem to be standard practice is to compute this PBKDF digest on the client-side while registering/updating a passphrase. Instead, it is often sent to the server and then the user is left to only hope they handle it properly.
Why is this so? Am I missing something?

EDIT: Because this was unclear to some, I don't mean to suggest the server-side should not hash. The server should. I'm asking why it's common practice to not hash client-side at all.

A:

I think the main issue are the client side languages (normally JavaScript), they are relatively slow. This would often lead to fewer hashing rounds and therefore weakens security.
If your client side language is fast enough, you could calculate the expensive PBKDF client side, then calculate a cheap hash on server side (SHA512 for example). To get the plaintext passwords an attacker still had to calculate the slow PBKDF. It is also not possible to use the PBKDF directly as password, because only the hash of the PBKDF is stored (the output of a PBKDF2 can be seen as a very strong "password", so it is safe to use a cheap hash function).
One downside is, that the handling will become more complex, you need to send salt and cost factor to the client for verification of the entered password. Another problem is to ensure integrity of the client side code, if somebody could alter the delivered JavaScript code, he could return a known string and you would store the now unsafe PBKDF.


Q:

Merge or combine two arrays - only if specified id exists

I would like to combine two arrays, but I don't know which is the right method (array_merge, array_combine, array_unique) in my case.
First array:
Array
(
    [0] => Array
        (
            [id_person] => 194
            [firstname] => Jesper
            [lastname] => Hansen
            [pos] => 29
            [position] => 1
            [starter] => 0
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

    [1] => Array
        (
            [id_person] => 195
            [firstname] => Mikkel
            [lastname] => Andersen
            [pos] => 1
            [position] => 1
            [starter] => 1
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

    [2] => Array
        (
            [id_person] => 197
            [firstname] => Alexander
            [lastname] => Scholz
            [pos] => 6
            [position] => 2
            [starter] => 1
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

    [3] => Array
        (
            [id_person] => 198
            [firstname] => Erik
            [lastname] => Sviatchenko
            [pos] => 10
            [position] => 2
            [starter] => 1
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

    [4] => Array
        (
            [id_person] => 199
            [firstname] => Kian
            [lastname] => Hansen
            [pos] => 14
            [position] => 2
            [starter] => 1
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

    [5] => Array
        (
            [id_person] => 204
            [firstname] => Manjrekar
            [lastname] => James
            [pos] => 30
            [position] => 2
            [starter] => 0
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

[6] => Array
        (
            [id_person] => 236
            [firstname] => Sebastian
            [lastname] => Buch
            [pos] => 14
            [position] => 14
            [starter] => 0
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

[7] => Array
        (
            [id_person] => 209
            [firstname] => Joel
            [lastname] => Andersson
            [pos] => 18
            [position] => 3
            [starter] => 1
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )
)

Second array:
Array
(
    [0] => Array
        (
            [id_person] => 195
            [position] => 1
            [first] => Mikkel
            [last] => Andersen
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 1
            [subsmin_in] =>
            [subsmin_out] =>
        )

    [1] => Array
        (
            [id_person] => 236
            [position] => 14
            [first] => Sebastian
            [last] => Buch
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 14
            [subsmin_in] =>
            [subsmin_out] =>
        )

    [2] => Array
        (
            [id_person] => 209
            [position] => 3
            [first] => Joel
            [last] => Andersson
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 18
            [subsmin_in] =>
            [subsmin_out] =>
        )

)

I would like to copy from the first array the starter, subs, goal, yellow card, red card items to the second array (only if id_person from first array exist in the second array)
Desired result:
Array
(
    [0] => Array
        (
            [id_person] => 195
            [position] => 1
            [first] => Mikkel
            [last] => Andersen
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 1
            [subsmin_in] =>
            [subsmin_out] =>
            [starter] => 1
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

    [1] => Array
        (
            [id_person] => 236
            [position] => 14
            [first] => Sebastian
            [last] => Buch
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 14
            [subsmin_in] =>
            [subsmin_out] =>
            [starter] => 0
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

    [2] => Array
        (
            [id_person] => 209
            [position] => 3
            [first] => Joel
            [last] => Andersson
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 18
            [subsmin_in] =>
            [subsmin_out] =>
            [starter] => 1
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

)

I hope that someone could help for me. Many thanks.

A:

If I understand your requirements properly then
you can do it with the help of foreach(), array_search() and array_column() like below,
foreach($second_array as $k=>$v){
    $id_person = $v['id_person'];
    $key = array_search($id_person, array_column($first_array, 'id_person'));
    if($key){
        $second_array[$k]['starter'] = $first_array[$key]['starter'];
        $second_array[$k]['subs'] = $first_array[$key]['subs'];
        $second_array[$k]['yellow_card'] = $first_array[$key]['yellow_card'];
        $second_array[$k]['red_card'] = $first_array[$key]['red_card'];
    }
}
print_r($second_array);

OR using array_merge() instead of 4 lines.
foreach($second_array as $k=>$v){
    $id_person = $v['id_person'];
    $key = array_search($id_person, array_column($first_array, 'id_person'));
    if($key){
        array_merge($second_array[$k],['starter'=>$first_array[$key]['starter'],'subs'=>$first_array[$key]['subs'],'yellow_card'=>$first_array[$key]['yellow_card'],'red_card'=>$first_array[$key]['red_card']]);
    }
}
print_r($second_array);

WORKING DEMO: https://3v4l.org/FeanU

A:

This is another way of tackling the issue:
/*
    Go through both arrays and put the person_id as key in each array
    (e.g. [0]['person_id'] = 197 TO [197]['person_id'] etc)
*/
foreach($first_array as $key=>$item) {
    $first_array[$item['id_person']] = $item;
    unset($first_array[$key]); //remove current item
}
foreach($second_array as $key=>$item) {
    $second_array[$item['id_person']] = $item;
    unset($second_array[$key]); //remove current item
}

/*
    Go through second array. If first array contains the same person_id
    the key for person_id exists, that's why we can use isset() here
*/
foreach($second_array as $key=>$item) {
    if (isset($first_array[$key])) {
        //Just copy the part that you intented from first array
        //to this $second_array
        $second_array[$key]['starter'] = $first_array[$key]['starter'];
        $second_array[$key]['subs'] = $first_array[$key]['subs'];
        $second_array[$key]['goal'] = $first_array[$key]['goal'];
        $second_array[$key]['yellow_card'] = $first_array[$key]['yellow_card'];
        $second_array[$key]['red_card'] = $first_array[$key]['red_card'];
    }
}

This will result in:
Array
(
    [195] => Array
        (
            [id_person] => 195
            [position] => 1
            [first] => Mikkel
            [last] => Andersen
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 1
            [subsmin_in] =>
            [subsmin_out] =>
            [starter] => 1
            [subs] => 0
            [goal] => 3
            [yellow_card] => 2
            [red_card] =>
        )

    [236] => Array
        (
            [id_person] => 236
            [position] => 14
            [first] => Sebastian
            [last] => Buch
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 14
            [subsmin_in] =>
            [subsmin_out] =>
            [starter] => 0
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

    [209] => Array
        (
            [id_person] => 209
            [position] => 3
            [first] => Joel
            [last] => Andersson
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 18
            [subsmin_in] =>
            [subsmin_out] =>
            [starter] => 1
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

)

If you want indexes starting at zero you can just do:
$second_array = array_values($second_array);

and you will have:
Array
(
    [0] => Array
        (
            [id_person] => 195
            [position] => 1
            [first] => Mikkel
            [last] => Andersen
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 1
            [subsmin_in] =>
            [subsmin_out] =>
            [starter] => 1
            [subs] => 0
            [goal] => 3
            [yellow_card] => 2
            [red_card] =>
        )

    [1] => Array
        (
            [id_person] => 236
            [position] => 14
            [first] => Sebastian
            [last] => Buch
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 14
            [subsmin_in] =>
            [subsmin_out] =>
            [starter] => 0
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

    [2] => Array
        (
            [id_person] => 209
            [position] => 3
            [first] => Joel
            [last] => Andersson
            [id_club] => 2
            [type] => 2
            [captain] => 0
            [pos] => 18
            [subsmin_in] =>
            [subsmin_out] =>
            [starter] => 1
            [subs] => 0
            [goal] => 0
            [yellow_card] =>
            [red_card] =>
        )

)

NOTE! I have changed some values just for testing purposes.


Q:

Convert NodeBuilder result to object hierarchy

Imagine nodeBuilder used to express an object hierarchy:
class TestBuilder {

static main(args) {

        def builder = new NodeBuilder()
    def ulcDate = new Date(107,0,1)
    def invoices = builder.invoices{
        invoice(date: ulcDate){

            item(count:5){
                product(name:'ULC', dollar:1499)
            }
            item(count:1){
                product(name:'Visual Editor', dollar:499)
            }
        }
        invoice(date: new Date(106,1,2)){
            item(count:4) {
                product(name:'Visual Editor', dollar:499)
            }
        }
    }

}

   class Invoice {
        List items
        Date date
     }

   class LineItem {
        Product product
        int count
        int total()
        {
            return product.dollar * count
        }
    }

   class Product {
        String name
        def dollar
    }

How do I actually convert invoices object, which was generated by NodeBuilder, to an instance of Invoice class with everything configured from the invoices object? I probably have to have use GPath to do so (?) but how would that code look like?
The reason that I need to do so is that the other methods of other classes require an instance of the Invoice class to operate further and won't accept a NodeBuilder output I guess.

A:

Giving a slight tweak to your base classes:
class Invoice {
  List lineItems = []
  Date date

  String toString() {
    String ret = "Invoice $date $lineItems"
  }
}

class LineItem {
  Product product
  int count

  int total() {
    product.dollar * count
  }

  String toString() {
    "$product * $count"
  }
}

class Product {
  String name
  int dollar

  String toString() {
    "$name ($dollar)"
  }
}

Means you can easily use ObjectGraphBuilder to build your list:
List invoices = new ObjectGraphBuilder(classLoader: getClass().classLoader).with {
  [
    invoice( date: new Date( 107, 0, 1 ) ) {
      lineItem( count: 5 ) {
        product( name: 'ULC', dollar: 1499 )
      }
      lineItem(count:1){
        product(name:'Visual Editor', dollar:499)
      }
    },
    invoice(date: new Date(106,1,2)){
      lineItem(count:4) {
        product(name:'Visual Editor', dollar:499)
      }
    }
  ]
}

If it isn't possible to tweak the base classes, you can customise how properties are looked up by setting the resolvers before building your graph


Q:

align cache for non-POD structure

Suppose there is non-POD struct below, is the alignment taken effect? If not, what would be expected?
struct S1
{
    string s;
    int32_t i;
    double d;
} __attribute__ ((aligned (64)));

EDIT: the output of the sample code below is 64 even s is set to a long string.
int main(int argc,char *argv[])
{

        S1 s1;

        s1.s = "123451111111111111111111111111111111111111111111111111111111111111111111111111";
        s1.i = 100;
        s1.d = 20.123;
        printf("%ld\n", sizeof(s1));
        return 1;
}

A:

Yes, the alignment takes effect in GCC.
Example code:
#include <string>
#include <iostream>
#include <cstddef>
using namespace std;

struct S1
{
    string s;
    int i;
    double d;
} __attribute__ ((aligned (64)));

struct S2
{
    string s;
    int i;
    double d;
} __attribute__ ((aligned)); // let the compiler decide

struct S3
{
    string s;
    int i;
    double d;
};

int main() {
    cout << "S1 " << sizeof(S1) << endl;
    cout << "S2 " << sizeof(S2) << endl;
    cout << "S3 " << sizeof(S3) << endl;
}

Output:
S1 64
S2 16
S3 16

Also: You have observed that S1 is non-POD. Note that std::string is allowed to store its data externally (it usually does so because the data can be of arbitrary length, so a memory buffer must be allocated dynamically).
Remember that sizeof is only calculated during compilation, it can't depend on runtime values. Specifically, you can't ever query a size of dynamically allocated memory this way.
Also remember that every element in an array is always of the same type, so of the same size too.


Q:

Python 3, http.client HTTP error 400

I've been working on a small pet project where I am using http.client to communicate (sorry if that's bad terminology, feel free to correct me) with omdbapi. From here I access the data on the website using the following code:
import http.client, json
__connection = http.client.HTTPConnection("www.omdbapi.com")

def getDetailsFromTitle(title):
    __connection.request("GET", "/?t=" + title)
    return __processRequest()

def getDetailsFromID(id):
     __connection.request("GET", "/?i=" + id)
     return __processRequest()

def __processRequest():
    try:
        response = __connection.getresponse()
        data = response.read()
        data = data.decode("utf-8")
        return json.loads(data)
except: return None

This worked fine for my first few trials, like I was able to get all my data back properly if I looked up say "Eureka", or "Superbad"; however, as soon as I inputted "Bad Kids Go To Hell" my try in __processRequest was being broken and None was being returned.
The data I managed to get from the request was:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request

HTTP Error 400. The request is badly formed.

It's obviously breaking on the json.loads(data) as data isn't what is expected, but I'm not overly sure why I'm receiving this error. I went to the website and inputted "Bad Kids Go To Hell" and all worked fine.
Please let me know if you need anything more to assist me,
Thank you.

A:

To create the parameter lists of your urls, you should use [urlencode()][1]. In this case it's likely the spaces in the string that causes the problem, they should be converted to '+' characters.
__connection.request("GET", "/"+(urlencode({'t': title})


Q:

Where does Android View.scrollTo(x, y) scroll to?

scrollTo(int x, int y) says:

x the x position to scroll to
y the y position to scroll to

onScrollChanged(int l, int t, int oldl, int oldt) says:

l Current horizontal scroll origin.
t Current vertical scroll origin.

What I would like to know and can't find anywhere, is where is x,y? Top left? Center? I tried a few tests and can't figure it out.

A:

After extensive research and testing I've finally understood how scrollTo() works.
(0,0) are the coordinates to the top left corner of the View container. When scrolling to any (x,y) point, the top left corner of the View will be placed at the (x,y) coordinates.
If the View is showing an image, Bitmap, larger than the View itself, scrolling to (0,0) will place the View in the center of the image. This way, the top left corner of the image will be located at (-dX/2, -dY/2) and the bottom right corner at (mW - dX/2, mH - dY/2). dX represents the difference between the widths of the image and the View. And dY represents the difference between the heights of the image and the View.
In order to see the bottom right corner and not go passed it (lower or further to the right), this is the proper call: scrollTo(mW - ivW - dX/2, mH - ivH - dY/2);
The attached image shows the graphical representation of the View and Bitmap image positioning.


Q:

How to escape < or > in a parameter in shell?

I'd like to use grep with a PCRE expression that contains the < character. Bash thinks I want to redirect, but I don't want to. How can I escape <?

A:

I was able to do it with a backslash:
25 % grep \< xmospos.c
#include        <stdio.h>
#include        <stdlib.h>
#include        <getopt.h>
#include        <X11/Xlib.h>

A quoted less-than, and a quoted, backslashed less than both gave goofy answers.

A:

Two simple rules:

A backslash \C escapes the next character, whatever it is, other than a newline.
Single quotes 'text' escape any character between them, including a backslash, but not including a single quote (since it marks the end of the quoted text).

Thus:
grep -P '<html>' myfile
grep -P \<html\> myfile
grep -P '(?<!<)html' myfile
grep -P \(\?\<\!\<\) myfile

If you need to pass an argument that contains single quotes, you can use '\'' to “escape” a single quote inside single quotes. Technically, what this does is end the first literal text, then put a literal ' in the same word, then more literal text still in the same word.
grep '^D'\''oh!' myfile

The rest of the quoting rules (summarized):

You need to quote the following characters at least some of the times: whitespace and !"#$&'()*;<>?[\]^`{|}~ (in other words, the following characters are safe: letters, digits, %+,-./:=@_ and non-ASCII characters).
Between double quotes, all characters are used literally except "$\` and (in shells with history enabled) !. A backslash between double quotes will appear in the string unless it precedes one of the non-literal characters.

These rules are for bash and other Bourne-style shells (such as ash and ksh). They apply to zsh as well (except that = after whitespace may need quoting). The rules in csh/tcsh and in Fish are different.


Q:

Apache Rewrite RULE

People I have been working for days in this and I,m no able to make it work.
I,m trying to do a RewriteRule in my apache server but is not working.
if i use a simple url like this it works perfect.
RewriteEngine On
RewriteRule ^(/.php/m/) htp://www.index.php

but if i use a complex url dont work , something like this:
RewriteEngine On
RewriteRule ^(/index.php?option=com_rsform&Itemid=8&lang=en) htp://www.index.php

does some body know why apache is not understanding this url what i,m missing
index.php?option=com_rsform&Itemid=8&lang=en

A:

The query part is not included when you match an URL with a RewriteRule, see this part of the docs:

What is matched?
The Pattern will initially be matched
  against the part of the URL after the
  hostname and port, and before the
  query string. If you wish to match
  against the hostname, port, or query
  string, use a RewriteCond with the
  %{HTTP_HOST}, %{SERVER_PORT}, or
  %{QUERY_STRING} variables
  respectively.

As suggested by the docs, you can use a RewriteCond expression to match on %{QUERY_STRING}:
RewriteCond %{QUERY_STRING} ^option=com_rsform&Itemid=8&lang=en$
RewriteRule ^index.php$ http://www.index.php

Note that this only works when the query string is exactly the one you're matching. An equivalent query string in which the order of the arguments is changed, f.i. option=com_rsform&lang=en&Itemid=8, will not be matched. So in this case, I think you'd be better to send all requests to your PHP script, and have that look at $_GET and decide whether to forward or not.


Q:

How to move a child node under another child?

I've researched and tried some of the suggestions on stack overflow, but the code doesn't seem to be working.  I've been trying to move a node, by copying and then deleting the node, but everything ends up getting deleted in firebase (original and copied post).
Goal: move the data from under the child "pending" to child "post" after the user hits a button.
I want to move Shelly A. pending post under post.
Firebase database:
-pending
  -childByAutoId()
    -name: Shelly A.
    -post: "Haha"

-posts
  -childByAutoId()
    -name: Josh A.
    -post: "funny"

Code
ref = Database.database().reference()

//copying the node from the child "pending" to child "posts"
self.ref.child("pending").child(event.id!).observe(.value, with: { (snapshot) in
                self.ref.child("posts").child(event.id!).setValue(snapshot.value)

            })
        //deleting the original posts
            self.ref.child("pending").child(event.id!).setValue(nil)

Watching the database, I'm able to get the data copied, but a split second later, the new copied data gets completely deleted with the old post.  Any help?

A:

If you see a change being made briefly before being rolled back, most commonly this happens because you have a security rule that rejects the change.
In that case, the client first fires the local events for the change, then sends the change to the server. Then when it hears back from the server that the change was rejected, it fires local events to get the state correct again.
So it sounds like in your case you are allowed to delete the node from pending, but not allowed to add the data under posts.

A good way to prevent this type of partial operation is to include both the delete and the write in a single, multi-location update operation.
ref = Database.database().reference()

self.ref.child("pending").child(event.id!).observe(.value, with: { (snapshot) in
    var updates = [
        "posts/\(event.id!)": snapshot.value,
        "pending/\(event.id!)": nil
    ]
    self.ref. updateChildValues(updates)
})

With this code, both the write of the new node, and deleting the old node are sent to the database as one operation, so also get accepted or rejected by your security rules as one.


Q:

copy data from one HDFS directory to another continuously

I have a directory in hdfs which gets files populated every 2 days. I want to copy all the files in this directory to another in such a way that if a new file comes in today, I want the file to be copied to the duplicate directory.
How can we do that in Hdfs.
I know we can do that in linux using rsync. Is there any method like this in Hdfs as well?

A:

No, there are no file sync methods available with HDFS. You have to either do hdfs dfs -cp or hadoop distcp manually or through any scheduler (cron).
If the number of files are more, distcp is preferred.
hadoop distcp -update <src_dir> <dest_dir>

The -update flag would overwrite if source and destination differ in size, blocksize, or checksum.


Q:

Entity Framework - No Repository abstraction

In my project, I need to use EF and abstract the queries from the Presentation layer. Based from what I've been reading questions and answers all over the net, EF is built having repository pattern on it's DbSet and Unit of work on DbContext.
Repository pattern can easily do the requirement but I don't wanna repeat this implementation and now confused where should I initialize or access the DbContext. Should it be on the service layer?
MVC4 Api will be used for this project

A:

One way I have seen this done in the past is to essentially remove the DbContext's dependency on a physical database by creating an interface for your context then make your data access calls from your Services Layer (Business Logic Layer).
There is however, a disadvantage in using this approach, which is the fact that your unit tests (which will be using a Fake implementation of your DbContext) will be using LINQ to Objects to run your queries whereas your concrete implementation will use LINQ to Entities which does not support all LINQ to Objects methods.
There's documentation on MSDN (http://msdn.microsoft.com/en-us/library/bb738550.aspx) which highlights these differences.
I also recommend reading this article (http://kearon.blogspot.com.au/2011/02/mocking-entity-framework-4-code-first.html) which demonstrates how to make DbContext unit testable by removing the inderlying dependency on a phyiscal database.
Hope this all helps!


Q:

Keep Windows Installer from using largest drive for temporary files

By default Windows Installer uses the largest drive for temporary storage, no matter if that's needed (meaning there would also be enough space on the system drive).
Taken from http://msdn.microsoft.com/en-us/library/aa371372%28VS.85%29.aspx:

During an administrative installation the installer sets ROOTDRIVE to the first connected network drive it finds that can be written to. If it is not an administrative installation, or if the installer can find no network drives, the installer sets ROOTDRIVE to the local drive that can be written to having the most free space.

Now my system drive is an SSD, my largest drive is a RAID, that spins down when it's not used. Remember the SSD as system drive? Everything is silent now! Until I install something and Windows Installer wakes up my RAID again just to put a small .tmp file on it... How can I prevent Windows Installer from using the largest drive as temporary storage? Can I maybe set some access rights to disallow the Windows Installer to write on my RAID drive? Any other ideas? Thank you!

A:

Editing these entries in the registry (to point to the desired drive, C: in this example) worked for me - Server 2012
HKEY_CLASSES_ROOT\Msi.Package\shell\Open\command
"%SystemRoot%\System32\msiexec.exe" /i "%1" ROOTDRIVE=C:\ %*

HKEY_CLASSES_ROOT\Msi.Package\shell\Repair\command
"%SystemRoot%\System32\msiexec.exe" /f "%1" ROOTDRIVE=C:\ %*

HKEY_CLASSES_ROOT\Msi.Package\shell\Uninstall\command
"%SystemRoot%\System32\msiexec.exe" /x "%1" ROOTDRIVE=C:\ %*

HKEY_CLASSES_ROOT\Msi.Patch\shell\Open\command
"%SystemRoot%\System32\msiexec.exe" /p "%1" ROOTDRIVE=C:\ %*


Q:

How to click drop down (which is not created by select ) using selenium webdriver (eclipse)?

I tried to select a value of the drop down for "Payment Method"  at the following page.
Login to https://my.orderhive.com/
Redirect to  https://my.orderhive.com/orders >> Click "New Order" button
On this page, there is a drop down for "Payment Method". I want to select "Cheque" value for that drop down.
I tried to select using link text, XPath, select & Actions. But, none of them are working.
Actions a = new Actions(driver);
WebElement b = driver.findElement(By.xpath("//[@id=\"footerAction\"]/span"));
a.moveToElement(b).click().perform();

Click Here to See Image

A:

Use Following Code :
WebDriverWait wait =new WebDriverWait(driver,10);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[normalize-space()='Payment Method']//following-sibling::div")));
driver.findElement(By.xpath("//label[normalize-space()='Payment Method']//following-sibling::div")).click();

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='PaymentMethod']//div[@id='footerAction']")));
List<WebElement>options= driver.findElements(By.xpath("//div[@id='PaymentMethod']//div[@id='footerAction']"));

    for (WebElement option : options){
        if (option.getText().equals("Cheque")){
            option.click();
            break;
        }
    }


Q:

Does LD_PRELOAD work on all flavors of unix/linux?

I wrote a simple LD_PRELOAD module, compiled on Ubuntu server. Will this preload work on other systems like Solaris, FreeBSD, CentOS and etc. Are there any special issues on some of the OSes?

A:

The LD_PRELOAD mechanism works across all ELF systems (Linux, Solaris, etc...).
In theory the same library could be usable on different operating systems if the architecture is a match (e.g. an i386 library won't work on Solaris SPARC) but there are many pitfalls. For example, many data structures provided by the C library have different sizes and member arrangements and they will be incompatible between operating systems even if the architecture is the same.
If you are very careful about what functions you call in your LD_PRELOAD library then you may be able to create a library that is compatible between operating systems. You will definitely need to test it.


Q:

18.04 No mouse buttons work

I can login.  I was previously unable to click on the 'next' button on the 'welcome to 18.04' splash after login to finally get that off of my screen.  But now I can't do anything.
My USB mouse cursor moves, but no buttons work; left, middle, right.  I have tried two different mice(?) but still no joy.  The left button works fine on the login purple screen, but then it no long works on the desktop.  I have (login settings) tried both the GNOME on Xorg, an the Ubuntu, but both have the same problem - buttons don't work!
Looking at other suggestions on other answers, I did sudo ubuntu-drivers autoinstall but no joy.  I also do sudo apt update and upgrade, but no joy.
I'm able to login to the computer that has the problem via ssh from another system that is running 17.10.
So my 18.04 computer is totally down and unable to be used.  How can I debug/fix this?

A:

From the comments...
It was the Workspaces to Dock GNOME extension that caused the mouse and keyboard issues. It's a known problem with this extension. Rename the directory back, and then it should be uninstalled at https://extensions.gnome.org/local/
Update #1:
It seems that the latest update to this GNOME extension has fixed this problem.
Update #2:
Although the extension update fixed the original problem, it created new problems with the workspace overview.


Q:

IIS7 + ASP.NET Large Media File Downloading

I'm attempting to make a website that allows large file downloads (downloads in the sense that the browser doesn't try to play the video, or display the text file. I want to force the user to choose a place to save the file) in ASP.NET v4 and IIS7, however I'm facing a few issues with this that quite frankly are annoying me.
Now, I've found a website that provides a way to stream even really large files through the http:
http://www.cnblogs.com/bestcomy/archive/2004/08/10/31950.aspx
The issue with this source however is that I cannot send any other requests to the http while this file is downloading. So if a user were to try and download more than 1 file at a time, it will sit there until the first request is finished.
Is there any way to perform very large media based file downloads, that allows a user to download multiple at a time, and requires a user to choose a place to save it, as opposed to having to right click and save as?
Edit: Just to expand on this, the downloads are behind a Session page (user logged in), so I can prevent unauthorized users from downloading files (security through anonymity is not security :P ). Anyway, I can open a new browser session, and login and download another file (or the same file even), however, any further requests sit there and "load" until the download finishes.
Another Edit: I'm using the Razor MVC Framework, if that changes anything
Thanks!

A:

Now with a bit more context, I think this can be simplified quite a bit:
To allow concurrent downloads you need to ensure the Session is read-only. In MVC3 you'd  decorate your controller with [SessionState(SessionStateBehavior.ReadOnly)], for your custom security checks. Now, I don't know your implementation, but take into consideration that security is usually handled through the use of the Authorize attribute or similar.
Now, to force the prompt for saving the file instead of opening it by default, check Darin's answer in the following post: https://stackoverflow.com/a/5830215/1373170
You can avoid custom code to download the file if the standard FileResult suits your needs.


Q:

Binary to Decimal - java

I want to write a program which receive a string value and print the decimal number.
In addition, if the string value is not 1 or 0, I need to print a message.
I wrote this code but it is always getting inside the if command.
I Would appreciate your support!
Thank you
import java.util.Random;
public class Decimal {

    public static void main(String[] args) {
        String input = (args[0]);
        int sum = 0;
        for (int i = 0; i <= input.length(); i++) {
            if (!(input.charAt(i) == '0') || (input.charAt(i) == '1')) {
                System.out.println("wrong string");
                break;
            }
            char a = input.charAt(i);
            if (a == '1') {
                sum |= 0x01;
            }
            sum <<= 1;
            sum >>= 1;
            System.out.println(sum);
        }
    }
}

A:

The ! (not) operator of the if statement only applies to the first part:
if ( ! (input.charAt(i) == '0')
     ||
     (input.charAt(i) == '1')
   ) {

So that is the same as:
if ((input.charAt(i) != '0') || (input.charAt(i) == '1')) {

When you actually meant to do:
if (input.charAt(i) != '0' && input.charAt(i) != '1') {

It's a good thing though, because once that works, you're going to get an IndexOutOfBoundsException when i == input.length(). Change the loop to:
for (int i = 0; i < input.length(); i++) {

And for performance, move variable a up and use it in that first if statement. Rename to c or ch is more descriptive/common.
Doing both sum <<= 1 and sum >>= 1 leaves you where you started. Is that what you wanted? You should also do the left-shift before setting the right-most bit.
Applying all that, I believe you meant to do this:
String input = args[0];
int sum = 0;
for (int i = 0; i < input.length(); i++) {
    char c = input.charAt(i);
    if (c != '0' && c != '1') {
        System.out.println("wrong string");
        break;
    }
    sum <<= 1;
    if (c == '1')
        sum |= 1;
}
System.out.println(sum);


Q:

Recursive breadth first traversal in Bash

I'm trying to discover why my traversal isn't working.  I believe I've isolated the problem to the point in code where it says "directory contains" and then what was passed to the function.  The function gets passed an array containing all of the new file paths to echo but for some reason it is only receiving the first one.  Am I passing the array incorrectly or could it be something else?
#!/bin/bash

traverse(){
  directory=$1
  for x in ${directory[@]}; do
    echo "directory contains: " ${directory[@]}
    temp=(`ls $x`)
    new_temp=( )
    for y in ${temp[@]}; do
      echo $x/$y
      new_temp=(${new_temp[@]} $x/$y)
    done
  done

  ((depth--))

  if [ $depth -gt 0 ]; then
    traverse $new_temp
  fi
}

A:

You cannot pass arrays as arguments. You can only pass strings. You'll have to expand
the array to a list of its contents first. I've taken the liberty of making depth
local to your function, rather than what I assume is a global variable.
traverse(){
  local depth=$1
  shift
  # Create a new array consisting of all the arguments.
  # Get into the habit of quoting anything that
  # might contain a space
  for x in "$@"; do
    echo "directory contains: $@"
    new_temp=()
    for y in "$x"/*; do
      echo "$x/$y"
      new_temp+=( "$x/$y" )
    done
  done

  (( depth-- ))
  if (( depth > 0 )); then
    traverse $depth "${new_temp[@]}"
  fi
}

$ dir=( a b c d )
$ init_depth=3
$ traverse $init_depth "${dir[@]}"


Q:

How is $y' = x^2$ a differential equation if it doesn't contain a function $y$?

The way I learned differential equations is in the form
$$y' = y$$
for example. So for example, $y' = x$ or $y'' = 0$ was never given as examples as differential equations. However, according to my new textbook $y' = x^2$ is given as an example of a differential equation.
Can someone explain what's going on here?

A:

Yes. A differential equation is an expression involving a function (typically denoted $y(x)$) of a variable $x$, together with one or more of the derivatives of $y$. The coefficient of $y$ (or any derivative of $y$) can be zero in such an equation, so
$$
y' = 0\\
y' = 3x y \\
y'' + y = 0 \\
y'' + x^2 = 9
$$
are all differential equations. Typically one requires that the coefficient of at least one of the derivatives of $y$ is nonzero, so you could say "It's an equation that specifies a function $y$ by saying something about some derivative of $y$."
Equations that don't involve anything except $y'$ are generally easy to solve: you isolate $y'$, getting something like
$$
y' = x^2
$$
and then integrate both sides with respec to $x$, getting
$$
y(x) + C = \frac{x^3}{3} + K
$$
and then combine the two constants of integration into one to get
$$
y(x) = \frac{x^3}{3} + A.
$$
Of course, you can still have things like
$$
(y')^5 + y' + 1 = 0,
$$
where the "isolating $y'$" step may be effectively impossible. The "isolate $y'$ " strategy works best when $y'$ appears only to the first power. For other situations...you need other ideas, which is why we have whole books about ODEs. :)


Q:

How to determine by reflection if a Method returns 'void'

I have a java.lang.reflect.Method object and I would like to know if it's return type is void.
I've checked the Javadocs and there is a getReturnType() method that returns a Class object. The thing is that they don't say what would be the return type if the method is void.
Thanks!

A:

if( method.getReturnType().equals(Void.TYPE)){
    out.println("It does");
 }

Quick sample:
$cat X.java

import java.lang.reflect.Method;

public class X {
    public static void main( String [] args ) {
        for( Method m : X.class.getMethods() ) {
            if( m.getReturnType().equals(Void.TYPE)){
                System.out.println( m.getName()  + " returns void ");
            }
        }
    }

    public void hello(){}
}
$java X
hello returns void
main returns void
wait returns void
wait returns void
wait returns void
notify returns void
notifyAll returns void

A:

method.getReturnType()==void.class     √

method.getReturnType()==Void.Type      √

method.getReturnType()==Void.class     X

A:

method.getReturnType() returns void.class/Void.TYPE.


Q:

if/else statement with setTimeout causes flicker

I'm displaying an element on scrolling down and hiding it when scrolling up again. Without using setTimeout, this works just as expected. However, using setTimeout causes the 'display' class to be added and removed in short intervals when scrolling down. How can I avoid this while keeping the delay?
onscroll = function() {
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 110) {
    menuButton.classList.add('display');
  } else {
    setTimeout(function() {
      menuButton.classList.remove('display');
    }, 400);
  }
}

A:

The timeout was still firing from earlier events. Here is my fix:
onscroll = function() {
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  var timer;
  if (scrollTop > 110) {
    window.clearTimeout(timer);
    menuButton.classList.add('display');
  } else {
    timer = window.setTimeout(function() {
          menuButton.classList.remove('display');
      }, 400);
  }
}


Q:

Jquery cfml - none of the script is executable

I have a CF page that has a CFdiv.  The Cfdiv is bound to an element on the page.  The main page contains the script. None of the script executes on elements in the CFdiv. There seems to be a problem with the ajax call.  When I take that code out, the rest of the code seems to be enabled in Firebug but still will not execute.
<script type="text/javascript">
  $(document).ready(function () {
    $('#candidatesubmit').on('click', function () {
      $.ajax({
      type: 'POST',
      url: 'actEditStatusForm.cfm',
      data: 'form=',
      error: function (xhr, textStatus, errorThrown)(
      // show error
      alert(errorThrown);),
      success: function (response1, textStatus, jqXHR)(
      alert('success');)
       });
    ColdFusion.Grid.refresh('candidatesGrid', true);
  });
  $(function () {$("#JDOrgChartRESOutlineSentToCand").datepicker({dateFormat: 'yy/mm/dd'});});
  $(function () {$("#IndepthWRec").datepicker({dateFormat: 'yy/mm/dd'});});
</script>

A:

First, you have some syntax errors. Perhaps this is just a problem as pasted above, and not in your real code. But make sure the body of your error and success functions are surrounded by curly brackets, not parentheses.
So instead of this:
error: function (xhr, textStatus, errorThrown)(
  alert(errorThrown);),

You should have this:
error: function (xhr, textStatus, errorThrown) {
  alert(errorThrown);
},

Second, your grid refresh is outside the success function of the ajax call. Since that call is asynchronous, the grid refresh is likely running before that call has completed. Move the refresh into your success callback function, like this:
success: function (response1, textStatus, jqXHR){
  ColdFusion.Grid.refresh('candidatesGrid', true);
  alert('success');
}

Third, if the content of the cfdiv is being loaded asynchronously, and the #candidatesubmit element is inside that dynamically loaded content, your function will not be bound to its click event because it won't be present when the main page's ready event is triggered.
So instead of directly binding to the element, use a delegation strategy by listening for events on an enclosing element that you know will be present in the initial page load. So instead of this:
$('#candidatesubmit').on('click', function () {

Try something like this:
$('#some_outer_div').on('click','#candidatesubmit', function () {

#some_outer_div will now be listening for any click events that bubble up from its descendant elements (even those that were not present when the page first loaded). If the target of one of those clicks is #candidatesubmit, the handler will fire.


Q:

Calling a method of One View controller from Another View Controller

I have a method "someMethod" declared in OneViewController.h
@interface OneViewController
{
UIView *tempView;
..

}
-(void) someMethod ;
@end

and implemented in OneViewController.m file
@implementation OneViewController

-(void) someMethod
{
tempView = [[UIView alloc]initWithFrame:CGRectMake(100, 50, 200, 250)];
tempView.backgroundColor = [UIColor yellowColor];
if([[self.view subviews] containsObject:tempView])
[tempView removeFromSuperView];
   else
   [self.view addsubview:tempView];

}

I want to call someMethod when present at different viewController - secondViewController
(something like [OneViewController someMethod]), So that when I get back to OneViewController I can see the changes made by someMethod.
Do I need to use appDelegate methods?
I have tried following but it doesn't work.
neViewController *newViewController = [[OneViewController alloc] init];
[newViewController someMethod];

Thanks for any help in advance..

A:

In the SecondViewController, declare a reference for OneViewController class. You can have assign property. Set the reference before you move to SecondViewController. Now with the reference, you can call the instance method [_oneView someMethod].
Edit:
Declare
OneViewController *_oneView;

Also add the assign property,
@property(nonatomic,assign) OneViewController *_oneView;

Synthesize the variable in .m file.
While showing the SecondViewController from OneViewController, just add the following line.
secondView._oneView = self;

A:

sometimes calling a method directlry creating [classObject methodName] does not refelect the changes in views. Like if you want to change a UIScrollView property from scrollEnble = NO; to scrollEnable = YES;, it does not refelect.
You should use singleton of UIApplication.
Suppose you want to call ViewController1's method - (void)myMethod in ViewController2 then here are the steps:

In you AppDelegate import ViewController1 and create its object *vc. Delare property @property (strong, nonatomic) ViewController1 *vc;. synthesize also.
Now come to Viewcontroller1 class. Import AppDelegate.h in you Viewcontroller1's and in viewDidLoad write like this:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
 appDelegate.vc1 = self;
Go to your ViewController2.h and import AppDelegate.h
Go to the line where you want to call ViewController2's method and write like this:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
 [[appDelegate vc1] myMethod]; // to allow scrolling


Q:

Is tag sponsorship contributing to confusion between "metro" and "metro-ui"?

We've discussed the Windows 8 / Metro situation before.

What should the tag for the new Windows 8 runtime be?
Consensus on taxonomy for Windows Phone, Windows 8, and things named Metro?
Windows 8 and related tags need a little love
Should the "metro" tag refer to a Java framework or Windows 8 technology?

But people are still tagging stuff metro when it should be metro-ui. Today I was wondering - do they even read anything we show them? I brought up the tagged questions to easily find the other wrong ones and look what I saw:

I think this sponsorship is "outweighing" the actual text of the tag wiki. Maybe the excerpt should be first. Maybe Soluto shouldn't be allowed to sponsor metro, only metro-ui.
Update: It's been two weeks and the metro folks are still at it. In fact I am now seeing questions tagged with both metro and metro-ui showing that they know about the "right" tag but they think the other one is also right. I don't understand why people are allowed to sponsor "wrong" tags like this. I would really like an answer about that part of it.

A:

metro is ambiguous and has to go, or you'll keep getting questions accidentally tagged to it.
I would suggest to use metro-web or metro-web-java or metro-java instead:

metro-web makes the user more likely to read what it is, but accidental tags could still happen.
metro-web-java is as verbose as it can gets, no way that you can misunderstand that.
metro-java could work as well, since the web notion might not be necessary.

Don't add framework because it adds no value to the tag name.

So, here's the approach I would suggest:

Contact the sponsor that he is sponsoring the wrong tag.
Sort out metro to only contain Java Metro-related questions, metro-ui for the design language.
Move all questions from metro to metro-web-java or metro-java.
Call Trogdor using the awesome sign and ask him to burninate metro (and blacklist it).
???
Profit! Everybody happy...

Here is an image explaining it all with tags, SE team, sponsor(s), freehand circles, unicorns and Trogdor:

Any resemblance with real-life persons, drakes or unicorns is purely coincidentally...


Q:

Setting a offset on my SQL Report with Paramters

I'm using SQL reports for label printing and I want to be able to pass a top and left offset to the report to make float adjustments to where the data will appear on the label. I have all the data in a rectangle and I'm trying to using TopOffset and LeftOffset to move the rectangle from it's default position as needed. I can't find the proper expression to do this, or where to assign it.
I've tried going into the location properties of my offset rectangle and using these for my Top parameter:
=Parameters!TopOffset.Value + .14
=Parameters!TopOffset.Value in + .14 in
=(in)Parameters!TopOffset.Value + .14 in

I always get the error:

=Parameters!TopOffset.Value + .14 in cannot be parsed as a unit because it does not contain numeric values. Examples of valid unit
  strings are "1pt" and ".5in".

Can anyone help?

A:

Unfortunately, you can't specify an expression for the location properties.
You would have to find another way to move the rectangle, by showing/hiding another item for example but it will be hard to do this as precisely as what you want.


Q:

database is malformed in iphone + error disk i/o error

I have More than 5000 Record to be loaded from Server to my App and Inserted into Database.
While inserting these records after some successful insertion  I am getting this kind of error and my app crashes.
database is malformed in iPhone + error disk i/o error
Following are code snippet that could be useful,Here I am getting Records in 5 Categories One by One and Inserting them into Database
    if (tag==1) {
        NSMutableDictionary *catDic=[dic valueForKeyPath:@"GetAllRecords.results.categories.category"];
        [self performSelectorInBackground:@selector(insertDataInCategoryMaster:) withObject:catDic];

        NSMutableDictionary *levelDic=[dic valueForKeyPath:@"GetAllRecords.results.levels.level"];
        [self performSelectorInBackground:@selector(insertDataInLevelMaster:) withObject:levelDic];

        NSMutableDictionary *queDic=[dic valueForKeyPath:@"GetAllRecords.results.questions.question"];

        [self performSelectorInBackground:@selector(insertDataInQueMaster:) withObject:queDic];

        [self getQueCatLevelData:2];
    }
    else if(tag==2){

        NSMutableDictionary *queDic=[dic valueForKeyPath:@"GetAllRecords.results.questions.question"];
        [self performSelectorInBackground:@selector(insertDataInQueMaster:) withObject:queDic];

        [self getQueCatLevelData:3];

    }
    else if(tag==3){

        NSMutableDictionary *queDic=[dic valueForKeyPath:@"GetAllRecords.results.questions.question"];
        [self performSelectorInBackground:@selector(insertDataInQueMaster:) withObject:queDic];

        [self getQueCatLevelData:4];
    }//and so on for 5 also

in each insertDataInQueMaster I am doing  following things.
         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        for(NSDictionary *queDictionary in dictionary)
        {

            NSString *strQuery = [NSString stringWithFormat:@"insert into QuestionMaster values(%d,'%@','%@',%d,%d,%d,%d,%d,0,'%@')",[[queDictionary valueForKey:@"questionid"]intValue], [queDictionary valueForKey:@"questiontext"],[queDictionary valueForKey:@"answertext"],[[queDictionary valueForKey:@"categoryid"]intValue],[[queDictionary valueForKey:@"levelid"] intValue],[[queDictionary valueForKey:@"status"]intValue],[[queDictionary valueForKey:@"RangeFrom"]intValue],[[queDictionary valueForKey:@"RangeTo"]intValue],[queDictionary valueForKey:@"Fact"]];

            [NSNumber requestWithSynchronousExcuteQuery:strQuery withReturnningError:&error];

            if(error)
            {
                NSLog(@"error description:%@",[[error userInfo] description]);
                [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"FirstTime"];
            }

        }

        count++;
        [[NSUserDefaults standardUserDefaults]setInteger:count forKey:@"CheckCount"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        [pool drain];

I am doing These all things while App is Loading in AppDelegate.m , that too in Background
The Error Comes After  successfully inserting few records in Database so I think there is no problem with Database opening and Inserting.
I hope I am clear,
Please comment if any confusion.
Waiting for reply.
Thanks in advance.

A:

hurray, I got the Simple Solution to this
I just Placed
  @synchronized(self)
  {
      //My Whole Code  for Background methods goes here
  }

and that's it, it solved my error and crash too.
The @synchronized()directive locks a section of code for use by a single thread. Other threads are blocked until the thread exits the protected code—that is, when execution continues past the last statement in the @synchronized() block.
The @synchronized() directive takes as its only argument any Objective-C object, including self.


Q:

Better way to write common function with parameter is different class

In my project, I have some functions like that:
func 1 (with 2 class: class1 and classs1_1):
List<class1> GetData1(class1_1 cls)
{
    List<class1> list = new List<class1>();
    cls = new cls();
    //do something for cls, like cls.GetSpecialCase();

    //fill data from cls to list, as using foreach to fill data to list

    return list;
}

func 2 (with 2 class: class2 and classs2_2):
List<class2> GetData2(class2_2 cls)
{
    List<class2> list = new List<class2>();
    cls = new cls();
    //do something for cls, like cls.GetSpecialCase();

    //fill data from cls to list, as using foreach to fill data to list

    return list;
}

How could I write a function like that (because I don't want to use a lot of functions as above):
common func (with T is class1, object cls is class1_1):
List<T> GetData(object cls)
{
    List<T> list = new List<T>();
    //how to recognize which class of cls
    if(cls == class1_1)     class1_1 other_cls = cls as class1_1;
    if(cls == class2_2)     class2_2 other_cls = cls as class2_2;
    //do something for other_cls

    //fill data from other_cls to list
    return list;
}

I just want to pass parameter as object, and in the common function, I want to know which class I'm passing to so that I can treat to right class, and call right function.
Anyone helps me to solve this problem.
Thank you very much.

A:

It sounds like you need:

An interface or abstract base class with the GetSpecialCase method
A generic method (with type parameters for both input and output) of
List<TResult> GetData<T, TResult>(T item) where T : ISpecialCase<TResult>
{
    List<TResult> list = new List<TResult>();
    var other = item.GetSpecialCase();
    // Fill list via other
    return list;
}

If you can't introduce an interface or base class, you could use dynamic typing, but I'd strongly recommend that you use polymorphism to express what the different classes have in common (GetSpecialCase here) if you possibly can.


Q:

Regarding iterated maps $\mathbb{R}^2 \rightarrow \mathbb{R}^2$, and strictly decreasing norm

Consider a map $g:\mathbb{R}^2 \rightarrow \mathbb{R}^2$, and the iteration $(x,y) \mapsto g(x,y)$. Say that the origin is an asymptotically stable fixed point and there is a region $A$ in the first quadrant where we can show that for all $(x_0,y_0) \in A$,

$g(x,y) \in A$
$\|g(x,y)\| < \|(x,y)\|$
$g(x,y)$ continuous

Now, my goal is to show that all $(x,y) \in A$ will eventually converge to the origin, or equivalently $$\lim_{k \to \infty} \|g^k(x,y)\| = 0.$$
I initially thought that the conditions listed above were sufficient, but now I have doubts. What if, even though the norm was strictly decreasing, it only approached some nonzero limit, with $$\lim_{k \to \infty} g^k(x,y) = p \ne (0,0) \in A.$$
My question is: could such a $p$ exist? For it cannot be a fixed point under the iteration due to (2) above. This means that $$\lim_{k \to \infty} g^k(p) \ne p$$
Basically I am pretty sure there is a contradiction in combining $$\lim_{k \to \infty} g^k(x,y) = p$$ with $$g(p) \ne p,$$ but I can't exactly pin it down.
Summed up, is it possible that there could be some sequence $\{(x,y),g(x,y), g^2(x,y), \ldots g^k(x,y)\}$ that never reaches the origin, even though there are no fixed points in $A$ besides the origin? And why not precisely? Thank you.

A:

If $g$ is not continuous, then there is such a sequence, even in 1D, take for example
$$g(x) = \begin{cases}1/4+x/2 & \mbox{ for } x > 1/2\\ 0 & \mbox{ else}\end{cases}$$
However if $g$ needs to be continous then there is no such function. Assume there is a sequence of points $p_k = g^k(x_0,y_0)$ not converging to 0.
Since $g$ and the norm are continuous, $f:(x,y) \mapsto \|g(x,y)\|$ is a continous function. But clearly $f(p_k)$ is a decreasing sequence and bounded from below, so $f(p_k)$ converges to some $r > 0$.
Since $\|p_k\| < \|p_0\|$ for all $k\in\mathbb{N}$, $p_k$ is a bounded sequence, so by Bolzano-Weierstrass, there is some converging subsequence $p_{k_l} \rightarrow p \neq 0$. Now on one hand by continuity of $f$
$$ r= \lim_{l\rightarrow \infty} f(p_{k_l}) = f(p) = \|g(p)\|$$
and on the other hand
$$ r = \lim_{l\rightarrow \infty} f(p_{k_l-1}) = \lim_{l\rightarrow \infty} \|g(p_{k_l-1})\| = \lim_{l\rightarrow \infty} \|p_{k_l}\| = \|p\|$$
and thus $\|p\|=r=\|g(p)\|$ which is a contradiction.
Edit: also I just noted, I need that A is closed, otherwise $p$ may not lie in $A$ and there probably again is a counterexample.


Q:

EXT JS Open form on btn Click

Relativly new to EXTJS,
I have an edit form that I want to show when the user clicks the edit button.
previously I had been doing it like this:
edit_window_xtype: 'window name',

which works perfectly, in this case I have a need to only call the form when the button is clicked and not when the user double clicks a field in my grid.(this is what edit_window_xtype: 'window name' would accomplish)
I had
btnEdit_onClick: function (btn) {
    Ext.create('window name').show();
},

but that doesn't work.

A:

It appears I have alot to learn with Extjs.  Here is what I came up with, If someone has a better solution please let me know.  Always looking for better ways to accomplish something.  :)
btnEdit_onClick: function (btn) {
    var config = {
        xtype: 'MyWindow_Name',
        mode: 'edit',
        title: 'Edit Window',
        editId: this.id
    };
    var win = Ext.ComponentMgr.create(config);
    win.show();
};


Q:

IE doesn't display properly the same code on the same page twice

Okey, here it goes. I have a block of code that repeats it self twice. But it doesn't display the same, it is on the same page. I've checked everything is the same the html and the CSS. I realy can't wrap my head around this. This code is part of joomla module. I have to note that this is not my code!!! But i have to fix it so..

                            Product

                                111 $

                            Product

                                111 $

                            Product

                                111 $

and the CSS:
    .thirdDiv {
 float: left;
 width: 176px;
 height: 240px;
    }

the div that contains all that is 550 px wide

A:

Use FireBug to find out why.
Perhaps the second time it is nested within another div and there is a style like:
.otherDiv .thirdDiv {
    width: 300px; /* override width */
}


Q:

How to store some info while user is submitting rating with Fivestar module?

I want to store this rating on different site and I am doing this with the help of RESTful api. I have altered "fivestar_custom_widget" form with hook_form_alter. My call is not working beacuse it is not removing div which has 'field-name-field-fivestar-rating' class and not adding div which has 'rating-wrapper' id.
function recipe_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'fivestar_custom_widget') {
    $form['#submit'][] = 'fivestar_rest_api';
  }
}

function fivestar_rest_api($form, $form_state) {
   $ch = curl_init("http://www.example.com/");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   $data = curl_exec($ch);
   curl_close($ch);
   $json = json_decode($data,true);
   $errorMessage = $json['errorMessage'];
   $errorCode = $json['errorCode'];
   $commands[] = ajax_command_remove('.field-name-field-fivestar-rating');
   $commands[] = ajax_command_append('#rating-wrapper', 'Thankyou for your rating.');
   return array('#type' => 'ajax', '#commands' => $commands);
 }

A:

Submit handler was not working so I have decide to do it with validate handler like this

function recipe_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'fivestar_custom_widget') {
    $form['#validate'][] = 'fivestar_rest_api';
  }
}

function fivestar_rest_api($form, $form_state) {
   $ch = curl_init("http://www.example.com/xxx");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   $data = curl_exec($ch);
   curl_close($ch);
   $json = json_decode($data,true);
   $errorMessage = $json['errorMessage'];
   $errorCode = $json['errorCode'];
   $commands[] = ajax_command_remove('.field-name-field-fivestar-rating');
   $commands[] = ajax_command_append('#rating-wrapper', 'Thankyou for your rating.');
   return array('#type' => 'ajax', '#commands' => $commands);
 }

Now it is working fine form me.


Q:

Using the literal '@' with a string variable

I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command?
Instead of this:
string filePath = @"C:\somepath\file.txt";

I want to do this:
string filePath = @helper.getFilePath(); //getFilePath returns a string

This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something?

A:

I don't think you have to worry about it if you already have the value. The @ operator is for when you're specifying the string (like in your first code snippet).
What are you attempting to do with the path string that isn't working?

A:

I'm not sure if I understand. In your example: if helper.getFilePath() returns "c:\somepath\file.txt", there will be no problem, since the @ is only needed if you are explicitely specifying a string with "".
When Functions talk to each other, you will always get the literal path. If the XML contains c:\somepath\file.txt and your function returns c:\somepath\file.txt, then string filePath will also contain c:\somepath\file.txt as a valid path.

A:

The @"" just makes it easier to write string literals.
string (C# Reference, MSDN)

Verbatim string literals start with @ and are also enclosed in double quotation marks. For example:

@"good morning"  // a string literal

The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:

@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"

One place where I've used it is in a regex pattern:
string pattern = @"\b[DdFf][0-9]+\b";
If you have a string in a variable, you do not need to make a "literal" out of it, since if it is well formed, it already has the correct contents.


Q:

Usage of bucketfullaccesscontrol permission in bucket objects

I am using spring integration channel technology in my application. I just want to put some files inside aws s3 bucket with full access permissions. my  configuration is in XML form.
Need to implement via using expression-acl-object attribute  in s3 outbound gateway .
Please help to configure this.

A:

Your question is not clear and it is fully out of our imagination what is your code without any samples from your side. But still it sounds like you are talking about:
    <xsd:attribute name="object-acl-expression">
        <xsd:annotation>
            <xsd:documentation>
                A SpEL expression to evaluate S3Object ACL at runtime against request message
                for the 'upload' operation.
            </xsd:documentation>
        </xsd:annotation>
    </xsd:attribute>

The result of this expression must be an instance of AccessControlList or CannedAccessControlList:
Object acl = this.objectAclExpression.getValue(this.evaluationContext, requestMessage);
Assert.state(acl instanceof AccessControlList || acl instanceof CannedAccessControlList,
                    "The 'objectAclExpression' ["
                            + this.objectAclExpression.getExpressionString()
                            + "] must evaluate to com.amazonaws.services.s3.model.AccessControlList " +
                            "or must evaluate to com.amazonaws.services.s3.model.CannedAccessControlList. " +
                            "Gotten: [" + acl + "]");

So, if you talk about a full access permissions, it looks like you just need to use CannedAccessControlList.AwsExecRead in that expression:
/**
 * Specifies the owner is granted {@link Permission#FullControl}. Amazon EC2
 * is granted {@link Permission#Read} access to GET an Amazon Machine Image
 * (AMI) bundle from Amazon S3.
 */
AwsExecRead("aws-exec-read");

Such an expression may look like:
object-acl-expression="T(com.amazonaws.services.s3.model.CannedAccessControlList).AwsExecRead"


Q:

Button image stretching

I am having a problem with the button image. I have a green background and an icon. The problem is that on larger screens the image stretches due to the button also stretch to the size of the screen.
I found several other topics they were talking about something, but none of them helped me solve this problem.
The next best picture explains the problem:

A:

If you want your button to look like the 3rd image, you will have to use an image of that size and resolution.
Alternatively, you can set contentMode on your UIButton's imageView object. Use this line of code in your viewDidLoad function
button.imageView!.contentMode = UIViewContentMode.ScaleAspectFit

When your constraints increase the size of your button, the image used inside it will abide by the contentMode property set. Using those you can stretch it, which it's doing right now, or you can keep the aspect ratio, in which case it will show empty space on sides.


Q:

What does dollar sign do in scala

When I was reading spark source code here, I saw code like $(a_variable).
What does it mean?
I copy the code here:
  final val blockSize: IntParam = new IntParam(this, "blockSize",
    "Block size for stacking input data in matrices. Data is stacked within partitions." +
      " If block size is more than remaining data in a partition then " +
      "it is adjusted to the size of this data. Recommended size is between 10 and 1000",
    ParamValidators.gt(0))

  /** @group getParam */
  final def getBlockSize: Int = $(blockSize)

A:

That isn't special Scala syntax, it's a method name. In Scala $ is a legal identifier. The method is inherited from the org.apache.spark.ml.param.Param trait.
See the source.


Q:

Guitar : Difficulty in chords shifting

I have started learning guitar basics,since last couple of months. I am facing huge difficulty in shifting chords.
I have started playing simple open chords like C,Am,Em,Gm. I am practicing for these four chords. I am facing huge difficulty while shifting. It is sometimes very depressing and at the same time frustrating when I cannot play it correct.
I have tried practicing with metronome and go slow, but still I cannot shift easily from one chord to another.
Any tips will be really helpful.
Thanks

A:

*Try to think hard about where your fingers have to move from/to. With C - Am, for example, two fingers (4th and 2nd strings) don't need to move off their frets.
*Try to move a pair of fingers together, as in Em - Am,keeping them touching each other as they move across between strings. When you learn E, then A, you leave your index finger on the 3rd string (for E), but also don't take it away for A. You'll find some chords which often move between each other, like E/A, and E/B7, found in many many songs. Leave fingers in place if you can, as pivots for your other fingers.
*Learn to 'hammer on' chords, so that all your fingers arrive at the same time.
*Gm is not one of the chords I'd be teaching a beginner. Apart from not being easy to play a proper version, the other chords found in a song with Gm are not beginners chords, either.
*Don't lift your fingers far above the fingerboard when changing chords.
*If you're looking at the fingerboard while finding chords, it'll put  guitar at a bad angle for your wrist and hand. Don't! Use a mirror, or try to feel your way.

A:

I feel your frustration!  But it is a normal part of learning to play guitar.
One reason so many aspiring new guitarist, give up before they ever get to a point where they feel a sense of reward and accomplishment, is that learning guitar involves overcoming several difficult challenges thrown at you all at once in the very beginning.
First you have the pain of tender fingers pressing on steel strings.  Then you are using muscles in your hand and fingers that ordinary daily living activities have not helped you to develop the strength required for playing guitar.  And, as expressed in your question, you must train your brain to tell your fingers and hands to contort in very unnatural and strange positions to play chords.
My best advice is to abandoned any idea of instant gratification and commit to the idea that learning guitar is a slow process in the beginning.  It gets exponentially easier to improve your skills after you get past the huge hurdles you encounter in the beginning.
Think of where you presently are in your journey as merely preparation and training.  You are getting in shape to learn to play by developing some basic skills and building finger strength and callouses and coordination. Progress will be very slow in the beginning but if you persevere, you will reach a point where progress comes at a far more rapid pace.
Now to your specific challenge.  Before working on transitions between chords, you must first train your brain to tell your fingers to form the proper shape for each of the two chords.  Start one at a time.  Learn to properly form and play a particular chord (say a C chord for example).  Practice forming the chord and releasing your hand and forming the chord again and releasing.  Do this over and over until you can go from an open hand position to a C chord without hesitation.  Do this before you even think about transitioning from a C chord to something else.
Next step is to learn the next chord (Em for example).  Practice forming an Em chord and opening your hand and forming the chord again - until you can play it without hesitation.
Once you are able to form a C chord from an open hand without much hesitation and can do the same with the Em chord, then you can begin to practice the transition between the two chords.  To do this, start on one chord, then play the second chord and repeat this process.  Start slowly and you will build speed over time.  Don't use a metronome in the beginning, it will only add to your frustration.  Once you can quickly and easily transition between the two chords, you can begin to practice using a metronome to further ingrain your transition and develop some rhythm at the same time.
It would be very helpful to have a teacher or experienced guitarist, help you with the proper fingering and hand position for every chord you endeavor to learn.  Efficiently forming a chord involves more than just putting your fingers on the right strings at the right frets.  Each chord requires a different hand position and sometimes arm position.  Some chords have you tilting your hand one direction - others the opposite.  Some chords have your thumb in the center of the back of the neck, while others may be much easier to play if your thumb is at the top of the neck.
Keep your goals and expectations realistic.  It may be helpful to set a goal of learning the I - IV and V chord of a particular key and then learning to transition between those three.  In the key of C that would be I = C  IV = F and V = G.  Once you learn the basic I - IV and V chords and develop the ability to transition between them, you will be able to play literally thousands of songs.
If you accomplish that one small goal, you will develop the passion and desire to continue your journey, which will provide opportunities to continue to learn and improve for the rest of your life.  And it gets more enjoyable as you go.
Don't give up!  What you are experiencing is normal and something that all of us (who have learned to play guitar) went through in the beginning.  It takes slow and deliberate practice to get over the huge wall at the start.  It gets much easier after you get over that initial wall.  Good luck!


Q:

Qtip is not showing up

This is probably a really simple solution. But, I am new to jquery, and qtip. For the life of me I cannot get my qtip to show up. All that is shown is the default tooltip. Anyone know what could be the problem?
<html>
<head>
<link type="text/css" rel="stylesheet" href="/jquery.qtip.min.css"/>
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type='text/javascript' src="/jquery.qtip.min.js"></script>

<script>
$('a[title]').qtip()
</script>

</head>
<body>
<a title="why wont this tooltip work" href ="#">Hello there punk
</body>
</html>

Here is a simple example that wont work, any suggestions?

A:

Reading the docs i think this is the way to do
and this should be called only after document is ready
$(document).ready(function()
{
    $('body a[href]').qtip();
});


Q:

Custom Event Handler to handle Emails in Project Server

I am working on writing an event handler that handles the OnSending event of Project Server in 2010. I am very new to writing event handlers in MS Project and require your help in getting started on it..I have Googled, but did not find any good resources on it. I know this is kind of vague question, but would request you experts to help me to get started with this.
Thanks in advance!

A:

Here is a good article that should help you get started: http://msdn.microsoft.com/en-us/library/gg615466.aspx
Also - I would download the Project Server 2010 SDK: http://msdn.microsoft.com/en-us/library/ms512767.aspx
The SDK contains alot of good references and will provide you with other examples of how to access Project Server Data via the PSI.
Finally, Event Handlers are difficult to troubleshoot.  When you deploy to an environment off your development machine and need to troubleshoot, I would recommend taking advantage of SharePoint's ULS log's.  Your Project Server event handler can write to these logs too.
Here is a method that I use to catch errors and issues:
    internal static void writeULS(string traceValue)
    {
        SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;

        diagSvc.WriteTrace(0, // custom trace id
        new SPDiagnosticsCategory("YOUR ULS LOG CATEGORY NAME (IE//COMPANY.APP)",
        TraceSeverity.Monitorable,
        EventSeverity.Information), // create a category
        TraceSeverity.Monitorable, // set the logging level of this record
        "{0}", // custom message
        new object[] { traceValue } // parameters to message
        );
    }


Q:

Creating an algebraic data type in Haskell which has either an Int or an array of them

What I require is a data type that either contains an exact value or contains a list of possible candidates. (I will be using values of type Int).
What I would want is that if I perform an f: Int -> ... function on a Cell which has an exact value it is performed on the value and if I perform a function of the form f : [Int] -> ... on a Cell with candidates it performs the function on the array of candidates. Hence I define my data like this:
data Cell a = Exactly a | Candidates [a] deriving (Eq, Read, Show)

instance Functor Cell where
    fmap f (Exactly x) = Exactly (f x)
    fmap f (Candidates (x:xs)) = Candidates ( f (x:xs))

This does not compile and gives me an error of the form
Occurs check: cannot construct the infinite type: b ~ [b]  ...
If I edit my code to
fmap f (Candidates (x:xs)) = Candidates ( map f (x:xs))
this does compile but then does not serve my function well as sometimes I would have to work on the whole array rather than the members element-wise.
Thanks for help.

A:

Your problem is with this line
fmap f (Candidates (x:xs)) = Candidates ( f (x:xs))

the function f works only on single values and you are trying to apply it to a list.  What you need to do is apply f to each element in the list.
Try:
fmap f (Candidates xs) = Candidates ( fmap f xs)

This will apply f to each member of xs.

As an aside, have you read this article (or similar) about the list monad?


Q:

iOS7 distributed App installation via iTunes fails without error

After I my App as usually I tried to install it via iTunes.
It has successfully synced to the iPhone, but the Icon is grayed out and it seems like the installation has not finished
Where you normally find the App-Name "Installation ..." has appeared.
Can't find any log or error message
(can't push the App with the development machine because of Apple's new security feature => "do you trust this computer" which just won't disappear)

A:

There is actually one log you can look at during the install; go to  the Organizer window in Xcode, look at your device in the Devices tab, and look at the Device Logs. There should be several issues that will be logged during the iTunes install: rollback notifications, errors and such.
Look for one error in particular, similar to this one:
installd[31] : profile not valid: 0xe8008012
As Nikos M. alluded to in his comment above, this would indicate a provisioning profile issue. When I had this issue, my provisioning profile was up to date, but the app still wasn't installing. I found this question on this site, and the accepted answer fixed the issue for me: Xcode 4.5 - can't install developer .ipa files via iTunes
Basically, it's a problem with the provisioning profile. Not sure why it happens, but it prevents the app from being installed on some devices sometimes. As answered in the question above, you need to get on the iOS Developer Portal, make a small edit to your provisioning profile (your Ad-Hoc Distribution Profile, not the Development profile), change it back, regenerate the profile and download it again. Rebuild your .ipa file with this fresh profile, replace your old .ipa with this new one in iTunes and try installing the app again.


Q:

Technique for removing support from Ultimaker 2+?

I have made some prints with the Ultimaker 2+ and Ultimaker 2 Extended+. The prints are in PLA. For slicing, I use Cura and I check the support checkbox (haven't gone to advanced settings to adjust support yet). I can clearly see that there is a little space between the support and the print. The supports often look like long pillars and such.
My question then is: "What is the best technique for removing the support?". Is it to use a knife, pliers or perhaps PLA-water? Is it possible to use PLA-water to remove support when printed with Ulitmaker 2+ or is that just the Ultimaker 3? What type of technique would give a good looking print?
Ultimaker 3 has support filament that's water-soluble. Is there something similar for Ultimaker 2+?

A:

The Ultimaker 2+ is a single extruder 3D printer. Without changing the PLA spool and PVA spool continuously during the print you practically cannot make water soluble supports on the Ultimaker 2+ which can be done on the Ultimaker 3. Note that PVA (from experience) is strange material to print, the filament is very hygroscopic and will form bubbles during printing when moist. Also, PVA is prone to clog the nozzle (it cooks easily) it therefore has its own printer core (nozzle assembly) on the Ultimaker 3 (still it clogs easily). Furthermore, it takes a while to dissolve in water.
If you have a single extruder and nozzle, your best option is to use the same material for support, but modify the support settings as such that it can be easily removed. E.g. on thin layer heights (0.1 mm) I usually increase the gap between support and product over the default value, see this answer.
On dual extruder printers, e.g. on the Ultimaker 3 and S5, my colleagues have better experience using Ultimaker Breakaway filament rather than using PVA. As with the PLA supports, you need to "break them away" from the actual product; I use a Leatherman Charge or FREE P4 as these tools have fine pointed pliers. Note that there are removal tools available that are best described as soldering irons that can aid in the removal of support structures:

Note that I have mixed feelings about this product; it is hard to neatly remove supports using these small soldering irons, but it sometimes works.


Q:

sprintf function's buffer overflow?

{
    char buf[8];
    sprintf(buf,"AAAA%3s","XXXXXXXX");
    printf("%s\n",buf);
}

what will happen?
The buffer have 8 characters space and only 3 free characters left, however, "XXXXXXXX" is 8 characters long.
I take a test with Visual Studion 2008 on Windows 7. As a result, the program printed:AAAXXXXXXX, and a run-time error happened.

A:

It makes a lot of sense to consider what happens in your and, more importantly, similar, cases. As other posters have noted, it invokes UB. That's probably true. However, the world does not stop simply because someone did not define what exactly should happen next. And what physically happens next, may well be a major security hole.
If your string XXX... comes from uncontrolled sources, you are very close to generating a buffer overflow vulnerability.
(1) Your stack typically "grows" backwards, i.e. the smaller the addresses, the more the stack is filled.
(2) Strings expect the characters belonging to that string to be stored so that character n+1 is stored after character n.
(3) When you call a function, the return address, i.e. the address of the instruction that is to be executed after the function returns, is pushed to the stack (among other things, typically).
Now consider a stack frame of your function.
|----------------|
| buf [size 8]   |
|----------------|
| (func args)    |
|----------------|
| (other stuff)  |
|----------------|
| return address |
|----------------|

By finding out what exactly the offset between buf and the return address on the stack is, a malicious user may manipulate input to your application in a way that the XXX... string contains an address of the attacker's choosing at just the point where the uncontrolled sprintf function will overwrite the return address on the stack. (NB: Better use snprintf if it's available to you). Thereby the attacker mounted a buffer overflow attack. He might use something like the NOP sled technique to have your application start a shell for him. If you were writing an application that ran under a privileged user account, you'd just have provided an attacker with a first-grade entry to your costumer's system, an ACE hole, if you will.
Update
The run-time error you experience may well be due to an overwritten return address. Since you filled it with, basically, gargabe, the address the CPU jumped to did probably contain byte sequences that, interpreted as program text, cause an invalid memory access (or the address itself was already bad).
It should be noted that some compilers can help against these kinds of errors. GCC, for example, has the -fstack-protector. I'm not familiar with how good those features are.

A:

The function sprintf() will write past the array as it writes in the string, and therefore invokes undefined behavior. Looking at your code, it'll probably write over the first few bytes of whatever happens to be next on the stack, or cause a runtime error, but that behavior is not guaranteed.
Undefined behavior quite literally means anything can happen. That means your code may do nothing wrong, cause a runtime error, or cause your computer to explode, win the lottery, make unicorns appear in your backyard, raise Hitler from the dead or assassinate the President of the United States. Please don't do this.
Always ensure that your character buffer has enough space to hold whatever you are sprintf()-ing into it plus an extra character for the null terminator. In general, don't try to mess around with memory spaces that are not yours.

A:

Instead of using this method you should try using the snprintf() method as described here. This method performs essentially the same function but it allows you to control the number of characters explictly, preventing undefined behaviour (this is a good thing)

snprintf is guaranteed not to write
  more than size bytes into str, so use
  of it can help avoid the risk of a
  buffer overflow
  Wiki


Q:

How to finish several SingleInstance Activities?

I have several activities with launchMode SingleInstance.  On log out i want to finish all activities  and open launchScreen.
val intent = Intent(context, LauncherActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
(context as AppCompatActivity).finishAffinity()
context.startActivity(intent)

However if i press back at Launcher activity i am forwarded to previously launched activities with singleInstance mode

A:

UPDATE 11/1/2018:
I've tested multiple approach to deal with it such as event propagation, intent flags, counting activity instances, etc. There is some weird scenarios such as starting multiple singleInstance activities sequentially. In this case, middle activities doesn't start at all (onCreate method isn't called) and after pressing back button, they'll be started. Therefore no one of the prior approaches works! As the issue is a bit strange, I tried to solve it using a bit strange way.
We maintain the logout state in a singleton object called LogoutHandler. It cooperates with a class LogoutAwareActivity which is inherited by all activities except LoginActivity because it should not be affected by logout mechanism. When the logout occurs, a flag is set in the LogoutHandler until the last child of LogoutAwareActivity has finished then clears the flag.
Here is an implementation of that:
LogoutHandler:
import java.util.*

object LogoutHandler {

    private var isLogout = false
    private var timerWatchDog: TimerWatchDog? = null

    fun isLogout() = isLogout

    fun onActivityDestroyed() {
        if (isLogout) {
            timerWatchDog?.refresh(Runnable {
                isLogout = false
                timerWatchDog = null
            })
        }
    }

    fun logout() {
        isLogout = true
        timerWatchDog = TimerWatchDog(500)
    }

    private class TimerWatchDog(private val delay: Long) : Runnable {

        private var timer: Timer? = null
        private var runnable: Runnable? = null

        fun refresh(runnable: Runnable) {
            this.runnable = runnable
            timer?.cancel()

            val timerTask = object : TimerTask() {
                override fun run() {
                    Thread(this@TimerWatchDog).start()
                }
            }
            timer = Timer()
            timer?.schedule(timerTask, delay)
        }

        override fun run() {
            runnable?.run()
        }
    }

}

LogoutAwareActivity:
import android.support.v7.app.AppCompatActivity

abstract class LogoutAwareActivity : AppCompatActivity() {

    override fun onResume() {
        super.onResume()
        if (LogoutHandler.isLogout()) {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LoginHandler.onActivityDestroyed()
    }

}

A concrete Activity:
class ActivityA : LogoutAwareActivity() {

    // ...
}

Another concrete Activity:
class ActivityB : LogoutAwareActivity() {

    // ...
}

Your logout function:
fun logout() {
    val intent = Intent(context, LoginActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

    LogoutHandler.logout()
    context.startActivity(intent)
}

Visual Result:
All of MainActivity, ActivityA, ActivityB and ActivityC are single instance.
Traversing between activities by pressing back button:

Going to LoginActivity then pressing back button:

A:

Before launching splash screen add this line
ActivityCompat.finishAffinity(this)


Q:

Python: list(filter object) empties the object

guys!
I'm using Python 3.6.1 and got into an interesting issue:
I'm using a simple itertools.filter() to get a sub-list from an items list, and then I just print it twice.
items = [1,2,3,4,5]
operateVersions = filter(lambda t: t, items)
print ("1: %s" % list(operateVersions))
print ("2: %s" % list(operateVersions))

The result is weird:
1: [1, 2, 3, 4, 5]
2: []

so, when i run list(operateVersions) it somehow rewrites operateVersions filter object instead of just returning the list interpretation
Is it an OK behavior? It doesn't look for me it is

A:

A filter is a special iterable object, and like a generator, you can only iterate over it once. So essentially it returns an empty list when you run it a second time.