问:
Retrieve Multiple Documents by Specifying a Compound Key for Each
I have a collection of documents that has a compound key of  {_id:{id:x, version:x}}:

```<code>{'_id':{'id':1, 'version':1}}
{'_id':{'id':1, 'version':2}}
{'_id':{'id':1, 'version':3}}
{'_id':{'id':2, 'version':1}}
{'_id':{'id':3, 'version':1}}
{'_id':{'id':4, 'version':1}}
{'_id':{'id':4, 'version':2}}
{'_id':{'id':4, 'version':3}}
{'_id':{'id':5, 'version':1}}
</code>```

I want to write a query that retrieves multiple documents, in sql I would do something like

```<code>WHERE (id,version) IN (1,1),(1,2),(3,1),(4,1)
</code>```

How can I do this in mongo?

答:
You would actually use an $or expression.

It depends on how your source data is stored. So for an array of "objects"

```<code>var params = [{ id: 1, version: 1 },{ id: 2, version: 1 },{ id: 3, version: 2 }];

db.collection.find({
  "$or": map.params( p =>
    Object.keys(p).map( k => ({ [`_id.${k}`]: p[k] }) )
      .reduce((acc,curr) => Object.assign(acc,curr), {})
  )
})
</code>```

Or if you list have an "array of arrays" like in your SQL:

```<code>var params = [[1,1],[2,1],[3,2]];

db.collection.find({
  "$or": params.map(([id,version]) => ({ '_id.id': id, '_id.version': version }) )
})
</code>```

Which should give you a bit more perspective on the sort of transformation happening here.

Basically it's about the $or and the "dot notation" to denote the compound keys. But I'm showing you a little transform here because with MongoDB you're typically working with "data structures", so you want to manipulate those instead of writing out a statement like SQL does.

Without the "mapping" that basically looks like:

```<code>db.collection.find({
  "$or": [
    { "_id.id": 1, "_id.version": 1 },
    { "_id.id": 2, "_id.version": 1 },
    { "_id.id": 3, "_id.version": 2 }
  ]
})
</code>```

Which means that "any" of those listed conditions are going to possibly match a document ( or more than one ) and return them.

So the example is just the JavaScript way since that's what the provided "shell" allows. But you can essentially adapt the approach to your language of choice.

Of course you set this up in your MongoDB shell first with:

```<code>db.collection.insertMany([
  {'_id':{'id':1, 'version':1}},
  {'_id':{'id':1, 'version':2}},
  {'_id':{'id':1, 'version':3}},
  {'_id':{'id':2, 'version':1}},
  {'_id':{'id':3, 'version':1}},
  {'_id':{'id':4, 'version':1}},
  {'_id':{'id':4, 'version':2}},
  {'_id':{'id':4, 'version':3}},
  {'_id':{'id':5, 'version':1}}
])
</code>```

Body:
I have a collection of documents that has a compound key of  {_id:{id:x, version:x}}:

{'_id':{'id':1, 'version':1}}
{'_id':{'id':1, 'version':2}}
{'_id':{'id':1, 'version':3}}
{'_id':{'id':2, 'version':1}}
{'_id':{'id':3, 'version':1}}
{'_id':{'id':4, 'version':1}}
{'_id':{'id':4, 'version':2}}
{'_id':{'id':4, 'version':3}}
{'_id':{'id':5, 'version':1}}

I want to write a query that retrieves multiple documents, in sql I would do something like

WHERE (id,version) IN (1,1),(1,2),(3,1),(4,1)

How can I do this in mongo?

Body:
You would actually use an $or expression.

It depends on how your source data is stored. So for an array of "objects"

var params = [{ id: 1, version: 1 },{ id: 2, version: 1 },{ id: 3, version: 2 }];

db.collection.find({
  "$or": map.params( p =>
    Object.keys(p).map( k => ({ [`_id.${k}`]: p[k] }) )
      .reduce((acc,curr) => Object.assign(acc,curr), {})
  )
})

Or if you list have an "array of arrays" like in your SQL:

var params = [[1,1],[2,1],[3,2]];

db.collection.find({
  "$or": params.map(([id,version]) => ({ '_id.id': id, '_id.version': version }) )
})

Which should give you a bit more perspective on the sort of transformation happening here.

Basically it's about the $or and the "dot notation" to denote the compound keys. But I'm showing you a little transform here because with MongoDB you're typically working with "data structures", so you want to manipulate those instead of writing out a statement like SQL does.

Without the "mapping" that basically looks like:

db.collection.find({
  "$or": [
    { "_id.id": 1, "_id.version": 1 },
    { "_id.id": 2, "_id.version": 1 },
    { "_id.id": 3, "_id.version": 2 }
  ]
})

Which means that "any" of those listed conditions are going to possibly match a document ( or more than one ) and return them.

So the example is just the JavaScript way since that's what the provided "shell" allows. But you can essentially adapt the approach to your language of choice.

Of course you set this up in your MongoDB shell first with:

db.collection.insertMany([
  {'_id':{'id':1, 'version':1}},
  {'_id':{'id':1, 'version':2}},
  {'_id':{'id':1, 'version':3}},
  {'_id':{'id':2, 'version':1}},
  {'_id':{'id':3, 'version':1}},
  {'_id':{'id':4, 'version':1}},
  {'_id':{'id':4, 'version':2}},
  {'_id':{'id':4, 'version':3}},
  {'_id':{'id':5, 'version':1}}
])


来源: stackexchange

问:
Import iCal (ics) with fullcalendar?
What would need to be done in order to load .ics files with fullcalendar?
I cannot use php or .net unfortunately.</p>

答:
I manage to do it. Not as hard as I thought. I use ical.js as ics parser. After parsing, I get a json object which contains all the information in the ics. And then traverse it and construct event object according to the definition of FullCalendar Event object.

Update with FullCalendar v4 and reccuring events

As v4 changed the initialization code and the code bellow didn't count with recurring events, here's one that does and works with the v4 version:

```<code>$.get(calendarUrl).then(function (data) {
     // parse the ics data
     var jcalData = ICAL.parse(data.trim());
     var comp = new ICAL.Component(jcalData);
     var eventComps = comp.getAllSubcomponents("vevent");
     // map them to FullCalendar events
     var events = $.map(eventComps, function (item) {

        if (item.getFirstPropertyValue("class") == "PRIVATE") {
            return null;
        }
        else {
            var toreturn = {
                "title": item.getFirstPropertyValue("summary"),
                "location": item.getFirstPropertyValue("location"),
            };
            var rrule=item.getFirstPropertyValue("rrule");
            if(rrule!= null){ //event recurs
                toreturn.rrule={};
                if(rrule.freq) toreturn.rrule.freq=rrule.freq;
                if(rrule.parts.BYDAY) toreturn.rrule.byweekday=rrule.parts.BYDAY;
                if(rrule.until) toreturn.rrule.until=rrule.until.toString();
                if(rrule.until) toreturn.rrule.until=rrule.until.toString();
                if(rrule.interval) toreturn.rrule.interval=rrule.interval;
                var dtstart=item.getFirstPropertyValue("dtstart").toString();
                var dtend=item.getFirstPropertyValue("dtend").toString();
                toreturn.rrule.dtstart=dtstart;
                //count duration ms
                var startdate=new Date(dtstart);
                var enddate=new Date(dtend);
                toreturn.duration = enddate - startdate;
            }else{
                toreturn.start=item.getFirstPropertyValue("dtstart").toString();
                toreturn.end=item.getFirstPropertyValue("dtend").toString();
            }
            return toreturn;
        }
     });
     var calendarEl = document.getElementById('calendar');
     var calendar = new FullCalendar.Calendar(calendarEl, {

              plugins: [ 'interaction','dayGrid','rrule' ],
              defaultView: 'dayGridWeek',
              displayEventEnd: true,
              header: {
                  left: 'prev,next',
                  center: 'title',
                  right: 'dayGridDay,dayGridWeek,dayGridMonth'
              },
              events: events,
              eventRender: function (info) {
                // console.log(info.event);
                // append location
                if (info.event.extendedProps.location != null && info.event.extendedProps.location != "") {
                    info.el.append(info.event.extendedProps.location );
                }
              }
     });
     calendar.render();
});
</code>```

Original answer's code (v3 and lower):

