text:
Q: When do two lattices have the same stabilizer in the diagonal torus? This is moved from MSE, where I asked and didn't receive an answer (see https://math.stackexchange.com/questions/1145151/lattices-in-mathbbq-pn-with-the-same-stabilizer)
Let $T$ be the diagonal torus in $G = GL_n(\mathbb{Q}_p)$, and consider the action of $G$ on the set of (full-rank) lattices $\Lambda\subset \mathbb{Q}_p^n$.  Let $\Lambda$ and $\Lambda'$ be full-rank sublattices ($\mathbb{Z}_p$-submodules of rank $n$) such $Stab_T(\Lambda) = Stab_T(\Lambda')$.  Is it true that $\Lambda' = t\cdot \Lambda$ for some $t\in T$?
This is true when $n = 2$ and $p > 2$; to see this, if $\{e_1,\, e_2\}$ is the standard basis and $\Lambda$ any lattice, we can always take a basis of the form
$$\{p^re_1,\, \alpha e_1 + p^s e_2\}$$
where $r,\, s\in \mathbb{Z}$ and $\alpha$ is chosen modulo $p^s$; at this point you can check directly that $\Lambda$ and $\Lambda'$ have the same stabilizer if and only if $v_p(\alpha) - r = v_p(\alpha') - r'$, and any two such lattices are in the same $T$-orbit.
If this is known, I'd love a reference.
EDITED: When $p = 2$, this is false, even when $n = 2$, in view of JWitte's example below.  I'm still interested in the case where $p > 2$.

A: First a counter example:
Look at the case $\mathbb{Q}_2$ and $n=2$:
Take $\Lambda = \langle e_1,e_2\rangle$ and $\Lambda'= \langle pe_1, e_1+e_2\rangle$. Let $t_{\alpha,\beta}$ be the diagonal matrix with $\alpha$ and $\beta$ on the diagonal: $t_{\alpha,\beta}e_1 = \alpha e_1$ and $t_{\alpha,\beta}e_2 = \beta e_2$.
The stabilizer of $\Lambda$ in $T$ is $\{ t_{\alpha,\beta} : v(\alpha)=v(\beta)=0\}$.
Now we show that this is also the stabilizer of $\Lambda'$:
Assume that $v(\alpha)=v(\beta)=0$, then $\alpha\beta^{-1} = 1 + \gamma p$ with $v(\gamma)\geq 0$ (p=2!). Now $t_{\alpha,\beta}\Lambda' = \langle p\alpha e_1, \alpha e_1+\beta e_2\rangle = \langle pe_1, \alpha\beta^{-1} e_1+e_2\rangle = \langle pe_1, \gamma p e_1+e_1+e_2\rangle=\langle pe_1,e_1+e_2\rangle=\Lambda'$.
Let $\pi_i$ be the projection to $e_i$ for $i\in\{1,2\}$. Then $\pi_i(\Lambda') = \mathbb{Z}_p e_i$. Now $\pi_1(t_{\alpha,\beta} \Lambda') = \alpha\mathbb{Z}_p$ and $\pi_2(t_{\alpha,\beta}\Lambda') = \beta\mathbb{Z}_p$. Therefore if $t_{\alpha,\beta}$ fixes $\Lambda'$, then $v(\alpha)=v(\beta)=0$.
Moreover if $t_{\alpha,\beta}\Lambda' =\Lambda$, then $\pi_i(t_{\alpha,\beta}\Lambda') = \pi_i(\Lambda) = \mathbb{Z}_p e_i$. Thus $v(\alpha)=v(\beta)=0$ by the preceding calculations. But then $t_{\alpha,\beta}$ is in the stabilizer of $\Lambda$. Thus $\Lambda$ and $\Lambda'$ are not in the same $T$ orbit.
A general comment:
If you know something about buildings, you could see that this example is based on 3.6.1 of Reductive groups over local fields, J. Tits. The stabilizer of a point in the apartment of $T$ is the set of diagonal matrices with units. And 3.6.1 states that if the residual characteristic is 2 this stabilizer fixes also points in the building that are not in the apartment of $T$. Because $T$ acts on its own apartment the points outside the apartment of $T$ are not in the same orbit as a point in the apartment. So the answer to your question is negative for all $n$ in the case $p=2$. However for odd $p$ I don't know the answer.


text:
Q: How to provide Angular LOCALE_ID with fall back to the build configuration locale? This should be easy but I'm just not finding it. I think the more general question is how to conditionally override an existing provider.
I want to create a LOCALE_ID provider in my app module that can provide an overridden locale I allowed the user to set somewhere - could get it from any of several places, saved in local browser storage, loaded from a user profile by an APP_INITIALIZER, whatever. That part itself is easy, but here's what I'm missing - if I find no value, wherever I'm looking for it, I just want to default to the locale specified by the build configuration. So in other words, I want to fall back to whatever LOCALE_ID would have been provided by Angular if I hadn't created my own provider. And I don't want to use a different injection token instead of LOCALE_ID, that would require that any code needing to inject LOCALE_ID would need to know about the new custom token, and hacks to get the locale-aware pipes use the new token, etc.
Anything I try that looks for the existing LOCALE_ID injector value causes a circular DI dependency error to be thrown, which makes sense. This is what I want:
...
    {
      provide: LOCALE_ID,
      useFactory: () => {
        const overrideLocaleId = getMyOverrideLocalIdFromSomewhere();
        if (overrideLocalId) {
          return overrideLocaleId;
        } else {
          // Return the locale specified in the build configuration, which would have
          // otherwise been provided by LOCALE_ID.
        }
      }
    },
...

A: As I'm writing this question, I found what I consider a hack that seems to work, but is there a better way? This works, basically uses a static function that could get the value from someplace like a cookie or browser storage, which could have been poked into there by an app initializer if I needed something loaded from the backend. And if I find a value there, I create the provider for the LOCALE_ID token, otherwise I create it for some arbitrary token I'll never try to inject anywhere.
...

const DONT_PROVIDE_LOCALE_ID = new InjectionToken<string>('NeverMind');

function getCookie(name: string): string {
  // My getCookie implementation.
}

...

    {
      provide: getCookie('lang') ? LOCALE_ID : DONT_PROVIDE_LOCALE_ID,
      useValue: getCookie('lang') || 'en'
    },

...

redpajama_set_name: RedPajamaStackExchange


text:
Q: send Kotlin suspend method as parameter This is my function in retrofit interface
@POST("/api/Auth/login")
suspend fun patientLogin(@Body loginReq: LoginRequest): Response<BaseResponse<User>>

I need to send this patientLogin(data) methods as a parameter into another method which should be a generic method which will call this method in a IO scope and will return the response with a listener (Interface). The only issue is that I am not sure how to send this method itself as a parameter. Thankyou

A: // One cannot return caculcated value from a coroutine, only the job
fun <T, R> CoroutineScope.functionName(block: suspend (T) -> R): Job = launch(Dispatchers.IO) {
    block() //provide T either as another parameter to this function or if this function belongs to a class you take it from a class' state
}

// One can return a deferred value and wait for the actual R value to be calculated
fun <T, R> CoroutineScope.functionName(block: suspend (T) -> R): Deferred<R> = async(Dispatchers.IO) {
    block()
}

// Will execute on the inherited dispatcher from the coroutine that executes this function
suspend fun <T, R> functionName(block: suspend (T) -> R): R = coroutineScope {
    block()
}

// Always executes on the IO dispatcher
suspend fun <T, R> functionName(block: suspend (T) -> R): R = withContext(Dispatchers.IO) {
    block()
}

A: So finally I was able to do what I wanted and I just though that I should also post the answer, that may be helpful to others. Thank you for all the contributors who answered to my question.
fun <T : Any> callBaseApi(call: suspend () -> Response<BaseResponse<T>>, apiCallback: ApiCallback<T>) {
    CoroutineScope(Dispatchers.IO).launch {
       try {
           val response = call.invoke()

           withContext(Dispatchers.Main) {
               if (response.isSuccessful) {
                   apiCallback.onSuccess(
                       response.body()?.data,
                       response.body()?.message,
                       response.body()?.status!!
                   )
               } else {
                   apiCallback.onFailure(response.message(), response.code())
                   Log.e("makeApiCall: ", response.errorBody().toString())
               }
           }
       }catch (e:Exception){
           withContext(Dispatchers.Main) {
               apiCallback.onFailure(e.message, -1)
           }
       }
    }
}

and to call this method
callBaseApi({WebServicesHandler.getWebServices(CacheManager.getCurrentUser()!!.token!!)
            .editPatientPersonalInfo(data)}, apiCallback)

A: I just had the same issue, and your 'suspend' in the parameter definition helped me.
May someone find some clarity with this example:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class Worker {

    fun doWork() {
        println("Start work")
        Thread.sleep(1000)
        println("End work")
    }

    suspend fun doWorkSuspend() = withContext(Dispatchers.Default) {
        println("Start work suspended")
        Thread.sleep(1000)
        println("End work suspended")
    }

}

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

class Controller {
    private val scope = CoroutineScope(Dispatchers.Default)
    private val startedJobs = mutableListOf<Job>()

    fun launchWork(perform: () -> Unit) {
        perform()
    }

    fun launchWorkSuspended(perform: suspend() -> Unit) {
        val job = scope.launch {
            perform()
        }
        startedJobs.add(job)
    }

}

fun main(args: Array<String>) {

    val controller = Controller()
    val worker = Worker()

    controller.launchWork { worker.doWork() } // fine
    controller.launchWorkSuspended { worker.doWork() } // fine
    controller.launchWorkSuspended { worker.doWorkSuspend() } // fine

}


text:
Q: switch between 2 classes on each click I am trying to work out how to change between this:

and this:

on each click of the menu.  Basically so the menu opens on each click if closed and closes on each click if open
Code Snippet:

          Menu Heading

Option 1

Option 2

Option 3

Option 4

