text:
Q: How to detect all imges loading finished in AngularJS I want to use ng-repeat to show more then 100 images in a page. Those images are taking significant time in loading and i don't want to show them getting loaded to the users. So, I only want show them after all of them are loaded in the browser.
Is there a way to detect, if all the images are loaded?

A: you can use load event like this.
image.addEventListener('load', function() {
       /* do stuff */
});

Angular Directives
Solution for single image
HTML

        <loaded-img src="src"></loaded-img>
        '

JS
var myApp = angular.module('myapp',[]);
myApp
    .controller('MyCtrl1', function ($scope) {
            $scope.src = "http://lorempixel.com/800/200/sports/1/";
            $scope.src2 = "http://lorempixel.com/800/200/sports/2/";
    })
    .directive('loadedImg', function(){
        return {
            restrict: 'E',
            scope: {
                src: '='
            },
            replace: true,
            template: '',
            link: function(scope, ele, attr){
                ele.on('load', function(){
                    ele.removeClass('none');
                });
            }
        };
    });

CSS
.none{
    display: none;
}

http://jsfiddle.net/jigardafda/rqkor67a/4/
if you see the jsfiddle demo, you will notice src image is only showing after  image is fully loaded whereas in case of src2 you can see image loading.(disable cache to see the difference)
Solution for multiple images
HTML

            <loaded-img isrc="imgx.path" onloadimg="imgx.callback(imgx)"></loaded-img>

JS
var myApp = angular.module('myapp',[]);
myApp
    .controller('MyCtrl1', function ($scope, $q) {

        var imp = 'http://lorempixel.com/800/300/sports/';

        var deferred;
        var dArr = [];
        var imgpaths = [];

        for(var i = 0; i < 10; i++){
            deferred = $q.defer();
            imgpaths.push({
                path: imp + i,
                callback: deferred.resolve
            });
            dArr.push(deferred.promise);
        }

        $scope.imgpaths = imgpaths;

        $scope.hideall = true;

        $q.all(dArr).then(function(){
            $scope.hideall = false;
            console.log('all loaded')
        });
    })
    .directive('loadedImg', function(){
        return {
            restrict: 'E',
            scope: {
                isrc: '=',
                onloadimg: '&'
            },
            replace: true,
            template: '',
            link: function(scope, ele, attr){
                ele.on('load', function(){
                    console.log(scope.isrc, 'loaded');
                    ele.removeClass('none');
                    scope.onloadimg();
                });
            }
        };
    });

To detect if all images are loaded,
for each image i generated a deferred object and passed its deferred.resolve as a image onload callback of the directive and then pushed that deferred objects promise in an array. and after that i used $q.all to detect if all those promise are yet resolved or not.
http://jsfiddle.net/jigardafda/rqkor67a/5/
UPDATE: angular way added.
UPDATE: added solution for loading multiple images.

A: Check if all images are loaded
jQuery.fn.extend({
  imagesLoaded: function( callback ) {
    var i, c = true, t = this, l = t.length;
    for ( i = 0; i < l; i++ ) {
      if (this[i].tagName === "IMG") {
        c = (c && this[i].complete && this[i].height !== 0);
      }
    }
    if (c) {
      if (typeof callback === "function") { callback(); }
    } else {
      setTimeout(function(){
        jQuery(t).imagesLoaded( callback );
      }, 200);
    }
  }
});

*

*Callback occurs when all images are loaded

*image load errors are ignored (complete will be true)

*Use:

$('.wrap img').imagesLoaded(function(){
    alert('all images loaded');
});
Note : this code worked for me, Source :
http://wowmotty.blogspot.in/2011/12/all-images-loaded-imagesloaded.html


text:
Q: convert a function outputting string new line by new line to list i have a function that is generating string elements using a for loop like this:
a
b
c
d
....

how can i convert my ouput to list like:
['a','b','c','d'...]

and so on..
the function is as follows:
def proper_lemmatize_sentence(sent, cond):
    tokens = word_tokenize(sent)
    tagged_tokens = pos_tag(tokens)
    for tagged_token in tagged_tokens:
        word = tagged_token[0]
        if cond:
            word_pos = tagged_token[1]
        else:
            word_pos = 'n'
        word_pos1 = get_wordnet_pos(word_pos)
        lemma = wnl.lemmatize(word, pos=word_pos1)
        print(lemma)

A: Create the list before the loop; append to the list at the bottom of the loop; then return (or print) the list when the loop completes.
s = 'abcde'
def f(sequence):
    result = []
    for lemma in sequence:
        # do stuff
        result.append(lemma)
    return result

>>> print(f(s))
['a', 'b', 'c', 'd', 'e']
>>>

