Q: My code in JS isn't coming out with a letter grade I wrote a function in JS towards the end that is suppose to give you a letter grade once you get the average of 5 subjects, but it's not showing me anything
I'm lost right now
The forth function I wrote doesn't seem to produce any letter grade. I believe everything else is right

function getHandleValue(idName) {
  const value = parseInt(document.getElementById(idName).value);
  console.log(value);
  return value;
}

function getTotal() {
  //console.log("app js starts loading")
  let english = getHandleValue('english');
  let math = getHandleValue('math');
  let physics = getHandleValue('physics');
  let computer = getHandleValue('computer');
  let science = getHandleValue('science');
  //console.log("app js ends loading")
  let total = english + math + physics + computer + science;
  document.getElementById('total').innerHTML = total;
  return total;

}

function getAverage() {
  // option  1
  // const total = parseInt(document.getElementById('total').innerHTML);
  // const average = total / 5;
  // document.getElementById('average').innerHTML = average;

  // option 2
  const average = getTotal() / 5;
  document.getElementById('average').innerHTML = average;
}

function letterGrade() {
  letterGrade;
  if (grade >= 90 && grade <= 100)
    letterGrade = 'A';

  else if (grade >= 80 && grade <= 89)
    letterGrade = 'B';

  else if (grade >= 70 && grade <= 79)
    letterGrade = 'C';

  else if (grade >= 60 && grade <= 69)
    letterGrade = 'D';

  else if (grade > 1 && grade <= 59)
    letterGrade = 'F';

  let average = letterGrade;
  document.getElementById('Grade').innerHTML = Grade;
}

A: letterGrade isn't declared properly, do:
let letterGrade = ' '

This declares the letterGrade variable.

A: You haven't declared the lettergrade variable. To do this, replace letterGrade; with let letterGrade;
In your code, this will look like:

function getHandleValue(idName) {
  const value = parseInt(document.getElementById(idName).value);
  console.log(value);
  return value;
}

function getTotal() {
  //console.log("app js starts loading")
  let english = getHandleValue('english');
  let math = getHandleValue('math');
  let physics = getHandleValue('physics');
  let computer = getHandleValue('computer');
  let science = getHandleValue('science');
  //console.log("app js ends loading")
  let total = english + math + physics + computer + science;
  document.getElementById('total').innerHTML = total;
  return total;

}

function getAverage() {
  // option  1
  // const total = parseInt(document.getElementById('total').innerHTML);
  // const average = total / 5;
  // document.getElementById('average').innerHTML = average;

  // option 2
  const average = getTotal() / 5;
  document.getElementById('average').innerHTML = average;
}

function letterGrade() {
  let letterGrade;
  if (grade >= 90 && grade <= 100)
    letterGrade = 'A';

  else if (grade >= 80 && grade <= 89)
    letterGrade = 'B';

  else if (grade >= 70 && grade <= 79)
    letterGrade = 'C';

  else if (grade >= 60 && grade <= 69)
    letterGrade = 'D';

  else if (grade > 1 && grade <= 59)
    letterGrade = 'F';

  let average = letterGrade;
  document.getElementById('Grade').innerHTML = Grade;
}

A: Problems
I assume comments and answers have already stated, that the function letterGrade() doesn't use the correct variable letterGrade but instead uses an undefined variable Grade. Also, the variable grade is neither defined nor is it passed as a parameter or is within scope. Figure I is a breakdown of letterGrade().
Figure I

function letterGrade() {
  /**
   * ISSUE 1 * Naming a Variable
   * Do not name a variable with the same name as the function in which it
   * resides within
   * ISSUE 2 * Declaring or Defining a Variable
   * Use identifier var (not recommended), let, or const
   *   ex. let letter;
   */
  letterGrade;
  /**
   * ISSUE 3 * Declaring or Defining Variables
   * grade isn't declared
   *   ex. let grade;
   * grade isn't defined
   *   ex. let grade = 0;
   * grade isn't a parameter
   *   ex. function letterGrade(grade) {...
   * grade isn't within scope
   *   ex. let grade = 0;
   *       function letterGrade() {...
   */
  if (grade >= 90 && grade <= 100)
    letterGrade = 'A';

  else if (grade >= 80 && grade <= 89)
    letterGrade = 'B';

  else if (grade >= 70 && grade <= 79)
    letterGrade = 'C';

  else if (grade >= 60 && grade <= 69)
    letterGrade = 'D';

  else if (grade > 1 && grade <= 59)
    letterGrade = 'F';

  /**
   * ISSUE 4 * Passing by Value
   * average is never used. If average is a reference to the value calculated
   * by function getAverage(), then...
   *   - getAverage() should return that value,
   *   - then that value must be defined outside of getAverage()
   *   - or passed as a parameter of letterGrade() (recommennded).
   *     ex. ..::OUTSIDE OF letterGrade()::..
   *         function getAverage() {
   *           ...
   *           return average;
   *         }
   *         // Option A
   *         let average = getAverage()
   *         letterGrade(average)
   *         // Option B (recommended)
   *         letterGrade(getAverage)
   *
   *         ..::INSIDE OF letterGrade()::..
   *         function letterGrade(average) {
   *           let grade = typeof average === "number" ? grade : 0;
   *           ...
   *         }
   * Even if average was to be used, it would be useless as the value of
   * letterGrade, there's no point in reassigning it to another variable
   * unless it's to create a copy of another variable declared or defined
   * outside of the function.
   */
  let average = letterGrade;
  /**
   * ISSUE 5 * Defining or Declaring Variables
   * Grade variable has the same problem as ISSUE 3
   */
  document.getElementById('Grade').innerHTML = Grade;
}

Solutions
Provided are two examples (Example A and Example B) that require familiarity with a few methods, properties, events, and techniques, please refer to Appendix located at the end of this answer. Both examples have step-by-step details commented within the source.
Example A
Example A is a working example that comprises of:

*

*a <form> tag

*an <input type="range">

*two <output> tags

*an event handler getGrade(e)

*a functional letterGrade(score)

/**
 * Reference <form>
 * Bind the "input" event to <form>
 */
const grade = document.forms.grade;
grade.oninput = getGrade;

/**
 * Event handler passes (e)vent object by default
 * Reference the tag the user is currently typing into
 * Reference all form controls (<fieldset>, <input>, <output>)
 * Reference both <output>
 * If the tag the user is currently using is NOT <form>
 * AND the tag is #score...
 * Assign the value of the currently used <input> as the
 * value of the first <output>
 * Next pass the same value to letterGrade(score) and assign
 * it's value to the second <output>
 */
function getGrade(e) {
  const dataIN = e.target;
  const io = this.elements;
  const number = io.number;
  const letter = io.letter;
  if (dataIN !== this && dataIN.id === "score") {
    number.value = dataIN.value;
    letter.value = letterGrade(dataIN.value);
  }
}

/**
 * Convert a given number in the range of 0 to 100 to a
 * letter grade in the range of "A" to "F".
 * @param {Number} score - A number in the range of 0 to 100
 * @returns {String} - A letter in the range of "A" to "F"
 * @default {String} - A "" if the @param is out of the
 *          range of 0 to 100
 */
function letterGrade(score) {
  if (score >= 0 && score < 60) return "F";
  if (score >= 60 && score < 70) return "D";
  if (score >= 70 && score < 80) return "C";
  if (score >= 80 && score < 90) return "B";
  if (score >= 90 && score < 101) return "A";
  return "";
}
label {
  display: flex;
  align-items: center;
  margin: 0.5rem 0;
}

input {
  cursor: pointer;
}
<form id="grade">
  Set Score:

    0
    <input id="score" type="range" min="0" max="100" value="0">
     100

  Score: <output id="number"></output>
  Grade: <output id="letter"></output>
</form>

Note the pattern of the flow control statements in Example A:
if (CONDITION) return LETTER;
if (CONDITION) return LETTER;
if (CONDITION) return LETTER;
if (CONDITION) return LETTER;
if (CONDITION) return LETTER;
return "";

If a CONDITION is true then a LETTER is returned. Whenever a value (LETTER) is returned, the function will terminate, so for example the third CONDITION is true, then the third LETTER is returned, the function ends, and the rest of the function doesn't execute. This technique is called a short circuit
Example B
Example B is a working example comprising of:

*

*a <form>

*five <input type="number">

*two <output>

*an event handler calc(e)

*a terse version of letterGrade(avg) that uses ternary expressions

/**
 * Reference <form>
 * Bind the "input" event to <form>
 */
const ga = document.forms.ga;
ga.oninput = calc;

/**
 * Event handler passes the (e)vent object by default
 * Reference the tag the user is entering text into
 * Reference all form controls (<fieldset>, <input>, <output>)
 * Collect all tags with [name="subject"] into an array
 * Reference the <output>
 * If the <input> that the user is currently using is NOT <form>...
 * AND if it is [name="subject"]...
 * convert the value of each <input> of the >subs< array into a
 * number, then use .reduce() to get the sum of all of them (>total<)
 * Next divide >total< by the .length of >subs<
 * Then get the letter grade determined by the given >average<
 * Then display the quotient as the value of the first <output>
 * Finally, display the letter grade as the value of the second <output>
 */
function calc(e) {
  const dataIN = e.target;
  const io = this.elements;
  const subs = Array.from(io.subject);
  const avg = io.avg;
  const grd = io.grd;
  if (dataIN !== this && dataIN.name === "subject") {
    const total = subs.reduce((sum, add) => +sum + parseInt(add.value), 0);
    const average = total / subs.length;
    const letter = grade(average);
    avg.value = average;
    grd.value = letter;
  }
}

/**
 * Given a number in the range of 0 to 100 return The letter grade equivalent.
 * @param {Number} avg - A number in the range of 0 to 100
 * @returns {String} - A letter grade "A" to "F"
 * @default {String} - If avg ts not within the range of 0 to 100,
 * a "" is returned
 */
function grade(avg) {
  return avg >= 0 && avg < 60 ? "F" :
    avg >= 60 && avg < 70 ? "D" :
    avg >= 70 && avg < 80 ? "C" :
    avg >= 80 && avg < 90 ? "B" :
    avg >= 90 && avg < 101 ? "A" : "";
}
:root {
  font: 300 ch2/1.15 "Segoe UI"
}

fieldset {
  display: flex;
  flex-flow: column nowrap;
  width: 50vw;
  max-width: 60ch;
  margin: auto;
}

legend {
  font-weight: 500;
  font-size: 1.15rem;
}

label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0.25rem 1rem;
}

.last+label {
  margin-top: 1.25rem;
}

input,
output {
  display: inline-block;
  width: 6ch;
  font: inherit;
  line-height: normal;
  text-align: center;
}