```<code>$.get(calendarUrl).then(function (data) {
// parse the ics data
var jcalData = ICAL.parse(data.trim());
var comp = new ICAL.Component(jcalData);
var eventComps = comp.getAllSubcomponents("vevent");
// console.log(JSON.stringify(eventComps));
// map them to FullCalendar events
var events = $.map(eventComps, function (item) {
    if (item.getFirstPropertyValue("class") == "PRIVATE") {
        return null;
    }
    else {
        return {
            "title": item.getFirstPropertyValue("summary") + ";",
            "start": item.getFirstPropertyValue("dtstart").toJSDate(),
            "end": item.getFirstPropertyValue("dtend").toJSDate(),
            "location": item.getFirstPropertyValue("location")
        };
    }
});

// refresh the control
calendarCtrl.fullCalendar('destroy');
calendarCtrl.fullCalendar({
    events: events,
    timeFormat: "H:mm",
    displayEventEnd: true,
    eventRender: function (event, element) {
        // console.log(element);
        // append location
        if (event.location != null && event.location != "") {
            element.append("<span>" + event.location + "</span>");
        }
    },
    header: {
        left: 'title',
        center: '',
        right: 'today,month,basicWeek,listDay prev,next'
    }
});
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Import iCal (ics) with fullcalendar?

Body:
I manage to do it. Not as hard as I thought. I use ical.js as ics parser. After parsing, I get a json object which contains all the information in the ics. And then traverse it and construct event object according to the definition of FullCalendar Event object.

Update with FullCalendar v4 and reccuring events

As v4 changed the initialization code and the code bellow didn't count with recurring events, here's one that does and works with the v4 version:

$.get(calendarUrl).then(function (data) {
     // parse the ics data
     var jcalData = ICAL.parse(data.trim());
     var comp = new ICAL.Component(jcalData);
     var eventComps = comp.getAllSubcomponents("vevent");
     // map them to FullCalendar events
     var events = $.map(eventComps, function (item) {

        if (item.getFirstPropertyValue("class") == "PRIVATE") {
            return null;
        }
        else {
            var toreturn = {
                "title": item.getFirstPropertyValue("summary"),
                "location": item.getFirstPropertyValue("location"),
            };
            var rrule=item.getFirstPropertyValue("rrule");
            if(rrule!= null){ //event recurs
                toreturn.rrule={};
                if(rrule.freq) toreturn.rrule.freq=rrule.freq;
                if(rrule.parts.BYDAY) toreturn.rrule.byweekday=rrule.parts.BYDAY;
                if(rrule.until) toreturn.rrule.until=rrule.until.toString();
                if(rrule.until) toreturn.rrule.until=rrule.until.toString();
                if(rrule.interval) toreturn.rrule.interval=rrule.interval;
                var dtstart=item.getFirstPropertyValue("dtstart").toString();
                var dtend=item.getFirstPropertyValue("dtend").toString();
                toreturn.rrule.dtstart=dtstart;
                //count duration ms
                var startdate=new Date(dtstart);
                var enddate=new Date(dtend);
                toreturn.duration = enddate - startdate;
            }else{
                toreturn.start=item.getFirstPropertyValue("dtstart").toString();
                toreturn.end=item.getFirstPropertyValue("dtend").toString();
            }
            return toreturn;
        }
     });
     var calendarEl = document.getElementById('calendar');
     var calendar = new FullCalendar.Calendar(calendarEl, {

              plugins: [ 'interaction','dayGrid','rrule' ],
              defaultView: 'dayGridWeek',
              displayEventEnd: true,
              header: {
                  left: 'prev,next',
                  center: 'title',
                  right: 'dayGridDay,dayGridWeek,dayGridMonth'
              },
              events: events,
              eventRender: function (info) {
                // console.log(info.event);
                // append location
                if (info.event.extendedProps.location != null && info.event.extendedProps.location != "") {
                    info.el.append(info.event.extendedProps.location );
                }
              }
     });
     calendar.render();
});

Original answer's code (v3 and lower):

$.get(calendarUrl).then(function (data) {
// parse the ics data
var jcalData = ICAL.parse(data.trim());
var comp = new ICAL.Component(jcalData);
var eventComps = comp.getAllSubcomponents("vevent");
// console.log(JSON.stringify(eventComps));
// map them to FullCalendar events
var events = $.map(eventComps, function (item) {
    if (item.getFirstPropertyValue("class") == "PRIVATE") {
        return null;
    }
    else {
        return {
            "title": item.getFirstPropertyValue("summary") + ";",
            "start": item.getFirstPropertyValue("dtstart").toJSDate(),
            "end": item.getFirstPropertyValue("dtend").toJSDate(),
            "location": item.getFirstPropertyValue("location")
        };
    }
});

// refresh the control
calendarCtrl.fullCalendar('destroy');
calendarCtrl.fullCalendar({
    events: events,
    timeFormat: "H:mm",
    displayEventEnd: true,
    eventRender: function (event, element) {
        // console.log(element);
        // append location
        if (event.location != null && event.location != "") {
            element.append("<span>" + event.location + "</span>");
        }
    },
    header: {
        left: 'title',
        center: '',
        right: 'today,month,basicWeek,listDay prev,next'
    }
});
});

ContentLicense: CC BY-SA 4.0


问:
Create a method called filter that has two string parameters and returns a string
The method will filter out all occurrences of the second string from the first sting. The filter is case sensitive. Do not filter out cat if the second argument is CAT.

```<code>public static void main(String[] args){        // should filter out the
  System.out.println("method: filter");       // second string
  System.out.println(filter( "CS221 is terrible", "terrible"));
  System.out.println(filter( "my cat is a nice cat", "cat"));
  System.out.println(filter( "ababababa","ab"));
  System.out.println(filter( "not here", "a"));
  System.out.println(filter( "abababab","ab"));
  System.out.println(filter( "CATcatCAT","CAT"));
  System.out.println(filter( "dark","k"));
  System.out.println(filter("ususerer", "user"));
}
public static String filter ( String str, String filter){
  String temp = "";
  int i = 0;

  while(i < str.length() && str.indexOf(filter,i) != -1){
     if(str.indexOf(filter,i)!=-1){
         temp+=str.substring(i, str.indexOf(filter,i));
     }else{
         temp+=str.substring(i,str.length());
     }
     i = str.indexOf(filter, i)+ filter.length();
     i++;
  }
  return temp;

}
</code>```

Output of the code

```<code> CS221 is
 my is a nice
 b

 b
 at
 dar
 us
</code>```

Expected output

```<code> CS221 is
 my is a nice
 a
 not here
 nothing prints at all on this line its just blank
 cat
 dar
 user
</code>```

答:
Why can't you use replaceAll

```<code>public static String filter(String str, String filter) {
    return str.replaceAll(filter, "").replaceAll("\\s{2,}", " ");
}
</code>```

Body:
The method will filter out all occurrences of the second string from the first sting. The filter is case sensitive. Do not filter out cat if the second argument is CAT.

public static void main(String[] args){        // should filter out the
  System.out.println("method: filter");       // second string
  System.out.println(filter( "CS221 is terrible", "terrible"));
  System.out.println(filter( "my cat is a nice cat", "cat"));
  System.out.println(filter( "ababababa","ab"));
  System.out.println(filter( "not here", "a"));
  System.out.println(filter( "abababab","ab"));
  System.out.println(filter( "CATcatCAT","CAT"));
  System.out.println(filter( "dark","k"));
  System.out.println(filter("ususerer", "user"));
}
public static String filter ( String str, String filter){
  String temp = "";
  int i = 0;

  while(i < str.length() && str.indexOf(filter,i) != -1){
     if(str.indexOf(filter,i)!=-1){
         temp+=str.substring(i, str.indexOf(filter,i));
     }else{
         temp+=str.substring(i,str.length());
     }
     i = str.indexOf(filter, i)+ filter.length();
     i++;
  }
  return temp;

}

Output of the code

 CS221 is
 my is a nice
 b

 b
 at
 dar
 us

Expected output

 CS221 is
 my is a nice
 a
 not here
 nothing prints at all on this line its just blank
 cat
 dar
 user

Body:
Why can't you use replaceAll

public static String filter(String str, String filter) {
    return str.replaceAll(filter, "").replaceAll("\\s{2,}", " ");
}


问:
Fetch comma separated values from mysql database particularly
I have database where i have a column where multiple ids are saved in comma separated way. That ids are defined some other table . I am fetching the but i am getting result where there is single value (no comma)

i need all all the ids value fetched there definition from another table and show.

Is it possible in mysql query ?

答:
Get first all id's,by column, and then explode it by comma,

```<code>$explode = explode(',',$array->column);
</code>```

then using foreach pass the value to another table to get the row,

```<code> foreach($explode as $single){
  // pass single id to query using where condition you can get row of that id.
 }
