问:
Getting the max and min price of current chart
After performing

```<code>ChartNavigate(0, CHART_END, -5142);
</code>```

I want to get the max and min price of that particular chart.

I tried

```<code>ChartGetDouble(0,CHART_PRICE_MAX,0,top)
ChartGetDouble(0,CHART_PRICE_MIN,0,top)
WindowPriceMax
WindowPriceMin
</code>```

None of them gives me the price after the ChartNavigate.
What is the right way to do this?

答:
New-MQL4.56789 features may surprise, nevertheless:

Step 0: always catch Chart_OkFLAG

```<code>    bool   Chart_OkFLAG;
    double Chart_min,
           Chart_MAX;
    int    Chart_ToBeMODIFIED          = ChartID();
    int    Chart_ToBeMODIFIED_SubWinID = 0;
    int    Chart_nBarsRelativeSHIFT    = 0;

           Chart_OkFLAG = ChartNavigate( Chart_ToBeMODIFIED,
                                       < CHART_BEGIN       |
                                         CHART_END         |
                                         CHART_CURRENT_POS >,
                                         Chart_nBarsRelativeSHIFT
                                         );
</code>```

If OK: you won the first round, the GUI command has been accepted for being syntactically & context-wise correct. That does not mean, it was executed by the GUI processor. It was just let in, to the tail of the GUI-command-QUEUE.

Step 1: Enforce it's execution ( wise to think about deferring such processing to some safe place, after mission-critical elements have been fulfilled )

```<code>   if (  Chart_OkFLAG ){
         WindowRedraw();                                        // ol'-MQL4
         ChartRedraw(                Chart_ToBeMODIFIED );      // new-MQL4
         Chart_min =  ChartPriceMin( Chart_ToBeMODIFIED,
                                     Chart_ToBeMODIFIED_SubWinID
                                     );
         Chart_MAX =  ChartPriceMAX( Chart_ToBeMODIFIED,
                                     Chart_ToBeMODIFIED_SubWinID
                                     );
   }
   else{
      // ERROR HANDLING onChartNavigate(T)ERROR
   }
</code>```

ALWAYS: do not hesitate to inline error handlers, even where MQL4 language seems straightforward ( you never know, when that effort pays off by avoiding hours of bug tracking  )

```<code>double ChartPriceMin( const long Chart_ID           = 0,
                      const int  Chart_SubWindow_ID = 0
                      ) {
                      double result = EMPTY_VALUE;
                      ResetLastError();
                      if (  !ChartGetDouble( Chart_ID,
                                             CHART_PRICE_MIN,
                                             Chart_SubWindow_ID,
                                             result
                                             )
                             ){
                             PrintFormat( "ERROR: Code(%d) in [%s]",
                                           GetLastError(),
                                           __FUNCTION__,
                                           );
                      }
                      return( result );
}
double ChartPriceMAX( const long Chart_ID           = 0,
                      const int  Chart_SubWindow_ID = 0
                      ) {
                      double result = EMPTY_VALUE;
                      ResetLastError();
                      if (  !ChartGetDouble( Chart_ID,
                                             CHART_PRICE_MAX,
                                             Chart_SubWindow_ID,
                                             result
                                             )
                             ){
                             PrintFormat( "ERROR: Code(%d) in [%s]",
                                           GetLastError(),
                                           __FUNCTION__,
                                           );
                      }
                      return( result );
}
</code>```

Body:
After performing

ChartNavigate(0, CHART_END, -5142);

I want to get the max and min price of that particular chart.

I tried

ChartGetDouble(0,CHART_PRICE_MAX,0,top)
ChartGetDouble(0,CHART_PRICE_MIN,0,top)
WindowPriceMax
WindowPriceMin

None of them gives me the price after the ChartNavigate.
What is the right way to do this?

Body:
New-MQL4.56789 features may surprise, nevertheless:

Step 0: always catch Chart_OkFLAG

    bool   Chart_OkFLAG;
    double Chart_min,
           Chart_MAX;
    int    Chart_ToBeMODIFIED          = ChartID();
    int    Chart_ToBeMODIFIED_SubWinID = 0;
    int    Chart_nBarsRelativeSHIFT    = 0;

           Chart_OkFLAG = ChartNavigate( Chart_ToBeMODIFIED,
                                       < CHART_BEGIN       |
                                         CHART_END         |
                                         CHART_CURRENT_POS >,
                                         Chart_nBarsRelativeSHIFT
                                         );

If OK: you won the first round, the GUI command has been accepted for being syntactically & context-wise correct. That does not mean, it was executed by the GUI processor. It was just let in, to the tail of the GUI-command-QUEUE.

Step 1: Enforce it's execution ( wise to think about deferring such processing to some safe place, after mission-critical elements have been fulfilled )

   if (  Chart_OkFLAG ){
         WindowRedraw();                                        // ol'-MQL4
         ChartRedraw(                Chart_ToBeMODIFIED );      // new-MQL4
         Chart_min =  ChartPriceMin( Chart_ToBeMODIFIED,
                                     Chart_ToBeMODIFIED_SubWinID
                                     );
         Chart_MAX =  ChartPriceMAX( Chart_ToBeMODIFIED,
                                     Chart_ToBeMODIFIED_SubWinID
                                     );
   }
   else{
      // ERROR HANDLING onChartNavigate(T)ERROR
   }

ALWAYS: do not hesitate to inline error handlers, even where MQL4 language seems straightforward ( you never know, when that effort pays off by avoiding hours of bug tracking  )

double ChartPriceMin( const long Chart_ID           = 0,
                      const int  Chart_SubWindow_ID = 0
                      ) {
                      double result = EMPTY_VALUE;
                      ResetLastError();
                      if (  !ChartGetDouble( Chart_ID,
                                             CHART_PRICE_MIN,
                                             Chart_SubWindow_ID,
                                             result
                                             )
                             ){
                             PrintFormat( "ERROR: Code(%d) in [%s]",
                                           GetLastError(),
                                           __FUNCTION__,
                                           );
                      }
                      return( result );
}
double ChartPriceMAX( const long Chart_ID           = 0,
                      const int  Chart_SubWindow_ID = 0
                      ) {
                      double result = EMPTY_VALUE;
                      ResetLastError();
                      if (  !ChartGetDouble( Chart_ID,
                                             CHART_PRICE_MAX,
                                             Chart_SubWindow_ID,
                                             result
                                             )
                             ){
                             PrintFormat( "ERROR: Code(%d) in [%s]",
                                           GetLastError(),
                                           __FUNCTION__,
                                           );
                      }
                      return( result );
}


来源: stackexchange

问:
convert all colors of a pdf file to blue using imagemagick
How can I convert all colors no matter what to blue color using imagemagick? or any other simple and fast solution?

I am out of black ink and want to convert a pdf that is in grayscale to only blue color and then print it.
My printer has limited options.

答:
```<code>convert image.pdf -fill blue -colorize 100 image.pdf
</code>```

I am not sure this is what you want. The result will be totally blue everywhere. Do you want something else? You say all colors, but does that include white and black and shades of gray?

If you want every color but white to be blue, then

```<code>convert image.pdf -fill blue +opaque white image.pdf
</code>```

However, IM is not a good tool to use to go from vector to vector format. IM will rasterize the vector image and then put a vector shell about it.

ContentLicense: CC BY-SA 3.0

Body:
convert image.pdf -fill blue -colorize 100 image.pdf

I am not sure this is what you want. The result will be totally blue everywhere. Do you want something else? You say all colors, but does that include white and black and shades of gray?

If you want every color but white to be blue, then

convert image.pdf -fill blue +opaque white image.pdf

However, IM is not a good tool to use to go from vector to vector format. IM will rasterize the vector image and then put a vector shell about it.


问:
How to limit the number of threads excecuted by ManagedExecutorService
The class javax.enterprise.concurrent.ManagedExecutorService manages threads within Enterprise Java Bean. As threads in EJBs should not be started in the classical Java SE way, I use the ManagedExecutorService to handle threads.

"Obligatory warning: Creating your own threads in a Java EE app server (even Tomcat) is discouraged as it can be a huge performance issue and in most cases will prevent container functionality, such as JNDI, from working. The new threads won't know which application they belong to, the Thread context classloader will not be set and many other hidden issues."

In Java SE you can define the maximum number of threads, as shown in the following code.

```<code>java.util.concurrent.Executors.newFixedThreadPool(numberOfThreadsInThePool);
</code>```

Do you know how to limit the number of threads excecuted by the ManagedExecutorService?

答: When you are using an EE container, you should address issues about the number of threads through configuration of the container.  For Glassfish, check the Oracle documentation on thread pool management and performance tuning.</p>

Body:
The class javax.enterprise.concurrent.ManagedExecutorService manages threads within Enterprise Java Bean. As threads in EJBs should not be started in the classical Java SE way, I use the ManagedExecutorService to handle threads.

"Obligatory warning: Creating your own threads in a Java EE app server (even Tomcat) is discouraged as it can be a huge performance issue and in most cases will prevent container functionality, such as JNDI, from working. The new threads won't know which application they belong to, the Thread context classloader will not be set and many other hidden issues."

In Java SE you can define the maximum number of threads, as shown in the following code.

java.util.concurrent.Executors.newFixedThreadPool(numberOfThreadsInThePool);

Do you know how to limit the number of threads excecuted by the ManagedExecutorService?


问:
How to get all same 'key[0]' and calculate its value in the dictionary
```<code>counts = {'A1':3,'A2':2,'A3':1,'A4':10,'B1':11,'B2':12,'B3':3,'B4':0,'C1':3,'C2':16,'C3':8,'C4':2}

#Order grid
def orderGrid(grid):

    lst = list()
    for key,val in grid.items():
        lst.append((val,key))

    lst.sort(reverse=True)

    for val,key in lst:
        print key, val

#Order row
def orderRow(row):
    count = dict()
    for key in row.items():
        if key[0] not in count:
            count[key] = row[key]
        else:
            count[key] += row[key]
    print 'A:', count
</code>```

orderGrid function can run successful, but as the orderrow function is for cluster All amount, which start from 'A', and then rank the rows ('A','B','C','D')

答:
You can use sorted and apply directly on counts

```<code>import operator

sorted_x = sorted(counts.items(), key=operator.itemgetter(1), reverse=True)
</code>```