A: Try with:
text = text.split('\n')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show that the composition operator is a bounded linear operator. Problem: Fix a continuous function $\phi:[0,1]\to[0,1]$ and define the operator $C_\phi:C([0,1])\to C([0,1])$ by $(C_\phi f)(x)=f(\phi(x)).$ Prove that this is a bounded linear operator with $\|C_\phi\|\le1$.
Attempt: Consider $\|C_\phi\|_{op}$, now,
$$\|C_\phi\|_{op}=\sup\{\|C_\phi f\|_\infty:f\in C([0,1])\}=\sup\{\sup\{|(C_\phi f)(x)|:x\in[0,1]\}:f\in C([0,1])\}$$
Regard the "inner supremum" on it's own for the time being. Using the definition of $C_\phi$ we see that,
$$\sup\{|(C_\phi f)(x)|:x\in[0,1]\}=\{\sup\{|f(\phi(x))|:x\in[0,1]\}$$
Since $\phi:[0,1]\to[0,1]$ it is clear that $\phi(x)=y$ where $y\in[0,1]$, we get that,
$$\sup\{|f(\phi(x))|:x\in[0,1]\}=\sup\{|f(y)|:y\in[0,1]\}=\|f\|_\infty$$
So that, going back to the "sup of the sup" we had before,
$$\sup\{\sup\{|(C_\phi f)(x)|:x\in[0,1]\}:f\in C([0,1])\}=\sup\{\|f\|_\infty:f\in C([0,1])\}=\|f\|_\infty$$
But then, putting this all together, we have that $\|C_\phi\|_{op}=\|f\|_\infty$, and I don't believe that this is right. I think that it is, rather, an incorrect means to approach the problem.
--
On the other hand if we just considered,
$$\|C_\phi f\|_\infty=\sup\{|(C_\phi f)(x)|:x\in[0,1]\}=\sup\{|f(y)|:y\in[0,1]\}=\|f\|_\infty$$
So that in particular, $\|C_\phi f\|_\infty=\|f\|_\infty$ which would mean that $\|C_\phi\|_{op}=1$. Now saying that something is equal to something does still satisfy saying that it is less than or equal to something. So I have to wonder, is this sufficient to answer the problem? Or have I done something wrong, this second time round, which has made it seem easier than it should?

A: Since linearity is trivial, all you have left to prove is $\forall f\in C([0,1]), \|C_{\phi}f\|\leq\|f\|$.
Note that $\{|f(\phi(x))|, x\in [0,1]\}\subset \{|f(x)|, x\in [0,1]\}$, thus $$\sup\{|f(\phi(x))|, x\in [0,1]\}\leq \sup \{|f(x)|, x\in [0,1]\}$$
which rewrites as $\|C_{\phi}f\|\leq\|f\|$.


text:
Q: Appending value in websql to a html textbox Please can someone suggest a better way to do this, I want to append a user phone number in web sqldatabase to all textbox with id userphone in all other pages. Such that one the user registered the detail will be saved to web sqldatabase and later once needed it will be fetch from that websqldatabase. This the code indly review it please
addfrd(){
 if (!window.openDatabase) {
  alert('Databases are not supported in this browser.');
  return;
 }
 db.transaction(function(tran) {
   tran.executeSql('SELECT * FROM User', [],function(tx, result) {
        for (var i = 0; i < result.rows.length; i++) {
         var  a = result.rows.item(0)['phoneN'];
         document.getElementById("userphone").value=a;
        }

     },errorHandler);
 },errorHandler,nullHandler);

//$('#userphone').hide();
 $("#Addingfriend").click(function(){
  var frdname = $("#frdname").val();
  var userphone=$("#userphone").val();
 var frdphone=$("#frdphone").val();
 var dataString="frdname="+frdname+"&userphone="+userphone+"&frdphone="+frdphone+"&Addingfriend=";
 if($.trim(frdname).length>0 & $.trim(userphone).length>0 & $.trim(frdphone).length>0)
 {
 $.ajax({
 type: "POST",
 url:"http://localhost/phonegap/addingfriend.php",
 data: dataString,
 crossDomain: true,
 cache: false,
 beforeSend: function(){ $("#Addingfriend").val('Connecting...');},
 success: function(data){
 if(data=="ok")
 {
 alert("you Have successfully added a friend");
 $("#Addingfriend").val('submit');
 AddValueToFrd();
 }
 else if(data=="Number Not Exist")
 {
 alert("Either your friend has not registered or You added yourself!");
 }
 }
 });
 }else{
 alert("Fill up all fields");
 }return false;
 });
 }

 //
 function AddValueToFrd() {
    if (!window.openDatabase) {
        alert('Databases are not supported in this browser.');
    return;
    }
 db.transaction(function(trans) {
   trans.executeSql('INSERT INTO Friends(friendName,yourphn,friendPhone) VALUES (?,?,?)',[$('#frdname').val(), $('#userphone').val(),$('#frdphone').val()], nullHandler,errorHandler);
   });
alert('successfully added friend');
 return false;

}


text:
Q: Getting the data from backend to display it on Front end in X-CART I am working on a X-Cart Module. I need the backend configuration values to the front end. In admin/configuration file I have created an array which contains the value which I need to use it in adv_search.php which is in the root folder. I don't know how to pass that array to adv_search.php.
Thanks in advance.

A: It is not quite clear how you store the configuration values. It may be easier to store them in the table xcart_config and access them directly as $config['Option-category']['option_name'] in php files and {$config.Option-category.option_name} in the Smarty-templates.
Or just define an array in module's config.php file and this array will be available everywhere in php-scripts. Look at the modules/UPS_OnLine_Tools/config.php file for example.


text:
Q: How to use Spring method DELETE I have some customers in ArrayList and when I want through Postman delete (with id) it is not working : 500 - Internal Error. Please Could someone help me ?

Delete customer
DELETE http://localhost:8080/api/customers/{customerId}

@DeleteMapping("/api/customers{customerId}")
public void deleteCustomer(@PathVariable  Long customerId) {
    customers.remove(this.customers.get(Math.toIntExact(customerId)));

}

A: try like this you did not add "/" in delete mapping.
@DeleteMapping("/api/customers/{customerId}")
public void deleteCustomer(@PathVariable  Long customerId) {
    customers.remove(this.customers.get(Math.toIntExact(customerId)));

}

A: Is this how you send the request?
http://localhost:8080/api/customers/{customerId}

If you are sending like this, it won't work because you gave path like this:
/api/customers{customerId}

In my opinion, either change the path like this:
/api/customers/{customerId}

Or send the request like this:
http://localhost:8080/api/customers{customerId}


text:
Q: how variables are set when using multiple OR (||) operators in Jquery/Javascript? I'm having trouble understanding the order in which an || is executed in Jquery/Javascript.
If I have this:
  someVar = $el.attr("one") || options.two || "three";

it sets someVar to "three" when both $el.attr("one") and options.two are not defined.
I need to add another condition to this statement, like so:
  someVar = $el.attr("one") || options.two || options.extra == "true" ? undefined : "three";

So this should say:
If neither '$el.attr("one")' or 'options.two' are defined, check if 'options.extra == true', if it's true, set to 'undefined', otherwise set to 'three'.
However, I'm always getting undefined even if I set $el.attr("one") and I don't understand why?
Can anyone tell me what is wrong in my logic?
Thanks!

A: I think you must put some parenthesis:
someVar = $el.attr("one") || options.two || (options.extra == "true" ? undefined : "three");

in fact your own code is read as:
someVar = ($el.attr("one") || options.two || options.extra == "true") ? undefined : "three";

A: The reason is that ? : has a weaker binding than || and therefore is evaluated last. This is the same as if you would write:
( $el.attr("one") || options.two || options.extra == "true" ) ? undefined : "three";

which always will yield undefined as the first expression always is true (because you set $el.attr("one"))
That's why you have to take parens to fix that:
$el.attr("one") || options.two || (options.extra == "true" ? undefined : "three");

Check the operator precedence table, it comes in handy in such cases.

A: The way to write it with logic operators only is
  someVar = $el.attr("one") || options.two || options.extra != "true" && "three" || undefined;

...not that I would use that in actual code. (I probably wouldn't mix logic operators with the conditional operator either.)


text:
Q: Problema ao instalar pacote "@material-ui/core" em minha aplicação "create-react-app" Estou obtendo um erro quando tento instalar o pacote @material-ui/core 3.9.0 na minha aplicação.
Quando executo o yarn add @material-ui/core recebo  o seguinte retorno
yarn add v1.12.3
[1/4] Resolving packages...
warning @material-ui/core > compress-buffer@1.2.0: this has been created when no compression library existed for Node.js. This isn't the case for years
warning @material-ui/core > node-uuid@1.4.1: Use uuid module instead
[2/4] Fetching packages...
info fsevents@1.2.4: The platform "linux" is incompatible with this module.
info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
error core@1.0.113: The engine "node" is incompatible with this module. Expected version "0.6 || 0.8". Got "10.15.0"
error Found incompatible module
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Quando tento usando npm install @material-ui/core
npm ERR! code ETARGET
npm ERR! notarget No matching version found for core@^3.9.0
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/robson/.npm/_logs/2019-01-16T18_13_20_542Z-debug.log

Meu atual ambiente é
node v10.15.0
npm 6.4.1
yarn  v1.12.3 (Ps : já tentei com a versão atual v1.13.0)
OS : Ubuntu 18.04

eu executei "npm view @material-ui/core"
E obtive o seguinte retorno
core@1.0.113 | Proprietary | deps: 16 | versions: 448
Core Libs

dist
.tarball: https://registry.npmjs.org/core/-/core-1.0.113.tgz
.shasum: 3d87bff90c63bb1b6192d9051b7f11c6d8142ed4
.unpackedSize: 556.7 kB

dependencies:
amqp-dl: 0.2.4-0       hiredis: ~0.1.17       knox: 0.8.6            node-uuid: 1.4.1       rewire: ~1.1.2         xml2js: ~0.2.8
base64: 2.0.3          iconv: 2.0.6           mime: 1.2.4            pg: 1.1.0              stacktrace: 1.1.0
compress-buffer: 1.2.0 js-yaml: 3.2.3         mysql: 2.0.0-alpha3    redis: ~0.8.4          uriparser: >= 2.1.2

maintainers:
- albert-lacki <albert.lacki@gmail.com>
- aldor <marcin.kaciuba@gmail.com>
- dreamlab <janecki@gmail.com>
- kuebk <kuebzky@gmail.com>
- mkwinta2 <kwinta.mateusz@gmail.com>
- psulowicz <psulow@gmail.com>

dist-tags:
latest: 1.0.113

published 10 months ago by dreamlab <janecki@gmail.com>

Já tentei remover node, yarn, npm e instalar novamente, tentei com outras versões e não obtive sucesso, alguém já teve esse problema ?


text:
Q: The Math class does not appear to exist I think I broke my Flash. I'm using Flash CS5.5, and when I use AS3, any references to the Math class give me errors like this:
1061: Call to a possibly undefined method sqrt through a reference with static type Class.
1061: Call to a possibly undefined method pow through a reference with static type Class.
1061: Call to a possibly undefined method pow through a reference with static type Class.

The code in error is this:
var dist:Number = Math.sqrt(Math.pow(initPos.x - pos.x, 2) + Math.pow(initPos.y - pos.y, 2));

What the heck is going on here? Math is a top-level class, so I don't think I should be getting an error like this. Is it possible to somehow "break" the Math class? If so, how do I fix it?

A: Edited from discussion below
The compiler error reference says that "You are calling a method that is not defined." Math not being defined sounds pretty serious - if you have no idea of why this occurred, maybe reinstall your SDK?

Original answer:
Does other Actionscript work for you? Is it only the Math class that is broken for you? If others are broken too, it's probably a build path configuration issue.
If not, check to make sure that you don't have any class named Math in the package that might interfere.


text:
Q: Improve performance of musical note synthesis using AudioTrack I am trying to build an android app which synthesizes and plays musical notes. I am using AudioTrack. It seems that my program is unable to fill the track buffer fast enough due to the latency in generating the audio information. I am generating the audio info from the fourier coefficients of the note. Hence before each write, the program has to create and sample 2048 sine waves each with a sample size of 2400 and sample rate of 44100!
So instead of a continuous sound I hear intermittent beeps. The Logcat gives the following warning in between beeps:
W/AudioTrack﹕ obtainBuffer() track 0x177ff80 disabled, restarting

My code is given below. Can anyone identify ways in which I could optimize the code?
package com.alantaar.alantaar;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

import java.util.Arrays;

public class AudioGenerator {
    private AudioTrack audio;
    private double[] coefficients;
    private int bufferSize;
    private int sampleRate;
    private double[] phases;
    private double frequency;

public AudioGenerator(double[] coefficients, double frequency, int sampleRate, int bufferSize){
    int minBufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_OUT_MONO,
            AudioFormat.ENCODING_PCM_16BIT);
    this.bufferSize = bufferSize > minBufferSize ? bufferSize : minBufferSize;
    audio = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO,
            AudioFormat.ENCODING_PCM_16BIT, this.bufferSize, AudioTrack.MODE_STREAM);

    this.coefficients = coefficients;
    this.sampleRate = sampleRate;
    this.frequency = frequency;
    this.phases = new double[coefficients.length];
    Arrays.fill(this.phases, 0.0);
    Log.i("length", Integer.toString(coefficients.length));

    audio.play();
}

public void playNote(){
    while(true){
        short[] waveSample = sampleWave();
        audio.write(waveSample, 0, waveSample.length);
    }
}

private short[] sampleWave(){
    short [] waveSample = new short[bufferSize];
    Arrays.fill(waveSample, (short)0);
    for(int i = 0; i < coefficients.length; i++){
        double coefficient = coefficients[i];
        short[] sineSamples = sampleSineWave(coefficient, i);
        for(int j = 0; j < waveSample.length; j++){
            waveSample[j] += sineSamples[j];
        }
    }
    return waveSample;
}

private short [] sampleSineWave(double coefficient, int index){
    double freq = frequency * index;
    short [] samples = new short[bufferSize];
    for(int i = 0; i < bufferSize; i++){
        samples[i] = (short) (coefficient * Short.MAX_VALUE * Math.cos(phases[index]));
        phases[index] += 2 * Math.PI * freq/sampleRate;
    }
    return samples;
}

public void pauseNote(){
    audio.stop();
}

public void stopNote(){
    audio.release();
}

}

A: Here are a few things that pop out at me:

*

*Move computations out of the inner loop.  For example, the 2*pi*freq/sampleRate could be done right before the for. Same with coefficient * Short.MAX_VALUE.

*I'd bet that your note doesn't actually contain 2048 different meaningful sine components.One option would be to NOT generate tones when the coefficient falls below a certain threshold.

*Use FFT! You are implementing a DFT which is O(n^2).  FFT runs in O(n log n).

*Use the time while audio.write is blocking to generate more samples. I don't know the behavior of AudioTrack's streaming mode but there is a good chance that your program is spending most of its time in a blocking call.


text:
Q: Magento 2 products not being added to cart The "Add to cart" button changes to "adding" and stays like that. It does nothing after that.It doesn't work from anywhere not even product details page.

A: Change your base URL from localhost to 127.0.0.1.
Using localhost as the domain in your base URL causes problems in Magento 2.
Magento's base URL configuration is located in the core_config_data table. The following values may need to be changed:

*

*web/unsecure/base_url

*web/secure/base_url
For example, if you previously had http://localhost/yourproject/, you should change it to http://127.0.0.1/yourproject/
After changing the url, flush the cache (bin/magento cache:flush). You might also need to clear out your var directories.

A: go to PHPMyAdmin coreconfigdata
change URL localhost/project to 127.0.0.1/project


text:
Q: Probability that given weight is on the heavier side of a balance Assume we have 6 balls weighting 101, 102, 103, 104, 105 and 106 in kg. If we randomly pick 3 balls and place them on one side of the scale and the other 3 left are placed on the other side of the scale. What is the probability that the ball weighting 106 kg is on the heavier side?

A: Let $X,Y$ be the other two balls on the same side as the $106kg$ ball,
The event "106kg is on the heavier side"($E$) can be expressed as the following:
$$E \iff X+Y+106 \geq \left \lceil \frac{621}{2} \right\rceil = 311 \implies X+ Y \geq 311 - 106 = 205 \implies $$
$$P(E) = P(X + Y \geq 205)$$
If we set aside 106 then $X,Y$ are chosen from the remaining 5 balls, so there are ${5 \choose 2} = 10$ total possibilities. Of these, the ones that result in $205$ or higher are:
$(101,104),(101,105), (102,103), (102,104), (102,105), (103,104),(103,105),(104,105)$
So 8 possibilities out of 10, so $80\%$ probability that the side that htas 106 kg ball is the heavier side..