I have read a few posts about toggleClass but cannot seem to get it working.  If someone could break it down simply for me it would be greatly appreciated!
Here is a clipping from the CSS:
.topbar div > ul a.menu:hover,
.nav a.menu:hover,
.topbar div > ul li.open .menu,
.nav li.open .menu,
.topbar div > ul .dropdown-toggle:hover,
.nav .dropdown-toggle:hover,
.topbar div > ul .dropdown.open .dropdown-toggle,
.nav .dropdown.open .dropdown-toggle {
  background: #444;
  background: rgba(255, 255, 255, 0.05);
}
.topbar div > ul .menu-dropdown,
.nav .menu-dropdown,
.topbar div > ul .dropdown-menu,
.nav .dropdown-menu {
  background-color: #333;
}
.topbar div > ul .menu-dropdown a.menu,
.nav .menu-dropdown a.menu,
.topbar div > ul .dropdown-menu a.menu,
.nav .dropdown-menu a.menu,
.topbar div > ul .menu-dropdown .dropdown-toggle,
.nav .menu-dropdown .dropdown-toggle,
.topbar div > ul .dropdown-menu .dropdown-toggle,
.nav .dropdown-menu .dropdown-toggle {
  color: #ffffff;
}
.topbar div > ul .menu-dropdown a.menu.open,
.nav .menu-dropdown a.menu.open,
.topbar div > ul .dropdown-menu a.menu.open,
.nav .dropdown-menu a.menu.open,
.topbar div > ul .menu-dropdown .dropdown-toggle.open,
.nav .menu-dropdown .dropdown-toggle.open,
.topbar div > ul .dropdown-menu .dropdown-toggle.open,
.nav .dropdown-menu .dropdown-toggle.open {
  background: #444;
  background: rgba(255, 255, 255, 0.05);
}
.topbar div > ul .menu-dropdown li a,
.nav .menu-dropdown li a,
.topbar div > ul .dropdown-menu li a,
.nav .dropdown-menu li a {
  color: #999;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.5);
}
.topbar div > ul .menu-dropdown li a:hover,
.nav .menu-dropdown li a:hover,
.topbar div > ul .dropdown-menu li a:hover,
.nav .dropdown-menu li a:hover {
  background-color: #191919;
  background-repeat: repeat-x;
  background-image: -khtml-gradient(linear, left top, left bottom, from(#292929),     to(#191919));
  background-image: -moz-linear-gradient(top, #292929, #191919);
  background-image: -ms-linear-gradient(top, #292929, #191919);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #292929), color-stop(100%, #191919));
  background-image: -webkit-linear-gradient(top, #292929, #191919);
  background-image: -o-linear-gradient(top, #292929, #191919);
  background-image: linear-gradient(top, #292929, #191919);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#292929', endColorstr='#191919', GradientType=0);
  color: #ffffff;
}
.topbar div > ul .menu-dropdown .active a,
.nav .menu-dropdown .active a,
.topbar div > ul .dropdown-menu .active a,
.nav .dropdown-menu .active a {
  color: #ffffff;
}
.topbar div > ul .menu-dropdown .divider,
.nav .menu-dropdown .divider,
.topbar div > ul .dropdown-menu .divider,
.nav .dropdown-menu .divider {
  background-color: #222;
  border-color: #444;
}
.topbar ul .menu-dropdown li a, .topbar ul .dropdown-menu li a {
  padding: 4px 15px;
}
li.menu, .dropdown {
  position: relative;
}
a.menu:after, .dropdown-toggle:after {
  width: 0;
  height: 0;
  display: inline-block;
  content: "↓";
  text-indent: -99999px;
  vertical-align: top;
  margin-top: 8px;
  margin-left: 4px;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 4px solid #ffffff;
  filter: alpha(opacity=50);
  -khtml-opacity: 0.5;
  -moz-opacity: 0.5;
  opacity: 0.5;
}
.menu-dropdown, .dropdown-menu {
  background-color: #ffffff;
  float: left;
  display: none;
  position: absolute;
  top: 40px;
  z-index: 900;
  min-width: 160px;
  max-width: 220px;
  width: 160px;
  margin-left: 0;
  margin-right: 0;
  padding: 6px 0;
  zoom: 1;
  border-color: #999;
  border-color: rgba(0, 0, 0, 0.2);
  border-style: solid;
  border-width: 0 1px 1px;
  -webkit-border-radius: 0 0 6px 6px;
  -moz-border-radius: 0 0 6px 6px;
  border-radius: 0 0 6px 6px;
  -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  -webkit-background-clip: padding-box;
  -moz-background-clip: padding-box;
  background-clip: padding-box;
}
.menu-dropdown li, .dropdown-menu li {
  float: none;
  display: block;
  background-color: none;
}
.menu-dropdown .divider, .dropdown-menu .divider {
  height: 1px;
  margin: 5px 0;
  overflow: hidden;
  background-color: #eee;
  border-bottom: 1px solid #ffffff;
}
.topbar .dropdown-menu a, .dropdown-menu a {
  display: block;
  padding: 4px 15px;
  clear: both;
  font-weight: normal;
  line-height: 18px;
  color: #808080;
  text-shadow: 0 1px 0 #ffffff;
}
.topbar .dropdown-menu a:hover,
.dropdown-menu a:hover,
.topbar .dropdown-menu a.hover,
.dropdown-menu a.hover {
  background-color: #dddddd;
  background-repeat: repeat-x;
  background-image: -khtml-gradient(linear, left top, left bottom, from(#eeeeee), to(#dddddd));
  background-image: -moz-linear-gradient(top, #eeeeee, #dddddd);
  background-image: -ms-linear-gradient(top, #eeeeee, #dddddd);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #eeeeee), color-stop(100%, #dddddd));
  background-image: -webkit-linear-gradient(top, #eeeeee, #dddddd);
  background-image: -o-linear-gradient(top, #eeeeee, #dddddd);
  background-image: linear-gradient(top, #eeeeee, #dddddd);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#dddddd', GradientType=0);
  color: #404040;
  text-decoration: none;
  -webkit-box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.025), inset 0 -1px rgba(0, 0, 0, 0.025);
  -moz-box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.025), inset 0 -1px rgba(0, 0, 0, 0.025);
  box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.025), inset 0 -1px rgba(0, 0, 0, 0.025);
}
.open .menu,
.dropdown.open .menu,
.open .dropdown-toggle,
.dropdown.open .dropdown-toggle {
  color: #ffffff;
  background: #ccc;
  background: rgba(0, 0, 0, 0.3);
}
.open .menu-dropdown,
.dropdown.open .menu-dropdown,
.open .dropdown-menu,
.dropdown.open .dropdown-menu {
  display: block;
}

A: If you aren't using jQuery and need to do this in plain javascript, then you can do it like this:
// function called by click to toggle class on parent
function toggleMenu(item) {
    toggleClass(item.parentNode, "open");
    return(false);    // don't do other default handling for the click
}

// utility functions for adding, removing classes
function addClass(elem, cls) {
    var oldCls = elem.className;
    if (oldCls) {
        oldCls += " ";
    }
    elem.className = oldCls + cls;
}

function removeClass(elem, cls) {
    var str = " " + elem.className + " ";
    elem.className = str.replace(" " + cls + " ", "").replace(/^\s+/g, "").replace(/\s+$/g, "");
}

function hasClass(elem, cls) {
    var str = " " + elem.className + " ";
    var testCls = " " + cls + " ";
    return(str.indexOf(testCls) != -1) ;
}

function toggleClass(elem, cls) {
    if (hasClass(elem, cls)) {
        removeClass(elem, cls);
    } else {
        addClass(elem, cls);
    }
}

And, in your HTML, I added an onclick handler to one item:

      Menu Heading

Option 1

Option 2

Option 3

Option 4

Working demo: http://jsfiddle.net/jfriend00/2pVmF/

A: You've tagged your question toggleclass, which is a jQuery-specific tag. Assuming you're really using jQuery, then it's a trivial application of a click handler and toggleClass:
$(".menu").click(function() {
    // Toggle the class
    $(this).toggleClass("open");
});

If you want to do anything further, other than just toggling the class:
$(".menu").click(function() {
    var $this = $(this);

    // Toggle the class
    $this.toggleClass("open");

    // Further work
    if ($this.hasClass("open")) {
        // The menu is now open, do stuff related to that...
    }
    else {
        // The menu is now closed, do stuff related to that...
    }
});

A: If you're working with modern browsers that supports classList, you can simple have:
 element.classList.toggle("open");

Where element is the reference to the element you want to "toggle" the css class. However, jQuery and libraries like that are more indicated for this kind of operations, especially in combination with event listeners.

A: If using jquery use
$(".menu").addClass("open");
$(".menu").removeClass("open");


text:
Q: Angular string enum as param how to call in the view I've got a string enum and a method in my component:
export enum Language {
    de = 'de',
    en = 'en'
}

setLang(lang: Language.en | Language.de) {
    const curent = Language[lang]
}

Than I want to call it in the view:
<button (click)="setLang('en')">

but when I run ng build --prod I've got this error
Argument of type '"en"' is not assignable to parameter of type 'Language'.
I know if I should call in the component it should be
setLang( Language.en) but
how can I call setLang in the view?
UPDATE
All in all I don't like very much passing
a reference of my enum to a property class
so may be this could be a better approach
type LangKeys = keyof typeof  Language;

function foo(lang:LangKeys) {
    const curent = Language[lang]
}

foo('en')

A: Just create a property in your Component Class:
import { Language } from './path-to-enum-file';

...

languageEnum = Language

setLang(lang: Language.en | Language.de) {
  const curent = Language[lang]
}

And then in the template try doing this:
<button (click)="setLang(languageEnum.en)">

A: You can do something like that:
Comonent TS
import { Component } from '@angular/core';

export enum Language {
  de = 'de',
  en = 'en'
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  // Store a reference to the enum
  language = Language;

  setLang(lang: Language) {
    const current = Language[lang];
    console.log(current);
  }

}

HTML file
<button (click)="setLang(language.en)">click</button>

Hope it helps!

A: Expose the enum as a property of your component:
current: Language;
Language = Language;

setLang(language: Language) {
  this.current = language;
}

and in the view:
(click)="setLang(Language.en)"

Alternative: use a union type rather than en enum:
type Language = 'en' | 'de';
[...]
current: Language;

setLang(language: Language) {
  this.current = language;
}

and in the view:
(click)="setLang('en')"


text:
Q: Creating an object from another class I've spent some time trying to solve this, but clearly I'm missing something because I just can't get the code to work correctly. I currently have a program with three class - person, doctor and ConsoleApplication. Person essentially holds a constructor with information like firstname, lastname, phonenumber etc. Doctor is a subclass of Person as the only extra information I need is their medical specialty - I'm aiming for it to inherit the information in the Person object.
The ConesoleApplication class handles creation of objects from the person and doctor classes, in addition to giving the user a way to modify the objects through input. I've managed to successfully spawn objects of Persons in this class and store them in an array, but I can't figure out how to do the same for the Doctor objects.
Here's an example of the code for the AddNewDoctor method in the ConesoleApplication class. I don't provide inputs for all the fields or store the object in an array because I'm simply trying to test if it works.
    private static void AddNewDoctor() {
    int personID = 0;
    Person person;
        System.out.print("Please enter the identification number of the person that is becoming a doctor: ");

    try {
        personID = input.nextInt();
        input.nextLine();
    }
    catch (InputMismatchException e) {
            System.out.println("Oops!! Please enter only integral numbers");
            System.out.println(input.next() + " was not valid input.");
    }

    person = getPersonID(personID);

    if (null == person)
        System.out.println ("This person cannot be found \n");
    else {
        String spec = null;
        String firstName = null;
        String lastName = null;
        String homeAddress = null;
        String phoneNumber = null;

        firstName = person.getFirstName(firstName);

        System.out.print ("Enter speciality of the doctor: ");
        spec = input.nextLine();

        Doctor b = new Doctor(firstName, lastName, homeAddress, phoneNumber, spec);
        System.out.println(b);

    }

}

This code will simply result in
Identification Number: 0
Name: null
Surname: null
Address: null
Mobile/Telephone: null

I was hoping that the object would be created with correct firstName and specialty, but apparently I've done something wrong because they don't appear there. I don't understand why the speciality (spec) field doesn't appear either.
Here's the working code I have for creating objects of the person class - I thought I'd include this just for reference.
        private static void AddNewPerson() {
        String firstName, lastName, homeAddress, phoneNumber;
        input.nextLine();
        System.out.print ("Enter the first name of the person: ");
        firstName = input.nextLine();

        System.out.print ("Enter the last name of the person: ");
        lastName = input.nextLine();

        System.out.print ("Enter the home address of the person: ");
        homeAddress = input.nextLine();

        System.out.print ("Enter the phone number of the person: ");
        phoneNumber = input.nextLine();

        persons[amountPersons] = new Person (firstName, lastName, homeAddress, phoneNumber);
        amountPersons++;

        System.out.print ("The new person has been successfully added. " + "\n"
                           + "" + "\n" );
    }

Here's the constructors for the Person and Doctor classes.
Person
// Default constructor to initialize default instance variables
public Person()
{
firstName = " ";
lastName = " ";
homeAddress = " ";
phoneNumber = " ";
personNumber = 0;
}

//Overloaded constructor designed for objects to spawn
public Person (String firstName, String lastName, String homeAddress, String phoneNumber)
{
// Initialize instance variables
this.firstName = firstName;
this.lastName = lastName;
this.homeAddress = homeAddress;
this.phoneNumber = phoneNumber;
personNumber = NumberSystem;
NumberSystem = NumberSystem + 1;
}

Doctor
    public Doctor(String firstName, String lastName, String homeAddress, String phoneNumber, String spec) {
    //Constructor with inherited person information and new doctor information
    super(firstName, lastName, homeAddress, phoneNumber);
    spec = speciality;
    int doctorID = 0;
    personNumber = doctorID;
    }

Is there are brave soul out there that is willing to read this all and put me on the correct path? I've gotten very frustrated from trying to figure out why I can't create objects of Doctor correctly. :(

A: You haven't posted the fields for Doctor class, but it seems speciality is the field and spec the parameter passed to constructor. So instead of
spec = speciality;

it should be:
speciality = spec;


text:
Q: Ordering allIds array with slice reducer I have the following structure:
{
  todos: {
    byId: {
      123456: {
        id: 123456,
        text: "Hello World",
        dateTime: "2019-01-21T06:15:53.300Z"
      },
      ...
    },
    allIds: [123456, ...]
  }
}

Then I use slice reducer as described here.
const byId = createReducer({})({
  [ADD]: (state, { payload }) => ({
    ...state, [payload.id]: payload
  })
})

const allIds = createReducer([])({
  [ADD]: (state, { payload }) => [
    ...state, payload.id
  ]
})

export default combineReducers({ byId, allIds })

How would you handle ordering by date here? Because allIds reducer only gets the state (the array) and the new added object with its date.
The website linked above just says "Arrays of IDs should be used to indicate ordering.".
I can make a new entry in the state named orderedTodoIds for example but then the sentence above is not correct.


text:
Q: How to limit resultSet size when I retrieve tables from database Here, the source code that retrieve the tables of a database:
    DatabaseMetaData dmd = connection.getMetaData();
    ResultSet resultSet = dmd.getTables(connection.getCatalog(), null, null, TABLE_TYPES);
    while(resultSet.next()){
        treeMap.put(resultSet.getString(TABLE_NAME), new ArrayList<>());
        ResultSet fields = dmd.getColumns(null, null, resultSet.getString(TABLE_NAME), null);
        while(fields.next()){
            treeMap.get(resultSet.getString(TABLE_NAME)).add(fields.getString("COLUMN_NAME"));
        }
    }
    connection.close();
    treeMap.forEach((s, strings) -> System.out.println(s+" -> "+String.join(",",strings)));
    return treeMap;


text:
Q: Polynomial fit of quaternions Imagine that I have a sequence of object poses over time. Each pose is represented by:
t,x,y,z,q0,q1,q2,q3
Where x,y,z is the center of said object, and q0,q1,q2,q3 is the orientation given by a quaternion rotation. The trajectory of such body is observed to obey a 2nd order polynomial curve in 3D space.
I've been using parametric equations for XYZ, like f(t)=ax2+bx+c, where abc are computed from a 2nd order polynomial fit using a T,X dataset.
Can I meaningfully apply the same technique for the individual components of the quaternions?
Is there another technique that is used for this type of problem?
I know that slerp is used to calculate the interpolation between 2 quaternions, but in this case, I want to fit a series of them to a curve over time, if that makes sense.


text:
Q: Merging develop into master makes commit moving on top I'm running in a strange problem that I do not understand.
I have develop branch where all the mainstream development goes. Then I have master where tags are created.
The situation was clean before but right now, when I merge develop into master I see a situation like this:

Before the merge, I see commits in the correct order both with "Ancestor Order" and "Date Order" (using SourceTree, but the same happens with Tower). After the merge, commits and associated tags are moved to the top.
Any idea why it's happening?


text:
Q: Capture a Winforms control for video playback So, I have a Winforms control that is an ElementHost of a WPF control. This WPF control houses several different UIElements that renders GIS data (vector and raster). What I'd like to do is record the user's activity and any animations (like vehicle position). None of the following methods work for me because they are either too slow or have limitations.
Method 1: DrawToBitmap
In previous iterations, the control was in pure Winforms. I could just call the Winforms DrawToBitmap method and get an image in about 10ms. But now that I'm using an ElementHost, getting an image in about 80ms. I have a feeling that behind the scenes, this method is using the RenderTargetBitmap method.
Method 2: RenderTargetBitmap
Alternatively, I tried using RenderTargetBitmap, passing in the canvas from the WPF control to create a bitmap image. But this also takes about 80ms to complete.
Method 3: System.Drawing CopyFromScreen
Doing a screen capture this way works. I can get images in about 35ms. But if a separate window gets in the way during recording or something of that matter, then the recording sees it too.
My Question
Is there a way to record a control that is faster than RenderTargetBitmap without the downside of CopyFromScreen? Is it possible to get in front of the RenderContext found in the OnRender of a control and create an image from that?
Or maybe there is some other way that I'm not thinking of?


text:
Q: Is there a way to completely block the ability to take screenshots in Android? I'm currently developing a light-weight application where in one part of the app I would like to COMPLETELY take away the ability to take a screenshot in Android. When I say screenshot, I'm talking about iPhone's "screen capture" feature. This is for security reasons.  I realize there are apps out there that allow users in Android to do this as well, and I want to block this functionality. Any way of doing this is fine, whether disabling the hardware buttons, freezing the phone, or via software.

A: You can use the window LayoutParam FLAG_SECURE. Add this to your onCreate method:
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
}

More on this topic can be found here.

A: Add an application class in your project like that to prevent the full app from screen-shot (All Activity and Fragment around your app). This is the example project and below I mentioned the core code -
public class MyApplicationContext extends Application {

    private  Context context;

    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        setupActivityListener();
    }

    private void setupActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);            }
            @Override
            public void onActivityStarted(Activity activity) {
            }
            @Override
            public void onActivityResumed(Activity activity) {

            }
            @Override
            public void onActivityPaused(Activity activity) {

            }
            @Override
            public void onActivityStopped(Activity activity) {
            }
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }
            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }
}


text:
Q: Update mysql table to swap the entire rows i have to swap data in row for the entire table. I've searched for the solutions but it is only for two rows. That is not what i'm searching for. I've to swap the entire table's row. The row would only contain two type of data. Like 0 or 1.
My mysql table looks like this.
*CustomerId             Band         Gender*
Kurt Cobain            Nirvana      Male
John Mayer             JohnMayer    Male
Katy Perry             Katy Perry   Female
Lana Del Rey           Lana Del     Female
Axl Rose               GNR          Male

After the swap i want my table to look like this.
*CustomerId            Band         Gender*
Kurt Cobain            Nirvana      Female
John Mayer             JohnMayer    Female
Katy Perry             Katy Perry   Male
Lana Del Rey           Lana Del     Male
Axl Rose               GNR          Female

I want my ID to be same as it is.
Thank you !!!!!

A: If the values you want to swap are 0 and 1, you can do something like:
UPDATE table_name SET Gender = 1 - Gender;

if your current values is 1, it will do this (1-1 =0), else if your value is 0, it will do this(1-0 = 1)
OR
If you are working with strings, you can simply do something like:
UPDATE table_name SET Gender = IF(Gender="Male", "Female", "Male");

This query does a basic if statement, if the gender field is Male, it will set it to Female, else, it will set it to Male
Here is a working DEMO

A: UPDATE table SET gender=CASE WHEN gender='female' THEN 'male' WHEN gender='male' THEN 'female' ELSE NULL END


text:
Q: How to add extension .html in url asp.net mvc 4? I have the url:
http://localhost:1714/Message/Index
I want to show:
http://localhost:1714/Message/Index.html
How can I do it?

A: You need to modify Web.config to map requests for your HTML files to TransferRequestHandler.
like so:
<system.webServer>
    ...
    <handlers>
      <add name="HtmlFileHandler" path="*.html" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    ...
  </system.webServer>

This is explained here by Jon Galloway.
And put this to your RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
        {
            ...
            routes.MapRoute("Default", "{controller}/{action}.html", new { controller = "Home", action = "Index" });
            ...
        }

Than accessing http://localhost:{port}/Home/Index.html will send you to your Home page.


text:
Q: Converting C# method to vb.net I am new to vb.net and need to convert on of the C# classes to vb.net. Here is C# class
[Serializable]
    [XmlType(TypeName = "DomEvents")]
    public class DomEvents : System.Collections.CollectionBase
    {

        public void Add(DomEvent domEvent)
        {
            List.Add(domEvent);
        }

        public DomEvent this[int index]
        {
            get { return (DomEvent)List[index]; }
            set { List[index] = value; }
        }
    }

Now here is vb.net that have
Imports System
Imports System.Xml.Serialization

<System.Serializable()>
<XmlType(TypeName:="DomEvents")>
Public Class DomEvents
    Inherits System.Collections.CollectionBase

    Public Sub Add(ByVal domEvent As DomEvent)
        List.Add(domEvent)
    End Sub

End Class

How can i convert the DomEvent property to vb.net?
public DomEvent this[int index]
        {
            get { return (DomEvent)List[index]; }
            set { List[index] = value; }
        }

A: There are lots of C#/VB converters available online. The most popular one I know is Telerik (hint: it's the first result when searching for "C# to VB").
It says this is the translation to VB:
Public Default Property Item(index As Integer) As DomEvent
    Get
        Return DirectCast(List(index), DomEvent)
    End Get
    Set
        List(index) = value
    End Set
End Property

As Tim quite rightly pointed out it's worth mentioning that these tools are not bullet proof by any means, but they're a good starting point. Often the code works immediately, other times it requires a little reverse engineering on your part.

A: I wouldn't recommend the telerik online tool I ve seen in another answer..
I would suggest Roslyn Code Converter - icsharpcode/CodeConverter online (which is based

It produced casting errors in my case

Example VB:
myObj.myProp = CType(someObj, SomeType).Value

Converted by telerik to:
myObj.myProp = (SomeType)someObj.Value;

While the correct (from icsharpcode) is:
myObj.myProp = ((SomeType)someObj).Value;


text:
Q: SQL Diff software that support SQL Server 2012 - any recommendations? In a previous work place we worked with a software called SQL Delta which compared 2 sql servers - so we could sync the changes from our development machine and the production machine. I checked and they don't seem to support SQL Server 2012 yet.
Does anyone have any recommendation about another SQL Diff software that works with SQL Server 2012, has a good easy and clear interface?
An advantage is that it will also support SQL Server Azure.
Thanks

A: Try red-gate, this also support sql server 2012
http://www.red-gate.com/products/sql-development/sql-compare/features
also:
http://www.sqlaccessories.com/SQL_Examiner/
and
dbforge

A: You can also check xSQL, I had used their free version sometime back and found it to be pretty good.


text:
Q: Is it possible to use xml intellisense in vb.net code in visual studio 2010? I'm currently learning the XML features of VB.NET and Visual Studio 2010, and I have learned how I can enable intellisense in a XML file by associating it with a schema, and this works well. However since I'm mostly generating xml and not reading data from an xml file, I would like to be able to do the same when writing xml in a VB.NET module, class etc.
e.g. when writing xml directly in vb.net code like this:
Dim JohnDoe As XElement = <Person Name="John Doe">
                              <Height>180</Height>
                              <HeightUnit>Meter</HeightUnit>
                              <HeightUnitType>Metric</HeightUnitType>
                          </Person>

Is this possible?

A: I found that the problem was that a targetNamespace attribute has to be added manually to my schema in order for me to be able to import it.


text:
Q: mongodb queries per second I have a server with 64G RAM and I am running a script which compares one million data in a csv file against the database. If matches are found, the script just prints the number of matches at the end of execution.
The script when ran, is taking 3 minutes to finish. Tested with 50,000, 1 lakh, 3 lakh, 5 lakh data files as well and the performance rate or the rate at which the script is executed is proportional. There is enough memory free in the server. The mongostat output when the script was running is pasted below. My questions is, I believe the script is executing close to 5000 queries per second. I have read in many posts, that they are getting an average of 50K queries per second. How can this be achieved? My server is running Ubuntu, 64 bit, and 24 cores.
insert  query update delete getmore command flushes mapped  vsize res faults            locked db idx miss %     qr|qw   ar|aw  netIn netOut  conn       time
    *0   3885     *0     *0       0     1|0       0    12g  24.2g 64m      0 db_list_restore:0.0%          0       0|0     1|0 380k   142k     2   03:09:26
    *0   4188     *0     *0       0     1|0       0    12g  24.2g 68m      0 db_list_restore:0.0%          0       0|0     0|0 410k   153k     2   03:09:27
    *0   4462     *0     *0       0     1|0       0    12g  24.2g 72m      0 db_list_restore:0.0%          0       0|0     0|0 440k   163k     2   03:09:28
    *0   4401     *0     *0       0     1|0       0    12g  24.2g 76m      0 db_list_restore:0.0%          0       0|0     0|0 435k   161k     2   03:09:29
    *0   4368     *0     *0       0     2|0       0    12g  24.2g 81m      0 db_list_restore:0.0%          0       0|0     1|0 432k   160k     2   03:09:30
    *0   4416     *0     *0       0     1|0       0    12g  24.2g 84m      0 db_list_restore:0.0%          0       0|0     1|0 437k   161k     2   03:09:31
    *0   4245     *0     *0       0     1|0       0    12g  24.2g 89m      0 db_list_restore:0.0%          0       0|0     0|0 420k   155k     2   03:09:32
    *0   4561     *0     *0       0     1|0       0    12g  24.2g 93m      0 db_list_restore:0.0%          0       0|0     1|0 451k   167k     2   03:09:33
    *0   3920     *0     *0       0     1|0       0    12g  24.2g 97m      0 db_list_restore:0.0%          0       0|0     0|0 388k   144k     2   03:09:34
    *0   4307     *0     *0       0     2|0       0    12g  24.2g 105m      0 db_list_restore:0.0%          0       0|0     0|0 426k   157k     2   03:09:35

A: These number look relatively reasonable for a single process doing all the work - depending on what sort of query you are doing of course.
In general you'll have thousands of webserver processes (depending on your application workload and cpu count, maybe only few hundreds), which will be generating the traffic - so you'll have thousands of sockets open to the server allowing you to scale whichever component in your infrastructure independently.
For a single process application you'll be stuck in "wait loops" as there is only so much individual resource is asked to do at each time so you will never be able to maximize your potential with only one process, one socket, one task. You want to occupy all your resources all the time.
To achieve this you would want to parallelize your workflow as much as you can. There is no predefined number of workers that is the correct answer, so how much work each process should be doing is something you'll have to figureout for yourself by trying it out.
If you have million entries in the CSV file, you may want to start dividing the work up in 10 pieaces, create 10 PHP processes that seek into the file and work read through 100.000 entries.
Benchmark that, and then maybe try 100 processes, each working on 10.000 entries at a time, and compare to the previous results.


text:
Q: How to find all image links on a website? Let's say for example the image URL for certain images on a website is something along the lines of:
> www.example.com/store/productimages/details/87540_item_a.jpg
> www.example.com/store/productimages/details/48395_item_b.jpg
> www.example.com/store/productimages/details/75435_item_c.jpg

The site is constantly getting updated and while those image links can still be pulled up, one can no longer find the exact image unless they have the exact link to it.
So in other words, once the page for: www.example.com/store/productimages/details/87540_item_a.jpg is taken down and no longer indexed buy Google, the only way to find it again is to have had that particular link copied down somewhere and to search it manually to pull it up.
However, since web archives exist, I'm able to locate a few of those said links, but obviously only the ones that have been archived. The thing is, those links aren't broken and are still being hosted on that particular www.example.com site, independent from the web archive site. (ex. I can take an image link that is 6 years old from that web archiver, paste, and search it for it as usual in the address bar.) So this leads me to believe that they are still on the website's index. The problem is that the index isn't publicly accessible. I've tried using the site's sitemap.xml, but it is the most current one and doesn't contain any of the older image links. Even the older image links are set up the same way as these newer ones and are presumably under the same directory mixed in with the old ones.
My question is how would I go about finding all of those older image links if tools like HTTrack and wget only crawl what is currently on the site? Or am I just using these wrong? I've tried to use HTTrack and wget by telling them to crawl all .jpgs under the www.example.com/store/productimages/details/ directory, but it comes up with nothing because its forbidden I take. Is there another way to go about finding those old image links?

A: since in your example the images are all numbers, you could try all numbers, one after another.
I.e. have your browser/wget/curl ...
try to GET files with names 00000.jpg ..... infinity.jpg
and the server will serve up the file, if it is present.
or if they are not numbers, have your program run through all the possible combinations that match the pattern of filenames that you know about.
On the whole, it sounds like you are going against the intentions of the site owners, if you are not accessing the data according to a mechanism that the site offers to its standard users. This is not a bad thing in and of itself, as interesting results can come from unintended uses, which the originators had not thought of, and was not necessarily against their wishes. (you might try to ask them if they have any objections)


text:
Q: How to fix "yo: command not found" after installing Yeoman Following these instructions, I tried to install yeoman using npm twice:
http://yeoman.io/learning/index.html
After the first failure, I uninstalled node using these instructions:
How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X) Then, I installed nvm and node/npm (via nvm) with one error:
[Yeoman Doctor] Uh oh, I found potential errors on your machine
---------------

[Error] NPM root value is not in your NODE_PATH
  [info]
    NODE_PATH = /Users/joanna/.nvm/v0.10.22/lib/node_modules:.
    NPM root  = /Users/joanna/.node/lib/node_modules

  [Fix] Append the NPM root value to your NODE_PATH variable
    Add this line to your .bashrc
      export NODE_PATH=$NODE_PATH:/Users/joanna/.node/lib/node_modules
    Or run this command
      echo "export NODE_PATH=$NODE_PATH:/Users/joanna/.node/lib/node_modules" >> ~/.bashrc && source ~/.bashrc

I pasted that command in, and then I ran npm install -g yo again.
After following the instructions from the yeoman site again, it still can't find yeoman. I receive this error:
-bash: yo: command not found
What is wrong? The Yeoman Doctor says: "Everything looks alright!"

A: Just to add on,I am using OS X 10.11.1, the code as mentioned by steve works for me too.
npm install -y -g yo
echo export PATH="$HOME/npm/bin:$PATH" >> ~/.bashrc
npm config set prefix ~/npm
echo "export NODE_PATH=$NODE_PATH:/home/$USER/npm/lib/node_modules" >> ~/.bashrc && source ~/.bashrc
npm install -y -g yo

A: After trying the above suggestion, I noticed that yeoman was installed, as expected, in /Users/joanna/.node/bin/yo.  I set up symbolic links to yo, grunt, and bower in /usr/local/bin with
ln -s /Users/joanna/.node/bin/yo /usr/local/bin/yo
ln -s /Users/joanna/.node/bin/grunt /usr/local/bin/grunt
ln -s /Users/joanna/.node/bin/bower /usr/local/bin/bower

Everything works now, but I'm concerned that the links might cause problems in the future. Is there a better solution?

A: All I needed to do was adding this line to .bash_profile
export PATH="$PATH":~/.node/bin

You can execute this to add it automatically:
printf "\nexport PATH=\"\$PATH\":%s\n" ~/.node/bin >> ~/.bash_profile

Tested on OS X 10.9, 10.10, 10.11 and Ubuntu 14.04

A: Short version:
In your shell, type the following commands:

*

* npm config set prefix ~/npm

*echo "export NODE_PATH=$NODE_PATH:/home/$USER/npm/lib/node_modules" >> ~/.bashrc && source ~/.bashrc

*Then reinstall Yeoman:
npm install -g yo
Then everything should work fine!
Explanation:
Had a similar condition, except yo command did work, but any installed generators didn't appear after installing them, this solved the issue.
The problem is that your npm path is set to /usr/local, which is a directory that requires root/sudo privileges, since yo is a user command, it shouldn't be ran as a superuser, and if you'll try to run sudo yo, Yeoman will tell you that explicitly.
I also tried to chown -R $USER:$USER /usr/local, and chmod -R /user/local +rw, but none of those helped.
Keep in mind that the node modules(yo generators are also node modules) that were previously installed in /usr/local might no longer be available and will require re-intalling.

A: For me on Ubuntu only the following worked for me...
Ubuntu
Tested on Ubuntu 14.04.2
This was a base install of Ubuntu 14.04.2 on VirtualBox using ubuntu-trusty-64.
I had just installed node and npm fresh and they were working well.
npm install -y -g yo
echo export PATH="$HOME/npm/bin:$PATH" >> ~/.bashrc
npm config set prefix ~/npm
echo "export NODE_PATH=$NODE_PATH:/home/$USER/npm/lib/node_modules" >> ~/.bashrc && source ~/.bashrc
npm install -y -g yo

yes I had to install yeoman, fix the path issues, then reinstall yeoman.
The explanations are above from Oleg Tikhonov and bfred.it

A: The source of the problem is that you have NODE_PATH set while using NVM at the same time. When you use NVM you shouldn't have a NODE_PATH variable at all, since NVM installs global packages in its version specific root.
Delete all packages that are in your NODE_PATH, remove the environment variable, and install yo and the generators or any other global packages you need. You will see that it stops complaining and everything ends up in the nvm subdirectory matching the current version.
When you start using a different Node version in NVM, reinstall the global packages. This will keep everything organised neatly by version like its meant to be.
More info on this discussion here:
https://github.com/creationix/nvm/pull/97

A: In my case i had to execute :
npm config delete prefix

then set a nvm version
nvm use 8

and it works

A: I used :
$HOME/npm/bin
And it pretty worked !
In MAC OSX

A: Check where your npm is installed:
where npm

Running above command will list the directory where npm is, as follows:
/usr/local/Cellar/node/5.1.0/libexec/npm/bin/npm

Copy the path till bin folder and export the same as a PATH variable, as below:
export PATH=$PATH:/usr/local/Cellar/node/5.1.0/libexec/npm/bin


text:
Q: Android MediaPlayer background music thread randomly stops I have a single activity game while playing (after login and character selection).  My sound pool for SFX works great, but my background music randomly stops playing.  I tried to add in setOnErrorListener, but never saw anything there.  I am wondering if the thread is being garbage collected?
When you are in different towns or wilderness the music changes and that is checked here: !currentPlayingMusicFilename.equals(shortFilename).  If you stay in the same music area, randomly the music stops looping.
I have read so many posts on here and google and can't find the "proper" way to play game background music.  I've tried soundpool, but they are over 1MB, saw many things saying not to do service, and having an issue with this approach.  Any help is greatly appreciated.
I am leaving in the "SFX" portion in case that code can help anyone and provide a full picture.
public static void playSoundOrMusic(final String shortFilename, final String type, double distanceFactor) {
    String fullFilename = "";

    if (type.equals("SFX")){
        fullFilename = "res/sounds/sfx/" + shortFilename;
    } else if (type.equals("MUSIC")){
        if (mp3MUSICPlayer != null && mp3MUSICPlayer.isPlaying() && !currentPlayingMusicFilename.equals(shortFilename)){
            mp3MUSICPlayer.stop();
        }
        fullFilename = "res/sounds/music/" + shortFilename;
    }

    float volumeManipulation = 1.0f;
    if (type.equals("SFX")){
        int sfxVolume = MyCommandReceiver.GetSharedPreferences().getInt(MyCommandReceiver.GetStringById(R.string.pref_general_sfx_volume_key), 100);
        sfxVolume *= distanceFactor;
        volumeManipulation = (float) (sfxVolume / 100.0);
        //volumeManipulation = (float) (1 - (Math.log(MAX_VOLUME - sfxVolume) / Math.log(MAX_VOLUME)));
        LoggerWrite("v", TAG, "sfxVolume: " + volumeManipulation);
    } else if (type.equals("MUSIC")){
        int musicVolume = MyCommandReceiver.GetSharedPreferences().getInt(MyCommandReceiver.GetStringById(R.string.pref_general_music_volume_key), 100);
        volumeManipulation = (float) (musicVolume / 100.0);
        //volumeManipulation = (float) (1 - (Math.log(MAX_VOLUME - musicVolume) / Math.log(MAX_VOLUME)));
        LoggerWrite("v", TAG, "musicVolume: " + volumeManipulation);
    }
    final float finalVolume = volumeManipulation;

    if (MyCommandReceiver.GetActiveActivity() == null){ //if not yet in Activity
        return;
    }
    try {
        Uri myUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/KisnardOnline/" + fullFilename));
        if (type.equals("SFX")){
            if (!soundPoolIds.containsKey(Environment.getExternalStorageDirectory() + "/KisnardOnline/" + fullFilename)){ //not yet in soundpool
                int soundId = soundPool.load(Environment.getExternalStorageDirectory() + "/KisnardOnline/" + fullFilename, 1);
                soundPoolIds.put(Environment.getExternalStorageDirectory() + "/KisnardOnline/" + fullFilename, soundId);
                //play it manually one time
                mp3SFXPlayer = new MediaPlayer();
                mp3SFXPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mp3SFXPlayer.setVolume(finalVolume, finalVolume);
                mp3SFXPlayer.setDataSource(MyCommandReceiver.GetActiveActivity(), myUri);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mp3SFXPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    mp3SFXPlayer.start();
                                }
                            });
                            mp3SFXPlayer.prepare();
                        } catch (Exception ex) {
                            GameActivity.LoggerWrite("e", TAG, "Sound(sfx) playing issue" + ex);
                        }
                    }
                }).start();
            } else { //already in soundpool - play it
                soundPool.play(soundPoolIds.get(Environment.getExternalStorageDirectory() + "/KisnardOnline/" + fullFilename), finalVolume, finalVolume, 0, 0, 1);
            }
        } else if (type.equals("MUSIC")){
            if (!currentPlayingMusicFilename.equals(shortFilename)){
                mp3MUSICPlayer = new MediaPlayer();
                mp3MUSICPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mp3MUSICPlayer.setVolume(finalVolume, finalVolume);
                mp3MUSICPlayer.setDataSource(MyCommandReceiver.GetActiveActivity(), myUri);
            }
        }
    } catch (Exception e) {
        GameActivity.LoggerWrite("e", TAG, "Sound file issue" + e);
    }

    if (type.equals("MUSIC") && !currentPlayingMusicFilename.equals(shortFilename)){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mp3MUSICPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            currentPlayingMusicFilename = shortFilename;
                            mp3MUSICPlayer.start();
                        }
                    });
                    mp3MUSICPlayer.prepare();
                    mp3MUSICPlayer.setLooping(true);
                } catch (Exception ex) {
                    GameActivity.LoggerWrite("e", TAG, "Sound(music) playing issue" + ex);
                }
            }
        }).start();
    }
}