You can take a new dict and assign key, values as follows:

```<code>In [71]: mydict = {}

In [72]: for k, v in counts.items():
    ...:     if k[0] not in mydict:
    ...:         mydict[k[0]] = v
    ...:     else:
    ...:         mydict[k[0]] += v
    ...:

In [73]: mydict
Out[73]: {'A': 16, 'B': 26, 'C': 29}
</code>```

Replacing the functions would look like this,

```<code>import operator

counts = {'A1':3,'A2':2,'A3':1,'A4':10,'B1':11,'B2':12,'B3':3,'B4':0,'C1':3,'C2':16,'C3':8,'C4':2}

#Order grid
def orderGrid(grid):
    sorted_x = sorted(counts.items(), key=operator.itemgetter(1), reverse=True)
    for key,val in sorted_x:
        print key, val

#Order row
def orderRow(row):
    mydict = {}
    for k, v in row.items():
        if k[0] not in mydict:
            mydict[k[0]] = v
        else:
            mydict[k[0]] += v
    print mydict
</code>```

Body:
counts = {'A1':3,'A2':2,'A3':1,'A4':10,'B1':11,'B2':12,'B3':3,'B4':0,'C1':3,'C2':16,'C3':8,'C4':2}

#Order grid
def orderGrid(grid):

    lst = list()
    for key,val in grid.items():
        lst.append((val,key))

    lst.sort(reverse=True)

    for val,key in lst:
        print key, val

#Order row
def orderRow(row):
    count = dict()
    for key in row.items():
        if key[0] not in count:
            count[key] = row[key]
        else:
            count[key] += row[key]
    print 'A:', count

orderGrid function can run successful, but as the orderrow function is for cluster All amount, which start from 'A', and then rank the rows ('A','B','C','D')

Body:
You can use sorted and apply directly on counts

import operator

sorted_x = sorted(counts.items(), key=operator.itemgetter(1), reverse=True)

You can take a new dict and assign key, values as follows:

In [71]: mydict = {}

In [72]: for k, v in counts.items():
    ...:     if k[0] not in mydict:
    ...:         mydict[k[0]] = v
    ...:     else:
    ...:         mydict[k[0]] += v
    ...:

In [73]: mydict
Out[73]: {'A': 16, 'B': 26, 'C': 29}

Replacing the functions would look like this,

import operator

counts = {'A1':3,'A2':2,'A3':1,'A4':10,'B1':11,'B2':12,'B3':3,'B4':0,'C1':3,'C2':16,'C3':8,'C4':2}

#Order grid
def orderGrid(grid):
    sorted_x = sorted(counts.items(), key=operator.itemgetter(1), reverse=True)
    for key,val in sorted_x:
        print key, val

#Order row
def orderRow(row):
    mydict = {}
    for k, v in row.items():
        if k[0] not in mydict:
            mydict[k[0]] = v
        else:
            mydict[k[0]] += v
    print mydict


问:
Sort an Arraylist using Comparator
To print an output as {first max,first min,second max,second min,third max,third min and so on.....}

```<code>   import java.util.ArrayList;
   import java.util.Collection;
   import java.util.Collections;
   import java.util.Comparator;
   import java.util.Iterator;
   import java.util.List;

  import compl.compl;

  public class Arraylist1 {

public static void main(String args[]){

    List <Integer>list= new ArrayList <Integer> ( );

 list.add(20);
 list.add(30);
 list.add(70);
 list.add(50);
 list.add(60);
 list.add(40);

  Comparator<Integer> cmp=new Comparator<Integer>() {

    @Override
    public int compare(Integer o1, Integer o2) {
        // TODO Auto-generated method stub
        int pos=0;
        if(pos%2==0){
            if(o1<o2){
                return 1;
            }
            }
           if(pos%2!=0){
            if(o1>o2){
                return -1;
            }
            }
            pos++;
        }
    }
};

Collections.sort(list, cmp);
for(int i=0;i<list.size();i++){
    System.out.println(list);
}

 }
}
</code>```

Getting an error as:

```<code>Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    This method must return a result of type int

    at Arraylist1$1.compare(Arraylist1.java:51)
    at Arraylist1$1.compare(Arraylist1.java:1)
    at java.util.TimSort.countRunAndMakeAscending(TimSort.java:324)
    at java.util.TimSort.sort(TimSort.java:189)
    at java.util.TimSort.sort(TimSort.java:173)
    at java.util.Arrays.sort(Arrays.java:659)
    at java.util.Collections.sort(Collections.java:217)
    at Arraylist1.main(Arraylist1.java:67)
</code>```

Not getting exactly why am i getting this error, i guess this cause compartor need return type,but in my case here return type cannot be specified.

答:
The custom comparator cmp was just assigned the task to sort the list in descending order

```<code>Comparator<Integer> cmp = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        if (o1 < o2) {
            return 1;
        } else {
            return -1;
        }
    }
};

Collections.sort(list, cmp);
</code>```

Output: 70 60 50 40 30 20

Then the method modifyList was called to satisfy the max and min requirements. In this, I have created another List<Integer> which will pick elements from the above output list and allocated them in 1st max, 1st min, 2nd max, 2nd min ... so on... order

```<code>public static List<Integer> modifyList(List<Integer> list) {
    List<Integer> result = new ArrayList<>(list.size());

    int i = 0, j = list.size() - 1;
    int r = 0;
    while (r < list.size()) {
        result.add(r++, list.get(i++));
        if (i < j)
            result.add(r++, list.get(j--));
    }

    return result;
}
</code>```

Simply filling elements from front and back side to the resultant list.

Complete program code here

Final Output

Title: Sort an Arraylist using Comparator

Body:
To print an output as {first max,first min,second max,second min,third max,third min and so on.....}

   import java.util.ArrayList;
   import java.util.Collection;
   import java.util.Collections;
   import java.util.Comparator;
   import java.util.Iterator;
   import java.util.List;

  import compl.compl;

  public class Arraylist1 {

public static void main(String args[]){

    List <Integer>list= new ArrayList <Integer> ( );

 list.add(20);
 list.add(30);
 list.add(70);
 list.add(50);
 list.add(60);
 list.add(40);

  Comparator<Integer> cmp=new Comparator<Integer>() {

    @Override
    public int compare(Integer o1, Integer o2) {
        // TODO Auto-generated method stub
        int pos=0;
        if(pos%2==0){
            if(o1<o2){
                return 1;
            }
            }
           if(pos%2!=0){
            if(o1>o2){
                return -1;
            }
            }
            pos++;
        }
    }
};

Collections.sort(list, cmp);
for(int i=0;i<list.size();i++){
    System.out.println(list);
}

 }
}

Getting an error as:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    This method must return a result of type int

    at Arraylist1$1.compare(Arraylist1.java:51)
    at Arraylist1$1.compare(Arraylist1.java:1)
    at java.util.TimSort.countRunAndMakeAscending(TimSort.java:324)
    at java.util.TimSort.sort(TimSort.java:189)
    at java.util.TimSort.sort(TimSort.java:173)
    at java.util.Arrays.sort(Arrays.java:659)
    at java.util.Collections.sort(Collections.java:217)
    at Arraylist1.main(Arraylist1.java:67)

Not getting exactly why am i getting this error, i guess this cause compartor need return type,but in my case here return type cannot be specified.

Body:
The custom comparator cmp was just assigned the task to sort the list in descending order

Comparator<Integer> cmp = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        if (o1 < o2) {
            return 1;
        } else {
            return -1;
        }
    }
};

Collections.sort(list, cmp);

Output: 70 60 50 40 30 20

Then the method modifyList was called to satisfy the max and min requirements. In this, I have created another List<Integer> which will pick elements from the above output list and allocated them in 1st max, 1st min, 2nd max, 2nd min ... so on... order

public static List<Integer> modifyList(List<Integer> list) {
    List<Integer> result = new ArrayList<>(list.size());

    int i = 0, j = list.size() - 1;
    int r = 0;
    while (r < list.size()) {
        result.add(r++, list.get(i++));
        if (i < j)
            result.add(r++, list.get(j--));
    }

    return result;
}

Simply filling elements from front and back side to the resultant list.

Complete program code here

Final Output


问:
jQuery: any suggestions how to preload all images in dom sequentially?
any ideas about it? any plugin? I want find all img tag and show them sequentially?
thank you</p>

答:
Create a small jQuery utility method:

```<code>jQuery.preloadImages = function() {
    var set = jQuery('img');
    var current = 0;
    var iterate = function() {
        var current_src = set[current].src;
        var temp = jQuery('<img/>');
        jQuery(temp).bind('load', function() {
            console.log($(this).attr('src') + ' loaded');
            jQuery(this).remove(); //remove temp image from DOM.
        });

        temp[0].src = current_src;
        jQuery('body').append(temp);
        if(++current < set.length) iterate(); //recursive call
    };
    iterate();
};
</code>```

Invoke this like such:

```<code>$.preloadImages();
</code>```

jsFiddle example

ContentLicense: CC BY-SA 2.5

Body:
Create a small jQuery utility method:

jQuery.preloadImages = function() {
    var set = jQuery('img');
    var current = 0;
    var iterate = function() {
        var current_src = set[current].src;
        var temp = jQuery('<img/>');
        jQuery(temp).bind('load', function() {
            console.log($(this).attr('src') + ' loaded');
            jQuery(this).remove(); //remove temp image from DOM.
        });

        temp[0].src = current_src;
        jQuery('body').append(temp);
        if(++current < set.length) iterate(); //recursive call
    };
    iterate();
};

Invoke this like such:

$.preloadImages();

jsFiddle example


问:
ionic2 AlertController, how to return the buttons clicked value from method
I m fairly new in Typescript, I have following code in provider

```<code>...
confirm(message, title=""){
        let confirm = this.alertCtrl.create({
            title: title || "Please confirm",
            message: message,
            buttons: [
                {
                  text: 'Yes',
                  handler: () => {
                    return true;
                  }
                },
                {
                  text: 'No',
                  handler: () => {
                    return false;
                  }
                }
              ]
        });

        confirm.present();
    }
</code>```

UPDATE:

There is a button in a page, which calls a function deleteItems

