Input is not showing the Angular´s reactive form value

Question: I´m building up an Angular basic CRUD app for try new things, but wish to know why this is happening.
I´m trying to get the "post" data and I do from a service, this is working fine, the problem is when I´m setting up the form, show the rest of the values, but not the user ID.
This is the code:
HTML

Modify register

Modify register

        <form [formGroup]="editRegisterForm" (ngSubmit)="editRegister()">

                <input type="text" class="form-control" id="userIdInput" formControlName="user" readonly>

                <textarea class="form-control" id="titleInput" cols="30" rows="3" placeholder="Write here the title of your post" formControlName="title"></textarea>

                <select class="form-select" name="completedSelect" id="comletedSelect" formControlName="completed">
                <option value="default" hidden>Choose an option</option>
                <option value="completed">Completed</option>
                <option value="no completed">Not completed</option>
              </select>

            <button type="submit" class="btn btn-outline-primary new__register__form__submit">Update register</button>
        </form>

TypeScript
 ngOnInit(): void {
    this.registerId = this.route.snapshot.paramMap.get('id');
    this.todosService.getAllRegistersById(this.registerId).subscribe((res: any) => {
      this.editRegisterForm = this.initEditForm(res);
    });
  }

 initEditForm(response: any){
    const { user, title, completed } = response;
    let status;
    completed === true? (status = 'completed'): (status = 'no completed');
    return this.fb.group({
      user: [user, [Validators.required]],
      title: [title, [Validators.required, Validators.maxLength(199)]],
      completed: [status, [Validators.required]]
    });
  }

Comment: Can you elaborate on the issue? I don't quite understand the issue you are facing.
Comment: @caslawter the problem here is, on ```initEditForm()```, I try to set default values. User value is set, but is not shown on HTML, I´ve cheked if it was ```formControlName``` problem, but guess nope.
Answer: Try injecting ChangeDetectorRef in constructor and run markforcheck() after form is initialized.
Comment: I´ve tried it, but not working
Answer: I would suggest a different approach.

Don't try to reassign a value to editRegisterForm, but instead inside initEditForm, you can do the following:

      this.editRegisterForm.get('user').setValue(yourUserValue);
      this.editRegisterForm.get('title').setValue(yourTitleValue);
      this.editRegisterForm.get('completed').setValue(yourCompletedValue);

This way you're going to update your FormControl's values. Otherwise your approach is probably causing an issue with change detection and I don't see a point to reassign the value of your FormGroup, when you're just trying to update your field's values and there's an API defined for that.


Style does not affect input in Ionic 3

Question: I am trying create a login page for my app. But style does not work as I wish, here is the photo from problem
1
Here is the login.html codes
<ion-content class="app-content padding main-bg text-center">

  <form class="app-form">

              <input type="text" class="text-center" placeholder="username">

              <input type="password" class="text-center" placeholder="Password">

      <button class="button button-block button-clear main-btn main-bg-color" ng-click="goto('/app/home')">Login</button>
      Register

Forget Password?

  </form>
</ion-content>

Here is the login.scss codes
 .app-form .list-inset {
    margin-left: 0;
    margin-right: 0;
    background: none;
  }

.app-form {
    .item-input {
      margin-bottom: 20px;
      background: none;
      border: 1px solid;
      border-radius: 30px;
      padding: 5px 10px;
    }
    .list-inset .item {
      border-radius: 30px;
      height: 46px;
      &.item-input input {
        padding: 0;
        color: white;
      }
    }
    input {
      &::-webkit-input-placeholder, &:-moz-placeholder {
        color: white;
        text-transform: capitalize;
      }
    }
  }

.app-form .item-select {
    select {
      width: 100%;
      max-width: 100%;
      background: none;
      text-align-last: center;
      padding: 0;
      text-align: -moz-center;
      text-align: -webkit-center;
      text-align-last: -moz-center;
      text-align-last: -webkit-center;
      direction: ltr;
    }
    &:after {
      top: 60%;
      right: 55px;
    }
  }

And here is the what I want from original login.html :)
2
And from original html's browser screenshot
3
And from my app's browser screenshot
4
Thanks for your helping :)
EDIT
After change html tags with ion tags
Answer: Ionic introduces and uses their own tags,  for example, which has default styles added to it. It seems that you are using standard tags in your app such as  and . Change your input to something like
<ion-item>
  <ion-label>Username</ion-label>
  <ion-input type="text"></ion-input>
</ion-item>

and things shall work smoother.
Ionic is fun to learn because it is easy. Have a visit the Official Doc to see how you can make things easier. With the proper syntax, you will not less styling rules.
Comment: Great suggest, white textboxes has gone thank you :) But still I can't get action from margins and text center. Textboxes laying full width, and their texts begining from left. I need extra styling for this?
Comment: Read here https://ionicframework.com/docs/theming/css-utilities/ . Ofcourse you may add custom styling when necessary. Can you post the a photo of the current output?

Style does not affect input in Ionic 3


Fetching a single record is outputting more than the records contents and json.parse not logging the correct data

Question: I set up a new table called triggers. What I am doing is setting up a simple binary system that triggers things from showing or not showing. The code below is from an attempt I just made at doing this.
I'm running into two issues with the code below.

The echo json_encode is actually echoing onto the file's page. I have never had this happen before, so I'm unsure why it is doing so.

The echoed result is this:
{"specialPopStatus":{"setting":"1","0":"1"}}

The only number that should be showing up is 1. I don't understand where the trailing 0 and 1 are coming from.

The console.log results from the JSON.parse is [object Object]. I don't understand why, if at the very least, the 1, 0 and 1 isn't outputting.

Ultimately, all I am wanting is the setting result from the db for the single record I indicate by the name. Then I want to fetch this record via my ajax function. It will always be either 0 or 1.
What am I doing wrong?
PHP
try {
    $con = getConfig('pdo');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $special_pop_sql = "
        SELECT setting
        FROM triggers
        WHERE trigger_name = 'Special Pop'
        LIMIT 1
    ";

    if ($special_pop_stmt = $con->prepare($special_pop_sql)) {
        $special_pop_stmt->execute();
        $special_pop_row = $special_pop_stmt->fetch();
    }
}
catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

echo json_encode(['specialPopStatus' => $special_pop_row]);

JS
var status2 = 0;
function ajaxSpecialPopTrigger() {
    $.ajax({
        url: '/php/triggers.php',
        datatype: 'json',
        success: function (data) {
            obj = JSON.parse(data);

            specialPopStatus = obj.specialPopStatus;
            status2 = specialPopStatus;
            console.log(status2 + ' This is the status');
        }
    });
}
ajaxSpecialPopTrigger();

EDIT - New JS:
var status2 = 0;
function ajaxSpecialPopTrigger() {
    $.ajax({
        url: '/php/triggers.php',
        datatype: 'json',
        success: function (data) {
            //obj = JSON.parse(data);

            //Catalog Requests
            specialPopStatus = data.specialPopStatus;
            status2 = specialPopStatus;
            console.log(status2 + ' This is the status');
        }
    });
}
ajaxSpecialPopTrigger();