A: Here is how I solved this as it does not seem there is an answer out there to why it dies randomly.
if (type.equals("MUSIC") && (!currentPlayingMusicFilename.equals(shortFilename) || !mp3MUSICPlayer.isPlaying())){
        new Thread(new Runnable() {
        ...


text:
Q: filter objects by relations tastypie "argument of type 'NoneType' is not iterable" I'm using the tastypie API and a neo4j database with Django 1.5.3. & Neo4django. I would like to access/filter e.g. a Lemma(s) that are related to Words with a specific pos value via the API.
models.py
class Lemma(models.NodeModel):

    value = models.StringProperty(max_length=100)
    def __unicode__(self):
        return self.value

class Word(models.NodeModel):

    pos = models.StringProperty(max_length=12, blank=True, null=True)
    cid = models.IntegerProperty(blank=True, null=True)

    lemma = models.Relationship(Lemma,
                                rel_type='has_base',
                                single=True,
                                related_name='values'
                               )
def __unicode__(self):
    return self.value

api.py:
class LemmaResource(ModelResource):

    word = fields.ToManyField('api.api.WordResource', 'values', related_name='lemma', null=True )

    class Meta:
        queryset = Lemma.objects.all()
        resource_name = 'lemma'
        always_return_data = True
        excludes = ['require_order', 'require_all']
        authorization = ReadOnlyAuthorization()
        filtering = {'value': ALL,
            'word': ALL_WITH_RELATIONS}

class WordResource(ModelResource):

    lemma = fields.ToOneField(LemmaResource, 'lemma', null=True )

    class Meta:
        queryset = Word.objects.all()
        resource_name = 'word'
        always_return_data = True
        excludes = ['require_order', 'require_all']
        authorization = ReadOnlyAuthorization()
        filtering = {'CTS': ALL,
                'lemma': ALL_WITH_RELATIONS,
                'pos': ALL}

I tried to follow this example (Filtering on reverse relations) I would like to call via the API e.g. ../api/lemma/?word__pos=noun&format=json , but I got an "argument of type 'NoneType' is not iterable" ERROR. Do I have to name the filters as in the model calsses or should that be the filed names? Could it be that the neo4j database makes some problems.
I appreciate any hints. Thanks.


text:
Q: Deletar elemento do array de um model do mongoose Digamos que eu tenha um model de usuário assim:

const userSchema = new mongoose.Schema({
  email: {type: String, required: true, unique: true},
  password: {type: String, required: true},
  username: {type: String, required: true},
  favorites: []
})

const userModel = mongoose.model('User', userSchema)

E estou armazenando um objeto assim na array de favoritos:

{
  id: 1,//exemplo de id
  data: {}, //um objeto com grandes dados, como resposta de api
  name: "something",
  description: "something"
}

Como posso filtrar esse objeto no array de favoritos, apenas pelo seu id (sem passar esse objeto inteiro em funções como updateOne e update do mongoose, apenas o id dele)?


text:
Q: Identifying the two-hole torus with an octagon I am aware that the 2-hole torus can be identified with the octagon with the equivalence relation as given in this picture:
https://www.quantamagazine.org/wp-content/uploads/2012/09/Haken_sized_Figure02.jpg
However, today in a topology revision lecture, the lecturer said the 2-hole torus can be represented by the octagon with opposite sides identified. This is different to the picture, so was our lecturer wrong? If so what surface is given by the octagon with opposite sides identified?

A: Edit/disclaimer:
Although the solution below does indeed identify the two-hole torus with an octagon, it does not answer OP's question which was the two-hole torus can be represented by the octagon with opposite sides identified. I do not explain how to identify the opposites sides of an octagon, but rather how to glue two representations of a torus to get a two-hole torus.

Original answer:
Basically, what you want to do is to glue two tori.
Both tori can be identified with the following representation:

Now to glue them together, you want to cut a small piece of each torus, and glue them in a certain way on the area you cut. We are going to cut a small triangle at points $p$ and $q$ as following way:

Note that $p$ and $q$ are note at the same place in both tori!
Now we glue them together, $p$ goes on $p$ and $q$ goes on $q$ which gives:

Redrawing it as an octagon, it gives:

A: The space resulting from gluing opposite edges of an octagon naturally depends on the orientation of the gluing, but assuming "antipodal edges" are glued with the same orientation, as when building a torus from a square, the result is indeed a two-holed torus.

It's easy to see that

*

*Two vertices that are endpoints of a dashed segment are identified, so all eight vertices are identified. Consequently, the interior angles of the octagon are joined cyclically; after identification, the vertex has a disk neighborhood.

*

*Each edge is identified with the opposite edge, and no others, in a manner compatible with the orientation of the octagon.

It follows that the identification space is an orientable surface having a cellular decomposition with one vertex, four edges, and one $2$-cell. The Euler characteristic is $\chi = 1 - 4 + 1 = -2$. By the classification of surfaces, the glued octagon is a two-holed torus.
(Presumably the same conclusion can be reached by surgery, modifying the octagon to the "conventional" gluing, though I haven't checked carefully.)


text:
Q: Foreach statement w/ Jquery So I am trying to reposition an element each time a user clicks on an input element.

'desired_equity_help' is the element that I am trying to toggle and reposition based on the input element clicked. Any ideas why this isn't working?
Here is the HTML:

                            Desired Equity

Hello World! This is some dummy text.

                    Desired:<input  style="width:110px" type="text" id="desired_equity" name="desired_equity"/>

                    Break:<input style="width:110px" type="text" /> at: <input type="text" style="width:110px" /><select><option>Independent Users</option></select>

                    Last One:<textarea rows="3" cols="50"></textarea>

A: Forget the foreach and apply the event straight to the selector like so...
$('input').focus(function(){
   var p = $(this);
   var position = p.position();
   $('#desired_equity_help').css("left", position.left - 435 );
   $('#desired_equity_help').css("top", position.top -20 );
   $('#desired_equity_help').show();
});

$('input').blur(function(){
    $('#desired_equity_help').hide();//hide on exit of input
});

Note: Using position will require your desired_equity_help element to belong to the same parent as your input elements. if this is not the case consider using offset instead

A: This is probably closer to what you are looking for.  You had an undefined variable and the element should probably be shown instead of toggled.
$('input').each(function(index) {
    var $this = $(this);
    var position = $this.position();

    $this.focus(function() {
        $('#desired_equity_help').css({"left": position.left + 150,
                                       "top": position.top}).show();
    });
});

Demo: http://jsfiddle.net/nEMye/

A: Ohhhhh, it looks like your doing a lot of stuff there, according to what you want to do you don't need the each() or toggle() methods there. Here is what I would do:
$(document).ready(function(){
    $('input').click(function(e){
        var position = $(this).position();
        $('#desired_equity_help')
        .css({"left" : position.left - 435 ,
            "top" : position.top -20 });
    });
});

By binding the click event to the input you are telling it to execute that function every time the input is clicked. If you don't want the click method you can change it to the focus method or whichever method is relevant to you. The toggle method is unecessary as well, it is more or less used for switch type button, a button you would click once and it goes into one state then after you click it again it goes back to the previous state or something like that.
Hope this helps!


text:
Q: What is RDSAppXPlugin? In windows 2012 event viewer in the "Applications and Services > Microsoft > Windows > TerminalSerices - LocalSessionManager > Operational" path I can see the following event:
"Plugin RDSAppXPlugin has been successfully initialized"
Any idea what is that plugin? I could not find any source by googling!
Screenshot:
RDSAppXPlugin


text:
Q: python drawing a graph My code :
def izrisi_vektor(vektor):
    plt.axis([0,9,0,100])

    plt.plot(vektor,color='black')

    povprec=povprecje(vektor)
    plt.plot(povprec,color='red')

    std=standardna_deviacija(vektor)
    plt.plot(std,color='blue')

    plt.ylabel('Amplituda')
    plt.xlabel('Vzorec')
    plt.show()
    return 0

the vektor is a array consisting of 10 random numbers from 0 to 100
the function povprecje returns a float number witch is average of these 10 numbers. And standardna_deviacija(vektor) returns a float number of standard diviation of these numbers in arrayl. What I am trying to do is draw these on a graph.
Only one that works is the first one where I plot these array numbers.
Graph that I have at the moment

A: You are drawing the graph only once.
Your code should be something like this:
x = range(0, 101)
plt.plot(x, vektor, 'black', x, povprec, 'red', x, std, 'blue')

This will draw all 3 lines on the same axis.
See the documentaion of plot the function signature allows you to pass multiple curves to draw as:
 x1, y1, format, x2, y2, format2 ...

A: Usually in Python, the values are plotted on the same figure until you run "plt.show()".  From your question statement, the first plot is 10 float numbers, thus you have a nice line.  For your mean and standard deviations, they are just float numbers, which is just a point.  They are also plotted on the graph, you just cant see it because it is just one point and you are using plt.plot.  To see the trend line and 2 other points for mean and standard deviation, do:
plt.plot(vektor,color='black')
plt.show()

plt.scatter(1, povprec,color='red')
plt.show()

plt.scatter(1, std,color='blue')
plt.show()

This will output 3 plots, first one is your line as shown in your question.  The other 2 are points, with the y axis being their respective "units" (mean, standard deviation).


text:
Q: Amazon Aws iot dynamo db insert I am trying to update DynamoDB and I send JSON data from Rasperry PI 2, but when I look to CloudWatch I see below error message.
Does anyone come across this error and aware of any solution?
2016-10-09 19:19:56.162 TRACEID:d898d574-2181-e999-4354-1d086e66ba32 PRINCIPALID:bf0e71506eb955a89d3a1cf7caecd33a3af27c13a4e560c5fa852f1d5d89a8e0 [ERROR] EVENT:DynamoActionFailure TOPICNAME:easyprk/sensorData CLIENTID:easyprk MESSAGE:Dynamo Insert record failed. The error received was One or more parameter values were invalid: An AttributeValue may not contain a null or empty binary type. (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 0PNKCG5DO7SRFP49SOJIDSKD7RVV4KQNSO5AEMVJF66Q9ASUAAJG). Message arrived on: easyprk/sensorData, Action: dynamo, Table: sensorData, HashKeyField: serialKey, HashKeyValue: , RangeKeyField: None, RangeKeyValue: 1476040796073

A: When inserting items to DyanmoDB you need to make sure you dont have any empty/null attributes.

A: thanks for help,comments is helpful for me,dynamoDb range key cannot be null.
when i changed nosql columns through not empty.it works now i can get data from rasperry pi :)


text:
Q: SQL Server error 'Cannot find data type' I'm getting this error message when saving/updating a table from c#.

Column, parameter, or variable #6: Cannot find data type MyDataType.

User defined data-type MyDataType is numeric(18,2)
Everything worked OK before re-installing the machine where the SQL Server 2008 was installed.
Already tried setting compatibility_level, but the issue is still there.

A: Try to re-create the type:
create type MyDataType from numeric(18,2) not null


text:
Q: Is there a simple way to automatically test remote JMX URLs? I'm having a painful afternoon trying to configure a server to provide remote JMX access.  The simplest tool I've found to connect to a JMX server is jconsole, but it doesn't seem a great tool when trying to repeatedly access multiple URLs.
Is there a simple way, preferably from the command line, to check if a particular URL points to a valid JMX server?  E.g.
jmxTest service:jmx:rmi://192.168.0.101:1099/jndi/rmi://192.168.0.101:1099/jmxrmi

returning status 0 for a working server, and 1 for a non-working one
Edit
I tried the following, but it seems to work even when the first half of the JMX URL points to a non-existent IP:
JMXServiceURL url = new JMXServiceURL(urlAsString);
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);

MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
mbsc.getDomains();

A: There are many tools that support jmx access. You can write your simple main class, make it accept params, or a config file, and it can do the check for you.
Or you can use a tool that is more suited for that, for example JMeter. Take a look at that:
http://wiki.apache.org/jmeter/JmxTestPlan
It also has a gui so you don't get xml crazy.


text:
Q: How to conditionally provision N role assignments for storage accounts with ARM Template copy? I am trying to provision N storage accounts, N role assignments (1 per storage account) that grant access to a specific identity, but only conditionally deploy the role assignments. The storage accounts and identity already exist and template logic for them has been working for some time.
If I try to deploy the below template snippet, I hit "the language expression property array index '0' is out of bounds" on "'[concat(parameters('BackupStorageAccountRoleAssignmentsDeployment')[0].AccountName, '/Microsoft.Authorization/', guid(parameters('BackupStorageAccountRoleAssignmentsDeployment')[0].Name))]'" when the input array of role assignments is empty.
I'm already using trick to force a 0 length copy to length = 1 and then guard deployment on a condition. I've tried variations using a default array of size 1, moving my role assignment section into a nested template, and manually unrolling my loop into 4 role assignments. No matter what, I hit the same error. What is wrong with this snippet?
{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "RoleAssignments": {
            "type": "array"
        },
        "IdentityName": {
            "type": "string"
        },
        "StorageAccounts": {
            "type": "array"
        }
    },
    "variables": {
        "IdentityResourceId": "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', parameters('IdentityName'))]"
    },
    "resources": [
        { // Everything related to role assignments chokes completely, even if I unroll the loop
            "dependsOn": [
                "[variables('IdentityResourceId')]",
                "storageaccountcopy"
            ],
            "copy": {
                "name": "RoleAssignmentsCopy",
                "count": "[max(length(parameters('BackupStorageAccountRoleAssignmentsDeployment')), 1)]"
            },
            "condition": "[greater(length(parameters('RoleAssignments')), 0)]",
            "type": "Microsoft.Storage/storageAccounts/providers/roleAssignments",
            "apiVersion": "2020-04-01-preview",
            "name": "[concat(parameters('RoleAssignments')[copyIndex()].AccountName, '/Microsoft.Authorization/', guid(parameters('RoleAssignments')[copyIndex()].Name))]",
            "properties": {
                "roleDefinitionId": "[parameters('RoleAssignments')[copyIndex()].RoleDefinitionId]",
                "principalId": "[if(and(empty(parameters('RoleAssignments')[copyIndex()].ResourceId), not(empty(parameters('RoleAssignments')[copyIndex()].PrincipalId))),
                                parameters('RoleAssignments')[copyIndex()].PrincipalId,
                                reference(parameters('RoleAssignments')[copyIndex()].ResourceId, '2018-11-30').PrincipalId)]",
                "scope": "[parameters('RoleAssignments')[copyIndex()].Scope]",
                "principalType": "[parameters('RoleAssignments')[copyIndex()].PrincipalType]"
            }
        },
        {   // Everthing related to storage account provisioning works fine, this was existing code
            "condition": "[and(greater(length(parameters('StorageAccounts')), 0), not(parameters('SkipStorageAccountProvisioning')), equals(parameters('StorageAccountProvisioningDefault'), 'true'))]",
            "copy": {
                "name": "storageaccountcopy",
                "count": "[length(parameters('StorageAccounts'))]"
            },
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2019-06-01",
            "name": "[parameters('StorageAccounts')[copyIndex()].AccountName]",
            "location": "[resourceGroup().location]",
            "sku": {
                "name": "[if(equals(parameters('StorageAccounts')[copyIndex()].AccountTypeOverride, parameters('StorageAccountTypeOverrideDefault')), parameters('StorageAccounts')[copyIndex()].AccountType, parameters('StorageAccounts')[copyIndex()].AccountTypeOverride)]",
                "tier": "Standard"
            },
            "kind": "[parameters('StorageAccounts')[copyIndex()].AccountKind]",
            "properties": {
                "networkAcls": {
                    "bypass": "AzureServices",
                    "virtualNetworkRules": [],
                    "ipRules": [],
                    "defaultAction": "Allow"
                },
                "supportsHttpsTrafficOnly": true,
                "encryption": {
                    "services": {
                        "file": {
                            "keyType": "Account",
                            "enabled": true
                        },
                        "blob": {
                            "keyType": "Account",
                            "enabled": true
                        }
                    },
                    "keySource": "Microsoft.Storage"
                }
            }
        }
    ]
}