```<code>deleteItems(){
    this.popup.confirm("Are you sure you want to delete this item");
    if(this.popup.isTrue == true){
          //delete items
     }

}
</code>```

I want the confirm method to return true or false depending upon the button "Yes" or "No" clicked.

Can anybody tell me how to achieve this?

答:
Both buttons take a handler each. I would use the handlers to set a.

Define arrow functions

```<code>a:boolean;
onYesHandler = ()=>{
   this.a = true;
}

onNoHandler = () =>{
   this.a = false;
}
</code>```

let confirm function take the handlers along with message:

```<code>confirm(message, yesHandler,noHandler,title=""){
        let confirm = this.alertCtrl.create({
            title: title || "Please confirm",
            message: message,
            buttons: [
                {
                  text: 'Yes',
                  handler: yesHandler
                },
                {
                  text: 'No',
                  handler: noHandler
                }
              ]
        });

        confirm.present();
    }
</code>```

call the confirm function:

```<code>this.popup.confirm("Are you sure you want to delete this item",this.onYesHandler,this.onNoHandler);
</code>```

Body:
I m fairly new in Typescript, I have following code in provider

...
confirm(message, title=""){
        let confirm = this.alertCtrl.create({
            title: title || "Please confirm",
            message: message,
            buttons: [
                {
                  text: 'Yes',
                  handler: () => {
                    return true;
                  }
                },
                {
                  text: 'No',
                  handler: () => {
                    return false;
                  }
                }
              ]
        });

        confirm.present();
    }

UPDATE:

There is a button in a page, which calls a function deleteItems

deleteItems(){
    this.popup.confirm("Are you sure you want to delete this item");
    if(this.popup.isTrue == true){
          //delete items
     }

}

I want the confirm method to return true or false depending upon the button "Yes" or "No" clicked.

Can anybody tell me how to achieve this?

Body:
Both buttons take a handler each. I would use the handlers to set a.

Define arrow functions

a:boolean;
onYesHandler = ()=>{
   this.a = true;
}

onNoHandler = () =>{
   this.a = false;
}

let confirm function take the handlers along with message:

confirm(message, yesHandler,noHandler,title=""){
        let confirm = this.alertCtrl.create({
            title: title || "Please confirm",
            message: message,
            buttons: [
                {
                  text: 'Yes',
                  handler: yesHandler
                },
                {
                  text: 'No',
                  handler: noHandler
                }
              ]
        });

        confirm.present();
    }

call the confirm function:

this.popup.confirm("Are you sure you want to delete this item",this.onYesHandler,this.onNoHandler);


问:
How to add a mouselistener below other things in the JFrame?
If my question sounds stupid, I'm sorry, I'm still new to java. I'm gonna show you this bit of code:

```<code>public class Window extends JFrame{

    private static final long serialVersionUID = -2139430787087799923L;

    private TransparentJPanel mousepanel;

    public Window(int width, int height, String title, Game game) {
        super(title);
        HandlerClass handler = new HandlerClass();
        mousepanel = new TransparentJPanel();
        mousepanel.addMouseListener(handler);

        setPreferredSize(new Dimension(width,height));
        setMaximumSize(new Dimension(width,height));
        setMinimumSize(new Dimension(width,height));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        setVisible(true);
        add(game);      <-- here I add the game
        add(mousepanel);    <-- here I add the panel with the mouselistener
        game.start();
    }
}
</code>```

the TransparentJPanel class:

```<code>private class TransparentJPanel extends JPanel {
    private static final long serialVersionUID = 8855609189172945035L;

    TransparentJPanel() {
        super() ;
        this.setOpaque( false ) ;
        this.setLayout( null ) ;
    }
}
</code>```

when I add the game first, the game shows up and the mouse listener doesn't work, but when I add the jpanel first, the game doesnt show up, but the mouselistener works.
Here's my HandlerClass class:

```<code>private class HandlerClass implements MouseListener {
    public void mouseClicked(MouseEvent event) {
        System.out.println(String.format("Clicked at %d,%d", event.getX(), event.getY()));
    }

    public void mouseEntered(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Entered frame at X: " + x + " - Y: " + y);

    }
    public void mouseExited(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Exited frame at X: " + x + " - Y: " + y);

    }
    public void mousePressed(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Pressed frame at X: " + x + " - Y: " + y);

    }

    public void mouseReleased(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Released at X: " + x + " - Y: " + y);

    }

}
</code>```

So, that's my problem.
Please help.

答:
The solution turned out to be simple!

instead of creating a panel for the mouse listener, you can add a mouselistener to the game object, namely as follows

```<code>public Window(int width, int title, String title, Game game) {
    super(title);
    HandlerClass handler = new HandlerClass();

    setPreferredSize(new Dimension(width,height));
    setMaximumSize(new Dimension(width,height));
    setMinimumSize(new Dimension(width,height));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setResizable(false);

    setVisible(true);
    add(game, BorderLayout.CENTER);
    game.addMouseListener(handler);
    game.start();
}
</code>```

Hope this helps!

Body:
If my question sounds stupid, I'm sorry, I'm still new to java. I'm gonna show you this bit of code:

public class Window extends JFrame{

    private static final long serialVersionUID = -2139430787087799923L;

    private TransparentJPanel mousepanel;

    public Window(int width, int height, String title, Game game) {
        super(title);
        HandlerClass handler = new HandlerClass();
        mousepanel = new TransparentJPanel();
        mousepanel.addMouseListener(handler);

        setPreferredSize(new Dimension(width,height));
        setMaximumSize(new Dimension(width,height));
        setMinimumSize(new Dimension(width,height));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        setVisible(true);
        add(game);      <-- here I add the game
        add(mousepanel);    <-- here I add the panel with the mouselistener
        game.start();
    }
}

the TransparentJPanel class:

private class TransparentJPanel extends JPanel {
    private static final long serialVersionUID = 8855609189172945035L;

    TransparentJPanel() {
        super() ;
        this.setOpaque( false ) ;
        this.setLayout( null ) ;
    }
}

when I add the game first, the game shows up and the mouse listener doesn't work, but when I add the jpanel first, the game doesnt show up, but the mouselistener works.
Here's my HandlerClass class:

private class HandlerClass implements MouseListener {
    public void mouseClicked(MouseEvent event) {
        System.out.println(String.format("Clicked at %d,%d", event.getX(), event.getY()));
    }

    public void mouseEntered(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Entered frame at X: " + x + " - Y: " + y);

    }
    public void mouseExited(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Exited frame at X: " + x + " - Y: " + y);

    }
    public void mousePressed(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Pressed frame at X: " + x + " - Y: " + y);

    }

    public void mouseReleased(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        System.out.println("Mouse Released at X: " + x + " - Y: " + y);

    }

}

So, that's my problem.
Please help.

Body:
The solution turned out to be simple!

instead of creating a panel for the mouse listener, you can add a mouselistener to the game object, namely as follows

public Window(int width, int title, String title, Game game) {
    super(title);
    HandlerClass handler = new HandlerClass();

    setPreferredSize(new Dimension(width,height));
    setMaximumSize(new Dimension(width,height));
    setMinimumSize(new Dimension(width,height));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setResizable(false);

    setVisible(true);
    add(game, BorderLayout.CENTER);
    game.addMouseListener(handler);
    game.start();
}

Hope this helps!


问:
While Loop Variable Initialization and Variable Types(C)
I'm relatively new to coding and am currently studying C. I had some trouble regarding a textbook exercise and some help would be much appreciated.

The exercise's main objective is to calculate the total salary that an employee should receive by inputting the hours of work done and the hourly rate. The rate is 100% up to 40 hours, but after 40 hours it goes up to 150%. Here's the code that I wrote:

```<code>#include <stdio.h>

int main (void) {
    int employee, hour, ratenormal, totalrate, counter, rate;
    int salary;

    hour = 1;

    while (hour != -1) {
        printf("Enter # of hours worked (-1 to end): ");
        scanf_s("%d", &hour);
        if (hour == -1) break;

        printf("Enter hourly rate of the work ($00.00): $");
        scanf_s("%d", &rate);

        if (hour <= 40) {
            salary = hour * rate;
        }
        else if (hour > 40) {
            salary = salary + ((hour - 40) * (rate * 1.5));
        }

        printf("Salary is $%d\n\n", salary);
    }

    return 0;
}
</code>```

I had a couple of questions:

1) If I declare the variable "salary" as a float, then the result only prints 0. Why is that?

2) The loop works fine, but only for the first iteration. The problem is that I need to initialize the variable salary again, otherwise it keeps storing some of the value that has been previously used. How could I do this?

Thank you for all the help!

答:
Your problem is using salary uninitialized in the salary calculation for hours > 40. You can take from that it is always good to initialize your variables. Next, you should simply substitute 40 * rate for normal rate part of salary in the hour > 40 salary equation, e.g.

```<code>#include <stdio.h>

int main (void) {
    int hour = 0;
    float rate = 0.0, salary = 0.0;

    while (hour != -1) {
        printf("Enter # of hours worked (-1 to end): ");
        if (scanf ("%d", &hour) != 1) {
            fprintf (stderr, "error: invalid hours input.\n");
            return 1;
        }
        if (hour == -1) break;

        printf("Enter hourly rate of the work ($00.00): $");
        if (scanf ("%f", &rate) != 1) {
            fprintf (stderr, "error: invalid rate input.\n");
            return 1;
        }

        if (hour <= 40) {
            salary = hour * rate;
        }
        else if (hour > 40) {
            salary = 40 * rate + ((hour - 40) * (rate * 1.5));
        }

        printf("Salary is $%.2f\n\n", salary);
    }

    return 0;
}
</code>```

Example Use/Output

```<code>$ ./bin/salary2
Enter # of hours worked (-1 to end): 20
Enter hourly rate of the work ($00.00): $10.50
Salary is $210.00

Enter # of hours worked (-1 to end): 60
Enter hourly rate of the work ($00.00): $10.50
Salary is $735.00
</code>```

note: I have no scanf_s function on Linux (they _s flavors a primarily windoze), so I have used scanf above, but scanf_s will work fine in  your case.

Body:
I'm relatively new to coding and am currently studying C. I had some trouble regarding a textbook exercise and some help would be much appreciated.