Comment: I think you mean you have setup a TABLE called triggers. There is a non subtile difference
Comment: Why are you preparing a query that has NO Parameters?
Comment: @RiggsFolly Yep, you are correct. Edited.
Comment: @RiggsFollyThat is the only way I know how to do a PDO statement.
Comment: You could have done a [simple `->query()`](https://www.php.net/manual/en/pdo.query.php)
Answer: The reason for the extra data in the json string is that you use
$special_pop_row = $special_pop_stmt->fetch();

the default of which is to return an assoc array AND a numeric array, notice the data value is 1 in both cases.
So fix that by doing this small mod
$special_pop_row = $special_pop_stmt->fetch(PDO::FETCH_ASSOC);

Also in the javascript because you have given
datatype: 'json',

as the paramter, you dont have to parse the json as jQuery will do that for you
So the javascript code be written
var status2 = 0;
function ajaxSpecialPopTrigger() {
    $.ajax({
        url: '/php/triggers.php',
        datatype: 'json',
        success: function (data) {
            //obj = JSON.parse(data);

            specialPopStatus = data.specialPopStatus;
            //status2 = specialPopStatus;
            console.log(specialPopStatus + ' This is the status');
        }
    });
}
ajaxSpecialPopTrigger();

Comment: Thank you for the explanations. The echoed `json_encode` is now correct. BTW - if I take away the echo part of it, will the JS file still read it? However, the console.log statement is now reading `undefined`.
Comment: No, the `echo json_encode(['specialPopStatus' => $special_pop_row]);` is what passes data back to the waiting ajax function
Comment: Then how do I get it so the results aren't showing up on the page? I've never had the json_encode actually show up on the page. I also edited my question to show the updated JS regarding why it is now showing up as undefined.
Comment: I figured out why the `json_encode` results were outputting to my page. I forgot to delete my `include_once` code for the php file. I still can't figure out why the results are showing undefined in the `console.log` though.


How to learn JQuery coming from a Drupal background but with little to no knowledge of Javascript?

Question: So here I am in 2012 and although I've been making websites in my spare time for several years, I've managed to get the results I needed by using Drupal and simply cutting and pasting Javascript snippets, etc. when necessary.
Recently, I've got into development more seriously and I have some time to study the right way to do things so I've decided that I'd like to learn jQuery.  Basically, I'd like to make my sites a little more exciting and interactive; in the past, the sites I have built have been praised/criticized as "highly informative but very plain."
That said, I don't know much about Javascript to begin with.  Where should I start?  If it matters all my projects going forward will be in Drupal 7.
I was looking forward to the JQuery and Drupal videos on drupalize.me, but unfortunately I live in Japan and have a slow Internet connection which makes it almost impossible to stream the videos.
Comment: Japan? Slow internet connection? Wow, that's unusual!
Answer: Understanding basics of Javascript is very important to effectively use and extend jQuery. http://www.youtube.com/watch?v=v2ifWcnQs6M
Answer: As said, you should try and pick up some knowledge of JavaScript (JS).
A good way to learn jQuery, which is a library of JavaScript, when you know the basis of JS is 30 Days to Learn jQuery. I've done this course myself and they give a lot of tips and best practices! Also Learning jQuery has some good tips.
To start off with JavaScript itself, take a peek at W3Schools!


I have semi (explained) perfect pitch but can't handle harmonic intervals. What do I practice?

Question: As the title suggests I have a form of perfect pitch that is not exactly perfect pitch. So let's say I hear a melody. I can name the notes as I hear them if they're not insanely fast of course. The thing is that if it's flat or sharp ... I have no clue about it. My mind adjusts to the scale and will just call out the right note according to which scale is the melody on. So for example, let's say someone plays the notes " Eb G Ab" I will call them out as E G A. But by grabbing the instrument and knowing what I just said I can reproduce it right away.
My problem is chords. I'll listen to a chord and I'll be able to identify the top most note right away but that's about it all. I fail to distinguish the rest of the notes in the chords. Lately I managed to listen to the bass too but I want to do what it seems easier than it is to me for most people I interact with, which is to identify chord quality (major/minor/Dom7 e.t.c e.t.c)
I have the impression that this "semi perfect pitch" or whatever it is is getting in my way so I'm asking for ear training suggestions. I also think I have a bad memory cause I can't remember what I hear.  I'm already going for the interval ear training and can identify the intervals melodically but again when it comes to chords it seems extremely hard to me.
Just more info:
I developed my type of pitch recognition by reading sheet music as a classical guitar player and always speaking the topmost note (the melody usually) in my head. Doing this for years trained my ear to adjust to scale and speaking notes. Adjusting to scale because I never said "E flat or F Sharp" they were just E and F. And no I don't need a reference tone to start doing it.
I also have bad aural memory. If I don't act instantly on what I hear it vanishes from my memory. Which is doing this even harder for me. I'm hoping that by developing my recognition skills it will become easier to memorize music since I can file it in a "visual/photographic" way which is stronger for me than memorizing sounds.
Answer: Based on what you've said, I believe you need to learn how to distinguish between notes with the same note name but different accidentals first. You say you refer to Eb as "E" depending on the context. But that nomenclature will doom you the moment you read music that suddenly switches to the tonic minor. You see, the only difference between a C major chord and a C minor chord is the middle note: E natural for C major, and E flat for C minor.
I believe this is getting in the way of your ability to learn chord qualities. When you refer to both Eb and E natural as "E", I fear that's why you almost cannot distinguish between major and minor chords.
So play those notes with the same note name but different accidentals consecutively. Reliably label all your Gb's, G naturals, and G#'s. When you can do that for all such notes, then you can try identifying major and minor chords.
Start easy. Maybe get a teacher or a helper. When I was young, my piano teacher trained me to identify major and minor chords by playing them, then asking me whether I just heard a major or minor chord. You may need similar ear training.
Save identifying dominant 7ths, diminished chords, etc. for later. Major and minor chords can already be hard enough to distinguish. (I also have absolute pitch but a somewhat poor time identifying chord qualities--I'm slow to recognize diminished and augmented chords, and inversions of half-diminished 7th chords can trip me up to the point where I don't initially think they're half-diminished 7th chords. At least I reliably recognize major and minor chords, though.)
Comment: I'm not sure what you mean by "doomed when **reading** music that switches to the tonic minor." When it comes to playing my instrument by reading music I have no issues at all. I'm actually really good at reading sheet music. I'm bad at identifying what I hear.  I also know music theory and the difference between minor/major - Just in case you thought I'm untrained. I also can identify minor/major if I have the time but at a moving setup (listening music) I can't be consistent. It's more about how much info I can retain in my memory which is not much. So it has to become spontaneous.
Answer: I had similar problems. What helped me out was using certain exercises on a good website
https://www.teoria.com/en/exercises/
Got to the interval section and select harmonic intervals and pick some simple distances. After a week you will smash it !
Comment: Thanks for the link. I'm actually already using a site like the one you mentioned (https://tonedear.com/). The thing is as I say at a comment to another answer: I can already identify the intervals if I have the time. Which  that's exactly what sites like that do. You have to much time to think. When it comes to playing/reproducing what you hear or matching on to what you hear you don't have time to think. It has to happen instantaneously. And that's what I'm trying to train/improve. So the bottom line of the problem is that even if I know how an interval sounds. I can't use that in practice.


Project problem, looking for advice about image processing

Question: I'm a senior in high school and this year I have to do a project for my electronic class, I  was hoping to get some advice from people with some experience.
My idea is kind of complicated and has a lot of different sensors but not too crazy, the problem begins with possible image processing. I have a camera who need to check for flashing light and send the video to a screen without the frames of the flashing (like just skipping the frame, so the video is always a frame in delay but the person won't notice it).
The fashing light is supposed to be like in a party or in a video game you get a warning on. The idea is to notice the extreme changing of lighting and to not show it on the screen.
My teacher is afraid that doing image processing might be too complicated and video processing as well... I don't have any knowledge in it, and I have a little background in Python and other languages, do you think it is possible? Can anyone give me an advice or a good video/tutorial to learn from?
Thank you in advance:)
Comment: It would help if you were a bit more specific about your flashing light - is it a flashlight/torch around 100m away that will appear as a tiny dot in your image that is otherwise black? Or is it an 800W photographic studio flash 2m away that will blast your image to full whiteout? What is its duty cycle? Off for 5s then on for 2ms? Or on for 1s then off for 1s?
Comment: It doesn't sound too hard if the difference between *"not flashing"* and *"flashing"* is very large. You could maybe *"learn"* the mean lighting and its variance over the first few seconds of video then, if a frame comes along that exceeds the learned variance, keep re-sending the previous *"acceptable"* frame until the current frame is within limits again.
Comment: browse these tutorials https://docs.opencv.org/master/ I think it's doable and might be achieved in a dozen or so lines of code. **please share a camera picture that shows the flash**
Answer: your probleme if quite diificult, cause it envolved unknown environnement in a dynamic time range.
if you admit as an axiom that your camera has for exemple a frame rate of 20 FPS, the chances that your difference between Frame f' and next frame f+1 are quite low.
UNLESS you have a huge color change du to ligth flash,
So you can process with an image similarity such as ssim or psim
https://www.pyimagesearch.com/2017/06/19/image-difference-with-opencv-and-python/
if your image is over a certain treshold that you have to define ( can use also a kalmann filter to dynamically reajust the difference treshold)
so it will probably mean that your flash light is on.


The real part of $z^n$

Question: Prove that $${\displaystyle\lim \limits_{n \to +\infty}{|r^ncos(nθ)|}}=+\infty,$$
where  $n$ is integer, $r>1$, $θ/π$ is irrational.
I got this problem from here $1+x+\ldots+x^n$ perfect square , I think it's true for the general situation.
PS:
The original problem is to prove
$${\displaystyle\lim \limits_{n \to +\infty}{|z^n+\overline{z}^n|}}=+\infty,$$
where $n$ is integer, $z=x+yi,\overline{z}=x-yi,x>y>0,x^2+y^2>1,i=\sqrt{-1}.$
But according to the answer given by @mrf, this is not true when $y/x=tan(π/8)$,so I add the condition that $θ/π$ is irrational.
Thanks in advance!
Comment: Is this homework ?
Comment: @Kasper,no,this is not homework
Comment: Is $n\in\mathbb Z$? @sophia
Comment: @Babak S.yes,n is always an integer.
Comment: @Kasper: She is just asking for any help of us. :-) We are not forced to answer her in a complete detailed answer. So let's help her. +1
Comment: @BabakS. I didn't downvote, but I think it is good that the OP knows why there are downvotes, and that some people here will consider to close this question. Go ahead helping here !
Comment: @Kasper: Exactly! :-)
Comment: @Kasper,thanks for your advice,I have been here for more than a month now,I know how to work here,I didn't write anything just because I have no idea to this problem.I have try many numerical calculate but it's not worth to write here, maybe my mistake is I forget to add the link for this problem.
Comment: Since it has been edited, the only given answer doesn't match the question anymore!
Comment: @girianshiido,it's my fault.@mrf's answer is helpful to me,but my main question was not answered,so I have to edit it to make the question meaningful.
Comment: Maybe you should try to reverse back to the original question and complete it instead!
Comment: @girianshiido,I will take your suggestions.
Answer: The statement can be false even when you assume $\frac{\theta}{\pi}$ is irrational.
Let $(s_k)_{k=1,2\ldots}$ be the sequence defined recursively by:
$$s_k = \begin{cases}1,&\quad\text{ for }k = 1\\2^{s_{k-1}},&\quad\text{ for }k > 1\end{cases}$$
and $s$ be the Liouville number $s = \sum_{k=1}^{\infty} 2^{-s_k}$.
For $r = \sqrt{2}$, and $\theta = s\frac{\pi}{2}$, we have:
$$\begin{align}r^{2^{s_m}} |\cos( 2^{s_m} \theta )| = &
2^{(2^{s_m}/2)} \left|\cos\left(\frac{\pi}{2}(1 + \sum_{k=m+1}^{\infty} 2^{s_m-s_{k}})\right)\right|\\ \sim & \frac{\pi}{2}2^{(2^{s_m}/2) + s_m - s_{m+1}}\\
= & \frac{\pi}{2}2^{s_m - (s_{m+1}/2)}
\end{align}$$
As this converges to $0$ as $m \to \infty$, $r^{n} |\cos(n\theta)|$ has a
sub-sequence which converges to $0$ and hence it cannot diverges to $\infty$.
Comment: Thank you,it seems that my idea is completely wrong..Maybe it's true for irrational algebraic numbers :)
Comment: @Sophie The statement is probably true when $z$ is an algebraic number and $\frac{\theta}{\pi}$ is irrational. I have an argument for this in an [old post](https://groups.google.com/d/msg/sci.math/XCljh7L4E0U/90q942YOjw4J) on sci.math. However, it is an argument not a proof because I don't really know the Baker and Wustholz theory of linear form used in my argument there.
Answer: Use the polar representation of $z$, $z = re^{i\theta}$. By the assumptions, $r > 1$ and $0 < \theta < \pi/4$.
Computing, you get $z^n = r^n e^{in\theta}$ and $\bar z^n = r^n e^{-in\theta}$, so
$$ z^n + \bar z^n = r^n \big( e^{in\theta} + e^{-in\theta} \big) = 2 r^n \cos(n\theta).$$
Here you can see that there's something wrong with your (supposed) conclusion. Take for example $z = 2e^{i\pi/8}$, then $z^n + \bar z^n = 0$ if $n = 8k+4$ for $k\in\mathbb{Z}$.
Comment: +1.nice,how about if $θ/π$ is irrational?For example,$z=1+\sqrt{2}i$,this is the original problem in that link.

The real part of $z^n$


ReentrantLock tryLock(timeout,timeUnit) doesn't work as expected

Question: I have some confuse about ReentrantLock tryLock(timeout,timeUnit) method , when
running below code it seems tryLock timeout until the previous thread end,could anyone explains this?
public class MyService2 {
public ReentrantLock lock = new ReentrantLock();

public void waitMethod() {
    try {
        System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " enter ");
        boolean b = lock.tryLock(2, TimeUnit.SECONDS);
        if (b) {
            System.out.println(System.currentTimeMillis() + " lock begin:" + Thread.currentThread().getName());
            for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
                Math.random();
            }
            System.out.println(System.currentTimeMillis() + " lock end " + Thread.currentThread().getName());
            return;
        }
        System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " got no lock end ");
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

public static void main(String[] args) throws InterruptedException {
    MyService2 myService2 = new MyService2();
    Runnable runnable = myService2::waitMethod;
    Thread thread1 = new Thread(runnable);
    thread1.setName("T1");
    thread1.start();
    TimeUnit.MILLISECONDS.sleep(10);
    Thread thread2 = new Thread(runnable);
    thread2.setName("T2");
    thread2.start();
}

after running this code ,the result is like that
1555343172612 T1 enter
1555343172613 lock begin:T1
1555343172627 T2 enter
1555343179665 lock end T1
1555343179665 T2 got no lock end

my question is why thread T2 doesn't timeout in 2s rather than waiting until thread T1 ends?
BUT I just found:

if replace Math.random() with TimeUnit.SECONDS.sleep(1) for example ,it works fine.
if run in debug mode ,it works fine too.
Comment: This works fine for me. Check that your OS isn't occupied with other processes or that your JVM isn't blocked in GC or otherwise paused.
Comment: @SotiriosDelimanolis thanks for your suggestion ,I'll give a try .
Comment: "Fairness" in scheduling when threads runs cannot be generally assumed.  When running with multiple threads, or with explicit thread management durations (explicit wait times) it's unsafe to assume that a thread will immediately resume at the conclusion of the explicit duration.
Comment: The issue is the unexpected long time in 'boolean b = lock.tryLock(2, TimeUnit.SECONDS);'.  What may be happening is that the second tread is prevented from running for a long time while in the midst of the call to 'tryLock'.
Comment: @ThomasBitont  Sorry,I don't get it .what I learned from javadoc is only that "If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:
The lock is acquired by the current thread; or
Some other thread interrupts the current thread; or
The specified waiting time elapses";
Comment: That documentation is misleading, and perhaps incomplete.  "lies dormant until" seems to imply that the thread will immediately wake after the time elapses, but there is no guarantee of this.  There is also no guarantee that the dormant period will begin immediately.  As far as I'm aware, java does not guarantee timely execution of threads, as would a real time environment.  There can be arbitrary delays at any point of the invocation of 'tryLock' independent of the specified two seconds.
Comment: @ThomasBitonti but how to explain "runing under debug mode works fine" or "replace Math.random() with TimeUnit.SECONDS.sleep(1) also works fine"
Comment: Both of those will considerably change the running characteristics of the program.  Running a debugger adds a whole new layer of control over when threads run.  Running 'Math.random' in a loop will tend to keep a thread as the running thread, whereas invoking sleep explicitly means the thread is not running, and explicitly gives other threads more opportunities to run.
Answer: Here is an alternate which has a number modifications:
First, cleanups.  Clearer names.  Less intrusive logging.  Relative time values.
Second, the 0.1s sleep between the launch of the two compute threads is moved into each of the threads.  That more clearly gives precedence to the thread which launches the compute threads.
Third, the launch thread has joins with the compute threads.  That is to tie the conclusion of the computation to the launch thread.  In the original code, there is no management of the compute threads after they have been launched.  If the compute threads are intended to be unmanaged, that needs to be documented.
Fourth, the entire launch thread plus two compute threads structure is replicated.  That is to place give the structure a more realistic runtime environment, and, to present the different behaviors of the structure together in a single view.
A theme to the modifications is to provide clarity, both to the intended behavior of the program, and to the actual behavior (as viewed through the logging output).  The goal is to provide maximal clarity to these.
An additional modification is recommended, which is to put the log statements into a cache, then display the collected log lines after all of the computation cells have completed.  That removes behavior changes caused by the log statements, which are often considerable.
package my.tests;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

    private static long initialTime;

    protected static void setInitialTime() {
        initialTime = System.currentTimeMillis();
    }

    public static long getInitialTime() {
        return initialTime;
    }

    public static final int CELL_COUNT = 10;

    public static void main(String[] args) {
        setInitialTime();

        System.out.println("Beginning [ " + Integer.toString(CELL_COUNT) + " ] computation cells");

        Thread[] cellThreads = new Thread[CELL_COUNT];
        for ( int cellNo = 0; cellNo < CELL_COUNT; cellNo++ ) {
            final String cellNoText = Integer.toString(cellNo);
            Runnable computeCell = () -> {
                (new LockTest(cellNoText) ).compute();
            };
            Thread cellThread = new Thread(computeCell);
            cellThreads[cellNo] = cellThread;
        }

        // Start them all up ...

        for ( Thread cellThread : cellThreads ) {
            cellThread.start();
        }

        // Then wait for them all to finish ...

        for ( Thread cellThread : cellThreads ) {
            try {
                cellThread.join();
            } catch ( InterruptedException e ) {
                System.out.println("Unexpected interruption: " + e.getMessage());
                e.printStackTrace();
            }
        }

        System.out.println("Completed [ " + Integer.toString(CELL_COUNT) + " ] computation cells");
    }

    //

    public LockTest(String cellName) {
        this.cellName = cellName;
    }

    private final String cellName;

    public String getCellName() {
        return cellName;
    }

    // Logging ...

    public String formatTime(long timeMs) {
        return String.format("%12d (ms)", new Long(timeMs));
    }

    public long getRelativeTime(long currentTime) {
        return currentTime - getInitialTime();
    }

    public String formatRelativeTime(long timeMs) {
        return String.format(
            "%12d %8d (ms)",
            new Long(timeMs),
            new Long( timeMs - getInitialTime() ));
    }

    public void log(String methodName, String message) {
        long timeMs = System.currentTimeMillis();
        String threadName = Thread.currentThread().getName();

        System.out.println(
            formatRelativeTime(timeMs) + ": " +
            methodName + ": " +
            threadName + ": " + message);
    }

    //

    public void compute() {
        log("compute", "ENTER: " + getCellName());

        Runnable computation = () -> {
            guardedComputation(
                100L, 0,                  // Pause 0.1s before attempting the computation
                1, TimeUnit.SECONDS,      // Try to obtain the computation lock for up to 1.0s.
                Integer.MAX_VALUE / 60 ); // Run this many computations; takes about 2s; adjust as needed
        };

        Thread computer1 = new Thread(computation);
        computer1.setName( getCellName() + "." + "T1");

        Thread computer2 = new Thread(computation);
        computer2.setName( getCellName() + "." + "T2");

        // Run two sets of computations:
        //
        // Each will pause for 0.1s before performing the computations.
        //
        // Performing computations requires a computation lock; wait up to 2.0s
        // to acquire the lock.

        computer1.start();
        computer2.start();

        try {
            computer1.join();
        } catch ( InterruptedException e ) {
            System.out.println("Unexpected interruption: " + e.getMessage());
            e.printStackTrace();
            return;
        }

        try {
            computer2.join();
        } catch ( InterruptedException e ) {
            System.out.println("Unexpected interruption: " + e.getMessage());
            e.printStackTrace();
            return;
        }

        log("compute", "RETURN: " + getCellName());
    }

    // Computation locking ...

    private final ReentrantLock computationLock = new ReentrantLock();

    public boolean acquireComputationLock(long maxWait, TimeUnit maxWaitUnit) throws InterruptedException {
        return computationLock.tryLock(maxWait, maxWaitUnit);
    }

    public void releaseComputationLock() {
        if ( computationLock.isHeldByCurrentThread() ) {
            computationLock.unlock();
        }
    }

    //

    public void guardedComputation(
        long pauseMs, int pauseNs,
        long maxWait, TimeUnit maxWaitUnit, int computations) {

        String methodName = "guardedComputation";

        log(methodName, "ENTER");

        try {
            Thread.sleep(pauseMs, pauseNs);
        } catch ( InterruptedException e ) {
            System.out.println("Unexpected interruption: " + e.getMessage());
            e.printStackTrace();
            return;
        }

        try {
            boolean didLock;
            try {
                didLock = acquireComputationLock(maxWait, maxWaitUnit);
            } catch ( InterruptedException e ) {
                System.out.println("Unexpected interruption: " + e.getMessage());
                e.printStackTrace();
                return;
            }

            String computationsText = Integer.toString(computations);
            if ( didLock ) {
                log(methodName, "Starting computations: " + computationsText);
                for ( int computationNo = 0; computationNo < computations; computationNo++ ) {
                    Math.random();
                }
                log(methodName, "Completed computations: " + computationsText);
            } else {
                log(methodName, "Skipping computations: " + computationsText);
            }

        } finally {
            releaseComputationLock();
        }

        log(methodName, "RETURN");
    }
}