output {
  text-align: left;
}
<form id="ga">
  <fieldset>
    <legend>Subjects</legend>
    English: <input id="eng" name="subject" type="number" min="0" max="100" value="0">
    Math: <input id="mat" name="subject" type="number" min="0" max="100" value="0">
    History: <input id="his" name="subject" type="number" min="0" max="100" value="0">
    Science: <input id="sci" name="subject" type="number" min="0" max="100" value="0">
    Art: <input id="art" name="subject" type="number" min="0" max="100" value="0">
    Average: <output id="avg"></output>
    Grade: <output id="grd"></output>
  </fieldset>
</form>

Appendix

*

*Events

*Event Delegation

*Inline Event Handlers are Garbage

*HTMLFormElement Interface

*HTMLFormControlsCollection Interface

*List of Form Controls

*Scope and Closures

A: NOTES

*

*This is a fully working example of how you can go about calculating the grades in a generic way without having to use ids for each subject input.

*By building it this way, you can add more subjects without changing the calculation logic.

*Also if you do not put a value for a subject than it will not be used in the calculations.

HTML

Total:0

Average:0

Grade:-

<form onsubmit="return false;">
    English:<input type="number" min="0" max="100" step="1" name="english" value="0" />

    Math:<input type="number" min="0" max="100" step="1" name="math" value="0" />

    Physics:<input type="number" min="0" max="100" step="1" name="physics" value="0" />

    Computer:<input type="number" min="0" max="100" step="1" name="computer" value="0" />

    Science:<input type="number" min="0" max="100" step="1" name="science" value="0" />

    <button onclick="calculateGrades(this)">Calculate Grade</button>
</form>

CSS
label {
    display: inline-block;
    width: 4rem;
    margin-right: 2rem;
    padding: 0.25rem 1rem;
}

JS
const totalElement = document.getElementById("total");
const averageElement = document.getElementById("average");
const gradeElement = document.getElementById("grade");

// Calculate the grades function
function calculateGrades(btn) {

    // find inputs
    const form = btn.closest("form");
    const inputs = form.getElementsByTagName("input");

    // define variables
    let total = 0;
    let used = 0;
    let average = 0;

    // loop over inputs
    for (const input of inputs) {
        // if value = 0, then do not use in calculation
        if (input.value == 0) continue;

        // convert input to number and add it to total
        total += Number( input.value );

        // increment number of subjects used
        used++;
    }

    // calculate average grade
    average = total / used;

    // display the values
    totalElement.innerText = total;
    averageElement.innerText = average;

    // get letter grade
    letterGrade( average );
}

// Calculate the grade letter function
function letterGrade(value) {

    // define variables
    let letterGrade = null;

    // if there is no value return
    if ( !value ) return letterGrade;

    // determine letter from value
    switch (true) {
        case value >= 90:
            letterGrade = "A";
            break;
        case value >= 80:
            letterGrade = "B";
            break;
        case value >= 70:
            letterGrade = "C";
            break;
        case value >= 60:
            letterGrade = "D";
            break;
        default:
            letterGrade = "F";
            break;
    }

    // display the grade letter
    gradeElement.innerText = letterGrade;
}


Q: Infinite scroll with angularfire2 I'm attempting to recreate this simple example for infinite scroll with a firebase backend: https://angularfirebase.com/lessons/infinite-scroll-with-firebase-data-and-angular-animation/
The problem is that i want to use the latest version of angularfire2, and I just can't figure out how to rewrite 1 method.
I'm stuck at the movies-list.components.ts file's getMovies() method, since in the latest version of angularfire2 there's no 'do()' method on AngularFireList objects. Is there a way to run arbitrary code before .take(1).subscribe() ?
private getMovies(key?) {
    if (this.finished) return

    this.movieService
        .getMovies(this.batch+1, this.lastKey)
        .do(movies => {

          /// set the lastKey in preparation for next query
          this.lastKey = _.last(movies)['$key']
          const newMovies = _.slice(movies, 0, this.batch)

          /// Get current movies in BehaviorSubject
          const currentMovies = this.movies.getValue()

          /// If data is identical, stop making queries
          if (this.lastKey == _.last(newMovies)['$key']) {
              this.finished = true
          }

          /// Concatenate new movies to current movies
          this.movies.next( _.concat(currentMovies, newMovies) )
        })
        .take(1)
        .subscribe()
}

A: do() is called tap() in RxJS 6+.