The exercise's main objective is to calculate the total salary that an employee should receive by inputting the hours of work done and the hourly rate. The rate is 100% up to 40 hours, but after 40 hours it goes up to 150%. Here's the code that I wrote:

#include <stdio.h>

int main (void) {
    int employee, hour, ratenormal, totalrate, counter, rate;
    int salary;

    hour = 1;

    while (hour != -1) {
        printf("Enter # of hours worked (-1 to end): ");
        scanf_s("%d", &hour);
        if (hour == -1) break;

        printf("Enter hourly rate of the work ($00.00): $");
        scanf_s("%d", &rate);

        if (hour <= 40) {
            salary = hour * rate;
        }
        else if (hour > 40) {
            salary = salary + ((hour - 40) * (rate * 1.5));
        }

        printf("Salary is $%d\n\n", salary);
    }

    return 0;
}

I had a couple of questions:

1) If I declare the variable "salary" as a float, then the result only prints 0. Why is that?

2) The loop works fine, but only for the first iteration. The problem is that I need to initialize the variable salary again, otherwise it keeps storing some of the value that has been previously used. How could I do this?

Thank you for all the help!

Body:
Your problem is using salary uninitialized in the salary calculation for hours > 40. You can take from that it is always good to initialize your variables. Next, you should simply substitute 40 * rate for normal rate part of salary in the hour > 40 salary equation, e.g.

#include <stdio.h>

int main (void) {
    int hour = 0;
    float rate = 0.0, salary = 0.0;

    while (hour != -1) {
        printf("Enter # of hours worked (-1 to end): ");
        if (scanf ("%d", &hour) != 1) {
            fprintf (stderr, "error: invalid hours input.\n");
            return 1;
        }
        if (hour == -1) break;

        printf("Enter hourly rate of the work ($00.00): $");
        if (scanf ("%f", &rate) != 1) {
            fprintf (stderr, "error: invalid rate input.\n");
            return 1;
        }

        if (hour <= 40) {
            salary = hour * rate;
        }
        else if (hour > 40) {
            salary = 40 * rate + ((hour - 40) * (rate * 1.5));
        }

        printf("Salary is $%.2f\n\n", salary);
    }

    return 0;
}

Example Use/Output

$ ./bin/salary2
Enter # of hours worked (-1 to end): 20
Enter hourly rate of the work ($00.00): $10.50
Salary is $210.00

Enter # of hours worked (-1 to end): 60
Enter hourly rate of the work ($00.00): $10.50
Salary is $735.00

note: I have no scanf_s function on Linux (they _s flavors a primarily windoze), so I have used scanf above, but scanf_s will work fine in  your case.


问:
How to resize images in org-mode
Is there a general way to define the size, in percent or pixels, for an image that is linked in org-mode?

Say I have the following link in my .org file:

```<code>[[~/images/example.jpg]]
</code>```

This JPG is way too large, so if I export it to HTML or LaTeX or open it in org-mode with C-c C-o i will only see a fraction of the image.

答:
This is a sample on how to resize an image using percentages (Org mode version 9.0.5):

```<code>#+CAPTION: Weight space
#+ATTR_HTML: :alt neural network :title Neural network representation :align right
#+ATTR_HTML: :width 50% :height 50%
https://i.stack.imgur.com/nzHSl.jpg
</code>```

Title: How to resize images in org-mode

Body:
Is there a general way to define the size, in percent or pixels, for an image that is linked in org-mode?

Say I have the following link in my .org file:

[[~/images/example.jpg]]

This JPG is way too large, so if I export it to HTML or LaTeX or open it in org-mode with C-c C-o i will only see a fraction of the image.

Body:
This is a sample on how to resize an image using percentages (Org mode version 9.0.5):

#+CAPTION: Weight space
#+ATTR_HTML: :alt neural network :title Neural network representation :align right
#+ATTR_HTML: :width 50% :height 50%
https://i.stack.imgur.com/nzHSl.jpg


问:
Rails accessing fields_for hidden_field id
I have a nested form with a parent object (full_application) and a collection of child objects (fullapplication_districts) via a has_many association. I am attempting to allow for deletion of individual child objects on the form (via javascript) but to do so I need to be able to grab the id of each child object in the view for passing to the controller. fields_for creates a hidden input field for the id but I can't seem to figure out how to grab the id from it. In the example below the record is the 13th in the list of rendered child objects.

```<code><input type="hidden" value="538" name="full_application[fullapplication_districts_attributes][12][id]" id="full_application_fullapplication_districts_attributes_12_id">
</code>```

Here's the form setup in the view:

```<code><%= form_for(@full_application, url: full_applications_edit_path, method: :put) do |f| %>
  <%= f.fields_for :fullapplication_districts do |fad| %>
    <%= fad.collection_select :district_id, District.all, :id, :name, {include_blank: true}, {class: 'form-control'} %>
    <%= fad.number_field :percent_one, class: 'form-control', step: :any %>
    <%= fad.number_field :percent_two, class: 'form-control', step: :any %>
    <%= fad.number_field :percent_three, class: 'form-control', step: :any %>
    <%= link_to full_applications_districts_path(???), method: :delete, remote: true, data: { confirm: "Are you sure you want to delete this record?" } do %>
      <i class="fa fa-trash"></i>
    <% end %>
  <% end %>
<% end %>
</code>```

答:
You can use: fad.object or fad.object.id. This will return to fullapplication_district instance.

```<code> <%= link_to full_applications_districts_path(fad.object), method: :delete, remote: true, data: { confirm: "Are you sure you want to delete this record?" } do %>
    <i class="fa fa-trash"></i>
 <% end %>
</code>```

Body:
I have a nested form with a parent object (full_application) and a collection of child objects (fullapplication_districts) via a has_many association. I am attempting to allow for deletion of individual child objects on the form (via javascript) but to do so I need to be able to grab the id of each child object in the view for passing to the controller. fields_for creates a hidden input field for the id but I can't seem to figure out how to grab the id from it. In the example below the record is the 13th in the list of rendered child objects.

<input type="hidden" value="538" name="full_application[fullapplication_districts_attributes][12][id]" id="full_application_fullapplication_districts_attributes_12_id">

Here's the form setup in the view:

<%= form_for(@full_application, url: full_applications_edit_path, method: :put) do |f| %>
  <%= f.fields_for :fullapplication_districts do |fad| %>
    <%= fad.collection_select :district_id, District.all, :id, :name, {include_blank: true}, {class: 'form-control'} %>
    <%= fad.number_field :percent_one, class: 'form-control', step: :any %>
    <%= fad.number_field :percent_two, class: 'form-control', step: :any %>
    <%= fad.number_field :percent_three, class: 'form-control', step: :any %>
    <%= link_to full_applications_districts_path(???), method: :delete, remote: true, data: { confirm: "Are you sure you want to delete this record?" } do %>

    <% end %>
  <% end %>
<% end %>

Body:
You can use: fad.object or fad.object.id. This will return to fullapplication_district instance.

 <%= link_to full_applications_districts_path(fad.object), method: :delete, remote: true, data: { confirm: "Are you sure you want to delete this record?" } do %>
    <i class="fa fa-trash"></i>
 <% end %>


问:
Expand a random range from 1–5 to 1–7
Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.</p>

答:
```<code>int getOneToSeven(){
    int added = 0;
    for(int i = 1; i<=7; i++){
        added += getOneToFive();
    }
    return (added)%7+1;
}
</code>```

OwnerDisplayName: praveen chettypally

ContentLicense: CC BY-SA 4.0

Title: Expand a random range from 1–5 to 1–7

LastEditorDisplayName: Roger Pate


问:
Make container stay in position when dropdown menu is click on mobile
Every time I click the "burger logo" my container gets pushed down a couple pixels and I want the "nav-list" to position its self above the container so that when a user clicks the logo, the container stays in place while the list items just float on top of them. I tried everything from "position: absolute" to "z-index: 100" and nothing seems to work.
Please try and open it up in "inspect element" and go to "iPhone 6 plus -vertical" view and test out and you will see the "Open Touch" moves down.
Here is my code:

Demo:

```<code>http://codepen.io/anon/pen/xqMrRy
</code>```

html

```<code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>Open Touch</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <link href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&subset=latin" rel="stylesheet">

        <link href="https://fonts.googleapis.com/css?family=Nunito:700" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Baloo" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

             <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

        <link rel="stylesheet" type="text/css" href="magicstyle.css">

        </head>
        <body>
            <!-- Section for Jobs Popup -->
            <div id="top-bar">
                  <a id="burger-nav"></a>
                    <ul id="nav-menu" class="blah">
                    <li id="job" class="testAgain">Jobs</li>
                    <li id="contact" class="testAgain">Contact</li>
                    <li id="press" class="testAgain">Press</li>
                    <li id="legal" class="testAgain">Legal</li>
                    <li id="support" class="testAgain">Support</li>

                </ul>
                </div>

            <div id="container">

                <div id="name-div">
                <h1 id="name">Open Touch</h1>
                </div>

            </div>

        </body>

</html>
</code>```

Css

