text:
Q: Filtering a collection based on an arbitrary number of options How can the following Scala function be refactored to use idiomatic best practices?
  def getFilteredList(ids: Seq[Int],
      idsMustBeInThisListIfItExists: Option[Seq[Int]],
      idsMustAlsoBeInThisListIfItExists: Option[Seq[Int]]): Seq[Int] = {

    var output = ids

    if (idsMustBeInThisListIfItExists.isDefined) {
      output = output.intersect(idsMustBeInThisListIfItExists.get)
    }
    if (idsMustAlsoBeInThisListIfItExists.isDefined) {
      output = output.intersect(idsMustAlsoBeInThisListIfItExists.get)
    }

    output
  }

Expected IO:
val ids = Seq(1,2,3,4,5)
val output1 = getFilteredList(ids, None, Some(Seq(3,5))) // 3, 5
val output2 = getFilteredList(ids, None, None) // 1,2,3,4,5
val output3 = getFilteredList(ids, Some(Seq(1,2)), None) // 1,2
val output4 = getFilteredList(ids, Some(Seq(1)), Some(Seq(5))) // 1,5

Thank you for your time.

A: Here's a simple way to do this:
  implicit class SeqAugmenter[T](val seq: Seq[T]) extends AnyVal {
    def intersect(opt: Option[Seq[T]]): Seq[T] = {
      opt.fold(seq)(seq intersect _)
    }
  }

  def getFilteredList(ids: Seq[Int],
    idsMustBeInThisListIfItExists: Option[Seq[Int]],
    idsMustAlsoBeInThisListIfItExists: Option[Seq[Int]]
  ): Seq[Int] = {
    ids intersect
      idsMustBeInThisListIfItExists intersect
      idsMustAlsoBeInThisListIfItExists
  }

A: Yet another way without for comprehensions and implicits:
def getFilteredList(ids: Seq[Int],
                  idsMustBeInThisListIfItExists: Option[Seq[Int]],
                  idsMustAlsoBeInThisListIfItExists: Option[Seq[Int]]): Seq[Int] = {

  val output1 = ids.intersect(idsMustBeInThisListIfItExists.getOrElse(ids))
  val output2 = output1.intersect(idsMustAlsoBeInThisListIfItExists.getOrElse(output1))

  output2
}

A: Another similar way, without implicits.
def getFilteredList[A](ids: Seq[A],
                       idsMustBeInThisListIfItExists: Option[Seq[A]],
                       idsMustAlsoBeInThisListIfItExists: Option[Seq[A]]): Seq[A] = {
  val  a = intersect(Some(ids), idsMustBeInThisListIfItExists)(ids)
  val  b = intersect(Some(a), idsMustAlsoBeInThisListIfItExists)(a)
  b
}

def intersect[A](ma: Option[Seq[A]], mb: Option[Seq[A]])(default: Seq[A]) = {
  (for {
     a <- ma
     b <- mb
   } yield {
     a.intersect(b)
   }).getOrElse(default)
}


text:
Q: Authentication on LDAP Server using React Native and Firebase custom tokens I'm trying to authenticate my users (from my RN application) through the LDAP server (I've already found one to try authentication here, and it works!). I can create a custom token using Firebase every time I receive the credentials of the users (username and password) and save it in the Firebase real-time database.
The main problem is that I do not know how to connect my application with the LDAP server, I investigated and found that I have to install something like openLDAP or ldapjs but I do not understand how authentication has to be
My guess is:

*

*User login in my RN application

*The RN application sends credentials to Firebase

*Firebase creates a custom token (uses the Firebase Functions to generate the custom token)

*Firebase returns the custom token to the RN application

*The RN application sends the token to the LDAP server (the server has predetermined users and passwords for testing)

*The LDAP server validates the token, therefore, authentication

*LDAP server returns attributes or "not found" to the RN application

*RN App grant / deny access to the app

Any help or advice will be well received, thanks :)
Sorry for my bad english.

A: You're almost there, but instead of sending the Firebase custom token to the LDAP server, you authenticate the user with the LDAP server before minting the Firebase token. Both of these must be done in a trusted environment, such as a server you control or Cloud Functions, and you'll typically use a Firebase Admin SDK on that environment.
So:

*

*User login in my RN application.

*The RN application sends credentials to trusted environment.

*Trusted environment verified credentials with the LDAP server.

*Trusted environment creates a custom token using the Firebase Admin SDK. If needed this token can contain custom attributes from the LDAP server, in the form of Custom Claims.

*Trusted environment returns the custom token to the RN application

*RN App grant / deny access to the app

For more on this, see the Firebase documentation on custom auth. From there:

To achieve this, you must create a server endpoint that accepts sign-in credentials—such as a username and password—and, if the credentials are valid, returns a custom JWT. The custom JWT returned from your server can then be used by a client device to authenticate with Firebase (iOS, Android, web).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Ads suddenly stopped working after few months [Android][iOS][Flutter] I had banner, interstitial, and reward ads on one of my apps. The ads seemed to have been working for the past 2 months and then suddenly yesterday both android and iOS apps stopped showing ads:
iOS Error: code: 1, domain: com.google.admob, message: Request Error: No ad to show
Android: code: 3, domain: com.google.android.gms.ads, message: No ad config
It's also strange that both the apps have different error codes.
Package: google_mobile_ads: ^0.12.1+1
Code:
Container(
     height: bannerAd.size.height.toDouble(),
     child: AdWidget(
            ad: bannerAd,
            ),
     margin: EdgeInsets.symmetric(vertical: 30),
)

Note:

*

*The test ads seem to work just fine.

*The Android and iOS apps have been published on the stores and have been working just fine for the past 2 months.

A: If your test ads are working fine, means their is nothing to worry, your implementation is correct, just cross check your ads ids is correct and on place.

Something, i want to mention here that the ads are user specific and
may be for you ads are not available at some moments, Just check with
other users or other devices.
Also check your admob account for any limit putted by admob due to unwanted traffic or may be for some other reason.

You can wait for sometime, if their is any limit putted by admob will be automatically removed.
Suggestion
Don't click on any ads from your side and also don't increase ad traffic on your account from one device

A: Error Code 3 : ERROR_CODE_NO_FILL
Description : The ad request was successful, but no ad was returned due to lack of ad inventory.
Why is  it Happening : Advertisers can target specific regions, platforms and user profiles based on business relevance, which can sometimes result in lower availability of Ads for a particular region or user profile. Error code suggests that the implementation is correct, and that the Ad Request was not filled because of lack of availability of a suitable Ad at that particular instant of time when an Ad Request was sent from the app.

A: This maybe because, the ads might no be available at the moment. As there will be a limit for the ads that you render in your applications. Please wait for a while or just ping the product analysis team.

A: It happens to my admobs as well. They do not always have ads available. What I started doing was testing for an ad from admobs and if non available, I use an ad from somebody else.


text:
Q: How to enable a function only if the parameter is dereferencable to a certain type? I am making a function template:
template <typename T>
void foo (T arg1) {}

But I want to make sure T is deferencable to type Foo, so arg1 needs to be either:
Foo * //This case T = Foo*

Or
Any type X which implements `*` operator which returns a Foo/Foo&/Foo&&

So I need something like:
template <typename T>
void foo(T arg1, std::enable_if<std::is_same<typeid(*arg1), typeid(Foo)>::value> * = 0) {}

But this does not compile and complains:
typecheck.cpp:6:54: error: use of parameter âarg1â outside function body
 void foo(T arg1, std::enable_if<std::is_same<typeid(*arg1), typeid(Foo)>::value> * = 0) {}
                                                      ^

How can I achieve this?

A: You should prefer is_convertible instead of is_same to catch sub classes of Foo, the enable_if in the template argument list instead of the function arguments or return type is also easier to read.
template <typename T, typename = typename std::enable_if<std::is_convertible<decltype( *std::declval<T>() ), Foo>::value>::type >
void foo(T arg1);

less garbage in c++14 :
template <typename T, typename = std::enable_if_t<std::is_convertible<decltype( *std::declval<T>() ), Foo>::value> >
void foo(T arg1);

A: You want decltype, not typeid. You use typeid to get run-time type information, whereas decltype will give you the type of an expression at compile-time.
std::is_same<decltype(*arg1), Foo>::value

Note, if you don't need a call with a type that doesn't point at a Foo to fall back to a different overload, then you might prefer to use static_assert instead of std::enable_if:
template <typename T>
void foo(T arg1) {
  static_assert(std::is_same<decltype(*arg1), Foo>::value, "Performing indirection with an object of type T must give a Foo");
  // ...
}

A: A template is way too complicated:
void foo(Foo&);
void foo(const Foo&);
void foo(Foo*);
void foo(const Foo*);

and dispatch accordingly.
#include <iostream>

struct Foo {};
struct Any {
    operator Foo () const { return Foo(); }
};

void foo(const Foo&) {
    std::cout << "Hello Foo\n";
}

int main() {
    Any a;
    foo(a);
}


text:
Q: Using VS2012 diff tool from console Is it possible to use VS 2012 diff tool from console like below?
compare.exe c:\file1 c:\file2

EDIT

*

*Also you can run diff tool from Command Window and it will run in the same instance of VS.
Tools.DiffFiles c:\file1 c:\file2

*Moreover there is an extension for VS 2012.

A: devenv /diff c:\file1 c:\file2

A: To open the Visual Studio Code Diff Tool from cmd or powershell you can enter the following command and need to specify your files of course:
code --diff <path1> <path2>


text:
Q: Add Text To A Certain Line In A Text File With Batch Is it possible to have a command used in a batch file to append to a text file and add text on a certain Line in the txt file?

Txt File:
  1
  2
  3
  5

Is it possible to add a new line and put 4 between 3 and 5?

A: This answer will add a 4 between a 3 and a 5.
@echo off
setlocal enabledelayedexpansion
ren in.txt in.tmp
set p=
for /f %%a in (in.tmp) do (
  if "%%a"=="5" if "!p!"=="3" Echo 4 >> in.txt
  Echo %%a >>in.txt
  set p=%%a
)
del in.tmp


text:
Q: Django South alternative? After reading some older posts about Django South's features, I began wondering why there wasn't a similar tool built in to Django itself.  Then I was curious if maybe something had been added these last few years.
Has something been added?
Are there any alternatives to South, or is it the accepted way of handling migrations and such?

A: The same thought django core developers had. Since Django 1.7, migrations is a built-in feature:

Django now has built-in support for schema migrations. It allows
  models to be updated, changed, and deleted by creating migration files
  that represent the model changes and which can be run on any
  development, staging or production database.

Note that 1.7 is not a stable version at the moment.