Comment: What is it they are trying? How is this piece of code different from theirs? How does the difference affect program execution and how does it explain the behavior the OP sees?


Uploading Multiple Images With An Input File Field

Question: I'm building a simple website where I want to upload images into a folder so I'm doing this by enabling multiple in the input box.
Here is my HTML:
<input type="file" name="gallery[]" multiple />

And here is the PHP:
$id = time();
$year = date("Y");
$photo_path = "photos/$year/";
$zip_path = "sets/$year/";

$photo = $_FILES["photo"]["name"];
$gallery = $_FILES["gallery"]["name"];

move_uploaded_file($_FILES["photo"]["tmp_name"],"$photo_path" . $id . ".jpg"); // This Adds Photo To $photo_path
move_uploaded_file($_FILES["gallery"]["tmp_name"],"$zip_path"); // This Doesn't Add 5 Files To $zip_path

This adds the photo into the $photo_path folder, but doesn't add the selected 5 images to the $zip_path folder.
Any ideas where I'm going wrong?
Update:
foreach ($_FILES["gallery"] as $file) {

    move_uploaded_file($_FILES["gallery"]["tmp_name"],"$zip_path");

}

Answer: You need to handle multiple files in a loop. Here is an example directly from the manual.
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}

Answer: When you calling multiple file upload, it will return an array of files. you can iterate it like:
if(count($_FILES['gallery'])) {
    foreach ($_FILES['gallery'] as $key=>$file) {

        //do your upload stuff here
        move_uploaded_file($_FILES['gallery']["tmp_name"][$key], $zip_path . time() . ".jpg");

    }
}