```<code>            @font-face{
                font-family: 'custom';
                src: url('HelveticaNeue.ttf');
            }
             #top-bar{
                width:100%;
                min-height: 5px;
                background-color: #FFFFFF;
                position: relative;
                 z-index: 3;
                z-index: 101;
                 overflow: hidden;

            }
            #nav-menu{
                width: 100%;
                height: 32px;
                min-height: 5px;
                list-style: none;
                overflow: hidden;
            }
            #nav-menu li{
                float: left;
                padding-right: 100px;
                font-size: 1.2em;
                position: relative;
                top:0.6vh;
                left:14%;
                vertical-align: middle;
                display: inline-block;
                cursor: pointer;
                -webkit-user-select: none;
                -ms-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;

            }

            #container{
                width: 100%;
                height: 100vh;
                background-image: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
                position: absolute;
                left:0;
                right:0;
                overflow: hidden;

            }
            body {
                width: 100%;
                height: 100vh;
                margin: 0;
                padding: 0;
                color:#262626;
                overflow-y: hidden;
                overflow-x: hidden;
                font-family: 'custom';
            }
            #name-div{
               margin-left:auto;
                margin-right:auto;
                width:80%;
                position: relative;
                top:27%;
                z-index: 10;
                -webkit-user-select: none;
                -ms-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;

            }
/* Start of Job css for popup and animation ------------------------------------------------------------------------------------------------------------- */
        #name{
                color:white;
                font-size: 7em;
                word-wrap: break-word;
                z-index: 10;
                text-align: center;

            }

@media screen and (max-width: 414px) {
      #burger-nav{
        display: block;
        width: 100%;
        height: 40px;
        background: url(burgerlogo.png) no-repeat 98% center;
        background-size: 30px 30px;
         background-color: white;

    }
    #burger-nav.show{
        background-color: #f97072;
    }
     #nav-menu{
        background-color: white;
        margin: 0;
        padding:0;
        width: 100%;
        height:100%;
        overflow: hidden;
         display: none;

    }
    #nav-menu.open{
        display: block;
        z-index: 100;
    }

    #nav-menu li{
        float: none;
        padding: 10px;
        position: relative;
        text-align: right;
        top:0;
        left:0;
        cursor: pointer;
        border-bottom: 0.1px solid #f8f9fb;
        display: block;
        font-weight: bold;

    }
    #nav-menu li:hover {
        background-color: #f8f9fb;
    }
    #name-div{
        position: absolute;
        top: 40%;
        left: 0%;
        z-index: 10;
        -webkit-user-select: none;
        -ms-user-select: none;
        -moz-user-select: none;
        -o-user-select: none;

            }
    #name{
        font-size: 4em;
    }
    #name.show{
        position: relative;
        bottom: 40px;
    }

}
</code>```

Java script

```<code>   // document.getElementById("burger-nav").onclick = function() {
      //  var menu = document.getElementById("nav-menu");
        //menu.classList.toggle("open");
    //}

    $("document").ready(function() {

        document.getElementById("burger-nav").onclick = function() {
            var menu = document.getElementById("nav-menu");
                menu.classList.toggle("open");
        }
        $(".testAgain").click(function() {
            $("#burger-nav").css("background-color", "#f97072");
           $(".blah").removeClass("open");
        });
    });
</code>```

答:
First, you need to absolute position the menu for it to be remove from the layout and not affect the position of elements after it.

Second, the menu currently lives in a parent element to which you have set overflow:hidden. This is why it looks like the z-index is making it show underneath the content when in reality it's just completely outside bounds the overflow.

Third, the ul has a specified height of 100% AND 32px that is shrinking it to the size of the container which is only ~1 list item high.

http://codepen.io/anon/pen/jBdwva

Body:
Every time I click the "burger logo" my container gets pushed down a couple pixels and I want the "nav-list" to position its self above the container so that when a user clicks the logo, the container stays in place while the list items just float on top of them. I tried everything from "position: absolute" to "z-index: 100" and nothing seems to work.
Please try and open it up in "inspect element" and go to "iPhone 6 plus -vertical" view and test out and you will see the "Open Touch" moves down.
Here is my code:

Demo:

http://codepen.io/anon/pen/xqMrRy

html

        <title>Open Touch</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <link href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&subset=latin" rel="stylesheet">

        <link href="https://fonts.googleapis.com/css?family=Nunito:700" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Baloo" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

        <link rel="stylesheet" type="text/css" href="magicstyle.css">

Jobs

Contact

Press

Legal

Support

Open Touch

Css

            @font-face{
                font-family: 'custom';
                src: url('HelveticaNeue.ttf');
            }
             #top-bar{
                width:100%;
                min-height: 5px;
                background-color: #FFFFFF;
                position: relative;
                 z-index: 3;
                z-index: 101;
                 overflow: hidden;

            }
            #nav-menu{
                width: 100%;
                height: 32px;
                min-height: 5px;
                list-style: none;
                overflow: hidden;
            }
            #nav-menu li{
                float: left;
                padding-right: 100px;
                font-size: 1.2em;
                position: relative;
                top:0.6vh;
                left:14%;
                vertical-align: middle;
                display: inline-block;
                cursor: pointer;
                -webkit-user-select: none;
                -ms-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;

            }

            #container{
                width: 100%;
                height: 100vh;
                background-image: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
                position: absolute;
                left:0;
                right:0;
                overflow: hidden;

            }
            body {
                width: 100%;
                height: 100vh;
                margin: 0;
                padding: 0;
                color:#262626;
                overflow-y: hidden;
                overflow-x: hidden;
                font-family: 'custom';
            }
            #name-div{
               margin-left:auto;
                margin-right:auto;
                width:80%;
                position: relative;
                top:27%;
                z-index: 10;
                -webkit-user-select: none;
                -ms-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;

            }
/* Start of Job css for popup and animation ------------------------------------------------------------------------------------------------------------- */
        #name{
                color:white;
                font-size: 7em;
                word-wrap: break-word;
                z-index: 10;
                text-align: center;

            }

@media screen and (max-width: 414px) {
      #burger-nav{
        display: block;
        width: 100%;
        height: 40px;
        background: url(burgerlogo.png) no-repeat 98% center;
        background-size: 30px 30px;
         background-color: white;

    }
    #burger-nav.show{
        background-color: #f97072;
    }
     #nav-menu{
        background-color: white;
        margin: 0;
        padding:0;
        width: 100%;
        height:100%;
        overflow: hidden;
         display: none;

    }
    #nav-menu.open{
        display: block;
        z-index: 100;
    }

    #nav-menu li{
        float: none;
        padding: 10px;
        position: relative;
        text-align: right;
        top:0;
        left:0;
        cursor: pointer;
        border-bottom: 0.1px solid #f8f9fb;
        display: block;
        font-weight: bold;

    }
    #nav-menu li:hover {
        background-color: #f8f9fb;
    }
    #name-div{
        position: absolute;
        top: 40%;
        left: 0%;
        z-index: 10;
        -webkit-user-select: none;
        -ms-user-select: none;
        -moz-user-select: none;
        -o-user-select: none;

            }
    #name{
        font-size: 4em;
    }
    #name.show{
        position: relative;
        bottom: 40px;
    }

}

Java script

   // document.getElementById("burger-nav").onclick = function() {
      //  var menu = document.getElementById("nav-menu");
        //menu.classList.toggle("open");
    //}

    $("document").ready(function() {

        document.getElementById("burger-nav").onclick = function() {
            var menu = document.getElementById("nav-menu");
                menu.classList.toggle("open");
        }
        $(".testAgain").click(function() {
            $("#burger-nav").css("background-color", "#f97072");
           $(".blah").removeClass("open");
        });
    });


问:
Pass data from Activity to Service using an Intent
How do I get data within an Android Service that was passed from an invoking Activity?

答:
Another posibility is using intent.getAction:

In Service:

```<code>public class SampleService inherits Service{
    static final String ACTION_START = "com.yourcompany.yourapp.SampleService.ACTION_START";
    static final String ACTION_DO_SOMETHING_1 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_1";
    static final String ACTION_DO_SOMETHING_2 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_2";
    static final String ACTION_STOP_SERVICE = "com.yourcompany.yourapp.SampleService.STOP_SERVICE";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        //System.out.println("ACTION: "+action);
        switch (action){
            case ACTION_START:
                startingService(intent.getIntExtra("valueStart",0));
                break;
            case ACTION_DO_SOMETHING_1:
                int value1,value2;
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething1(value1,value2);
                break;
            case ACTION_DO_SOMETHING_2:
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething2(value1,value2);
                break;
            case ACTION_STOP_SERVICE:
                stopService();
                break;
        }
        return START_STICKY;
    }

    public void startingService(int value){
        //calling when start
    }

    public void doSomething1(int value1, int value2){
        //...
    }

    public void doSomething2(int value1, int value2){
        //...
    }

    public void stopService(){
        //...destroy/release objects
        stopself();
    }
}
</code>```

In Activity:

```<code>public void startService(int value){
    Intent myIntent = new Intent(SampleService.ACTION_START);
    myIntent.putExtra("valueStart",value);
    startService(myIntent);
}

public void serviceDoSomething1(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_1);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void serviceDoSomething2(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_2);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void endService(){
    Intent myIntent = new Intent(SampleService.STOP_SERVICE);
    startService(myIntent);
}
</code>```

Finally, In Manifest file:

```<code><service android:name=".SampleService">
    <intent-filter>
        <action android:name="com.yourcompany.yourapp.SampleService.ACTION_START"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"/>
        <action android:name="com.yourcompany.yourapp.SampleService.STOP_SERVICE"/>
    </intent-filter>
</service>
</code>```

Body:
Another posibility is using intent.getAction:

In Service:

public class SampleService inherits Service{
    static final String ACTION_START = "com.yourcompany.yourapp.SampleService.ACTION_START";
    static final String ACTION_DO_SOMETHING_1 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_1";
    static final String ACTION_DO_SOMETHING_2 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_2";
    static final String ACTION_STOP_SERVICE = "com.yourcompany.yourapp.SampleService.STOP_SERVICE";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        //System.out.println("ACTION: "+action);
        switch (action){
            case ACTION_START:
                startingService(intent.getIntExtra("valueStart",0));
                break;
            case ACTION_DO_SOMETHING_1:
                int value1,value2;
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething1(value1,value2);
                break;
            case ACTION_DO_SOMETHING_2:
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething2(value1,value2);
                break;
            case ACTION_STOP_SERVICE:
                stopService();
                break;
        }
        return START_STICKY;
    }

    public void startingService(int value){
        //calling when start
    }

    public void doSomething1(int value1, int value2){
        //...
    }

    public void doSomething2(int value1, int value2){
        //...
    }

    public void stopService(){
        //...destroy/release objects
        stopself();
    }
}

In Activity:

public void startService(int value){
    Intent myIntent = new Intent(SampleService.ACTION_START);
    myIntent.putExtra("valueStart",value);
    startService(myIntent);
}

public void serviceDoSomething1(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_1);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void serviceDoSomething2(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_2);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void endService(){
    Intent myIntent = new Intent(SampleService.STOP_SERVICE);
    startService(myIntent);
}

Finally, In Manifest file:

<service android:name=".SampleService">
    <intent-filter>
        <action android:name="com.yourcompany.yourapp.SampleService.ACTION_START"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"/>
        <action android:name="com.yourcompany.yourapp.SampleService.STOP_SERVICE"/>
    </intent-filter>
</service>