EDIT:
Per feeback I tried moving the snippet into a nested template. Fails with the exact same error, The template resource '[concat(parameters('RoleAssignments')[copyIndex()].AccountName, '/Microsoft.Authorization/', guid(parameters('BackupStorageAccountRoleAssignments')[copyIndex()].Name))]' at line '1' and column '837' is not valid: The language expression property array index '0' is out of bounds..
{
      "dependsOn": [
        "[variables('IdentityResourceId')]"
      ],
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2020-10-01",
      "name": "RoleAssignmentsDeployment",
      "properties": {
        "mode": "Incremental",
        "expressionEvaluationOptions": {
          "scope": "inner"
        },
        "parameters": {
          "RoleAssignments": {
            "value": "[parameters('RoleAssignmentsDeployment')]"
          }
        },
        "template": {
          "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
          "contentVersion": "1.0.0.0",
          "parameters": {
            "RoleAssignments": {
              "type": "array"
            }
          },
          "resources": [
            {
              "dependsOn": [
                "[resourceId('Microsoft.Storage/storageAccounts', parameters('RoleAssignments')[copyIndex()].AccountName)]"
              ],
              "copy": {
                "name": "RoleAssignmentsDeploymentCopy",
                "count": "[max(length(parameters('RoleAssignments')), 1)]"
              },
              "condition": "[greater(length(parameters('RoleAssignments')), 0)]",
              "type": "Microsoft.Storage/storageAccounts/providers/roleAssignments",
              "apiVersion": "2020-10-01",
              "name": "[concat(parameters('RoleAssignments')[copyIndex()].AccountName, '/Microsoft.Authorization/', guid(parameters('RoleAssignments')[copyIndex()].Name))]",
              "properties": {
                "scope": "[parameters('RoleAssignments')[copyIndex()].Scope]",
                "principalType": "[parameters('RoleAssignments')[copyIndex()].PrincipalType]",
                "roleDefinitionId": "[parameters('RoleAssignments')[copyIndex()].RoleDefinitionId]",

                "principalId": "[if(and(empty(parameters('RoleAssignments')[copyIndex()].ResourceId), not(empty(parameters('RoleAssignments')[copyIndex()].PrincipalId))),
                                    parameters('RoleAssignments')[copyIndex()].PrincipalId,
                                    reference(parameters('RoleAssignments')[copyIndex()].ResourceId, '2020-10-01').PrincipalId)]"
              }
            }
          ]
        }
      }
    }