</code>```

or you can also use subquery, do google am sure stack overflow gives better result.

Body:
Get first all id's,by column, and then explode it by comma,

$explode = explode(',',$array->column);

then using foreach pass the value to another table to get the row,

 foreach($explode as $single){
  // pass single id to query using where condition you can get row of that id.
 }

or you can also use subquery, do google am sure stack overflow gives better result.


问:
JS iterate over an object and remove the enabled false
I have a dynamic object with the following structure:

```<code>{
 a: {
  someKey: {
    propOne: '',
    enabled: true
  }
 },
 b: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
c: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
   someKey: {
      ab: {
        propOne: '',
        enabled: true
      }
     }
    }
</code>```

I need to remove the tree with the enabled false. So in the above example the result should be:

```<code> const result = {
     a: {
      someKey: {
        propOne: '',
        enabled: true
      }
     },

   d: {
      someKey: {
        propOne: '',
        enabled: true
      }
     }
    }
</code>```

How can I do this?

答:
You could use a recursive check for a property enabled with the value false and delete this branch from the object.

function deleteKey(object) {
    Object
        .keys(object)
        .forEach(function (key) {
            if (object[key].enabled === false) {
                delete object[key];
                return;
            }
            if (object[key] && typeof object[key] === 'object') {
                deleteKey(object[key]);
                if (!Object.keys(object[key]).length) {
                    delete object[key];
                }
            }
        });
}

var object = { name: "WHITE_THEME", source: "WHITE_THEME", page: { layout: { grid: "TILES", margin: { enabled: true, left: 15, top: 15, right: 15, bottom: 15 } }, background: { filter: { enabled: false, blur: { enabled: false, value: null, unit: "px" }, brightness: { enabled: false, value: 100, unit: "%" }, contrast: { enabled: false, value: 0, unit: "%" }, grayscale: { enabled: false, value: 0, unit: "%" }, invert: { enabled: false, value: 0, unit: "%" }, opacity: { enabled: false, value: 100, unit: "%" }, saturate: { enabled: false, value: 100, unit: "%" } }, color: { enabled: false, value: "rgba(232, 232, 232, 1)" } } } };

deleteKey(object);

console.log(object);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a dynamic object with the following structure:

{
 a: {
  someKey: {
    propOne: '',
    enabled: true
  }
 },
 b: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
c: {
  someKey: {
    propOne: '',
    enabled: false
  }
 },
   someKey: {
      ab: {
        propOne: '',
        enabled: true
      }
     }
    }

I need to remove the tree with the enabled false. So in the above example the result should be:

 const result = {
     a: {
      someKey: {
        propOne: '',
        enabled: true
      }
     },

   d: {
      someKey: {
        propOne: '',
        enabled: true
      }
     }
    }

How can I do this?

Body:
You could use a recursive check for a property enabled with the value false and delete this branch from the object.

function deleteKey(object) {
    Object
        .keys(object)
        .forEach(function (key) {
            if (object[key].enabled === false) {
                delete object[key];
                return;
            }
            if (object[key] && typeof object[key] === 'object') {
                deleteKey(object[key]);
                if (!Object.keys(object[key]).length) {
                    delete object[key];
                }
            }
        });
}

var object = { name: "WHITE_THEME", source: "WHITE_THEME", page: { layout: { grid: "TILES", margin: { enabled: true, left: 15, top: 15, right: 15, bottom: 15 } }, background: { filter: { enabled: false, blur: { enabled: false, value: null, unit: "px" }, brightness: { enabled: false, value: 100, unit: "%" }, contrast: { enabled: false, value: 0, unit: "%" }, grayscale: { enabled: false, value: 0, unit: "%" }, invert: { enabled: false, value: 0, unit: "%" }, opacity: { enabled: false, value: 100, unit: "%" }, saturate: { enabled: false, value: 100, unit: "%" } }, color: { enabled: false, value: "rgba(232, 232, 232, 1)" } } } };

deleteKey(object);

console.log(object);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Print the values in an array using batch
The following code lists all the folders in a directory sorted by date and prints the latest folder in %a%

```<code>FOR /F "delims=" %%i IN ('dir "directory" /b /ad-h /t:c /od') DO SET a=%%i
echo Most recent subfolder: %a%
</code>```

How do i print the second recent one? I tried using %a[1]% but it did not work.

答:
```<code>set "a="
FOR /F "delims=" %%i IN ('dir "directory" /b /ad-h /t:c /o-d') DO if not defined a SET "a=%%i"
</code>```

sets the latest

```<code>set "a="
FOR /F "skip=1delims=" %%i IN ('dir "directory" /b /ad-h /t:c /o-d') DO if not defined a SET "a=%%i"
</code>```

sets the second-latest

sadly, skip=0 is not implemented.

Please use meaningful variable-names.

Body:
The following code lists all the folders in a directory sorted by date and prints the latest folder in %a%

FOR /F "delims=" %%i IN ('dir "directory" /b /ad-h /t:c /od') DO SET a=%%i
echo Most recent subfolder: %a%

How do i print the second recent one? I tried using %a[1]% but it did not work.

Body:
set "a="
FOR /F "delims=" %%i IN ('dir "directory" /b /ad-h /t:c /o-d') DO if not defined a SET "a=%%i"

sets the latest

set "a="
FOR /F "skip=1delims=" %%i IN ('dir "directory" /b /ad-h /t:c /o-d') DO if not defined a SET "a=%%i"

sets the second-latest

sadly, skip=0 is not implemented.

Please use meaningful variable-names.


问:
jQuery: resetting .animated divs position
I am using the following code to expand and center on div on :hover

```<code>    $(document).ready(function(){

    //animation on hover

        $('#sliding_grid li').hover(function() {
          $(this).addClass('highlight');
        }, function() {
          //$(this).removeClass('highlight');
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":"0px", "left":"0px", "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });
</code>```

My problem is two things:

1) I'm not sure how to reset the "top" and "left" css coordinates to their original value on mouseOut.  To see a working demo, go here:

http://jsfiddle.net/kTFvj/1/

2) The z-index (see here: http://jsfiddle.net/kTFvj/1/) is not affecting the :hovered grid elements.  Not sure why.

答:
What about using % instead of pixels?

Another solution is saving the actual value of width and height in some vars and restoring on mouse out.

ContentLicense: CC BY-SA 2.5

Body:
I am using the following code to expand and center on div on :hover

    $(document).ready(function(){

    //animation on hover

        $('#sliding_grid li').hover(function() {
          $(this).addClass('highlight');
        }, function() {
          //$(this).removeClass('highlight');
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":"0px", "left":"0px", "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });

My problem is two things:

1) I'm not sure how to reset the "top" and "left" css coordinates to their original value on mouseOut.  To see a working demo, go here:

http://jsfiddle.net/kTFvj/1/

2) The z-index (see here: http://jsfiddle.net/kTFvj/1/) is not affecting the :hovered grid elements.  Not sure why.


问:
problem with width:50% when border != none (CSS)
problem with width:50% when border != none

take a look
http://jsfiddle.net/5nYSf/

result should be like this

答:
There is a easy way:
add { box-sizing: border-box; } in .attachments
and the 50% width will contain the border too</p>


问:
How to return an object from a method that contains a DataTask
I am new on swift and trying to do something like that :

I have struct named Api Response :

```<code>struct ApiResponse {
    var IsSuccess : Bool = false
    var Message : String?
    var ReturnedData : Data?
}
</code>```

and have a func in another class named CommonHandler, that makes api call

```<code>public class CommonHandler {

    public func CallApi(_ apiUrl : String , _ parameters : [String : Any] ) -> ApiResponse
    {
        var apiResponse = ApiResponse()

        let url = URL(string: apiUrl)!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

        let task = URLSession.shared.dataTask(with: request , completionHandler : { data, response, error in
            if let error = error {
                // handle the transport error
                return
            }
            guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
                // handle the server error
                return
            }
            apiResponse.ReturnedData = data
            apiResponse.IsSuccess = true
            apiResponse.Message = "Succeed"

        })
        task.resume()

        return apiResponse
    }
}
</code>```

I want to call this function in UIViewController like that :

```<code>var handler = CommonHandler()
let param :[String : String] = ["param":"param"]
let url = "url"

let response = handler.CallApi(url, param)
print(response.IsSuccess)
print(response.Message!)
</code>```

I am aware that i can not use dataTask method like this. It's async.
But how can i do api call in a non-void func and return its response data ?
I parse ReturnedData json to struct then.
What is the best approach in this case ?
Thanks

答:
Use an asynchronous completion handler

```<code>public func callApi(with url : String , parameters : [String : Any], completion: @escaping (ApiResponse?) -> () )
{
    var apiResponse = ApiResponse()

    let url = URL(string: apiUrl)!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

    let task = URLSession.shared.dataTask(with: request , completionHandler : { data, response, error in
        if let error = error {
            // handle the transport error
            completion(nil)
            return
        }
        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            // handle the server error
            completion(nil)
            return
        }
        apiResponse.ReturnedData = data
        apiResponse.IsSuccess = true
        apiResponse.Message = "Succeed"
        completion(apiResponse)

    })
    task.resume()
}
</code>```

and call it:

```<code>var handler = CommonHandler()
let param = ["param":"param"]
let url = "url"