问:
Distutils: Compiling an Objective-C++ source file as part of a C++ extension
I am writing a Python extension in C++. I compile it by defining a list of the constituent source files in my setup.py file, like so:

extensions = {
    'im': [
        "im/src/buffer.cpp",
        "im/src/detail.cpp",
        "im/src/gil.cpp",
        "im/src/halideimage.cpp",
        "im/src/hybrid.cpp",
        "im/src/hybridimage.cpp",
        "im/src/options.cpp",
        "im/src/pybuffer.cpp",
        "im/src/pycapsule.cpp",
        "im/src/structcode.cpp",
        "im/src/typecode.cpp",
        "im/src/module.cpp"
    ],
}
```

<p>… these are used to define an instance of <code>setuptools.Extension</code> which is ultimately passed to the <code>setup()</code> function. This has all worked just fine throughout the project, until now, when I tried to add a platform-specific bit:</p>

<pre class="lang-py prettyprint-override"><code>preview_source = (sys.platform == 'darwin') and 'im/src/plat/preview_mac.mm' or \
                  (sys.platform == 'linux') and 'im/src/plat/preview_linux.cpp' or \
                  (sys.platform == 'win32') and 'im/src/plat/preview_windows.cpp' or \
                                                'im/src/plat/preview.cpp'

extensions = {
    'im': [
        "im/src/buffer.cpp",
        "im/src/detail.cpp",
        "im/src/gil.cpp",
        "im/src/halideimage.cpp",
        "im/src/hybrid.cpp",
        "im/src/hybridimage.cpp",
        "im/src/options.cpp",
        preview_source,
        "im/src/pybuffer.cpp",
        "im/src/pycapsule.cpp",
        "im/src/structcode.cpp",
        "im/src/typecode.cpp",
        "im/src/module.cpp"
    ],
}
</code>```

… adding this new bit chooses the right file for compilation – but it fails to compile at all on Mac OS X. Apparently distutils/setuptools doesn’t recognize the “.mm” extension as a source file:

error: unknown file type '.mm'

I am no expert when it comes to distutils and setuptools platform-specific configuration – what’s a simple way to conditionally add this one source file to the source file list on the Mac?

答:
I ran into the same issue, did you ever find some solution?

It looks like '.mm' is not supported in my version of distutils but '.m' is. So I separated the C++ parts of the .mm file into a .cpp file, and create a small C header to access the .m file from that .cpp.

Body:
I am writing a Python extension in C++. I compile it by defining a list of the constituent source files in my setup.py file, like so:

extensions = {
    'im': [
        "im/src/buffer.cpp",
        "im/src/detail.cpp",
        "im/src/gil.cpp",
        "im/src/halideimage.cpp",
        "im/src/hybrid.cpp",
        "im/src/hybridimage.cpp",
        "im/src/options.cpp",
        "im/src/pybuffer.cpp",
        "im/src/pycapsule.cpp",
        "im/src/structcode.cpp",
        "im/src/typecode.cpp",
        "im/src/module.cpp"
    ],
}

… these are used to define an instance of setuptools.Extension which is ultimately passed to the setup() function. This has all worked just fine throughout the project, until now, when I tried to add a platform-specific bit:

preview_source = (sys.platform == 'darwin') and 'im/src/plat/preview_mac.mm' or \
                  (sys.platform == 'linux') and 'im/src/plat/preview_linux.cpp' or \
                  (sys.platform == 'win32') and 'im/src/plat/preview_windows.cpp' or \
                                                'im/src/plat/preview.cpp'

extensions = {
    'im': [
        "im/src/buffer.cpp",
        "im/src/detail.cpp",
        "im/src/gil.cpp",
        "im/src/halideimage.cpp",
        "im/src/hybrid.cpp",
        "im/src/hybridimage.cpp",
        "im/src/options.cpp",
        preview_source,
        "im/src/pybuffer.cpp",
        "im/src/pycapsule.cpp",
        "im/src/structcode.cpp",
        "im/src/typecode.cpp",
        "im/src/module.cpp"
    ],
}

… adding this new bit chooses the right file for compilation – but it fails to compile at all on Mac OS X. Apparently distutils/setuptools doesn’t recognize the “.mm” extension as a source file:

error: unknown file type '.mm'

I am no expert when it comes to distutils and setuptools platform-specific configuration – what’s a simple way to conditionally add this one source file to the source file list on the Mac?


问:
Understanding binary addition program
This program is about binary addition in Java:

```<code>public static String binaryAddition(String s1, String s2) {
    if (s1 == null || s2 == null) return "";
    int first = s1.length() - 1;
    int second = s2.length() - 1;
    StringBuilder sb = new StringBuilder();
    int carry = 0;
    while (first >= 0 || second >= 0) {
        int sum = carry;
        if (first >= 0) {
            sum += s1.charAt(first) - '0';
            first--;
        }
        if (second >= 0) {
            sum += s2.charAt(second) - '0';
            second--;
        }
        carry = sum >> 1;
        sum = sum & 1;
        sb.append(sum == 0 ? '0' : '1');
    }
    if (carry > 0)
        sb.append('1');

    sb.reverse();
    return String.valueOf(sb);
}
</code>```

I am having difficulty in understanding this program.

Why we have to substract with 0 here?

```<code>sum += s1.charAt(first) - '0';
</code>```

What is the use of >> operator and & operator here:

```<code>        carry = sum >> 1;
        sum = sum & 1;
        sb.append(sum == 0 ? '0' : '1');
</code>```

Can you please help me in understanding this program.

答:
Why we have to subtract with 0 here?

```<code> sum += s1.charAt(first) - '0';
</code>```

That is converting the characters '0' and '1' to the numbers 0 and 1.

What is the use of >> operator and & operator here:

The >> is shifting one bit to the right, and the & is masking out all bits apart from the rightmost one.

Can I recommend that you find and read a tutorial on how bitwise operations work in Java.  This is very basic stuff.  Once you understand the basics, then you should be able to read and understand code like the code you have shown us.

Title: Understanding binary addition program

Body:
This program is about binary addition in Java:

public static String binaryAddition(String s1, String s2) {
    if (s1 == null || s2 == null) return "";
    int first = s1.length() - 1;
    int second = s2.length() - 1;
    StringBuilder sb = new StringBuilder();
    int carry = 0;
    while (first >= 0 || second >= 0) {
        int sum = carry;
        if (first >= 0) {
            sum += s1.charAt(first) - '0';
            first--;
        }
        if (second >= 0) {
            sum += s2.charAt(second) - '0';
            second--;
        }
        carry = sum >> 1;
        sum = sum & 1;
        sb.append(sum == 0 ? '0' : '1');
    }
    if (carry > 0)
        sb.append('1');

    sb.reverse();
    return String.valueOf(sb);
}

I am having difficulty in understanding this program.

Why we have to substract with 0 here?

sum += s1.charAt(first) - '0';

What is the use of >> operator and & operator here:

        carry = sum >> 1;
        sum = sum & 1;
        sb.append(sum == 0 ? '0' : '1');

Can you please help me in understanding this program.

Body:
Why we have to subtract with 0 here?

 sum += s1.charAt(first) - '0';

That is converting the characters '0' and '1' to the numbers 0 and 1.

What is the use of >> operator and & operator here:

The >> is shifting one bit to the right, and the & is masking out all bits apart from the rightmost one.

Can I recommend that you find and read a tutorial on how bitwise operations work in Java.  This is very basic stuff.  Once you understand the basics, then you should be able to read and understand code like the code you have shown us.


问:
Android: Help create progress bar while injecting sql
I am doing some injections to sql, about a hundred on first launch.  it doesn't take that long but i want a progress bar while the app is injecting data. </p>

<p>This is my code but progress bar doesn't appear, only black screen.  </p>

```<code>SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        boolean firstStart = settings.getBoolean("firstStart", true);

        if(firstStart) {
         ProgressDialog dialog = ProgressDialog.show(myInject.this, "", "Please wait.", true);

            addInjection("The quick brown fox"); // about a hundred of these injections

SharedPreferences.Editor editor = settings.edit();
         editor.putBoolean("firstStart", false);
         editor.commit();

         dialog.dismiss(); //if i remove this i can see the progress dialog but wont close.
}
</code>```

答:
You will be running the operation on the UI Thread doing it this way. Take a look at running the 'inject' code within an AsyncTask

It's worth having a read up on the developer site about not running tasks on the UI Thread.

Body:
I am doing some injections to sql, about a hundred on first launch.  it doesn't take that long but i want a progress bar while the app is injecting data.

This is my code but progress bar doesn't appear, only black screen.

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        boolean firstStart = settings.getBoolean("firstStart", true);

        if(firstStart) {
         ProgressDialog dialog = ProgressDialog.show(myInject.this, "", "Please wait.", true);

            addInjection("The quick brown fox"); // about a hundred of these injections

SharedPreferences.Editor editor = settings.edit();
         editor.putBoolean("firstStart", false);
         editor.commit();

         dialog.dismiss(); //if i remove this i can see the progress dialog but wont close.
}


问:
I want to make a plot in R with ggplot but it gives me a value
I'm trying to make a barplot with ggplot2. This is the dataset (Error should be in the x, and cantidad as y):

When I run this:

```<code>grafico <- ggplot(tipoerror, aes(x = Error, y = Cantidad))
</code>```

I have no plot in the plots section. I have a new value in the environment instead.

Can you help me to see what I'm doing wrong?

答:
If your data is already summarised, you need to add stat = "identity". As mentioned in the comments, you will also need layer. In this case, geom_bar. </p>

```<code>library(ggplot)
er <- data.frame(A = c("John", "Erik", "David"), Count = c(39, 49, 68))
er
ggplot(er, aes(x = A, y = Count)) + geom_bar(stat = "identity")
</code>```

Body:
I'm trying to make a barplot with ggplot2. This is the dataset (Error should be in the x, and cantidad as y):

When I run this:

grafico <- ggplot(tipoerror, aes(x = Error, y = Cantidad))

I have no plot in the plots section. I have a new value in the environment instead.

Can you help me to see what I'm doing wrong?

Body:
If your data is already summarised, you need to add stat = "identity". As mentioned in the comments, you will also need layer. In this case, geom_bar.