Q: CollectD server system load look scary Please excuse my poor server skill here.
However, I just installed collectD on Linux (web server) about minutes ago and found that the system load look a bit scary.
All graphs (cpu, memory) look fine except this one.
Can you guys let me know if everything is ok given by the graph below?
http://oi43.tinypic.com/2q8ocht.jpg
If so, can you direct me how to read this graph or point me the source to do further research from here.
(does red line graph and the 100m dash look like something it's not suppose to be on the stable server?)

A: 100m (milli) means a loadavg of 0.1: your server is pretty fine!


Q: Calculating which compiler is faster in terms of cycling I just have a simple question, a bit silly, but I just need some clarification for an upcoming exam so I don't make a stupid mistake. I am currently taking a class in computer organization and design and am learning about execution time, CPI, clock cycles, etc.
For a problem, I have to calculate the amount of cycles for 2 compilers and find out which one is faster and by how much given the number of instructions and the cycles for each instruction. My main problem is figuring how much faster the faster compiler is.
For example lets say their are two compilers:
Compiler 1 has 3 load instructions, 4 store instructions, and 5 add
instructions.

Compiler 2 has 5 load instructions, 4 store instructions, and 3 add
instructions

A load instruction takes 2 cycles, a store instruction takes 3 cycles and a add instruction takes 1 cycle
So what I would do this add up to the instructions (3+4+5) and (5+4+3) which both equal to 12 instructions.
I'd then calculate the cycles by multiplying the number of instructions by the cycles and adding them all together like this
Compiler 1: (3*2)+(4*3)+(5*1) = 23 cycles
Compiler 2: (5*2)+(4*3)+(3*1) = 25 cycles

So obviously compiler 1 is faster because it requires less cycles. To find out how much faster compiler 1 is against compiler 2 would I just divide the ratio of the cycles?
My calculation was 23/25 = 0.92, so compiler 1 is 0.92 times faster than compiler 2 (92% faster).
A classmate of mine was discussing this with me and claims that it would be 25/23 which would mean it is 1.08 times faster.
I know I can also calculate this by dividing the cycles by the instructions like:
23 cycles/12 instructions = 1.91
25 cycles/12 instructions = 2.08
and then 1.91/2.08 = 0.92 which is the same as the above answer.

I'm not sure which way would be correct.
I was also wondering if the amount of instructions are difference for the second compiler, let's say 15 instructions. Would calculating the ratio of the cycles be sufficient enough?
Or would I have to divide the cycles with the instructions (cycles/instructions) but put 15 instructions for both?
(ex. 23/15 and 25/15?) and then divide the quotients of both to get
the times faster? I also get the same number(0.92) in that case.

Thank you for any clarification.

A: The first compiler would be 1.08 times the speed of the second compiler, which is 8% faster (because 1.0 + 0.08 = 1.08).

A: Probably both calculations are innacurate, with modern/multi-core processors a compiler that generates more instruction may actually produce faster code.


Q: CKEditor ReadOnly I got a problem since I use the CKEditor (http://ckeditor.com/). The problem is that I can't find a way to make the editor ReadOnly and I can't just use a textarea since I want to keep consistency. I've already seen lots og questions like this at StackOwerflow, but none of them work or are too old.
My code so far is only to display/initialize the editor:
$(document).ready(function(){
    CKEDITOR.replace( 'ckeditor', {
        on: {
            // Check for availability of corresponding plugins.
            pluginsLoaded: function( evt ) {
                var doc = CKEDITOR.document, ed = evt.editor;
                if ( !ed.getCommand( 'bold' ) )
                    doc.getById( 'exec-bold' ).hide();
                if ( !ed.getCommand( 'link' ) )
                    doc.getById( 'exec-link' ).hide();
            }
        }
    });
});

I use the newest CKEditor version(v.4.1.1 Full package)
Thanks in advance! :)

A: In the docs readOnly you can set the config to readOnly
config.readOnly = true;

There is also an example that shows setting it via a method
editor.setReadOnly( true);

A: try with following lines,
<textarea id="editor1" name="editor1" ></textarea>
<textarea id="editor2" name="editor2" ></textarea>

<input type="button" onclick="EnableEditor2()" value="EnableEditor2" />

A: have you tried
this
?
they say, that this should work
var editor;

// The instanceReady event is fired, when an instance of CKEditor has finished
// its initialization.
CKEDITOR.on( 'instanceReady', function( ev )
{
    editor = ev.editor;

    // Show this "on" button.
    document.getElementById( 'readOnlyOn' ).style.display = '';

    // Event fired when the readOnly property changes.
    editor.on( 'readOnly', function()
        {
            document.getElementById( 'readOnlyOn' ).style.display = this.readOnly ? 'none' : '';
            document.getElementById( 'readOnlyOff' ).style.display = this.readOnly ? '' : 'none';
        });
});

function toggleReadOnly( isReadOnly )
{
    // Change the read-only state of the editor.
    // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#setReadOnly
    editor.setReadOnly( isReadOnly );
}

and html
<form action="sample_posteddata.php" method="post">

        <textarea class="ckeditor" id="editor1" name="editor1" cols="100" rows="10"><p>This is some <strong>sample text</strong>. You are using <a href="http://ckeditor.com/">CKEditor</a>.</p></textarea>

        <input id="readOnlyOn" onclick="toggleReadOnly();" type="button" value="Make it read-only" style="display:none" />
        <input id="readOnlyOff" onclick="toggleReadOnly( false );" type="button" value="Make it editable again" style="display:none" />

</form>

A: In version 5 i do this:
ClassicEditor
    .create( document.querySelector( '.editor' ), {
        removePlugins: ['Title'],
        licenseKey: '',

    } )
    .then( editor => {
        window.editor = editor;
        editor.isReadOnly = true;

    } )
    .catch( error => {
        console.error( 'Oops, something went wrong!' );
        console.error( 'Please, report the following error on https://github.com/ckeditor/ckeditor5/issues with the build id and the error stack trace:' );
        console.warn( 'Build id: efxy8wt6qchd-qhxgzg9ulnyo' );
        console.error( error );
    } );

A: Sources :
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.readOnly
http://rev.ckeditor.com/ckeditor/trunk/7657/_samples/readonly.html
CKEDITOR.config.readOnly = true;

A: Check this one out. The idea is if a user logs in a system with a classification other than 'BPPA', the CK editor shall be disabled and read-only. If the classification of a user is BPPA, thus the CK editor is editable. Note that these code fractions are actually in PHP. They need a working database to work but I figured you might get the idea and be able to work your own magic.
<?php
                //This line is to disable PART A if classification != 'BPPA'
                $bppa = mysql_query("SELECT * from roles WHERE username = '$_SESSION[username]'");
                $bppa_row = mysql_fetch_array($bppa);
                if($bppa_row['classification'] != 'BPPA'){
                    $disabled = 'disabled = "disabled"';
                }else{
                    $disabled = "";
                }
                //ends here
?>

Then, apply $disable to your text area:
<?php
echo '<textarea class="ckeditor" '.$disabled.' name="content' . $n . '" id="content' . $n . '">' . $saved . '</textarea>';
?>

A: with version 4.5.4 you can do it with:
$('#idElement).ckeditorGet().setReadOnly(true);

A: In case you have several editors on the same page and you want to disable all of them on the page display :
CKEDITOR.on('instanceReady', function (ev) {
    ev.editor.setReadOnly(true);
});

Documentation


Q: Android pin activity on boot I've got an app that registers itself as the default launcher and pins itself automatically when started.
This all works fine when installing the app. It pins itself and only the back button is visible.
The problem is that when the device first boots up, it does not pin properly. I see a series of toasts "Screen pinned" and "Screen unpinned" multiple times. The "Home" and "Recent Tasks" buttons are still visible as well.
--
Running "adb shell dumpsys activity activities" - the last lines indicate that it is not pinned:
mLockTaskModeState=NONE mLockTaskPackages (userId:packages)=
0:[com.example.myapp]
mLockTaskModeTasks[]

--
Testing device Asus ZenPad running Marshmallow/6.0/23
I'm relying on the MainActivity manifest attribute "lockTaskMode" to pin (rather than activity.startLockTask()):
<activity
    android:name=".MainActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:label="@string/launcher_main"
    android:launchMode="singleTask"
    android:lockTaskMode="if_whitelisted"
    android:screenOrientation="landscape">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.HOME"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>

Any help or pointers would be appreciated

A: I had the same problem and I could really only find one solution.  I'm not sure why but yeah, something in android prevents task locking when booting up which boggles my mind since the task lock was designed to create these "kiosk" type of applications.  The only solution I could find was to detect for a case when it didn't lock then restart the application.  Its a little "hacky" but what else can you do?
To detect for the case where it didn't lock I  created a state variable and assigning states (Locking, Locked, Unlocking, Unlocked).  Then in the device admin receiver in onTaskModeExiting if the state isn't "Unlocking" then I know it unlocked on its own. So if this case happened where it failed, I then restart the application using this method (which schedules the application in the alarm manager then kills the application):
how to programmatically "restart" android app?
Here is some sample code:
DeviceAdminReceiver
@Override
public void onLockTaskModeEntering(Context context, Intent intent, String pkg) {
    super.onLockTaskModeEntering(context, intent, pkg);
    Lockdown.LockState = Lockdown.LOCK_STATE_LOCKED;
}

@Override
public void onLockTaskModeExiting(Context context, Intent intent) {
    super.onLockTaskModeExiting(context, intent);

    if (Lockdown.LockState != Lockdown.LOCK_STATE_UNLOCKING) {
        MainActivity.restartActivity(context);
    }
    Lockdown.LockState = Lockdown.LOCK_STATE_UNLOCKED;
}

MainActivity
public static void restartActivity(Context context) {
    if (context != null) {
        PackageManager pm = context.getPackageManager();
        if (pm != null) {
            Intent intent = pm.getLaunchIntentForPackage(context.getPackageName());
            if (intent != null) {
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                int pendingIntentId = 223344;
                PendingIntent pendingIntent = PendingIntent.getActivity(context, pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
                AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
                System.exit(0);
            }
        }
    }
}

private void lock() {
    Lockdown.LockState = Lockdown.LOCK_STATE_LOCKING;
    startLockTask();
}

private void unlock() {
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED) {
        Lockdown.LockState = Lockdown.LOCK_STATE_UNLOCKING;
        stopLockTask();
    }
}

In truth this is a simplified version of what I implemented.  But it should hopefully get you pointed towards a solution.

A: The only solution I found as for now : make another launcher app, without locktask, which will trigger main app every time when launcher appears. This prevent user for waiting few more seconds before LockTasked app is being called with on BOOT_COMPLETED receiver. So we can meet this problem only when lockTask app has launcher properties for some activity in manifest.

A: Sorry for late answering, but...
Anyone has this problem can do this tricky work in first (LAUNCHER/HOME) activity (e.g. MainActivity):
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (mSharedPreferences.getBoolean(KEY_PREF_RECREATED, false)) {
        mSharedPreferences.edit().putBoolean(KEY_PREF_RECREATED, false).apply();

        // start LOCK TASK here
    } else {
        mSharedPreferences.edit().putBoolean(KEY_PREF_RECREATED, true).apply();

        finish(); // close the app
        startActivity(new Intent(this, MainActivity.class)); // reopen the app
        return;
    }

    setContentView(R.layout.activity_main);

    // other codes
}


Q: Connecting to remote HBase service using Java I have a small sample code in which I try to establish a connection to a remote HBase entity. The code runs on a windows machine without HBase installed and I try to connect to a remote Ubuntu Server that has it installed and running. The IP in the below snippet is of course just a placeholder.
The code is as follows:
public static void main(String[] args) {

    Configuration conf = HBaseConfiguration.create();
    HBaseAdmin admin = null;

    String ip = "10.10.10.10";
    String port = "2181";

    conf.set("hbase.zookeeper.quorum", ip);
    conf.set("hbase.zookeeper.property.clientPort", port);

    try {
        admin = new HBaseAdmin(conf);
        boolean bool = admin.tableExists("sensor_data");
        System.out.println("Table exists? " + bool);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

But for some reason I get this error:
org.apache.hadoop.hbase.DoNotRetryIOException: java.lang.IllegalAccessError: tried to access method com.google.common.base.Stopwatch.<init>()V from class org.apache.hadoop.hbase.zookeeper.MetaTableLocator
at org.apache.hadoop.hbase.client.RpcRetryingCaller.translateException(RpcRetryingCaller.java:229)
at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithoutRetries(RpcRetryingCaller.java:202)
at org.apache.hadoop.hbase.client.ClientScanner.call(ClientScanner.java:320)
at org.apache.hadoop.hbase.client.ClientScanner.nextScanner(ClientScanner.java:295)
at org.apache.hadoop.hbase.client.ClientScanner.initializeScannerInConstruction(ClientScanner.java:160)
at org.apache.hadoop.hbase.client.ClientScanner.<init>(ClientScanner.java:155)
at org.apache.hadoop.hbase.client.HTable.getScanner(HTable.java:811)
at org.apache.hadoop.hbase.MetaTableAccessor.fullScan(MetaTableAccessor.java:602)
at org.apache.hadoop.hbase.MetaTableAccessor.tableExists(MetaTableAccessor.java:366)
at org.apache.hadoop.hbase.client.HBaseAdmin.tableExists(HBaseAdmin.java:303)
at org.apache.hadoop.hbase.client.HBaseAdmin.tableExists(HBaseAdmin.java:313)
at com.twoBM.Tests.HBaseWriter.main(HBaseWriter.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.IllegalAccessError: tried to access method com.google.common.base.Stopwatch.<init>()V from class org.apache.hadoop.hbase.zookeeper.MetaTableLocator
at org.apache.hadoop.hbase.zookeeper.MetaTableLocator.blockUntilAvailable(MetaTableLocator.java:596)
at org.apache.hadoop.hbase.zookeeper.MetaTableLocator.blockUntilAvailable(MetaTableLocator.java:580)
at org.apache.hadoop.hbase.zookeeper.MetaTableLocator.blockUntilAvailable(MetaTableLocator.java:559)
at org.apache.hadoop.hbase.client.ZooKeeperRegistry.getMetaRegionLocation(ZooKeeperRegistry.java:61)
at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.locateMeta(ConnectionManager.java:1185)
at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.locateRegion(ConnectionManager.java:1152)
at org.apache.hadoop.hbase.client.RpcRetryingCallerWithReadReplicas.getRegionLocations(RpcRetryingCallerWithReadReplicas.java:300)
at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas.call(ScannerCallableWithReplicas.java:153)
at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas.call(ScannerCallableWithReplicas.java:61)
at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithoutRetries(RpcRetryingCaller.java:200)
... 15 more

I am using Gradle to build my project and currently I am only using the two following dependencies:
compile 'org.apache.hive:hive-jdbc:2.1.0'
compile 'org.apache.hbase:hbase:1.1.6'

Does anyone know to fix this problem? I have tried googling this problem, but without any of the found links providing an actual solution.
Best regards

A: This is definitely Google Guava's dependency conflict. The default constructor of Stopwatch class became private since Guava v.17 and marked deprecated even earlier.
So to HBase Java client works properly you need Guava v.16 or earlier. Check the way you build your application (Maven/Gradle/Classpath) and find the dependency which uses Guava v.17+. After that, you can resolve the conflict.

A: I received the same error and had to spend for 5 days to know the issue.
I added following dependency and its gone.
<dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>15.0</version>
</dependency>

A: You can use maven shade plugin to solve this issue. That a look at this blog post. Here is an example (actually a snippet from my working pom.)
  <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.0.0</version>
            <executions>
                <execution>
                    <id>assemble-all</id>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <!--<finalName>PROJECT_NAME-${project.version}-shaded</finalName>-->
                        <relocations>
                            <relocation>
                                <pattern>com.google.common</pattern>
                                <shadedPattern>shaded.com.google.common</shadedPattern>
                            </relocation>
                            <relocation>
                                <pattern>com.google.protobuf</pattern>
                                <shadedPattern>shaded.com.google.protobuf</shadedPattern>
                            </relocation>
                        </relocations>
                        <artifactSet>
                            <includes>
                                <include>*:*</include>
                            </includes>
                        </artifactSet>
                    </configuration>
                </execution>
            </executions>
        </plugin>


Q: Trying to use hashmap to count frequency of words in array This is my code:
public static void main(String args[]) throws Exception
{
    BufferedReader infile = new BufferedReader(new FileReader(args[0]));
    HashMap<String,Integer> histogram = new HashMap<String,Integer>();
    while ( infile.ready() )
    {
        String SPACE = " ";
        String [] words = infile.readLine().split(SPACE);

        for (String word : words)
        {
            Integer f = histogram.get(word);
            histogram.put(word,f+1);
        }
    }
    infile.close();
    printHistogram( histogram );
}
private static void printHistogram( HashMap<String,Integer> hm )
{
    System.out.println(hm);
}

I keep getting a NullPointerException for the " histogram.put(word,f+1);" part. why is this?

A: This happens because f will be null if the value is not found in the map.  Try this, inside the for loop.
Integer f = histogram.get(word);
if (f == null) {
    histogram.put(word, 1);
} else {
    histogram.put(word, f+1);
}


Q: No "Location" header in JMeter for Auth 2.0 Auth 2.0.
"code" parameter is required to perform
POST /.../oauth2/v2.0/token
with code value.
In Fiddler code value could be found in Location header of response to /kmsi request:

However, here is no Location header in JMeter for the same request:

Why? Are there any tip to get Location header in JMeter too?

A: If you're seeing different response it means that

*

*Either you're sending a different request. In this case inspect request details from JMeter and from the real browser using a 3rd-party sniffer tool like Fiddler or Burp, identify the inconsistencies and amend your JMeter configuration so it would send exactly the same request as the real browser does (apart from dynamic values which need to be correlated)

*Or one of the previous requests fails somewhere somehow, JMeter automatically treats HTTP responses with status codes below 400 as successful, it might be the case they are not really successful, i.e. you're continuously hitting the login page (you can check it by inspecting response data tab of the View Results Tree listener). Try adding a Response Assertions to the HTTP Request samplers so there will be another layer of explicit checks of the response data, this way you will get confidence that JMeter is doing what it is supposed to be doing.


Q: Text file with columns and records, analyze Python I have text file with some columns and records(<1000 records).

Name Surname Age Grade Faculty
Chris M 20 5 Electronics
Jack A 22 3 Computer science
Michael J 21 4 Computer science
...

Now I want type a functions with dicitionary.

*

*1) Show students names with 22 age .

*2) Show students of Electronics.

Example 1)
'Chris': 20,
My code:
a = {}
with open("file.txt") as f:
    for line in f:
       k,v = line.split(' ') #spacebar in file
       a[k.strip()] = v.strip()

But of course not working because I have not idea.
What would be the best way to do this in Python?
Thanks in advance.

A: The easiest way is Pandas. Read data from file into DataFrame:
import pandas as pd
df = pd.read_csv('file.txt', sep=' ')

1) Show students names with 22 age.
result = df[df['Age'] == 22]