handler.callApi(with: url, parameters: param) { response in
    if let response = response {
       print(response.IsSuccess)
       print(response.Message!)
    }
}
</code>```

Note:

Please conform to the naming convention that variable and function names start with lowercase letter and use parameter labels for better readability.

Body:
I am new on swift and trying to do something like that :

I have struct named Api Response :

struct ApiResponse {
    var IsSuccess : Bool = false
    var Message : String?
    var ReturnedData : Data?
}

and have a func in another class named CommonHandler, that makes api call

public class CommonHandler {

    public func CallApi(_ apiUrl : String , _ parameters : [String : Any] ) -> ApiResponse
    {
        var apiResponse = ApiResponse()

        let url = URL(string: apiUrl)!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

        let task = URLSession.shared.dataTask(with: request , completionHandler : { data, response, error in
            if let error = error {
                // handle the transport error
                return
            }
            guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
                // handle the server error
                return
            }
            apiResponse.ReturnedData = data
            apiResponse.IsSuccess = true
            apiResponse.Message = "Succeed"

        })
        task.resume()

        return apiResponse
    }
}

I want to call this function in UIViewController like that :

var handler = CommonHandler()
let param :[String : String] = ["param":"param"]
let url = "url"

let response = handler.CallApi(url, param)
print(response.IsSuccess)
print(response.Message!)

I am aware that i can not use dataTask method like this. It's async.
But how can i do api call in a non-void func and return its response data ?
I parse ReturnedData json to struct then.
What is the best approach in this case ?
Thanks

Body:
Use an asynchronous completion handler

public func callApi(with url : String , parameters : [String : Any], completion: @escaping (ApiResponse?) -> () )
{
    var apiResponse = ApiResponse()

    let url = URL(string: apiUrl)!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

    let task = URLSession.shared.dataTask(with: request , completionHandler : { data, response, error in
        if let error = error {
            // handle the transport error
            completion(nil)
            return
        }
        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            // handle the server error
            completion(nil)
            return
        }
        apiResponse.ReturnedData = data
        apiResponse.IsSuccess = true
        apiResponse.Message = "Succeed"
        completion(apiResponse)

    })
    task.resume()
}

and call it:

var handler = CommonHandler()
let param = ["param":"param"]
let url = "url"

handler.callApi(with: url, parameters: param) { response in
    if let response = response {
       print(response.IsSuccess)
       print(response.Message!)
    }
}

Note:

Please conform to the naming convention that variable and function names start with lowercase letter and use parameter labels for better readability.


答:
I sorted this out using php

```<code>$sequence = "1,2,1,2,3,2,4,2,3,3";
$seq_arr = explode(',', $sequence);
</code>```

Step 1:

Created array to store all details

```<code>$questions = array(); // to store all questions
$final_questions = array(); // tos store final questions in the sequence needed
$level_1 = array(); // level 1 questions
$level_2 = array(); // level 2 questions
$level_3 = array(); // level 3 questions
$level_4 = array(); // level 4 questions
$level_5 = array(); // level 5 questions
</code>```

Step 2 :

Select all array from Db and store in each array according to question level

```<code>$this->db->select(*);
$this->db->from(questions);
$query = $this->db->get();
$result = $query->result_array();
for ($i=0; $i<count($result) ; $i++) {
 if(isset($result[$i]) && !empty($result[$i])){
  if($result[$i]['question_level'] == 1)
  {
    $level_1[] = $result[$i];
  }
  if($result[$i]['question_level'] == 2)
  {
    $level_2[] = $result[$i];
  }
  if($result[$i]['question_level'] == 3)
  {
    $level_3[] = $result[$i];
  }
  if($result[$i]['question_level'] == 4)
  {
    $level_4[] = $result[$i];
  }
  if($result[$i]['question_level'] == 5)
  {
    $level_5[] = $result[$i];
  }
 }
}
</code>```

Step 3 :

Match sequence with all array and store into final array.

```<code>foreach ($seq_arr as $key => $value) {
  if($value == 1)
    {
         for ($i=0; $i < count($difficulty_array) ; $i++)
          {
             if(isset($level_1[$i]) && !empty($level_1[$i])){
               if(!in_array($level_1[$i], $final_questions))
                 {
                    $final_questions[] = $level_1[$i];
                    break;
                 }
             }
          }
     }
   if($value == 2)
     {
         for ($i=0; $i < count($difficulty_array) ; $i++)
          {
             if(isset($level_2[$i]) && !empty($level_2[$i])){
               if(!in_array($level_2[$i], $final_questions))
                 {
                    $final_questions[] = $level_2[$i];
                    break;
                 }
              }
           }
      }
    if($value == 3)
      {
        for ($i=0; $i < count($difficulty_array) ; $i++)
         {
            if(isset($level_3[$i]) && !empty($level_3[$i])){
               if(!in_array($level_3[$i], $final_questions))
                 {
                    $final_questions[] = $level_3[$i];
                    break;
                 }
             }
          }
     }
     if($value == 4)
       {
          for ($i=0; $i < count($difficulty_array) ; $i++)
            {
              if(isset($level_4[$i]) && !empty($level_4[$i])){
                if(!in_array($level_4[$i], $final_questions))
                   {
                     $final_questions[] = $level_4[$i];
                     break;
                   }
              }
            }
       }
     if($value == 5)
       {
          for ($i=0; $i < count($difficulty_array) ; $i++)
             {
                if(isset($level_5[$i]) && !empty($level_5[$i])){
                   if(!in_array($level_5[$i], $final_questions))
                      {
                         $final_questions[] = $level_5[$i];
                         break;
                       }
                 }
             }
          }
      }