library(ggplot)
er <- data.frame(A = c("John", "Erik", "David"), Count = c(39, 49, 68))
er
ggplot(er, aes(x = A, y = Count)) + geom_bar(stat = "identity")


问:
Doctrine query with join table
I'm trying to create this SQL query in a doctrine QueryBuilder

```<code>SELECT count(DISTINCT d.id)
FROM `discount` d
JOIN `order_discount_relationships` od ON od.discount_id = d.id
JOIN `orders` o ON o.id = od.order_id
WHERE o.status = 3
</code>```

My two entity are those:

```<code>/**
 * @ORM\Table
 */
class Discount
{
    // ...
}
</code>```

And

```<code>/**
 * @ORM\Table
 */
class Order
{
    // ...

    /**
     * @var Discount[]|ArrayCollection
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Discount")
     * @ORM\OrderBy({"id" = "ASC"})
     * @ORM\JoinTable(name="order_discount_relationships",
     *      joinColumns={@ORM\JoinColumn(name="order_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="discount_id", referencedColumnName="id")}
     * )
     */
    private $discounts;

    // ...
}
</code>```

I'd like to count Discount which are already used (in a order with status 3)

```<code>$qb = $this->createQueryBuilder('d');
$qb->select('count(DISTINCT d)')
    ->join('AppBundle:Order', 'o', 'WITH', 'o.discountCodes = d')
    ->where('o.status = :status')
    ->setParameter('status', Order::STATUS_SUCCESS)
;
</code>```

But I got this error:

Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected

Do you know how do that?
Thanks for helping

答:
Try to use member of

```<code>$qb->select('count(DISTINCT d)')
    ->join('AppBundle:Order', 'o', 'WITH', 'd member of o.discounts')
    ->where('o.status = :status')
    ->setParameter('status', Order::STATUS_SUCCESS)
;
</code>```

Title: Doctrine query with join table

Body:
I'm trying to create this SQL query in a doctrine QueryBuilder

SELECT count(DISTINCT d.id)
FROM `discount` d
JOIN `order_discount_relationships` od ON od.discount_id = d.id
JOIN `orders` o ON o.id = od.order_id
WHERE o.status = 3

My two entity are those:

/**
 * @ORM\Table
 */
class Discount
{
    // ...
}

And

/**
 * @ORM\Table
 */
class Order
{
    // ...

    /**
     * @var Discount[]|ArrayCollection
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Discount")
     * @ORM\OrderBy({"id" = "ASC"})
     * @ORM\JoinTable(name="order_discount_relationships",
     *      joinColumns={@ORM\JoinColumn(name="order_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="discount_id", referencedColumnName="id")}
     * )
     */
    private $discounts;

    // ...
}

I'd like to count Discount which are already used (in a order with status 3)

$qb = $this->createQueryBuilder('d');
$qb->select('count(DISTINCT d)')
    ->join('AppBundle:Order', 'o', 'WITH', 'o.discountCodes = d')
    ->where('o.status = :status')
    ->setParameter('status', Order::STATUS_SUCCESS)
;

But I got this error:

Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected

Do you know how do that?
Thanks for helping

Body:
Try to use member of

$qb->select('count(DISTINCT d)')
    ->join('AppBundle:Order', 'o', 'WITH', 'd member of o.discounts')
    ->where('o.status = :status')
    ->setParameter('status', Order::STATUS_SUCCESS)
;


问:
Karma test injected service
I'm trying to test a component with injected service that contains a http post method. but when I run the test karma shows me the message below :

TypeError: Cannot read property 'response' of undefined

this is my code :

this is the save method that is invoked by the button and the method addUser that call the SignupService  addUser method:

```<code>save() {
this.addUser();
this.onShowModal();

 }

  private addUser(){
  // Copy the form values over the product object values
  let user = Object.assign({}, this.customer, this.signUpForm.value);
  this.signUpService.addUser(user).subscribe((result) =>         this.onSaveComplete(result),
    (error: any) => this.errorMessage = <any>error);
   this.modalMessage = this.errorMessage

}
</code>```

and this is the SignupService addUser method :

```<code>addUser (user : Customer){
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.url,user,options)
  .map(this.extractResponseData)
  .do(data => console.log('Add user : ' + JSON.stringify(data)))
  .catch(this.handleError);

private handleError(error: Response) {
return Observable.throw(error.json().error || 'Server error');}

 private extractResponseData(response: Response){
let body = response.json();
console.log(body.data);
return body.data || {};
</code>```

}

and finally this is my spec that handle the error:

```<code>   it('should save the user submetted',() => {
   component.save();
   let signup = component.signUpForm;
   signup.get('firstName').setValue('BEN');
   signup.get('secondName').setValue('wis');
   signup.get('username').setValue('wiss013');
   signup.get('email').setValue('xz@gmail.com');
   signup.get('passwordMatch').get('password').setValue('wis');
   signup.get('passwordMatch').get('confirmPassword').setValue('wis');
   let show = component.showModal;
   expect(show).toBeTruthy();
 });
});
</code>```

Any one can help me please ?!

答:
```<code>describe('Test you service', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [YOUR_SERVICE]
    });
  });

  it('hashCode should return correct hash code', inject([YOUR_SERVICE], (service: YOUR_SERVICE) => {
    ....
  }));
});
</code>```

Title: Karma test injected service

Body:
I'm trying to test a component with injected service that contains a http post method. but when I run the test karma shows me the message below :

TypeError: Cannot read property 'response' of undefined

this is my code :

this is the save method that is invoked by the button and the method addUser that call the SignupService  addUser method:

save() {
this.addUser();
this.onShowModal();

 }

  private addUser(){
  // Copy the form values over the product object values
  let user = Object.assign({}, this.customer, this.signUpForm.value);
  this.signUpService.addUser(user).subscribe((result) =>         this.onSaveComplete(result),
    (error: any) => this.errorMessage = <any>error);
   this.modalMessage = this.errorMessage

}

and this is the SignupService addUser method :

addUser (user : Customer){
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.url,user,options)
  .map(this.extractResponseData)
  .do(data => console.log('Add user : ' + JSON.stringify(data)))
  .catch(this.handleError);

private handleError(error: Response) {
return Observable.throw(error.json().error || 'Server error');}

 private extractResponseData(response: Response){
let body = response.json();
console.log(body.data);
return body.data || {};

}

and finally this is my spec that handle the error:

   it('should save the user submetted',() => {
   component.save();
   let signup = component.signUpForm;
   signup.get('firstName').setValue('BEN');
   signup.get('secondName').setValue('wis');
   signup.get('username').setValue('wiss013');
   signup.get('email').setValue('xz@gmail.com');
   signup.get('passwordMatch').get('password').setValue('wis');
   signup.get('passwordMatch').get('confirmPassword').setValue('wis');
   let show = component.showModal;
   expect(show).toBeTruthy();
 });
});

Any one can help me please ?!


问:
How can I retrieve data from Meteor collection on the client side with React?
I'm trying to retrieve my server data of a collection with the code bellow, but it just return undefined.

import { Posts } from '../../../api/posts.js';

class FeedUnit extends Component {

  constructor(props) {
      super(props);

      this.state = {
          open: true,
          emojis: false,
          isOver: false,
          likes: this.setLike(),
      };
  }

    setLike(){
    let self = this;
    let like;

    let post = Posts.findOne({ external_id: this.props.data.id });
    console.log(Posts.findOne({}))
    return like;
  }
  ```
</div>
</div>
</p>

<p>I already search on the data base manually and there I had the correct return using the command:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>db.posts.findOne({external_id: '1402366059774445_1503319816345735'})</code>```

答:
```<code>Posts.findOne is async function you need either to get data from callback or by promise as below
 Posts.findOne({ external_id: this.props.data.id })
.then((posts)=>{
//do whatever you want
})
.catch(err=>console.log(err))
</code>```

Body:
I'm trying to retrieve my server data of a collection with the code bellow, but it just return undefined.

import { Posts } from '../../../api/posts.js';

class FeedUnit extends Component {

  constructor(props) {
      super(props);

      this.state = {
          open: true,
          emojis: false,
          isOver: false,
          likes: this.setLike(),
      };
  }

