text:
Q: How to use Micrometer timer together with webflux endpoints IS there any simple way to use Micrometer timers with Webflux controllers?
It seems that @Timed works only with non-reactive methods. For reactive it records very low time values.
I found a similar question: How to use Micrometer Timer to record duration of async method (returns Mono or Flux) but the answers were too complex for such a common issue
Any ideas?

A: If you want to measure time for Web-flux methods/calls you can then use easily metrics directly from Flux/Mono (plus configure your project to export metrics, e.g. for graphite)
An example looks like
Flux<String> dataStream = Flux.just("AA", "BB", "CC", "DD");
dataStream.name("my-test-name").tag("key1", "value1").metrics().subscribe(p ->
   {
      System.out.println("Hello " + p);
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         e.printStackTrace();
   }
});

Then in my case the metrics in the graphite are e.g.under application-name.magdalena.reactor.flow.duration.exception.flow.my-test-name.status.completed.type.Flux.p50
p50 - is the latency for the half of the requests (or p98 latency for 98% pf the requestsetc.). Thanks they the artificial delay in this example you can observe that they values is near 4000 (1s x 4 elements processed).
Configuration in application.yml for graphite:
management:
    metrics:
        export:
            graphite:
                enabled: true
                host: graphite-lhr10.something.com
                port: 2003
                protocol: plaintext

@Timed annotation did not worked fro me too.


text:
Q: Is there a way to use 'and' in a django template to check 2 variables? I am trying to check if two variables are equal to none and if so, display something, but I am not sure how to use an and in the template and check if both variables are None.
HTML:
{% if post.company_title and post.company_image %}

{% elif post.company_title == "" %}

{% elif post.company_image == "" %}

{{ post.company_title }}

{% elif not post.company_title and not post.company_image %}

nooo

{% endif %}

*

*The first if checks if both have a value.

*The first else if checks if one doesn't have a value

*The second else if checks if one doesn't have a value

*The last else if should check if they both do not have values.

If anyone knows how to check to variables if they are equal to none that would be great.

A: Simply use variable is None.
None, True and False are available in Django templates

redpajama_set_name: RedPajamaStackExchange


text:
Q: django one request.is_ajax() check and multiple forms so i have this code that checks if there is an ajax request and then handle the form stuff if there is, but my problem is it's kind of repetitive to check each time like you will see in the code that i will add, what i want is to check only once and then say if form_1 do some stuff, if form_2 do some stuff
here is the code:
   if request.is_ajax():
       Form1 = form_1(request.POST)
       if form_1.is_valid():
          # do some stuff
       else:
         # do some stuff)

   if request.is_ajax():
       Form2 = form_2(request.POST)
       if form_2.is_valid():
          # do some stuff
       else:
         # do some stuff

what i want to do is something like this or an alternative to the following:
   if request.is_ajax():
      if it's form1:
         # do form1 stuff
      elif it's form2:
         # do form2 stuff

A: Why not pass the form as a parameter of the request, something like:
if request.is_ajax() and request.GET.get('form1'):
    ...

elif request.is_ajax() and request.GET.get('form2'):
    ...

else:
    ...


text:
Q: what does & do in php I have this code
$myNewClass->cars =& Orders_Car::GetRecords($myNewClass->searchString);
                   ^

what is & doing there.
thanks

A: It changes the variable to be 'passed by reference'. This is as opposed to passing a copy of the variable in.
See the manual for details.
One common use is in foreach.
Typically, foreach operates on a copy of the iterable array or object.
That means
$salad=array(1,2,3);
foreach ($salad as $leaf){
  $leaf+=1;
  }
echo $salad[0];// output: 1

foreach ($salad as &$leaf){
  $leaf+=1;
  }
echo $salad[0];// output: 2 because & made the assignment affect the original array

A: It creates a reference. If you don't know what a reference is, read this : http://www.php.net/manual/en/language.references.php

A: Read Do not use PHP references by PHP expert Johannes Schlüter
PHP references are a holdover from PHP 4, where objects were passed by value instead of by reference unless you deliberately made them by reference.  This isn't necessary when using PHP 5, because all objects are passed by reference in PHP 5 all the time.
Scalars and arrays are still passed by value by default in PHP 5.  If you need to pass them by reference, you should just use an object.

A: It is used for passing values by reference rather than by value which is default in php.


text:
Q: Why doesn't != work for string index comparison? I tried to run this code with input "AC039"
 code = input("Enter code: ").upper()
 if code[0] != ('N' or 'A' or 'C' ):
     print("The first character must be N, A or C")
else:
    print("Pass!")

It gave me the output error result:
The first character must be N, A or C

However, if I input "AC039" into the below code using 'not in',
code = input("Enter code: ").upper()
if code[0] not in ["N", "A", "C"]:
    print("The first character must be N, A or C")
else:
    print("Pass!")

The resulting output is:
print("Pass!")

Why doesn't "!=" work for the first set of code, since both code[0] and 'A' are string types?
I ran a check using type function on code[0] and it returned string type.
code = input("Enter code: ").upper()
print(type(code[0]))
print(type('A'))

returns:
<class 'str'>
<class 'str'>

A: These two lines are identical.
if code[0] != ('N' or 'A' or 'C' ):

if code[0] != 'N':

Because the operator 'or' checks if the first operand is true, then it takes it; otherwise, it checks another one.
Examples:
>>> 1 or 2
1
>>> 0 or 3
3
>>> 0 or 2 or 3
2
>>> False or 2
2
>>> False or 0
0

As a result, you can apply this pattern to solve your problem.
if code[0] in ('N', 'A', 'C'):

or
if code[0] == 'N' or code[0] == 'A' or code[0] == 'C':

A: I think this is best explained with a rough implementation of what a or b or c or ... does.
import typing as t

T = t.TypeVar("T")

def Or(*args: T) -> T:
    arg: T
    for arg in args[:-1]:
        if bool(arg) is True:
            return arg
    return args[-1]

>>> Or("N", "A", "T")  # equivalent to `"N" or "A" or "T"`
'N'
>>> Or("", None, 0)  # equivalent to `"" or None or 0`
0

A: It's because the "or" operator compares sequentially.
from the given input "AC039",
code[0] != ('N' or 'A' or 'C' ):

what's happening from the above code is, comparing one by one.
(code[0] != 'N') -> True
(code[0] != 'A') -> False
(code[0] != 'C') -> True

since the first 'N' doesn't match with 'A', it stops going through other comparisons, 'A' and 'C'.
print('N' != ('N' or 'A' or 'C' )) -> False
print('A' != ('N' or 'A' or 'C' )) -> True
print('C' != ('N' or 'A' or 'C' )) -> True

However, if code[0] not in ["N", "A", "C"]: works because "not in" checks whole elements in the array.
I hope it helps.


text:
Q: How to create Custom Navigation Bar like the following image in swift?

I am working on a project where i need the exact same configuration in the navigation bar.Since the height of navigation bar is fixed I am not able to create one like in the given image.I am using a UITableViewController embedded inside a Navigation controller.

Does anyone know how to do this?
Thanks in advance

A: Hey i did a lot of google and finally found a solution to this problem.
here is the snapshot from xcode 7 interface builder.

heres the link where apple had provided the sample code for extending the navbar, so i used it as per my requirement.Its in Objective C.
https://developer.apple.com/library/ios/samplecode/NavBar/Introduction/Intro.html

here is what i did :
1) User a viewcontroller embeded inside a navigation controller instead of a tableview controller.
2) Add a UIView from interface builder as per your required size under the navbar and add whatever you want inside the view (eg: Segmented Control)
3) Place the Tableview under the UIView and hook it up to the viewcontroller so that it becomes functioning
 In order to make the hairline of the navbar go away and make the UIView as a part of the navabar we have to add some code to the viewDidLoad
 The code is in Swift 2.0
self.navigationController?.navigationBar.translucent = true
self.navigationController?.navigationBar.clipsToBounds = true

and finally try to match the backgroundcolor of the UIView as close to the navbar and there we have a extended Custom Navigation Bar.