print_r($final_questions);
</code>```

Title: fetch record in order with IN clause - having duplicate values in IN clause

Body:
I have table questions as

id   | question    | question_level
______________________________________
1    | abc         | 1
______________________________________
2    | prs         | 3
______________________________________
3    | oesl        | 2
______________________________________
4    | ocsl        | 3
______________________________________
5    | qoindos     | 1
______________________________________
6    | xyz         | 3
______________________________________
7    | mnlop       | 2
______________________________________
8    | cllse       | 2
______________________________________
9    | teuosn      | 4
______________________________________
10   | ulcd        | 2
______________________________________

I want to select 10 records which will match with question level
I have order of level in which I want all records as below

1,2,1,2,3,2,4,2,3,3

Output should be

id   | question    | question_level
______________________________________
1    | abc         | 1
______________________________________
3    | oesl        | 2
______________________________________
5    | qoindos     | 1
______________________________________
7    | mnlop       | 2
______________________________________
2    | prs         | 3
______________________________________
8    | cllse       | 2
______________________________________
9    | teuosn      | 4
______________________________________
10   | ulcd        | 2
______________________________________
4    | ocsl        | 3
______________________________________
6    | xyz         | 3
______________________________________

I tried different solutions but couldn't get correct output
tried with field, find_in_set but no success.
Refered [Force MySQL to return duplicates from WHERE IN clause without using JOIN/UNION?
but getting only count and record in asceding order

I tried below solutions

SELECT question_level FROM `tbl_questions` WHERE `question_level` IN (1,2,1,2,3,2,4,2,3,3) ORDER BY FIELD(`question_level`, 1, 2, 1, 2, 3, 2, 4, 2, 3, 3) LIMIT 10

SELECT question_level FROM tbl_questions WHERE FIND_IN_SET(`question_level`,'1,2,1,2,3,2,4,2,3,3');

SELECT question_level,question_object_name,question_object_path,question_answer
        FROM tbl_questions e JOIN (SELECT 1 AS question_level UNION ALL
              SELECT 2 UNION ALL
              SELECT 1 UNION ALL
              SELECT 2 UNION ALL
              SELECT 3 UNION ALL
              SELECT 2 UNION ALL
              SELECT 4 UNION ALL
              SELECT 2 UNION ALL
              SELECT 3 UNION ALL
              SELECT 3
             ) matches
             USING (question_level) LIMIT 10;

I tried with foreach loop also but every time getting same record when question level matches with value

$array = explode(',', '1,2,1,2,3,2,4,2,3,3')
foreach ($array as $value) {
 SELECT question_level FROM tbl_questions
 WHERE question_level = $value;
}

If it is not possible in mysql then can it be achieve using php.

Thanks in advance

Body:
I sorted this out using php

$sequence = "1,2,1,2,3,2,4,2,3,3";
$seq_arr = explode(',', $sequence);

Step 1:

Created array to store all details

$questions = array(); // to store all questions
$final_questions = array(); // tos store final questions in the sequence needed
$level_1 = array(); // level 1 questions
$level_2 = array(); // level 2 questions
$level_3 = array(); // level 3 questions
$level_4 = array(); // level 4 questions
$level_5 = array(); // level 5 questions

Step 2 :

Select all array from Db and store in each array according to question level

$this->db->select(*);
$this->db->from(questions);
$query = $this->db->get();
$result = $query->result_array();
for ($i=0; $i<count($result) ; $i++) {
 if(isset($result[$i]) && !empty($result[$i])){
  if($result[$i]['question_level'] == 1)
  {
    $level_1[] = $result[$i];
  }
  if($result[$i]['question_level'] == 2)
  {
    $level_2[] = $result[$i];
  }
  if($result[$i]['question_level'] == 3)
  {
    $level_3[] = $result[$i];
  }
  if($result[$i]['question_level'] == 4)
  {
    $level_4[] = $result[$i];
  }
  if($result[$i]['question_level'] == 5)
  {
    $level_5[] = $result[$i];
  }
 }
}

Step 3 :

Match sequence with all array and store into final array.

foreach ($seq_arr as $key => $value) {
  if($value == 1)
    {
         for ($i=0; $i < count($difficulty_array) ; $i++)
          {
             if(isset($level_1[$i]) && !empty($level_1[$i])){
               if(!in_array($level_1[$i], $final_questions))
                 {
                    $final_questions[] = $level_1[$i];
                    break;
                 }
             }
          }
     }
   if($value == 2)
     {
         for ($i=0; $i < count($difficulty_array) ; $i++)
          {
             if(isset($level_2[$i]) && !empty($level_2[$i])){
               if(!in_array($level_2[$i], $final_questions))
                 {
                    $final_questions[] = $level_2[$i];
                    break;
                 }
              }
           }
      }
    if($value == 3)
      {
        for ($i=0; $i < count($difficulty_array) ; $i++)
         {
            if(isset($level_3[$i]) && !empty($level_3[$i])){
               if(!in_array($level_3[$i], $final_questions))
                 {
                    $final_questions[] = $level_3[$i];
                    break;
                 }
             }
          }
     }
     if($value == 4)
       {
          for ($i=0; $i < count($difficulty_array) ; $i++)
            {
              if(isset($level_4[$i]) && !empty($level_4[$i])){
                if(!in_array($level_4[$i], $final_questions))
                   {
                     $final_questions[] = $level_4[$i];
                     break;
                   }
              }
            }
       }
     if($value == 5)
       {
          for ($i=0; $i < count($difficulty_array) ; $i++)
             {
                if(isset($level_5[$i]) && !empty($level_5[$i])){
                   if(!in_array($level_5[$i], $final_questions))
                      {
                         $final_questions[] = $level_5[$i];
                         break;
                       }
                 }
             }
          }
      }
print_r($final_questions);


问:
how to pass data along with files from angular controller to node server?
I am passing some data from angular.js controller in following format:

```<code>data: { model: { title: 'hello'}, files: $scope.files}
</code>```

I am able to get this in node.js by doing this:

req.files

Now I want to send one more data with existing data, so I tried doing this:

```<code>data: { model: { title: 'hello', id:newId}, files: $scope.files}
</code>```

but when I did req.id. I am getting undefined.

What I am doing wrong?

答:
In angular, pass by combining in formdata :

```<code>var fd = new FormData();
fd.append("object", JSON.stringify($scope.yourJsonObject)); //pass json here
fd.append("files", $scope.files);

//wild card(*/*) consumes type
$http.post("Your URL", fd, {
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
});
</code>```

Then retrive object and files separately by their names.

Body:
I am passing some data from angular.js controller in following format:

data: { model: { title: 'hello'}, files: $scope.files}

I am able to get this in node.js by doing this:

req.files

Now I want to send one more data with existing data, so I tried doing this:

data: { model: { title: 'hello', id:newId}, files: $scope.files}

but when I did req.id. I am getting undefined.

What I am doing wrong?

Body:
In angular, pass by combining in formdata :

var fd = new FormData();
fd.append("object", JSON.stringify($scope.yourJsonObject)); //pass json here
fd.append("files", $scope.files);

//wild card(*/*) consumes type
$http.post("Your URL", fd, {
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
});

Then retrive object and files separately by their names.


问:
Is design now a subset of refactoring?
Looking at the cool new principles of software development:

Agile

You Ain't Gonna Need It

Less As A Competitive Advantage

Behaviour-Driven Development

The Evils Of Premature Optimization

The New Way seems to be to dive in and write what you need to achieve the first iteration of scope objectives, and refactor as necessary to have elegant solutions. Your codebase grows incrementally, and never has a big planning/hierarchical design stage. That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring, because that's where the elegant code comes from, not the incremental additions to functionality.

Am I wrong?

答:
I'd say that doing it the way you describe is a recipe for disaster, I would still recommend to do the overall design up front. Of course during the project you will need to change the design, it is never set in stone, flexibility is a must! (That's where the refactoring has to come in). I would also recommend to do the more detailed design for a module just before you start coding it.

But a solid general design is worth its weight in gold: It gives all developers a common base from which to start, a common idea or perhaps vision, of the goal.

Without that everybody will do as he/she thinks best, with the result that everybody does things in a different way. And suddenly you have to refactor a lot, just to align everybody to what has emerged as the apps architecture. The resulting code is ... not very elegant.

OwnerDisplayName: Phil H

Title: Is design now a subset of refactoring?

LastEditorDisplayName: Phil H

OwnerDisplayName: Treb


问:
HTML upload file small manipulation
When I use this code on IE8, the file is sent through the HTTP request fine:

```<code><form action="http:localhost:8080/myApp"
enctype="multipart/form-data" method="post">
<p>
Type some text (if you like):<br>
<input type="text" name="textline" size="30">
</p>
<p>
Please specify a file<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input type="submit" value="Send">
</div>
</form>
</code>```

but when I add another intermediate button, 'Add file', as you can see below instead of pressing the 'browse' button itself, the file isn't sent to the server side, why??

```<code><form action="http:localhost:8080/myApp"
enctype="multipart/form-data" method="post">
<p>
Type some text (if you like):<br>
<input type="text" name="textline" size="30">
</p>
<p>
Please specify a file<br>
<input id="fileChooser" type="file" name="datafile" size="40">
</p>
<button onclick="document.getElementById('fileChooser').click()">Add File</button>
<div>
<input type="submit" value="Send">
</div>
</form>
</code>```

答: Have the real input of type file hidden by setting its opacity to 0 then put the fake button on top of it, with smaller z-index value. This way when clicking the fake button, user will actually click the real button underneath and you will achieve the visual effect you desire.

Title: HTML upload file small manipulation

Body:
When I use this code on IE8, the file is sent through the HTTP request fine:

<form action="http:localhost:8080/myApp"
enctype="multipart/form-data" method="post">

Type some text (if you like):

<input type="text" name="textline" size="30">

Please specify a file

<input type="file" name="datafile" size="40">

<input type="submit" value="Send">

</form>

but when I add another intermediate button, 'Add file', as you can see below instead of pressing the 'browse' button itself, the file isn't sent to the server side, why??

<form action="http:localhost:8080/myApp"
enctype="multipart/form-data" method="post">

Type some text (if you like):

<input type="text" name="textline" size="30">

Please specify a file

<input id="fileChooser" type="file" name="datafile" size="40">

<button onclick="document.getElementById('fileChooser').click()">Add File</button>

<input type="submit" value="Send">

</form>


问:
How does Data Encapsulation actually happen in OOP?
I'm learning C++.

Came across data encapsulation and data hiding at a website, check out the following piece of code:

```<code>#include<iostream.h>
#include<conio.h>

class sum {
private: int a, b, c;

public:
    void add() {
        clrscr();
        cout << "Enter any two numbers: ";
        cin >> a >> b;
        c = a + b;
        cout << "Sum: " << c;
    }
};
void main() {
    sum s;
    s.add();
    getch();
}
</code>```

NOW. As it says here that:

The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.

What happens underneath the code, what does the compiler do that makes it inaccessible to other classes? And in the given example what was the reason behind defining a,b and c as private.

What were they trying to achieve by hiding "just the declarations of the three variables"? Because anyone can see that inside public three numbers being used are a,b, and c - first two for input and third one for output.

答:
What happens underneath the code, what does the compiler do that makes it unaccessible to other classes?

Not much. The compiler doesn't protect against access to the data. It protects against access to the name of the data. For instance:

```<code>void foo(class bar&, int&);