text:
Q: Running Karate in Github Actions? I have got Github project for a backend which has an elaborate REST API. I would like to add Karate-based testing as one of the Github Actions steps.
Has anybody written a Github Action that runs standalone Karate to do test against a backend? (Feels like something that more people might want to do.. but I couldn't find anything)

A: I think the answer is because Karate is typically "just another JUnit project" - so if you are for e.g. maven based, you just use an existing Maven GitHub action and you should be good.
FWIW - here is how Karate runs a CI job on GitHub: https://stackoverflow.com/a/66005331/143475


text:
Q: Problem with an angular filter of objects without using routes (Angular TS) I need some help about the code: I have to make a filter for a list of objects and I have to use the observables (the exercise only includes the front end part) and the objects are in a database.
    with the code written as soon as I insert a letter in the search bar, the array is emptied and only the last letter remains (for example insert C and after I insert E, in the filter only the E remains)
in TS:
Search(name:any):void{

        this.arraycopy=this.mylist

        })
        this.arraycopy=this.mylist.filter(res =>{
            return res.description.includes(name.key) ;
        })
 }

IN HTML:

                  {{list.description}}

A: Are you sure you're updating your Observable with the full search-bar input and not just the last key pressed?
You are probably updating it based on the keypress event which returns the last key pressed.
Update on Answer:
Try this:
Search-bar:
<input type="text" [ngModel]="searchInput" (keyup)="Search()">

In TS:
  public searchTerm = new BehaviorSubject('');
  public searchInput: string;

      constructor() {
          this.searchTerm.subscribe((text: string) => {
              this.arraycopy = this.mylist.filter(res => {
                  return res.description.includes(text);
              });
          });
       }

       public Search(): void {
           this.searchTerm.next(this.searchInput);
       }

This should work, but with this you're not using Observables so good.


text:
Q: Spherical perverse sheaves on the affine Grassmannian and critically twisted $D$-modules Let $G$ be a reductive algebraic group and let $Gr_G=G((z))/G[[z]]$ be its affine Grassmannian. Define $\mathcal{D}(Gr_G)_{crit}-mod$ to be the category of right $D$-modules on $Gr_G$ twisted by the critical level of $G$ (which is $-1/2$ the Killing form).
In this paper of Frenkel-Gaitsgory it is mentioned on page $1347$ that there is an equivalence
$$\mathcal{D}(Gr_G)_{crit}-mod^{G[[z]]} \cong Rep(G^{\vee})$$
between the category of $G[[z]]$ equivariant critically twisted $D$-modules on $Gr_G$ and representations of the Langlands dual. I'm a little bit confused since the geometric Satake equivalence is phrased most often using $G[[z]]$-equivariant perverse sheaves on $Gr_G$, and not $D$-modules.
By Riemann-Hilbert, I know that perverse sheaves are related to regular holonomic $D$-modules, but I fail to see how this gives us the equivalence of categories written above. Does anyone have a quick explanation of this? Thanks in advance.


text:
Q: The spin degeneracy and the adiabatic theorem Consider that we have a system with a time dependent hamiltonian $H(t)$. We consider that the hamiltonian changes from $H(0)$ to $H(t)$, ($t$ large), and we assume that the change occurs slowly. So, the adiabact theorem states that, if the system is initially in the $n$th eigenstate of $H(0)$, in the instant $t$ it will be in the $n$th eigenstate of $H(t)$.
A condition to it be true is that the spectrum is non-degenerate and discrete, so there is no ambiguity in the ordering of the eigenstates. My question is: Suppose our system is simply a spin 1/2 particle subject to a potential that does not depend on the spin of the particle; the eigenstates of its hamiltonian will be degenerate with respect to the spin (right?). In this case the adiabatic theorem would be appliable? To me, it look likes we can use the theorem, because I think the change in hamiltonian can't change the spin of the particle.

A: This system can be decomposed into a tensor product of two uncoupled subsystems, one which does not depend on spin and one which depends only on spin. The adiabatic theorem can be applied to the former subsystem.


text:
Q: Implementing permission directive won't update view until page refresh I have created a directive to show/hide element according to permission.
Implementation of directive is somehow like:
 <ng-container *appHasAccess="'user.profile'">
<button>Profile</button>
</ng-container>

Directive code is:
import {
  Directive,
  Input,
  OnDestroy,
  OnInit,
  TemplateRef,
  ViewContainerRef,
} from "@angular/core";
import { PermissionsService } from "@core/services/permissions";
import { Subject } from "rxjs";
import { takeUntil } from "rxjs/operators";

@Directive({
  selector: "[appHasAccess]",
})
export class HasAccessDirective implements OnInit, OnDestroy {
  @Input() appHasAccess: string;
  stop$ = new Subject();

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private permissionsService: PermissionsService
  ) {}

  ngOnInit(): void {
    this.permissionsService
      .checkAuthorization(this.appHasAccess)
      .pipe(takeUntil(this.stop$))
      .subscribe((authorized) => {
        if (authorized) {
          this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
          this.viewContainer.clear();
        }
      });
  }

  ngOnDestroy() {
    this.stop$.next();
  }
}

This works for only page refresh scenario. View is not updated on value change.
Can anyone help me on this?

A: If I have understood correctly your problem, you could set the current username in the PermissionService as a Subject. That way the service can emit new values when the curren user changes:
service.ts
export class PermissionsService {
  user = '';
  private currentUser = new Subject<string>();

  public setCurrentUser(user) {
    this.user = user;
    this.currentUser.next(user);
  }

  checkAuthorization(): Observable<boolean> {
    return this.currentUser.pipe(
      map( x => { return x === 'me'; })
    )
  }
}

In the above code the checkAuthorization is an observable to which you can subscribe in your Directive. In fact this code is almost the same you had except that I removed the parameter:
directive.ts
  ngOnInit(): void {
    this.permissionsService.checkAuthorization()
      .pipe(takeUntil(this.stop$))
      .subscribe((authorized) => {
        this.viewContainer.clear();
        if (authorized) {
          this.viewContainer.createEmbeddedView(this.templateRef);
        }
      });
  }

Note that you have to clear the viewContainer always because otherwise it would create a new button every time.
Check this demo I made based on your example: https://stackblitz.com/edit/angular-fevt6t


text:
Q: How can I exit a click function or prevent the function from triggering until a condition is met Goal:
I want to be able to add comments onto images and use their X,Y coordinates to save the comment and display for later.
Expected Result:
I want a user to click on a "New Comment" button which enables "Comment Mode" and displays a form. If a user clicks away from the form, I want the form to hide and "Comment Mode" to become disabled until the user clicks "New Comment" again. If "New Comment" is pressed again, repeat the above.
Actual Result:
The snippet of code currently allows a user to click "New Comment". Once clicked the commentMode() function is triggered and listens for a click on the #imageWrapper. If the user clicks away, the form is hidden - but when I press "New Comment" again, the form remains hidden.
function commentMode() {
          imageWrapper.toggleClass('new-comment-pointer'); // changes cursor to show its active
          imageWrapper.click(function(e) { // on clicking the image
            newComment = !newComment; // newComment is true
            console.log(newComment);
            if(newComment) { // if newComment is true, show the form near the click
              getCoordinates(e, $('#imageWrapper'));
              form.show().css({'left': formX, 'top': formY});
              form.find('textarea').focus();
              form.find('#xAxis').val(x); // x is from the getCoordinates
              form.find('#yAxis').val(y); // y is from the getCoordinates
            } else { // if newComment is false, hide the form and turn stop imageWrapper.click
              form.hide();
              imageWrapper.removeClass('new-comment-pointer');
              newComment = !newComment;
              return; //stop listening for click
            }
            return;
          });
        }

https://codepen.io/lachiekimber/pen/YzzPEqw

A: I do not know why everybody make it complicated.
First give the form and the button a id. Then define a default form css class which is hidden.Define another ones which makes it visible some kind of:

Now we add a document listener which make things more simple instead fiddeling on whatever event...
document.addEventListener(" click ", function(event) {
//try to get a id even when the event element has not
// directly a id but maybee his parent the form
try {
   var id = event.target.id;
   if (id === "") {
      for (i = 0; i < event.path.length; i++) {
        id = event.path[i].id;
        if (id !== "") {
           if (id === "formid") {
            break;
           }
        }

    }
    } catch(ex){
       console.log(ex);
       return;
    }
    var form=document.getElementById("formid");
    switch(id){
        case "showcommehtbuttonid":
        case "formid":
              form.classList.add("visible");
        break;
        default:
              form.classList.remove("visible");
    }
 }

The toggle state has a disadvantage in your case - complicate to handle. Works best by a simple id and button. There is no doubt about then. Adding and removing handlers also makes no real sense. Either the user clicks on the form or the button and the form becomes visible. Or he clicks something else. In this case no id or the "wrong" id will be chosen. In this case the default switch rule make the form invisible. The thing is untested and might need some minor tweaks. And best - in the event handler you can now also add very simple more actions.

A: As @Davo mentioned in the comments, I attempted to refactor the code. I started by cleaning up the code into functions and not nesting click events. Whilst refactoring, I used console.log's to help me identify when the commentMode was active - then triggered the showForm() or hideForm() functions. For a working example: https://codepen.io/lachiekimber/pen/bGGNYmK
$(function () {

        var imageWrapper = $('#imageWrapper');
        var form = $('.new-comment');
        var x, y, formX, formY;
        var newComment = true;
        var commentMode = false;

        $('#newComment').click(function() {
          imageWrapper.toggleClass('new-comment-pointer');
          commentMode = !commentMode;
          //console.log('newComment');
        });

        $('#imageWrapper').click(function(e) {
          if(commentMode) {
            //console.log('commentMode: true');
            showForm(e);
          } else {
            //console.log('commentMode: false');
            hideForm();
          }
        });

        function showForm(e) {
          getCoordinates(e, imageWrapper);
          form.show().css({'left': formX, 'top': formY});
          form.find('textarea').focus();
          form.find('#xAxis').val(x); // x is from the getCoordinates
          form.find('#yAxis').val(y); // y is from the getCoordinates
        }

        function hideForm() {
          form.hide();
        }

        function getCoordinates(e, image) {
          var offset = image.offset();
          x = e.pageX - offset.left;
          y = e.pageY - offset.top;
          formX = x + 50;
          formY = y + 20;
        }

});

A: Working and tested  :) ! Ok we could work on the page style quite a bit but :d
Look how simple the whole page looks also. I do not have to fight with jquery for this little task :) I set also the autofocus just by plain html.
            <!DOCTYPE HTML>

                <title>Untitled</title>

                <form id="formid" class="invisible">

Form

                    <input type="text" name="size" autofocus>

                </form>

                <input type="button" value="click" id="showcommentbuttonid">


text:
Q: Cauchy Integrals This was given to me as a $2$ part question. I was able to answer the $1$st part but the $2$nd part has me confused.
a. Let C be the unit circle $z=e^{i\theta}$ where $-\pi\le\theta\le\pi$. Use the Cauchy Integral Formula to evaluate $$\int_C\frac{e^{az}}{z}dz$$
I worked this out to be $2\pi i$. The $2$nd part is where I get lost.
b. Express the integral in terms of $\theta$ and find the values of $$\int_0^\pi e^{a\cos\theta }\cos\left(a\sin\theta\right)\ d\theta $$
I'm not sure where to go with part b.