Comment: That looks to make sense but It's not uploading any of the images. I've added my code to the end of the original question.


sampling distribution for N(0,1) samples

Question: Here is an portion of my lecture notes from class, we are studying sampling distributions. I am confused on some of the examples that are showed in the attached picture.

For the first example, from my analysis its saying that the sample mean $\bar{x}= {1\over{n}} \sum_{i=1}^n x_i \sim N(0,1/n)$? Is that safe to assume or correct?
For the second example where $2\bar{x}\sim N(0,1)$,  I am completely lost.  I am not sure as to why this is true. Can someone please explain?
I understand part 3 since it was explained as a theorem s.t ${(n-1)S^2\over{v^2}} = {\sum_{i=1}^n (x_i-\bar{x})^2\over{v^2}} ~ \chi^2_{n-1}$. [here $i$ indicate $v$ as variance]
For the fourth example, I am uncertain as to where $\sqrt{S^2}$ or sample variance came from. I know that $T={Z\over{\sqrt{W/n}}}$ where $W~\chi^2$ with $n$ df and that $Z\sim N(0,1)$  where both Z and W are independent. So I guess I am confused as to how the $\sqrt{S^2}=\sqrt{W/n}$ where n is the sample size. (update I have found the explanation to this)
However I am still confused as to part 2. Can someone please explain part 2?
Comment: https://en.wikipedia.org/wiki/Variance#Basic_properties
Comment: Did you forget to attach the picture?
Answer: In the first example, you are correct. While it's not explicitly stated, the examples seem to assume that the marks of the different students will be independent of one another (which seems fairly reasonable). The following are fairly well known results for $x_i \sim N(\mu_i, \sigma_i^2)$, where the $x_i$ are independent:

$\sum_{i=1}^n x_i \sim N(\sum_{i=1}^n\mu_i,\sum_{i=1}^n\sigma_i^2)$
$Cx_i \sim N(C\mu_i, C^2\sigma_i^2)$ where C is a constant

For the first two points, you just need to use these two facts (the second part just uses the second fact, setting C=2, $\sigma_i^2$=1/4).
You seem to get the rest, which is great :)


Using chart js within Bootstrap Carousel

Question:

 //Sampel Line Chart
 var LineChartSampleData = {
  labels: ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6","Q7"],
  datasets: [{
   label: "Sales 1",
   fillColor: "transparent",
   strokeColor: "rgba(220,220,220,1)",
   pointColor: "rgba(220,220,220,1)",
   pointStrokeColor: "#fff",
   pointHighlightFill: "#fff",
   pointHighlightStroke: "rgba(220,220,220,1)",
   data: [11, 12, 13, 14, 15, 16, 17]
  }, {
   label: "Sales 5",
   fillColor: "transparent",
   strokeColor: "rgba(236, 80, 80,1)",
   pointColor: "rgba(236, 80, 80,1)",
   pointStrokeColor: "#fff",
   pointHighlightFill: "#fff",
   pointHighlightStroke: "rgba(236, 80, 80,1)",
   data: [15, 21, 35, 42, 33, 33, 81]
  }]
 };

 //Sampel Bar Chart
 var BarChartSampleData = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        },
        {
            label: "My Second dataset",
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 86, 27, 90]
        }
    ]
};

//Sampel Radar Chart
var RadarChartSampleData = {
    labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 90, 81, 56, 55, 40]
        },
        {
            label: "My Second dataset",
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 96, 27, 100]
        }
    ]
};

//Sampel Polor Chart
var PolarChartSampleData = [
    {
        value: 300,
        color:"#F7464A",
        highlight: "#FF5A5E",
        label: "Red"
    },
    {
        value: 50,
        color: "#46BFBD",
        highlight: "#5AD3D1",
        label: "Green"
    },
    {
        value: 100,
        color: "#FDB45C",
        highlight: "#FFC870",
        label: "Yellow"
    },
    {
        value: 40,
        color: "#949FB1",
        highlight: "#A8B3C5",
        label: "Grey"
    },
    {
        value: 120,
        color: "#4D5360",
        highlight: "#616774",
        label: "Dark Grey"
    }

];

//Sampel Pie Doughnut Chart
var PieDoughnutChartSampleData = [
    {
        value: 300,
        color:"#F7464A",
        highlight: "#FF5A5E",
        label: "Red"
    },
    {
        value: 50,
        color: "#46BFBD",
        highlight: "#5AD3D1",
        label: "Green"
    },
    {
        value: 100,
        color: "#FDB45C",
        highlight: "#FFC870",
        label: "Yellow"
    }
]

 window.onload = function() {

  window.LineChartSample = new Chart(document.getElementById("line-chart-sample").getContext("2d")).Line(LineChartSampleData,{
   responsive:true
  });

  window.BarChartSample = new Chart(document.getElementById("bar-chart-sample").getContext("2d")).Bar(BarChartSampleData,{
   responsive:true
  });

  window.RadarChartSample = new Chart(document.getElementById("radar-chart-sample").getContext("2d")).Radar(RadarChartSampleData,{
   responsive:true
  });

  window.PolarChartSample = new Chart(document.getElementById("polar-chart-sample").getContext("2d")).PolarArea(PolarChartSampleData,{
   responsive:true
  });

  window.PieChartSample = new Chart(document.getElementById("pie-chart-sample").getContext("2d")).Pie(PieDoughnutChartSampleData,{
   responsive:true
  });
  window.DoughnutChartSample = new Chart(document.getElementById("doughnut-chart-sample").getContext("2d")).Pie(PieDoughnutChartSampleData,{
   responsive:true
  });

 };
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      <canvas id="bar-chart-sample" height="80"></canvas>

Mobile

 Kitchen

 Home

    <canvas id="line-chart-sample" height="80"></canvas>

    <canvas id="line-chart-sample" height="80"></canvas>

    Previous

    Next

I have a problem with Chart Js within Bootstrap Carousel, its not show because chart not load, it show with width:0px and height:0px. Ive been working around this thing in last few hours, hope you guys can help me
This is my Html :

          <canvas id="bar-chart-sample" height="80"></canvas>

Mobile

 Kitchen

 Home

        <canvas id="line-chart-sample" height="80"></canvas>

        Previous

        Next

Chart JS:
      //Sampel Line Chart
         var LineChartSampleData = {
          labels: ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6","Q7"],
          datasets: [{
           label: "Sales 1",
           fillColor: "transparent",
           strokeColor: "rgba(220,220,220,1)",
           pointColor: "rgba(220,220,220,1)",
           pointStrokeColor: "#fff",
           pointHighlightFill: "#fff",
           pointHighlightStroke: "rgba(220,220,220,1)",
           data: [11, 12, 13, 14, 15, 16, 17]
          }, {
           label: "Sales 5",
           fillColor: "transparent",
           strokeColor: "rgba(236, 80, 80,1)",
           pointColor: "rgba(236, 80, 80,1)",
           pointStrokeColor: "#fff",
           pointHighlightFill: "#fff",
           pointHighlightStroke: "rgba(236, 80, 80,1)",
           data: [15, 21, 35, 42, 33, 33, 81]
          }]
         };

     var BarChartSampleData = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "My First dataset",
                fillColor: "rgba(220,220,220,0.5)",
                strokeColor: "rgba(220,220,220,0.8)",
                highlightFill: "rgba(220,220,220,0.75)",
                highlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "My Second dataset",
                fillColor: "rgba(151,187,205,0.5)",
                strokeColor: "rgba(151,187,205,0.8)",
                highlightFill: "rgba(151,187,205,0.75)",
                highlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

 window.onload = function() {

  window.LineChartSample = new Chart(document.getElementById("line-chart-sample").getContext("2d")).Line(LineChartSampleData,{
   responsive:true
  });

  window.BarChartSample = new Chart(document.getElementById("bar-chart-sample").getContext("2d")).Bar(BarChartSampleData,{
   responsive:true
  });
 };

Thanks for your help,Cheers!
Comment: You're using `id="line-chart-sample"` twice. Element id should be unique.
Comment: yep,my fault, changed it but still not working. any ideas? @raz
Comment: Have you tried checking if it works when it's not within bootstrap carousel? What steps have you done to isolate the problem? Can you provide a https://jsfiddle.net/ sample of your work so it can be easier for us to find a solution.
Answer: Here's a revised version your code. I assumed you are using Chartjs 1.0.2.
HTML: (same html just removed empty

)
CHARTJS:
function generateChart() {

    var LineChartCanvas = $("#line-chart-sample").get(0).getContext("2d");
    var LineChartSample = new Chart(LineChartCanvas);

    var LineChartSampleData = {
    labels: ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6","Q7"],
    datasets: [
        {
        label: "Sales 1",
        fillColor: "transparent",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [11, 12, 13, 14, 15, 16, 17]
        },
        {
        label: "Sales 5",
        fillColor: "transparent",
        strokeColor: "rgba(236, 80, 80,1)",
        pointColor: "rgba(236, 80, 80,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(236, 80, 80,1)",
        data: [15, 21, 35, 42, 33, 33, 81]
        }
        ]
    };
    LineChartSample.Line(LineChartSampleData);

    //Bar Chart Sample
    var BarChartCanvas = $("#bar-chart-sample").get(0).getContext("2d");
    var BarChartSample = new Chart(BarChartCanvas);

    var BarChartSampleData = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
            {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
            label: "My Second dataset",
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };
    BarChartSample.Bar(BarChartSampleData);
};
generateChart();

Now since you are using bootstrap carousel, only the item with an active class is displayed. Chartjs can't generate chart for hidden canvas elements.
One work around would be generating the charts once an event is triggered.
Like this:
function resetChart() {
    //Reset chart data
    $('canvas').remove();
    $('.item2').prepend('<canvas id="line-chart-sample" height="80"></canvas>');
    $('.item1').prepend('<canvas id="bar-chart-sample" height="80"></canvas>');

    generateChart();
}

$(document).on('click', '.carousel-control', function () {
    resetChart();
});

Now I'm not sure if this is the best way of working around this issue. But it works.
UPDATE:
Slide animation
$('#myCarousel').carousel({
    interval: 2000,
    cycle: true
});

Call function once slide method has completed transition
$('#myCarousel').on('slid.bs.carousel', function () {
    resetChart();
})