A: Problem with copy loops on zero-length arrays is known and Microsoft team has fixing it on its road map.
For now the solution is to move the loop into an nested deployment, pass the array as a parameter and condition that nested deployment with a check if array is not empty. Although I'm not sure if the deployment has to be inner scoped or not. For sure it will work with variable scope set to inner.

A: So there are a few ways to solve this. I had some difficulty getting Miq's suggestion to work the way I want. I did find another workaround though; use a variable in the template to ensure that the input array is ALWAYs populated
Notes:

*

*Regular "defaultValue" property on the parameter won't work, default values won't be applied if an empty array is passed. You need to use some if block to compute a single-element array as a default value for a no-op deployment

*ARM expands templates at "compile" time. So you get the "0 is out of bounds" error based on replacement values for the template, not when the actual deployment starts. The problem was I was trying to use a zero length copy AND I was referencing that copyindex() within special ARM functions/items like reference and dependsOn.
{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "RoleAssignments": {
            "type": "array"
        },
        "IdentityName": {
            "type": "string"
        },
        "StorageAccounts": {
            "type": "array"
        },
        "Enabled": {
            "type: "bool"
        }
    },
    "variables": {
        "IdentityResourceId": "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', parameters('IdentityName'))]",
         "ComputedRoleAssignments": "[if(greater(length(parameters('RoleAssignments')), 0),
                                              parameters('RoleAssignments'),
                                              createArray(createObject('AccountName', 'dummy', 'Name', 'dummy', 'ResourceId', 'dummy', 'RoleDefinitionId', 'dummy', 'PrincipalType', 'dummy', 'Scope', 'dummy', 'PrincipalId', 'dummy')))]"

    },
    "resources": [
        { // Everything related to role assignments chokes completely, even if I unroll the loop
            "dependsOn": [
                "[variables('IdentityResourceId')]",
                "storageaccountcopy"
            ],
            "copy": {
                "name": "RoleAssignmentsCopy",
                "count": "[length(variables('ComputedRoleAssignments'))]"
            }, // Conditionally deploy based on parameters, but use the value from computed variables
            "condition": "[and(greater(length(parameters('RoleAssignments')), 0), parameters('Enabled'))]",
            "type": "Microsoft.Storage/storageAccounts/providers/roleAssignments",
            "apiVersion": "2020-04-01-preview",
            "name": "[concat(variables('ComputedRoleAssignments')[copyIndex()].AccountName, '/Microsoft.Authorization/', guid(variables('ComputedRoleAssignments')[copyIndex()].Name))]",
            "properties": {
                "roleDefinitionId": "[variables('ComputedRoleAssignments')[copyIndex()].RoleDefinitionId]",
                "principalId": "[if(and(empty(parameters('ComputedRoleAssignments')[copyIndex()].ResourceId), not(empty(parameters('ComputedRoleAssignments')[copyIndex()].PrincipalId))),
                                variables('ComputedRoleAssignments')[copyIndex()].PrincipalId,
                                reference(variables('ComputedRoleAssignments')[copyIndex()].ResourceId, '2018-11-30').PrincipalId)]",
                "scope": "[variables('ComputedRoleAssignments')[copyIndex()].Scope]",
                "principalType": "[variables('ComputedRoleAssignments')[copyIndex()].PrincipalType]"
            }
        },
        {   // Everthing related to storage account provisioning works fine, this was existing code
            "condition": "[and(greater(length(parameters('StorageAccounts')), 0), not(parameters('SkipStorageAccountProvisioning')), equals(parameters('StorageAccountProvisioningDefault'), 'true'))]",
            "copy": {
                "name": "storageaccountcopy",
                "count": "[length(parameters('StorageAccounts'))]"
            },
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2019-06-01",
            "name": "[parameters('StorageAccounts')[copyIndex()].AccountName]",
            "location": "[resourceGroup().location]",
            "sku": {
                "name": "[if(equals(parameters('StorageAccounts')[copyIndex()].AccountTypeOverride, parameters('StorageAccountTypeOverrideDefault')), parameters('StorageAccounts')[copyIndex()].AccountType, parameters('StorageAccounts')[copyIndex()].AccountTypeOverride)]",
                "tier": "Standard"
            },
            "kind": "[parameters('StorageAccounts')[copyIndex()].AccountKind]",
            "properties": {
                "networkAcls": {
                    "bypass": "AzureServices",
                    "virtualNetworkRules": [],
                    "ipRules": [],
                    "defaultAction": "Allow"
                },
                "supportsHttpsTrafficOnly": true,
                "encryption": {
                    "services": {
                        "file": {
                            "keyType": "Account",
                            "enabled": true
                        },
                        "blob": {
                            "keyType": "Account",
                            "enabled": true
                        }
                    },
                    "keySource": "Microsoft.Storage"
                }
            }
        }
    ]
}