A: You may parametrize the integral as $z=e^{i\theta}$ which makes the integral into:
$$\int_{-\pi}^{\pi}\frac{e^{ae^{i\theta}}}{e^{i\theta}}ie^{i\theta}d\theta=\int_{-\pi}^{\pi}e^{a\cos(\theta)+ia\sin(\theta)}id\theta=\int_{-\pi}^{\pi}e^{a\cos(\theta)}(\cos(a\sin(\theta))+i\sin(a\sin(\theta)))id\theta$$
$$=2i\int_{0}^{\pi}e^{a\cos(\theta)}\cos(a\sin(\theta))d\theta$$
Recall that from $(a)$ we have the value of $\frac{1}{2i\pi}\int_{C}\frac{e^{az}}{z}dz$


text:
Q: How to extract two integers for a string and perform arithmetic operation? I have made a code that could extract an int from a string and perform calculation in python
user_input = input('')
     if user_input[0:3] in ['add']:
          print(int(user_input[4]) + int(user_input[10]))

The code could add only one digit number but I wanna add two 'n' digit number it goes in a lengthy way for tons of lines so I don't want to repeat the same code again and again instead I need a small block of code replacing to add two 'n' digit numbers can any one give me any suggestions.

A: You can use split() to break the input string into operation and argument components, and then perform the arithmetic operation. I am assuming that your input has this format:
<op> <arg1> <arg2>

for example,
add 1 2

If the user enters add 100 24 then when you split it you will get this:
>>> user_input = input()
add 100 24
>>> user_input.split()
['add', '100', '24']

You can bind the items of the list returned by split() to variables like this:
>>> op, arg1, arg2 = user_input.split()
>>> op
add
>>> arg1
100
>>> arg2
24

In order to perform the operation we need the arguments as numeric values (I'm assuming that floats may be entered):
>>> arg1 = float(arg1)
>>> arg2 = float(arg2)

Now arg1 and arg2 are 100.0 and 24.0 respectively. Next step is to perform the operation. You can map strings to functions using a dictionary:
import operator

operations = {'add': operator.add,
              'sub': operator.sub,
              'mul': operator.mul,
              'div': operator.truediv}

and then perform the operation like this:
if op in operations:
    result = operations[op](arg1, arg2)
else:
    print('Invalid operation: {}'.format(op))

Now you can perform any of the above operations, e.g. div 100 20, sub 10 100 etc.
This works by looking up the operation in the dictionary using the op as a key, and then using the corresponding value as the function to call, passing the arguments to that function.

A: If all you want to do is to add stuff, you can simply split your string along the word add:
test1 = "17 add 4"

summands = test1.split("add")
result = sum(int(s) for s in summands)
print(result)

In case you want to do more advanced stuff, you have to split your string a bit more carefully. In this case, regular expressions can come in handy:
import re

test2 = "17 add 4 divide 3"
parts = re.split(r"(add|divide)", test2)
print(parts)

This gives you a list of number literals and operators. It's then up to you to transform this list into a computation.
Of course you can also cheat:
test3 = "(17 add 4) divide 3"
print(int(eval(test3.replace("add", "+").replace("divide", "/"))))

This is unsafe if you have no control over your input (in this case, an attacker  might use eval to execute arbitrary code).
Edited to add:
Since I'm procrastinating, I went ahead and wrote a more complete example:
# Testcase
test4 = "((17 ADD 4) DIVIDE 3) MINUS 4"

# Define stuff that can appear inside an expression:
operators = ["add", "subtract", "minus", "multiply", "times", "divide"]
parens = [r"\(", r"\)"]
replacements = {
    "add": "+", "subtract": "-", "minus": "-", "multiply": "*",
    "times": "*", "divide": "/",
}
tokens = operators + parens
baretokens = [t.replace("\\", "") for t in tokens]
delims = "({0})".format("|".join(tokens))

# Split the testcase in its parts
parts = re.split(delims, test4.lower())
print(parts)

# Replace operators with their Python counterparts:
result = ""
for p in parts:
    if p.strip().isdigit():
        result += p
    elif p in baretokens:
        if p in replacements:
            result += replacements[p]
        else:
            result += p
    elif p.strip() == "":
        pass
    else:
        raise ValueError("Malformed expression: '{0}'".format(p))
print(result)

# Do the computation using eval (should probably be safe, since
# maliscious code should be refused as malformed):
computed = int(eval(result))
print(computed)


text:
Q: convert xml to plist - xml attributes? I want to convert a xml file to a plist file, but I dont know how to save the information of the xml attributes <tag attribute="value"></tag>
example xml:
<root>
     <tag attribute="value">Stackoverflow</tag>
</root>

as far as I know, .plist file doesnt provide attributes, so what can I do to prevent a .plist like this:
<root>
     <array>
          <item>StackOverflow</item>
          <item>value</item>
     </array>
</root>

I dont want an array for each tag with an attribute, so does anyone knows a simplier approach? I searched the web on this but couldnt find a solution. Thank you.

A: Rather than dwelling on the plist format, I think the more interesting question is what is the appropriate combination of nested NSArray and NSDictionary collection objects that best represent this structure in Objective-C. Then, once you have it in nested collection objects, you can employ the writeToFile method to generate the plist file automatically.
Now you say that you don't want an "array for each tag with an attribute". First, I wouldn't have suggested an array, but I'd actually suggest a dictionary. Second, that's precisely what I think you want, a consistent, intelligible representation for each tag. Third, I'd suggest you do this not only for the tags with attributes, but I might even do it for all tags.
I'm not sure why you said you don't want to use an array for each tag, but while it might seem inefficient, it turns out that it's much easier to do that, because then your structure will be in a consistent, easy to use format.
The simplest solution is to have a dictionary for each element in the XML source, one key would be @"value" and another would be @"attributes" (and you could omit the attributes if there were none).
Imagine the following XML:
<produce>
    <product>
        <name language="English">Apple</name>
        <price currency="USD">1.23</price>
        <color>red</color>
    </product>
    <product>
        <name language="English">Banana</name>
        <price currency="USD">2.63</price>
        <color>yellow</color>
    </product>
</produce>

I'm suggesting you have an array of products, for which each product is a NSDictionary with three keys, name, price, and color. The values for these three are, themselves, NSDictionary objects, but with two keys, value and, if appropriate, attributes. Thus, if you were going to represent that resulting series of nested objects manually in code, it might look like (where, @[a, b, c] is a NSArray, and @{key1:value1, key2:value2} is a NSDictionary):
NSArray *array = @[
                   @{
                       @"name":
                           @{
                               @"value" : @"Apple",
                               @"attributes" : @{@"language":@"English"}
                            },
                       @"price":
                           @{
                               @"value" : @1.23,
                               @"attributes" : @{@"currency":@"USD"}
                            },
                       @"color":
                           @{
                               @"value" : @"red"
                            }
                    },
                   @{
                       @"name":
                           @{
                               @"value" : @"Banana",
                               @"attributes" : @{@"language":@"English"}
                            },
                       @"price":
                           @{
                               @"value":@1.46,
                               @"attributes":@{@"currency":@"USD"}
                            },
                       @"color":@{@"value":@"yellow"}
                    }
                ];

While that looks complicated, it's actually incredibly easy to use. If you want the second object, that would be array[1]. If you want the color of that second object, it would be array[1][@"color"][@"value"]. If you wanted the name of the language of the first object, it would be array[0][@"name"][@"attributes"][@"language"]. Once you start using this nested collection object structure, you can see (a) why I prefer dictionaries to arrays; but also why (b) I use the same dictionary structure whether there is an attribute or not, that way the process of retrieving the value is consistent at all times.
Anyway, if I now employ the writeToFile method, that happens to yields a plist like so:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>color</key>
        <dict>
            <key>value</key>
            <string>red</string>
        </dict>
        <key>name</key>
        <dict>
            <key>attributes</key>
            <dict>
                <key>language</key>
                <string>English</string>
            </dict>
            <key>value</key>
            <string>Apple</string>
        </dict>
        <key>price</key>
        <dict>
            <key>attributes</key>
            <dict>
                <key>currency</key>
                <string>USD</string>
            </dict>
            <key>value</key>
            <real>1.23</real>
        </dict>
    </dict>
    <dict>
        <key>color</key>
        <dict>
            <key>value</key>
            <string>yellow</string>
        </dict>
        <key>name</key>
        <dict>
            <key>attributes</key>
            <dict>
                <key>language</key>
                <string>English</string>
            </dict>
            <key>value</key>
            <string>Banana</string>
        </dict>
        <key>price</key>
        <dict>
            <key>attributes</key>
            <dict>
                <key>currency</key>
                <string>USD</string>
            </dict>
            <key>value</key>
            <real>1.46</real>
        </dict>
    </dict>
</array>
</plist>

But the nice thing is, I don't have to write a plist myself. I just load the XML into my structure of nested arrays and dictionaries, and then use writeToFile to generate the plist file. And when I want to use that plist, I can now read it with a single call to arrayWithContentsOfFile.


text:
Q: what is an 'outstanding' frame? What is meant by outstanding frame ?
I read this term while studying GBN protocol .
From wikipedia:

frames since the first lost frame are outstanding, and
  will go back to sequence number

A: I think outstanding here means - still waiting for acknowledgement.
All the successful frames were passed successfully and the reciever sent an acknowledgement for them, but it didn't recieve the lost frame and ignore the following frames, so these frames are still outstanding

A: The outstanding frames are those frames which the source had sent from inside the window and their acknowledgement has not yet come.
Suppose The window size is 4 then source will send 4 packets at a time and these packets are not been acknowledged and are still inside the window so these are the outstanding frames.
In your case this line means that if the first frame sent by the source is lost or does not get an acknowledgement then It would send those outstanding frames again form the start because destination hasnt recieved the frames in sequence.

A: From Windows Security Encyclopedia

"Outstanding packets" are packets that the Packet Scheduler has submitted to a network adapter for transmission but which have not yet been sent.


text:
Q: How do I put a .csv file correctly into an array in PHP? So I'd like to make a basic login/register page. I got a CSV file which roughly looks like this:
a, b
r,d
login, pass

I am already able to correctly add new combinations to the file. But if I want to put the CSV into an array so that I can check if the username/password combination is true, I only get the first row in the array, so [0] = "a" and [1] = "b". There are similar questions on this site on how to put a csv into an array, but with every solution this problem comes up. How do I get the other elements in the array, too?
Edit: as suggested, the code I used:
$database = fopen("database.csv", "r");
                $data = fgetcsv($database, 1000, ",");
                print_r($data);

This returns: Array ( [0] => q [1] => w )
Exact data:
q,w
g,h
o,p
t,y
c,d
o,p
o,p
a,b

Hope you can help me.

A: You can see from the documentation that fgetcsv returns just one line from the file pointer, and NULL or FALSE if it was unable to get another line.
You should put your code in a while loop to get all of the CSV rows.
$credentials = array();
$database = fopen("database.csv", "r");
while (is_array($data = fgetcsv($database, 1000, ','))) {
    $credentials[] = $data;
}
fclose($database);

var_dump($credentials); // This contains all of the credentials.


text:
Q: Create hdf5 file with combination of image and matrix I tried to retrain a model from this github but I encounter a problem of creating hdf5 for it. So far i only know that hdf5 should contain images path and possible label/class of it.
But on my case, it has a combination of images and matrix of light estimation. Is this possible to achieve or did I make wrong interpretation of the instruction. Please help me understand this
This is one of the light estimation matrix that they provide
0.300794    0.121209    -0.115402   0.073493    -0.126265   -0.035606   0.013735    -0.018538   -0.055469   0.202293    0.105253    -0.058834   0.047335    -0.097811   -0.032969   0.010878    -0.024713   -0.028035   0.150027    0.096441    -0.049527   0.032507    -0.088273   -0.033228   0.007316    -0.015788   -0.021543


text:
Q: 'Two of us' or 'the two of us' If my dad and I are going a market, can I say

Two of us are going to the market.

or I should say

The two of us are going to the market.

I am kind of confused about the "the" here. What role is it playing over here??
If I take a guess, I would say that the difference is just like "a car" and "the car"? Am I right?

A: The is the definite article. When you use it, you think that your listener/reader already knows the thing being referred to, or that he will be able to understand what you are referring to from the context.
Let's say there are 5 persons in your family. Imagine that you and your father are talking with a friend of your family. The friend knows that there are 5 persons in your family. The other 3 members of your family are not present. You say:

Two of us are going to the market.

Depending on the context of your conversation, he might understand this as:

*

*2 persons from your family of 5 will go to the market. That might be the mother and one of the daughters. That might be the father and the mother, etc.

*2 persons out of the 3 persons present during the talk will go to the market. That might be the friend and you, or the friend and your father. Who that will be exactly has not been determined yet.

*2 persons out of some group you have mentioned during the talk will go to the market. You belong to this group, but that does not necessarily mean that you personally will go to the market.
However, if you say:

The two of us are going to the market.

Then, depending on the context of your conversation, he might understand this as:

*

*You and your father are going to the market.

*You and him are going to the market.
The most likely situation is that you and your father are going to the market, and you're telling this to the friend of the family.
Note that with the, in both cases you are part of this two-person group.   Without the, in all the three cases you may be part of the two-person group, but not necessarily.

A: The role being played is being specific. "Two of us" could be any pair in theory while "The two of us" is more specific by using a definite article.
There could also be some emphasis as another part added here since the second sentence seems to focus more on there being two of us.

A: When you use the phrase "two of us",  it means you + a person (indefinite) who the listener doesn't know are going to the market.
On the other hand, when you use  "the two of us", it means that the listener knows who you are referring to (i.e. you + your father) who are going to the market.

A: I've just up-voted CowperKettle's answer, but on second thoughts, I agree with only the first part.

The is the definite article. When you use it, you think that your listener/reader already knows the thing being referred to, or that he will be able to understand what you are referring to from the context.

I agree with this part. I am just another English learner, but I want to know if what I feel is correct.
I think that either 'two of us' or 'the two of us' might include the speaker, but not necessarily.
Also, I think when there are only the speaker and his son in the living room, the father starts to talk about his idea by saying "Two of us are going to the market." Here it doesn't matter how many are in the family. It's the same 'two of us' as spoken by any couple of people meaning 'you and me.' And this is the reason it implies 'excluding the rest.'
And when he talks more about the idea, I think it's natural to keep saying 'two of us' or 'we.' (This is when talking among the two person.)
When 'the two of us' includes the speaker, it might be just an alternative expression to talk about the two already mentioned, but I think it gets to sound like the speaker is being objective or a story teller, or shifting his point of view to the third person. (You use 'The two of us' to talk about us to someone else.)
I would like a confirmation or correction from native speakers.
I have another situation: I think it's natural to start speaking by saying "Two of them look sad" while watching the two people sitting in some distance, though "The two of them look sad" is also natural without any context because you are watching them. Am I correct?


text:
Q: abbreviation for number neutral? I don't know if this is the right place to ask this..
But when identifying pronouns, they are often given codes
1ms = 1st person masculine singular
and if a language, e.g. english and many others, don't specify gender in the first person, then C is (common?) gender..
1cs = (I guess) 1st person ("common?") singular
So "I" or "me" in English is given the pronoun abbreviation code 1cs
What about though, if the third letter in the abbreviation (the gender), is "common"? e.g. in English, in the second person "You" can be male or female, singular or plural.  It's like 2cc (though i've not seen the abbreviation 2cc)   What is the correct abbreviation to describe that neutral gender and neutral number?