A: The problem is same as considering the weights $1,2,3,4,5,6$ instead.
There are $\dfrac{6!}{3!3!2!}=10$ ways to divide $6$ distinct objects into two groups of threes. One way, quick enough, is to list out the ten pairs of triples and see for how many cases $6$ belongs to the group with larger sum.
A yet shorter way is to consider the sum $1+2+3+4+5+6=21$. $6$ belongs to heavier side, when sum of three weights including $6$ is more than $21/2=10.5$. Unfavorable cases are only two : $(6,1,2)$ and $(6,1,3)$.
Number of favorable events is $10-2=8$ and required probability is $8/10$.


text:
Q: PSCustomObject and overload method Where I'm poking around a PSCustomObject and the PowerShell ISE auto complete showed me something interesting that I cannot seem to find more information about.
If you've got a variable containing PSCustomObject, there appears to be a not easily found method for filtering.
Would this method for filtering be faster than using the pipeline and Where-Object?
$CusomObject.Where({$_ -like '*hidden*'})

Using $CustomObject | Get-Member -Force does not list this overload.  I found reference to this overload here but cannot seem to find much use of this in my searching.

A: This just appears to execute a script block and confirm the return is True. From limited testing the Where is faster (~1 second ) on a PS Object. Note: Stopwatch may be inaccurate. Where-Object has documentation and executes faster than the ForEach-Object. BeWhere There's bugs in PSv4.
Where Script Block
write-host "Started at $(get-date)"
$j = $i.Where({$_ -like "*"})
write-host "Ended at $(get-date)"
write-host "Total Elapsed Time: $($elapsed.Elapsed.ToString())"

00:00:00.0309266
ForEach-Object
$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
write-host "Started at $(get-date)"
$j = $i | %{$_ -like "*"}
write-host "Ended at $(get-date)"
write-host "Total Elapsed Time: $($elapsed.Elapsed.ToString())"

00:00:01.0555753
Where-Object
$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
write-host "Started at $(get-date)"
$j = $i | ?{$_ -like "*"}
write-host "Ended at $(get-date)"
write-host "Total Elapsed Time: $($elapsed.Elapsed.ToString())"

00:00:00.0348174


text:
Q: Having problems getting divs to line up properly I'm having problems getting some divs to display inline. I've tried a bunch of things but nothing is working correctly. How do y'all normally do it? Floating them? Putting them in a list and lining that up? Maybe I'm not thinking of something =/
Thanks.

A: DIVs are "block" elements by default. If you want inline behaviour, use the style element "display: inline"
-Oisin

A: You can either do it with float, absolute positioning, or tables (not reccommended for layout). Have a look at some tutorials, here's one that'll get you started :D
http://www.456bereastreet.com/lab/developing_with_web_standards/csslayout/2-col/


text:
Q: expo ios app production review rejected due to white blank screen while it is running with expo client in production mode Expo ios app production review is rejecting again and again due white blank screen while it is running as expected without any error with expo client in production mode.
Unable to reproduce on my local env.
However, I tried
expo start --no-dev --minify

It is also working as expected without any issue


text:
Q: Как применить директиву после окончания загрузки данных Имеется в HTML коде таблица

                {{item.Id}}
                {{item.Name}}

JS код

Серверный код
public IHttpActionResult GetValues()
{
    return Ok(JsonConvert.SerializeObject(db.Values));
}

Проблема в том, что данные приходят позже, чем отрисовывается таблица, а нужно, чтобы таблица рисовалась когда в ней уже есть данные. Как это реализовать?


text:
Q: Java Applet code changes not reflected in browser Applet viewer issue
I have written code for applet application. The application changes hasn't reflected properly, while loading browser.
Even I am just commenting some part of applet coding.
I have following below steps to load application in browser (every change).

*

*Clear browser history

*Clear objects

*Clear java cache
After doing this all, application working as expected.

Why it's not reflected immediately, if any changes happened?
Browser : IE 11.0.145
Java    : 1.8.0.66
We are loading dependency (jar) files using JNLP file format.
Kindly assist me on this.


text:
Q: Database Facade to wrap our existing queries? We have a very big application written in C++ using the MFC framework (millions of code lines). No need to say that it's a legacy system, but it's also heavily maintained and updated. This application lacks a lot of architecture. For example, we have a lot of classes that do queries directly to the database, which creates a lot of difficulty for unit testing.
I have read the book Working Effectively With Legacy Code, and one of the most important things to do first is to create some kind of architecture so we can separate the GUI from the logic and from the database.
My idea to go towards this is to create something like a database facade. There will be 2 goals for this:

*

*Encapsulate all the calls to the database behind this facade.

*Be able to test the facade in batch to detect errors in the SQL very fast.

The database facade itself will be implementing an IDatabaseXXXX interface so it could be easily mocked in the unit tests. The second goal will be to be able to run all the functions in the facade in batch to test if there are errors in the SQL queries. I don't count them as unit tests and would be running them only once per day.
My main concern about doing this is that I don't know if there is an existing framework or library to take care of this abstraction. As far as I know, there are some on other platforms like .NET, but it seems that for C++ or MFC, there are not a lot of options. Like I said, the application is very big and the change will be done slowly, mostly when new queries are added to the software.
I think it is a good thing to add that we also have a LOT of recordsets (one for almost each object). For the moment, I don't know how to deal with them, so I kept them on the side and decided to deal with the regular SQL queries. But if you have suggestions to deal with recordsets, I will be glad to hear them.
So my main question is: Is this whole idea of database facade worth trying? Is there any library of framework to help me in this adventure? If there are C++/MFC programmers out there, how do you deal with the abstraction of the query to the database?
Thanks!
EDIT
Some people on the chat suggest looking up at repository pattern which I knew from the world of MVC 3. Any suggestion or tutorial about the repository pattern in C++? Most of what I found is in the .NET world.

A: As your update suggets, the repository pattern would be able to help seperate the database calls from your UI. And replacing the database calls with calls to an IDatabase interface is certainly an improvement. The repository pattern will allow you to further abstract the the data retrieval into something meaningful to the application. UserRepository, ThingRepository, etc.
http://msdn.microsoft.com/en-us/library/ff649690.aspx
As an approach to implementing this architecture. When I need to make code testable to refactor the first test is always the hardest. Find a well understood piece of code that you want to test and make that class/method testable. Once this is in place it is persistence and patience that will allow you to complete the task of introducing the new architecture into the legacy system.

A:
I have read the book Working Effectively With Legacy Code, and one of the most important
  things to do first is to create some kind of architecture so we can separate the GUI from
  the logic and from the database.

That would be how to read the legacy code and then rewrite the system in a new platform.  But you can't honestly expect to actually do this in the legacy code itself.  Adding architecture to legacy code after the fact...that just doesn't sound feasible in the real world.


text:
Q: Initialize a const char* Array I'm working in C++17 project, but have to use a C-legacy-library. For this I have to create a const char* array in C-style, but im struggling with the initialization. In particular,
#include <iostream>

int main(int argc, char* argv[])
{
    const int bound = 3;

    const char* inames[bound]{ "" };
    for(unsigned int i = 0; i < bound; i++) {
        const char *number = std::to_string(i).c_str();
        inames[i] = number;
    }

    for(unsigned int i = 0; i < bound; i++) {
        std::cout << "inames["
                  << std::to_string(i)
                  << "] = "
                  << inames[i]
                  << std::endl;
    }

    return 0;
}

returns
inames[0] = 2
inames[1] = 2
inames[2] = 2

as output, which I don't unterstand. I expected the output to be
inames[0] = 0
inames[1] = 1
inames[2] = 2

Can anyone please help me point me to my error?

A: You code has undefined behavior.
std::to_string(i).c_str()

You are creating a temporary std::string instance, then getting its internal const char* pointer. At the end of the line the temporary instance is dead, so the pointer is now dangling.

A: The problem is you don't have anywhere to actually store the strings themselves, only the pointers to them.
By doing it this way, the strings are stored in std::strings while beeing referenced by the plain C array:
const int bound = 3;
std::vector<std::string> strings(bound);
const char* inames[bound];
for (unsigned int i = 0; i < bound; i++) {
    strings[i] =  std::to_string(i);
    inames[i] = strings[i].c_str();
}


text:
Q: Remove a class from all ID's that begin with username- I have a bunch of elements that look like

I need to loop through all of them on the page and remove a class from them using jQuery.
How can I do this? I don't know all the ID's so I need to search for all matching username.

A: This should do it with the attributeStartsWith selector:
$('div[id^=username-]').removeClass('myclass');

Presumably, however, you have control of these
s as they are printed onto the page. It would be in better taste to simply give them all a class signifying they are a "user div", so then you can just do:
$('div.user').removeClass('myclass');

This would be both faster and cleaner.


text:
Q: Can't find error in my sum-of-squares code def sum_of_squares(n):
  for i in range(1, n):
    for j in range(1, n):
      if n == i*i + j*j:
        return True
        break
      else:
        return False

A: A more efficient way would be to do it like that:
import math
def is_sum_of_squares(n):
    s=set()
    if 2*int(math.sqrt(n/2.0))**2==n:
        return True
    for i in range(1,int(math.sqrt(n)+1)):
        if n-i**2 in s:
            return True
        else:
            s.add(i**2)
    return False

Here you do only one iteration and only until the square root. The first if checks if n is a sum of two equal squares (like 8=4+4), as this case is not covered in the for loop.

A: you have to test for all values and not returning if the first try is not equal.
def sumofsquares(n):
  for i in range(1, n):
    for j in range(1, n):
      if n == (i*i) + (j*j):
        return (true)
  return (false)

you may also use pow:
pow(i, 2) + pow(j, 2)

or:
(i**2) + (j**2)

A: It's not correct because no matter what the n is, the function will will return after the first check. You should put the return False out of the two loops like:
def sumofsquares(n):
for i in range(1, n):
    for j in range(1, n):
        if n == ((i * i) + (j * j)):
            return True
return False

It would be better if j starts from i:
def sumofsquares(n):
    for i in range(1, n):
        for j in range(i, n):
            if n == ((i * i) + (j * j)):
                return True
    return False


text:
Q: What is the grammatical role of "that" in "the percentage that + clause"? I am confused with the role of "that" and the clause that follows in the passage below. Is the "that-clause" grammatical here? If no, how should it be put in a grammatical manner? If yes, what is the grammatical role of "that" (like complementizer, relative pronoun? ) and how to analyze the structure of the clause?
"[...] In 2005, Iceland's pay gap showed that women were, on average, still being paid only 64.15% of what men earned. So, on the thirtieth anniversary of the Women's Day Off, women organized another strike and left work at 2:08 p.m., shortening their workday by the exact percentage that their salaries were lower than men's. In 2016, women in Iceland again left work early, this time at 2:38 p.m. [...]"
Your help and clarification are much appreciated!