class bar {
  int i = 0;
public:
  void baz() {
    foo(*this, i);
  }
};

void foo(class bar& b, int& i) {
  //b.i = 42; // This is an error. b.i is private

  i = 42; // This is okay, no matter what the local i refers to
}
</code>```

In the example above, foo() cannot access b.i by name, because it's a private data member. But it can still modify it if it obtains a reference by other means. The member function baz() which has access to that name, binds it to the reference that foo() accepts. Thus allowing for its modification from outside the class's scope.

Body:
I'm learning C++.

Came across data encapsulation and data hiding at a website, check out the following piece of code:

#include<iostream.h>
#include<conio.h>

class sum {
private: int a, b, c;

public:
    void add() {
        clrscr();
        cout << "Enter any two numbers: ";
        cin >> a >> b;
        c = a + b;
        cout << "Sum: " << c;
    }
};
void main() {
    sum s;
    s.add();
    getch();
}

NOW. As it says here that:

The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.

What happens underneath the code, what does the compiler do that makes it inaccessible to other classes? And in the given example what was the reason behind defining a,b and c as private.

What were they trying to achieve by hiding "just the declarations of the three variables"? Because anyone can see that inside public three numbers being used are a,b, and c - first two for input and third one for output.

Body:
What happens underneath the code, what does the compiler do that makes it unaccessible to other classes?

Not much. The compiler doesn't protect against access to the data. It protects against access to the name of the data. For instance:

void foo(class bar&, int&);

class bar {
  int i = 0;
public:
  void baz() {
    foo(*this, i);
  }
};

void foo(class bar& b, int& i) {
  //b.i = 42; // This is an error. b.i is private

  i = 42; // This is okay, no matter what the local i refers to
}

In the example above, foo() cannot access b.i by name, because it's a private data member. But it can still modify it if it obtains a reference by other means. The member function baz() which has access to that name, binds it to the reference that foo() accepts. Thus allowing for its modification from outside the class's scope.


问:
How to minimize load time of a landing page
I'm honestly confused about where to start with minimizing the load time of a website i'm building - https://projectrhea.herokuapp.com/ . Currently takes around 9 seconds to load the website which I want to try and bring down to sub 3 seconds.

I've done a diagnostic test, shown here https://www.webpagetest.org/result/171113_T2_851758db144ac117ab4e986a3798b1b5/1/details/#waterfall_view_step1 .

From what I can see there are three main reasons it would be taking awhile to load.

The first is the javascript.

I only need a small amount of it to run the site but I am very
confused about how to separate the code I need from the code I don't
need. I use it for the banner to show multiple phrases underneath the
banner that I would rather keep.

The second part is the shear amount of CSS files I'm drawing from.

I used a template to begin the site (it was a good way for me to learn
how to design the site). Now I think this has meant there is way too
many css and other files connected to this landing page.

The third part is the video file I have.

I would love to keep this
video as I just like how it fits in the site. I'll try and minimize
the file size after I have worked out the above issues.

This is my first real time trying to solve an issue like this and I would really appreciate the knowledge a more experienced coder could bring to this. Thanks!

答: Place your css imports in the top of the page and import your javascript after your html body ends.</p>


问:
How to write return statement in java array function
I was writing this code, and I am not able to resolve this error missing return statement. Tried but still, nothing happened.

```<code>public class Solution {

    static int[] getRecord(int[] s){

   // Complete this function
    int bada=0,chota=0;
    for(int i=0;i<s.length;i++){
        int heighst=s[0];
        int lowest=s[0];
        if(s[i]<s[i+1]){
          heighst=s[i+1];
            bada++;

        }
        if(s[i]>s[i+1]){
            lowest=s[0];
            chota++;

        }
    }

}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int[] s = new int[n];
    for(int s_i=0; s_i < n; s_i++){
        s[s_i] = in.nextInt();
    }
    int[] result = getRecord(s);
    String separator = "", delimiter = " ";
    for (Integer val : result) {
        System.out.print(separator + val);
        separator = delimiter;
    }
    System.out.println("");
}
</code>```

}

答:
Your getRecord is counting things in bada and chota, which are local variables to that function, and so nothing else can access them. The function serves no purpose unless it returns them (and/or heighst [sic] and lowest).

Since there are multiple things to return, you need some kind of structure to return them in — an object or an array.

Apparently you or your instructor have chosen to use an array for that, so you need to create an int array with enough slots for the things you want to return, put those things (e.g., bada, chota, heighst [sic] and/or lowest) in it, and return that array.

This answer purposefully does not contain code. The OP is clearly working on an assignment, handing them the answer rather than leading them to the answer probably won't help them learn.

Body:
I was writing this code, and I am not able to resolve this error missing return statement. Tried but still, nothing happened.

public class Solution {

    static int[] getRecord(int[] s){

   // Complete this function
    int bada=0,chota=0;
    for(int i=0;i<s.length;i++){
        int heighst=s[0];
        int lowest=s[0];
        if(s[i]<s[i+1]){
          heighst=s[i+1];
            bada++;

        }
        if(s[i]>s[i+1]){
            lowest=s[0];
            chota++;

        }
    }

}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int[] s = new int[n];
    for(int s_i=0; s_i < n; s_i++){
        s[s_i] = in.nextInt();
    }
    int[] result = getRecord(s);
    String separator = "", delimiter = " ";
    for (Integer val : result) {
        System.out.print(separator + val);
        separator = delimiter;
    }
    System.out.println("");
}

}


问:
Is it possible to hook into Hardware keyboard events at an Application level?
I am developing a Xamarin.Forms application for iOS, Android and UWP.

I would like to hook into hardware keyboard events at an application level (not an individual page level (because its a Xamarin.Forms application)) so that when a user presses a key on the keyboard I can invoke an action in my application.

On Android I did this using the following event on MainActivity:.

```<code>public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
    //process key press
    return base.OnKeyUp(keyCode, e);
}
</code>```

Is there an equivilent for Xamarin iOS?

答:
You can use the KeyCommands to track the key pressing from hardware keyboard.

keyCommands

A responder object that supports hardware keyboard commands can redefine this property and use it to return an array of UIKeyCommand objects that it supports. Each key command object represents the keyboard sequence to recognize and the action method of the responder to call in response.

The key commands you return from this method are applied to the entire responder chain. When an key combination is pressed that matches a key command object, UIKit walks the responder chain looking for an object that implements the corresponding action method. It calls that method on the first object it finds and then stops processing the event.

In Xamarin.forms, you have to create custom renderer for ContentPage at iOS platform. Then the keycommands can be added in that page renderer.

If you want the key presses can be handled by the ViewController(Page), not just the input controls(such as Entry), use canBecomeFirstResponder to enable viewcontroller to become a first responder.

For example, the custom renderer of ContentPage in iOS platform could like this:

```<code>using System;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using KeyCommandsInXamarinForms.iOS;