A: There is a misconception in the basis of your question here: common gender is not the same as not specifying gender. The common gender is an actual gender, used in some languages (Danish, Swedish, Norwegian Bokmål, Hittite, etc.). I would not advise using that to refer to non-gendered forms.
In languages (or pronouns, or any other context) that does not specify gender at all, the most common practice is to simply leave out the gender-designating letter altogether. So where 1ms is 'first person singular, masculine', the most common way of writing 'first person singular, any gender' is simply 1s.
The same logic is sometimes applied to number as well; for example, the Lithuanian verb is always the same in the third person, whether singular or plural, and this is often noted as simply 3, with no extra letters at all. The same can be done for you in English.
If you wish to be more specific and reduce the risk of misunderstanding—a single number in running text is not necessarily very clear—you can include all the possible values instead of leaving them all out. In that way, the Lithuanian verb forms would be 3spl (or 3s/pl for enhanced readability), and you in English is 2splmf (or 2s/pl-m/f for readability). This is the approach usually taken when a particular form is relevant to multiple (but not all) cases in a given paradigm, like the Sanskrit ending -bhyām, which is idadu (instrumental, dative, and ablative dual).


text:
Q: Minecraft Spigot: Null pointer Error while registering a command I have a plugin but I've been having an issue registering a command. the command is setup in the onEnable along with in the plugin.yml. any ideas on what could be wrong?
Main Class
public void onEnable() {
        //////
        this.getCommand("wsmain").setExecutor(new wsmain());
}

Plugin.yml
name: [Redacted]
version: ${project.version}
author: [Redacted]
main: [Redacted]

commands:
  wsmain:
    description: [Redacted]
    usage: /<command>
    permission: ws.main

api-version: 1.13

loadbefore: [FastAsyncWorldEdit, WorldEdit, BuildersUtilities]

StackTrace

[14:57:23 INFO]: [WorldSystem] Enabling WorldSystem v2.4.10
[14:57:23 ERROR]: Error occurred while enabling WorldSystem v2.4.10 (Is it up >to date?)
java.lang.NullPointerException: null
at de.butzlabben.world.WorldSystem.onEnable(WorldSystem.java:103) ~>>>[?:?]
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:263)
[patched_1.16.1.jar:git-Paper-135]
at >org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:380>) ~[patched_1.16.1.jar:git-Paper-135]
at >org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:48>3) ~[patched_1.16.1.jar:git-Paper-135]
at org.bukkit.craftbukkit.v1_16_R1.CraftServer.enablePlugin(CraftServer.java:500) ~[patched_1.16.1.jar:git-Paper-135]
at org.bukkit.craftbukkit.v1_16_R1.CraftServer.enablePlugins(CraftServer.java:414) ~[patched_1.16.1.jar:git-Paper-135]
at net.minecraft.server.v1_16_R1.DedicatedServer.init(DedicatedServer.java:209) ~[patched_1.16.1.jar:git-Paper-135]
at net.minecraft.server.v1_16_R1.MinecraftServer.v(MinecraftServer.java:941) ~[patched_1.16.1.jar:git-Paper-135]        at net.minecraft.server.v1_16_R1.MinecraftServer.lambda$a$0(MinecraftServer.java:177) ~[patched_1.16.1.jar:git-Paper-135]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_231]
[14:57:23 INFO]: [WorldSystem] Disabling WorldSystem v2.4.10
[14:57:23 ERROR]: Error occurred while disabling WorldSystem v2.4.10 (Is it up to date?)
java.lang.ExceptionInInitializerError: null
at de.butzlabben.world.WorldSystem.onDisable(WorldSystem.java:212) ~[?:?]
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:265) ~[patched_1.16.1.jar:git-Paper-135]
at org.bukkit.plugin.java.JavaPluginLoader.disablePlugin(JavaPluginLoader.java:415) ~[patched_1.16.1.jar:git-Paper-135]
at org.bukkit.plugin.SimplePluginManager.disablePlugin(SimplePluginManager.java:516) ~[patched_1.16.1.jar:git-Paper-135]
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:384) ~[patched_1.16.1.jar:git-Paper-135]
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:483) ~[patched_1.16.1.jar:git-Paper-135]
at org.bukkit.craftbukkit.v1_16_R1.CraftServer.enablePlugin(CraftServer.java:500) ~[patched_1.16.1.jar:git-Paper-135]
at org.bukkit.craftbukkit.v1_16_R1.CraftServer.enablePlugins(CraftServer.java:414) ~[patched_1.16.1.jar:git-Paper-135]
at net.minecraft.server.v1_16_R1.DedicatedServer.init(DedicatedServer.java:209) ~[patched_1.16.1.jar:git-Paper-135]
at net.minecraft.server.v1_16_R1.MinecraftServer.v(MinecraftServer.java:941) ~[patched_1.16.1.jar:git-Paper-135]        at net.minecraft.server.v1_16_R1.MinecraftServer.lambda$a$0(MinecraftServer.java:177) ~[patched_1.16.1.jar:git-Paper-135]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_231]
Caused by: java.lang.NullPointerException
at java.io.FileInputStream.(Unknown Source) ~[?:1.8.0_231]
at de.butzlabben.world.config.PluginConfig.getConfig(PluginConfig.java:95) ~[?:?]
at de.butzlabben.world.config.PluginConfig.getDatabaseType(PluginConfig.java:212) ~[?:?]
at de.butzlabben.world.util.database.DatabaseProvider.(DatabaseProvider.java:14) ~[?:?]
at de.butzlabben.world.util.database.DatabaseProvider.(DatabaseProvider.java:8) ~[?:?]
... 12 more

A: Did you try it by deliting the "this." before getCommand("...").?

A: [?:1.8.0_231] [14:57:23 INFO]: [WorldSystem] Disabling WorldSystem v2.4.10 [14:57:23 ERROR]: Error occurred while disabling WorldSystem v2.4.10 (Is it up to date?)
So I think u might have imported an older Version of Spigot in your IDE so if you have try to import the same Spigot File as in your Server Directory

A: The Error was Spigot Gradlew Doesn't use the traditional Plugin.yml
https://github.com/spigradle/spigradle/blob/master/docs/spigot_plugin.md#usage