2) Show students of Electronics.
result = df[df['Faculty'] == 'Electronics']

A: I can give you a hint on building a dictionary:
a = []
with open("file.txt") as f:
    keys = f.readline().strip().split(' ', 4)
    for line in f:
       val = line.strip().split(' ', 4) # spacebar in file
       a.append(dict(zip(keys, val)))

Now a contains a list of dictionaries like this one:
{'Name': 'Chris',
 'Surname': 'M',
 'Age': '20',
 'Grade': '5',
 'Faculty': 'Electronics'
}


Q: r-value Reference Casting and Temporary Materialization The output for the code below produces:
void doit(const T1 &, const T2 &) [T1 = unsigned long, T2 = int]
t1 == t2
t1 == (T1)t2
t1 != (T1&)t2
t1 == (T1&&)t2

I understand that the t1 == t2 case is simply an integral promotion.
The second case t1 == (T1)t2 is the same thing, just explicit.
The third case t1 == (T1&)t2 must be a reinterpret_cast of some sort... Though, further explanation would be helpful.
The fourth case t1 == (T1&&)t2 is what I am stuck on. I put in the term 'Temporary Materialization' in the question's title as this is the closest I could come to some sort of answer.
Could someone go over these four cases?
Code:
#include <iostream>

template <typename T1, typename T2>
void doit(const T1& t1, const T2& t2) {
  std::cout << __PRETTY_FUNCTION__ << '\n';

  if (t1 == t2) {
    std::cout << "t1 == t2" << '\n';
  }
  else {
    std::cout << "t1 != t2" << '\n';
  }

  if (t1 == (T1)t2) {
    std::cout << "t1 == (T1)t2" << '\n';
  }
  else {
    std::cout << "t1 != (T1)t2" << '\n';
  }

  if (t1 == (T1&)t2) {
    std::cout << "t1 == (T1&)t2" << '\n';
  }
  else {
    std::cout << "t1 != (T1&)t2" << '\n';
  }

  if (t1 == (T1&&)t2) {
    std::cout << "t1 == (T1&&)t2" << '\n';
  }
  else {
    std::cout << "t1 != (T1&&)t2" << '\n';
  }
}

int main() {
  const unsigned long a = 1;
  const int b = 1;

  doit(a, b);

  return 0;
}

A: The compiler attempts to interpret c-style casts as c++-style casts, in the following order (see cppreference for full details):

*

*const_cast

*static_cast

*static_cast followed by const_cast

*reinterpret_cast

*reinterpret_cast followed by const_cast

Interpretation of (T1)t2 is pretty straightforward.  const_cast fails, but static_cast works, so it's interpreted as static_cast<T1>(t2) (#2 above).
For (T1&)t2, it's impossible to convert an int& to unsigned long& via static_cast.  Both const_cast and static_cast fail, so reinterpret_cast is ultimately used, giving reinterpret_cast<T1&>(t2).  To be precise, #5 above, since t2 is const: const_cast<T1&>(reinterpret_cast<const T1&>(t2)).
EDIT: The static_cast for (T1&)t2 fails due to a key line in cppreference:  "If the cast can be interpreted in more than one way as static_cast followed by a const_cast, it cannot be compiled.".  Implicit conversions are involved, and all of the following are valid (I assume the following overloads exist, at a minimum):

*

*T1 c1 = t2; const_cast<T1&>(static_cast<const T1&>(c1))

*const T1& c1 = t2; const_cast<T1&>(static_cast<const T1&>(c1))

*T1&& c1 = t2; const_cast<T1&>(static_cast<const T1&>(std::move(c1)))
Note that the actual expression, t1 == (T1&)t2, leads to undefined behavior, as Swift pointed out (assuming sizeof(int) != sizeof(unsigned long)).  An address that holds an int is being treated (reinterpreted) as holding an unsigned long.  Swap the order of definition of a and b in main(), and the result will change to be equal (on x86 systems with gcc).  This is the only case that has undefined behavior, due to a bad reinterpret_cast.  Other cases are well defined, with results that are platform specific.
For (T1&&)t2, the conversion is from an int (lvalue) to an unsigned long (xvalue).  An xvalue is essentially an lvalue that is "moveable;" it is not a reference.  The conversion is static_cast<T1&&>(t2) (#2 above).  The conversion is equivalent to std::move((T1)t2), or std:move(static_cast<T1>(t2)).  When writing code, use std:move(static_cast<T1>(t2)) instead of static_cast<T1&&>(t2), as the intent is much more clear.
This example shows why c++-style casts should be used instead of c-style casts. Code intent is clear with c++-style casts, as the correct cast is explicitly specified by the developer.  With c-style casts, the actual cast is selected by the compiler, and may lead to surprising results.

A: Let's look at (T1&&)t2 first. This is indeed a temporary materialization; what happens is that the compiler performs lvalue-to-rvalue conversion on t2 (i.e. accesses its value), casts that value to T1, constructs a temporary of type T1 (with value 1, since that is the value of b and is a valid value of type T1), and binds it to an rvalue reference.  Then, in the comparison t1 == (T1&&)t2, both sides are again subject to lvalue-to-rvalue conversion, and since this is valid (both refer to an object of type T1 within its lifetime, the left hand side to a and the right hand side to the temporary) and both sides have value 1, they compare equal.
Note that a materialized temporary of type T1 (say) can bind either to a reference T1&& or T1 const&, so you could try the latter as well in your program.
Also note that while the T1 converted from t2 is a temporary, it would be lifetime extended if you bound it to a local variable (e.g. T1&& r2 = (T1&&)t2;). That would extend the lifetime of the temporary to that of the local reference variable, i.e. to the end of the scope.  This is important when considering the "with its lifetime" rule, but here the temporary is destroyed at the end of the expression, which is still after it is accessed by the == comparison.
Next, (T1&)t2 should be interpreted as a static_cast reference binding to a temporary T1 followed by a const_cast; that is, const_cast<T1&>(static_cast<T1 const&>(t2)).  The first (inner) cast materializes a temporary T1 with value converted from t2 and binds it to a T1 const& reference, and the second (outer) cast casts away const.  Then, the == comparison performs lvalue-to-rvalue conversion on t1 and on the T1& reference; both of these are valid since both refer to an object of type T1 within its lifetime, and since both have value 1 they should compare equal. (Interestingly, the materialized temporary is also a candidate for lifetime extension, but that doesn't matter here.)
However, all major compilers currently fail to spot that they should do the above (Why is (int&)0 ill-formed? Why does this C-style cast not consider static_cast followed by const_cast?) and instead perform a reinterpret_cast (actually a reinterpret_cast to T1 const& followed by a const_cast to T1&). This has undefined behavior (since unsigned long and int are distinct types that are not related by signedness and are not types that can access raw memory), and on platforms where they are different sizes (e.g. Linux) will result in reading stack garbage after b and thus usually print that they are unequal.  On Windows, where unsigned long and int are the same size, it will print that they are equal for the wrong reason, which will nevertheless be undefined behavior.

A: Technically all four variants are platform dependent
t1 == t2
t2 gets promoted to 'long', the casted to unsigned long.
t1 == (T1)t2
signed int gets converted to its representation as unsigned long, in order being casted to long first. There were debates if this must be considered an UB or not, because result is depending on platform, I honestly not sure how it is defined now, aside from clause in C99 standard. Result of comparison would be same as t1 == t2.
t1 == (T1&)t2
The cast result is a reference, you compare reference ( essentially a pointer) to T1, which operation yields unknown result. Why? Reference js pointing to a different type.
t1 == (T1&&)t2
The cast expression yields an rvalue, so you do compare values, but its type is rvalue reference. Result of comparison would be same as t1 == t2.
PS.
Funny thing happen (depends on platform, essentially an UB) if if you use such values:
  const unsigned long a = 0xFFFFFFFFFFFFFFFF;
  const int b = -1;

Output might be:
t1 == t2
t1 == (T1)t2
t1 == (T1&)t2
t1 == (T1&&)t2

This is one of reasons why you should be careful in comparing unsigned to signed values, especially with < or >. You'll be surprised by -1 being greater than 1.
if unsigned long is 64bit int and pointer is equal to 64-bit int. -1 if casted to unsigned, becomes its binary representation. Essentially b would become a pointer with address 0xFFFFFFFFFFFFFFFF.


Q: how to make an operation wait until the other operation finish in swift I'm working on an application which fetches data from api's
I'm using alamofire to fetch data
my question is how could I make an application wait until the data fetching finish
I'm using following code to fetch data
class abc:NSOperation{

static let sharedInstance = abc()

func main() {

    Alamofire.request(.GET, "http://playground.dzireinfotech.com/admin/event/getallevents", parameters: nil).response{
        (request, response, data, error) in

        if(error == nil){
            let jsn = JSON(data: data!)

            if let nn = jsn.array{
                let a = nn.count
                print("a\(a)")
                for(var i=0; i<a; i++){
                    self.e_Id.append(jsn[i]["e_id"].string!)
                    self.e_date.append(jsn[i]["e_date"].string!)
                    self.e_time.append(jsn[i]["e_time"].string!)
                    self.e_title.append(jsn[i]["e_title"].string!)
                    self.e_image.append(jsn[i]["e_image"].string!)
                    self.e_description.append(jsn[i]["e_description"].string!)
                    self.e_num_table.append(jsn[i]["e_num_table"].string!)

                    self.imgx.append(self.ImgURL + (jsn[i]["e_image"].string!))
                    // self.e_latitude.append(jsn[i]["e_latitude"].string!)
                    // self.e_longitude.append(jsn[i]["e_longitude"].string!)
                    //self.e_status.append(jsn[i]["e_status"].string!)
                }

            }

            if(self.imgx.count>0){
                FirstViewController.sharedInstance.loadData(self)
            }

        }else{
            print("Error")
        }
    }
}

The above code works fine but it gives problem in following code
class pqr: UIViewController{

  override func viewDidLoad() {

    super.viewDidLoad()

    abc.sharedInstance.main()
    //I want to make wait here
    imageUrls = abc.sharedInstance.imgx
    let ab =  abc.sharedInstance.img_number
    print("ImageUrl\(imageUrls)")
    print("Image Number\(ab)")
    let urlx:NSURL = NSURL(string: imageUrls[ab])!
    self.imageView.sd_setImageWithURL(urlx)
  }
}

A: Move all the code in viewDidLoad that depends on the long running operation to another method and then call that method in the completion handler of the long-running process.

A: You could put all of this code into your viewdidload so that the app won't open until that code is finished running.
Are you trying to make it so the app stays on the launch screen until the the data has been fetched.
If I am correct you should just put the code in the viewdidload function it should say.
View did appear and then in the put the code correct me if I am wrong I am new to this.
Can you share the top of your code.


Q: Process functions from a list of strings in Python I have a module that I import to my main application called pageprocs.py with a collection of functions in it that generate different content and return it in a string. pageprocs is supposed to be a way of allowing authenticated users to create plugins for the different content type.
I then have a list of strings: ['check_stats', 'build_table', 'build_ace'] which are the names of some functions in pageprocs. I need to execute the functions in the order they are in the list and can't find a way of doing this without using exec():
for i in list_of_funcs:
    exec('pageprocs.%s()' % i)

This just seems like a seriously bad idea to me and not easy to catch any exceptions in users code. Is there an alternative to running code this way or does anybody have suggestions on user-defined content generation (I ask this because I maybe approaching the whole situation wrong).

A: for i in list_of_stats:
    getattr(pageprocs, i, lambda: None)()

The lambda: None part is optional, but will prevent AttributeError being raised if the specified function doesn't exist (it's an anonymous do-nothing function).


Q: Removing duplicates from a list of lists based on a comparison of an element of the inner lists I have a large list of lists and need to remove duplicate elements based on specific criteria:

*

*Uniqueness is determined by the first element of the lists.

*Removal of duplicates is determined by comparing the value of the second element of the duplicate lists, namely keep the list with the lowest second element.

[[1, 4, 5], [1, 3, 4], [1, 2, 3]]
All the above lists are considered duplicates since their first elements are equal. The third list needs to be kept since it's second element is the smallest. Note the actual list of lists has over 4 million elements, is double sorted and ordering needs to be preserved.
The list is first sorted based on the second element of the inner lists and in reverse (descending) order, followed by normal (ascending) order based on the first element:
sorted(sorted(the_list, key=itemgetter(1), reverse=True), key=itemgetter(0))

An example of three duplicate lists in their actual ordering:
[...
[33554432, 50331647, 1695008306],
[33554432, 34603007, 1904606324],
[33554432, 33554687, 2208089473],
...]

The goal is to prepare the list for bisect searching. Can someone provide me with insight on how this might be achieved using Python?

A: You can group the elements using a dict, always keeping the sublist with the smaller second element:
l = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [2, 4, 3], [2, 5, 6], [2, 1, 3]]
d = {}
for sub in l:
    k = sub[0]
    if k not in d or sub[1] < d[k][1]:
        d[k] = sub

Also you can pass two keys to sorted, you don't need to call sorted twice:
In [3]:  l = [[1,4,6,2],[2,2,4,6],[1,2,4,5]]
In [4]: sorted(l,key=lambda x: (-x[1],x[0]))
Out[4]: [[1, 4, 6, 2], [1, 2, 4, 5], [2, 2, 4, 6]]

If you wanted to maintain order in the dict as per ordering needs to be preserved.:
from collections import OrderedDict

l = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [2, 4, 3], [2, 5, 6], [2, 1, 3]]
d = OrderedDict()
for sub in l:
    k = sub[0]
    if k not in d or sub[1] < d[k][1]:
        d[sub[0]] = sub