[assembly: ExportRenderer(typeof(ContentPage), typeof(MyCustomPageRenderer))]
namespace KeyCommandsInXamarinForms.iOS
{
    public class MyCustomPageRenderer : PageRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null || Element == null)
            {
                return;
            }

            //Create your keycommand as you need.
            UIKeyCommand keyCommand1 = UIKeyCommand.Create(new NSString("1"), UIKeyModifierFlags.Command, new ObjCRuntime.Selector("Action:"));
            UIKeyCommand keyCommand2 = UIKeyCommand.Create(new NSString("\t"), 0, new ObjCRuntime.Selector("Action:"));
            //Add your keycommands
            this.AddKeyCommand(keyCommand1);
            this.AddKeyCommand(keyCommand2);
        }

        [Export("Action:")]
        private void Excute(UIKeyCommand keyCommand)
        {
            Console.WriteLine(String.Format("key pressed - {0}", keyCommand.Value);
        }

        //Enable viewcontroller to become the first responder, so it is able to respond to the key commands.
        public override bool CanBecomeFirstResponder
        {
            get
            {
                return true;
            }
        }
    }
}
</code>```

Notice this line, using typeof(ContentPage) as the handler parameter, then you don't need to change anything in your PCL:

[assembly: ExportRenderer(typeof(ContentPage), typeof(MyCustomPageRenderer))]

Body:
I am developing a Xamarin.Forms application for iOS, Android and UWP.

I would like to hook into hardware keyboard events at an application level (not an individual page level (because its a Xamarin.Forms application)) so that when a user presses a key on the keyboard I can invoke an action in my application.

On Android I did this using the following event on MainActivity:.

public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
    //process key press
    return base.OnKeyUp(keyCode, e);
}

Is there an equivilent for Xamarin iOS?

Body:
You can use the KeyCommands to track the key pressing from hardware keyboard.

keyCommands

A responder object that supports hardware keyboard commands can redefine this property and use it to return an array of UIKeyCommand objects that it supports. Each key command object represents the keyboard sequence to recognize and the action method of the responder to call in response.

The key commands you return from this method are applied to the entire responder chain. When an key combination is pressed that matches a key command object, UIKit walks the responder chain looking for an object that implements the corresponding action method. It calls that method on the first object it finds and then stops processing the event.

In Xamarin.forms, you have to create custom renderer for ContentPage at iOS platform. Then the keycommands can be added in that page renderer.

If you want the key presses can be handled by the ViewController(Page), not just the input controls(such as Entry), use canBecomeFirstResponder to enable viewcontroller to become a first responder.

For example, the custom renderer of ContentPage in iOS platform could like this:

using System;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using KeyCommandsInXamarinForms.iOS;

[assembly: ExportRenderer(typeof(ContentPage), typeof(MyCustomPageRenderer))]
namespace KeyCommandsInXamarinForms.iOS
{
    public class MyCustomPageRenderer : PageRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null || Element == null)
            {
                return;
            }

            //Create your keycommand as you need.
            UIKeyCommand keyCommand1 = UIKeyCommand.Create(new NSString("1"), UIKeyModifierFlags.Command, new ObjCRuntime.Selector("Action:"));
            UIKeyCommand keyCommand2 = UIKeyCommand.Create(new NSString("\t"), 0, new ObjCRuntime.Selector("Action:"));
            //Add your keycommands
            this.AddKeyCommand(keyCommand1);
            this.AddKeyCommand(keyCommand2);
        }

        [Export("Action:")]
        private void Excute(UIKeyCommand keyCommand)
        {
            Console.WriteLine(String.Format("key pressed - {0}", keyCommand.Value);
        }

        //Enable viewcontroller to become the first responder, so it is able to respond to the key commands.
        public override bool CanBecomeFirstResponder
        {
            get
            {
                return true;
            }
        }
    }
}

Notice this line, using typeof(ContentPage) as the handler parameter, then you don't need to change anything in your PCL:

[assembly: ExportRenderer(typeof(ContentPage), typeof(MyCustomPageRenderer))]


问:
Javascript add html dropdown options
I have the following html code:

```<code>    <!-- Small button group -->
<div class="btn-group">
    <button class="btn btn-danger btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Small button
    </button>
    <div class="dropdown-menu">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action</a>
        <a class="dropdown-item" href="#">Something else here</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">Separated link</a>
    </div>
</div>
</code>```

And now I would like to add dropdown-items over javascript based on the parsing of a xml file. But I have completely no idea how to do it. I've tried the way how it is described here: https://www.w3schools.com/jsref/met_select_add.asp, but that was not working.

答:
Do you mean something like this? https://www.w3schools.com/tags/tag_select.asp

<!DOCTYPE html>

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

```

Title: Javascript add html dropdown options

Body:
I have the following html code:

    <button class="btn btn-danger btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Small button
    </button>

        Action
        Another action
        Something else here

        Separated link

And now I would like to add dropdown-items over javascript based on the parsing of a xml file. But I have completely no idea how to do it. I've tried the way how it is described here: https://www.w3schools.com/jsref/met_select_add.asp, but that was not working.

Body:
Do you mean something like this? https://www.w3schools.com/tags/tag_select.asp

<!DOCTYPE html>
<html>
<body>

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

</body>
</html>


问:
Promise flattening fails - why?
```<code>const simplePromise = i => {
    return new Promise(function(resolve, reject) {
        console.log(i);
        setTimeout(function(){
            resolve();
        }, 2000);
    });
}

var anchor = simplePromise(0);
for (var i=1; i<4; i++) {
    anchor = anchor.then(_ => simplePromise(i));
}
</code>```

prints:

```<code>0
4
4
4
4
</code>```

instead of:

```<code>0
1
2
3
4
</code>```

1. Can someone explain why? and 2. tell me how to achieve this?

I can see that the first promise is executed (i=0), then the loop runs and then the value of i(=4) gets passed to the next promise. Shouldn't this be solved by having a function inside then (_ => simplePromise(i)) ?

答:
Your mistake is one of most common mistakes in JS - if not the most common - using a for loop to manipulate a state variable in an asynchronous situation. Your promises and your loop do not run in sync. The loop finishes much faster than any of your promises do.

Yet you use i in your promise callback, which only ever runs after the loop is done. Don't do that. There are ways to prevent it, but this has been discussed so often that I will only suggest to research and read a few of the existing answers.

I strongly suspect that you do not even want to loop over a fixed range of numbers. You actually have an array of items.

Simply drop the for loop and use the array iteration tools to dodge the scoping problem. Array#reduce is the perfect candidate here.

const simplePromise = val => {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            console.log(val);
            resolve(val);
        }, 200);
    });
}

var items = [0,1,2,3,4];

console.log("array iteration starts");

items
    .reduce((acc, i) => acc.then(_ => simplePromise(i)), Promise.resolve())
    .then(val => console.log("chain execution end w/ " + val));

console.log("array iteration done");