text:
Q: como puedo hacer que funcione bien mi DB::Select en laravel? Buen día, colegas programadores tengo un problema que no entiendo el por qué, tengo el siguiente query:
$cuotas = DB::select('select fecha, if(cantidad>0, cantidad + cantidad * porcentaje,cantidad) cantidad, round(if(cantidad>0, @saldo:= cantidad + cantidad * porcentaje, @saldo:=@saldo + cantidad),2) saldo from credito where id_cliente='.$id_cliente.' and id>=(select max(id) id from (SELECT * FROM credito where cantidad>0 and id_cliente='.$id_cliente.') a)');

y me muestra esto (esto está bien):

pero al hacer este query:
$cuotas = DB::select('select fecha, cantidad, saldo from (select fecha, if(cantidad>0, cantidad + cantidad * porcentaje,cantidad) cantidad, round(if(cantidad>0, @saldo:= cantidad + cantidad * porcentaje, @saldo:=@saldo + cantidad),2) saldo from credito where id_cliente='.$id_cliente.' and id>=(select max(id) id from (SELECT * FROM credito where cantidad>0 and id_cliente='.$id_cliente.') a) order by fecha desc limit 5 ) a order by fecha asc');

y muestra esto que no me muestra el saldo, sino que lo muestra null (esto está mal):

Pero si yo hago ese query en mi Gestor de BD todo está bien porque me muestra lo siguiente:

Pensando en la solución se me ocurren varias cosas.
1- Como puedo hacer para que el query me funcione y no me dé nulo.
2- Como puedo hacer para que aunque ponga todo el resultado en el foreach ó html me muestre únicamente las últimas 5 filas por ejemplo.
PD: ya hice varias pruebas y me he dado cuenta de que cuando agrego "Order by" ya me empieza a mostrar el null en el saldo, específicamente cuando le coloco el DESC, ya que si se deja como esta o se le coloca ASC no hay ningún problema


text:
Q: Google Keep -- how to hack info into Keep using Javascript Does anyone know how I might put a new note into Google Keep using Javascript, e.g. from a Chrome app or extension?  There doesn't seem to be an API, and it's not clear to me how to trick the front end into thinking that I have typed in text or uploaded an image.
All help greatly appreciated!

A: You are correct that there is not yet a published API, however, take a look here for clues to the unpublished API you might be able to use: http://discovery-check.appspot.com/notes/v1


text:
Q: How can I write a list comprehension to create a list of sets? I tried to create a list of sets [set([0]), set([1]), set([2]),..] using
>>> [set(i) for i in range(9)]

but it did not come out well
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not iterable

How to create that list with a list comprehension? Is it possible?

A: To create [set([0]), set([1]), set([2]),..] with a list comprehension you would use:
>>> [{i} for i in range(5)]
[set([0]), set([1]), set([2]), set([3]), set([4])]

Unless you are using any version of Python prior to version 2.7, then use:
>>> [set((i,)) for i in range(5)]
[set([0]), set([1]), set([2]), set([3]), set([4])]

However, it seems kind of silly that you are creating a list of sets where each set is a single integer of increasing sequence. Whatever you are trying to accomplish might be better done a different way, please consult The XY Problem and make sure you are not falling into this.
Depending on what you are trying to accomplish, there may be a better way to store your data, or perform the logic you are trying to perform.
NOTE:
Originally I wrote [set([i]) for i in range(5)] But after timing the different options, I realized that converting the integer into a single-item list is more wasteful than converting it to a tuple, so I changed my answer, and subsequently changed it again to use the set literal , timing below:
>python -mtimeit "[{i} for i in range(5)]"
1000000 loops, best of 3: 0.853 usec per loop

>python -mtimeit "[set((i,)) for i in range(5)]"
1000000 loops, best of 3: 1.64 usec per loop

>python -mtimeit "[set([i]) for i in range(5)]"
1000000 loops, best of 3: 1.87 usec per loop


text:
Q: Not getting acronyms list displayed separately in latex document while the same code works fine in overleaf (online latex platform) This following code is giving me the output without displaying the list of acronyms.
Code:
\documentclass{article}

\usepackage[acronym]{glossaries}
\makeglossaries

\newacronym{cd}{CD}{compact disk}

\begin{document}
\noindent
First use \gls{cd}\\
subsequent \gls{cd}

\printglossaries

\end{document}

Output:
First use compact disk (CD)
subsequent CD

Can someone please help me identify the issue? The same code works fine in overleaf. Probably some issue with installed glossaries package but not sure.


text:
Q: error in initializing the c-array in the constructor in c++ This is my code  i am getting error in initializing the char array in the constructor. i have also tried to initialize it with a string but all in vain . good help will be appreciated.
#include <iostream>
using namespace std;
class employe
{
    char name[30];
    int id;
public:
    employe(int a, char b[30] ) :id(a), name(b)
    {

    }
    char getid()
    {
        return name;
    }

};

A: The problem is that when an array is passed to a function (and the constructor is just a function) then it will decay to a pointer to its first element.
That means the argument b in your constructor is really a pointer (type char*), and you can't initialize an array from a pointer.
The simplest solution is to copy from the pointer to the array inside the constructor body:
// Copy the string from b to name
// Don't copy out of bounds of name, and don't copy more than the string in b contains (plus terminator)
std::copy_n(b, std::min(strlen(b) + 1, sizeof name), name);

A better solution is to use std::string for strings, and then you can initialize like you attempt to do now.


text:
Q: explaining by giving example I want to explain a situation that happened in my results using an example.
If I say my idea as follows;

For example, because of merging of two segments shown in yellow colour
  in Fig. 8, disappearing of a relation (or graph edge) relevant to the
  vanished segment and creation of an incorrect relation with
  unrealistic adjacencies occurred.

My question is, can I use "because of" just after "for example" and explain like above?
any assistance please.

A: I would say there's nothing wrong with using "because of" just after "for example," but I feel the whole sentence would flow better if you used active voice:

For example, the merging of two segments shown in yellow colour in Fig. 8 caused the disappearance of a relation (or graph edge) relevant to the vanished segment, and the creation of an incorrect relation with unrealistic adjacencies.


text:
Q: Proving the non-degeneracy of the critical points of the potential function for a certain vector field with $ n $ point-singularities This question is an expansion of another question that I asked over at Math Stack Exchange.
In what follows, $ \alpha \in \mathbb{R}_{> 1} $ is a constant, $ n $ a fixed integer $ \geq 2 $, and $ [n] \stackrel{\text{df}}{=} \mathbb{N}_{\leq n} $.

Let $ \mathbf{p}_{1},\ldots,\mathbf{p}_{n} $ be distinct points in $ \mathbb{R}^{2} $, and let $ q_{1},\ldots,q_{n} $ be positive real numbers. Then define a smooth vector field $ \mathbf{F}: \mathbb{R}^{2} \setminus \{ \mathbf{p}_{i} \}_{i \in [n]} \to \mathbb{R}^{2} $ by
$$
\mathbf{F}(\mathbf{x})
\stackrel{\text{df}}{=}
\sum_{i = 1}^{n}
\frac{q_{i}}{\| \mathbf{x} - \mathbf{p}_{i} \|^{\alpha}} \cdot
(\mathbf{x} - \mathbf{p}_{i}).
$$
One can interpret $ \mathbf{F}(\mathbf{x}) $ as a sum of repulsive central forces exerted by $ \mathbf{p}_{1},\ldots,\mathbf{p}_{n} $ on $ \mathbf{x} $.
By a winding-number argument, one can prove there exists an $ \mathbf{x} \in \mathbb{R}^{2} \setminus \{ \mathbf{p}_{i} \}_{i \in [n]} $ lying inside the closed convex hull of $ \{ \mathbf{p}_{i} \}_{i \in [n]} $ such that $ \mathbf{F}(\mathbf{x}) = \mathbf{0} $. The argument runs roughly like this:

*

*Assume for the sake of contradiction that there is no such $ \mathbf{x} $.

*Then the only singularities of $ \mathbf{F} $ are $ \mathbf{p}_{1},\ldots,\mathbf{p}_{n} $.

*Let $ C $ be a circular counterclockwise contour that contains $ \mathbf{p}_{1},\ldots,\mathbf{p}_{n} $ in its interior.

*The winding number of $ \mathbf{F} $ with respect to $ C $ should be $ 1 $.

*Let $ \{ C_{i} \}_{i \in [n]} $ be a collection of circular counterclockwise contours such that for every $ i \in [n] $, (i) the center of $ C_{i} $ is $ \mathbf{p}_{i} $ and (ii) $ \mathbf{p}_{j} $ lies outside of $ C_{i} $ for every $ j \in [n] \setminus \{ i \} $.

*For every $ i \in [n] $, the winding number of $ \mathbf{F} $ with respect to $ C_{i} $ should also be $ 1 $.

*Hence, the total index of $ \mathbf{F} $ at its singularities is $ n $.

*However, this contradicts the Index Theorem (as $ n \neq 1 $).

If $ U $ denotes the potential function for $ \mathbf{F} $, then what this says is that $ U $ has a critical point.

Question. Is it true that every critical point of $ U $ is isolated, or even better, non-degenerate?

One can derive from the Hessian of $ U $ the system of equations that must hold for non-degeneracy to occur, but this system forms a wall that I am unable to surmount.
I would appreciate it if someone could offer suggestions on how to tackle this problem. References are also very welcome. Thank you!

A: I consider it highly unlikely that the critical points are always nondegenerate. Intuitively, you can imagine a finite number of such points for a generic choice of $q$, which could then "collide" for special choices of $q$. Even taking something as simple as regular $n$-
-gon for $n>2$ and all $q=1$ might give a degenerate critical point at the origin (but I haven't done the calculation).
On the other hand, my intuition is that there should be no positive-dimensional sets of critical points, but I don't have a proof of this either.

A: My reason for this post is two-fold: (i) To give an answer for the case $ \alpha = 2 $. (ii) To attract attention to the other cases, which remain open.

The potential function $ U: \mathbb{R}^{2} \setminus \{ \mathbf{p}_{i} \}_{i \in [n]} \to \mathbb{R} $ corresponding to $ \mathbf{F} $ is given by
$$
\forall \mathbf{x} \in \mathbb{R}^{2} \setminus \{ \mathbf{p}_{i} \}_{i \in [n]}:
\quad
  U(\mathbf{x})
= \sum_{i = 1}^{n}
  \frac{q_{i}}{2} \cdot \ln(\| \mathbf{x} - \mathbf{p}_{i} \|^{2}).
$$
Let $ \mathbf{c} $ be a critical point of $ U $. Then let $ (l_{i})_{i \in [n]} $ be a sequence of parallel and non-intersecting rays in $ \mathbb{R}^{2} $ so that for every $ i \in [n] $, the following conditions hold:

*

*The starting point of $ l_{i} $ is $ \mathbf{p}_{i} $.

*$ \mathbf{c} \notin l_{i} $.

By these conditions, $ \displaystyle D \stackrel{\text{df}}{=} \mathbb{R}^{2} \bigg\backslash \bigcup_{i = 1}^{n} l_{i} $ is a connected open subset of $ \mathbb{R}^{2} $ that contains $ \mathbf{c} $.
Define a sequence $ (L_{i})_{i \in [n]} $ so that for every $ i \in [n] $, $ L_{i} $ denotes the complex logarithm function with branch cut $ l_{i} $. Identifying $ \mathbb{R}^{2} $ with $ \mathbb{C} $, the sum $ \displaystyle L \stackrel{\text{df}}{=} \sum_{i = 1}^{n} L_{i} $ is a non-constant holomorphic function on $ D $. Consequently, $ \mathbf{c} $ is an isolated critical point of $ U $ as $ U|_{D} = \Re(L) $.

The question thus has an affirmative answer when $ \alpha = 2 $. However, the interesting case is $ \alpha = 3 $, which models inverse-square-law forces and so is more relevant to the natural world.


text:
Q: Issue accessing elements of nested associative array So I have some data that's coming back from a database query, and the resulting array (gotten with print_r) looks like this (it's assigned to a var called $locationData):
Array
(
    [0] => Array
        (
            [id] => 1
            [location_name] => Cook Minnesota
            [location_lat] => 47.72037
            [location_long] => -90.32667
        )

    [1] => Array
        (
            [id] => 2
            [location_name] => Lake Minnesota
            [location_lat] => 47.18238
            [location_long] => -91.35301
        )

    [2] => Array
        (
            [id] => 3
            [location_name] => St. Louis Minnesota
            [location_lat] => 46.83572
            [location_long] => -91.96299
        )
 )