See it working here:
JSfiddle Demo
Comment: Thanks mate, its worked for me now :) Btw, is that any possible way that chart being load without trigger? because i need that chart being load in bootstrap carousel auto slide
Comment: Wow,thank you so so much! you saved my life once again :) thanks mate @raz


CMakeLists for C++ library to use in source code

Question: I include a header file from a library in my source file and get this following error my initial guess is there is something wrong in CMakeLists any suggestions please
/usr/include/c++/4.8/bits/c++0_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard.
This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
#error This file requires compiler and library support for the
make[2]: *** [CMakeFiles..] Error 1
make[1]: *** [CMakeFiles..] Error 2
make: *** [all] Error 2
Comment: And have you tried doing what the compiler suggests? Also note that GCC version 4.8 is getting old now, and don't support all of C++11 and very little if anything at all of later standards.
Comment: Is there a direct way to update GCC version 4.8 to C++11
Comment: Read the messages again, especially this part: "This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options." Have you tried adding the option `-std=c++11` when building?
Comment: It means I am suppose to compile it as follows
  make -std=c++11   or make -std=gnu++11    ?  It didnt work as well
Answer: As the error states:
<code>/usr/include/c++/4.8/bits/c++0_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard.
</code>
You need to enable the C++11 support. You can do this in the CMakeLists.txt by writing the following line
<code>add_definitions(-std=c++11)
</code>
And recompiling.
Also beware that GCC 4.8 has limited support for C++11, you can check the support here.
Comment: Thanks alot. It helped alot.  There is another obstacle here i.e  to include a static library with the extension .a Any idea what to write in CMakeLists.txt in order to include the following Makefile command                                                                        LIB_NAME = AdsLib-$(OS_NAME).a
Comment: uff, that would require a long answer, but you can just look here for an example http://docs.ros.org/jade/api/catkin/html/howto/format2/system_library_dependencies.html for some hints.


How do you insert javascript code into HTML

Question: I have learned to build a fun piece of javascript on codeacademy and wanted to add it on a html document. How would I go about doing this or is it even possible?
Here is the site. I tried to use script tags but they do not work. Not sure if I am putting them in the right place.
http://www.codecademy.com/courses/animate-your-name/0/2
Comment: Actually it's alright. Could you post your entire code, or the code that you wanted to add to your document?
Answer: Looking at the Codeacademy link, it seems as if there are some dependancies. You need to make sure to include those. Your HTML file should look like this. Note: You should probably combine all of your JS into an external file and link it with  tags. Also, make sure that your script tags come at the end of the page (but before the ), it will make your page faster as your JS won't block the DOM construction.
Update
If you included all of the known dependancies and it still doesn't seem to work, Codecademy probably buried some important code somewhere. The easiest way to get around this would be to just download the web page itself as an HTML file (option click on the link on mac) and either use that or poke around to make sure you have everything.
<!DOCTYPE html>

<canvas id="myCanvas"></canvas>

Comment: Sorry new to javascript or coding in general. I changed it to my .js but when i open html page nothing happens
Comment: Ok so I instead of just linking the file, you can just include it inline. Just copy and paste the code into your text editor, save and open in your browser.
Comment: So i copied and pasted code and still nothing happens. Appreciate the help!
Comment: Ok, I'm looking back at it.
Answer: You can add inline JavaScript by using the

OR:

Hope this is what you needed!


Getting Permanent API key for Riot

Question: I am currently using Riot API to run my program on python to access League of Legends player status. However, every time I run my code, I have to refresh my Riot API key, which will become inconvenient to the users. Is there any ways to get a permanent Riot API key or refresh it automatically?
Answer: You can submit an application for a permanent API key
https://developer.riotgames.com/app-type

Getting Permanent API key for Riot


Calling id of button to javascript file after onclick event

Question: I have created several buttons using this general code:
   <button class="button" id = "b1" value="0" onclick="checker()"></button>

I am currently writing a javascript 'checker()' method which checks to see if the 'id' of a button matches an external value. To do this, I need the 'id' of the button to be sent to my script once it's corresponding button clicked. Then, I will set that 'id' variable to a value. How can I do this? I could do it for a button where I know the id, but I want my code to be general. I am open to using jQuery.
Comment: I guess you want something like this? function checker() { var myId = $(this).attr("id"); //This will retreive clicked button's id. Then compare it with external value, for example, if (myId == targetId) { // Do something } }
Comment: what you would like to do with id when you pass it to a script method? what does men I will set that id variable to a value?
Comment: I am literally going to say var xyz = [value of 'id']
Comment: check for my answer mate
Answer: First let's create javascript method that will accept id as a parameter:
var checker = function(id)
{
  //we will do something here later, lets understand this now
}

I need the 'id' of the button to be sent to my script once it's
  corresponding button clicked.

So if you want to get the ID of the element the event handler is bound to, you can do this easily with  this.id (this refers to the element), like this:
<button class="button" id = "b1" value="0" onclick="checker(this.id)"></button>

Then, I will set that 'id' variable to a value. How can I do this? I
  am open to using jQuery.

You could do this by following code below, basically we get the id of the clicked button, and inside of your method you could do whatever you want with your id. By reading your comment I saw that you would simply assign the value of id to some xyz variable:
var checker = function(id)
{
   var xyz = id; // now your xyz has a value of clicked button id
}

Answer: Since you are open to using jQuery and want to keep your code general, there is a much simpler way to accomplish what you want, with less typing.
Your Button
<button class="button" id = "b1" value="0"></button>

Your JavaScript
//be sure to include jQuery

Below is a working example snippet

$(function(){
    $(".button").on("click", function(){
         var btnId = $(this).attr("id");
         alert(btnId);
    });
});

<button class="button" id="b1" value="B1">B1</button>
<button class="button" id="b2" value="B2">B2</button>
Comment: Any particular reason one felt they should downvote this answer?  Can it be improved somehow?


Using characteristics to transform a transport PDE

Question: I am given an inhomogeneous transport equation
$$
\partial_t u(t,x) + a(t,x)\cdot\nabla u(t,x)=b(t,x),
$$
with $x\in\mathbb{R}^3$,
$\nabla u(t,x)=\sum_{i=1}^3 \partial_{x_1}u(t,x)$,
$a : [0,\infty)\times \mathbb{R}^3\to\mathbb{R}^3$,
$b : [0 \infty)\times\mathbb{R}^3\to\mathbb{R}$ and
$u : [0, \infty)\times\mathbb{R}^3\to\mathbb{R}$, $u(0,x)=u_0(x)$.
and also given a solution $\chi: [0,\infty)\times\mathbb{R}^3\to\mathbb{R}^3$ to the characteristic equation
$$
\partial_t\chi(t,y)=a(t,\chi(t,y)),
$$
with $\chi(0,y)=y$.

I then have to show that
$$
\partial_t u(t,\chi(t,y)) = b(t,\chi(t,y)),\quad u(t,\chi(t,y))=u_0(y),
$$
whenever $u$ is a solution to the transport equation.
Does this mean that I need to prove that $a(t,x)\cdot \nabla u(t,x) = 0$ for $x=\chi(t, y)$, and thus all $y$?
My work:
We can expand the transport equation to
$$
u_t + a_1 u_{x_1} + a_2 u_{x_2} + a_3 u_{x_3} = b.
$$
I think this is a linear first order PDE, and by this (Solution transport equation) answer we get
$$
\frac{dt}{1} = \frac{dx_1}{a_1(t,x)} = \frac{dx_2}{a_2(t,x)} = \frac{dx_3}{a_3(t,x)} = \frac{dw}{b(t,x)},
$$
though my case is different, since my $a$ depends on $x$ and $t$.
From here I do not understand how this ties into the characteristic equation given.
I wanted to follow the Wikipedia example on Method of characteristics, but I immediately don't understand how to link my problem to it. There they're using that the variables $x$ and $t$ on which $u$ depends, only depend on one variable $s$. But we have that $\chi(t,y)$ depends on two variables, so I cannot do something like $\frac{d}{ds} u(t,\chi(t, y))$, because I don't see how $t$ and $\chi(t,y)$ only depend on one other variable.
Answer: I assume that by $\partial u(t,\chi(t,y))$ you mean $\partial_{\color{red}t} \color{red}(u(t,\chi(t,y))\color{red})$ . Then its nothing but the chain rule,
$$ \partial_{\color{red}t} \color{red}(u(t,\chi(t,y))\color{red}) = (\partial_t u)(t,\chi(t,y)) + \partial_t\chi(t,y)\cdot\nabla u(t,\chi(t,y))$$
plug what $\partial_t\chi(t,y)$ is equal to from the characteristics ODE,
$$\partial_t\chi(t,y)=a(t,\chi(t,y)),$$ and use the equation for $u(t,\bullet)$. Done-
$$\partial_t[ u (t,\chi(t,y)) ] \overset{\text{above & $\chi$ ODE}}{=} [\partial_t u + a\cdot \nabla u](t,\chi(t,y)) \overset{u \text{ PDE}}= b(t,\chi(t,y)) $$
Comment: @TheCodingWombat I think that's largely a notation problem, its something like

$$ \frac{d}{dx}[ f(2x)] = 2\frac{df}{dx}(2x)$$
here $d/dx$ is an operator acting on a function $x\mapsto f(2x)$, and $df/dx$ is a function, which is evaluated at $2x$.
Comment: Thanks, that seems to do it. How do you see the difference between when you take $\partial_t$ with respect to the function only, as in the equation at the top of my question, and $\partial_t$ using the chain rule, as in your answer?


select max(id) de cada* registro

Question:
opa pessoal, tenho um query com esses dados da imagem, queria dar um select apenas no max(id) de cada numeroExterno para guardar em outra tabela@
Comment: *"queria dar um select apenas no max(id) de cada numeroExterno"* isso não faz sentido "de cada numeroExterno", se é max vai ser de todos, senão não seria um max. quanto a inserir em outra tabela só fazer insert com select ou select into
Comment: vou reformular minha pergunta.
Answer: Para pegar o max(id) para cada numeroExterno, faça um select com group by
Exemplo:
select
    max(ID),
    NUMEROEXTERNO
from
    BA_COBAN.DETALHELOJAARQCADASTRAL
where
    NUMEROEXTERNOMATRIZ = '50494'

Agora utilize esse select para fazer join no select que você já tem para fazer o insert na tabela, assim vai filtrar apenas o max de cada numero externo.
Exemplo:
select
    *
from
    (select
         max(ID),
         NUMEROEXTERNO
     from
         BA_COBAN.DETALHELOJAARQCADASTRAL
     where
         NUMEROEXTERNOMATRIZ = '50494') X
inner join BA_COBAN.DETALHELOJAARQCADASTRAL DE on DE.ID = X.ID

Comment: @Diego Garcia Se a resposta lhe foi útil, se puder marque-a como aceita `√`, assim quando outros usuários visualizarem sua questão verão que já tem uma resposta correta e aceita por você.

select max(id) de cada* registro


Enabling password expiry notification for RDP connections

Question: We have an external user who connects to one of our servers only over Remote Desktop. The server has a local user account set up for him. The account security policy follows our normal conventions, which include a password expiry notification if the expiry date is coming up in less than 14 days.
Unlike our normal users, the remote user does not see the notification bubble when the password is about to expire. It's unclear what is causing this. The server is constantly online.
Are there any specific Group Policy settings, workarounds or known issues that affect notifications being shown over RDP connections?
Answer: Check group policy setting Interactive Logon: Prompt user to change password before expiration in Computer Configuration\Policies\Windows Settings\Security Settings\Local Policies\Security Options
It should work regardless of the type of user session. Please check resulting Group Policy on your RDP host to check that this setting not changed.
Comment: That's the same Group Policy where we've set the 14 day notification period before expiry. Thanks for the suggestion, though.
Comment: Did you ever find a resolution to this? I've got the same problem with remote desktop services on Windows Server 2019. I have a *sneaking* suspicion this is because the RDS server is also the domain controller (it's a very small set-up). The GP mentioned above is applied and checked via rsop.msc. I've set it both in the OU applied to the server and even in Default Domain Policy but the password change prompt never appears
Answer: I found that we had the GPO setting "Interactive Logon: Prompt user to change password before expiration" was set at the domain level, BUT our servers were in OUs with inheritance blocked.