A: It is not how I would express it. I would say the exact percentage by which their salaries were lower than men's.
However, "by which" is somewhat formal, and people will often prefer to turn it round, and leave the preposition at the end of the relative clause:

the man to whom I was talking -> the man [who/whom/that] I was talking to

If you do that in this case, you get

the exact percentage that their salaries were lower than men's by.

which is nearly what you quoted. But they left out the final "by" - I suspect that is because of the "by" just before what I quoted.
So I would say that the text is grammatically defective; but that is (as it often is) a complementizer in a relative clause without explicit relative pronoun.


text:
Q: Derivative notation between $D$ and $\nabla$ Sorry if this is likely a duplicate question (and that I am asking two questions) but I am confused on some notation.
For a function $f(x_1, x_2): \mathbb{R}^2 \to \mathbb{R}$, for simplicity, why does the product rule tell us that
$$ \displaystyle Df(x_1, x_2) = \frac{\partial f(x_1, x_2)}{\partial x_1} \ dx_1 + \frac{\partial f(x_1, x_2)}{\partial x_2} \ dx_2 $$
Wouldn't we need a given functional form to know to apply the product rule (ie. if $f(x_1, x_2) = x_1 / x_2$ then we apply the quotient rule.
Further given the above, since the codomain of $f$ is scalar, it does not seem to match the following identity:
$$ \nabla f= [Df]^T $$
That is $Df$ is the transpose of the gradient of $f$, a vector.
(edit: I read these in Microeconomic Theory by Mas-Collel, Whinston and Green)

A: That isn't the product rule. That is the exterior derivative of $f$. You know that $df$ is a 1-form with the property that if $v_p \in T_p\mathbb{R}^n$ then;
$$(df)(v_p) = v_p[f]$$
However since $df$ is a one form, if you select $x^1,...,x^n$ to be the standard coordinate functions on $\mathbb{R}^n$ then;
$$df = \sum_j \alpha^j \cdot dx^j$$
where $\alpha^j$ is smooth. Moreover, we know that if we let $p \in \mathbb{R}^n$, then with this selection of coordinates;
$$\left\{\frac{\partial}{\partial x^j}\Bigr|_p: j = 1,...,n\right\}$$
is a basis for $T_p\mathbb{R}^n$ with corresponding dual basis;
$$\{(dx^j)_p: j=1,...,n\} \Rightarrow dx^j\left(\frac{\partial}{\partial x^i}\Bigr|_p\right) = \delta_{ij}$$
Now if we apply $\dfrac{\partial}{\partial x^i}$ to both sides then we get;
$$(df)\left(\frac{\partial}{\partial x^i}\Bigr|_p\right) = \sum_j \alpha^j dx^j\left(\frac{\partial}{\partial x^i}\Bigr|_p\right) = \sum_j \alpha^j \delta_{ij} = \alpha^i$$
Looking at the LHS, by definition we have;
$$\left(\frac{\partial}{\partial x^i}\Bigr|_p\right)(f) = \alpha^i \Rightarrow df = \sum_j \frac{\partial f}{\partial x^j}\Bigr|_p \ dx^j$$
$\textbf{Addition}$: It may be just a choice of notation but maybe an expert can comment on the use for $\nabla$ notation. At least for a vector field $W$, the covariant-derivative of $W$ in the direction of a vector $\textbf{v}$ at $p$ is denoted as; $\nabla_{\textbf{v}} W = W(p+t\textbf{v})'(0)$. So in this context, $\nabla_{\textbf{v}}$ is a derivation(i.e tangent vector, operator) that gives you the initial-rate of change for a vector field in the direction $\textbf{v}$.


text:
Q: Plugin errors after upgrading appolo-server-express from v2 to v3 I'm using the plugin example from one of Sentry's help pages.  It was working fine - but after upgrading to apollo-server-express 3 I'm getting the following typescript error.  I don't understand what I have to do in order to fix the error.
TS2322: Type '{ requestDidStart(: any): { didEncounterErrors(ctx: any): void; }; }[]' is not assignable to type 'PluginDefinition[]'.   Type '{ requestDidStart(: any): { didEncounterErrors(ctx: any): void; }; }' is not assignable to type 'PluginDefinition'.     Type '{ requestDidStart(_: any): { didEncounterErrors(ctx: any): void; }; }' is not assignable to type 'ApolloServerPlugin<Record<string, any>>'.       The types returned by 'requestDidStart(...)' are incompatible between these types.         Type '{ didEncounterErrors(ctx: any): void; }' is missing the following properties from type 'Promise<void | GraphQLRequestListener<Record<string, any>>>': then, catch, [Symbol.toStringTag], finally  types.d.ts(45, 5): The expected type comes from property 'plugins' which is declared here on type 'Config'
Here's the plugin:
const plugins = [
    {
       requestDidStart(_:any) {
        /* Within this returned object, define functions that respond
           to request-specific lifecycle events. */
        return {
          didEncounterErrors(ctx:any ) {
            // If we couldn't parse the operation, don't
            // do anything here
            if (!ctx.operation) {
              return
            }

            for (const err of ctx.errors) {
              // Only report internal server errors,
              // all errors extending ApolloError should be user-facing
              if (err instanceof ApolloError) {
                continue;
              }

              // Add scoped report details and send to Sentry
              Sentry.withScope(scope => {
                // Annotate whether failing operation was query/mutation/subscription
                scope.setTag("kind", ctx.operation.operation);

                // Log query and variables as extras (make sure to strip out sensitive data!)
                scope.setExtra("query", ctx.request.query);
                scope.setExtra("variables", ctx.request.variables);

                if (err.path) {
                  // We can also add the path as breadcrumb
                  scope.addBreadcrumb({
                    category: "query-path",
                    message: err.path.join(" > "),
                    level: Sentry.Severity.Debug
                  });
                }

                const transactionId = ctx.request.http.headers.get(
                  "x-transaction-id"
                );
                if (transactionId) {
                  scope.setTransaction(transactionId);
                }

                Sentry.captureException(err);
              });
            }
          }
        };
      }
    }
  ]

A: Add the async keyword before requestDidStart and before didEncounterErrors
Looks like the expected return result has to be a Promise now.


text:
Q: How to output all class objects in console? I have a class Student and i want to output every student name, but dont know how to do this.
I have tried to make this using cycle.
class Student
{
    public int score;
    public string name;
}
class Program
{
    static void Main(string[] args)
    {
        Student first = new Student
        {
            name = "Alex",
            score = 190
        };

        Student second = new Student
        {
            name = "Misha",
            score = 177
        };
        //+8 students
    }

I expect some method in the class, which will output every student name.

A: You can make a list of object, add the objects in and then iterate through the list.
List<Student> students = new List<Student>();

Then add the object to the list this way...
students.Add(first);
//Do this for every student object

Then do whatever you want with it
foreach (var student in students)
{
   Console.WriteLine(i.name + " " + i.score);
}

A: First, declare a collection that will hold the reference to all Student objects.
Lets use an array for this example.
// add more students if needed.
var students = new Student[] {  new Student
                                    {
                                        name = "Alex",
                                        score = 190
                                    },
                                    new Student
                                    {
                                        name = "Misha",
                                        score = 177
                                    }};

foreach (var s in students)
{
    Console.Write($"Student name is {s.name}");
}

After we have the array, lets loop over the students using foreach:
foreach(var s in students)
{
   Console.Write($"Student name is {s.name}");
}


text:
Q: linear recurrence inequality of positive terms This is a follow up on my previous linear recurrence inequality question.
I have some matrices which satisfy a linear recurrence formula of the form
$$
A_{n+1} = \alpha A_{n} + \beta A_{n-1},\qquad n\geq 1,
$$
with $A_0 \in \mathbb{R}^{d\times d}$ given. Assume that $\alpha,\beta \geq 0$. Defining the sequence of norms $\{ f_n = ||A_n||\}_{n=0}^{\infty}$, we come up with a linear recurrence inequality,
$$
f_{n+1} \leq \alpha f_n + \beta f_{n-1},\qquad n\geq 1,
$$
and real non-negative $\alpha, \beta$, with the property that $f_n\geq 0$ for all $n$. The question is: is it correct to solve this by the standard generating functions method? (if the coefficients are allowed to be negative then this is not true, see the answer to my previous question).
So if we let $F(x) = \sum_{x=0}^\infty f_n x^n$, then (maybe assuming $x\in (0,\mu)\in \mathbb{R}^+$) we obtain
$$
F(x) \leq \dfrac{f_0 + xf_1 - \alpha x f_0}{1-\alpha x - \beta x^2}.
$$
The question is if we are allowed to compare the Taylor coefficients on the left and on the right hand sides of this inequality,
$$
f_n = [x^n] F(x) \overset{?}{\leq} [x^n] \dfrac{f_0 + xf_1 - \alpha x f_0}{1-\alpha x - \beta x^2}.
$$

A: If $\alpha$ and $\beta$ are nonnegative, then the conclusion is indeed true; the condition $f_n\ge0$ is not needed.
First here, note that
$$[x^n] \dfrac{f_0 + xf_1 - \alpha x f_0}{1-\alpha x - \beta x^2}=g_n,$$
where $(g_n)$ solves the linear recurrence
$$
g_{n+1} = \alpha g_n + \beta g_{n-1},\qquad n\geq 1,
$$
with $g_0=f_0$ and $g_1=f_1$. The conclusion now follows by induction. Indeed, if $f_k\le g_k$ for $k=0,\dots,n$ for some natural $n$, then
$$
f_{n+1} \leq \alpha f_n + \beta f_{n-1}\leq \alpha g_n + \beta g_{n-1}=g_{n+1}.
$$


text:
Q: Display Content from Array to React Component I'm trying to display my AboutPageContent.js to AboutPage.js. I would assume I would have to map it out somehow, but I'm not sure how.
Relevant Code
AboutPage.js
import React from 'react';

// CSS import statements
import '../css/AboutPage.css';
import '../css/App.css';

// Content import Statements
import AboutPageContent from '../content/AboutPageContent.js';

class About extends React.Component {
    constructor(props) {
        super(props);
        this.state = AboutPageContent;
    }

    render() {
    return(

{this.state.about.name}

{this.state.about.desc.map(paragraph =>
{paragraph}
)}

    )
    }
}

export default About;

AboutPageContent.js

let AboutPageContent = {
    about: [{
        name: 'About Me',
        desc: [
            'p1',
            'p2',
            'p3',
            'p4',
            'p5',
            'p6'
        ],
        id: 1
}]};

export default AboutPageContent;

A: You have to do 2 maps, 1 for state.about and another one for state.about[i].desc.
class About extends React.Component {
  constructor(props) {
    super(props);
    this.state = AboutPageContent;
  }