I have a foreach loop that needs to grab the location_name from each. It looks like this:
foreach ($locationData as $location => $value ) {
   echo '
name ' . $location['location_name']. '
';
}

I'm 99% certain this should work; it's basically the same code I've used a dozen times before. But the echo is not returning anything - not even the static text (
name). It's not throwing any errors, and if I try to do a print_r($location), I get nothing.
Any ideas? I'm sure it's something really simple.

A: You want $value['location_name'] because $value represents the arrays while $location represents the indexes of the arrays:
   echo '
name ' . $value['location_name']. '
';

A: It is:
foreach ($locationData as $location => $value ) {
   echo '
name ' . $value['location_name']. '
';
}


text:
Q: Why does "\1" inside a triple-quoted string evaluate to a unicode 0x1 code point I wanted a String containing a text \1.
What I did was (the real string was longer but it's not important):
'''
 \1
'''

Which resulted in a String containing a unicode 0x1 codepoint.
I think what I should've done is just escape the backslash like this:
'''
 \\1
'''

What I don't understand is why Groovy didn't report an error here. I thought unicode escapes are supposed to look like \u1?
Instead of a syntax error I got a runtime exception when I tried to put this String into an XML element:
An invalid XML character (Unicode: 0x1) was found in the element content of the document.

A: The \ (backward slash) symbol is an escape symbol. If you mean to use it literally, you must escape it itself: \\.
When you escape any character, the character is interpreted to have special meaning. In the case of the \1 sequence, it just happens that this can be interpreted as the 0x01 codepoint.
This is the same in Java Strings.
If you want to not have to escape characters in Groovy, use slashy strings:
def x = /\1/
assert x == "\\1"

which also works as multiline:
def x = /
\1
/


text:
Q: Creating square responsive box with 4 elements per row MARKUP::

CSS::
.alumni {
max-height: 280px;
padding: 10px;
overflow: auto;
}
.alumni-list {
text-align: center;
margin-bottom: 10px;
padding: 0px 5px;
}
.innerBg {
height: 56px;
max-width: 56px;
background-size: cover;
border-radius: 4px;
background-position: center center !important;
}

alumni container contains 4 alumni-list. Irrespective of screen size, all alumni-list should come in square shape. This is what I tried so far and I'm using bootstrap 3.


text:
Q: Lightbox using InterImage Link with response I have a response in which I am storing both the thumbnail and the Original Images as shown below.
context.Response.Write("")

So Now how do I give the Lightbox effect
Here is my Uploadify OnComplete event:


text:
Q: Energy Conservation for STFT The project I am working on requires a short-time Fourier transformation. For this, I use scipy.signal.stft. From theory, we learn that the signal in time domain has the same energy as in time-frequency domain; Parseval's theorem (https://en.wikipedia.org/wiki/Parseval%27s_theorem). However, when I use scipy.signal.stft, I do not obtain the same amount of energy if I compare the computation for both values of energy. I am pretty sure, it is because there is some scaling involved when using scipy.signal.stft, so I spit through the source code. After some deep search, I have found a scaling factor of np.sqrt(1/(sum(win)**2)). However, using this scaling factor, does not work:
Example code:
fs = 10e3
N = 1e5
amp = 2 * np.sqrt(2)
noise_power = 0.01 * fs / 2
time = np.arange(N) / float(fs)
mod = 500*np.cos(2*np.pi*0.25*time)
carrier = amp * np.sin(2*np.pi*3e3*time + mod)
noise = np.random.normal(scale=np.sqrt(noise_power),
                         size=time.shape)
noise *= np.exp(-time/5)
x = carrier + noise

frame_size = 1000
window = scipy.signal.windows.hann(frame_size,sym=False)
f, t, Zxx = scipy.signal.stft(x, fs, window=window, nperseg=frame_size)
scale = np.sqrt(1/(sum(window)**2))
Zxx_scaled = Zxx/scale

Et=np.sum(x**2)
Ef=np.sum(abs(Zxx_scaled)**2)/N
print("Et = %.3f" % Et)
print( "Ef = %.3f" % Ef)

results in (depending on noise, but in the scale of):
Et = 1641328.607
Ef = 6158.539

Does anyone know how to properly scale the resulting STFT matrix values to obtain equal energy levels and prove energy conservation for the STFT?
(I am looking for a sum(window)**2 constant transformation (and window) and, as the window is used in the STFT and I-STFT, I assume I have a 'tight frame' transformation if I use the hann window. However, proving energy conservation is a first step.....)


text:
Q: Can I avoid running junit tests twice in eclipse when using a TestSuite? I need to do some per-suite initialisation (starting a web-server). It is working fine except that when I run all tests in my project in eclipse my tests run twice. My test suite looks a bit like this:
@RunWith(Suite.class)
@Suite.SuiteClasses({
   SubtestOne.class,
   SubtestTwo.class
})
public class TestSuite
{
   [...]
}

public class SubtestOne
{
   @Test public void testOne() { [...] }
}

public class SubtestTwo
{
   @Test public void testTwo() { [...] }
}

When I run all test in project in eclipse this causes the junit plugin to run the tests twice like this:

*

*SubtestOne

*SubtestTwo

*TestSuite

*

*SubtestOne

*SubtestTwo

Is it possible to make "run all test in project" not run the sub-tests twice? I want my sub tests to be only ever run as part of the suite.

A: No, the test class will always be started directly and then through the "link" in the suite. This is as expected.
One workaround might to set in the run configuration to only run tests from the package which contains your suites. Open the run configuration and select Run all tests in the selected project, package or source folder then click Search... and select the package.

A: I realize that this has been asked over 5 years ago, but as quite a few folks up-voted the question I thought I'd still chime in with a solution. Skip right to the end if you just want the solution; read the whole text if you also want to understand it ;-)
First of all, it is indeed possible to ensure that a particular JUnit test class gets only run inside a test suite. Also, it is irrelevant whether you want to run that test suite inside Eclipse (as asked here) or any other tool or environment; this is really a pure JUnit issue for the most part.
Before I sketch out the solution, it might be a good idea to revisit what the exact problem is here. All JUnit tests need to be visible and instantiable to be picked up by the JUnit framework and its various runners. This also applies to test suites and the individual tests that are part of a test suite. As a consequence, if JUnit picks up the test suite it will also pick up the individual tests, and all tests in the suite will be executed twice, once individually and once as part of the suite.
So, the trick, if you will, is to prevent JUnit from picking up the individual tests while still being able to instantiate and execute them as part of the suite.
One thing that comes to mind is to make the test classes static inner classes nested inside the test suite. However, the nested classes still need to be public (otherwise they can't be run in the suite either), and if they are public classes they will also be picked up individually, despite being nested inside the suite's public class. JUnit will not try to run test classes that are not considered visible, though. So, nesting the test classes inside a non-public class would presumably be sufficient to hide them, but we can't make the suite class non-public because then JUnit would not execute it. What we can do, however, is to nest the individual tests inside another non-public class that's nested inside the test suite, which leads us to the solution of this conundrum:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({AllTests.InSuiteOnly.Test1.class, AllTests.InSuiteOnly.Test2.class})
public class AllTests
{
    static class InSuiteOnly
    {
        public static class Test1
        {
            @Test
            public void test1()
            {
                //...
            }
        }

        public static class Test2
        {
            @Test
            public void test2()
            {
                //...
            }
        }
    }
}

A lot of folks will probably object to all tests needing to be inside a single source file now. What if I want to maintain separate JUnit test classes that don't get executed by themselves but still get executed inside the test suite? A simple solution is to make the individual test classes abstract (public/non-public doesn't matter) so that JUnit won't execute them, and inside the test suite we simply use concrete subclasses of the original abstract test classes:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({AllTests.InSuiteOnly.SuiteTest1.class, AllTests.InSuiteOnly.SuiteTest2.class})
public class AllTests
{
    static class InSuiteOnly
    {
        public static class SuiteTest1 extends Test1 {}
        public static class SuiteTest2 extends Test2 {}
    }
}

abstract class Test1
{
    @Test
    public void test1()
    {
        //...
    }
}

abstract class Test2
{
    @Test
    public void test2()
    {
        //...
    }
}

This scheme works with Maven, Eclipse, and all other environments that either directly leverage JUnit's runners or implement their own runners that closely follow JUnit's original behavior and semantics.

A: I have an idea for you. Actually you do not want to run these test case as stand-alone test cases. You can do the following.
Mark the test cases with annotation @RunWith(DoNothingRunner.class)
Implment DoNothingRunner as following:
public class DoNothingRunner extends Runner {
    public Description getDescription() {
              return "do nothing";
        }
    public void run(RunNotifier notifier) {
            // indeed do nothing
        }
}

I have not tried this personally but I hope this will work.

A: do you need the suite in the first place ? depending on when you click for run all (class, package, or src/test/java), all underlying tests will be executed. So what's the point of having a suite ?

A: There is a solution, it's a bit tricky, but it may easily resolve your problem: create one suite class, and include all your suite classes in it. Then you can use this suite class to run all your tests.
@RunWith(Suite.class)
@Suite.SuiteClasses({
    AXXSuite.class,
    BXXSuite.class,
    CXXSuite.class
})
public class AllSuites {

}


text:
Q: "Range Based for loops not allowed in C++98 mode" Error in Visual Studio Code I m trying to learn vectors and happened to come across this code, I tried building it in Visual Studio Code but unfortunately, it doesn't work.
This was the error message as shown in the problem tab

This was the error message as shown in the Terminal after Building

I googled the error message, but I couldn't seem to find anything that would have solved this problem in VS Code.
I am aware that the for loop can be written in the basic simpler form but is there anyway to make this format work?
#include <iostream>
#include <string>
#include <vector>
int main() {
    std::vector <int> vecOfInts(5);
    for (int x: vecOfInts)
    {
        std::cout << x << std::endl;
    }
}


text:
Q: Maximal optimization for cosine similarity search I have pre-made database full of 512 dimensional vectors and want to implement an efficient searching algorithm over them.

Research
Cosine similarity:
The best algorithm in this case would consist of cosine similarity measure, which is basically a normalized dot product, which is:
def cossim(a, b): numpy.inner(a, b)/(numpy.linalg.norm(a)*numpy.linalg.norm(b))

In Python.
Linear search:
Most obvious and simple search for this case would be linear search O(n), which iterates the whole database and eventually picks the most similar result:
def linear_search(query_text, db):  # where db is set of 512D vectors
    most_similar = ("", 0)  # placeholder
    for query in db:
        current_sim = cossim(query_text, query)  # cossim function defined above
        if current_sim > most_similar[1]:
            most_similar = (query, current_sim)
    return most_similar[0]

As you can see, the whole database should be scanned, which might be quite inefficient if database contains hundreds of thousands of vectors.
Quasilinear search: (partially resolved)
There is a fundamental relation between Cosine similarity and Euclidean distance (explained very well in this answer) - we can derive Euclidean distance from following equation:
|a - b|² = 2(1 - cossim(a,b))

As mentioned in the answer, Euclidean distance will get smaller as cosine between two vectors get larger, therefore we can turn this into the closest pairs of points problem, which can be solved in quasilinear O(n log n) time using recursive divide and conquer algorithm.
Thus I have to implement my own divide and conquer algorithm that will find closest pair of 512 dimensional vectors.
But unfortunately, this problem can't be directly solved due to high dimensionality of vectors. Classical divide and conquer algorithm is only specialized for two dimensions.
Indexing for binary search (unresolved):
The best way to optimize cosine similarity search in terms of speed from my knowledge would be indexing and then performing binary search.
The main problem here is that indexing 512 dimensional vectors is quite difficult, and I'm not yet aware of anything other than locality sensitive hashing that may, or may not be useful for indexing my database (main concern is dimensionality reduction, which might possibly cause consequential decrease in accuracy).
There is a new Angular Multi-index Hashing method, which unfortunately only works for binary based vectors and dimension independent similarity computation if vectors are sparse, but they are not.
Finally, there also is An Optimal Algorithm for Approximate Nearest
Neighbor Searching in Fixed Dimensions, which at first glance might perhaps be the best solution, but in the document it is stated:

Unfortunately, exponential factors in query time do imply that our
  algorithm is not practical for large values of d. However, our
  empirical evidence in Section 6 shows that the constant factors are
  much smaller than the bound given in Theorem 1 for the many
  distributions that we have tested. Our algorithm can provide
  significant improvements over brute-force search in dimensions as high
  as 20, with a relatively small average error.

We are trying to perform query over 20 * 25.6 = 512 dimensional vectors, which will make the algorithm above highly inefficient.
There was a similar question that contains similar concerns, but unfortunately the solution for indexing was yet not found.

Problem
Is there any way to optimize cosine similarity search for such vectors other than quasilinear search? Perhaps there is some other way of indexing high-dimensional vectors? I believe something like this has already been done before.
Closest solution
I believe I have found solution that might potentially be a solution, it includes randomized partition trees for indexing couple hundred dimensional vector databases, which I believe is what I exactly need. (see here)
Thank you!


text:
Q: How should the electric field produced by an electron look like if electron is described by a wave function? In quantum mechanics, the position of an object is not definitely known, but instead is described by a probability density function of where it would be located.
Then what should the electric field produced by an electron look like if its position is described a probability density? Is the electric field described by a probability density function as well?

A: In nonrelativistic QM the charge density is $\rho = e|\psi|^2 $. From this you find V and E using Coulomb's law.

A: In quantum mechanics, the field act as an operator acting on a state of electron.
The electrons state is described by some mathematical object (vector in some hilbert space) that encodes all the information of the electron we have (its state). There is also procedure how to get from this abstract mathematical object the physically meaningful information. For example, if you project the state of your electron on a vector that describes state of definite position you get amplitude that tells you how probable is finding the electron in that position.
Now, what should the field do to a state of some electron? Well, change it. So the field will be some operator that maps electron state to another.
In quantum mechanics the evolution of system is described by operator called Hamiltonian. This Hamiltonian operator can be vied in some sense as energy. You can look into Hamiltonian formulation of classical mechanics to gain deeper insight of connection between time evolution and energy, without the complications of QM. Anyway, the point is, that Hamiltonian is closely related to energy and it is operator that governs time evolution.
Now, the electric energy of electron in classical mechanics is given by the potential that is function of position of this electron. Specifically, the classical energy of system of two electrons is:
$$E=\frac{p_1^2}{2m_1}+\frac{p_2^2}{2m_2}+2k\frac{e^2}{\left(r_1-r_2\right)^2}$$
It turns out that in QM the Hamiltonian of the same system will have exactly this form. But now, ps and rs are not numbers, but operators that are changing the state of electron. In particular, the ps act as derivatives on wave function (in position space) and rs act as numbers you multiply the wave function (in position space) by.
Why the ps and rs are "derivatives/multiplier" operators can be answered elsewhere (or found elsewhere), the main point of my answer is that the electric field in QM is operator that maps some state of the system to another and curiously enaugh, this operator has the same form as formula for energy in classical physics.


text:
Q: Read JSON file from Azure Blob Storage using PowerShell script and write back to another file in blob storage I have following JSON file (product.json) stored in Azure Blob storage. Is it possible to write PowerShell script to read this file from blob storage make some changes and write back to another file.
The output file I would like where following changes should occur:

*

*Replace all "_id" with "id"

*Remove all "_rev" and their values.

Product.json
[
  {
    "_id": "9f4da9d6babeb9d411c896baa68c94c8",
    "_rev": "1-4259271795225df18768ab68baacc96c",
    "account_id": 692278,
    "limit": 10000,
    "products": [
      "Commodity",
      "InvestmentStock"
    ]
  },
  {
    "_id": "cc4b59f585b8556a2bedca78294a0797",
    "_rev": "1-410e479257faba0457bd9b4816c4dc95",
    "account_id": 328304,
    "limit": 10000,
    "products": [
      "Derivatives",
      "InvestmentStock",
      "CurrencyService"
    ]
  },
  {
    "_id": "d7e2a72963cff2760514ff772969ffe0",
    "_rev": "1-2ec6e2679eae13b76410c93f49c14c4a",
    "account_id": 674364,
    "limit": 10000,
    "products": [
      "InvestmentStock"
    ]
  }
]

The outputfile.json should be as follows:
[
  {
    "id": "9f4da9d6babeb9d411c896baa68c94c8",
    "account_id": 692278,
    "limit": 10000,
    "products": [
      "Commodity",
      "InvestmentStock"
    ]
  },
  {
    "id": "cc4b59f585b8556a2bedca78294a0797",
    "account_id": 328304,
    "limit": 10000,
    "products": [
      "Derivatives",
      "InvestmentStock",
      "CurrencyService"
    ]
  },
  {
    "id": "d7e2a72963cff2760514ff772969ffe0",
    "account_id": 674364,
    "limit": 10000,
    "products": [
      "InvestmentStock"
    ]
  }
]

A: If you want to store the file in memory, you can use the DownloadText() method to download the content into memory.
The sample code:
$accountName = "xxx"
$accountKey = "xxx"
$containerName = "xxx"
$blobName = "Product.json"
$outputBlobName = "Output.json"

$context = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey
$container_client = Get-AzStorageContainer -Name $containerName -Context $context
$source_blob_client = $container_client.CloudBlobContainer.GetBlockBlobReference($blobName)

#download the blob as text into memory
$download_file = $source_blob_client.DownloadText()

$jsonContent = $download_file | ConvertFrom-Json

#Loop through json content and manipulate it
For ($i=0; $i -lt $jsonContent.Length; $i++) {
    $jsonContent[$i] | Add-Member -NotePropertyName "id" -NotePropertyValue $jsonContent[$i]._id
    $jsonContent[$i].PsObject.Properties.Remove("_id")
    $jsonContent[$i].PsObject.Properties.Remove("_rev")
}

$replaced_json = $jsonContent | ConvertTo-Json

#upload the json file
$dest_blob_client =  $container_client.CloudBlobContainer.GetBlockBlobReference($outputBlobName)
$dest_blob_client.Properties.ContentType = "application/json"
$dest_blob_client.UploadText($replaced_json)

Write-Output("**completed**")

A: Not the most elegant way, but this should do the trick:
$accountName = "account-name"
$accountKey = "account-key"
$containerName = "container-name"
$blobName = "Product.json"
$outputBlobName = "Output.json"

$ctx = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey

#Read blob and save it to local file
Get-AzStorageBlobContent -Blob $blobName -Container $containerName -Destination "Product.json" -Context $ctx

#Read local file and get JSON object
$jsonContent = Get-Content -Raw -Path "Product.json" | ConvertFrom-Json

#Loop through json content and manipulate it
For ($i=0; $i -lt $jsonContent.Length; $i++) {
    $jsonContent[$i] | Add-Member -NotePropertyName "id" -NotePropertyValue $jsonContent[$i]._id
    $jsonContent[$i].PsObject.Properties.Remove("_id")
    $jsonContent[$i].PsObject.Properties.Remove("_rev")
}
$jsonContent

#Write content back to local disk
$jsonContent | ConvertTo-Json | Set-Content -Path $outputBlobName

#Upload into Azure Storage
$properties = @{"ContentType" = "application/json"}
Set-AzStorageBlobContent -File $outputBlobName -Container $containerName -Blob $outputBlobName -Properties $properties -Context $ctx


text:
Q: (xlib) how "mywm" can catches a window opened before itself? I have in my ".xinitrc" :
xterm &
mywm

in mywm I use XQueryTree to get the list of all windows children of root. I don't get the window of xterm. I need to do that to add my titlebar to windows opened before the wm.
My question is, how mywm can detect this window ?
actually, XQueryTree can detect the window, but I have to add a sleep of few seconds before calling XQueryTree.
it's tricky, there is a better way than just forced mywm to sleep a while ?
struct Client{
        Window                  frame/*frame*/;
        Client                 *next; // next client
        Client                 *previous; // previous client

};

void addClient(...){
        Client *client;
        client = (Client *)malloc(sizeof(Client));
        memset(c, 0, sizeof(Client));
         .
         .
         .
        client->next = head.next;
        if(head.next != NULL) head.next = client;
        client->previous = &head;
        head.next = client;
}

int main(int argc, char *argv[]){
  .
  .
  .
  while(continue) {
    .
    .
    .
    while(XPending(display)==0){ // as long as I don't get an event
      .
      .
      .
      XQueryTree(display,rootwin,&qr,&qp,&qc,&nc); // we got the list of the windows
      .                                            // children of root
      . -> call addclient()
      .
    }
    .
    .
    .
    XNextEvent(display, &e);
    switch(e.type){
      .
      .
      .
    }
  }
  .
  .
  .
 return 0;
}


text:
Q: Saving int with sharedPreferenses when click on back i'm (trying) to create a soccer goals calculator, with two activities, MainActivity and Score, but i'd like to save int value that represent goals when clicking on back button, that what i tried:
public class Score extends Activity {
public Button plus;
public Button minus;
public TextView scoretext;
public int value;
public static final String mypreference = "mypref";
SharedPreferences sharedpreferences;
public void save(View v){
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("inte", value); // Storing integer
    editor.apply(); // commit changes
}
public void restore(View v){
    this.sharedpreferences = this.getSharedPreferences("myPerf",
            Context.MODE_PRIVATE);

    if (this.sharedpreferences.contains("inte")) {
        okeh.setText(this.sharedpreferences.getInt("inte",value));
    }

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_score);
    plus = this.findViewById(R.id.plus);
    scoretext=this.findViewById(R.id.scoretext);
    minus=this.findViewById(R.id.minus);

    plus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            value++;
            String scorestring=String.valueOf(value);
            scoretext.setText(scorestring);
        }
    });
    minus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            value--;
            String scorestring=String.valueOf(value);
            scoretext.setText(scorestring);
        }
    });
    sharedpreferences = this.getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);
    if (sharedpreferences.contains("inte")) {
        okeh.setText(sharedpreferences.getInt("inte", value));
    }
}
}