Alternative proof of continuous on a closed bounded interval implies uniformly continuous.

Question: Consider a continuous function $f\colon [a,b] \to \mathbb{R}$, then for any given $\varepsilon>0$ define a function $\delta_{\varepsilon}\colon[a,b] \to \mathbb{R}$, where $\delta_{\varepsilon}(x)=\min(b-a,\sup\{\delta>0 :y \in [a,b] \text{ and }|x-y|<\delta \implies |f(x)-f(y)|<\varepsilon\})$ essentially taking the largest value of $\delta$ in the $\varepsilon-\delta$ definition that works for a given $x$ and fixed $\varepsilon$. Is it true that this function is continuous?
If so then $\delta_{\varepsilon}(x)$ attains its infimum on $[a,b]$ and by continuity of $f$ we must have that $\delta_{\varepsilon}(x)>0$ and thus we can take $\delta=\inf_{x \in [a,b]}(\delta_{\varepsilon}(x))>0$ in the definition of uniform continuity. I tried to prove that $\delta_{\varepsilon}$ is continuous, but I am not getting anywhere.
Answer: $\delta_\varepsilon(x)$ isn't even defined for all $x \in [a,b]$ for all continuous functions.
Let $\varepsilon > 0$, $[a,b] \subseteq \Bbb{R}$, and $f(x)$ be constant.  Then
$$  \{\delta > 0 :y \in [a,b], |x-y| < \delta \implies |f(x) - f(y)| < \varepsilon\} = (0,\infty)  \text{.}  $$
The consequent of the implication is always true, so there is no constraint on $\delta$.  This set's supremum does not exist, so the maximum in the definition of $\delta_\varepsilon(x)$ does not exist and $\delta_\varepsilon(x)$ is undefined for all $x \in [a,b]$.

Update: The item below may have been addressed in edits to the Question.

When $\delta_\varepsilon(x)$ is defined for all $x \in [a,b]$, $\delta_\varepsilon(x)$ is trivially continuous because it is constant.
The maximum of $|x-y|$ is $b-a$, so $\sup \{\delta > 0 \dots\}$ is less than or equal to $b-a$.  Therefore,
$$  \delta_\varepsilon(x)= \max\{b-a,\sup \{\delta > 0\dots\}\} = b-a  \text{.}  $$
Comment: Yeah, I made a mistake, was meant to write $\min$ instead of $\max$.
Comment: @MathStudent : Does not address the problem with constant $f$s.
Answer: I think (a slightly modified version of) your delta is lower-semicontinuous. Using that you can show that it has a positive minimum on the compact interval. Then you are done!


drupal_add_js cannot find my javascript file

Question: I am trying to add a simple footer.js to my page.  I created a new block and put it in the footer.  I then use PHP snippet in the body of the block with the PHP code:
<?php
drupal_add_js('footer.js');
?>

When viewing the source code, footer.js is there but when I click on it, it is a 404 error (not found).  The footer.js is located under: /var/www/drupal/sites/www.example.com/footer.js. Then I tried:
<?php
drupal_add_js('footer.js', array('type' => 'file', 'scope' => 'footer'));
?>

I don't think that is working, either.  I think the issue is with the path.  Any ideas, or do I have to write a custom module?
Answer: It is most likely a path issue, you should be able to use the DRUPAL_ROOT constant to get the correct one:
$path = DRUPAL_ROOT . '/sites/www.example.com/footer.js';
drupal_add_js($path);

Comment: Great! Now when I click on the footer.js via the source code of the web page, it opens up the javascript file. Now, is the javascript file the standard type (i.e. ), or is it that weird jQuery format that Drupal wants for inline (i.e. (function ($) {... })(jQuery);)
Comment: It's the second one, that wraps your javascript so it's nice and jQuery context-safe
Comment: Is there any way to bypass this jQuery format and use pure and strict javascript syntax?  jQuery makes no sense to me, and my code I want to embed is in javascript.  In Drupal 6, it was simple to just copy/paste javascript code directly into the footer and voila - it worked!  Looks like they took this out in Drupal 7
Comment: If its just normal js just put that directly in the external file (no script tags) and it will work. Do me a favour and up vote the answer, some idiot down voted it even though it's correct! There's a lot of unfulfilled people out there with nothing better to do!
Comment: I was able to get it to work by finding a module.  What I wanted to do was embed a Piwik javascript code in the footer of my webpage.  Apparently the process to embed javascript is so complicated that Piwik has a Drupal 7 module for it, BUT, I did learn from their module that you can put 'inline' javascript code.  That is good to know.  Anyhow, thank you for your quick response and suggestions.  You did ultimately answer my question of finding the javascript file, although I could not get the javascript to work.  Thanks!


Changing a group name in AD, effects?

Question: If I change an AD security group name from "name1" to "name2". Will that effect foldershares that are shared out to the group "name1"? Will it automatically be updated to "name2", or will I get trouble?
Answer: That don't have any effect on folder shares. Groups are identified by SID which doesn't change if you change group name. If you go to that folder share and take a look at security tab, then you might see old group name there, but it doesn't matter.

Changing a group name in AD, effects?


Allow authenticated user to equally access laravel 5.8 default login page

Question: I dont know how to go about this. I want a loggedin user in my web app to redirect to the login page without having to logout if they want to.
I have tried adding below code constructor method to AuthenticatesUser.php but to no avail.
public function __construct()
{
    $this->middleware('auth',['only' => ['showLoginForm']]);
}

I was also going through the Route.php but can't find my way out.
Answer: In LoginController remove the guest middleware
public function __construct()
{
    //$this->middleware('guest')->except('logout');
}

By default guest middleware will redirect if the user trying to access the route or method is already autheticated.
Basically only non-logged in users will be able to access the routes or method protected by this middleware.
It uses the RedirectIfAuthenticated middleware class so you can modify it to your needs too.


Multivariate Regression Analysis in SPSS

Question: I am using SPSS to perform a multivariate regression analysis. I have 4 factors, Group (1,2), AgeGroup (1,2), Sex (0,1), and handedness (0.1) with 4 dependent variables.
My question relates to interpretation of the outputs.
The ANOVA table presents interactions and main effects which is pretty straight forward.
It is the Beta coefficients that I am wondering about. Beta coefficients are not provided for each of the parameters. Does this relate to a default used by SPSS when the model is created??
Thanks
Comment: Although asked in terms of SPSS, the OP states that the question is about interpretation of the output. That is a statistical issue. IMO, this question should be considered on topic here.
Comment: Can you paste in the output that you got? Can you state the code or options you selected to get the output?
Answer: I think for your factors variables one level (such as male or female)'s $\beta$ will be set to zero automactically, this level is called the referece group. It also called overparameterise for your design matrix since there are linear dependent between the columns of your indicator variables for your factors.
Such as you have a design matrix, the first column is intercept, second column is male, third is female, you can see the sceond(male) and third colmn(female) are linear dependent you need to omit one colunm to solve the linear equations.
$\begin{bmatrix}
 1&1  &0 \\
 1&1  &0 \\
 1&0  &1 \\
 1&0  &1 \\
 1&0  &1 \\
 1&1  &0
\end{bmatrix}$


how to add color to the circle in the switch in android?

Question: I want to create a switch which looks like this
i have done that in this way
<LinearLayout
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Available"
        android:textColor="#82BCB4"
        android:textSize="20sp"
        />
    <Switch
        android:id="@+id/theSwitchId"
        android:textOn=""
        android:textOff=""
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:thumbTextPadding="5dp"
        android:switchMinWidth="90dp"
        android:layout_marginStart="40dp"
        android:minHeight="60dp"
        android:layout_gravity="center|center_vertical" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="UnAvailable"
        android:layout_marginStart="40dp"
        android:textColor="#224e6d"
        android:textSize="20sp"
        />
</LinearLayout>

i am not able to change the height of the switch and it doesnt look how its in this image. Please help me with this
Comment: You can try using a selector as described here: http://stackoverflow.com/a/11499595/1468093
Comment: I am a bit confused with this and completly new to this.. Is it not like this, when i click on the switch the toggle moves from left to right , without putting the images @KamranAhmed
Answer: all you need to do is just use a custom drawable as track of switch
this is the code for custom drawable:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
    <shape android:shape="rectangle">
        <corners
            android:radius="@dimen/_40sdp" />
        <solid
            android:color="@android:color/darker_gray" />
        <padding
            android:bottom="@dimen/_5dp"
            android:left="@dimen/_5dp"
            android:right="@dimen/_5dp"
            android:top="@dimen/_5dp" />
    </shape>
</item>

Further make these modification to your existing layout
add android:thumbTint="@android:color/holo_blue_dark" or any color that meets your requirement
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Available"
    android:textColor="#82BCB4"
    android:textSize="20sp" />