But not sure how that fits as you are sorting the data after so you will lose any order.
What you may find very useful is a sortedcontainers.sorteddict:

A SortedDict provides the same methods as a dict. Additionally, a SortedDict efficiently maintains its keys in sorted order. Consequently, the keys method will return the keys in sorted order, the popitem method will remove the item with the highest key, etc.
An optional key argument defines a callable that, like the key argument to Python’s sorted function, extracts a comparison key from each dict key. If no function is specified, the default compares the dict keys directly. The key argument must be provided as a positional argument and must come before all other arguments.

from sortedcontainers import SortedDict

l = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [2, 4, 3], [2, 5, 6], [2, 1, 3]]
d = SortedDict()
for sub in l:
    k = sub[0]
    if k not in d or sub[1] < d[k][1]:
        d[k] = sub

print(list(d.values()))

It has all the methods you want bisect, bisect_left etc..

A: If I got it correctly, the solution might be like this:
mylist = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [7, 3, 6], [7, 1, 8]]

ordering = []
newdata = {}

for a, b, c in mylist:
    if a in newdata:
        if b < newdata[a][1]:
            newdata[a] = [a, b, c]
    else:
        newdata[a] = [a, b, c]
        ordering.append(a)

newlist = [newdata[v] for v in ordering]

So in newlist we will receive reduced list of [[1, 2, 3], [7, 1, 8]].


Q: Downloading files from expressJS (sendFile) server to VueJS, is returning corrupted files? I have an API written in expressjs, that sends a file when provided with a fileID.
The backend is working fine, as it sends the correct file (uncorrupted) when the route url is typed directly int the browser.
ex. http://localhost:8080/download?id=1234 (downloads all files just fine ie.txt, xlsx, jpg, zip)
My express route actually uses res.download, which is really jsut a wrapper for sendFile.
When I try calling these route urls from a Vue http get request, it only returns txt files uncorrupted. All other files download, but they can be opened, due to corruption.
Can anyone please point me in the right direction as to why its not working in Vue?
For clarity, "item" is passed as an argument to this function.
        this.$http.get("http://localhost:8000/files/download", {params:{id:item._id}}, {responseType: 'arraybuffer'})
      .then(response => {

        var blob = new Blob([response.data], {type:response.headers.get('content-type')});

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = item.filename;
        link.click();
      })

For reference, this is my express route

A: Shout out to @Helpinghand for helping me troubleshoot this.
"I found the solution within the link you posted. The problem is that i was explicitly sending params in its own object before assigning "content-type". The example you posted concatenates the query params to the url. After making this switch, its working perfectly".
this.$http.get(`http://localhost:8000/files/download?id=${item._id}`, {responseType: 'arraybuffer'})
      .then(response => {
        console.log(response.headers.get('content-type'));
        console.log(response);

        var blob = new Blob([response.body], {type:response.headers.get('content-type')});

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = item.filename_version;
        link.click();
      })


Q: Continuous subset and ranking using sql I have a dataset like below:

Now, I need the output as below:
start_time  end_time    count
10:01   10:04   3
10:05   10:07   2

For this purpose, I wrote a query but it is not giving me the desired sequence. My query is as below:
with on_off as
(
select  time,status,case when status!=lag(status) over(order by time) then 1 else 0 end as continuous_count
  from time_status
)
,
grp as
(
  select *, row_number() over(partition by continuous_count order by time) rnk from  on_off
)
select * from grp order by time

It generates the output as below:

But in the rank section I need something as below:

So, what exactly am I doing wrong here?
Here are the PostgresSQL DDLs:
create table time_status(time varchar(10)  null, status varchar(10) null);

INSERT into  time_status(time,status) values('10:01','ON');
INSERT into  time_status(time,status) values('10:02','ON');
INSERT into  time_status(time,status) values('10:03','ON');
INSERT into  time_status(time,status) values('10:04','OFF');
INSERT into  time_status(time,status) values('10:05','ON');
INSERT into  time_status(time,status) values('10:06','ON');
INSERT into  time_status(time,status) values('10:07','OFF');

A: Try this query:
SELECT min(time) as start_time,
       max(time) as end_time,
       sum(case when status = 'ON' then 1 else 0 end) as cnt
  FROM (SELECT time, status,
               sum(case when status = 'OFF' then 1 else 0 end)
                 over (order by time desc) as grp
          FROM time_status) _
 GROUP BY grp
 ORDER BY min(time);

->Fiddle


Q: load a url after a specific amount of time I have a single url that I need to open it after a specific amount of time.
I think this can be done using js/jquery and I see it working like this: I open the page created with the js code inside and the url loads automatic in a new tab and after 5 minutes this same url is opened in a new tab or in the same tab that was previously opened.
It's a trick I am working on and the problem is that I don't know much in js/jquery that's why I need your help.
You might ask me: Hey, this code will open a new tab each 5 minutes so you'll have a lot of them running, are you sure you need this?.. and I say yes, that's what I need, a new tab for a single url each 5 minutes.
Thanks.

A: You could use setTimeout() which will wait a specified amount of time (ms) then execute the declared function.
Example:
setTimeout(openUrl, 5000); // Wait 5 seconds

function openUrl(){

   window.open('http://google.com');

}

To repeat an action on a timer you can use setInterval()
setInterval(openUrl, 5000);

A: check out the setTimeout and setInterval methods for JS
http://www.w3schools.com/js/js_timing.asp
http://www.w3schools.com/jsref/met_win_setinterval.asp

A: You need to call settimeout inside openUrl again to repeat it endlessly


Q: How to use parameters for lambda expressions correctly in C#? I was wondering, if I use Lambda expressions correctly in the following short code snippet? I want to store function calls over time and then execute them all together in Update_Calls(). Most importantly, I am asking whether the parameters var1-3 keep their value (the value they had when calling Extern_Func()) in ANY case?
static List<Action> callsForUpdate = new List<Action>();

public static void Extern_Func(int var1, int var2, float var3)
{
  Action callToStore = () => Func(var1, var2, var3);

  // Remember in call list
  callsForUpdate.Add(callToStore);
}

public static void Update_Calls()
{
  for (int i = 0; i < callsForUpdate.Count; i++)
  {
  callsForUpdate.ElementAt(i);
  }

  callsForUpdate.Clear();
}

A: Yes. They will be retained. Your Update_Calls has an issue.
    public static void Update_Calls()
    {
        for (int i = 0; i < callsForUpdate.Count; i++)
        {
            callsForUpdate.ElementAt(i)();
        }

        callsForUpdate.Clear();
    }

You were only referring the element. Not calling it.

A: What you are creating is called Closure, which means that Action will be called with the current values of var1, var2, var3, in this case they are local variables of Extern_Func, so unless you change them in that method (Extern_Func) they will keep their value.