  render() {
    return (

{this.state.about.name}

          {this.state.about.map((currAbout) =>
            currAbout.desc.map((paragraph, i) =>
{paragraph}
)
          )}

    );
  }
}

Or if you want to display the current about.name, move the
... inside this.state.about loop.
class About extends React.Component {
  constructor(props) {
    super(props);
    this.state = AboutPageContent;
  }

  render() {
    return (

          {this.state.about.map((currAbout, i) => (
            <React.Fragment key={i}>

{currAbout.name}

              {currAbout.desc.map((paragraph, i) => (

{paragraph}

              ))}
            </React.Fragment>
          ))}

    );
  }
}

A: Your this.state.about is an array, so you can't reference the name and desc properties with dot notation. Currently, this.state.about.name would be undefined. this.state.about[0].name would be equal to 'About Me'.
I would simply remove the [ ]s around the this.state.about property. That would make it an object (as opposed to an array) so the rest of your code should work fine. Leave this.state.about.desc as an array so you can use the map method.

A: You can access the object in about this way state.about[0]

const AboutPageContent = {
  about: [
    {
      name: "About Me",
      desc: ["p1", "p2", "p3", "p4", "p5", "p6"],
      id: 1,
    },
  ],
};

class About extends React.Component {
  constructor(props) {
    super(props);
    this.state = AboutPageContent;
  }

  render() {
    return (

{this.state.about[0].name}

          {this.state.about[0].desc.map((paragraph) => (

{paragraph}

          ))}

    );
  }
}
ReactDOM.render(
    <About />,
  document.getElementById('root')
);

However if you have more than one property in the object and you want to display description by name you could try this

const AboutPageContent = {
  about: [
    {
      name: "About Me",
      desc: ["p1", "p2", "p3", "p4", "p5", "p6"],
      id: 1,
    },
    {
      name: " Section 2",
      desc: ["p12", "p10"],
      id: 1,
    },
  ],
};

class About extends React.Component {
   state = AboutPageContent;
  render() {
    return (

         {Object.values(this.state)
            .flat()
            .map((o, i) => (
              <React.Fragment key={i}>

{o.name}

                {o.desc.map((paragraph) => (

{paragraph}

                ))}
              </React.Fragment>
            ))}

    );
  }
}
ReactDOM.render(
    <About />,
  document.getElementById('root')
);


text:
Q: League of legends I'm having trouble installing League of Legends with playonlinux on ubuntu 16.04.
I have had no luck so far with playonlinux. I manage to get to 30-40% progress on the install (sometimes more) before getting a bugsplat. I am constantly getting these bugsplats even though I have tried to install several different ways.
Could someone give me a detailed tutorial on how to install LoL? Any help is appreciated!

A: Here's how you should be able to remove bugsplat error:
Go to terminal (ctrl+alt+t)

*

*Get Root Access:
sudo su

Write your password then turn off the timestamps which were causing problems to all Ubuntu players with this line:

*Make sure you're writing as root@:
echo 0 > /proc/sys/net/ipv4/tcp_timestamps

*Next make sure you make it permanent, leave root@ by writing exit then enter, then write sudo gedit /etc/sysctl.conf then add the line net.ipv4.tcp_timestamps = 0 to the file

A: Unfortunately Play on Linux scripts are updated more slowly than they should be. I have found this script to be on the cutting edge of the WineHQ community:
https://github.com/TheUnnamedDude/pol_league_of_legends


text:
Q: DropDownList selecting incorrect value I have a DropDownList where I want to select an ID and its name twice, put that into a DataSet and bind to a DropDownList.  The below code is my Data Binding.
using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SFGSConnectionString1"].ConnectionString))
{
    string selectQuery1 = "SELECT [profileID], [profileName], [positionID], [positionName] from vw_profile WHERE memberID=@memberID";
    SqlCommand cmd1 = new SqlCommand(selectQuery1, conn1);
    cmd1.Parameters.AddWithValue("@memberID", memberID);

    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd1;
    DataSet ds = new DataSet();
    conn1.Open();
    da.Fill(ds);
    conn1.Close();

    chooseProfile.DataSource = ds;
    chooseProfile.DataTextField = "profileName";
    chooseProfile.DataValueField = "profileID";
    chooseProfile.DataBind();

    choosePosition.DataSource = ds;
    choosePosition.DataTextField = "positionName";
    choosePosition.DataValueField = "positionID";
    choosePosition.DataBind();
}

On my ASP.NET page, when the user hits Submit, it is meant to grab the values and insert into a table.
protected void submitReport_Click(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SFGSConnectionString1"].ConnectionString))
    {
        string selectQuery = "SELECT * FROM vw_profile";
        SqlCommand cmd = new SqlCommand(selectQuery, conn);
        conn.Open();
        SqlDataReader viewReader;
        viewReader = cmd.ExecuteReader();
        while (viewReader.Read())
        {
            var memberID = (string)viewReader["memberID"].ToString();

            using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SFGSConnectionString1"].ConnectionString))
                {
                string selectQuery1 = "SELECT * from vw_profile WHERE memberID=@memberID";
                SqlCommand cmd1 = new SqlCommand(selectQuery1, conn);
                cmd1.Parameters.AddWithValue("@memberID", memberID);
                conn1.Open();
                int submitProfileID = Convert.ToInt32(chooseProfile.SelectedItem.Value);
                int submitPositionID = Convert.ToInt32(choosePosition.SelectedItem.Value);
                DateTime dateTime = DateTime.Now;
                string date = dateTime.GetDateTimeFormats('d')[0];
                int reportNum;
                reportNum = Convert.ToInt32(viewReader["reportNumber"]);
                reportNum++;
                string reportTitle = "#" + reportNum + " - " + date;

                SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["SFGSConnectionString1"].ConnectionString);
                conn2.Open();
                SqlCommand cmd2 = new SqlCommand("INSERT INTO sfgs_reports(profileID,memberID,positionID,reportTitle,reportContent,reportDateStamp,reportNumber) values (@profileID,@memberID,@positionID,@reportTitle,@content,@datestamp,@reportNumber)", conn2);
                cmd2.Parameters.AddWithValue("@content", reportContent.Text);
                cmd2.Parameters.AddWithValue("@memberID", memberID);
                cmd2.Parameters.AddWithValue("@profileID", submitProfileID);
                cmd2.Parameters.AddWithValue("@positionID", submitPositionID);
                cmd2.Parameters.AddWithValue("@reportTitle", reportTitle);
                cmd2.Parameters.AddWithValue("@datestamp", dateTime);
                cmd2.Parameters.AddWithValue("@reportNumber", reportNum);
                cmd2.ExecuteNonQuery();
                conn2.Close();
            }
        }
        conn.Close();
    }
}

Now what happens when someone submits is that instead of grabbing the Value from the one I select, it is grabbing the Default value, as in the one displayed in the DropDownList by default.  Can anyone see anything wrong in this code that could be causing this?
Edit to show updated submitReport_Click method:
protected void submitReport_Click(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SFGSConnectionString1"].ConnectionString))
    {
        string selectQuery = "SELECT * FROM vw_profile WHERE profileName=@currentUser";
        SqlCommand cmd = new SqlCommand(selectQuery, conn);
        cmd.Parameters.AddWithValue("@currentUser", User.Identity.Name);
        conn.Open();
        SqlDataReader viewReader;
        viewReader = cmd.ExecuteReader();
        while (viewReader.Read())
        {
            var memberID = (string)viewReader["memberID"].ToString();

            if (!Page.IsPostBack)
            {
                using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SFGSConnectionString1"].ConnectionString))
                {
                    string selectQuery1 = "SELECT [profileID], [profileName], [positionID], [positionName] from vw_profile WHERE memberID=@memberID";
                    SqlCommand cmd1 = new SqlCommand(selectQuery1, conn1);
                    cmd1.Parameters.AddWithValue("@memberID", memberID);

                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = cmd1;
                    DataSet ds = new DataSet();
                    conn1.Open();
                    da.Fill(ds);
                    conn1.Close();

                    chooseProfile.DataSource = ds;
                    chooseProfile.DataTextField = "profileName";
                    chooseProfile.DataValueField = "profileID";
                    chooseProfile.DataBind();

                    choosePosition.DataSource = ds;
                    choosePosition.DataTextField = "positionName";
                    choosePosition.DataValueField = "positionID";
                    choosePosition.DataBind();
                }
            }

            using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SFGSConnectionString1"].ConnectionString))
            {
                string selectQuery1 = "SELECT * from vw_profile WHERE memberID=@memberID";
                SqlCommand cmd1 = new SqlCommand(selectQuery1, conn);
                cmd1.Parameters.AddWithValue("@memberID", memberID);
                conn1.Open();
                int submitProfileID = Convert.ToInt32(chooseProfile.SelectedItem.Value);
                int submitPositionID = Convert.ToInt32(choosePosition.SelectedItem.Value);
                DateTime dateTime = DateTime.Now;
                string date = dateTime.GetDateTimeFormats('d')[0];
                int reportNum = 1;
                string reportTitle = "#" + reportNum + " - " + date;

                SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["SFGSConnectionString1"].ConnectionString);
                conn2.Open();
                SqlCommand cmd2 = new SqlCommand("INSERT INTO sfgs_reports(profileID,memberID,positionID,reportTitle,reportContent,reportDateStamp,reportNumber) values (@profileID,@memberID,@positionID,@reportTitle,@content,@datestamp,@reportNumber)", conn2);
                cmd2.Parameters.AddWithValue("@content", reportContent.Text);
                cmd2.Parameters.AddWithValue("@memberID", memberID);
                cmd2.Parameters.AddWithValue("@profileID", submitProfileID);
                cmd2.Parameters.AddWithValue("@positionID", submitPositionID);
                cmd2.Parameters.AddWithValue("@reportTitle", reportTitle);
                cmd2.Parameters.AddWithValue("@datestamp", dateTime);
                cmd2.Parameters.AddWithValue("@reportNumber", reportNum);
                cmd2.ExecuteNonQuery();
                conn2.Close();

                Page.Response.Redirect("default.aspx?ResponseCode=3", false);
            }
        }
        conn.Close();
    }
}

A: As you said your DropDown Binding code is in Page Load Event...put your code in this block i m sure it will work..
if(!Page.IsPostBack)
{
using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SFGSConnectionString1"].ConnectionString))
{
    string selectQuery1 = "SELECT [profileID], [profileName], [positionID], [positionName] from vw_profile WHERE memberID=@memberID";
    SqlCommand cmd1 = new SqlCommand(selectQuery1, conn1);
    cmd1.Parameters.AddWithValue("@memberID", memberID);

    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd1;
    DataSet ds = new DataSet();
    conn1.Open();
    da.Fill(ds);
    conn1.Close();

    chooseProfile.DataSource = ds;
    chooseProfile.DataTextField = "profileName";
    chooseProfile.DataValueField = "profileID";
    chooseProfile.DataBind();

    choosePosition.DataSource = ds;
    choosePosition.DataTextField = "positionName";
    choosePosition.DataValueField = "positionID";
    choosePosition.DataBind();
}
}