<Switch
    android:id="@+id/theSwitchId"
    android:layout_width="wrap_content"
    android:layout_height="20dp"
    android:layout_gravity="center|center_vertical"
    android:layout_marginStart="40dp"
    android:minHeight="60dp"
    android:switchMinWidth="90dp"
    android:textOff=""
    android:textOn=""
    android:thumbTextPadding="5dp"
    android:thumbTint="@android:color/holo_blue_dark"
    android:track="@drawable/track_background" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="40dp"
    android:text="UnAvailable"
    android:textColor="#224e6d"
    android:textSize="20sp" />

hope this helps
click here to view the resulting screenshot
screenshot
Comment: Thank you @Subir Chakraborty
Answer: In style.xml

And code for switch is like
 <android.support.v7.widget.SwitchCompat
                android:id="@+id/switch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="@dimen/_10sdp"
                app:theme="@style/switchCompatStyle" />

Comment: switch itself is not visible if i add  @Rishabh Mahatha
Comment: Have you added the dependency `compile 'com.android.support:appcompat-v7:25.0.0'` in your gradle file?
Comment: Change your build version to 17
Comment: build is failing.. @Rishabh Mahatha
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/131143/discussion-between-yacky-and-rishabh-mahatha).
Answer: You create Thumb in drawable xml:
thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/ic_thumbselecter"/>
    <item android:drawable="@drawable/ic_thumbselecter"/>
</selector>

And put into switch (in my case I was using that):
<Switch
    app:kswThumbDrawable="@drawable/thumb"/>

Answer: Change the thumb (circle on the switch) color by using:
android:thumbTint="@color/thumbColor"

On your colors.xml:
<color name="thumbColor">#FFFFFF</color>


How do I check if a command prompt command executes valid?

Question: So I want to check if node.js is installed using c# by using this code.
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C node -v";
process.StartInfo = startInfo;
process.Start();

I'm not sure how to check if the command ran successfully. Is it possible in c# and if it is how?
Comment: 95% of process launch issues are caused by launching cmd.exe **instead of the process you are interested in**. This question is no exception.
Comment: You may also want to check the `ExitCode`, in case the error was handled by the process and it returned something other than zero. This of course depends 100% on the process following the exit code guidelines.
Comment: Redirect its standard output (or error), and read all its output, wait for it to exit, parse it, and then you will know. If it's interactive, or pumps to both streams and you need to react as it runs, hook the DataReceived events of the process and track what it outputs as it runs
Answer: Set StartInfo appropiately and redirects the standard output.
var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "cmd.exe",
        Arguments = "/C node -v",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

// Starts the process and reads its output.

proc.Start();
string output = proc.StandardOutput.ReadToEnd();


Sphinx / SphinxQL - Setting weights on select

Question: I'm using Sphinx, and I'm trying to execute the next query in mysql:
SELECT *
FROM `index_efemerides`, `index_programas`, `index_guias_para_el_aula`, `index_producciones_interactivas`
WHERE MATCH('(@(titulo,descripcion,etiquetas) nuevo)')
OPTION `field_weights` = (index_programas.titulo=100, index_programas.etiqueta=15, index_programas.descripcion=5, index_producciones_interactivas.titulo=53, index_producciones_interactivas.etiqueta=13, index_producciones_interactivas.descripcion=5, index_guias_para_el_aula.titulo=52, index_guias_para_el_aula.etiqueta=12, index_guias_para_el_aula.descripcion=5, index_efemerides.titulo=51, index_efemerides.etiqueta=11, index_efemerides.descripcion=5)

But I'm getting the next error msg:
sphinxql: syntax error, unexpected SUBKEY, expecting '=' near '.titulo=100, index_programas.etiqueta=15, index_programas.descripcion=5, index_producciones_interactivas.titulo=53, index_producciones_interactivas.etiqueta=13, index_producciones_interactivas.descripcion=5, index_guias_para_el_aula.titulo=52, index_guias_para_el_aula.etiqueta=12, index_guias_para_el_aula.descripcion=5, index_efemerides.titulo=51, index_efemerides.etiqueta=11, index_efemerides.descripcion=5)'

If I remove the dots it seems to work (not really sure because if i invent a field name, it doesn't show me any error). But i need to set the field weights different per table.
Comment: What are you expecting the dots to do anyway? Sphinx doesnt have subfields.
Comment: I am using real time indexes.
So i have 4 tables, one for each index. Most of them have the same field names. So i need to set different weights to index_programas.titulo and index_efemerides.titulo.
Answer: I've just found index_weight property. A possibility is to complement index_weight with field_weights like this:
SELECT * FROM `index_efemerides`, `index_programas`, `index_guias_para_el_aula`, `index_producciones_interactivas` WHERE MATCH('(@(titulo,descripcion,etiquetas) nuevo)') OPTION `field_weights` = (titulo=100, etiqueta=15, descripcion=5), `index_weights` = (index_programas=100, index_guias_para_el_aula=50, index_efemerides=75, index_producciones_interactivas=25);

Not pretty sure of the resulting weight.


Get a Steam key from a txt file then move it to another

Question: I'm currently working on a Steam bot project that trades Steam items for Game keys. I'm already done with all the trading part, and the only part missing now is the part where the script actually looks for a key in my txt file. (one key per line)
I have a variable ready called totalKeyWeGive that outputs 1 , 2 , 3 etc depending on how many keys is the user buying.
So now I want to 1. get 1 , 2 , 3 etc keys from my file, then move these used keys to another file.
How can I do that ?
this is the part that I need to modify (everything is working) :
<code>offer.accept(offer);
console.log("OFFER ACCEPTED");

//loop on how much we give the key

    //get steamkey from file here ------

}

var textMsg = "Hello ! You bought "+totalKeyWeGive+ " Game keys. Your keys are: "
}

client.chatMessage(offer.partner.getSteamID64(), textMsg);
</code>
Thanks to everyone who will take the time to read this post. It's kinda messy, sorry about that :/
Answer: Not sure how the keys are organized in the txt file, but assuming they are one per line you could do something like this: https://stackoverflow.com/a/38843461/4686055
That is, before removing the line, save it in memory and write it to the target file.
Send an interval to slice() to remove multiple lines. Check this out for an example of how it works: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Hope this helps!
Update: an alternative approach could be to use the readlines module instead of reading the entire file into memory: https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line


Binary expansion

Question: I am trying to get my head around the left and right shift for binary expansion.
The rules are:
Shifting to the right corresponds to division by 2.
Shifting to the left corresponds to multiplication by 2.
This means if we have: 0.001100110011... = 1/5
If we shift this to the right we get 0.0001100110011... = 2/5 because 1/5÷2 = 2/5
If we shift this to the right we get 0.01100110011... = 1/10 because 1/5÷ 1/10
My question is, how do we get from  0.001100110011 to 1/5? ive tried binary expansion ie
0x2^-1 + 1x2^-2 + 1x2^-3 and so on...
But I get:
819/2048
This isnt 1/5.
Any suggestions?
Answer: What you have is $0.\overline{0011}$.  The rule is that if you have a string of $n$ repeating symbols corresponding to the number $m$ in base $k$, then this repeating decimal corresponds to the fraction
$$\frac{m}{k^n - 1}$$
One way to see that this holds is that multiplication by $k^n$ would correspond to left shifting $n$ times.  In this case, we would get $11.\overline{0011}$.  Subtracting the original expression $0.\overline{0011}$ (before left shifting) gives us the number $m$.
So here, $n = 4$, $m = 3$, and $k = 2$, and the value of the decimal is
$$\frac{3}{16-1} = \frac{1}{5}$$

Binary expansion


LP - Artifical variable necessary or not for greater than sign

Question: I am current studying LP and also the simplex method. However, the slides from my professor are not that detailed so I was trying to search for online resources. Particularly about how to convert an LP to standard form (In our definition, all equations need to be in equal signs)
However, I have been getting different answers regards what should you do when you encounter a $\geq$ sign.
One book (Larson, Elementary Linear Algebra) explained that all you have to do is to add a surplus variable. Ex:
$$
5x_1+3x_2 \geq 10 \to 5x_1 + 3x_2-x_3 = 10
$$
However, another book (Intro to OR by Hillier) and some other resources stated that not only a slack variable is needed, but we also need to introduce an artificial variable. (And thus using either "Big-M method" or the "two-phase method" to solve it)
$$
   5x_1+3x_2 \geq 10 \to 5x_1 + 3x_2-x_3 + \overline{x}_5 = 10 \\
\text{where } \overline{x}_5 \text{ is an artificial variable}
$$
I am not really sure which way is the correct way
Comment: Add a slack to find the standard form. Add an artificial variable to solve phase 1.
Comment: You need a basic feasible solution. In your case $(x_1,x_2,x_3,x_5)=(0,0,0,10)$
Answer: They're both correct, however the first book forgot$^{(1)}$ to mention that you should add an artificial variable as if we took the following:
$$
5x_1+3x_2 \geq 10 \to 5x_1 + 3x_2-x_3 = 10
$$
and put it into a tableau we would get:
\begin{array} {|c|c|}
\hline BV & x_1 & x_2 & x_3 & RHS\\
\hline ? & 5 & 3 & -1 & 10 \\ \hline
\end{array}
since we have no starting basic variable for the Simplex Method, we'd be forced to make one like so:
\begin{array} {|c|c|}
\hline BV & x_1 & x_2 & x_3 & RHS\\
\hline x_1 & 1 & \frac{3}{5} & -\frac{1}{5} & 2 \\ \hline
\end{array}
$$\text{or}$$
\begin{array} {|c|c|}
\hline BV & x_1 & x_2 & x_3 & RHS\\
\hline x_2 & \frac{5}{3} & 1 & -\frac{1}{3} & \frac{10}{3} \\ \hline
\end{array}
$$\text{or}$$
\begin{array} {|c|c|}
\hline BV & x_1 & x_2 & x_3 & RHS\\
\hline x_3 & -5 & -3 & 1 & -10 \\ \hline
\end{array}
The third tableau is invalid if $x_3$ has the non-negativity constraint $x_3\ge0$. The above only really works if we have only one constraint in the model, or if $x_1$ or $x_2$ only appears in this constraint and no other.
Suppose we have the following constraints of a model:
$$5x_1+3x_2 \ge 10$$
$$x_1+x_2 \le 5$$
Since we cannot simply add just a negative slack to the first constraint as we'll have no starting basic variable in that row, and we can't just modify $x_1,x_2$, or $x_3$ to be a starting basic variable, we'll have to add an artificial variable like so:
$$5x_1+3x_2 -x_3+a_1= 10$$
$$x_1+x_2 +x_4 = 5$$
Where $a_1$ is the artificial variable. Which will look like the following in the initial tableau:
\begin{array} {|c|c|}
\hline BV & x_1 & x_2 & x_3 & x_4 & a_1 & RHS\\
\hline a_1 & 5 & 3 & -1 & 0 & 1& 10 \\
\hline x_4 & 1 & 1 &  0 & 1 & 0 & 5 \\ \hline
\end{array}
However, the introduction of an artificial variable does impact our objective function in a significant way. Thus, you should look into the Big-M and the Two-Phase methods for more information on how to add artificial variables into the objective function.