A: What you are doing is creating an expression pointed to by each item in the callsForUpdate list. Expressions are immutable. In order to change the values you supplied in an expression, the expression must be replaced by a new expression with new values.
In my best estimation of what you are asking is true for most any case because your list is simply a list of expressions to be executed with the values supplied at the time they were created by Etern_Func.

A: Closures capture variables, not values. Make sure that is clear.
In your case, var1, var2 and var3 are passed by value arguments that can only be changed locally. Therefore if you don't change them inside Extern_Func you are good to go.
To understand the difference between capturing values or variables, consider the following snippet:
var funcs = new List<Action>();

for (var i = 0; i < 5; i++)
{
    var temp = i;
    funcs.Add(() => Console.WriteLine(i));
    funcs.Add(() => Console.WriteLine(temp));
}

foreach (var f in funcs)
{
    f();
}

Can you guess the output?


Q: jquery image slider auto play and click Please suggest any change where i need to make in this code in order to make this slider auto play after 4000 milliseconds.right not it is working fine on click.i made few changes after following few suggestions but its not working
<script type="text/javascript">
$(function() {
var Page = (function() {
var $navArrows = $( '#nav-arrows' ),
$nav = $( '#nav-dots > span' ),
slitslider = $( '#slider' ).slitslider( {
onBeforeChange : function( slide, pos ) {

$nav.removeClass( 'nav-dot-current' );
$nav.eq( pos ).addClass( 'nav-dot-current' );
}
} ),
init = function() {
initEvents();
},
initEvents = function() {
// add navigation events
$navArrows.children( ':last' ).on( 'click', function() {
slitslider.next();
return false;
} );
$navArrows.children( ':first' ).on( 'click', function() {
slitslider.previous();
return false;
} );
$nav.each( function( i ) {
$( this ).on( 'click', function( event ) {
    var $dot = $( this );
    if( !slitslider.isActive() ) {
            $nav.removeClass( 'nav-dot-current' );
            $dot.addClass( 'nav-dot-current' );
    }
    slitslider.jump( i + 1 );
    return false;
} );
} );
};
return { init : init };
})();
Page.init();
});
</script>