A: You have to Override the onBackPressed method in your Score activity and save the int score in the shared preferences.
When you press the device back button the onBackPressed method will be called automatically and your latest Score will be saved in the shared preferences.
@Override
public void onBackPressed() {
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("inte", value); // Storing integer
    editor.apply(); // commit changes

    super.onBackPressed();
}

A: Your save and restore methods have a parameter View v and i'm not sure why.
Change it to an integer
public void save(int value){
    sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE); // 0 - for private mode
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("inte", value); // Storing integer
    editor.apply(); // commit changes
}

public int restore(){
    sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE);
    if (this.sharedPreferences.contains("inte")) {
        okeh.setText(this.sharedPreferences.getInt("inte",value));
    }
    return sharedPreferences.getInt("inte", 0); //return 0 if no data found
}

Alt + Insert and select override method
@Override
public void onBackPressed() {
    super.onBackPressed();
    // Put your sharedpreferences here that saves the int.
    save(value);
}

And now you can call your save method on places where you want to save the int value.
EDIT
plus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            value++;
            String scorestring=String.valueOf(value);
            scoretext.setText(scorestring);
            save(value);
        }
    });
    minus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            value--;
            String scorestring=String.valueOf(value);
            scoretext.setText(scorestring);
            save(value);
        }
    });