$(1)$ Forgot is a loaded term, they might have meant for the reader to be creative on trying to derive a basic variable without trying to use the artificial variable technique like what was shown, as it is often better for a model to not ever have to deal with artificial variables.


How to make ad login faster?

Question: I work at a medium sized organisation with high staff turnover and internal movement(1) and I've noticed a consistent problem for our new users that each time they visit a new PC - and they are required to do this a lot over the first two years of they career - the login process with their AD account takes a long time.
The login process is slow because it creates then updates a local profile.(2)
I understand this situation arose a number of years ago when roaming profiles where slow and would have had a detrimental effect on our network.
What are our options for speeding the login process? Have roaming profiles improved in both the network load and speed of login?
Its worth bearing in mind that while the users suffering the most are a minority (less than %10 of the workforce), they are key front line staff and are not only  vital to the organisation, but any impact we can make to improve their use of IT will improve the level of service we can provide.
(1) Normal in a hospital.
(2) it is also a common IT support strategy to delete unused local profiles on machines where dozens (maybe hundreds) of local profiles have been created.
Comment: Based on your description, the issue sounds relegated to roaming profiles and poor network bandwidth.  I don't know what your network topology looks like (switches and server types), so I can only guess at this point.  If you provide more info, I can give you a better answer.  As for your additional questions; those are in regards to company/hospital policy--check with your CIO or Director for directions how to manage those local profiles.
Answer: (1)Normal in a hospital? Not sure there
(2) Deleting local profiles is common and in fact was recommended and encouraged in Citrix environments. So that aspect is normal or at least in regular use in IT for many years.

I imagine there are security considerations there as local cache and working files would be left around with the profile for exploit.
Some consideration is made for efficiency there too as profiles can get quite large

Roaming profiles can be quite a handful unless all of your workstations are exactly the same also they do have an impact on network and server load and space.
So you are faced with a decision:

Do I use some user time to generate a local profile and put in the maintenance required to clean up periodically (not a huge task using delprof)?
Do I use server space and network bandwidth to copy a profile down to the workstation?

More of a resource decision in my opinion and really hard to answer without ALOT of specifics. Your mileage may vary based on those specifics.

How to make ad login faster?


S2D - How to reclaim space?

Question: I have a Windows Server 2016 failover cluster with storage based on S2D (Storage Spaces Direct).
I recently noticed that if I delete something (VHDX files of virtual machines) the space of the deleted items is not reclaimed.
For example before deleting 500GB VHDX file I had 200GB free and after deleting that VHDX file I still have 200GB free.
Two questions:

Is it normal for S2D?
How to reclaim free space?

Thanks.
Comment: Thanks@BaronSamedi1958.
So eventually free space will be reclaimed? I would rather avoid playing with PS cmdlets as this S2D turned out to be extremely fragile and highly unreliable. :)
Answer: Yes, there's sort of a delay in seeing your freed space back.
Try these PowerShell cmd-lets:
<code>
Optimize-StoragePool -FriendlyName "POOL_NAME"

Optimize-Volume -DriveLetter <DRIVE_LETTER:> -ReTrim -SlabConsolidate

</code>
You should see results immediately.

S2D - How to reclaim space?


Python: screenshot em loop salvando por cima

Question: Por qual motivo o código abaixo salva o arquivo um por cima do outro?
Eu desejo que a cada screenshot gere um arquivo separado dentro da pasta especificada.
import datetime
import pyautogui
import time

#armazena o nome do arquivo no formato dinâmico de ano-mês-dia_hora minuto_segundo, assim: "2018-05-09_224510.png"
nomeArquivo = datetime.datetime.now().strftime('%Y-%M-%d_%H%M%S'+'.png')

#loop para ficar tirando foto da tela de 10 em 10 segudos.
while True:
    foto = pyautogui.screenshot() #faz a foto
    foto.save('C://Users//WJRS//' + nomeArquivo) #salva na pasta indicada.
    time.sleep(10) #atraso de 10 segundos entre uma screenshot e outra.

Answer: Porque o nome do arquivo só é definido uma vez, quando o código é iniciado. Assim, todos as capturas de tela terão o mesmo nome e, consequentemente, sobrescreverá o arquivo anterior. Para evitar isso, você precisa atualizar o nome do arquivo conforme o horário colocando a definição do mesmo dentro do laço:
while True:
    nomeArquivo = datetime.datetime.now().strftime('%Y-%M-%d_%H%M%S'+'.png')
    foto = pyautogui.screenshot()
    foto.save('C://Users//WJRS//' + nomeArquivo)
    time.sleep(10)

Comment: Poxa vida! Verdade! Muito obrigado Anderson Carlos. Eu confesso que eu estava esgotado ontem, após 8 horas de trabalho e mais 3 horas de estudos eu já não estava bem... Muito obrigado!


Can you programmatically look up a word in the Mac OS's built-in dictionary?

Question: I'd like to have a program of mine retrieve a definition of a word. Is there a way to access the built-in dictionary using Objective-C? (i.e. the one that Dictionary.app and command-control-D use)
Answer: You can take a look at Apple's Dictionary Services Programming Guide.


how to update textview not from main thread?

Question: I have two applications one is the service and one is the client
the client is connected to the service application via AIDL .
when the client receives data from the service I want it to display it in a textView, however I am unable to update the textView , I get the following error :
*** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
            at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4039)
            at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:709)
            at android.view.View.requestLayout(View.java:12675)
            at android.view.View.requestLayout(View.java:12675)
            at android.view.View.requestLayout(View.java:12675)
            at android.view.View.requestLayout(View.java:12675)
            at android.view.View.requestLayout(View.java:12675)
            at android.view.View.requestLayout(View.java:12675)
            at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:268)
            at android.view.View.requestLayout(View.java:12675)
            at android.widget.TextView.checkForRelayout(TextView.java:6773)
            at android.widget.TextView.setText(TextView.java:3306)
            at android.widget.TextView.setText(TextView.java:3162)
            at android.widget.TextView.setText(TextView.java:3137)
            at com.tfl.tfltemperatureapplication.MainActivity.DisplayTemp(MainActivity.java:139)
            at com.tfl.tfltemperatureapplication.MainActivity$1.onSuccess(MainActivity.java:84)
            at com.tfl.extprotocolservice.IParameterCallBack$Stub.onTransact(IParameterCallBack.java:54)
            at android.os.Binder.execTransact(Binder.java:338)
            at dalvik.system.NativeStart.run(Native Method)

My client code :
public class MainActivity extends ActionBarActivity implements ServiceConnection {
    double temperature;
    TextView frontTemp,rearTemp;
    private IParameter binding=null;
    public static final int FRONT_TEMPERATURE_PARAMETER=262;
    public static final int REAR_TEMPERATURE_PARAMETER=263;

    public static final String TAG="TEMPERATURE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(activity_main);
        frontTemp= (TextView) findViewById(R.id.front_temp);
        rearTemp= (TextView) findViewById(R.id.rear_temp);
        connectToService();
    }

    public void connectToService() {
        Intent implicit = new Intent(IParameter.class.getName());
        List<ResolveInfo> matches = getPackageManager().queryIntentServices(implicit, 0);
        if (matches.size() == 0) {
            Toast.makeText(getApplicationContext(), "Cannot find a matching service!", Toast.LENGTH_LONG).show();
        } else if (matches.size() > 1) {
            Toast.makeText(getApplicationContext(), "Found multiple matching services!", Toast.LENGTH_LONG).show();
        } else {

            Intent explicit = new Intent(implicit);
            ServiceInfo svcInfo = matches.get(0).serviceInfo;
            ComponentName cn = new ComponentName(svcInfo.applicationInfo.packageName, svcInfo.name);
            explicit.setComponent(cn);
            ComponentName myService=startService(new Intent(this,IParameter.class));
            bindService(explicit, this, Context.BIND_AUTO_CREATE);

        }
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.d(TAG, "Connected to service");
        Thread t1=new Thread(new BindingToService(service));
        t1.start();

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        binding=null;

    }
    IParameterCallBack.Stub cb=new IParameterCallBack.Stub(){

        @Override
        public void onSuccess(int parameter, int value) throws RemoteException {
            temperature=ConvertToCelcius(value);
            DisplayTemp(parameter,temperature);

        }

        @Override
        public void onFailure(String msg) throws RemoteException {
            Log.d(TAG,"Failed to receive parameter: "+msg );

        }
    };

    public class BindingToService implements Runnable{
        IBinder service;
        public BindingToService(IBinder service){
            this.service=service;
        }

        @Override
        public void run() {
            binding=IParameter.Stub.asInterface(service);
            while(true){
                try {
                    binding.askForParameter(FRONT_TEMPERATURE_PARAMETER,cb);
                } catch (RemoteException e) {
                    Log.e(TAG, "" + e);
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    binding.askForParameter(REAR_TEMPERATURE_PARAMETER, cb);
                } catch (RemoteException e) {
                    Log.e(TAG, "" + e);
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    }
    public static double ConvertToCelcius(int temperature){
        return (double)temperature*0.00390625-273;
    }

    public void DisplayTemp(int parameter,double temperature){
        if(parameter==262){
            frontTemp.setText(""+temperature);
        }
        if(parameter==263){
            rearTemp.setText(""+temperature);
        }
    }

Comment: you can use `runOnUiThread` or `Handler` concept
Answer: Instead of using
textView.setText("text");

use
textView.post(new Runnable(){
    @Override
    public void run(){
        textView.setText("text");
    }
};

This can be called from any Thread and will always execute the Runnable action on the UI Thread. Also, it does not require you to have a reference to a Context object, which saves you from making unneeded cross-references.
Answer: you can use
runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //do your UI related operation
        }
    });

Comment: This will work fine, but it requires the caller to implement Context or have a Context reference. In complex application it is not a given, please see my answer.