/*
    acc = Promise.resolve()
      then simplePromise(0)
        then simplePromise(1)
          then simplePromise(2)
            then simplePromise(3)
              then simplePromise(4)
                then console.log("...")
*/```

Title: Promise flattening fails - why?

Body:
const simplePromise = i => {
    return new Promise(function(resolve, reject) {
        console.log(i);
        setTimeout(function(){
            resolve();
        }, 2000);
    });
}

var anchor = simplePromise(0);
for (var i=1; i<4; i++) {
    anchor = anchor.then(_ => simplePromise(i));
}

prints:

0
4
4
4
4

instead of:

0
1
2
3
4

1. Can someone explain why? and 2. tell me how to achieve this?

I can see that the first promise is executed (i=0), then the loop runs and then the value of i(=4) gets passed to the next promise. Shouldn't this be solved by having a function inside then (_ => simplePromise(i)) ?


问:
OpenTok not working on older Android (org/webrtc/voiceengine/BuildInfo.class maybe missing)
I have a React Native Android app with an OpenTok view (written as a native module). I'm experiencing a crash problem (immediately upon attempt to instantiate OpenTok view) affecting older Android versions (SDK 16-19, Jelly Bean through KitKat), with any OpenTok session. More recent Android phones have no issues; OpenTok works perfectly.

Here is the relevant Android logcat output:

```<code>11-12 16:30:12.993 2949-2949/com.myapp I/OpenTokUnifiedView: APIKEY Connect Session
11-12 16:30:13.003 2949-2949/com.myapp I/OpenTokUnifiedView: apiKey: ********** sessionId: ********** token: **********
11-12 16:30:13.023 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.033 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.033 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.033 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.033 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.053 2949-2949/com.myapp E/BluetoothAdapter: Bluetooth binder is null
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: java.lang.NoClassDefFoundError: org/webrtc/voiceengine/BuildInfo
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.opentok.android.Session.init(Native Method)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.opentok.android.Session.<init>(Session.java:710)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.opentok.android.Session$Builder.build(Session.java:588)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.myapp.OpenTokUnifiedView.connectSession(OpenTokUnifiedView.java:114)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.myapp.OpenTokUnifiedView.setApiKey(OpenTokUnifiedView.java:72)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.myapp.OpenTokUnifiedViewManager.setApiKey(OpenTokUnifiedViewManager.java:34)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.ViewManagersPropertyCache$PropSetter.updateViewProp(ViewManagersPropertyCache.java:83)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.ViewManagerPropertyUpdater$FallbackViewManagerSetter.setProperty(ViewManagerPropertyUpdater.java:129)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.ViewManagerPropertyUpdater.updateProps(ViewManagerPropertyUpdater.java:48)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.ViewManager.updateProperties(ViewManager.java:34)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.NativeViewHierarchyManager.createView(NativeViewHierarchyManager.java:227)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue$CreateViewOperation.execute(UIViewOperationQueue.java:153)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue$1.run(UIViewOperationQueue.java:809)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue.flushPendingBatches(UIViewOperationQueue.java:922)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue.access$2100(UIViewOperationQueue.java:47)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.doFrameGuarded(UIViewOperationQueue.java:982)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.GuardedFrameCallback.doFrame(GuardedFrameCallback.java:31)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.modules.core.ReactChoreographer$ReactChoreographerDispatcher.doFrame(ReactChoreographer.java:136)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.modules.core.ChoreographerCompat$FrameCallback$1.doFrame(ChoreographerCompat.java:107)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.view.Choreographer$CallbackRecord.run(Choreographer.java:759)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.view.Choreographer.doCallbacks(Choreographer.java:574)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.view.Choreographer.doFrame(Choreographer.java:543)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.os.Looper.loop(Looper.java:136)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at dalvik.system.NativeStart.main(Native Method)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: Caused by: java.lang.ClassNotFoundException: Didn't find class "org.webrtc.voiceengine.BuildInfo" on path: DexPathList[[zip file "/data/app/com.myapp-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.myapp-1, /vendor/lib, /system/lib]]
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: ... 34 more
11-12 16:30:13.063 2949-2949/com.myapp E/rtc: #
# Fatal error in ../../webrtc/modules/utility/source/helpers_android.cc, line 68
# last system error: 2
# Check failed: !jni->ExceptionCheck()
# Error during FindClass: org/webrtc/voiceengine/BuildInfo
#
11-12 16:30:13.063 2949-2949/com.myapp A/libc: Fatal signal 6 (SIGABRT) at 0x00000b85 (code=-6), thread 2949 (ale.app.staging)
</code>```

Since it looked like org/webrtc/voiceengine/BuildInfo.class was missing, I manually added audio_device_java.jar as a library (as recommended on https://groups.google.com/forum/#!topic/discuss-webrtc/PkfAVr_TYQs ) to see if it fixed the issue.

However, it looked like OpenTok SDK already had it when I tried to build, so manually adding audio_device_java.jar did not help:

```<code>:app:transformClassesWithJarMergingForDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/webrtc/voiceengine/BuildInfo.class
</code>```

Not sure why the app on older Android is missing org/webrtc/voiceengine/BuildInfo.class. What could be happening on older Android?

EDIT: I found that this actually works on Lollipop -- modified this question to reflect that the issue affects up to SDK 19 (KitKat).

答:
I resolved this issue by adding webrtc jar file into android project

Download libjingle_peerconnection_java.jar file from https://drive.google.com/open?id=1bElH-Krh56cO2S8Biyp0LSFurjcxFIcT

Place it into libs/ folder

Run your application

If you got "Multiple dex files define android Logging.class" then follow below steps

Extract your .jar file

Remove Logging class files from the folder (org.webrtc)

Finally Compress it as .jar and utilise it, your error will resolve.

That's it.

Body:
I have a React Native Android app with an OpenTok view (written as a native module). I'm experiencing a crash problem (immediately upon attempt to instantiate OpenTok view) affecting older Android versions (SDK 16-19, Jelly Bean through KitKat), with any OpenTok session. More recent Android phones have no issues; OpenTok works perfectly.

Here is the relevant Android logcat output:

11-12 16:30:12.993 2949-2949/com.myapp I/OpenTokUnifiedView: APIKEY Connect Session
11-12 16:30:13.003 2949-2949/com.myapp I/OpenTokUnifiedView: apiKey: ********** sessionId: ********** token: **********
11-12 16:30:13.023 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.033 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.033 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.033 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.033 2949-2949/com.myapp I/dalvikvm: threadid=1: recursive native library load attempt (/data/app-lib/com.myapp-1/libopentok.so)
11-12 16:30:13.053 2949-2949/com.myapp E/BluetoothAdapter: Bluetooth binder is null
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: java.lang.NoClassDefFoundError: org/webrtc/voiceengine/BuildInfo
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.opentok.android.Session.init(Native Method)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.opentok.android.Session.<init>(Session.java:710)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.opentok.android.Session$Builder.build(Session.java:588)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.myapp.OpenTokUnifiedView.connectSession(OpenTokUnifiedView.java:114)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.myapp.OpenTokUnifiedView.setApiKey(OpenTokUnifiedView.java:72)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.myapp.OpenTokUnifiedViewManager.setApiKey(OpenTokUnifiedViewManager.java:34)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.ViewManagersPropertyCache$PropSetter.updateViewProp(ViewManagersPropertyCache.java:83)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.ViewManagerPropertyUpdater$FallbackViewManagerSetter.setProperty(ViewManagerPropertyUpdater.java:129)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.ViewManagerPropertyUpdater.updateProps(ViewManagerPropertyUpdater.java:48)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.ViewManager.updateProperties(ViewManager.java:34)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.NativeViewHierarchyManager.createView(NativeViewHierarchyManager.java:227)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue$CreateViewOperation.execute(UIViewOperationQueue.java:153)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue$1.run(UIViewOperationQueue.java:809)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue.flushPendingBatches(UIViewOperationQueue.java:922)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue.access$2100(UIViewOperationQueue.java:47)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.doFrameGuarded(UIViewOperationQueue.java:982)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.uimanager.GuardedFrameCallback.doFrame(GuardedFrameCallback.java:31)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.modules.core.ReactChoreographer$ReactChoreographerDispatcher.doFrame(ReactChoreographer.java:136)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.facebook.react.modules.core.ChoreographerCompat$FrameCallback$1.doFrame(ChoreographerCompat.java:107)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.view.Choreographer$CallbackRecord.run(Choreographer.java:759)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.view.Choreographer.doCallbacks(Choreographer.java:574)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.view.Choreographer.doFrame(Choreographer.java:543)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.os.Looper.loop(Looper.java:136)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at dalvik.system.NativeStart.main(Native Method)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: Caused by: java.lang.ClassNotFoundException: Didn't find class "org.webrtc.voiceengine.BuildInfo" on path: DexPathList[[zip file "/data/app/com.myapp-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.myapp-1, /vendor/lib, /system/lib]]
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
11-12 16:30:13.063 2949-2949/com.myapp W/System.err: ... 34 more
11-12 16:30:13.063 2949-2949/com.myapp E/rtc: #
# Fatal error in ../../webrtc/modules/utility/source/helpers_android.cc, line 68
# last system error: 2
# Check failed: !jni->ExceptionCheck()
# Error during FindClass: org/webrtc/voiceengine/BuildInfo
#
11-12 16:30:13.063 2949-2949/com.myapp A/libc: Fatal signal 6 (SIGABRT) at 0x00000b85 (code=-6), thread 2949 (ale.app.staging)

Since it looked like org/webrtc/voiceengine/BuildInfo.class was missing, I manually added audio_device_java.jar as a library (as recommended on https://groups.google.com/forum/#!topic/discuss-webrtc/PkfAVr_TYQs ) to see if it fixed the issue.

However, it looked like OpenTok SDK already had it when I tried to build, so manually adding audio_device_java.jar did not help:

:app:transformClassesWithJarMergingForDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/webrtc/voiceengine/BuildInfo.class

Not sure why the app on older Android is missing org/webrtc/voiceengine/BuildInfo.class. What could be happening on older Android?

EDIT: I found that this actually works on Lollipop -- modified this question to reflect that the issue affects up to SDK 19 (KitKat).


问:
How does code push cordova get the path of the cordova project in visual studio team services?
How does code push cordova get the path of the cordova project in visual studio team services for the step to execute cordova prepare command?</p>

答:
The CodePush - Release (Cordova) task is using the default working directory, and the directory can not be specify for this task.

I add an issue Can not specity the directory to execute the command code-push release-cordova, you can follow up.

The work around for now is using Command Line task instead. Settings for the Command Line task as below:

Tool: cd

Arguments: path/to/your/cordova/app & code-push login <token> & code-push release-cordova AppName OS

Besides: CodePush task also can parse the variable Build.SourceDirectory, so you can define this variable with the value  $(Build.SourcesDirectory)\path\to\cordova\app in Variables Tab (below is an example).


问:
Calculate the difference between two non-adjacent columns, based on a "match column" using Excel VBA
I'm looking for the most efficient way to compare two sets of two columns, thus:

Set 1:

A | B  | C |

11_22 | 10 |   |

33_44 | 20 |   |

55_66 | 30 |   |

77_88 | 40 |   |

99_00 | 50 |   |

Set 2:

J     | K  |

33_44 | 19 |

99_00 | 47 |

77_88 | 40 |

For each match between column A and J, column C should display the difference between the adjacent cells
(in this case 33_44, 99_00, and 77_88) in B and K, respectively, with the full
amount in column B if no match exists in J

A     | B  | C

11_22 | 10 | 10

33_44 | 20 | 1

55_66 | 30 | 30

77_88 | 40 | 0

99_00 | 50 | 3

I'm thinking of creating two multi-dimensional arrays containing values
in the ranges (A, B) and (J, K), with a nested loop, but am not sure how to
get the result back into column C when a match occurs. Creating a third "result array" and outputting that on a fresh sheet would work too.

答: It is possible to do a lot with ADO, for example: Excel VBA to match and line up rows</p>