text:
Q: Combining jQuery ui datepicker and isotope data-filters I'm currently working with a jQuery ui datepicker and I'm trying to figure out if it is at all possible to combine the calendar with the isotope plugin, more specifically the data-filter, i.e. selecting a date from the datepicker and filtering out the relevant events (on that date).
Here's some of my html:

1

3

2

2

3

1

3

2

1

Also a working demo on jsfiddle here too
So is it at all possible to filter out the numbered blocks using the datepicker?
Any help would be greatly appreciated!

A: I did look at this again.
You can use the datepicker's onSelect() method and attach this:
onSelect: function (dateText, inst) {
  var date = $(this).datepicker('getDate');
  //var dayValue = date.getDate(); // or
   var dayValue = inst.selectedDay;

  $blocks.show();

  $blocks.filter(function () {
    if (this.innerHTML != dayValue) {
      $(this).hide();
    }
  });
}

You can use the first function parameter which holds a string version of the date you clicked or you can use the second parameter which is an instance of the datepicker object with useful properties values for the date elements.

DEMO 01 - Only show boxes matching the number clicked in calendar

I had a play around and the filter option of the isotop must be a selector. As far as I know you cannot generate a jQuery selector interrogation the value or innerHTML.
However, you can add a custom attribute to each block containing the same value, similar to this:

1

3

2

Now, you can generate a valid selector for the filter in the OnSelect method of the datepicker, like this:
onSelect: function (dateText, inst) {
  var date = $(this).datepicker('getDate');
  var dayValue = inst.selectedDay;

  $container.isotope({
    filter: '[data-value="' + dayValue + '"]'
  });
}

DEMO 02 - Using data attributes to connect datepicker to isotope filter

Code from the DEMOs in case of link-rot:

DEMO-01: HTML

1

3

2

2

DEMO-01: Script
var $blocks = $("div.blocks", "#block-wrap");

$(function () {
  $('#datepicker').datepicker({
    inline: true,
    //nextText: '→',
    //prevText: '←',
    showOtherMonths: true,
    //dateFormat: 'dd MM yy',
    dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
    //showOn: "button",
    //buttonImage: "img/calendar-blue.png",
    //buttonImageOnly: true,
    onSelect: function (dateText, inst) {
      var date = $(this).datepicker('getDate');
      var dayValue = date.getDate();

      $blocks.show();

      $blocks.filter(function () {
        if (this.innerHTML != dayValue) {
          $(this).hide();
        }
      });
    }
  });
});

var $container = $('#block-wrap');

$container.imagesLoaded(function () {
  $container.isotope({
    itemSelector: '.blocks',
    animationEngine: 'css',
    masonry: {
      columnWidth: 5
    }

  });
});

DEMO-02: HTML

1

3

2

2

1

DEMO 02 - Script (only onSelect changed when compared to DEMO 01 script)
onSelect: function (dateText, inst) {
  var date = $(this).datepicker('getDate');
  var dayValue = inst.selectedDay;
  $container.isotope({
    filter: '[data-value="' + dayValue + '"]'
  });
}

CSS same for both DEMOs
#datepicker {
  position: absolute;
  left: 5px;
  top: 5px;
  z-index: 9999;
}
#block-wrap {
  position: absolute;
  padding-left: 230px;
  top: 10px;
  width: auto;
}
.blocks {
  position: relative;
  width: 40px;
  height: 40px;
  background-color: silver;
  float: left;
  margin-right: 5px;
  margin-bottom: 5px;
}
.isotope-item {
  z-index: 2;
}
.isotope-hidden.isotope-item {
  z-index: 1;
}
.isotope, .isotope .isotope-item {
  /* change duration value to whatever you like */
  -webkit-transition-duration: 0.5s;
  -moz-transition-duration: 0.5s;
  -ms-transition-duration: 0.5s;
  -o-transition-duration: 0.5s;
  transition-duration: 0.5s;
}
.isotope {
  -webkit-transition-property: height, width;
  -moz-transition-property: height, width;
  -ms-transition-property: height, width;
  -o-transition-property: height, width;
  transition-property: height, width;
}
.isotope .isotope-item {
  -webkit-transition-property: -webkit-transform, opacity;
  -moz-transition-property: -moz-transform, opacity;
  -ms-transition-property: -ms-transform, opacity;
  -o-transition-property: -o-transform, opacity;
  transition-property: transform, opacity;
}
/**** disabling Isotope CSS3 transitions ****/
 .isotope.no-transition, .isotope.no-transition .isotope-item, .isotope .isotope-item.no-transition {
  -webkit-transition-duration: 0s;
  -moz-transition-duration: 0s;
  -ms-transition-duration: 0s;
  -o-transition-duration: 0s;
  transition-duration: 0s;
}


text:
Q: javascript nodejs promise all gets executed later I have multiple promises like this:
module.exports = function (a, b, c) {
    return someAsync(() => {
            someFunc(a);
        })
        .then(() => myPromises(a, b, c))
        .then(result => {
            console.log('log the result: ', JSON.stringify(result)); // empty
        })
};

const myPromises = function myPromises(a, b, c){
    Promise.all([
        somePromise(a),
        someOtherPromise(b)
    ]).then(function (data) {
        Promise.all([
            anotherPromise(data[0]),
            yetanotherPromise(data[1])
        ]).then(function (finalResult) {
            console.log('check out finalResult: ', JSON.stringify(finalResult)); // i see the expected results here
            return finalResult;
        }).catch(err => { return err });
    }).catch(err => { return err });
};

why is the console.log('log the result: ', JSON.stringify(result)); returning empty? in other words, why is this line getting executed before the promise.all is finished?
how can I make it to wait for promise all and then execute?

A: Not sure which promise you want to return, but the general idea would be to return the Promise.all there, instead of just calling Promise.all.
const myPromises = function myPromises(a, b, c){
  return Promise.all([

A: The problem is your second promise.all isn't returning anything for it to pass to the main Promise.all
Try this edited piece of code
module.exports = function (a, b, c) {
    return someAsync(() => {
            someFunc(a);
        })
        .then(() => myPromises(a, b, c))
        .then(result => {
            console.log('log the result: ', JSON.stringify(result)); // empty
        })
};

const myPromises = function myPromises(a, b, c){
    return Promise.all([ //missing return
        somePromise(a),
        someOtherPromise(b)
    ]).then(function (data) { //data from first promise all
        return Promise.all([ //missing return: passes data to next then
            anotherPromise(data[0]),
            yetanotherPromise(data[1])
        ])
     })
     .then(function (finalResult) { //data from second promise all
            console.log('check out finalResult:',JSON.stringify(finalResult)); // i see the expected results here
            return finalResult; //passes data to next then or top level return whichever available
    })
    .catch(err => { return err }); // top level catch works for the entire chain
};

The reason for your code not working is that promise chain is single flow, you didn't return anything from second promise for it to pass it to the outer promise.all chain


text:
Q: How to default to "Append New Result" in Workbench/J? Each time I open a new tab in Workbench/J the default setting is to not append new results in the results bar. I earned my stripes in Microsoft SQL Server so I'm used to this being default behavior and consistently forget to enable it each time I open a new tab - which becomes painful when I am running long queries.
Anyway to make this the DEFAULT behavior?

A: As documented in the manual:
Tools -> Options -> Data display -> Append results:


text:
Q: Changing the default values of the boolean data type in SSRS report parameter Is there any way to change the default values of the boolean data type in SSRS report parameters to other values like "YES" and "NO" or "Male" and "Female"?
Kindly note that I want to use only the radio buttons not the dropdown list.
Please help me.

A: Not from within SSRS.  The Boolean parameter type will either show True / False or be converted to a DropDown if you enter your own values.
A workaround would be to wrap the report inside another package (like C#) and use this package to create custom parameters such as your Male / Female radio buttons.  Pass the paramters to the report via code when you want to preview.  This path would be relatively costly, in terms of effort, but would enable you full control over the UI.