Because When you click a button POSTBACK occurs in which  first pageload event runs after that your button click event runs. Since your Page Loadevent runs before your Button Click your  DropDownList Binded Again Set to its Default Value.So before Binding dropdown check that it should not be a PostBack Call.For This i use Page.IsPostBack which weathere its PostBack Call OR normal call.

A: try to put the code something like this:
if(!IsPostBack)
{
dropdownlistname.items.clear();
do the things to bind the value
}


text:
Q: How to create Tensorflow image dataset from .mat files using h5py I want to make image dataset in tensorflow using a Figshare Brain Tumor dataset (https://figshare.com/articles/dataset/brain_tumor_dataset/1512427).
For reading the files I am using H5PY. I tried using scipy for reading, but it doesn't support that version of the .mat files.
I am using the code below to create the dataset.
def read_image(image_path):
    with h5py.File(image_path, 'r') as image_data:
        mask = tf.convert_to_tensor(image_data['cjdata']['tumorMask'])
        label = tf.convert_to_tensor(image_data['cjdata']['label'])
        image = tf.convert_to_tensor(image_data['cjdata']['image'])
        image = NormalizeImage(image)
    return image, mask, label

def data_generator(image_list, split='train'):
    dataset = tf.data.Dataset.from_tensors(image_list)
    dataset = dataset.shuffle(8*BATCH_SIZE) if split == 'train' else dataset
    dataset = dataset.map(lambda filename: read_image(filename), num_parallel_calls=tf.data.AUTOTUNE)
    dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)
    dataset = dataset.prefetch(tf.data.AUTOTUNE)
    return dataset

I tried using tf.data.Dataset.from_tensors, tf.data.Dataset.from_tensor_slices and tf.data.Dataset.list_files, but they all lead to the following exception:
dataset = dataset.map(read_image, num_parallel_calls=tf.data.AUTOTUNE)
TypeError: expected str, bytes or os.PathLike object, not Tensor

THe function DATA_GENERATOR accepts a list of file names. It looks like the map function passes the list of filenames instead of only one element of the list to the function and this leads to arror. Please tell me what you think.


text:
Q: How does a Python custom comparator work? I have the following Python dict:
[(2, [3, 4, 5]), (3, [1, 0, 0, 0, 1]), (4, [-1]), (10, [1, 2, 3])]

Now I want to sort them on the basis of sum of values of the values of dictionary, so for the first key the sum of values is 3+4+5=12.
I have written the following code that does the job:
def myComparator(a,b):
    print "Values(a,b): ",(a,b)
    sum_a=sum(a[1])
    sum_b=sum(b[1])
    print sum_a,sum_b
    print "Comparision Returns:",cmp(sum_a,sum_b)
    return cmp(sum_a,sum_b)

items.sort(myComparator)
print items

This is what the output that I get after running above:
Values(a,b):  ((3, [1, 0, 0, 0, 1]), (2, [3, 4, 5]))
2 12
Comparision Returns: -1
Values(a,b):  ((4, [-1]), (3, [1, 0, 0, 0, 1]))
-1 2
Comparision Returns: -1
Values(a,b):  ((10, [1, 2, 3]), (4, [-1]))
6 -1
Comparision Returns: 1
Values(a,b):  ((10, [1, 2, 3]), (3, [1, 0, 0, 0, 1]))
6 2
Comparision Returns: 1
Values(a,b):  ((10, [1, 2, 3]), (2, [3, 4, 5]))
6 12
Comparision Returns: -1
[(4, [-1]), (3, [1, 0, 0, 0, 1]), (10, [1, 2, 3]), (2, [3, 4, 5])]

Now I am unable to understand as to how the comparator is working, which two values are being passed and how many such comparisons would happen? Is it creating a sorted list of keys internally where it keeps track of each comparison made? Also the behavior seems to be very random. I am confused, any help would be appreciated.

A: The number and which comparisons are done is not documented and in fact, it can freely change from different implementations. The only guarantee is that if the comparison function makes sense the method will sort the list.
CPython uses the Timsort algorithm to sort lists, so what you see is the order in which that algorithm is performing the comparisons (if I'm not mistaken for very short lists Timsort just uses insertion sort)
Python is not keeping track of "keys". It just calls your comparison function every time a comparison is made. So your function can be called many more than len(items) times.
If you want to use keys you should use the key argument. In fact you could do:
items.sort(key=lambda x: sum(x[1]))

This will create the keys and then sort using the usual comparison operator on the keys. This is guaranteed to call the function passed by key only len(items) times.

Given that your list is:
[a,b,c,d]

The sequence of comparisons you are seeing is:
b < a   # -1  true   --> [b, a, c, d]
c < b   # -1  true   --> [c, b, a, d]
d < c   # 1   false
d < b   # 1   false
d < a   # -1  true   --> [c, b, d, a]

A:
how the comparator is working

This is well documented:

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

Instead of calling the cmp function you could have written:
sum_a=sum(a[1])
sum_b=sum(b[1])
if sum_a < sum_b:
   return -1
elif sum_a == sum_b:
   return 0
else:
   return 1

which two values are being passed

From your print statements you can see the two values that are passed. Let's look at the first iteration:
((3, [1, 0, 0, 0, 1]), (2, [3, 4, 5]))
What you are printing here is a tuple (a, b), so the actual values passed into your comparison functions are
a = (3, [1, 0, 0, 0, 1])
b = (2, [3, 4, 5]))

By means of your function, you then compare the sum of the two lists in each tuple, which you denote sum_a and sum_b in your code.

and how many such comparisons would happen?

I guess what you are really asking: How does the sort work, by just calling a single function?
The short answer is: it uses the Timsort algorithm, and it calls the comparison function O(n * log n) times (note that the actual number of calls is c * n * log n, where c > 0).
To understand what is happening, picture yourself sorting a list of values, say v = [4,2,6,3]. If you go about this systematically, you might do this:

*

*start at the first value, at index i = 0

*compare v[i] with v[i+1]

*If v[i+1] < v[i], swap them

*increase i, repeat from 2 until i == len(v) - 2

*start at 1 until no further swaps occurred

So you get, i =
0: 2 < 4 => [2, 4, 6, 3] (swap)
1: 6 < 4 => [2, 4, 6, 3] (no swap)
2: 3 < 6 => [2, 4, 3, 6] (swap)

Start again:
0: 4 < 2 => [2, 4, 3, 6] (no swap)
1: 3 < 4 => [2, 3, 4, 6] (swap)
2: 6 < 4 => [2, 3, 4, 6] (no swap)

Start again - there will be no further swaps, so stop. Your list is sorted. In this example we have run through the list 3 times, and there were 3 * 3 = 9 comparisons.
Obviously this is not very efficient -- the sort() method only calls your comparator function 5 times. The reason is that it employs a more efficient sort algorithm than the simple one explained above.

Also the behavior seems to be very random.

Note that the sequence of values passed to your comparator function is not, in general, defined. However, the sort function does all the necessary comparisons between any two values of the iterable it receives.

Is it creating a sorted list of keys internally where it keeps track of each comparison made?

No, it is not keeping a list of keys internally. Rather the sorting algorithm essentially iterates over the list you give it. In fact it builds subsets of lists to avoid doing too many comparisons - there is a nice visualization of how the sorting algorithm works at Visualising Sorting Algorithms: Python's timsort by Aldo Cortesi

A: Basically, for the simple list such as [2, 4, 6, 3, 1] and the complex list you provided, the sorting algorithms are the same.
The only differences are the complexity of elements in the list and the comparing scheme that how to compare any tow elements (e.g. myComparator you provided).
There is a good description for Python Sorting: https://wiki.python.org/moin/HowTo/Sorting

A: First, the cmp() function:
cmp(...)
    cmp(x, y) -> integer
    Return negative if x<y, zero if x==y, positive if x>y.

You are using this line: items.sort(myComparator) which is equivalent to saying: items.sort(-1) or items.sort(0) or items.sort(1)
Since you want to sort based on the sum of each tuples list, you could do this:
mylist = [(2, [3, 4, 5]), (3, [1, 0, 0, 0, 1]), (4, [-1]), (10, [1, 2, 3])]
sorted(mylist, key=lambda pair: sum(pair[1]))

What this is doing is, I think, exactly what you wanted. Sorting mylist based on the sum() of each tuples list


text:
Q: Observer is not available - Elixir I am working on ubuntu 14.04 LTS. I installed elixir as per instructions given in the offical website ran the following lines in console and everything works fine
Add Erlang Solutions repo: wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb
Run: sudo apt-get update
Run: sudo apt-get install elixir

But when i run :observer.start in the iex shell,i get the following error

** (UndefinedFunctionError) undefined function: :observer.start/0 (module :observer is not available)
      :observer.start()

I ran a few commands after looking up the net, to solve the issue
apt list | grep -i erlang

It gave back many lines of which this could be relevance

erlang-observer/unknown 1:18.0 amd64

Any help on how to make it work?
Update
It seems that other modules like :dbg and :mnesia is working. Though I cant confirm if all the modules are working. Also wonder why some are working and some arent?

A: Thanks to @JoseValim, simply re-running the commands(without deleting anything) helped me. I think the first time I must have had some internet connectivity issue.
Add Erlang Solutions repo: wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb
Run: sudo apt-get update
Run: sudo apt-get install elixir

A: It's worth noting that the observer requires a GUI.
When this may not be clear: if you are running iex on WSL and using remote-connection from VS Code or through any terminal connected to WSL.
There aren't any issues with developing on this setup, but if you need an observer it isn't going to be available through the terminal connected to WSL because of the lack of GUI. There are some options available to install a GUI on WSL for remote connection from the Windows machine, but I suspect this would result in the same outcome if using Windows tooling with WSL.

A: Can you be sure Erlang was also installed from Erlang Solutions? Distributions are known to break Erlang into multiple packages (Erlang Solutions does not), so if observer is not available, you very likely need to install erlang-observer indeed.


text:
Q: How do I make client browser stop requesting an expired session id? I am developing a Java web application that will run on a secure intranet and does not require a user login. The application does, however, keep conversational state in an HttpSession. User input is not persisted to the database until they explicitly click a save button at some stage in the conversation. Until then, their input is retained in the HttpSession object. If their session expires, the user must be directed to a page that informs them of the session expiry.
This is working fine except for a problem with the redirect. When a user allows their session to sit idle for longer than the time defined in <session-timeout>, the session expires as expected. However, my attempt to redirect the user to a simple "Your session has expired" page seems to have backfired. The redirect works alright, but unless the user closes all the open browser windows on their desktop (not just the ones that were open to my web app page) they will continue being redirected to the "session expired" page forever.
Here are my constraints:

*

*Client workstations use Internet Explorer. This is company-wide and will not change anytime soon.

*Users will have mulitple instances of IE open on their desktop as part of their normal workflow. Telling them to close all instances of IE is not acceptable.

*Not using any AJAX components in this web app

I've implemented the redirect with a Java Servlet Filter. Here are the relevant code snippets:
@Override
public void doFilter(
        ServletRequest request,
        ServletResponse response,
        FilterChain filterChain)
        throws IOException, ServletException {
    Validate.notNull(filterConfig);
    Validate.isTrue(request instanceof HttpServletRequest);
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String requestedSessionId = httpServletRequest.getRequestedSessionId();
    logger.info("requestedSessionId: " + requestedSessionId);
    HttpSession httpSession = httpServletRequest.getSession(false);

    if (requestedSessionId == null) {
        // No need to do anything here if no session exists yet
        logger.debug("No session exists yet");
        filterChain.doFilter(request, response);
    } else {
        if (httpSession == null) {
            Validate.isTrue(response instanceof HttpServletResponse);
            HttpServletResponse httpServletResponse =
                (HttpServletResponse) response;
            handleSessionExpired(
                httpServletRequest,
                httpServletResponse);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Session OK | requested URL: " +
                    httpServletRequest.getRequestURL().toString());
                }
                filterChain.doFilter(request, response);
            }
        }
    }
}

private void handleSessionExpired(
        HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse)
        throws IOException {
    logger.warn("expired session | id: " +
        httpServletRequest.getRequestedSessionId());
    String expirationPageURL =
        httpServletRequest.getContextPath() + "/" +
        "SessionExpiredNotification.html";
    httpServletResponse.sendRedirect(expirationPageURL);
}

The SessionExpiredNotification.html page is meant to be the end of the line. The user should close this browser window and open a new one if they want to start a new conversation. The problem is that the new browser window still wants to use the old session id value that was associated with the now invalidated session whenever the user has any other instances of Internet Explorer open on their desktop. This isn't specific to IE, as I have confirmed that Firefox behaves exactly the same way.
When this code is reached in my Filter:
String requestedSessionId = httpServletRequest.getRequestedSessionId();
logger.info("requestedSessionId: " + requestedSessionId);

I can see that the client-side browser is still holding on to the old session id value and requesting it over and over again.
I'm not sure if it is relevant, but my web application container is Tomcat 6.x.
MY QUESTION:
How can the server web app signal the client workstation that a session id is no longer valid such that the client will discard it?

A: If request.getSession(false) returns null, you should then create a new session. You can do this by calling request.getSession(true).
In other words, at no point in the code posted are you instructing the servlet container to create a new session and assign the current request to it.