text:
Q: sudo: pam_authenticate: Conversation error Unable to execute shell script, receiving the errors
The shell script I wrote connects to remote server over ssh and executes commands.
sudo: no tty present and no askpass program specified
sudo: pam_authenticate: Conversation error

The User with which I'm establishing ssh connection has sudo privileges on the remote server but the user account is not defined locally within the system [User is authenticating using a centralized service].
While I may have overcome the first error
sudo: no tty present and no askpass program specified

by using "sudo -S" within the script the second error persists
I'm using sshpass utility to pass ssh password:
sshpass -p 'PASSWORD' ssh -n -o StrictHostKeyChecking=no $USER@$IPADDRESS "COMMANDS"

A: Use ssh -t to force TTY allocation so that sudo can ask for your password.


text:
Q: What is the correct syntax in AngularJS' ng-options? I got an array from rest-service and I am trying to create an option/dropdown from that data.
jsfiddle
$scope.reasons = [{
"languageLanguageId": {
    "languageId": 1,
    "lastUpdate": "2015-05-08T11:14:00+03:00",
    "name": "eng"
},
"returnText": "reason1",
"returnreasonId": 1}, {
"languageLanguageId": {
    "languageId": 1,
    "lastUpdate": "2015-05-08T11:14:00+03:00",
    "name": "eng"
},
"returnText": "reason2",
"returnreasonId": 2}, {
"languageLanguageId": {
    "languageId": 1,
    "lastUpdate": "2015-05-08T11:14:00+03:00",
    "name": "eng"
},
"returnText": "reason3",
"returnreasonId": 3

}];
HTML