text:
Q: Rendering command validation errors across a redirect I cannot render the errors from my command object. It does the job well but my .gsp view does not render the errors I raise.
Here is my controller action:
def handleModifyProfile2 = { CreditProviderModificationCommand cpmc -> // bind params to the command object
   if (cpmc.hasErrors()) {
      flash.message = "Error modifying your profile:"
      redirect(action: "modifyProfile", params: [creditProvider : cpmc])
   } ...

Here is how I try to render the errors in my .gsp view:
<g:hasErrors bean="${creditProvider}">
   <div class="errors">
       <g:renderErrors bean="${creditProvider}" as="list" />
   </div>
</g:hasErrors>

How can I get the errors to be displayed in the view?

A: You can't send the command across in a redirect using params. You have a couple options:

*

*render() in the error condition instead of redirect()ing:
if(cpmc.hasErrors()) {
    render(view: 'profile', model: [creditProvider: cpmc])
}

This is the most common idiom for what you're doing.

*Store the command in the session to persist it across the redirect:
if(cpmc.hasErrors()) {
    session.cpmc = cpmc
    redirect(...)
}

// and in your action
def cpmc = session.cpmc ?: null
render(view: 'profile', model: [creditProvider: cpmc])

This option is somewhat questionable. If not done correctly, you can pollute the session and leave objects hanging around, taking up memory. If done correctly, though, it can be a decent way to implement a post-redirect-get.

A: With Grails 3 (I don't know if this worked earlier) it's possible to use the flash for this. According to the documentation, the flash will be "cleared at the end of the next request".
I like to use a pattern like this:
def save(MyDomain myDomain) {
    if (myDomain.validate()) {
        myDomain.save()
    } else {
        flash.errors = myDomain.errors
    }
    redirect(action: 'edit', id: myDomain.id)
}

def edit(MyDomain myDomain) {
    if (flash.errors) {
        myDomain.errors = (Errors) flash.errors
    }
    return [myDomain: myDomain]
}

I don't like to use render() for this kind of error handling, because it makes URLs shown in the browser inconsistent with the shown page. This breaks when users set bookmarks, for example.


text:
Q: How do I make resizing images while displaying my screen not be inefficient in processing.core (PApplet) I am new to coding and don't really know what I am doing. I know that there my code is pretty inefficient and I could probably fix it later (i.e. collision and movement), but I have what I think is an efficient map setup. It only renders what is either around the camera or is around the player based on the camera type (freeRoam vs placerCentered). This works and runs fine until I start to resize pictures when I zoom in and out my map. I think that every time I draw a resized image my computer resizes it and then draws it for every instance of it rather than resizing it once and drawing it. Would I have to make images for every instance of zooming in or out or is there an optimized resizing tool that I am missing?
Google Drive link with images if anyone is interested: https://drive.google.com/drive/folders/1s5_9YPX7_6QWaxZPexN7pWk8zgmaT0w5?usp=sharing
(All images are 20 x 20 I think besides warrior1 and stoneTile1 which are both 32 x 32)
import processing.core.*;
import processing.event.MouseEvent;
import java.util.*;

public class Dungeon1 extends PApplet implements MyLibrary {
    static gameState currentState;
    static cameraState currentCameraState = cameraState.playerCentered;
    enum gameState {
        Over, Running
    }
    enum cameraState {
        freeRoam, playerCentered
    }
    int cameraScaling = 20;
    PImage testBoots;
    PImage clown;
    PImage testSquare;
    PImage stoneTile1;
    PImage resizedTile;
    PImage warrior1;
    float enemyX = 10;
    float enemyY = 10;
    float redSquare;
    int currentXPos = 10;
    int currentYPos = 10;
    int tileType;
    int mapWidth = 500;
    int mapHeight = 500;
    int[][] squareType = new int[mapHeight][mapWidth];
    boolean movingUp, movingDown, movingLeft, movingRight;
    int squareX;
    int squareY;
    boolean canMoveUp, canMoveDown, canMoveLeft, canMoveRight = true;
    int cameraX = currentXPos;
    int cameraY = currentYPos;
    int lastCameraX;
    int lastCameraY;
    boolean centerCamera = false;
    int pastMouseXPosition;
    int pastMouseYPosition;
    int squareWidth;
    int squareHeight;
    boolean mouseDragging = true, freeRoam, playerCentered;

    public static void main(String[] args) {
        PApplet.main("Dungeon1");
    }

    public void settings() {
        fullScreen();
    }

    public void setup() {
        playerStartPos();
        createMap();
        currentState = gameState.Running;
        testBoots = loadImage("Images/TestBoots.png");
        clown = loadImage("Images/clown.png");
        testSquare = loadImage("Images/testSquare.png");
        stoneTile1 = loadImage("Images/stoneTile1.png");
        resizedTile = loadImage("Images/resizedTile.png");
        warrior1 = loadImage("Images/warrior1.png");
    }

    public void draw() {
        background(0, 0, 0);
        drawMap();
        isMoving();
    }

    public void keyPressed() {
        if (key == 'w') {
            movingUp = true;
        }
        if (key == 's') {
            movingDown = true;
        }
        if (key == 'a') {
            movingLeft = true;
        }
        if (key == 'd') {
            movingRight = true;
        }
        if (key == 'k') {
            Test = true;
        }
        if (key == 'c') {
            currentCameraState = cameraState.playerCentered;
            centerCamera = true;
        }
        if (key == 'v') {
                currentCameraState = cameraState.freeRoam;

        }
        if (key == 'b') {
                currentCameraState = cameraState.playerCentered;

        }
    }

    public void keyReleased() {
        if (key == 'w') {
            movingUp = false;
        }
        if (key == 's') {
            movingDown = false;
        }
        if (key == 'a') {
            movingLeft = false;
        }
        if (key == 'd') {
            movingRight = false;
        }
        if (key == 'k') {
            Test = false;
        }

    }

    public void mouseDragged(MouseEvent e) {

        if (pastMouseXPosition < mouseX) {
          lastCameraX--;
        }
        if (pastMouseXPosition > mouseX) {
          lastCameraX++;
        }
        if (pastMouseYPosition < mouseY) {
          lastCameraY--;
        }
        if (pastMouseYPosition > mouseY) {
          lastCameraY++;
        }
            pastMouseXPosition = mouseX;
            pastMouseYPosition = mouseY;
    }
    public void mousePressed() {
        currentCameraState = cameraState.freeRoam;
        mouseDragging = true;
            pastMouseXPosition = mouseX;
            pastMouseYPosition = mouseY;
    }
    public void mouseReleased() {
        mouseDragging = false;
    }

    public void mouseWheel(MouseEvent e) {
        if (e.getAmount() < 0) {

            cameraScaling--;
        } else {

            cameraScaling++;
        }
    }
    public void isMoving() {
        if (movingUp) {
            if (canMoveUp) {
                currentYPos--;
                cameraY--;
            }
            if (squareType[currentXPos][currentYPos] == 2) {
                currentYPos++;
                canMoveUp = false;
                cameraY++;
            }
        }
        if (movingDown) {
            if (canMoveDown) {
                currentYPos++;
                cameraY++;
            }
            if (squareType[currentXPos][currentYPos] == 2) {
                currentYPos--;
                canMoveDown = false;
                cameraY--;
            }
        }
        if (movingRight) {
            if (canMoveRight) {
                currentXPos++;
                cameraX++;
            }
            if (squareType[currentXPos][currentYPos] == 2) {
                currentXPos--;
                canMoveRight = false;
                cameraX--;
            }
        }
        if (movingLeft) {
            if (canMoveLeft) {
                currentXPos--;
                cameraX--;
            }
            if (squareType[currentXPos][currentYPos] == 2) {
                currentXPos++;
                canMoveLeft = false;
                cameraX++;
            }
        }
        if (squareType[currentXPos][currentYPos] != 2) {
            drawPlayer();
            canMoveUp = true;
            canMoveLeft = true;
            canMoveDown = true;
            canMoveRight = true;
        }
    }
    public void playerStartPos() {
        currentXPos = 96/2;
        currentYPos = 54/2;
    }
    public void drawPlayer() {
        if (currentCameraState == cameraState.playerCentered) {
            image(testSquare, (currentXPos * cameraScaling - cameraX * cameraScaling), (currentYPos * cameraScaling - cameraY * cameraScaling), cameraScaling, cameraScaling);
                  } else if (currentCameraState == cameraState.freeRoam) {
            image(testSquare, (currentXPos * cameraScaling - lastCameraX * cameraScaling), (currentYPos * cameraScaling - lastCameraY * cameraScaling), cameraScaling, cameraScaling);
            }
    }

    public void createMap() {
        //First creates the plane to navigate
            for (int r = 0; r < mapHeight; r++) {
                for (int c = 0; c < mapWidth; c++) {
                    redSquare = generator.nextInt(100);

                    if (redSquare > 90) {
                        tileType = 2;
                    } else {
                        tileType = 0;
                    }
                    squareType[r][c] = tileType;
                }
            }

    }
    public void drawMap() {
    //TODO: Either figure out how to make actual scaled images not run poorly or make a bunch of images that only are displayed a scaled resolution
        if (cameraScaling < 15) {
            cameraScaling = 15;
        }
        if (cameraScaling > 50) {
            cameraScaling = 50;
        }
        if (centerCamera) {
            cameraX = currentXPos - 47*20/ cameraScaling;
            cameraY = currentYPos - 23*20/ cameraScaling;
        }
        squareWidth = 20+ cameraScaling;
        squareHeight = 20+ cameraScaling;
        centerCamera = false;
        if (currentCameraState == cameraState.freeRoam) {
            cameraX = lastCameraX;
            cameraY = lastCameraY;
            for (int r = lastCameraX; r < lastCameraX + 96*20/ cameraScaling + 2 ; r++) {
                for (int c = lastCameraY; c < lastCameraY + 54*20/ cameraScaling + 2; c++) {
                    squareX = r * cameraScaling - lastCameraX * cameraScaling;
                    squareY = c * cameraScaling - lastCameraY * cameraScaling;
                    if (r > 0 && c > 0 && r < mapWidth && c < mapHeight) {
                        if (squareType[r][c] == 0) {
                            image(resizedTile, squareX, squareY, cameraScaling, cameraScaling);
                        } else {
                            colorTiles(r, c);
                            rect(squareX, squareY, cameraScaling, cameraScaling);
                        }
                    }
                }
            }
        } else if (currentCameraState == cameraState.playerCentered) {

            lastCameraX = cameraX;
            lastCameraY = cameraY;
                for (int r = cameraX; r < cameraX + 96*20/ cameraScaling + 2; r++) {
                    for (int c = cameraY; c < cameraY + 54*20/ cameraScaling + 2; c++) {

                        squareX = r * cameraScaling - cameraX * cameraScaling;
                        squareY = c * cameraScaling - cameraY * cameraScaling;
                        if (r > 0 && c > 0 && r < mapWidth && c < mapHeight) {

                            if (squareType[r][c] == 0) {
                                image(resizedTile, squareX, squareY, cameraScaling, cameraScaling);
                            } else {
                                colorTiles(r, c);
                                rect(squareX, squareY, cameraScaling, cameraScaling);
                            }
                        }
                    }
             }
        }
    }

    public void colorTiles(int r, int c) {
        if (squareType[r][c] == 2) {
            fill(255, 0, 0);
        }
    }

}```


text:
Q: Absolutely positioned element is appearing on top of my other elements

            Freelance Web/Logo

            Designer & Developer

            → Muzammil Hussain

CSS :
body { font-size:12px/20px; }
#wrapper { position:relative; }
#header { width:100%; height:150px; background:url(http://i55.tinypic.com/1zpgny8.jpg) repeat-x;}
#pattern { width:100%; height:150px; background:url(http://i51.tinypic.com/ao75eg.jpg) repeat; position:absolute; top:0px; }
#main { width:1200px; margin:0 auto; margin-top:-103px; }
#main img { float:left; margin-right:10px; }
#main h3 { float:left; margin-top:5px; font:12px/20px "Bookman Old Style"; text-shadow: 1px 1px #000; line-height:14px; color:#fff; }

Well please first of all check if i did any mistake let me know. and also i having trouble that my #pattern overlaying all my classes. i just want this class appear over #header. but something i am missing..
Actually i want results like that.

Please let me know.

A: This markup could be improved a lot. But if you are just looking for a fix try adding position: relative to #main.
What's happening is #pattern is coming out of the natural flow of the document because it has position: absolute set on it. Therefore unless stated otherwise it appears on top of every other element inside it's parent element.
Also I would consider reducing your markup to something like this...

        Freelance Web/Logo

        Designer & Developer

        → Muzammil Hussain

Be careful not to use too many IDs when using them to style elements. They can be very powerful and on a large site can result in lots of pain trying to override them and their child elements when you want to.


text:
Q: I commited a file that's over github's file size limit. How do fix this commit without losing progress? I was working on a project and commited all changes to my local branch. When I tried to push to github I got denied because one of the new files created on my repo was over the default filesize limit. Now even if I remove the offending file and do a new commit I can't push to the repo, since a version of that file is on my branch history.
How can I remove this file from the existing commit without losing all changes done to other files?
I'm thinking of branching the previous commit, merging both except for the new file, but I'm not experienced enough to do it with confidence, so if anyone is willing to write out a step by step I'd appreciate it.
Thanks!

A: the command git reset --soft resets the commit history to the last commit without changing or deleting files in the working directory. From there, just recommit all the files you want to have in the commit.


text:
Q: CSS iOS - Why does :hover persist through states Please run the demo on an iOS device.
I have two pages with similar elements (that have :hover states) and clicking on any element in the first page takes you to the second page.
Problems:

*

*:hover persists between pages

*location of :hover remains identical (try tapping different links)

This happens until you interact with the page again.
Demo: https://codesandbox.io/s/ios-persisting-hover-state-se3m1
Has anyone experienced this before? What solutions do I have to fix it? Would rather not have to add a no-touch type class everywhere where I do hover states in my CSS if possible.
Thanks!

A: This should answer your question: https://humanwhocodes.com/blog/2012/07/05/ios-has-a-hover-problem/


text:
Q: ByteBuddy intercepting constructor arguments I am trying to dynamically create a class using ByteBuddy with my custom constructor.
I have read the Intercepting default constructor with Byte Buddy and I have written the following code base on that.
Class<?> dynamicType = new ByteBuddy().subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
                .name("foo").defineConstructor(Modifier.PUBLIC).withParameters(int.class)
                .intercept(
                        to(new Object() {
                            public void construct() throws Exception {
                                System.out.println("before constructor");
                            }
                        })
                        .andThen(MethodCall.invoke(Object.class.getConstructor()))
                        .andThen(to(new Object() {
                            public void construct() throws Exception {
                                System.out.println("after constructor");
                            }})
                        ))
                .make()
                .load(Main.class.getClassLoader(), INJECTION)
                .getLoaded();

        dynamicType.getConstructor(int.class).newInstance(3);

My question is how can I access the integer argument of 'foo' constructor in the custom codes that I have added before and after calling the super constructor.

A: Sure, simply define a parameter with an annotation @Argument(0).
I'd recommend against using anonymous classes as their package-private visibility might render tricky outcomes.


text:
Q: Problems converting axis angle to quaternion I have a vector which points from my camera to an object I want to point to, so I want to make a quaternion which rotates the camera so that it points to that vector. So i do this (using glm)
glm::quat rotation=glm::angleAxis(0.0f,vector);

If i understand that function correctly in the case of a vector of, for example, (0.0f,0.0f,-1.0f), the camera should point forward in the depth axis, and with no roll. But i don't know why, in that case it creates this quaternion:
x:-0
y:-0
z:-0
w:1
wich does nothing, and the x,y,z values only differ from 0 if the angle parameter passed to angleAxis() is different from 0. Why does this happen? if i pass angle 0, shouldn't it simply create a rotation with only yaw and pitch, and no roll?

A: Already go the answer: (on the gameDev forum, from the user clb)
No, your understanding is off. Angle-axis rotation generates rotation about the given axis, by the given angle. If you don't specify an angle, you'll always get identity back. This is because rotation a zero angle, be it about any axis, of course does not rotate at all.
What you are thinking about is the LookAt rotation. I am not sure what the function signature in glm is, but I'm sure they have a similar function. Use a LookAt rotation to orient one direction vector to face towards another vector.


text:
Q: Where do I ask about downloading an audio file from a website? Long story short: I wanted to download the audio file from here. As there is no download link, and it's probably not even supposed to be downloaded at all, I was searching for some other way to get the audio file.
After some Chrome F12 magic I actually found the file and could download it. But if I wouldn't have found out, where would I ask this question? My best guess was superuser.com, but it didn't seem to fit there either. Any better suggestion?
Edit: As a lot of discussion is about the fact whether it's illegal / morally questionable to achieve my goal: I explained my (moral) intentions in a comment below. When it comes to legality, living in Switzerland gives you quite a lot of freedom in using published content for personal use. I want to stress that I don't mean to gain any other benefit in downloading the audio file than to listen to it by myself.
Edit2: For the sake of completeness: Either I'm completely blind or they really added it just today, but now there is a download button on the page :-)

A: My bet would be on SuperUser since this is a general software usage question (the browser in this case).
I would prepare for downvotes if I were you, since some communities don't like people trying to do questionable things (in this case it feels like you want to 'steal' someone else's music).
Your question doesn't sound like it, but it could be a question for Information Security, if the question is about the security implications or how to prevent against such actions.


text:
Q: Is it possible to remove class of an element when change the screen size? I'm working on a menu bar @ which initially which have a width property and when the screen size is less than 767(@media screen and (max-width:767px)) I need to remove that property.so I'm trying to implement that using a class.the height property is specified in this class and want to remove that class when width is less than 767px .Is it possible to remove class of an element when change the screen size?.

A: basically this will remove the class blue when window width <= 767. this is jquery btw
$(window).resize(function(){

      if($(window).width() <= 767){
        $('.blue').removeClass('blue');
      }
    });

JSfiddle

A: You don't necessarily need javascript if you only want to change the properties.
Write the styling of that class inside a media query e.g
@media screen and (min-width:768px){
// i am usign MIN-WIDTH:786px not MAX-WIDTH
.yourclass{
float: right;
}
}

So this property will be added to that element ONLY on screens greater than 786.

A:

alert($(window).width());

if($(window).width() > 500) {
        $('#body').addClass('limit1200');
        $('#body').removeClass('limit400');
    }else{
        $('#body').addClass('limit400');
        $('#body').removeClass('limit1200');
    }
.limit400 h1 { font-size:10px; }
.limit1200 h1 { font-size:50px; }

Hey :D


text:
Q: Getting Error while Sending automatic email on background Getting error "java.lang.NoClassDefFoundError: javax.activation.DataHandler" while Sending automatic email on background..I have added activation.jar ,additional.jar.mail.jar already ,but getting same error again,,plz tell me proper solution..
Thanks in advance..

A: The Android SDK makes it very easy to send emails from an application, but unfortunately, that's only if you want to send them via the built-in mailing app. For most situations this works fine, but if you want to send something out and don't want any input/intervention from the user, it's not as easy.
so please follow this link
http://www.jondev.net/articles/Sending_Emails_without_User_Intervention_(no_Intents)_in_Android

A: Try going to Project -> Properties -> Java Build Path -> Order & Export and ensure Android Private Libraries are checked for your project and for all other library projects you are using.


text:
Q: Getting properties from one class into another in AS3 This is my code for the Main class:
package {
import flash.display.*;
import flash.events.Event;

public class Main extends Sprite{

    private var ball:Ball;
    private var paddle:Paddle;

    public function Main():void {
        addToUI();
        beginCode();
    }

    public function beginCode():void {
        addEventListener(Event.ENTER_FRAME, move);
        addEventListener(Event.ENTER_FRAME, hitTest);
    }

    public function move(event:Event):void {
        ball.move();
    }

    private function hitTest(event:Event):void {
        if(ball.hitTestObject(paddle)){
            vy = -20;
        }
    }

    private function addToUI():void {
        paddle = new Paddle();
        ball = new Ball();
        addChild(paddle);
        addChild(ball);

        paddle.x = 50;
        paddle.y = 200;

        ball.x = 75;
        ball.y = 100;
    }
}

}
This is my code for the Ball class:
package {

import flash.display.*;
import flash.events.Event;

public class Ball extends MovieClip {
    public var vy:Number = 10;

    public function move():void {
        vy += 2;
        this.y += vy;
    }

    /*
    public function hitTest(paddle):void {
        if(this.hitTestObject(paddle)){
            vy = -20;
        }
    }
    */
}

}
I'm having a hard time getting the collision test to work properly. When I use f. ex. use
trace("Collision works")

in the hitTest function, it responds properly. But I am not able to change the vy-property. I've also tried to write the hitTest in the Ball class, but then the compiler tells me that the property paddle is undefined.
How do I do this?

A: You have to change vy for the ball instance:
private function hitTest(event:Event):void {
    if(ball.hitTestObject(paddle)){
        ball.vy = -20;
    }
}


text:
Q: Build diagonal matrix without using for loop I am trying to build the following matrix in Python without using a for loop:
A
 [[ 0.1  0.2  0.   0.   0. ]
 [ 1.   2.   3.   0.   0. ]
 [ 0.   1.   2.   3.   0. ]
 [ 0.   0.   1.   2.   3. ]
 [ 0.   0.   0.   4.   5. ]]

I tried the fill_diagonal method in NumPy (see matrix B below) but it does not give me the same matrix as shown in matrix A:
B
 [[ 1.   0.2  0.   0.   0. ]
 [ 0.   2.   0.   0.   0. ]
 [ 0.   0.   3.   0.   0. ]
 [ 0.   0.   0.   1.   0. ]
 [ 0.   0.   0.   4.   5. ]]

Here is the Python code that I used to construct the matrices:
import numpy as np
import scipy.linalg as sp   # maybe use scipy to build diagonal matrix?

#---- build diagonal square array using "for" loop
m = 5

A = np.zeros((m, m))

A[0, 0] = 0.1
A[0, 1] = 0.2

for i in range(1, m-1):
    A[i, i-1] = 1   # m-1
    A[i, i] = 2     # m
    A[i, i+1] = 3   # m+1

A[m-1, m-2] = 4
A[m-1, m-1] = 5

print('A \n', A)

#---- build diagonal square array without loop
B = np.zeros((m, m))

B[0, 0] = 0.1
B[0, 1] = 0.2

np.fill_diagonal(B, [1, 2, 3])

B[m-1, m-2] = 4
B[m-1, m-1] = 5

print('B \n', B)

So is there a way to construct a diagonal matrix like the one shown by matrix A without using a for loop?

A: There are functions for this in scipy.sparse, e.g.:
from scipy.sparse import diags

C = diags([1,2,3], [-1,0,1], shape=(5,5), dtype=float)

C = C.toarray()

C[0, 0] = 0.1
C[0, 1] = 0.2
C[-1, -2] = 4
C[-1, -1] = 5

Diagonal matrices are generally very sparse, so you could also keep it as a sparse matrix. This could even have large efficiency benefits, depending on the application.

The efficiency gains sparse matrices could give you depend very much on matrix size. For a 5x5 array you can't really be bothered I guess. But for larger matrices creating the array could be a lot faster with sparse matrices, illustrated by the following example with an identity matrix:
%timeit np.eye(3000)
# 100 loops, best of 3: 3.12 ms per loop

%timeit sparse.eye(3000)
# 10000 loops, best of 3: 79.5 µs per loop

But the real strength of the sparse matrix data type is shown when you need to do mathematical operations on arrays that are sparse:
%timeit np.eye(3000).dot(np.eye(3000))
# 1 loops, best of 3: 2.8 s per loop

%timeit sparse.eye(3000).dot(sparse.eye(3000))
# 1000 loops, best of 3: 1.11 ms per loop

Or when you need to work with some very large but sparse array:
np.eye(1E6)
# ValueError: array is too big.

sparse.eye(1E6)
# <1000000x1000000 sparse matrix of type '<type 'numpy.float64'>'
# with 1000000 stored elements (1 diagonals) in DIAgonal format>

A: Notice that the number of 0 is always 3 (or a constant whenever you want to have a diagonal matrix like this):
In [10]:
import numpy as np
A1=[0.1, 0.2]
A2=[1,2,3]
A3=[4,5]
SPC=[0,0,0] #=or use np.zeros #spacing zeros
np.hstack((A1,SPC,A2,SPC,A2,SPC,A2,SPC,A3)).reshape(5,5)
Out[10]:
array([[ 0.1,  0.2,  0. ,  0. ,  0. ],
       [ 1. ,  2. ,  3. ,  0. ,  0. ],
       [ 0. ,  1. ,  2. ,  3. ,  0. ],
       [ 0. ,  0. ,  1. ,  2. ,  3. ],
       [ 0. ,  0. ,  0. ,  4. ,  5. ]])

In [11]:
import itertools #A more general way of doing it
np.hstack(list(itertools.chain(*[(item, SPC) for item in [A1, A2, A2, A2, A3]]))[:-1]).reshape(5,5)
Out[11]:
array([[ 0.1,  0.2,  0. ,  0. ,  0. ],
       [ 1. ,  2. ,  3. ,  0. ,  0. ],
       [ 0. ,  1. ,  2. ,  3. ,  0. ],
       [ 0. ,  0. ,  1. ,  2. ,  3. ],
       [ 0. ,  0. ,  0. ,  4. ,  5. ]])


text:
Q: SharePoint Workflow Date Range I'm trying to have a range of days that are blacked out on a SharePoint calendar.  Any event added between 3/1/2021 and 3/15/2021 should automatically be denied.  I have it working if the dates requested off are between 3/1/2021 and 3/15/2021, but I can't see to make it work if the date range for the event starts outside the blackout date range but ends during the blackout period.  For example: The start date is 2/25/2021 and the end date is 3/11/2021.  I want that request to reject and it isn't.
Current Programming
When I try to change the "and" between the date range to "or" it just says any date is during a blackout period and blocks everything.
How can I get events that start or end durning the blackout period to reject?
Thanks,
Laura


text:
Q: What object to use to lock threads from signle session (from single connected user) I would like to  lock("on some object")  to block two threads of a single user to access some part of the code in the same time. Two differents users with two differents sessions can do that.
I am using FormsAuthentication for handling sessions. What kind of object can I use for the lock ? Does this class (FormsAuthentication) supply some kind of singletons for each session, or do you know some other trick to do that?
I am thinking about handling a singleton hiding a dictionnary on a set of objects (as set of locks for different opened session). But before starting such complexe class that could make code less understandable,  am I forgetting some best and easyer way to do that?
Do you know some better trick to do that lock for a signle session ?

A: If you can create a string that is unique to the single session that you want to block, you could use a Named Mutex.
After you have created a Mutex, a thread can call WaitOne() to acquire the mutex (thereby blocking any other threads that subsequently call `WaitOne()).
Then the thread can call ReleaseMutex() to free it up and allow another thread waiting in WaitOne() to continue.
Some sample code for a Console app:
string mutexName = "Some name unique to the session";

bool created;
Console.WriteLine("Press RETURN to create mutex.");
Console.ReadLine();

using (var mutex = new Mutex(initiallyOwned:false, name:mutexName, createdNew: out created))
{
    Console.WriteLine("Attempting to enter mutex");
    mutex.WaitOne();
    Console.WriteLine("Got mutex. Press RETURN to release.");
    Console.ReadLine();
    mutex.ReleaseMutex();
    Console.WriteLine("Released mutex. Press RETURN to exit.");
    Console.ReadLine();
}

Note that this also works across processes. It does use up an operating system event handle, so it might be overkill if you have hundreds of sessions. It also, as Marc notes below, assumes "sticky" load balancing.


text:
Q: A "Hermitian" operator with imaginary eigenvalues Let $${\bf H}=\hat{x}^3\hat{p}+\hat{p}\hat{x}^3$$ where $\hat{p}=-id/dx$.
Clearly ${\bf H}^{\dagger}={\bf H}$, because ${\bf H}={\bf T} + {\bf T}^{\dagger}$, where ${\bf T}=\hat{x}^3\hat{p}$. In this sense ${\bf H}$ is "formally" self-adjoint.
It turns out that
$$ \psi_{\lambda}(x)=\frac{1}{|x|^{3/2}}e^{-\lambda/4x^2} \in L^2[-\infty,\infty]$$
is an eigenfunction of ${\bf H}$. In fact
$${\bf H}\psi_{\lambda}(x)=-i\lambda\psi_{\lambda}(x).$$
If we go through the usual proof that Hermitian operators have real eigenvalues, we see that something has to go wrong in the following steps:
$$ \langle\psi_{\lambda}(x)|{\bf H}\psi_{\lambda}(x)\rangle= \langle{\bf H}^{\dagger}\psi_{\lambda}(x)|\psi_{\lambda}(x)\rangle=\langle{\bf H}\psi_{\lambda}(x)|\psi_{\lambda}(x)\rangle=\langle\psi_{\lambda}(x)|{\bf H}\psi_{\lambda}(x)\rangle^{*}.$$
Clearly ${\bf H}\psi_{\lambda}(x) = -i\lambda\psi_{\lambda}(x)\in L^{2}.$ So all these operations seem to be well-defined.
Our book suggests that we look at ${\bf T}\psi_{\lambda}(x)$. It turns out that ${\bf T}\psi_{\lambda}(x),{\bf T}^{\dagger}\psi_{\lambda}(x) \notin L^{2}$. So when we are writing $$\langle\psi_{\lambda}(x)|{\bf H}\psi_{\lambda}(x)\rangle$$
we are really writing
$$\langle\psi_{\lambda}(x)|({\bf T} + {\bf T}^{\dagger})\psi_{\lambda}(x)\rangle=\langle\psi_{\lambda}(x)|{\bf T}\psi_{\lambda}(x)\rangle+\langle\psi_{\lambda}(x)|{\bf T}^{\dagger}\psi_{\lambda}(x)\rangle$$
where these inner products are no longer defined. Does the fact that these two inner products are undefined lead to this seemingly (and "formally") self-adjoint operator having imaginary eigenvalues? And how?

A: This problem is posed and solved by: François Gieres his article: Mathematical surprises and Dirac's formalism in quantum mechanics .
It is given in example 3 page 6 and its solution is given in: (3a) page 39 and continued on pages 45 and 46 where the  von Neumann's criterion for self adjontiness is formulated and applied to the problem.
As explained in the article, the basic reason that the function $\psi_{\lambda}$ is not an eigenfunction of $\mathbf{H}$ is that it does not belong to the Schwartz space $\mathcal{S}(\mathbf{R})$ (of rapidly decreasing  functions) which the mutual domain of definition of both $\hat{x}$ and $\hat{p}$.
In the second part it is shown that $\psi_{\lambda}$ is an eigenfunction of $\mathbf{H^{\dagger}}$ and there is no way to extend the domain of $\mathbf{H}$ to make it self adjoint.

A: The problem with this hamiltonian is that there is a difference between symmetric/Hermitian operators and self-adjoint operators. It looks like a nit-picky mathematician's poking holes into everything, but it is in fact important:

In general, the domains of $\hat{A}$ and $\hat{A}^\dagger$ do not coincide. If $\hat{A}=\hat{A}^\dagger$ on $D(\hat{A})$, then $D(\hat{A})\subseteq D(\hat{A}^\dagger)$ holds and $\hat{A}$ is called symmetric or Hermitian. If, in addition, $D(\hat{A}^\dagger)=D(\hat{A})$, then $\hat{A}$ is called self-adjoint.

The important existence and reality theorems for eigenvalues and eigenvectors are usually only for self-adjoint operators. This is made clear in page 13 of your textbook. While your operator is indeed symmetric, it is unlikely to be self-adjoint.
More specifically, $H$ is densely defined and therefore has an adjoint $H^\dagger$, which is an operator on some domain $D(H^\dagger)$ which satisfies $\langle\phi|H\psi\rangle=\langle H^\dagger\phi|\psi\rangle$ for all $\psi\in D(H)$ and $\phi\in D(H^\dagger)$. Your real job is characterizing the domains of both operators and seeing if they coincide, or figuring out whether $H$ can be extended to a larger domain such that the adjoint's domain will coincide with the original domain. None of that is particularly easy.

The thing is, though, that these mathematical troubles very rarely come on their own and are usually accompanied by trouble in the corresponding classical problem. This is beautifully made clear, together with a clear exposition of the necessary mathematical facts, in the paper

Classical symptoms of quantum illnesses. Chengjun Zhu and John R. Klauder. Am. J. Phys. 61 no. 7, 605 (1993).

The main point is that unless the classical problem has well-defined solutions for all time and for all initial conditions, you really have no business complaining about unexpected behaviour in the quantum counterpart.
For your model, the classical hamiltonian $H=\frac12(q^3p+pq^3)=q^3 p$ produces the Hamilton equations
$$
\left\{
\begin{array}{}
\dot p=-\frac{\partial H}{\partial q}=&3q^2 p,\\
\dot q=\phantom{-}\frac{\partial H}{\partial p}=&q^3.
\end{array}
\right.
$$
These are fairly easy to solve, and the solutions are not well behaved:
$$
\left\{
\begin{array}{}
\frac{1}{2q^2}&=t_0-t,\\
\frac{p_0^2}{p^2}&=(t_0-t)^3,
\end{array}
\right.
$$
where $t_0$ and $p_0$ are constants of integration. Note, in particular, that there are no (real) solutions after a certain time $t_0=t_\text{in}+\frac{1}{2q(t_\text{in})^2}$. How, then, are you expecting reasonable physics out of the quantized version of this?

Finally, as a coda, let me address Qmechanic's very interesting comment. It is true that for a given physical system, you will have a single hamiltonian and many other physical observables. How, then is one to make sense of this construction for an arbitrary observable? I would counter that any arbitrary observable can be considered as a hamiltonian, and that things like the spectrum do follow from properties like the corresponding time evolution.
Take some arbitrary self-adjoint, as-nice-as-necessary physical observable $\hat A$ in a physical system with state space $\mathcal H$. Even if it does not make physical sense, you can definitely postulate the flow associated with that observable, i.e. the curve $t\to|\psi(t)\rangle$ in $\mathcal H$ that obeys the Schrödinger-like equation
$$i\partial_t|\psi(t)\rangle=\hat A|\psi(t)\rangle.$$
If you want to bring the spectrum into play, you can solve this equation by decomposing the flow into the observable's eigenbasis, so
$|\psi(t)\rangle=\sum_n\psi_n e^{-ia_n t}|n\rangle$,
where $\hat A|n\rangle=a_n|n\rangle$ and $\psi_n=\langle n|\psi(0)\rangle$. (Here one needs to assume that $|\psi(0)\rangle$ is "general" or "random" enough that all the $\psi_n$ are nonzero.
The question, though, is how can you extract the spectrum from the time evolution? The answer to that is to Fourier transform into the frequency domain: define
$$|\tilde\psi(\omega)\rangle=\int_{-\infty}^\infty\text dt \, e^{i\omega t}|\psi(t)\rangle$$
and see what the eigenvector decomposition does to it:
$$|\tilde\psi(\omega)\rangle
=\int_{-\infty}^\infty\text dt \, e^{i\omega t}\sum_n\psi_n e^{-ia_n t}|n\rangle
=\sum_n\psi_n|n\rangle \int_{-\infty}^\infty\text dt \, e^{i(\omega -a_n) t}
=\sum_n\delta(\omega -a_n)\psi_n|n\rangle .
$$
That is: the Fourier transform of the $\hat A$-induced flow is equal to a number of spikes at the eigenvalues of $\hat A$, and the eigenvectors are the coefficients.
To put it another way, this offers a means of obtaining the spectrum from the time evolution: solve it in some way, Fourier transform the solution, and then read the eigenvalues from the support of the transform and the eigenvectors from the value at those points. In fact, this is a useful technique and it has quite wide deployment in numerical solutions of certain classes of problems. (For more information, see David Tannor's excellent textbook Introduction to Quantum Mechanics: A Time-Dependent Perspective (Ebookee).)
... and, of course, if you tried to diagonalize in this way an operator with the kind of problems described above, you'd be heading straight for trouble. Surely it is unreasonable to ask the quantum flow to be well-behaved when the classical flow isn't!

A: Although Emilio's answer is insightful, I don't think it directly answers your question.  I'll attempt to do that here.  This answer proceeds in two parts:

*

*We'll show that the operator you try to write down is hermitian with appropriate domain, but that it is not self-adjoint and has no self-adjoint extensions.

*We'll show that your formal manipulations have errors.
Part 1.
We set $\hbar=1$ for convenience throughout, and let $S(\mathbb R)$ denote Schwartz space.  Recall that the $L^2(\mathbb R)$ inner product is defined as follows:
\begin{align}
  \langle \psi, \phi\rangle = \int_{-\infty}^{\infty} dx\, \psi^*(x) \phi(x)
\end{align}
We are going to use the following definition which appears on page 138 of Reed and Simon's Methods of Modern Mathematical Physics Volume II (Fourier analysis, self-adjointness):
Definition. For a symmetric operator $A$, we define its deficiency indices by
\begin{align}
  n_+(A) &= \dim\mathrm{ker}(iI-A^\dagger) \\
  n_-(A) &= \dim\mathrm{ker}(iI+A^\dagger) \\
\end{align}
We are also going to need the following result which is part of a corollary on page 141 of Reed and Simon:
Lemma. Let $A$ be a closed hermitian operator with deficiency indices $n_+(A)$ and $n_-(A)$, then $A$ is self-adjoint if and only if $n_+(A) = 0 = n_-(A)$, and $A$ has at least one self-adjoint extension if and only of $n_+(A) = n_-(A)$.
With this lemma, we can prove the following claim.  What we are going to prove here tells us that there is no way to define $H$ self-adjoint operator on some domain in $L^2(\mathbb R)$.
Claim. The operator $H$ with domain $D(A) = S(\mathbb R)$ defined by
\begin{align}
  H\psi(x) = -ix^3\frac{d\psi}{dx}(x) -i \frac{d}{dx} (x^3\psi(x))
\end{align}
is closed and hermitian but not self-adjoint.  Furthermore, $H$ has no self-adjoint extensions on $L^2(\mathbb R)$.
Proof. We will show that $A$ is hermitian and closed but that $n_-(H) = 1$ while $n_+(H) = 0$.  The desired result then follows immediately from the lemma.  To show that $H$ is hermitian, it suffices to show that $\langle \psi, H\phi\rangle = \langle H\psi, \phi\rangle$ for all $\phi,\psi\in D(H) = S(\mathbb R)$.  We have
\begin{align}
  \langle \psi, H\phi\rangle
  &= \int_{-\infty}^\infty dx\, \psi^*\left(-ix^3\frac{d\phi}{dx} -i \frac{d}{dx} (x^3\phi)\right) \\
  &= -2i\psi^*x^3\phi\Big|_{-\infty}^\infty +i\int_{-\infty}^\infty dx\left(\frac{d}{dx}(\psi^*x^3)+\frac{d\psi^*}{dx}(x)x^3\right)\phi \\
  &= \int_{-\infty}^\infty dx\left(-i\frac{d}{dx}(\psi(x)x^3)-i\frac{d\psi}{dx}x^3\right)^*\phi \\
  &= \langle H\psi, \phi\rangle.
\end{align}
The boundary term in the second equality vanished because $\phi$ is rapidly decreasing.  This operator is closed (admittedly this is actually something I haven't been able to prove).  Because $H$ is hermitian, its adjoint $H^\dagger$ has the same action on elements of its domain as $H$ itself.  Moreover, let $D'$ the set of all $\psi\in L^2(\mathbb R)$ for which $H\psi$ is well-defined and also an element of $L^2(\mathbb R)$.  Then the computation be performed above to demonstrate hermiticity shows that if $\phi\in D'$, then $\langle\phi, H\psi\rangle = \langle H\phi, \psi\rangle$ for all $\psi\in D(H)$, so $D(H^\dagger) = D'$.  In particular, this domain is larger than that of $H$ which is therefore not self-adjoint.
Now if $\psi\in \mathrm{ker}(iI - A^\dagger)$, then $\psi$ obeys the following differential equation:
\begin{align}
  i\psi - \left(-ix^3\frac{d\psi}{dx} -i \frac{d}{dx} (x^3\psi)\right)=0
\end{align}
This differential equation can be simplified to give
\begin{align}
  (1+3x^2)\psi + 2x^3\frac{d\psi}{dx} =0
\end{align}
for $x> 0$ and $x<0$, we can separate variables and integrate to solve this differential equation.  The result is (I used mathematica for this)
\begin{align}
  \psi_>(x) &= \frac{e^{1/(4x^2)}}{x^{3/2}} + c_> \\
  \psi_<(x) &= \frac{e^{1/(4x^2)}}{(-x)^{3/2}} + c_<
\end{align}
These solutions both diverge at the origin, so our differential equation does not yield an $L^2(\mathbb R)$ solution.  This gives $\mathrm{ker}(iI - A^\dagger) = \{0\}$ so $n_+(H) = 0$.  On the other hand, if $\psi\in \mathrm{ker}(iI + A^\dagger)$ then
\begin{align}
  i\psi + \left(-ix^3\frac{d\psi}{dx} -i \frac{d}{dx} (x^3\psi)\right)=0
\end{align}
This differential equation can be simplified to give
\begin{align}
  (1-3x^2)\psi - 2x^3\frac{d\psi}{dx} =0
\end{align}
which admits the normalized solution
\begin{align}
  \psi(x) =\left\{ \begin{array}{cc}
                \frac{1}{\sqrt{2}}\frac{1}{|x|^{3/2}}e^{-1/(4x^2)}   &, x\neq 0 \\
                0 &, x=0
              \end{array}\right.
\end{align}
In fact, this is (up to normalization) exactly the function you wrote down in the original question statement.  This function is in $D(H^\dagger)$.  It follows that $\mathrm{ker}(iI + A^\dagger) = \mathrm{span}\{\psi_1\}$ so that $n_-(H) = 1$, as desired $\blacksquare$.
Part 2.
As for you manipulations, even if you were to enlarge the domain of $H$ to include $\psi_\lambda$, they would be wrong.  Notice, for example, that you got a nonzero boundary term in the following computation:
\begin{align}
  \langle \psi_\lambda, H\psi_\lambda\rangle
  &= \int_{-\infty}^\infty dx\, \psi_\lambda^*\left(-ix^3\frac{d\psi_\lambda}{dx} -i \frac{d}{dx} (x^3\psi_\lambda)\right) \\
  &= -2i\psi_\lambda^*x^3\psi_\lambda\Big|_{-\infty}^\infty +i\int_{-\infty}^\infty dx\left(\frac{d}{dx}(\psi_\lambda^*x^3)+\frac{d\psi_\lambda^*}{dx}(x)x^3\right)\psi_\lambda \\
  &= -2i\,\mathrm{sgn}(x)e^{-\lambda/(2x^2)}\Big|_{-\infty}^\infty +i\int_{-\infty}^\infty dx\left(\frac{d}{dx}(\psi_\lambda^*x^3)+\frac{d\psi_\lambda^*}{dx}(x)x^3\right)\psi_\lambda \\
  &= -4i +\int_{-\infty}^\infty dx\left(-i\frac{d}{dx}(\psi(x)x^3)-i\frac{d\psi}{dx}x^3\right)^*\psi_\lambda \\
  &= -4i+\langle H\psi_\lambda, \psi_\lambda\rangle
\end{align}
which we could have seen more easily by simply noting that
\begin{align}
  \langle\psi_\lambda, \psi_\lambda\rangle = \frac{2}{\lambda}
\end{align}
which gives
\begin{align}
  \langle \psi_\lambda, H\psi_\lambda\rangle &= -i\lambda \langle\psi_\lambda, \psi_\lambda\rangle = -2i \\
  \langle H\psi_\lambda, \psi_\lambda\rangle &= (-i\lambda)^* \langle\psi_\lambda, \psi_\lambda\rangle = 2i
\end{align}
In particular, both of these computations show that
\begin{align}
  \langle \psi_\lambda, H\psi_\lambda\rangle \neq \langle H\psi_\lambda, \psi_\lambda\rangle
\end{align}
in contradiction with what you claim.


text:
Q: Database Connection not closing What's the reason why my database connection won't be closed?
The error says that there are too many connections when i perform several queries
Thanks in advance, here's the code:
   try {
        st = DBConnector.getConnection().prepareStatement(sqlQuery);
        st.setString(1, userID);
        result = st.executeQuery();
        checker = !result.first();

    }catch(Exception e){
        e.printStackTrace();
    }
    finally
    {
        try {
            DBConnector.getConnection().close();
        }catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

here's my DBConnector class by the way
public class DBConnector {
    private static Connection;
    private static String host;
    private static String username;
    private static String password ;

    public static void setUsername(String newusername){
        username = newusername;
    }
    public static void setPassword(String newpassword){
        password = newpassword;
    }
    public static void setHost(String newHost){
        host = newHost;
    }
    public static void setConnection(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager.getConnection(host, username , password);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String getUsername(){
        return username;
    }
    public static String getPassword(){
        return password;
    }
    public static String getHost(){
        return host;
    }
    public static Connection getConnection(){
        setConnection();
        return conn;
    }

    public static void disconnect(){
        conn = null;
    }

}

A: If I read your class correctly, you create a new connection that is closed immediately in your finally block instead of closing the original one when you do DBConnector.getConnection().close().
Change your code to:
 Connection connection = DBConnector.getConnection();
 try {
     st = connection .prepareStatement(sqlQuery);
     // more code
  } catch (...) {
     // more code
  finally
    {
        try {
            connection.close(); //
        }catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Even better is to use try-with-resources (Java 7):
 try (Connection connection = DBConnector.getConnection()) {
     st = connection .prepareStatement(sqlQuery);
     // more code
 } catch (...) {
     // more code
 }

A: This is how you open and close your connection properly.
/**
 * Creates a connection to database if there isn't any established.
 *
 * @return {@link Connection} to database.
 */
protected Connection getConnection() throws ServiceException{
    try{
        if(this.conn == null || this.conn.isClosed()){
            // Here you have to create your connection
            // this.conn = ...
        }
        if(conn==null){
            // Retry to connect in case that the connection is still null!
            Thread.sleep(250);
            getConnection();
        }
    }catch(SQLException e ){
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return conn;
}

/**
 * Closes the {@link Connection} to database.
 */
protected void closeConnection(){
    try{
        if(this.conn != null && !this.conn.isClosed()){
            this.conn.close();
        }

    }catch(SQLException e){
        e.printStackTrace();
    }
    finally{
        this.conn = null;
    }
}


text:
Q: Laravel Http Image Caching Control Header for React Native App I need caching laravel storage image for my React Native app. How can I send my image with cache control header?

A: resolved. if you want you can global set cache header in RouteServiceProvider.
here:
public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->middleware('cache.headers:private;max_age=7200')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->middleware('cache.headers:private;max_age=7200')
                ->group(base_path('routes/web.php'));
        });
    }


text:
Q: Convert PDF to PNG using ImageMagick using ImageMagick, what command should i use to convert a PDF to PNG? I need highest quality, smallest file size. this is what I have so far (very slow by the way):
convert -density 300 -depth 8 -quality 85 a.pdf a.png

Looking at what Gmail does when a user "view" a PDF, the quality is awesome and the file size very minimal. The DPI is just 96 (I have to set a density of 300 to get anything decent). Anyone know how GMail does it? Thanks.

A: Reducing the image size before output results in something that looks sharper, in my case:
convert -density 300 a.pdf -resize 25% a.png

A: when you set the density to 96, doesn't it look good?
when i tried it i saw that saving as jpg resulted with better quality, but larger file size

A: To get high quality, one should do "supersampling" in Imagemagick. Convert at a high density, but then resize down as needed (nominal enough to compensate for the high density).
convert -density 288 input.pdf -resize 25% output.png

288=72*4 (72 dpi is default density, so 4x)
25%=1/4

So the 1/4 compensates for the 4x.

A: convert -density 192 input.pdf -quality 100 -alpha remove output.png

for pdf text document is good enough.
-density 192 double 96dpi, higher just make bigger image and file size
-quality 100 somehow this give slightly smaller file size
-alpha remove to remove png transparent background


text:
Q: Image Processing: Fastest direct-neighbor pixel comparison I have a written a code, that takes the difference of intensities of neighbor pixels and gets the maximum difference. However I would like some thoughts on how to implement my "algorithm" faster. Till now I resorted to switchand ifstatements.
my code is simple yet messy. There is the thoughts behind it:

*

*go to my point of interest

*identify the pixels in its direct neighborhood

*calculate the difference of intensities

*compare the calculated intensities and deduce the maximum

*take the maximum to etc...

That lead me to multiple switch and if statements. Do you have any thoughts on that ?

A: You can see OpenCv library, not need write this code this library have this and many other function. Read this:
http://www.seas.upenn.edu/~bensapp/opencvdocs/ref/opencvref_cv.htm


text:
Q: Why does J.Jonah Jameson hate Spider-Man? I read online before that J.Jonah Jameson's wife was murdered by a man in a mask, so he hates anyone in a mask, which sounds a bit odd, is that supported in canon?
Do we know exactly why he hates Spider-Man so much?

A: J. Jonah Jameson's hatred of Spider-man is both personal and pathological. Some of it is understandable but over the decades, different writers and editors have either expanded or contracted that hatred. In some decades, he was just shy of a madman, paying various scientists to create supervillains. In others, he is just a parasitic newsman taking advantage of Spider-man's notoriety/infamy to sell papers or air-time.

*

*Jonah has accomplished many things in his life. He was an award winning reporter and was active during the Civil Rights Movements. He did a series of stories on the KKK, exposing members, meeting places, and generally doing whatever he could to drag them into the public and humiliate them/lead to some arrests. He's actually been chased down and threatened with death by them. Ever since then, Jonah's mistrusted anyone in a mask, especially people who take the law into their own hands the way he feels Spider-Man does.

*Jonah's son John Jameson was an astronaut who was never afforded the fame Jonah felt his son deserved, while Spider-Man, a vigilante is lauded all over New York. John would also become known as the Man-Wolf at a later time in his life.

*Secretly, we learned that Jonah has more than a little jealousy of Spider-man's power and influence in society.

From Amazing Spider-Man #10
Pathological Hatred

*

*Most modern readers don't know the depth of Jameson's hatred of Spider-man. For a time Jameson hired or paid someone to create super-powered villains to attack Spider-Man

*The Scorpion was one of the first villains financed by J. Jonah Jameson to destroy Spider-Man.

*

*Former private investigator Mac Gargan was hired by J. Jonah Jameson to find out how Peter Parker was able to get incredible pictures of Spider-Man.1 Gargan's efforts to locate Peter in order to find out the truth triggered Parker's spider sense, making him easily avoidable every time.

The Scorpion, then and now; still as dangerous as ever.

*

*Frustrated, Jameson decided to pay $10,000 to Gargan to be the subject of an experiment. The experiment, created by Dr. Farley Stillwell, a researcher in animal mutation, which endowed the subject with the characteristic of another animal. Unfortunately the process resulted in the loss of Gargan's sanity, and the creation of the super-powered criminal menace known as the Scorpion.[Amazing Spider-Man #20]

He would later decide he wanted to take his revenge personally and hired mad scientists to create robots called Spider-slayers to kill the Wall-Crawler.

The first series of Spider-Slayer robots were originally designed and built by Dr. Spencer Smythe with the financial backing of J. Jonah Jameson who piloted them for the pleasure of personally hunting the superhero he hated for capture.

Spencer Smythe along with several Spider-Slayers

In Amazing Spider-Man #603, Jameson (now Mayor of New York) has some old Spider-Slayers sent to him from storage, to better equip his "Anti-Spider Squad" to take down Spider-Man. The Spider-Slayer technology is combined with that of the Mandroid suits. However, the "Spider-Slayer Squad" wearing the suits quit their jobs after Spider-Man saves them and New York from a dirty bomb.

A: Curiously enough, one episode of the early-mid 90's animated spider-man series, "The Sting of the Scorpion," went into more detail on this- in a flashback a masked mob enforcer tried to intimidate a younger J. Jonah out of printing a story; when Jameson ran it anyway said enforcer took a shot at him but missed, killing Jameson's fiance instead- Jameson just lumped Spider-man with other people "who wear masks and think they're above the law".


text:
Q: Why there is not Tomcat error page in Spring Boot 1.1.9.RELEASE I am using Spring Boot 1.1.9.RELEASE with thymeleaf. If there some error in my code, the Tomcat default error page doesn't display. I have disabled the sample error page. Please see my application.yml file.
error:
  whitelabel:
    enabled: false

Before 1.1.9.RELEASE, if I disable the whitelabel, the Tomcat error page will show. Is there any other config I need to do to show up the Tomat error page?

A: I don't think error.whitelable.enabled=false ever worked that way. To switch off the Boot error handling you need to actually exclude the ErrorMvcAutoConfiguration in your @EnableAutoConfiguration.


text:
Q: Killing process group from Ruby kills my whole computer I have a script (script.sh) that spawns a whole lot of child processes. If I run the script from the shell via ./script.sh, I can kill the whole process tree via
kill -- -<PID>

where PID is the process ID of the script.sh process (this apparently equals the group ID).
However, if I spawn the script from Ruby via
pid = Process.spawn(script.sh)

I cannot manage to kill the process tree.
Process.kill(9,pid)

only kills the parent process. And even worst, the following
Process.kill(9,-Process.getpgid(pid))  ### Don't try this line at home

terminates my computer.
Trying to kill the processes via
system("kill -- -#{pid}")

also fails.
How am I supposed to kill this process tree from Ruby?

A: I think I have found the solution. Spawning the process as
pid = Process.spawn(script.sh, :pgroup => true)

makes me able to kill the process group via
Process.kill(9,-Process.getpgid(pid))

It looks like bash groups processes by default, while Spawn doesn't enable this by default.


text:
Q: Subscribing to Podcasts in Windows Media Player I'm trying to subscribe to a podcast in Windows Media Player 10, but I did not find any options to do that. If Windows Media Player does not provide that option please suggest any other players (iTunes on Windows sucks).

A: It isn't possible.  Media player doesn't support podcasts.  Get the Zune player instead.  It has great podcast support.  You don't need a Zune to use it either.

A:
I use iTunes personally, works well on Windows and OS X.

I know you stated that you dislike iTunes on Windows, but I like it, regardless of platform.
You should just give it a go, especially if you have not used it recently. iTunes for Windows has really been polished up to make it harder, better, faster, stronger.
iTunes also has a massive repository of Podcasts in it's iTunes Online Music Store. I suggest you give it a look.

A: I use Juice personally, works well on Windows and other platforms. FOSS.


text:
Q: How to give download option for image,pdf etc files stored in storage folder depending on type of file in Laravel? I am learning Laravel. I want to show image(give download option)/pdf(show name of pdf file and give download and view(view on browser, in new tab) option) depending on extension on my view.
I have file_docs table. In that table I have column buyers_aadhar_file. In that column I am storing files like image OR pdf. I am customising name of file while storing like "buyersid_B_aadhar_nameoffile.ext" e.g 2_B_aadhar_Aadhaar-Card-New-Rules-Update-644x362.jpg or 3_B_aadhar_Aadhaar-Data-Update-Form-03.pdf
Now I want to display that files depending on type of file.
If file is image then show image also give download option for image. And if file is pdf then show name of pdf file, give download and view pdf file option for that file.
How do I check on my view, whether that file is image or pdf and how to implement relative download and view option for that file?

A: you could use path_info, a php function in the laravel view file to fetch the file extension and stuff like that
and you could look into this link for image showing and pdf showing in your view file


text:
Q: How to finish program with "Scanner.hasNext" in Java I'm wondering how the program with "java scanner" can be finished
especially when I use this with System.in and scanner.hasNext()
Scanner sc = new Scanner(System.in);

For example, when I run the code below on some IDE
    public static void main(String[] args){

         Scanner sc = new Scanner(System.in)
         int[] arr = new int[3];
         int i = 0;

         // put all the number from scanner to the array.
         while(sc.hasNext()){
              arr[i++] = sc.nextInt();
          }

          System.out.println(Arrays.toString(arr));

and input some numbers(for the inputs for scanner) in the console,
it doesn't stop receiving the numbers.
I wanted to use sc.hasNext() for the purpose of after finishing getting some input for the user, putting all the numbers received, as I commented on the code.
How can I finish the scanner getting the input on console?

A: Your code will run while stdin (System.in in Java) is open. You could close it programmatically if you want but it's usually done by pressing Ctrl+d
 in the terminal that program is running (Shortcut is for Linux/macOS in Windows console it's Ctrl+z I think).

A: You can change your while loop and put a conditional break when your number of integers reach array length. Try this,
while (sc.hasNext()) {
    arr[i++] = sc.nextInt();
    if (i == arr.length) {
        break;
    }
}

Or you can write it as a simple for loop,
// int i = 0;

for (int i = 0; i<arr.length;i++) {
    arr[i] = sc.nextInt();
}

Here it will be useful for you to understand how sc.nextInt() works.
Whenever sc.nextInt() gets executed, the scanner objects sc looks for an integer and returns the next integer it finds in the stream scanned by sc object. If it doesn't find an integer in the stream, it will throw some Exception.
Now coming to your code, when your while loop gets executed, every time the code gets inside while loop, it calls sc.nextInt() and one integer is read and assigned into the array but as you have declared your array size as 3 only you need to break the loop else it will try to access an index greater than 3 in your array and will result into ArrayIndexOutOfBounds exception which you will not want. Due to which I have put that condition in while loop and it breaks as soon as the index reaches 3. Similar thing is achieved in the for loop. Hope my explanation helps. Let me know if you have any queries further.
Another thing you could have done is, change sc.hasNext() to sc.hasNextInt() in your while loop as hasNext() captures any data (integer or non-integer) from the stream and returns true and you would not want it to return true if the next incoming data is not an integer else that will run into exception.
Once you change sc.hasNext() to sc.hasNextInt() in while loop condition, your program will automatically end once you provide 3 integers as input to your program but if user tried to enter more than 3 integers, it will run into ArrayIndexOutOfBounds exception as your array length is limited to 3 only. Hence you need that condition if (i==arr.length) { break; } So your while loop can also be like this,
while (sc.hasNextInt()) {
    arr[i++] = sc.nextInt();
    if (i == arr.length) {
        break;
    }
}

A: The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
However, to put the input from the user in your array, can be done by replacing your while condition with this:
while (sc.hasNext() && i!=arr.length) {
    arr[i++] = sc.nextInt();

}

A: Since your store the user's input inside a fixed size (4) structure, you can use a for loop,
after all this is the case to use it:

when the number of repetitions is predefined

for (int i = 0; i < arr.length; i++){
    arr[i] = sc.nextInt();
}

A: You don't need to put the condition for hasNext as it will always return true after entering an input.
You should have a condition on array length.
try this
                int[] arr = new int[3];
                 int i = 0;
                 while(i<arr.length)
                     arr[i++] = sc.nextInt();

                  System.out.println(Arrays.toString(arr));

A: just add a condition in while as you limit your array to a specific length so when it reach this length t can't take any more input and it will just close the loop and print your array
like this:
Scanner sc = new Scanner(System.in);
     int[] arr = new int[3];
     int i = 0;

     // put all the number from scanner to the array.
     while(sc.hasNext() && i < arr.length){
          arr[i++] = sc.nextInt();
      }

      System.out.println(Arrays.toString(arr));


text:
Q: Neo4j and Cypher: find all reachable nodes from a set of nodes with some constraints I have a graph containing two kinds of nodes: user nodes and IP nodes.
The only edge I have is :LOGGED_IN from user node to IP node.
What I am trying to find is all reachable user nodes from one user node.
So I have a Cypher like this:
MATCH (u: User)-[*]-(connected: User)
WHERE u.user_id = 'xxxxxxxxxxx'
RETURN distinct u, connected

However, I found that some IP nodes could be potentially a proxy IP so there will be more than 100 :LOGGED_IN edges to that specific IP node.
I am looking for a way to find all reachable user nodes but bypass all the one in the path with a proxy IP.
Also the definition of proxy IP node should be configurable like I can set a threshold to 1000 :LOGGED_IN edges. If there are more than 1000 incoming edges to the IP than it's a proxy IP.

A: An alternate to Bruno's solution (in case you have a great meany proxy ip nodes), is to add a WHERE clause to exclude any of those proxy nodes during the expansion.
match p = (u:User)-[*]-(connected:User)
where u.user_id = 'xxxxxxxxxxx'
and none(node in nodes(p) where node:ip and size((node)<-[:LOGGED_IN]-()) >= 1000)
return distinct u, connected

The none() function will be evaluated during expansion, not in a filter after the expansion, which should work for you.
One other thing you could try is using the expansion procs from APOC Procedures, some of which are optimized for only finding distinct nodes instead of finding all possible paths to the same nodes.
match (u:User)
where u.user_id = 'xxxxxxxxxxx'
call apoc.path.subgraphNodes(u, {labelFilter:'>User'}) yield node as connected
return u, connected

This one can't currently be optimized to exclude proxy ip nodes, but the NODE_GLOBAL uniqueness used during expansion may make up for it.

A: Try it:
match (i:ip)
where size(()-[:LOGGED_IN]->(i)) > 1000
match p = (u:User)-[*]-(connected:User)
where u.user_id = 'xxxxxxxxxxx'
and not i in nodes(p)
return distinct u, connected

That is: get all IP nodes with more than 1000 :LOGGED_IN relations. Then, get all paths that does not contains these nodes and return the desired data.

A: This is another version of @BrunoPeres' query that is fixed to correctly find paths without any proxy nodes.
Also, Unlike @InverseFalcon's first query, this one checks the degree-ness of each ip node once, instead of checking the (label and) degree-ness of every node in every path. Which approach is better depends on your DB's data characteristics.
MATCH (i:ip)
WHERE SIZE(()-[:LOGGED_IN]->(i)) >= 1000
WITH COLLECT(i) AS proxies
MATCH path = (u:User)-[*]-(connected:User)
WHERE u.user_id = 'xxxxxxxxxxx' AND NONE(p IN proxies WHERE p IN nodes(path))
RETURN DISTINCT u, connected


text:
Q: Getting F# on Ubuntu 10.04 I followed this to get F# on my Ubuntu machine. However, it returned me an error, saying

-- Resigning FSharp.Core.dll with mono.snk
  ./install-mono.sh: 24: sn: not found
  -- Installing FSharp DLLS into the GAC
  Failure adding assembly bin/FSharp.Core.dll to the cache: Strong name cannot be verified for delay-signed assembly

A: The sn utility is in the package mono-devel. So sudo apt-get install mono-devel and try again.
By the way: if you type sn into bash it will tell you which package you need to install to get sn. So the next time, you get a "command not found" error just try to type the command name into bash.

A: For reference, the reason for this issue is that FSharp.Core.dll needs to be re-signed with the Mono key at github.com/mono/mono/raw/master/mcs/class/mono.snk as described at bugzilla.novell.com/show_bug.cgi?id=615445 The solution to this issue is to re-sign the F# dll (download mono.snk, then run "sn -q -R FSharp.Core.dll mono.snk") as described by sepp2k.
However, since pre-built F# .deb packages for Ubuntu are now available at http://fsxplat.codeplex.com/ which work out-of-the-box without any need for dll re-signing you can simply use those instead.


text:
Q: D3 map - How do I include SVG image files in JSON data to create custom location markers? I'm trying to figure out how to include svg icon images in with my json data so the relevant icon will appear as a marker at the corresponding coordinates.
I've got the data in files separated by what shape of object was sighted (I'm mapping ufo sightings through the 20th century), and I created an svg image file for each shape as well.
I'm not sure what the best way is to connect the images to the data though. (I'm a relative beginner). here's a visual to help explain what I mean:
{   "date": "10/21/1989",   "shape": "Triangle",   "latitude": -41.05446,   "longitude": -130.72728,   "color": "violet" },

then I've got a corresponding 'Triangle.svg' icon in an 'icons' folder. I'm sure the solution is not a complicated one, I'm just not seeing it. Can anyone help?

A: It will be easier for you to switch from JSON to JS and use the following structure:
import TRIANGLE from '../path/to/triangle.svg';

const data = {
  date: '10/21/1989',
  shape: TRIANGLE,
  latitude: -41.05446,
  longitude: -130.72728,
  color: 'violet',
}

In case you are receiving the data from an API, try to get the full name and the path to the public folder. So you can have your images referenced as:
<img src={process.env.PUBLIC_URL + '/triangle.svg'} /> // here change triangle for your shape, in a loop or the way you render them.

More info on the PUBLIC_URL: https://create-react-app.dev/docs/using-the-public-folder/


text:
Q: Modify initial object values in JS I have a code what take the next array:

const arr = [
    {
        name:'',
        age:55
    },
    {
        name:'Bill',
        age:''
    },
]

..and i should take into account, if the key does not contains a value, i should output for that key, the value: no data;
 At the end i shoul get something like this:

const arr = [
    {
        name:'no data',
        age:55
    },
    {
        name:'Bill',
        age:'no data'
    },
]

I made this:

const arr = [
    {
        name:'',
        age:55
    },
    {
        name:'Bill',
        age:''
    },
]
const func = (arr) => {
const myKeys = arr.map(k => Object.keys(k))
   return  arr.map((i, k1) => {
        return myKeys[k1].reduce((acc,r )=> {
            return {
                [acc] : !i[r].toString().length ? 'no data' :i[r]
            }
        })

    })
};
console.log(func(arr))

How to achieve what i described above?

A: Not sure if i understood your question, but this seems to work:

const arr = [
    {
        name:'',
        age:55
    },
    {
        name:'Bill',
        age:''
    },
]

arr.forEach(item => {
  for(let key in item) {
    if(!item[key]) item[key] = 'no data';
  }
});

console.log(arr);

A: You could get the entries from the object, check the value and build a new object.

const
    array = [{ name: 'no data', age: 55 }, { name: 'Bill', age: 'no data' }],
    result = array.map(o =>
        Object.fromEntries(Object
            .entries(o)
            .map(([k, v]) => [k, v.toString() ? v : 'no data'])
        )
    );

console.log(result);

A: Solution with a double forEach:

const arr = [
    {
        name:'',
        age:55
    },
    {
        name:'Bill',
        age:''
    },
]
const func = (arr) => {
  arr.forEach((el) => {
    Object.keys(el).forEach((k) => el[k] = el[k].toString().length ? el[k] : 'no data')
  });
  return arr;
};
console.log(func(arr))

A: You're not updating the accumulator correctly in the reduce function. acc is the object you're building, not a property name. r is the current property name. So you should be assigning to acc[r].
You also need to provide an initial value argument {}.
You can also simplify the code by just calling Object.keys() inside the map function, rather than making a separate array of all the keys.

const arr = [{
    name: '',
    age: 55
  },
  {
    name: 'Bill',
    age: ''
  },
]
const func = (arr) => {
  return arr.map((i) => {
    return Object.keys(i).reduce((acc, r) => {
      acc[r] = !i[r].toString().length ? 'no data' : i[r];
      return acc;
    }, {})

  })
};
console.log(func(arr))

A: you can loop throw array object using map() then loop again throw object and see if object entry has value or not
arr.map(ele=>  {
  for (const [key, value] of Object.entries(ele)) {
        ele[key] = value ? value : 'no data';
    }
})


text:
Q: Get list of fields for History object via APEX I need to dynamically retrieve the list of fields for history objects, whether it be Asset or Opportunity etc. I normally use the following code to retrieve these fields for standard and custom objects:
String SobjectApiName = 'Asset';
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();

String apiNames = '';

for(String apiName : fieldMap.keyset())
{
    if(fieldMap.get(apiName).getDescribe().isUpdateable()) {
        apiNames += apiName + ',';
    }
}

system.debug(apiNames);

But this does not work for History objects.
How can I retrieve the list of field api names for say, "AssetHistory"?

A: When you collect the fields; you have a check isUpdateable; where you filter out the fields which are allowed to be updated by user.
As all fields on *History object (AssetHistory here) are read only, you do not see any fields in result.
Not sure what you are trying to do, removing isUpdateable condition will show you all the fields.


text:
Q: How to update a status label while processing something on the server? I have a requirement to process (server side) a lot of data (files) when the user clicks a button. I'd like to show a running summary of each file name as it's being processed. I've been trying to do it with the UpdatePanel control but only the very last update happens. Here's some simple code I created to simulate the issue (it should count up from 1 to 10 but instead waits the 5 seconds and outputs 10):
<%@ Page Language="C#" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>

    </form>

Is there a way to make this work? Or maybe a better way to do it?
Thanks in advance,
Jason

A: You'll need to use an ajax call to the server. I have copied this code from one of my previous projects it's a bit long code. try it and let me know if it works.
page1.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
   <ContentTemplate>

    <input type="submit" value="Start BackUp Process!"
    id="trigger" onclick="BeginProcess(); return false;"
    style="width: 250px;" />

    </ContentTemplate>
   </asp:UpdatePanel>

     <asp:UpdateProgress ID="UpdateProgress1"
     AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
         </ProgressTemplate>
</asp:UpdateProgress>

</asp:Content>

Process.aspx.cs
public partial class Process : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        StringBuilder SB = new StringBuilder();
        // Padding to circumvent IE's buffer.
        Response.Write(new string('*', 256));
        Response.Flush();

        // Initialization
        UpdateProgress(0, "Initializing task.");

        try
        {

            foreach (yourloophere)
            {

                        UpdateProgress(increment, db.Name + " Backup Started....");
                //your process code
                        UpdateProgress(increment, db.Name + " Backup Completed!");
  //your process code
                        SB.Append(db.Name + "BackUp Complted!");

        //your process code
                SB.Append("
");

            }

            // All finished!
            UpdateProgress(100, "All Database BackUp Completed!");

        }
        catch (Exception ex)
        {
            UpdateProgress(0, "Exception: " + ex.Message);

            SB.Append("Back Up Failed!");
            SB.Append("
");
            SB.Append("Failed DataBase: " + DBName);
            SB.Append("
");
            SB.Append("Exception: " + ex.Message);

        }

    }

    protected void UpdateProgress(double PercentComplete, string Message)
    {
        // Write out the parent script callback.
        Response.Write(String.Format("", PercentComplete, Message));
        // To be sure the response isn't buffered on the server.
        Response.Flush();
    }

}


text:
Q: Dynamic jQuery function with PHP I got a jQuery function that scales pictures so that the largest measurement is 350px, no matter of the original size.
jQuery:
function Scale(){
    var img = new Image();
img.onload = function () {
    alert('Orignal width:'+img.width+', height:'+img.height);
    var width, height;
    if (img.width > img.height) {
        width = (img.width > 350 ? 350 : img.width);
        height = img.height * (350 / img.width);
    } else {
        height = (img.height > 350 ? 350 : img.height);
        width = img.width * (350 / img.height);
    }
    img.width=width;
    img.height=height;
    $("#img-holder").append(img);
}

img.src = "picture.jpg"
}

I'm retrieving picture links from my database using a PHP loop.
PHP:
$q = "SELECT * FROM `items`";
$row = mysqli_query($con, $q) or die(mysqli_error());
while($r = mysqli_fetch_assoc($row))
{
  //do stuff
}

The picture link will then be stored as $r['picture'] every time the loop runs.
My problem: How do I run the jQuery script for every picture I retrieve with the loop?

A: Assign max-width and max-height in your CSS for all such images. No JavaScript required.
#img-holder img {
   max-width: 350px;
   max-height: 350px;
}

or, to maintain proportions:
#img-holder img {
    max-width: 350px;
    max-height: 350px;
    width: auto;
    height: auto;
}

http://jsfiddle.net/mblase75/FKsL8/

A: There has many ways to implement your need. One of them is you create a class model "ShowImage" include two property width, height, or just simple is create array of images that you got from SQL and pass to view. Then you can fetch each image and show them with your expect size.
But I recommend you do not do that. Just leave server side's stuff is on server side and client side's stuff is on client side.
You can do exactly thing with php like what your function Scale did since php there has function to get dimension of given image getimagesize.
Best is you just need one function that generates thumbnail with given max size, so you can resuse it, you will not worry about such stuff around image anymore.
There are so many functions that handle thumbnail stuff that you can find, such as here
<<
I don't encourage making by CSS, in the practice, you really do not want your page loads all the big images & just show them up by 350px.

A: You will have to use Ajax for that one. You could setup a button that would request the link via ajax to your php file. Then when you get the link back you would just display however you want it.


text:
Q: How an user of my application can delete sharedpreferences? I'm developing an app that use SharePreferences in order to avoid user cheating.
But how an user can delete sharedPreferences?
There is a better method to save data like SharePreferences that is more secure?

A: One way is for the user to uninstall the application, then re-install it. Unless you maintain data somewhere else, such as a hidden file elsewhere on the device, I'm not sure there's any way to get around that.

A: Consider using internal storage on the device. Only your app will have access to it. visit this link
you can read more here about the security of storage options


text:
Q: Are energy levels specific to certain atoms? For such a simple question, I cannot find an answer anywhere. Are the energy levels specific to each atom? For example, is the energy required to jump from the first energy level to the second energy level of Boron the same in each atom? Or are energy levels different for every single atom (even ones with the same proton number)?
Sorry if this is a stupid question, I'm fairly new to energy levels in physics.

A: Short/practical answer: Energy level structure is in a practical way, specific for atomic species. e.g. all Boron atoms have the same energy level structure. This is why spectroscopy works.
Long/theoretical answer: You need to specify the exact Hamiltonian of the system to do that calculation. When you do that, ionic species are slighty different in energy levels compared to neutral species due exchange interaction and total coulombian interaction, and isotopes have slighty differente energy levels due a negligible term of gravitational energy contribution because nucleus mass is different and also because reduced mass of system is changed (reduced mass as pointed @Sebastian Riese, when reduced mass is greater than another specie is near to Bohr-Oppenheimer approximation where nucleous is static).
Thus, energy levels are different in ionic and isotopes species of the same atomic number.


text:
Q: interfaces and DB I have code like this and this is pure java class which does not involve and DB Connections
    if(transfer.getAmount().getDestination().getCountryCode().equals("CN"){
        transfer.getBankDetails().setCountryCode("CN");
        transfer.setDeliveryOptions(null);
        return new Event(this, "D2B");
    }else if(transfer.getAmount().getDestination().getCountryCode().equals("US"){
        transfer.getBankDetails().setCountryCode("CN");
        transfer.setDeliveryOptions(null);
        return new Event(this, "D2B");
    }

and this code repeats for all the countries now I want optimize the code.
For that I have a table which has country name and country table.
So I want to get the country code from DB and reduce most of the code.

A: Use a HashMap<String, String> in which you will insert your list of countries. Then you just need to call you code once, like
String aCountryCode = transfer.getAmount().getDestination().getCountryCode();
String aBankCountryCode = aMapOfCountries.get(aCountryCode );

if (aBankCountryCode != null) {
  transfer.getBankDetails().setCountryCode(aBankCountryCode );
}


text:
Q: Is this possible to write in Dart the high performance code that works on 32-bit machines with 32-bit integers? I was a little discouraged such a huge difference in performance when working on 32-bit machines with 32-bit integers in Dart language.
Is this means that Dart VM still not optimized for integer arithmetic?
Here is my pretty straightforward test.
void main() {
  var tests = new List();
  tests.add({"name" : "16-bit", "result" : 0});
  tests.add({"name" : "32-bit", "result" : 0});
  tests[0]["result"] = test1(0x8000);
  tests[1]["result"] = test1(0x80000000);
  int best;
  for(var test in tests) {
    var result = test["result"];
    if(best == null) {
      best = result;
    } else if(best > result) {
      best = result;
    }
  }

  for(var test in tests) {
    var result = test["result"];
    var percent = (result / best * 100).round();
    print("${test["name"]}: $percent%");
  }
}

int test1(int value) {
  int result = 0;
  var count = 10000000;
  var sw = new Stopwatch();
  sw.start();
  for(var i = 0; i < count; i++) {
    var result = value + i;
  }

  sw.stop();
  return sw.elapsedMicroseconds;
}

Output:
16-bit: 100%
32-bit: 13285%

This means that in some real cases performance can be slower in 130 times?

A: Your test is flawed. test2 cannot use 32 bit integers since the number gets to large.
If you modify your test as follows they will take exactly the same time:
library lexer_perf;

import '_perf.dart';
import 'package:angular/core/parser/lexer.dart';

void main() {
  var tests = new List();
  tests.add({"name" : "16-bit", "result" : 0});
  tests.add({"name" : "32-bit", "result" : 0});
  tests[1]["result"] = test1(0x3fffffff); // 2^30 is the maximum small (32bit) integer value
  tests[0]["result"] = test1(0xffff);
  int best;
  for(var test in tests) {
    var result = test["result"];
    if(best == null) {
      best = result;
    } else if(best > result) {
      best = result;
    }
  }

  for(var test in tests) {
    var result = test["result"];
    var percent = (result / best * 100).round();
    print("${test["name"]}: $percent%");
  }
}

int test1(int value) {
  int result = 0;
  var count = 10000000;
  var sw = new Stopwatch();
  sw.start();
  for(var i = 0; i < count; i++) {
    var result = value - i; // Subtract instead of add so that we do not exceed maximum small integer value.
  }

  sw.stop();
  return sw.elapsedMicroseconds;
}

Output:
16-bit: 122% // Well within margin of error.
32-bit: 100%

A: Original question: "Is it possible to write in Dart the high performance code that works on 32-bit machines with 32-bit integers?"
Short Answer: No. It is possible to write high-performance code for 31bit integers, but not 32bit integers.
Why?
Dart doesn't have the notion of a 32bit integer.
Integers are, by Dart spec, arbitrary-length. But for performance reasons, there are different internal representations for smaller ranges. The problem is that the small int range is not 32bit, but 31bit (on a 32bit system). Thus, everything between [-(2^30+1), -(2^31)] or [2^30, 2^31-1] is not a small int anymore, but a medium int which is 64bit.
The full ranges, for completeness sake, are:
System          smi      mint     bigint
[32bit system]: 31bit    64bit    limited by RAM
[64bit system]: 63bit    64bit    limited by RAM

Source: https://www.dartlang.org/articles/numeric-computation/#integers