    setLike(){
    let self = this;
    let like;

    let post = Posts.findOne({ external_id: this.props.data.id });
    console.log(Posts.findOne({}))
    return like;
  }

I already search on the data base manually and there I had the correct return using the command:

db.posts.findOne({external_id: '1402366059774445_1503319816345735'})


问:
Boost loop performance when reshaping huge amount of data
This is an extended question from previous question here. I'm reshaping the data according to the code below. However when the data size get increased, in=rand(291081,1920);, the answer (preallocation) in the previous question can't handle it anymore, MATLAB even freezed the whole laptop. Thus as suggested by Teddy in the last question, I'm opening a new question to boost the performance of the loop.

Some quite similar but not alike question can be found here. From there, the answer given suggested to modify the loop to be column-wise. However, since my loop required to access row and column simultaneously, it seem the answer is not applicable in my case.

Is this loop can still be modified to improve its performance? Or can this loop be done without freezes the whole laptop? If possible, without getting involve with GPUs.

```<code>in=rand(291081,1920);
m=581;
[R,C]=size(in);
R_out=R/m;

out=zeros(m*C,R_out);
for k=1:m %from row 1 to nth row
    for i=1:C %reshape every column of nth row
        out(i+C*(k-1),:) = in(k:m:end,i)';
    end
end
</code>```

P/S: In previous question, when the data size getting bigger, the loop and arrayfun seem to not have large performance difference.

Thanks in advance!

答:
You could transpose you matrix and reshape it to only have R_outcolumns.

```<code>% Input
in=rand(291081,1920);
m=581;
[R,C]=size(in);
R_out=R/m;

% Reshape
out = reshape(in.', [], R_out);
</code>```

The most of the time needed for this operation is caused by the transposing of the in matrix. So to speed it upp further you could perhaps try to collect/feed the data so that it's already transposed and then just do the reshape.

Body:
This is an extended question from previous question here. I'm reshaping the data according to the code below. However when the data size get increased, in=rand(291081,1920);, the answer (preallocation) in the previous question can't handle it anymore, MATLAB even freezed the whole laptop. Thus as suggested by Teddy in the last question, I'm opening a new question to boost the performance of the loop.

Some quite similar but not alike question can be found here. From there, the answer given suggested to modify the loop to be column-wise. However, since my loop required to access row and column simultaneously, it seem the answer is not applicable in my case.

Is this loop can still be modified to improve its performance? Or can this loop be done without freezes the whole laptop? If possible, without getting involve with GPUs.

in=rand(291081,1920);
m=581;
[R,C]=size(in);
R_out=R/m;

out=zeros(m*C,R_out);
for k=1:m %from row 1 to nth row
    for i=1:C %reshape every column of nth row
        out(i+C*(k-1),:) = in(k:m:end,i)';
    end
end

P/S: In previous question, when the data size getting bigger, the loop and arrayfun seem to not have large performance difference.

Thanks in advance!

Body:
You could transpose you matrix and reshape it to only have R_outcolumns.

% Input
in=rand(291081,1920);
m=581;
[R,C]=size(in);
R_out=R/m;

% Reshape
out = reshape(in.', [], R_out);

The most of the time needed for this operation is caused by the transposing of the in matrix. So to speed it upp further you could perhaps try to collect/feed the data so that it's already transposed and then just do the reshape.


问:
angular 2 observable next
I'm trying to understand the use of observables,

everything is ok in the simple cases, but in one case I want to compress several images.

I'm using  ng2-img-tools

Method to compress an image. This reduces the quality of an image down
  until it fits a certain fileSize which is given as maxSizeInMB. Set
  ignoreAlpha to true if you want to ignore the alpha channel for png
  images and compress them nonetheless (not recommended - the alpha
  channel will be lost and the resulting image might differ from the
  original image). Returns an observable that for every file given,
  onNext receives either a File when everything went as planned or an
  error Object if something went wrong.

In my code, I'm doing the following :

```<code>compressImages(filesToUpload:File[]):Observable<any> {
    if (filesToUpload && filesToUpload.length > 0) {
      return this.ng2ImgToolsService.compress(filesToUpload,GlobalService.MAX_FILE_SIZE_MB).map(response =>  {
        console.log("response is");
        console.log(response)
        return response;
      });
    }
    return Observable.of("no_image").map(response =>  "no_image");

  }

this.imageService.compressImages(filesToUpload).flatMap(result => {
          console.log(result)
          return  this.http.post(...);
        }
      ).catch(UtilsService.handleError);
</code>```

the problem is result returns only 1 file, I know i should use result.next() somewhere but I have no idea how.

答:
The issue is that you need subscribe to the function, not perform another map. When you subscribe to an observable, you're implicitly receiving the value of onNext() as result

```<code>this.imageService.compressImages(filesToUpload).subscribe(
    result => {
        // this contains the value of onNext()
        console.log(result)
        return     this.imageService.compressImages(filesToUpload).subscribe(
    result => {
        // this contains the value of onNext()
        console.log(result)
        return  this.http.post(...);
    }, error => {
        // error
    } this.http.post(...);
    }, error => {
        // error
    }
</code>```

more info on subscribing

EDIT

if you'd like to collect all item in the stream and operate on them as one list, you can use toList() like so:

```<code>this.imageService.compressImages(filesToUpload).toList().subscribe(
    result => {
        // this contains all values from the stream
        console.log(result)
        return  this.http.post(...);
    }, error => {
        // error
    }
</code>```

Title: angular 2 observable next

Body:
I'm trying to understand the use of observables,

everything is ok in the simple cases, but in one case I want to compress several images.

I'm using  ng2-img-tools

Method to compress an image. This reduces the quality of an image down
  until it fits a certain fileSize which is given as maxSizeInMB. Set
  ignoreAlpha to true if you want to ignore the alpha channel for png
  images and compress them nonetheless (not recommended - the alpha
  channel will be lost and the resulting image might differ from the
  original image). Returns an observable that for every file given,
  onNext receives either a File when everything went as planned or an
  error Object if something went wrong.

In my code, I'm doing the following :

compressImages(filesToUpload:File[]):Observable<any> {
    if (filesToUpload && filesToUpload.length > 0) {
      return this.ng2ImgToolsService.compress(filesToUpload,GlobalService.MAX_FILE_SIZE_MB).map(response =>  {
        console.log("response is");
        console.log(response)
        return response;
      });
    }
    return Observable.of("no_image").map(response =>  "no_image");

  }

this.imageService.compressImages(filesToUpload).flatMap(result => {
          console.log(result)
          return  this.http.post(...);
        }
      ).catch(UtilsService.handleError);

the problem is result returns only 1 file, I know i should use result.next() somewhere but I have no idea how.

Body:
The issue is that you need subscribe to the function, not perform another map. When you subscribe to an observable, you're implicitly receiving the value of onNext() as result

this.imageService.compressImages(filesToUpload).subscribe(
    result => {
        // this contains the value of onNext()
        console.log(result)
        return     this.imageService.compressImages(filesToUpload).subscribe(
    result => {
        // this contains the value of onNext()
        console.log(result)
        return  this.http.post(...);
    }, error => {
        // error
    } this.http.post(...);
    }, error => {
        // error
    }

more info on subscribing

EDIT

if you'd like to collect all item in the stream and operate on them as one list, you can use toList() like so:

this.imageService.compressImages(filesToUpload).toList().subscribe(
    result => {
        // this contains all values from the stream
        console.log(result)
        return  this.http.post(...);
    }, error => {
        // error
    }


问:
JBPM stable version for production use?
I am working on building a workflow application and I'm planning to use JBPM as my BPM framework. Can anyone suggest me which is the stable version to use in producation environment?</p>

答: You can try with enterprise release of jBPM which is Red Hat JBoss BPMS. Red Hat will provide hot-fix patches to known issues. Also rollup patches are provided on certain interval, which includes fix for multiple issues. Along with all this you will get 24x7 support for issue. </p>

Title: JBPM stable version for production use?


问:
How to map AspNetUser table id as foreign key to another table
```<code>public class UserInfo
{
  public int id {get;set;} //Primary key

  public string UserId {get; set;} // Foreign key to AspNetUser - Id

  public string FirstName {get;set;}
  public string LastName {get;set;}
  ......
  ......
}
</code>```

How can I extend the AspNetUser table in the above fashion in EF6 code first approach?

答:
Perhaps, the ForeignKey attribute this will help you:

```<code>public string UserId {get; set;}

[ForeignKey("UserId")]
public AspNetUser User {get; set;}
</code>```

Body:
public class UserInfo
{
  public int id {get;set;} //Primary key

  public string UserId {get; set;} // Foreign key to AspNetUser - Id

  public string FirstName {get;set;}
  public string LastName {get;set;}
  ......
  ......
}

How can I extend the AspNetUser table in the above fashion in EF6 code first approach?

Body:
Perhaps, the ForeignKey attribute this will help you:

public string UserId {get; set;}

[ForeignKey("UserId")]
public AspNetUser User {get; set;}


问:
.htaccess error while forecefully accessing subdomains
I am using the current code for example.com

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]
</code>```

Which makes you add forefully https://www OR https:// if you have already put www.

The problem with this code is that even if i call subdomains like ex.example.com

it adds https://www.ex.example.com

what i want is for subdomain to redirect like this => https://ex.example.com

Please can anyone provide me a valid code ?

答:
Hope this will work fine.</p>

```<code>RewriteEngine On

#for normal domains like example.com or example.in to redirect to https://www.example.com
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^([^\.]+)\.(com|in)$ [NC]
RewriteRule ^ https://www.%1.%2%{REQUEST_URI} [R=301,L,NE]

#for subdomain like test.example.com to redirect to https://test.example.com
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^([\.\w\-]*)\.(com|in)$ [NC]
RewriteRule ^ https://%1.%2%{REQUEST_URI} [R=301,L,NE]
</code>```

Body:
I am using the current code for example.com

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Which makes you add forefully https://www OR https:// if you have already put www.

The problem with this code is that even if i call subdomains like ex.example.com

it adds https://www.ex.example.com

what i want is for subdomain to redirect like this => https://ex.example.com

Please can anyone provide me a valid code ?

Body:
Hope this will work fine.

RewriteEngine On

#for normal domains like example.com or example.in to redirect to https://www.example.com
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^([^\.]+)\.(com|in)$ [NC]
RewriteRule ^ https://www.%1.%2%{REQUEST_URI} [R=301,L,NE]

#for subdomain like test.example.com to redirect to https://test.example.com
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^([\.\w\-]*)\.(com|in)$ [NC]
RewriteRule ^ https://%1.%2%{REQUEST_URI} [R=301,L,NE]


问:
Open folder by using intent
i want to open a specific folder by using intent, now its working only when es file manager is available ,i want to open the folder even es file manager is not there, it should work with the inbuilt file manager, what the changes i have to make with my code, any help will be appreciated

here is my code

```<code>   Button button=(Button)rootview.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/AudioRecords/");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(selectedUri, "resource/folder");

            if (intent.resolveActivityInfo(getActivity().getPackageManager(), 0) != null)
            {
                startActivity(intent);
            }
            else
            {
                // if you reach this place, it means there is no any file
                // explorer app installed on your device
            }

        }
    });
</code>```

答:
Open folder by using intent, i want to open the folder even  file manager is not there

You can't do it in Android API version below 19 (KITKAT) without installed file manager.

```<code>  public void openFolder()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
    + "/myFolder/");
intent.setDataAndType(uri, "text/csv");
startActivity(Intent.createChooser(intent, "Open folder"));
}
</code>```

Title: Open folder by using intent

Body:
i want to open a specific folder by using intent, now its working only when es file manager is available ,i want to open the folder even es file manager is not there, it should work with the inbuilt file manager, what the changes i have to make with my code, any help will be appreciated

here is my code

   Button button=(Button)rootview.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/AudioRecords/");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(selectedUri, "resource/folder");

            if (intent.resolveActivityInfo(getActivity().getPackageManager(), 0) != null)
            {
                startActivity(intent);
            }
            else
            {
                // if you reach this place, it means there is no any file
                // explorer app installed on your device
            }

        }
    });

Body:
Open folder by using intent, i want to open the folder even  file manager is not there

You can't do it in Android API version below 19 (KITKAT) without installed file manager.

  public void openFolder()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
    + "/myFolder/");
intent.setDataAndType(uri, "text/csv");
startActivity(Intent.createChooser(intent, "Open folder"));
}