<select ng-model="reasons" ng-options="p.reason as (p.returnText + '('+p.returnreasonId+')') for p in reasons"></select>

    <select ng-model="reasons" ng-options="p.returnreasonId as p.returnText for p in reasons"></select>

A: You miss ng-app and the controller declaration:

            <select ng-model="reason"  ng-options="p.returnreasonId as p.returnText for p in reasons"></select>
             {{reason}}

And the controller:
function TodoCtrl($scope) {
$scope.reasons = [{
    "languageLanguageId": {
        "languageId": 1,
            "lastUpdate": "2015-05-08T11:14:00+03:00",
            "name": "eng"
    },
        "returnText": "reason1",
        "returnreasonId": 1
}, {
    "languageLanguageId": {
        "languageId": 1,
            "lastUpdate": "2015-05-08T11:14:00+03:00",
            "name": "eng"
    },
        "returnText": "reason2",
        "returnreasonId": 2
}, {
    "languageLanguageId": {
        "languageId": 1,
            "lastUpdate": "2015-05-08T11:14:00+03:00",
            "name": "eng"
    },
        "returnText": "reason3",
        "returnreasonId": 3
}];
}

EDIT:
I was mading a mistake. In ng-model you put where do you want to store the selected value. In ng-options you put all the values you can select. Hope this help you.
http://jsfiddle.net/U3pVM/15559/
Check the docs for more info:
https://docs.angularjs.org/api/ng/directive/select


text:
Q: Changing the fragment on button click I am having fragments with some buttons i.e. next & previous. Whenever button is clicked, I need to move on to the next fragment. Actually I implemented this with ViewPager, so when user swipes it move on to next fragment. But how can I change the fragment just by clicking the buttons. Please note that, buttons are present in Fragment class not in FragmentActivity class.

A: If button is part of the fragment, then your parent activity shall implement interface your fragments would also understand. Then, when button is hit, it shall tell the parent activity about that and it shall replace the fragment. If button is part of activity layout then read about managing fragments with Fragment Manager and its transactions.