A: Just looking at the slitslider docs I think you need to add these two lines to the following excerpt of your code:
.slitslider({

    // slideshow on / off
    autoplay : true,
    // time between transitions
    interval : 4000,

    onBeforeChange : function(slide, pos) {
    $nav.removeClass('nav-dot-current');
    $nav.eq(pos).addClass('nav-dot-current');
    }


Q: Reject a transition based on user input, without confirm() EmberJS: reject an upcoming transition
How would I reject an upcoming transition via willTransition, but using a custom pop up or jQuery .dialog box such as this:
willTransition: function(transition) {
    //Some conditional logic would go here to determine if they need to be prompted to save
    $("#confirmTransition").dialog({
        resizable: false,
        modal: true,
        draggable: false,
        buttons: {
            "Yes": function() {
                self.transitionTo(transition.targetName);
                $(this).dialog( "close" );
            },
            "No": function() {
                transition.abort();
                $(this).dialog( "close" );
            }
        }
    });
}

Rather than using confirm() which would actually wait until the user enters something. I can use a .then, but it fires after the transition completes. Would I be better off using beforeModel on all routes to handle a conditional abort, and then rely on willTransition to provide the popup to confirm?
Updated per accepted question:
willTransition: function(transition) {
    //Some conditional logic would go here to determine if they need to be prompted to save
    var self = this;
    if(!self._transitioning){
        $("#confirmTransition").dialog({
            resizable: false,
            modal: true,
            draggable: false,
            buttons: {
                "Yes": function() {
                    self._transitioning = true;
                    transition.retry().then(self._transitioning = false);
                    $(this).dialog( "close" );
                },
                "No": function() {
                    transition.abort();
                    $(this).dialog( "close" );
                }
            }
        });
    }
}

A: You could use the same approach to animate route transitions: You can take a look at the relatebase blog (as well as the jsbin example referred by the blog).
Essentially you handle a little state machine in the willTransition action: You abort the original transition and as soon as the user closes the dialog you retry the original transition.
Hope it helps!


Q: Do I need an iOS developer license for TestFlight I am going to be creating an iOS app to run on an iPad using the PhoneGap framework.  Instead of putting my app on the App Store I'm going to use TestFlight.  If I'm not going to be using the App Store do I still need to purchase an iOS developer license?

A: Yes, you need an iOS Developer Account in order to create the provisioning profiles and certificates you need for your app to actually run on a real device.

A: Yes, it is mandatory to have a certificate and provisioning profile to build your app for device. You have to enroll for developer program/enterprise developer program if you wish to install your app on a device. It does not matter if you choose to use TestFlight or not.


Q: jQuery error after setting anchor tag dynamically I am trying to set the href property of an anchor tag using jquery, by writing this code:
 myPage.URL != null ? $pages.find("#myPage").attr("href", myPage.URL.Url) : $pages.find("#myPage").attr("href", "#") ;

Where myPage object contains an object called URL 2 properties: Url and Description. If URL is not null, then for sure it will have a Url value.
After running this code, I try to click on the link, but it's giving this error:

jquery-1.11.3.min.js:2 Uncaught Error: Syntax error, unrecognized expression: http://yourlink.com(…)

Here's myPage object structure:
 pageType : "publishing",
 pageCategory: null
 Steps : null
 pageOwner: null
 audience: "All"
 audienceDescription: "description goes here for the audience"
 Title : "my page title"
 URL : Object
    > Description "any link goes here"
    > Url "http://google.com"

What am I doing wrong?
Thanks.

A: You need also to check if your object myPage.URL has the property Url then assign it :
if( myPage.URL != null )
     if( myPage.URL.hasOwnProperty("Url") )
           $pages.find("#myPage").attr("href", myPage.URL.Url);
     else
           $pages.find("#myPage").attr("href", "#")

Hope this helps.


Q: Populate second dropdown based on first dropdown using CodeIgniter I need to select first the source_type and then it automatically populate the location based on the source_type
view file
    <select name="source_type" id="source_type">
       <option value="">Source Type</option>
       <option value="Internal">Internal</option>
       <option value="External">External</option>
    </select>

    <select name="location" id="location">
       <option value="">Select</option>
    </select>

    $('#source_type').change(function(){
        $.ajax({
            type: 'post',
            data: 'source_type'+$(this).val(),
            url: 'get_sources_location',
            success: function(data) {
                $('#source_location').val(data);
            }
        });
    });

..controller
    public function get_sources_location()
    {
        $source_type = $this->input->post('source_type');

        $this->load->model('documents_model');
        $results = $this->documents_model->get_locations();
        echo $results;
    }

..model
    public function get_locations()
    {
     $query = $this
                ->db
                ->select('location')
                ->where('classification', $source_type = $this->input->post('source_type'))
                ->get('sources_location');

     $data = array();

     foreach ($query->result() as $row)
     {
         $data = $row->location;
     }
     return $data;
   }

A: try something like this
HTML CODE
<select name="source_type" id="source_type" onchange="populateLocation(this.value)">
   <option value="">Source Type</option>
   <option value="Internal">Internal</option>
   <option value="External">External</option>
</select>

<select name="location" id="location">
   <option value="">Select</option>
</select>

JAVASCRIPT CODE USING JQUERY
function populateLocation(source_type_value){
            if(source_type_value !=''){
                /*
                    Pass your source type value to controller function which will return you json for your
                    loaction dropdown
                */
                var url = 'controller/function/'+ source_type_value; //
                $.get(url, function(data) {
                 var $select = $('location');
                 // removing all previously filled option
                 $select.empty();
                 for (var propt in data) {
                        $select.append($('<option />', {
                            value: propt,
                            text: data[propt]
                        }));
                 }

            }
        }

JSON FORMAT to be returned from controller
{"":"Select","1":"New york","2":"London","3":"Mumbai"}

A: Put an AJAX Function like this,
$("#source_type").change(function(){

  $.ajax({
     type : 'POST',
     data : 'source_id='+ $(this).val(),
     url : 'controller/method',
     success : function(data){
                 $('#location').val(data);
     }
 });
});

In controller, put a method to get the values,
public function getLocations() {

     $source_id = $this->input->post('source_id');

     // Call the model function and get all the locations based on the source type id

     // Populate the dropdown options here

     echo $result;
}

A: attach a change event handler to your first DD and send an ajax call to the server to fetch data. In the success callback of the ajax call populate the second DD. Below is a simple proof of concept
$("#source_type").change(function(e)
{
    $.ajax({
        url:'/echo/json',
        success:function(data){
            console.log("success");
            $("<option/>",{text:'google',value:'google'}).appendTo("#location");
        }
    });

DEMO


Q: Will I get a postback each month when using subscriptions? I am using Google Wallet For Digital Goods.
Will I get a callback each month when money gets transferred or will the postback URL only get called once when setting up the subscription?

A: I'm afraid at this very moment Google Wallet only notifies the user when the subscription is cancelled.
I asked the same myself on google wallet for digital goods forum :
https://groups.google.com/forum/?fromgroups=#!topic/in-app-payments/YFaCBDwaF9g
See the 2nd answer from Mihai Ionescu from Google
EDIT: As suggested by Qix below, I'm quoting the answer given by Google below:

*

*After the subscription is setup, you will receive a postback only when the subscription is cancelled:
  https://developers.google.com/in-app-payments/docs/subscriptions#6

*Currently the merchant can cancel or refund a subscription from the Merchant Center. We are working on adding API support for
  cancellations and refunds.

Please note that the forum entry is from late 2012, however as of May 2014 things doesn't seem to have changed much, as Google still postbacks only for Subscription Cancellations


Q: Enctype issue when I try to upload a file with a Coldfusion webservice Can't get to work a Coldfusion webservice that uploads a file in an external server.
My application runs in "Server A" and the file repository (external server) is in "Server B"
The template (inicio.cfm) which contains the form with the <cfinput type="file"> to select the client's file to be uploaded, is stored in "Server A". This template performs more tasks than just show the upload form. It performs calculations, queries, etc. outside the form's code block. Also, the action page of this form is the template itself (because of my application's needed tasks).
The first code line of my form definition is (inside inicio.cfm):
<cfform method="post" name="AltaConvocatoria" enctype="multipart/form-data">

Which demonstrate that I'm using the right enctype definition.
In the other hand, stored in "Server B" is my Coldfusion component or webservice (alta_ga.cfc) which only task is to upload the file selected by user in "inicio.cfm" form and rename it.
Here's alta_ga.cfc code:
<cfcomponent>

    <cffunction access="remote" returntype="void" name="cargaAnuncio">

        <cfargument name="destinoAnuncio" required="yes" type="string">

        <cfargument name="PrefijoNvoNombre" required="yes" type="string">

        <cffile action="upload"
        fileField="str_ArchivoAnuncio"
        destination="#destinoAnuncio#"
        nameconflict="Overwrite">
        <cfset NvoNomAnuncio = #PrefijoNvoNombre# & #Right(cffile.ClientFile, 5)#>

        <cfset viejoNombre1 = #destinoAnuncio# & #cffile.ClientFile#>

        <cffile
        action = "rename"
        destination = "#NvoNomAnuncio#"
        source = "#viejoNombre1#">

    </cffunction>

</cfcomponent>

For that pupose, I invoke the webservice from the form's action code block in inicio.cfm with this:
<cfinvoke webservice="http://192.168.208.128/podi/mgmt/alta_ga.cfc?wsdl" method="cargaAnuncio" >
    <cfinvokeargument name="destinoAnuncio" value="#form.destinoAnuncio#" />
    <cfinvokeargument name="PrefijoNvoNombre" value="#form.PrefijoNvoNombre#" />
</cfinvoke>

When I try to load a file using my form's template inicio.cfm I get this message:
Cannot perform web service invocation cargaAnuncio.
The fault returned when invoking the web service operation is:
'' podi.mgmt.PodiMgmtAlta_gaCfcCFCInvocationExceptionException: coldfusion.tagext.io.FileUtils$CFFileNonMultipartException : Invalid content type: application/soap+xml; charset=UTF-8; action="urn:cargaAnuncio".The files upload action requires forms to use enctype="multipart/form-data".]
All the arguments and variables that I'm using are correct, because I tested the webservice as a local component (stored in Server A and uploading the file in the same server) and worked fine. Here's the code of the succesful test (invoked as a component instead of a webservice):
<cfinvoke component="alta_ga" method="cargaAnuncio" destinoAnuncio="#form.destinoAnuncio#" PrefijoNvoNombre="#form.PrefijoNvoNombre#">

¿What could be wrong?
There's a lack of documentation about this functionality. Adobe's user guide doesn't explain this functionality in depht. Ben Forta's books... same. Or I couldn't find the information.
Thanks in advance.

A: When a form is posted to a CFML server, the posted file is saved in a temporary directory before any of your code runs. All <cffile action="upload"> does is to copy a file from that temporary directory to the location you want it to be. Your remote server ServerB has no idea about any file posted on ServerA, so <cffile action="upload"> will not help you.
The action is misleading. It's not upload-ing anything. It's just copying from a predetermined temp directory. The web server handles the uploading before the CF server is even involved.
You will likely need to <cffile action="upload"> on ServerA to a specific place, and then it needs to post that file to your web service on ServerB. Then ServerB should be able to use <cffile action="upload"> to transfer it from the upload temp directory to wherever you need it to be. That said I have never tried this when posting to a web service.
Alternatively you could just post the file directly to ServerB in the first place, to save needing ServerA to be an intermediary. This might not be possible, of course.


Q: How to update a table using cursor I need to write a procedure to update a column of a table Xyz if today date is between the start_date and end_date of table ABC.
table ABC

    fin_cycle    start_date   end_date    account_class
    ----------------------------------------------------

    F2018        27-05-2020    29-05-20    2003

table xyz
account_no    account_class  ac_no_dr

1234           2003             Y

when I run the procedure today and if today's date is between start_date and end date of table ABC then the procedure will update column ac_no_dr as Y, else it will update the column as N. I have prepared this skeleton.
Create Or Replace PROCEDURE pr_no_debit
     Cursor c_Today(start_date, end_Date) is
     Select Today from sttm_branch  where today between start_Date and end_Date;

   l_No_Debit_List   ABC%ROW_TYPE;
   Begin

     For c_Today(l_No_Debit_List.start_Date,l_No_Debit_List.end_Date) Loop

       Update XYZ set ac_no_DR='Y' where account_class=l_No_Debit_List.account_class;

   End Loop;

     -- At the end of the period Change No_Debit to 'N'

   End pr_no_debit;

A: Here's one option: merge. (Today is 27.05.2020 which is between start and end date stored in the abc table).
Sample data:
SQL> select * From abc;

FIN_C START_DATE END_DATE   ACCOUNT_CLASS
----- ---------- ---------- -------------
F2018 27.05.2020 29.05.2020          2003

SQL> select * From xyz;

ACCOUNT_NO ACCOUNT_CLASS A
---------- ------------- -
      1234          2003

Merge statement:
SQL> merge into xyz a
  2    using (select account_class,
  3                  case when sysdate between start_date and end_date then 'Y'
  4                       else 'N'
  5                  end ac_no_dr
  6           from abc
  7          ) x
  8    on (a.account_class = x.account_class)
  9    when matched then update set a.ac_no_dr = x.ac_no_dr;

1 row merged.

Result:
SQL> select * From xyz;

ACCOUNT_NO ACCOUNT_CLASS A
---------- ------------- -
      1234          2003 Y

SQL>

The bottom line: you don't need a procedure nor a loop (which is inefficient) as everything can be done with a single SQL statement.

If - as you commented - has to be a procedure, no problem either:
create or replace procedure p_merge as
begin
  merge into xyz a
  using (select account_class,
                case when sysdate between start_date and end_date then 'Y'
                     else 'N'
                end ac_no_dr
         from abc
        ) x
  on (a.account_class = x.account_class)
  when matched then update set a.ac_no_dr = x.ac_no_dr;
end;
/


Q: How do you view HTML entities in Firefox Developer Edition's inspector Firefox Developer Edition was showing HTML entities (e.g.  ) in the DOM inspector. For some reason it stopped. I've created a fresh Firefox profile but I still can't see them. Anyone got any ideas how to view them in Firefox?

A: @luke-h I'm fairly certain it makes sense to piggyback https://bugzilla.mozilla.org/show_bug.cgi?id=1256756
I just did.


Q: Is binding events in jQuery very expensive, or very inexpensive? I just wrote a $().bind('event') function and then got concerned that this kind of a call might be very expensive if jQuery has to run through each element in the DOM to bind this event.
Or maybe, it's just about as efficient as an event could be. The jQuery docs I've read aren't making this clear. Any opinions?

A: There are two things that can make your event binding code slow: the selector and the # of bindings. The most critical of the two is the # of bindings, but the selector could impact your initial performance.
As far as selectors go, just make sure you don't use pure class name selectors like .myclass. If you know that the class of myclass will always be in a <div> element, make your selector be div.myclass as it will help jQuery find the matching elements faster. Also, don't take advantange of jQuery letting you give it huge selector strings. Everything it can do with string selectors it can also do through functions, and this is intentional, as it is (marginally, admittedly) faster to do it this way as jQuery doesn't have to sit around to parse your string to figure out what you want. So instead of doing $('#myform input:eq(2)'); you might do $('input','#myform').eq(2);. By specifying a context, we are also not making jQuery look anywhere it doesn't have to, which is much faster. More on this here.
As far as the amount of bindings: if you have a relatively medium-sized amount of elements then you should be fine - anything up to 200, 300 potential element matches will perform fine in modern browsers. If you have more than this you might want to instead look into Event Delegation.
What is Event Delegation? Essentially, when you run code like this:
$('div.test').click(function() {
    doSomething($(this));
});

jQuery is doing something like this behind the scenes (binding an event for each matched element):
$('div.test').each(function() {
    this.addEventListener('click', function() {
        doSomething(this);
    }, false);
});

This can get inefficient if you have a large amount of elements. With event delegation, you can cut down the amount of bindings done down to one. But how? The event object has a target property that lets you know what element the event acted on. So you could then do something like this:
$(document).click(function(e) {
    var $target = $(e.target);
    if($target.is('div.test')) { // the element clicked on is a DIV
                                 // with a class of test
       doSomething($target);
    }
});

Thankfully you don't actually have to code the above with jQuery. The live function, which is advertised as an easy way to bind events to elements that do not yet exist, is actually able to do this by using event delegation and checking at the time an action occurs if the target matches the selector you specify to it. This has the side effect, of course, of being very handy when speed is important.
The moral of the story? If you are concerned about the amount of bindings your script has just replace .bind with .live and make sure you have smart selectors.
Do note, however, that not all events are supported by .live. If you need something not supported by it, you can check out the livequery plugin, which is live on steroids.

A: Basically, you're not going to do any better.
All it is doing is calling attachEventListener() on each of your selected elements.
On parse time alone, this method is probably quicker than setting inlined event handlers on each element.
Generally, I would consider this to be a very inexpensive operation.


Q: Is there a function to select a group of hours from different days? I'm looking for a way to select in Amazon Athena a selection of hours for different days.
I have a table with visitors to a specific location for every half hour, I now want to know the visitors during opening hours for a store, for the period of a month.
I now used this but doing it day by day is quite a job.
Was trying to split datetime with Datepart but didn't get it working properly.
SELECT visitors, datetime
FROM corrected_scanners_per_half_hour
WHERE datetime
    BETWEEN CAST('2020-05-25 08:30:00' AS timestamp)
        AND CAST('2020-05-25 17:30:00' AS timestamp) ;

A: Here you go
select visitors, date(datetime)
from corrected_scanners_per_half_hour
where date_format(datetime, '%H:%i') between '08:30' and '17:30'


Q: Adding CURL as static library to a C++ CMake project I have a problem with adding CURL library to CMake project. In my CMakeList.txt I have the following lines for adding CURL:
    #option(CURL_STATICLIB "Set to ON to build libcurl with static linking."  ON)
if(WIN32)
    add_definitions("-DCURL_STATICLIB")
endif()
option(LIBCURL_ENABLE "Enable or disable the requirement of libcurl" ON)

if(LIBCURL_ENABLE)
    find_path(LCURL_INCLUDE_DIR
        NAMES
            curl.h
        PATHS
            /usr/include/curl
            ENV "PROGRAMFILES(X86)"
            ENV "LIBCURL_ROOT"
        PATH_SUFFIXES
            include)

    find_library(LCURL
        NAMES
            libcurl.a
            libcurl.lib
        PATHS
            /usr/lib/x86_64-linux-gnu
            /usr
        PATH_SUFFIXES
            lib
            lib/x86_64-linux-gnu)
    if(LCURL STREQUAL "LCURL-NOTFOUND")
        message(FATAL_ERROR "libcurl NOT found: use `-DLIBCURL_ENABLE=OFF` to build without libcurl support")
    else()
        set(LIBS ${LIBS} ${LCURL})
        include_directories(AFTER ${LCURL_INCLUDE_DIR})
    endif()
else()
    add_definitions("-DCONF_NO_LIBCURL")
endif()
...

if(LIBCURL_ENABLE)
    target_link_libraries(app ${ZLIB_LIBRARIES} ${LCURL})
endif()

Everything is okay on Windows. But on Linux, I got this message from the make install command:
/usr/bin/ld: /usr/lib/x86_64-linux-gnu/libcurl.a(libcurl_la-content_encoding.o): undefined reference to symbol 'inflateInit2_'
/usr/lib/x86_64-linux-gnu/libz.so: error adding symbols: DSO missing from command line

A: The compilation was resolved with the following replacement.
#option(CURL_STATICLIB "Set to ON to build libcurl with static linking."  ON)
if(WIN32)
    add_definitions("-DCURL_STATICLIB")
endif()
set(CURL_LIBRARY "-lcurl")
find_package(CURL REQUIRED)
include_directories(${CURL_INCLUDE_DIR})

if(LIBCURL_ENABLE)
    target_link_libraries(app ${CURL_LIBRARIES})
endif()


Q: Convert string date to Datetime C# How can I convert 1-2-2016 to Datetime format dd-MMM-yyyy
For Example :
The output of 1-2-2016 should be 1-Feb-2016
I've tried the following code but it's returing 2-Jan-2016.
 Updated_Value = Convert.ToDateTime(Updated_Value).ToString("dd-MMM-yyyy");

The Data in Update_Value variable is coming from database whose datatype is varchar.
Kindly Help me to resolve this .
Thanks in advance .

A: Try this:
DateTime dt;
DateTime.TryParseExact(Updated_Value, "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

var newdate = dt.ToString("d-MMM-yyyy");


Q: Visitor pattern. Is void* an acceptable return type for a completely abstract interface? I have an AST, represented in the usual way (a tree of nodes of an abstract type). I have several uses cases for traversing this tree (an optimizer, which returns another AST; IR code generation, which returns a llvm::Value*; and a debug analyzer, which simply outputs to stdout and returns nothing).
A visitor feels like the right way to go here, but the differing return types through each use case of the visitor make it hard to see how to implement an interface for this. I considered this:
class Visitor;

class ASTNode {
public:
  virtual void accept(Visitor *visitor);
};

class Visitor {
public:
  virtual void visit(CallNode *node) = 0;
  virtual void visit(BinExprNode *node) = 0;
  // etc
};

Because of the lack of return value, each Visitor implementation would need to build up internal state and provide a result() method with a suitable return type. That is complex, however, since each call to visit() needs some context around the expression being visited (i.e. the call standing alone, or is it being used as part of a binary expression?). It makes it tricky for things like binary expression code generation to collect return values from visiting the nodes of the operands (I could do it with an internal temporary state variable or some such, but it feels over-engineered) and hard to reason about (the state keeps changing).
class OptimizingVisitor : public Visitor {
  ASTNode *m_result;
public:
  ASTNode *result() {
    return m_result;
  }

  void setResult(ASTNode *node) {
    m_result = node;
  }

  void visit(CallNode *node) {
    node->left()->accept(this);
    ASTNode *optimizedL = result();
    node->right()->accept(this);
    ASTNode *optimizedR = result();
    setResult(new CallNode(optimizedL, optimizedR));
  }

  // ... snip ...
};

I could make it even more complex to avoid the "state keeps changing" issue by passing in a new visitor for each node. It just feels like this problem warrants a more functional solution.
Really, I'd like to write the above much more simply and easier to read:
class OptimizingVisitor : public Visitor {
public:
  ASTNode* visit(CallNode *node) {
    ASTNode *optimizedL = node->left()->accept(this);
    ASTNode *optimizedR = node->right()->accept(this);
    return new CallNode(optimizedL, optimizedR);
  }

  // ... snip ...
};

Of course now I've changed the return type, so it doesn't fit my Visitor contract. Far from defining completely separate interfaces for each possible implementation of a a Visitor and making the AST aware of those visitor types, it seems the only really logical thing to use is a void*. Does this sort of API warrant the use of void*? Is there a better way to do this?

A: If I get this right, I might have something useful. Referring to your sample at https://gist.github.com/d11wtq/9575063, you cannot have
class ASTNode {
public:
   template <class T>
   virtual T accept(Visitor<T> *visitor);
};

because there are no template virtual functions. However, you may have a generic class
template <class D, class T>
struct host {
   virtual T accept(Visitor<T> * visitor);
   // I guess, { return visitor->visit(static_cast <D*>(this)); }
};

and a collection
template <class D, class... T>
struct hosts : host <D, T>... { };

so that, when the set of possible return types is limited, you can say e.g.
class ASTNode : public hosts <ASTNode, T1, T2, T3> {
public:
   // ...
};

Now you have three different Visitor contracts of return types T1,T2,T3.

A: Maybe this is helpful.
Using return type covariance to make accept() calls type-safe:
class Visitor;

class ASTNode
{
public:
    virtual ASTNode* accept(Visitor* visitor);
};

class CallNode;
class BinaryExpressionNode;

class Visitor
{
public:
    virtual CallNode* visit(CallNode* node) = 0;
    virtual BinaryExpressionNode* visit(BinaryExpressionNode* node) = 0;
};

Implementations:
class CallNode : public ASTNode
{
public:
    CallNode(BinaryExpressionNode* left, BinaryExpressionNode* right);

    // return type covariance
    CallNode* accept(Visitor* visitor) override
    {
        return visitor->visit(this);
    }

    BinaryExpressionNode* left();
    BinaryExpressionNode* right();
};

class BinaryExpressionNode : public ASTNode
{
public:
    BinaryExpressionNode* accept(Visitor* visitor) override
    {
        return visitor->visit(this);
    }
}

class OptimizingVisitor : public Visitor
{
public:
    CallNode* visit(CallNode* node) override
    {
        // return type covariance will make this operation type-safe:
        BinaryExpressionNode* left = node->left()->accept(this);
        auto right = node->right()->accept(this);
        return new CallNode(left, right);
    }

    BinaryExpressionNode* visit(BinaryExpressionNode* node) override
    {
        return new BinaryExpressionNode(node);
    }
};


Q: Intellij Accessing file from hadoop cluster As part of my intellij environment set up I need to connect to a remote hadoop cluster and access the files in my local spark code.
Is there any way to connect to hadoop remote environment without creating hadoop local instance?
A connection code snippet would be the ideal answer.

A: If you have a keytab file to authenticate to the cluster, this is one way I've done it:
val conf: Configuration: = new Configuration()
conf.set("hadoop.security.authentication", "Kerberos")
UserGroupInformation.setConfiguration(conf)
UserGroupInformation.loginUserFromKeytab("user-name", "path/to/keytab/on/local/machine")
FileSystem.get(conf)

I believe to do this, you might also need some configuration xml docs. Namely core-site.xml, hdfs-site.xml, and mapred-site.xml. These are somewhere usually under /etc/hadoop/conf/.
You would put those under a directory in your program and mark it as Resources directory in IntelliJ.


Q: jQuery loading other html pages, but how to revert to original content So i have done this small piece of jQuery code to load html files into a DIV but I'm struggling to work out how i can for example place a back button on the loaded content and once clicked will revert to the original content any ideas?
Ideally i would like to use a ajax effect when loading the content with a throbber but reading up online loasd is the best way?
$('.load-page').on("click", function() {
  var href = $(this).attr("href");
  $('#in-the-news').load(href);
  return false
});

link:
link

html:

original content

A: You have to cache the original content into another object when the user presses the link, and then take it back when the user press the original link.
somethin like this (untested)
$('.load-page').on("click", function() {
  var href = $(this).attr("href");
  if ($('#hidden-cache').html() == ''){
      $('#hidden-cache').html($('#in-the-news').html());
  }
  $('#in-the-news').load(href);
  return false
});

$('.original-page').on("click", function() {
  $('#in-the-news').html($('#hidden-cache').html());
  return false
});

original content


Q: AEM: How common component injected in multiple components can have dynamic value I have a common component which is injected in multiple components via data-sly-resource.
componentA

componentB

In some-common-component.html a "class" need to be added to the div which will be dynamic and specific to the component it is injected from. For example, when this component is added in componentA
the html wuld be:

and when added in componentB it would be

How can I achieve this? How would I know who is injecting this component or it possible to send extra parameters from the parent component which I can access from some-common-component.html

A: For this use case it’s probably best to use HTL templates:
<sly data-sly-use.common="common.html" data-sly-call="${common.myTemplate @ buttonClass='myClassA'}"></sly>

A: You can make use of requestAttributes (refer here)
Component A (passing the value):
Sightly :

<sly data-sly-use.compA = "com.mysite.core.models.CompA"/>

Sling Model :
package com.realogy.sir.core.models;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class)
public class CompA {

    public Map<String, Object> attribute = new HashMap<>();

    @PostConstruct
    protected void init() {
        attribute.put("attributeVal", "componenta");
    }
}

Component B (passing the value):
Sightly :

<sly data-sly-use.compB = "com.mysite.core.models.CompB"/>

Sling Model :
package com.realogy.sir.core.models;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class)
public class CompB {

    public Map<String, Object> attribute = new HashMap<>();

    @PostConstruct
    protected void init() {
        attribute.put("attributeVal", "componentb");
   }
}

Common Component (consuming the value):
Sightly :

<sly data-sly-use.commonComp= "com.mysite.core.models.CommonComp"/>

Sling Model:
package com.mysite.core.models;

import javax.inject.Inject;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class)
public class CommonComp {

    @Inject @Optional @Default(values="component")
    private String attributeVal;

    public String getAttributeVal() {
        return attributeVal;
    }

}


Q: How to reset a variable after 3 seconds in Android? I am trying to create a Service. In this Service I ahve this variable:
String command="Go"

I want to design a function that does this:

Within 3 seconds, the command will return value "Go"
If the time is bigger than 3 seconds, the command will be reset to "".

My current solution is using a Thread. Do you think it is a safe and good solution?
public String command;

public String getValue(){
    command="GO";
    try {
        Thread.sleep(3000);
        command="";
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return command;
}

A: As you are doing it at MainThread the app will not response to user and it's the worst thing can happen! I suggest you to use RXJava and be aware of blocking UI Thread!
Observable.just(comment)
            .delay(3, TimeUnit.SECONDS)
            /*for doing at background*/
            .subscribeOn(Schedulers.io())
            /*for responsing at maint thread*/
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<String>() {
                @Override
                public void call(String s) {
                    comment = "";
                    // and other stuffs you wand after resetting the val
                }
            });

A: A good approach(based on you having a thread already) would be this:
long elapsed = (System.nanoTime()-startTime)/1000000;
if(elapsed>3000) {

    //reset your variable

    //Allow this to repeat:
    startTime = System.nanoTime();
}

In order to initialize, do startTime = System.nanoTime(); where you would initialize the activity.
Now this method has a big drawback: You have to use it with a thread. It cannot be used alone as a listener if you want it to update after 3 seconds and not after 3 seconds on a button press.
Using a thread is a good idea if you want something done repeatedly, but beware of background memory hogging. You may want to create an async thread

A: A better approach would be to use handlers and postDelayed instead of Thread.sleep().
postDelayed puts the Runnable in the handler thread's message queue. The message queue is processed when control returns to the thread's Looper.
Thread.sleep() blocks the thread.
final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Do stuff every 3000 ms
        handler.postDelayed(this, 3000);
      }
    }, 1500);