A: This is the solution I've used. I should not have been calling sendRedirect() in my filter, since that will never return a new JSESSIONID to the client browser. I need to send an actual response that kills the old JSESSIONID Cookie, otherwise the client browser will just keep trying to use it. My first thought was to get the JSESSIONID Cookie from the request header, set it to be expired, then include the expired Cookie in the response so the client will act on the expiry. Other Stackoverflow users suggested that was not a clean solution, so I have scrapped that idea.
I replaced my handleSessionExpired() method in the Filter to use a RequestDispatcher. This will allow my Filter to dispatch the request to a custom "your session is expired" JSP page. Unlike a redirect, the RequestDispatcher will send a proper response to the client.
Here is the primary method in my Filter:
@Override
public void doFilter(
        ServletRequest request,
        ServletResponse response,
        FilterChain filterChain)
        throws IOException, ServletException {
    Validate.notNull(filterConfig);
    Validate.isTrue(request instanceof HttpServletRequest);
    HttpServletRequest httpServletRequest =
        (HttpServletRequest) request;
    String requestedSessionId = httpServletRequest.getRequestedSessionId();
    logger.info("requestedSessionId: " + requestedSessionId);
    HttpSession httpSession = httpServletRequest.getSession(false);

    if (requestedSessionId == null) {
        // No need to do anything here if no session exists yet
        logger.debug("No session exists yet");
        filterChain.doFilter(request, response);
    } else {
        if (httpSession == null) {
            Validate.isTrue(response instanceof HttpServletResponse);
            HttpServletResponse httpServletResponse =
                (HttpServletResponse) response;
            handleSessionExpired(
                httpServletRequest,
                httpServletResponse);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}

My handleSessionExpired() method is very simple. This extra method call only exists because of another special use case that my filter needs to handle (but is not relevant to my original question).
private void handleSessionExpired(
        HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    logger.info("expired session | id: " +
        httpServletRequest.getRequestedSessionId());
    sendSessionExpiredResponse(httpServletRequest, httpServletResponse);
}

My sendSessionExpiredResponse() is also quite simple. The call to getSession() will cause a new session to be created (since no valid HttpSession already exists at this point) and the JSESSIONID to be included in the response. That takes care of cleaning the obsolete session id on the client side. I set a request attribute "isExpired" so the session expiry JSP knows to display a message saying that the session is expired. I'm also using the same JSP page when a user manually ends a session, so I use the attribute to decide what text to display on the page.
private void sendSessionExpiredResponse(
        HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    httpServletRequest.getSession(true); // force valid session to exist
    httpServletRequest.setAttribute("isExpired", true);
    RequestDispatcher rd = filterConfig.getServletContext()
        .getNamedDispatcher("SessionExpired");
    rd.forward(httpServletRequest, httpServletResponse);
}

The getNamedDispatcher() call gets the JSP via my entry in web.xml:
<servlet>
    <servlet-name>SessionExpired</servlet-name>
    <jsp-file>/SessionExpired.jsp</jsp-file>
</servlet>


text:
Q: Lifetime Borrow Rules Is there a good explanation of Rust's borrow rules: not just why the borrow rules imply safety, but why safety implies that these must be the rules?
The Rust book explains that borrows must follow these rules:

*

*There can be 1 mutable borrow
OR

*There can be any number of immutable borrows

*These are the only allowed borrows

The book explains that this is necessary because if there were two mutable borrows, they might both modify the same memory at the same time.
I found this unsatisfying. If there is the original variable and the mutable borrow, isn't that already 2 place where the memory can be modified at the same time? I know both cannot be used at the same time, but why is 2 references special? We could imagine that 3 mutable references are allowed, but you can only mutate with the 1st when the other 2 are gone, and you can only mutate with the 2nd when the 3rd is gone. Why is it 2?
If I could promise the compiler that my code will only run on one thread, like the dreaded Python GIL, would any of these rules be necessary?

A:
If there is the original variable and the mutable borrow, isn't that already 2 place where the memory can be modified at the same time?

No, because the compiler will not allow you to use them both at the same time.

If I could promise the compiler that my code will only run on one thread, like the dreaded Python GIL, would any of these rules be necessary?

Yes:
let mut v = vec![1];
let r = &v[0];
v.push(2);
println!("{}", r);

push may allocate, invalidating r.

A: The original variable cannot be used as long as the mutable borrow is alive, so using the variable will invalidate it, causing later uses of it to err.
You can observe it yourself:
let mut v = 0;
let r = &mut v;
v;
r;

error[E0503]: cannot use `v` because it was mutably borrowed
 --> src/main.rs:5:1
  |
4 | let r = &mut v;
  |         ------ borrow of `v` occurs here
5 | v;
  | ^ use of borrowed `v`
6 | r;
  | - borrow later used here

Playgroung.
It is tricky to observe because most of the thinks you think "use" the variable in fact creates a reference to it: for example, println!("{v}") expands into:
::std::io::_print(::core::fmt::Arguments::new_v1(
    &["", "\n"],
    &[::core::fmt::ArgumentV1::new_display(&v)],
));

And thus the error message is also different:
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
 --> src/main.rs:5:15
  |
4 |     let r = &mut v;
  |             ------ mutable borrow occurs here
5 |     println!("{v}");
  |               ^^^ immutable borrow occurs here
6 |     r;
  |     - mutable borrow later used here
  |
  = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)

Playground.
As far as I'm aware, the only things that do not create a reference is assigning to the variable and moving/copying it, or just naming it, which is pretty useless.

A: If a mutable borrow is made before an immutable borrow, and then used, the code won't compile.
For example, this works:
#[allow(unused)]
pub fn main() {
    let mut x = vec![1, 2, 3, 4, 5];
    let y = &x;
    let z = &mut x;
    z[1] = 3;
    z.push(6);
}

However, this does not:
#[allow(unused)]
pub fn main() {
    let mut x = vec![1, 2, 3, 4, 5];
    let y = &x;
    let z = &mut x;
    z[1] = 3;
    z.push(6);
    println!("{}", y[1]);
}

... giving the error output:
error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable
 --> main.rs:5:13
  |
4 |     let y = &x;
  |             -- immutable borrow occurs here
5 |     let z = &mut x;
  |             ^^^^^^ mutable borrow occurs here
...
8 |     println!("{}", y[1]);
  |                    - immutable borrow later used here

error: aborting due to previous error

Which, essentially, works as you'd expect. You can have as many immutable borrows as you want, until a mutable borrow, and then you can have only one mutable borrow, to the exclusion of any other previous borrows.
Also, you can't modify the original variable either while the mutable borrow is used.
#[allow(unused)]
pub fn main() {
    let mut x = vec![1, 2, 3, 4, 5];
    let z = &mut x;
    z[1] = 3;
    x[2] = 4;
    z[3] = 5;
}

... giving the error output:
error[E0499]: cannot borrow `x` as mutable more than once at a time
 --> main.rs:6:5
  |
4 |     let z = &mut x;
  |             ------ first mutable borrow occurs here
5 |     z[1] = 3;
6 |     x[2] = 4;
  |     ^ second mutable borrow occurs here
7 |     z[3] = 5;
  |     - first borrow later used here

error: aborting due to previous error

In short, borrowing rules enforce that only variable is allowed to mutate the data at a time. If the mutable borrow is no longer used, then we can freely mutate the original variable, or use immutable borrows of it.
For example, z is never used again so this code is fine:
#[allow(unused)]
pub fn main() {
    let mut x = vec![1, 2, 3, 4, 5];
    let z = &mut x;
    z[1] = 3;
    x[2] = 4;
}


text:
Q: Bring 'offline node' online script So I was wondering if it's possible to create a script that checks in a node is offline and if it is it should bring it back online. The login used should be by username and token.
I'm talking about a script that triggers this button on the right:

A: If you want to simply make temporarily disabled nodes online you can use the following script to do this.
def jenkinsNodes = Jenkins.instance.getNodes()
def nodeLabelToMatch = "label1"
  for(def node: jenkinsNodes) {
      if(node.labelString.contains(nodeLabelToMatch)) {
        if (node.getComputer().isOffline()){
            node.getComputer().cliOnline()
        }
      }
  }

Update : Full Pipeline
The script is written in groovy
pipeline {
    agent any

    stages {
        stage('Hello') {
            steps {
                script {
                    def jenkinsNodes = Jenkins.instance.getNodes()
                    def nodeLabelToMatch = "label1"
                      for(def node: jenkinsNodes) {
                          if(node.labelString.contains(nodeLabelToMatch)) {
                            if (node.getComputer().isOffline()){
                                node.getComputer().cliOnline()
                            }
                          }
                      }
                }
            }
        }
   }
}

Non-Depricated Method.
If you look at this depricated method, it simply calls a non depricated method setTemporarilyOffline(boolean temporarilyOffline, OfflineCause cause). So instead of using cliOnline() you can use setTemporarilyOffline. Check the following.
node.getComputer().setTemporarilyOffline(false, null)

Some proper code with a proper cause. The cause is not really needed when setting the node online though.
import hudson.slaves.OfflineCause.UserCause

def jenkinsNodes = Jenkins.instance.getNodes()
  for(def node: jenkinsNodes) {
      if (node.getComputer().isTemporarilyOffline()){
           node.getComputer().setTemporarilyOffline(false, null)
      }
  }

Setting to temporarily offline
UserCause cause =  new UserCause(User.current(), "This is a automated process!!")
node.getComputer().setTemporarilyOffline(true, cause)

A: TL;DR: the scripted action for that button is .doToggleOffline:
Jenkins.instance.getNode('Node-Name').getComputer().doToggleOffline(offlineMessage)
I knew I had dealt with this before but did not recall the cliOnline() command. In looking it up I noticed it was deprecated. Turns out I used a different approach.
Can't say I fully understand the possible states and their applicability as it's not well-documented. The table shown below is as reflected in the Build Executor Status side panel; the /computer Manage nodes and clouds table will only show the computer w/ or w/o X.
// Connect (Launch) / Disconnect Node
Jenkins.instance.getNode('Node-Name').getComputer().launch()
Jenkins.instance.getNode('Node-Name').getComputer().disconnect()

// Make this node temporarily offline (true) / Bring this node back online (false)
Jenkins.instance.getNode('Node-Name').getComputer().setTemporarilyOffline(false, OfflineCause cause)

// Availabiltiy: Accepting Tasks (true) / Not Accepting Tasks (false)
Jenkins.instance.getNode('Node-Name').getComputer().setAcceptingTasks(true)

The isAcceptingTasks() JavaDoc explains this as:

Needed to allow agents programmatic suspension of task scheduling that
does not overlap with being offline.

The isTemporarilyOffline() JavaDoc elaborates:

Returns true if this node is marked temporarily offline by the user.
In contrast, isOffline() represents the actual online/offline state

JavaDoc for isOffline (both Temporarily and Disconnected),  setTemporarilyOffline and setAcceptingTasks.

But, after all that, turns out there's one more option:
def offlineMessage = "I did it"
Jenkins.instance.getNode('Node-Name').getComputer().doToggleOffline(offlineMessage)

And if you run that from the groovy console, it toggles the state (so I guess you check state first):

And run it again:

My experience relates to: JENKINS-59283 - Use distinct icon for disconnected and temporarily offline computers / PR-4195 and having brought agents on-line when they should have been unavailable per schedule (Node Availability: Bring this agent online according to a schedule) so nothing ran. The PR was to introduce a yellow X for the Not Accepting but On-line condition, but the icons have now changed.


text:
Q: Two different $WORKON_HOME and $PROJECT_HOME variables in .bash_profile and .bashrc files For I did not have the choice, I had to set the $WORKON_HOME and PROJECT_HOME variables to different path in the .bashrc (local machine) and .bash_profile (remote machine) files.
e.g.:
In the .bashrc file (local):
export WORKON_HOME="$HOME/home-local/.virtualenvs"
export PROJECT_HOME="$HOME/home-local/venv_projects/"

and in the bash_profile one (remote):
export WORKON_HOME="$HOME/.virtualenvs"
export PROJECT_HOME="$HOME/venv_projects/"

My remote machine is mounted on my local machine under the home-local folder. I can not change this.
Thus, as I run most of my programs on the remote, I first need to create the virtualenv on the remote machine.
However, if I briefly want to work on my local machine, when I type workon env, the working directory gets changed to $HOME/.virtualenvs (as on the remote), instead of $HOME/home-local/.virtualenvs. I guess the WORKON_HOME and PROJECT_HOME variables are tied to the environment.
But is there any way to change this?
Thanks,

A: You cannot have 2 different values for 1 variable. But you can switch between values. Put
export WORKON_HOME="$HOME/.virtualenvs"
export PROJECT_HOME="$HOME/venv_projects/"

into a file, for example "$HOME"/home.sh, and
export WORKON_HOME="$HOME/home-local/.virtualenvs"
export PROJECT_HOME="$HOME/home-local/venv_projects/"

into, e.g., "$HOME"/home-local.sh. Now you can do source "$HOME"/home.sh or source "$HOME"/home-local.sh. And source can be shortened to just .: . "$HOME"/home-local.sh.
You can create aliases or shell functions instead:
home_virt() {
    export WORKON_HOME="$HOME/.virtualenvs"
    export PROJECT_HOME="$HOME/venv_projects/"
}

home_local_virt() {
    export WORKON_HOME="$HOME/home-local/.virtualenvs"
    export PROJECT_HOME="$HOME/home-local/venv_projects/"
}

and just call home_virt or home_local_virt.


text:
Q: Prime ideal factorisation degree Consider the ring $R=\mathbb{Z}[\zeta_p]=\mathscr{O}_{\mathbb{Q}(\zeta_p)}$ for $p$ a rational prime.
Why is it true that if an ideal $I$ of the form below in $R$ has prime factorisation $P_1^{e_1} \cdots P_n^{e_n}$ then $e_i \vert p-1$?
The form is $I=(\beta)$, where $$\beta=\alpha^{S},$$
and where $S=\prod_{e|l-1, \hspace{1mm} e \ne l-1}1-\sigma^e$, $a \in \mathbb{Q}(\zeta_p)$ is `semi-primary', and $\sigma$ is a generator for $\text{Gal}(\mathbb{Q}(\zeta_p)/\mathbb{Z})$.
Here `Semi-primary' means "in $\mathbb{Z}[\zeta_p]$, coprime to $p$ and congruent to a rational integer modulo $(1-\zeta_p)^2$".


text:
Q: How do I find the MAC address in Mac OS 9? I've never used a Mac in my life – now I have to find out the MAC address of Mac OS 9. I can't even find terminal or console there.

A:
Click Control Panels, TCP/IP
A dialog box will come up.
Click File, Get Info
A dialog box will come up.
The address is listed as the Hardware address

This is the way you do it.
Source


text:
Q: How to get PIDs that are using given file name in C#? How to get PIDs of processes that are using a given file name and mutex name?
(Not by custom kernel driver, but in C# in user mode.)
UPDATE: Thanks to Daniel Renshaw I found a script that lists all handles with PIDs. (Using a not undocumented and unfrozen functions.)

A: The following two SO questions may be of use:
How do I find out which process is locking a file using .NET?
Summary: use handle.exe and parse the output (i.e. not a great solution)
Win32: How to get the process/thread that owns a mutex?
Summary: may not be possible in user mode without using deprecated or undocumented functions (but some smaple code is provided in this question).


text:
Q: Direct sum of two subspace Given the definition on textbook: Let $V$ be a subspace of $\mathbb R^n.$ Every vector $u \in \mathbb R^n$ can be written uniquely as $u = n + p.$ I still don't understand what it means because i am ask to do with a question that ask me the prove the uniqueness claim in the definition.
The question is asking:
Let $v\in \mathbb R^n$. Suppose $p_1, p_2 \in V$ and $n_1,n_2 \in V^\bot$ are such that $v=p_1+n_1 = p_2 + n_2.$ Prove that $p_1 = p_2$ and $n_1 = n_2$.
Anyone can help me answer to this question?

A: Let's look at an easy example.
Let $n=2$ and $V= <\begin{pmatrix} 1\\0 \end{pmatrix}>$. Then $V^{\perp}=<\begin{pmatrix} 0\\1 \end{pmatrix}>$. Now pick some $x\in\mathbb{R}^2$, say, $x=\begin{pmatrix} x_1\\ x_2 \end{pmatrix}$. Then $x=n+p$ where $n=x_1\begin{pmatrix} 1\\0 \end{pmatrix}\in V$ and $p=x_2\begin{pmatrix} 0\\1 \end{pmatrix}\in V^{\perp}$. The theorem tells you that these are your only choices of $n$ and $p$ such that $x=n+p$.
Now to the proof:
Let $v=n_1+p_1$ and $v=n_2+p_2$. where $n_i\in V$ and $p_i\in V^{\perp}$ for $i=1,2$. Then $$0=(p_1-p_2)+(n_1-n_2)$$. Since $V$ and $V^{\perp}$ are subspaces of $\mathbb{R}^n$, we have that $p_1-p_2\in V$ and $n_1-n_2\in V^{\perp}$. By definition of $V$ and $V^{\perp}$, we get that $p_1-p_2 \perp n_1-n_2$. But if two vectors are orthogonal, they must be linearly independent. Hence we have that 0 is written as a linear combination of two linearly independent vectors, hence these two vectors must be zero, yielding $p_1-p_2=0$ and $n_1-n_2=0$ which proves that they were the same.

A: Since $V\cap V^{\perp}=0$, we can conclude from $(p_1-p_2)=-(n_1-n_2)$ that $p_1-p_2\in V\cap V^{\perp}=0$.

A: Let $V, U$ be subspaces of $\mathbb{R}^n$ such that their direct sum equals $\mathbb{R}^n$ (I use $U$ since I don't know how to write the orthogonality symbol). By definition of the direct sum, $U \cap V = \{0\}$. Suppose that
$$p_1 + n_1 = p_2 + n_2$$
then we obtain that
$$p_1 - p_2 = n_2 - n_1$$
the left hand side is an element of $V$ by definition of subspace. However, it equals an element in $U$, so $p_1 - p_2 \in U \cap V$. The intersection only contains $0$, so $p_1 - p_2 = 0$. Can you do the same for $n_2 - n_1$?
Hence if you assume that in a direct sum, you can express a vector $v$ as what appear to be two different sums, then those sum are actually the same. Hence each vector has a unique expression as a sum of elements in $V$ and its complementary space.