A: public class FragmentWithButtons extends Fragment {

    public interface Callbacks {
        void nextFragment();
        void previousFragment();
    }

    private static Callbacks sDummyCallbacks = new Callbacks() {
        void nextFragment() {
            // ignore
        }
        void previousFragment() {
            // ignore
        }
    }

    private Callbacks mCallbacks = sDummyCallbacks;

    private Button mPrevBtn;
    private Button mNextBtn;

    private View.OnClickListener mPrevBtnListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCallbacks.previousFragment();
        }
    }

    private View.OnClickListener mNextBtnListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCallbacks.nextFragment();
        }
    }

    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof Callbacks) {
            throw new IllegalStateException("Activity: " + activity + " must implement " + Callbacks.getCanonicalName());
        }
        mCallbacks = (Callbacks) activity;
    }

    public void onDetach() {
       super.onDetach();
       mCallbacks = sDummyCallbacks;
    }
}

public class ActivityWithButtonFragment extends Activity implements FragmentWithButtons.Callbacks {
    @Override
    public void previousFragment() {
        // switch to previous fragment using FragmentManager...
    }

    @Override
    public void nextFragment() {
        // switch to next fragment using FragmentManager...
    }
}

Also, check out http://developer.android.com/training/basics/fragments/communicating.html
That should give you an idea how to make the fragment-activity communication happen.


text:
Q: java.lang.UnsupportedOperationException at java.nio.ByteBuffer.arrayOffset? I need get the bitmap from IFrameCallback which was functioned to deal with the frame from a UVCCamera preview, but there's comes the exception:

java.lang.UnsupportedOperationException at
  java.nio.ByteBuffer.arrayOffset

private final IFrameCallback callback = new IFrameCallback() {
    @override
    public void onFrame(final ByteBuffer frame) {
        new Thread(new Runnable() {
            byte[] bytes = new byte[frame.remaining()];
            frame.get(bytes);

            if(bytes.length > 0) {
                int offset = frame.arrayOffset();
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, offset, bytes.length - offset);
                ......
            }
        }).start();
    }
}

or if I use createBitmap instead of decodeByteArray, I got this exception:

java.lang.RuntimeException: Buffer not large enough for pixels at
  android.graphics.Bitmap.copyPixelsFromBuffer

private final IFrameCallback callback = new IFrameCallback() {
    @override
    public void onFrame(final ByteBuffer frame) {
        new Thread(new Runnable() {
            Bitmap bitmap = Bitmap.createBitmap(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, Bitmap.Config.ARGB_8888);
            bitmap.copyPixelsFromBuffer(frame);
            ......
        }).start();
    }
}

Because the preview size is 1280 x 720, so the problem of RuntimeException can be ignored.
Is there any ideas about the first exception to get the arrayOffset from ByteBuffer?
PS: I know

UnsupportedOperationException - If this buffer is not backed by an
  accessible array

My point is: is there any other ways to get the arrayOffset, or if can't do that and how to solve the RuntimeException?

A: Well, since there's no a good solution, I had changed the way to get the bitmap from IFrameCallback.
Because I had applied the UVCCamera.PIXEL_FORMAT_NV21 format to the UVCCamera:

uvcCamera.setFrameCallback(frameCallback,
  UVCCamera.PIXEL_FORMAT_NV21);

So, I can get the bitmap just transform YuvImage:
private ChannelBufferOutputStream stream = new ChannelBufferOutputStream(MessageBuffers.dynamicBuffer());
......
private final IFrameCallback callback = new IFrameCallback() {
    @override
    public void onFrame(final ByteBuffer frame) {
        new Thread(new Runnable() {
            @override
            public void run() {
                byte[] bytes = new byte[frame.remaining()];
                frame.get(bytes);

                if(bytes.length > 0) {
                    YuvImage yuvImage = new YuvImage(bytes, ImageFormat.NV21, UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, null);
                    bytes = null;

                    if(yuvImage.getYuvData().length > 0) {
                        yuvImage.compressToJpeg(new Rect(0, 0, yuvImage.getWidth(), yuvImage.getHeight()), 80, stream);
                        Bitmap bitmap = BitmapFactory.decodeByteArray(stream.buffer().array(), 0, stream.buffer().array().length);
                        ......
                    }
                }
            }
        }).start();
    }
}


text:
Q: Increment dataframe column based on condition I have a dataframe and I want to create a new column based on a condition on a different column. Create the new column "ans" with 1 and increment based on the column "ix". In the "ix" column if the value is the same as the next one keep the "ans" column the same and if its different increment "ans"
Thank you for your answer, I am new to Python so I am not sure how to do this
      index   ix
        1     pa
        2     pa
        3     pa
        4     pe
        5     fc
        6     pb
        7     pb
        8     df

should result in:-
      index   ix  ans
        1     pa   1
        2     pa   1
        3     pa   1
        4     pe   2
        5     fc   3
        6     pb   4
        7     pb   4
        8     df   5

A: In [47]: df['ans'] = (df['ix'] != df['ix'].shift(1)).cumsum()

In [48]: df
Out[48]:
   index  ix  ans
0      1  pa    1
1      2  pa    1
2      3  pa    1
3      4  pe    2
4      5  fc    3
5      6  pb    4
6      7  pb    4
7      8  df    5


text:
Q: advanced custom fields update_field for field type: Taxonomy I need to insert a post via wp_insert_post and then add relevant post_meta - however, the WP admin has been customized with the excellent ACF.
I know I can add_post_meta in this way:
add_post_meta( $post_id, 'q_key_type', $q_key_type );

However, to make ACF happy, it's required to also use the "update_field" function - like so:
update_field( "field_52c737a413e07", $q_key_type, $post_id );

This method works fine, but I can't get a Taxonomy object to register correctly - I can get the value to save using add_post_meta - when I view the new post it does not recognise the Taxonomy - the value is empty, but in the postmeta table the value is stored correctly - what is missing is the correct field recognition.
I can save fields of the type "Text" and "User" correctly using these two methods.
Here is an image of two rows in the post_meta table - the first two are created by acf - the last two manually - they appear to be formatted identically:

I can only find one other reference to the same field name in the post_meta table - it contains an array with the following data - which seems to be the field set-up for acf:
Array (
    [key] => field_52c737a413e07
    [label] => Type
    [name] => q_key_type
    [type] => taxonomy
    [instructions] =>
    [required] => 0
    [taxonomy] => q_key_type
    [field_type] => select
    [allow_null] => 0
    [load_save_terms] => 1
    [return_format] => object
    [conditional_logic] => Array (
        [status] => 0
        [rules] => Array (
            [0] => Array (
                [field] => null
                [operator] => ==
                [value] =>
            )
        )
        [allorany] => all
    )
[order_no] => 3
)

So, the question is - where else is ACF saving the taxonomy data - I can't find anything in the terms tables?

A: I do need to add both post_meta:
add_post_meta( $insert_q_key_id, 'q_key_type', (int)$q_key_type ); // Q Key Type

And for ACF:
update_field( "field_52c737a413e07", (int)$q_key_type, $insert_q_key_id ); // Q Key Type

And the rest of the answer "should" be covered by wp_set_object_terms:
wp_set_object_terms( $insert_q_key_id, (int)$q_key_type, 'q_key_type', true );

However, this function is not fully available at the point I need it - so the answer was to create a simple replacement for this function:
     /**
     * simple wp_set_object_terms replacement as not available during API call
     *
     * @since       0.4
     * @global      Object      $wpdb
     * @param       integer     $object_id
     * @param       integer     $tt_id
     * @return      Mixed       Integer of inserted row on success | Boolean false
     */
    public function q_wp_set_object_terms( $object_id = null, $tt_id = null )
    {

        if ( ! $object_id || ! $tt_id ) { return false; }

        global $wpdb;

        if ( $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => (int)$object_id, 'term_taxonomy_id' => (int)$tt_id ) ) ) {

            return $wpdb->insert_id;

        }

        // if not ##
        return false;

    }

Which I can call using a static class instance ( as the method is part of a separate class in my case... ):
Q_Key::q_wp_set_object_terms ( $insert_q_key_id, (int)$q_key_type );

A: I've found that the update_field() function actually does the job for me, I don't know if it's been updated since to make that happen. All you have to watch out for is if you have a single choice (select) field or one that allows multiple selections - you need to pass through an array of taxonomy ID's if it's multiples, basically.
In example:
$field_key = 'field_xxxxxxxxxxxxxx';   //the field key of your chosen taxonomy field
$idarray = array("$termid->term_id");  //use an array to pass it multiple term IDs. Note that the term_id is in quotes, as it needs to be a string
$postid = '';                          //your post ID

update_field($field_key, $idarray, $postid);

The update_field() function will handle the serialize for you automatically based on the field settings, so you don't have to worry about anything else.
I've used this method to update both single and multiple taxonomy fields on the same post record, and I've tested that I can then query those results using the ACF-recommended ways of doing so, so it's definitely putting the data in correctly.
EDIT: one thing to bear in mind, you'll notice I've turned the term_id into a string by wrapping it in quotes - ACF stores the IDs as strings in serialized arrays, so this is essential or their suggested ways to query this data won't work (and when you go to end the field through wp-admin in the future, it will change it back to a string anyway).

A: Make sure you prefix the term ID of your custom taxonomy when using the update_field() function.
Example:
$post_id = "event_4"; // event (custom taxonomy) term ID = 4
update_field( 'my_field', 'my_value', $post_id );

The great ACF docs talk about this in the section 'Update a value from different objects': https://www.advancedcustomfields.com/resources/update_field/
ACF handles all the stuff around creating and syncing custom fields. No need to recreate that yourself with add_post_meta() etc.
I lost hours down this rabbit hole, really could use a RTFM! notification every 10 minute. ♂


text:
Q: How to remove blank spaces of treeview in c# winforms?
In above diagram the name 'sebin joseph' is in a treeview.
Make treeview ShowLines property to false.
How to remove left side space from treeview as in the above diagram?

A: You can remove the left side space by setting ShowRootLines property to false.
But note that it will also remove the plus/minus from the root nodes, so the only way to expand/collapse them would be the double click or using keyboard.

A: It is the Property Indent that you want to change:
treeView1.Indent = 5;

Also, ShowPlusMinus takes some of the space, if you want you can remove it:
treeView1.ShowPlusMinus = false;


text:
Q: the following print tree function does not work why? the code of my print function is -
void print(node* root){
    cout<<root->data<<" ";
    print(root->left);
    print(root->right);
    return;
}

where the structure of node used is:-
struct node
{
int data;
node* left;
node* right;
};

I can't figure out what the problem is.Is there any problem in the logic of the code?

A: Your recursive function is pretty close to working, but it is missing a base case, i.e. it does not tell the compiler what to do when root is nullptr. Adding an instruction to exit when root is nullptr will fix the problem:
void print(node* root) {
    if (!root) return;
    ... // The remaining code should remain the same
}

Note: the return statement at the bottom of a void function serves no particular purpose, and should be removed.