text:
Q: Getting set of values from array based on a condition I have a JavaScript array as shown below
var userMale = [];
var userData = [
                {userId: "100", userName: "John", gender: "M"},
                {userId: "101", userName: "Emma", gender: "F"},
                {userId: "102", userName: "Alex", gender: "F"},
                {userId: "103", userName: "Sam", gender: "M"}
              ]

I need to get all userIds in to a different array based on gender condition, i.e. All males should be in userMale array
I have written below code to achieve that. It works, however, I am looking to avoid for and if loops
for(var i=0; i<userData.length; i++) {
    if(userData[i].gender == "M") {
        userMale.push(userData[i].userId);
    }
}

console.log("userMale: ", userMale);

A: You can use filter.

var userData = [
                {userId: "100", userName: "John", gender: "M"},
                {userId: "101", userName: "Emma", gender: "F"},
                {userId: "102", userName: "Alex", gender: "F"},
                {userId: "103", userName: "Sam", gender: "M"}
              ]

let userMale = userData.filter(data => {
  return data.gender === "M"
})

console.log(userMale)

A: All you need is using filter function
var userData = [
                    {userId: "100", userName: "John", gender: "M"},
                    {userId: "101", userName: "Emma", gender: "F"},
                    {userId: "102", userName: "Alex", gender: "F"},
                    {userId: "103", userName: "Sam", gender: "M"}
                  ]

    let userMale = userData.filter(data => {
      return data.gender === "M"
    })

    let userFemale = userData.filter(data => {
      return data.gender === "F"
    })

A: You can use reject of Underscore.js
reject returns the values in list without the elements that the truth test (predicate) passes.
var userMale = _.reject(userData, function(item){ return item.gender != "M"; });

A: Since you want to filter and project the elements onto userId at the same time, an approach using Array.reduce seems the best fit. See here:

var userData = [
                {userId: "100", userName: "John", gender: "M"},
                {userId: "101", userName: "Emma", gender: "F"},
                {userId: "102", userName: "Alex", gender: "F"},
                {userId: "103", userName: "Sam", gender: "M"}
              ];

const convert = (data) => data.reduce((result, { userId, gender }) => {
  if (gender === 'M') {
    return result.concat(userId);
  }

  return result;
}, []);

var userMale = convert(userData);

console.log(userMale);

A: Using vanilla JavaScript :

var userData = [
  {userId: "100", userName: "John", gender: "M"},
  {userId: "101", userName: "Emma", gender: "F"},
  {userId: "102", userName: "Alex", gender: "F"},
  {userId: "103", userName: "Sam", gender: "M"}
];

function getMaleFemale ()
{
  // Create an array for each gender
  let male = [], female = [];

  // For each user, check if gender is F, if so, push id to female else to male
  userData.forEach( user => ( user.gender === 'F' ? female : male ).push( user.userId ) );

  // Return male and female
  return { male, female };
}

// Usage example
let { male, female } = getMaleFemale();

// Do something with male and female

console.log( 'male :', male );
console.log( 'female :', female );

A: A concise version of FK82's approach.
let userMale = userData.reduce((result, user) =>
    user.gender === 'M' ? result.concat(user.userId) : result
, [])


text:
Q: How should I represent an object whose instances share the same set of member function identifiers, but those identifiers specify different behaviors? I'm attempting to develop an open-source Python module for modeling task networks for discrete event simulation. The most fundamental component is the task object, which includes various data such as a distribution of possible task duration times, a release condition (criteria for initiating the task), a beginning effect (statements executed upon initiation of the task), an ending effect (statements executed upon conclusion of the task, such as beginning a different task), and so forth. While each task must include all of the above elements, the logic that they contain is unique to each task instance.
An entire task network could conceivably contain any number of tasks, so I would like to make it as easy as possible to create one. Therefore I was thinking of following an object-oriented paradigm and simply having a task class that users could instantiate, but I'm not sure how to implement the fact that there are different behaviors associated with each task instance. The obvious solution would be to make each task a subclass that overrides the main task class (or possibly just supplies a different class implementation file), but that seems silly because it would result in a ton of pointless singletons.
I also considered wrapping these methods in a dictionary that gets passed to the default constructor, but I don't want the process of defining a task to become unintuitive/require too many steps for the end user. I'm also trying to figure out how this task network data should be stored- raw Python, JSON (but as far as I'm aware this just runs into the same problem since JSON cannot represent the behavior associated with a task)? I'm sure this is probably a lot simpler than I'm making it out to be, but can anybody point me toward a good design pattern for this kind of situation? Thanks.

A: I've implemented a simulation framework for continuous time simulations (in Python) that allowed you to define custom behavior within an overall simulation framework, so I understand what you are getting at with the need for easy extensibility of your simulation objects.
One of the things about OO design is that inheritance gets a lot of play, but really it's composition and dependency injection that I've found to be more useful. From a design persepctive, your situation calls for something like a Strategy Pattern.
Here's some suggestions for making your Tasks user-friendly:

*

*Implement a "Task" as a class that takes other objects as arguments in its constructor. For example, based on your descirption, you'd feed it a task duration timer, a release condition checker (criteria for initiating the task), a beginning effect implementer (statements executed upon initiation of the task), an ending effect implementer (statements executed upon conclusion of the task, such as beginning a different task), and so forth.

*Implement each of the classes used in the Task constructor arguments as abstract classes - these are what you'll need to extend when you create new behavior. Note: If you are using a functional programming language (or where functions can be passed back and forth like objects), then you can skip the need for creating objects that encapsulate this behavior and just feed in functions directly (that's why I like Python and its ilk)

*The purpose of the Task class is to define the common interface that your simulation engine will expect to have available for working with all Tasks.

*Now, program your simulation engine so that you only allow yourself to use the interface defined in (1).

*Sub-class your behavior objects defined in (1) to represent the different behaviors you want (and use good, descriptive names for each sub-class). Try to think about how you can break up the behavior such that it is reusable (i.e., you don't have to constantly write new sub-classes, but just compose existing ones).

I hope this helps you organize your code. The key is to program to an interface not a concrete class. Then, you can hook in specific sub-classes (with the same interface) to change behavior as opposed to creating tons of Task sub-classes. You may even be able to use these components multiple times (bonus!)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retransmitting large packets with raw sockets Problem: On raw sockets, recvfrom can capture more bytes than sendto can send, preventing me from retransmitting packets larger than MTU.
Background: I'm programming an application that will capture and retransmit packets. Basically host A sends data to X that logs them and forwards them to B, all Linux machines. I'm using raw socket so I can capture all data and it's created with socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)).
Then, there's code waiting for and reading incoming packets:
const int buffer_size = 2048;
uint8_t* buffer = new uint8_t[buffer_size];
sockaddr_ll addr = {0};
socklen_t addr_len = sizeof(addr);
int received_bytes = recvfrom(_raw_socket, buffer, buffer_size, 0, (struct sockaddr*)&addr, &addr_len);

Packet processing follows and the loop is finished with sending packet out again:
struct sockaddr_ll addr;
memset(&addr, 0, sizeof(struct sockaddr_ll));
addr.sll_family = htons(AF_PACKET);
addr.sll_protocol = eth_hdr->type;
addr.sll_ifindex = interface().id();
addr.sll_halen = HardwareAddress::byte_size;
memcpy(&(addr.sll_addr), eth_hdr->dest_mac, HardwareAddress::byte_size);

// Try to send packet
if(sendto(raw_socket(), data, length, 0, (struct sockaddr*)&addr, sizeof(addr)) < 0)

The problem is that I don't expect to receive packets that are larger than Ethernet MTU (1500 bytes) and I shouldn't since I'm using raw sockets that process each packet individually. But sometimes I do receive packets larger than MTU. I thought it might be error in my code but Wireshark confirms that as shown in the image, so there must be some reassembly going on at lower level like network controller itself.

Well, ok then I don't think there's a way to disable this for just one application and I can't change the host configuration, so I might increase buffer size. But the problem is that when I call sendto with anything larger than MTU size (actually 1514B, becuase of eth header) I get 80: Message too long errno. And that's the problem stated above - I can't send out the same packet I received. What could be possible solution for this? And what buffer size would I need to always capture whole packet?
EDIT: I have just checked on the machines with ethtool -k interf and got tcp-segmentation-offload: on on all of them, so it seems that it's really NIC reassembling fragments. But I wonder why sendto doesn't behave as recvfrom. If the packets can be automatically reassembled, why not fragmented?
A side note: The application needs to send those packets. Setting up forwarding with iptables etc. won't work.

A: Your network card probably has segmentation offload enabled, which means the hardware can re-assemble TCP segments before they reach the OS or your code.
You can check whether that is the case by running ethtool -k.
While transparently capturing TCP traffic and re-transmitting it at such a low level is often more trouble than it is worth(one are often better off doing this at the application layer, terminate the TCP connection and set up a new TCP connection towards your host B), you cannot capture and re-send packets if your network card has messed with the packets. You need to:

*

*Turn off generic-segmentation-offload

*Turn off generic-receive-offload

*Turn off tcp-segmentation-offload

*Turn off udp-fragmentation-offload if you are also dealing with UDP

*Turn off rx-vlan-offload/tx-vlan-offload if your packets are VLAN encapsulated

*Possibly turn off rx-checksumming and tx-checksumming. It either works if both
are enabled, or it's broken wrt. RAW sockets if enabled, depending on your
kernel version and type of network card.

These can be turned on/off with the ethtool -K command, the exact syntax is described in the ethtool manpage.


text:
Q: O menor valor de uma lista composta do Python está me retornando 0 Estou analisando os dados de uma lista. Onde tenho que mostrar as pessoas cadastradas e o peso delas.
def function(foo):
    print(foo)

pessoas = list()
dados = list()
maiorpeso = menorpeso = pessoasC = 0
while True:
    dados.append(str(input('Nome: ')))
    dados.append(float(input('Peso: ')))
    pessoas.append(dados[:])
    dados.clear()
    pessoasC += 1
    resp = str(input('Quer continuar? [S/N]')).strip().upper()[0]
    if resp in 'N':
        break
for p in pessoas:
    if p[1] == 0:
        maiorpeso = menorpeso = p[1]
    else:
        if p[1] > maiorpeso:
            maiorpeso = p[1]
        if p[1] < menorpeso:
            menorpeso = p[1]
print(f'O maior peso é {maiorpeso}')
print(f'O menor peso é {menorpeso}')
print(f'Ao todo você cadastrou {pessoasC} pessoas.')

Eu tenho que informar qual o menor peso desses dados e o maior.
fiz o contador de maior e menor e especifiquei que o primeiro pese seria o menor e o maior.
caso não for pedi para analisar que se os próximos da lista composta que vierem vai ser caso seja maior ou menor que já especifiquei.
Que ficou assim:
for p in pessoas:
    if p[1] == 0:
        maiorpeso = menorpeso = p[1]
    else:
        if p[1] > maiorpeso:
            maiorpeso = p[1]
        if p[1] < menorpeso:
            menorpeso = p[1]

Quando porém no final só me retorna o MAIOR PESO corretamente,
quando retorna o MENOR PESO entre os dados das listas compostas, me retorna "0"
Ficando assim:
Nome: Rodrigo
Peso: 72
Quer continuar? [S/N]s
Nome: Elon Musk
Peso: 50
Quer continuar? [S/N]n
O maior peso é 72.0
O menor peso é 0
Ao todo você cadastrou 2 pessoas.

Já tentei mudar as ordem das listas, deixar elas separadas, mas ainda me retorna o valor 0
Não posso usar determinando que o menor peso seja 999 para me basear nesse valor.

A: O problema está na sua comparação. Você está usando a seguinte lógica:
    if p[1] < menorpeso:
        menorpeso = p[1]

Neste momento o menorpeso foi iniciado valendo 0, logo, nenhum peso que você inserir vai ser menor do que o valor atual e disparar o if.
Assim, altere a inicialização das variáveis:
maiorpeso, pessoasC = 0, 0
menorpeso = 999

Não entendi porque você está fazendo a seguinte lógica para printar:
print(f'O menor peso é {min(pessoas[1])}')

Eu trocaria para:
print(f'O menor peso é {menorpeso}')

A: Eu estava editando e acabei mudando a linha para:
print(f'O menor peso é {min(pessoas[1])}')

já foi alterado para {menorpeso}. Que era o que estava dando erro
Sobre a sua sugestão:
Na aula que estou tendo, não pode usar esse menor = 999, editei a pergunta colocando essa regra. Obrigado
La em cima eu determinei que a primeira posição do laço já é o menor e o maior peso.
(Porque ele vai ser o primeiro peso a ser acrescentado, ou seja ele no momento é o maior e o menor).
Senão:
Se:
os próximos números acrescentados forem menores ou maiores, o número que foi acrescentado vai receber a variável de maior ou menor peso.
A condição está dando certo para o maior peso. Porém para o menor peso está dando 0, mesmo eu colocando outros dados. Ou deixando só meu dado que já seria o menor e maior porque é único.


text:
Q: Acessa controller de um outro projeto na mesma solution Pessoal eu eu tenho 3 projetos na mesma solution:
KnockDocWeb, KanoDockModels e KnodockApi como mostra a imagem abaixo:

Quando eu compilo o projeto ele inicia o KanoDockWeb, porém eu quero Acessar uma Controller que esta no KanoDocApi  pelo KanoDockWeb.
Eu quero acessar uma controller chamada UsuarioApiController e o método Login;
Eu quero saber, na URL como eu acesso aquela controller?
Eu já tentei:
localhost:18459/UsuarioApi/Login
localhost:18459/api/UsuarioApi/Login
localhost:18459 /KnockDocApi/UsuarioApi/Login

Nenhum eu obtive êxito.
Mais uma coisa:
Quando eu dou um brakpoint em qualquer controller de KnockDocApi eu tenho a seguinte mensagem: The breakpoint will not currently be hit. No symbols have been loaded for this document.
Só ressaltando que o KanoDockApi é um projeto do tipo Web Api
Por favor, alguém me ajuda???
Agradeço desde já.

A: Robson, você está trabalhando com 2 projetos do tipo Web Application, para rodar, eles precisariam estar publicados (num servidor web ou numa web server virtual como está fazendo aí).
O que você está querendo fazer é o mesmo que 2 websites se comunicarem e trocarem informação.
Para conseguir rodar os 2, você teria que abrir uma porta para cada aplicação. Porém, mesmo assim não seria possível fazer essas chamadas, somente independentes. Suas tentativas não funcionam pois o KnockDocWeb está rodando na porta 18459, e não o KnockDocApi.
Te aconselho a criar um novo projeto do tipo Class Library que conterá a lógica desta controller que você está precisando chamar. Assim, ela pode ser compartilhada em ambos web sites.


text:
Q: Can I directly load text with numbers in CCC,CC format ? (K4) I have input with floats stored like 1000,50, ie. the decimal points are replaced by commas.
Is there an option in K to load these numbers directly into floats ?
When using
data:("SFF" ;";",";") 0:. filename
I get 0ns, of course, because the numbers are not recognized as floats.
I load them as strings now, and convert them using ssr like
c:.:' .q.ssr'[data;",";"."]
but that is extremely slow.
Is there an option somewhere to have K load these numbers in CCC,CC format as floats directly ? Normal format and ccc,cc format are not mixed, any file has just one of them.
If there is not, I imagine that it must by quite easy to replace a "." somewhere in the Q-binary where the load-function sits, with a ",", to get a version which loads these numbers. Has anybody tried that ? Or any other tip to load big files with these numbers in reasonable time ?
Cheers,
Co

A: If ssr' is slow for your task you may find this tiny function useful:
c2p:{c:-1_sums count each x;p:ss[r:raze x;","];r[p]:".";(0,c) _ r}

Update: an alternative version:
c2p:{p:ss[r:raze x;","];r[p]:".";(0,-1_sums count'[x])_r}

It concatenates all strings into a single long string, finds positions of commas, replaces commas with periods then splits that long string:
q)N:1000000
q)s:string[N?100000],'",",'string N?1000

q)\t r1:ssr'[s;",";"."]
4284
q)\t r2:c2p s
242
q)r1~r2
1b

A: I was thinking something like find (?) combined with indexing/applying
    q)N:1000000
    q)s:string[N?100000],'",",'string N?1000
    q)\ts {s[x;y]:"."}./:flip(til count s;s?\:",")
    967 52972144
    q)s
    "93912.794"
    "57144.788"
    "77809.659"
    "7839.47"
    "6363.523"
    "44761.244"
    "65699.712"

It's not perfect but that's the general idea. I'm sure there is an easier way...


text:
Q: Can't play HTML5 video using Flask I'm using Flask to serve .m3u8 and .ts files to simulate a vod stream.
The video player does not stream the file and shows an error (see the screenshot below).  I can't find a log of what error it is.

Is there a log message somewhere that I'm missing?  What is causing this and how can I fix it?

A: The development server runs in single threaded mode by default, meaning it can only handle one request at a time.  You are requesting streams of two files at once, the .m3u8 and the .ts.  You can pass threaded=True or processes=value greater than 1 to app.run to allow handling of multiple requests at once, but that comes with it's own problems.  The development server in general seems to have problems streaming html5 video and audio.  The real solution is to use an actual server such as Nginx or Apache to serve the media files.


text:
Q: Why do we need lseek when pread accepts offset value? I am having trouble to understand why lseek function is useful.
Assuming I got a parameter like this given to me from the user:
off_t offset = 10;

And I wanted to read from the offset 100 bytes.
I can use pread like this:
void * buf = malloc(100);
if (buf == NULL) { exit(1);}
int res = pread(file_id, buf, 100, offset);

On the other hand, I understand I can set the file with lseek like this:
off_t seek = lseek(file_id, offset, SEEK_SET);

So I believe I achieve reading using pread already. What did I miss regarding lseek in what it can do to help me read the file?

A: A function may have to read/write from/to a given file handle at a location that is not known to it (say current position), so you need to uncouple seeking from reading (or writing) because the caller may have a need to set the location.
More generally, many I/Os are just sequential so seeking is not necessary, while pread forces seeking.


text:
Q: Laravel updating polymorphic relation First of all, if there is a better way than using a polymorphic relation for this then please let me know. I have an appointments table that can have either a contact id or a relation id, depending on what the user selects when creating a new appointment. For this I am using a polymorphic relation, instead of having two seperate contact_id and relation_id columns.
Also, if there is a better way of doing the below (which I am currently doing in both my store and update methods) then please elaborate me.
    if ($request->has('contact_id'))
    {
        Contact::find($request['contact_id'])->appointments()->save($appointment);
    }

    if ($request->has('relation_id'))
    {
        Relation::find($request['relation_id'])->appointments()->save($appointment);
    }

The above basically checks if either a contact or relation was selected from one of the dropdowns, and if so, it should add that polymorphic relation to the newly inserted appointment.
But what I am doing in my update method, before I check if a contact_id or relation_id has been specified, is the following:
Appointment::where('id', $appointment->id)->update(['relationship_id' => '0', 'relationship_type' => '']);

So, I first empty the polymorphic relation, and then check for updates, because a contact or relation is optional. So when someone updates his/her appointment, and removes a at first specified contact or relation, it should be cleared from the database. There has gotta be a better way of going about this, and I know that what I am doing is not the way to go. But I am new to polymorphic relations and just trying to learn more about them. Any info will be appreciated :)


text:
Q: Jquery - find the next input:text element after a known element I have an id for a

Given the above, is it possible to find the next input:text element regardless of any other mark up in between . Is there a jQuery selector that I can use for this scenario?
For example :

     <input> // This is what I want to get to.

A: Check it out: moved this into a more complete question and answer
Based on the awesome answer by  @mrtsherman, I wrote this more complete solution:
(function( $ ){
 $.fn.findNext = function(sel) {
   var $result = $(sel).first();
   if ($result.length <= 0) {
     return $result;
   }
   $result = [];
   var thisIndex = $('*').index($(this));
   var selIndex = Number.MAX_VALUE; // Number.MAX_SAFE_INTEGER is not yet fully supported
   $(sel).each(function(i,val){
     var valIndex = $('*').index($(val));
     if (thisIndex < valIndex && valIndex < selIndex) {
       selIndex = valIndex;
       $result = $(val);
     }
   });
   return $result;
 };
})( jQuery );

Then you can use it as this:
$('#tagTR').findNext('input');

I would submit a PR for this on jQuery lib if I knew my code was properly optimized and if it was okay by Mr T Sherman there, meaning I think this should be a core method on jQuery! :P

A: I thought this question was very interesting. It seems others are reading this as, find the next input among siblings. But I read it as - find me the next input no matter what. I don't know if its in a sibling, a parent or a parent's sibling. This is what I came up with  based on feedback I received from this question.
http://jsfiddle.net/GesSj/1
//assume you know where you are starting from
var $startElement = $('#foo');

//get all text inputs
var $inputs = $('input[type=text]');

//search inputs for one that comes after starting element
for (var i = 0; i < $inputs.length; i++) {
    if (isAfter($inputs[i], $startElement)) {
        var nextInput = $inputs[i];
        alert($(nextInput).val());
    }
}

//is element before or after
function isAfter(elA, elB) {
    return ($('*').index($(elA).last()) > $('*').index($(elB).first()));
}

A: @Cawas - nice solution, but I suggest to use it not excessive, because of $('*') is expensive ;-)
Regardless of that, I extended it for my needs:
(function( $ ){
     $.fn.findNextOverall = function(sel, returnItselfIfMatched) {

       if(returnItselfIfMatched && $(this).is(sel)) return $(this);

       var $result = $(sel).first();
       if ($result.length <= 0) {
         return $result;
       }
       $result = [];
       var thisIndex = $('*').index($(this));
       var selIndex = Number.MAX_SAFE_INTEGER;
       $(sel).each(function(i,val){
         var valIndex = $('*').index($(val));
         if (thisIndex < valIndex && valIndex < selIndex) {
           selIndex = valIndex;
           $result = $(val);
         }
       });
       return $result;
     };
    })( jQuery );

So if returnItselfIfMatched is set true it returns itself, if it matches the selector itself. Useful, if you don't know, which element is calling and you are searching for exactly itself.

A: You cannot have a div tag in between TR's. It is not a valid markup.
To find the input element from the referred tr you can try this.
$('#tagTR').nextAll().filter(function(){
    return $(this).find('input:text').length > 1;
}).find('input');

A: You can use "next":
$("#tagTR").next("input")


text:
Q: Flutter - Unhandled exception I am learning flutter and I need so help / info regarding a weird behavior I'm experiencing.
Future<SharedPreferences> _preferences = SharedPreferences.getInstance();
final SharedPreferences preferences = await _preferences;
if (preferences.getString(USER_TOKEN_PREFERENCE) != '') {
  yield AuthentificationStatus.passed;
}

When the preferences are empty it's supposed to fire an Unhandled exception at the if line. Yet in debug on run the app is not crashing and the execution continues into the if statement.
When I evaluate in debug console an exception is indeed fired but if I wouldn't have noticed it if I hadn't checked...p
So why the execution is not stopping and the exception logged ?
Thanks

A:
execution is not stopping

because of your condition. if there is no data preferences.getString(USER_TOKEN_PREFERENCE) will return null and you check empty String in the condition. You should check
if (preferences.containsKey(USER_TOKEN_PREFERENCE) && preferences.getString(USER_TOKEN_PREFERENCE) != '') {
  yield AuthentificationStatus.passed;
}

or,
if (preferences.getString(USER_TOKEN_PREFERENCE) != null && preferences.getString(USER_TOKEN_PREFERENCE) != '') {
      yield AuthentificationStatus.passed;
    }

This article has a good example of SharedPreferences


text:
Q: Why can't the $\mathbb{Z}_2$ invariant be defined with a determinant instead of a pfaffian? I'm reading through Topological Insulators and Topological Superconductors by Bernevig and Hughes. I'm on Chapter 10, where he describes the original formulation of the $\mathbb{Z}_2$ invariant given in the original Kane-Mele paper. Both expositions are basically identical.
They consider an $N$-band model, and they denote the $N$-component wavefunction in $k$-space as $|u_k^n\rangle$, $n=1,..., N$. They define the quantity $P(k)=\text{Pf}(\langle u_k^n|\hat T|u_k^m\rangle)$, where $\hat{T}$ is the time-reversal operator. Then they argue the following things are true of $P(k)$:

*

*$|P(k)|=1$ if $k$ is a time-reversal-invariant momentum. This is because the matrix $\langle u_k^n|\hat T|u_k^m\rangle$ is unitary at such a point.

*If the phase of $P(k)$ winds around a loop, there is some $k_0$ inside that loop with $P(k_0)=0$. This is because $P(k)$ is a continuous function of $k$.

*If the phase of $P(k)$ winds $z$ times around $k_0$, then it winds $-z$ times around $-k_0$. This is because of time-reversal stuff.

The combination of those three facts makes them say that the total winding around the zeros of the $k_x>0$ half of the Brilloiun zone (mod 2) is a topological invariant. They argue that if we have a single vortex in the right half of the Brilloiun zone, the only way it can disappear is by combining with it's time reversed partner vortex in the left half of the Brilloiun zone. But because of point (3) above, the only place these vortexes can meet is at a time-reversal-invariant point, which is impossible because of (1).
I can accept all of that. But I don't understand: Why introduce the Pfaffian at all? The normal determinant should have all of those properties too! Since the determinant is just the pfaffian squared, it should be zero at the same time, it should have absolute value 1 at the same time, and if one winds the other should wind (twice as much, but still)! Why not just define $D(k)=\text{det}(\langle u_k^n|\hat T|u_k^m\rangle)$, and define your topological invariant to be the number of times $D(k)$ winds over half the Brillouin zone? You can just divide by two at the end and you get back the same answer, no? And who doesn't prefer determinants to pfaffians?
What am I missing here?

A: FWIW, I agree with you.
The index is
$$\frac{1}{2\pi i} \int_C d \vec k \cdot \nabla \log(P(k) + i \epsilon),$$
where $P(k)$ is the Pfaffian. The determinant is $D(k) = P(k)^2$ so we have
$$\log(D(k) + i2\epsilon) = \log((P(k) + i\epsilon)^2) = 2\log(P(k)+i\epsilon),$$
so the index is also
$$\frac{1}{4\pi i} \int_C d \vec k \cdot \nabla \log(D(k) + i \epsilon).$$
I think Kane and Mele might also agree with you. From their paper:

I wanted to point out that the fermionic ground state here is a Slater determinant, which is the point of the formula in the snippet for $P(\alpha)^2$. The determinant shows up because if you exchange indices of a matrix, ie. multiplying by a transposition matrix, the determinant picks up a minus sign. Thus, determinants are natural things for expressing fermionic ground states.
On the other hand, Pfaffians show up when computing (many-body) partition functions of real fermions. If we were computing some twisted partition function of this model, then we really would be concerned with its sign, since that would be precisely this $\mathbb{Z}_2$ invariant. It's an interesting general feature that winding invariants of single-particle ground states are captured by the many-body partition function. This is how the Pfaffian shows up in this classic (where you really need the Pfaffian and not the determinant), and I assume Kane and Mele had this on their mind when they wrote about the Pfaffian, see also Chiral Anomaly's answer. That square-root in the snippet looks reaaally spurious to me.

A: This is not my specialty, but the Bernevig and Hughes text looked interesting, so I spent some time with it.
I might be missing something, but as far as I can tell from the pieces I've digested, you're right. For the vorticity-based construction of the $Z_2$ invariant, the Pfaffian is being used only in what is presumably a connected region where it is continuous and nonzero (namely the boundary of the half-BZ); and in any such region, the Pfaffian can be reconstructed from its square except for an overall sign that has no bearing on the vorticity.
However, section 10.6 in the Bernevig and Hughes text highlights something that might help explain the general preference for using Pfaffians in this context, in addition to the reasons that were already mentioned in other comments/answers. Section 10.6 reviews two different ways of constructing the same $Z_2$ invariant, using the Pfaffians of two different quantities at different sets of points. Specifically, they define one matrix $m(\mathbf{k})$ that is antisymmetric for all $\mathbf{k}$ in the Brillouin zone (BZ), and they define another matrix $B(\mathbf{k})$ that is antisymmetric only at time-reversal invariant points. According to section 10.6, the same $Z_2$ invariant may be expressed in either of two ways:

*

*The modulo-$2$ vorticity of the Pfaffian of $m$ in half the BZ. This seems to be the construction used in the original Kane-Mele paper.

*The product of the signs of the Pfaffian of $B$ at those points where $B$ is antisymmetric, where the sign is defined by comparing it to one consistent branch of the square-root of the determinant. In this construction, knowing only the determinant of $B$ at those same points is clearly not sufficient.
These two constructions of the $Z_2$ invariant are also reviewed in "Notes on topological insulators," https://arxiv.org/abs/1501.02874. This paper and section 10.4 in the Bernevig and Hughes text both indicate that the second construction, the product-of-signs version, can also be applied in higher dimensions (not just 2d).
So instead of this:

And who doesn't prefer determinants to Pfaffians?

maybe Kane and Mele were thinking this:

And who doesn't prefer Pfaffians to determinants?

...because sometimes it does matter, and when it does, the Pfaffian is more informative.

A: Pfaffians are not weird objects but very natural for fermionic systems. They follow very similar rules as determinants.
You are missing the topological information in the sign of the Pfaffian. Taking a square root changes the topology of the manifold on which the function is single valued - just like the complex square root is properly defined on a topologically nontrivial Riemannian surface and not just on the plane of complex numbers.
Because of periodicity, winding over a Brillouin zone is well-defined but winding over half a Brillouin zone is path-dependent (without additional arguments).

A: TL;DR: Firstly, the main point is that one would always want to define & use the most fundamental/elementary objects in a theory, in OP's case, the Pfaffian (F), even if it doesn't matter in specific calculations, such as, e.g., the index $$\frac{1}{2\pi i}\oint_{\frac{1}{2}{\rm BZ}} \! \mathrm{d}{\rm Ln}\{{\rm Pf}(A(k))+i0^+\} ~=~ \frac{1}{4\pi i}\oint_{\frac{1}{2}{\rm BZ}} \! \mathrm{d}{\rm Ln}\{{\rm Det}(A(k))+i0^+\}, \tag{A}$$ which OP is asking about, cf. eq. (5) in Kane & Mele, and Ryan Thorngren's answer.
Why potentially lose information by working with composite objects? This is also the main point of Chiral Anomaly's answer.
Secondly in this answer, we want to stress the transformation properties (I) of the determinant (G), which somehow highlights its composite nature (H), in contrast to a fundamental/elementary determinant (C), cf. eqs. below.
I) One one hand, let $V$ be $n$-dimensional $\mathbb{C}$-vector space with a basis $(e_j)_{j=1, \ldots, n}$. Let $V^{\ast}$ be the dual vector space with the dual basis $(e^{\ast k})_{k=1, \ldots, n}$. Let
$$T~=~e_j~ T^j{}_k\otimes e^{\ast k}~ \in~V\otimes V^{\ast}~\cong~{\cal L}(V;V)\tag{B}$$
be a linear map from $V$ to $V$. Then the notion of determinant
$${\rm Det} (T)~:=~{\rm Det} (T^j{}_k)\tag{C}$$
is invariant under a change of basis
$$ e^{\prime}_k~=~e_j M^j{}_k, \qquad T^{\prime i}{}_{\ell}~=~M^i{}_j T^j{}_k(M^{-1})^k{}_{\ell}. \tag{D}$$
II) On the other hand, consider a 2-form
$$A~=~\frac{1}{2}e_j~ A^{jk}\wedge e_k~ \in~V\wedge V\tag{E}$$
with an antisymmetric matrix  $A^{jk}$. The Pfaffian can e.g. be defined via a Grassmann-odd Gaussian integral representation as$^1$
$$ {\rm Pf}(A)~:=~\int \!d\theta_n \ldots d\theta_1~
e^{\frac{1}{2}\theta_j A^{jk}\theta_k}.\tag{F}$$
Similarly it is not hard to show that the Grassmann-odd Gaussian integral representation
$${\rm Det}(A)~:=~\int \!d\theta_1 ~d\widetilde{\theta}_1 \ldots d\theta_n ~d\widetilde{\theta}_n~ e^{\widetilde{\theta}_j A^{jk}\theta_k} \tag{G}$$
reproduces the standard definition of a determinant, and that
$$  {\rm Det}(A)~=~{\rm Pf}(A)^2,\tag{H} $$
cf. e.g. my Math.SE answer here.
In contrast to the determinant (C), the Pfaffian (F) and the determinant (G) are not invariant, but transform as
$${\rm Pf}(A^{\prime})~=~{\rm Det}(M){\rm Pf}(A),\qquad {\rm Det}(A^{\prime})~=~{\rm Det}(M)^2{\rm Det}(A),\tag{I}$$
under a change of basis
$$ e^{\prime}_k~=~e_j M^j{}_k, \qquad A^{\prime i\ell}~=~M^i{}_j A^{jk}(M^t)_k{}^{\ell}, \tag{J}$$
cf. e.g. this Math.SE post.
--
$^1$ We use the sign convention that Berezin integration $$\int d\theta_i~\equiv~\frac{\partial}{\partial \theta_i}\tag{K} $$ is the same as differentiation wrt. $\theta_i$ acting from left. See e.g. this Phys.SE post.


text:
Q: Fatal error: Uncaught TypeError: Argument 1 passed Please anyone see my code and resolve this issue

Fatal error: Uncaught TypeError: Argument 1 passed to
  MyClass::__construct() must implement interface
  Magento\Framework\Session\SessionManagerInterface, none given, called
  in
  /home/dukaania/public_html/testing2/vendor/magento/module-checkout/view/frontend/templates/cart/shipping.phtml
  on line 132 and defined in
  /home/dukaania/public_html/testing2/vendor/magento/module-checkout/view/frontend/templates/cart/shipping.phtml:109
  Stack trace: #0

    use Magento\Framework\Session\SessionManagerInterface as CoreSession;

    class MyClass
    {

        protected $_coreSession;

        public function __construct(CoreSession $coreSession)
        {
            $this->_coreSession = $coreSession;

        }

      public function setValue($total_cost){
        $this->_coreSession->start();
        $this->_coreSession->setMessage($total_cost);

    }

    public function getValue(){
        $this->_coreSession->start();
        return $this->_coreSession->getMessage();

    }

}

$myclas = new MyClass();

 $myclas.setValue($total_cost);
 echo $myclas.getValue();

A: You issue at $myclas = new MyClass();
To initialize this class you have to use the object manager or have to inject that class to your class.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$myclass = $objectManager->create('{NameSpaceofClass}\MyClass');

A: simply run di compile
php -dmemory_limit=6G bin/magento setup:di:compile
AND
php bin/magento cache:clean && php bin/magento cache:flush
OR just run this command
If you are using Magento 2.1.9 or less than clear/remove
rm -rf var/generation folder
for above magento version run below command
rm -rf generated
and check your output again

A: Please replace your constructor with this and let's check if it works,
 public function __construct(
       \Magento\Framework\Session\SessionManagerInterface $coreSession
    ) {
        $this->_coreSession = $coreSession;
    }

As we are directly passing the SessionManagerInterface class in the constructor we don't need to include it.
Now run the following commands
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

A: Set/Get/Unset Value in Core Session:
protected $_coreSession;

public function __construct(
    -----
    \Magento\Framework\Session\SessionManagerInterface $coreSession
    ){
    $this->_coreSession = $coreSession;
    ----
}

public function setValue($total_cost){
    $this->_coreSession->start();
    $this->_coreSession->setMessage($total_cost);
}

public function getValue(){
    $this->_coreSession->start();
    return $this->_coreSession->getMessage();
}

public function unSetValue(){
    $this->_coreSession->start();
    return $this->_coreSession->unsMessage();
}

after this Run this SSH Command
  1. rm -rf var/*
  2. rm -rf generated/*


text:
Q: Retornar IQueryable no método Estou utilizando IdentityFramework no meu projeto e preciso criar um método que retorne um IQueryable
Segue abaixo estrutura da classe:
namespace MeuProjeto.Controllers
    public class UsuariosController : Controller
    {
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly UserManager<IdentityUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly AppSettings _appSettings;

        public UsuariosController(SignInManager<IdentityUser> signInManager,
                                  UserManager<IdentityUser> userManager,
                                  RoleManager<IdentityRole> roleManager,
                                  IOptions<AppSettings> appSettings)
        {
            _signInManager = signInManager;
            _userManager = userManager;
            _roleManager = roleManager;
            _appSettings = appSettings.Value;
        }

        public IQueryable<Usuario> ObterUsuarios1()
        {
            return _userManager.Users
                    .Select(u => new Usuario() { Id = u.Id, Name = u.UserName, Email = u.Email, Claims = ???? })
                    .OrderBy(u => u.Name);
        }

        public async Task<IQueryable<Usuario>> ObterUsuarios2()
        {
            var lista = new List<Usuario>();
            var usuarios = _userManager.Users.ToList();
            foreach (var usuario in usuarios)
            {
                var claims = (await _userManager.GetClaimsAsync(usuario)).Select(c => new UsuarioClaim { Type = c.Type, Value = c.Value });
                var novoUsuario = new Usuario() { Id = usuario.Id, Name = u.UserName, Email = usuario.Email, Claims = claims };
                lista.Add(novoUsuario);
            }

            return lista.AsQueryable();
        }
    }
}

Estrutura de Usuario e UsuarioClaim:
public class Usuario
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public IEnumerable<UsuarioClaim> Claims { get; set; }
}

public class UsuarioClaim
{
    public string Value { get; set; }
    public string Type { get; set; }
}

Preciso fazer com que um dos métodos funcionem.

*

*No Método ObterUsuarios1 eu não consegui adicionar as Claims, mas
está retornando IQueryable corretamente.

*No método ObterUsuarios2 eu consegui adicionar as Claims, mas
está dando um erro quando tento utilizar o retorno.

Mensagem de erro utilizando o retorno de ObterUsuarios2 (AsQueryable):
System.InvalidOperationException: The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IAsyncQueryProvider can be used for Entity Framework asynchronous operations.

A: Já tentou o código abaixo?
 public IQueryable<Usuario> ObterUsuarios()
        {
            return _userManager.Users
                    .Include(u => u.UsuarioClaim)
                    .OrderBy(u => u.Name);
        }


text:
Q: How to get the AppStore back on my iPad How do I get back my AppStore back on my mini iPad. Seems to have disappeared. Kindly help. I cannot see the icon and I can't find out how to install it back.

A: You can't delete the AppStore App. I must have moved on another page or in a folder.
You can access it by searching from the spotlight search bar ! (slip down from the springboard)


text:
Q: when called from xcode, my bash script does not get environment variables in .bash_profile In Xcode 5 I have a build phase that executes a bash script.
My problem is that when that script is called from Xcode, it does not have access to the environment variables that I have set in my .bash_profile.
I have tried to created an environement.plist file from xcode and duplicate my environment variables there, but still the bash script remains unaware of my variables.
One thing I can do is call source ~/.bash_profile from myscript. But in my bash_profile I have lines like
export PATH=/some/new/path:$PATH

so calling source ~/.bash_profile everytime xcode compile my project, will prepend /some/new/path to my path over and over again.
How do I make my script aware of environment variables when called from xcode?

A: There is nothing wrong with sourcing ~/.bash_profile. When Xcode runs your script, it calls the script, the script prepends /some/new/path to the PATH, compiles your project and exits. When Xcode runs your script again, the new script doesn't have the updated PATH, because it's a different process from the earlier run. So /some/new/path is not prepended "over and over again", it only happens once in the lifetime of the script. Each compilation triggers a completely new script, their environment is not shared, PATH does not grow forever.


text:
Q: Flash Game Error #1063 I've been coding the beginnings of a pretty basic game and I have hit a wall. When I compile my code, the game runs but spits out a run-time error:

ArgumentError: Error #1063: Argument count mismatch on block(). Expected 2, got 0.at flash.display:: Sprite/constructChildren()at flash display::Sprite()at flash.display::MovieClip()at AvoiderGame().

Here is my document class titled AvoiderGame:
package
{
    import flash.display.MovieClip;
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    public class AvoiderGame extends MovieClip
    {

        public var avatar1:avatar;
        public var gameTimer:Timer;
        public var army:Array;

        public function AvoiderGame()
        {
            army=new Array();
            var newblock= new block(100,-15);
            army.push(newblock);
            addChild(newblock);

            avatar1=new avatar();
            addChild (avatar1);
            avatar1.x=mouseX;
            avatar1.y=mouseY;

            gameTimer=new Timer(25);
            gameTimer.addEventListener(TimerEvent.TIMER, onTick);
            gameTimer.start();

        }

        public function onTick(timerEvent:TimerEvent):void
        {
            if ( Math.random() < 0.1 )
            {
                var randomX:Number = Math.random() * 400;
                var newblock:block = new block( randomX, -15 );

                army.push( newblock );
                addChild( newblock );
            }

            avatar1.x = mouseX;
            avatar1.y = mouseY;

            for each (var block1:block in army)
            {
                block1.moveDownaBit();

                if (avatar1.hitTestObject(block1))
                {
                    gameTimer.stop();
                }
            }
        }
    }
}

Finally here is my block class which seems to have the constructor function causing the error.
package
{
    import flash.display.MovieClip;

    public class block extends MovieClip
    {
        public var block1:block;

        public function block(startX:Number, startY:Number)
        {
            x=startX;
            y=startY;
        }

        public function moveDownaBit():void
        {
            y=y+3;
        }
    }
}

All I'm trying to get to work is a series of enemies spawning randomly on the stage and falling down without the avatar icon hitting it. I would appreciate any help I can receive greatly.

A: That sounds like you've got an instance of block on the stage, so Flash is creating it without passing startX and startY. You can either remove any pre-placed blocks, or just add default values to the constructor:
public function block(startX:Number = 0,startY:Number = 0)
{
    x = startX;
    y = startY;
}


text:
Q: MacBook is attacked but can't find any threats Recently, I was installing an unofficial software on my mac. It's a mistake, I know, but I was so confident that I can register if something is going wrong.
Coming to the point, I give the permission to run from an unidentified developer and start the installation. However, I did noticed that the installation is weird, you can tell with a little bit of experience, so I stoped it immediately, but it was too late. My mac is going too slow, even when I'm just browsing the internet and not doing any hard work, it's getting overheated and I also noticed that the battery is wasted significantly fast, even on sleep mode. So, I'm pretty sure that there is some sort of viruses running in the background.
I did tried several antivirus programs, malware scanners etc. but it all says the same "No viruses or malware found". Really don't know what to do, anyone have suggestions for advanced scanners or something like that? Just without formatting the device please.
Here is a screenshot from my Activity Monitor:

A: "Going slow" is not really an indicator of malware. Most malware can do its job without using significant CPU, and malware designers want their software to be unnoticed.
If several malware apps have said "it's not malware", then that's probably true.
It's much more likely that there are other problems with your Mac. Check Activity Monitor, and see what is using excessive CPU. Remove third-party Launch Agents or any other software that runs in the background. Test a new user account, and see if that it better. If so: it's a user account problem.
Make sure you have low memory pressure (also in Activity Monitor), and that you have plenty of free disk space.

A: Try Clean My Mac. It checks for viruses and deletes them, as well as uninstalls any unnecessary files. It can also act as an app uninstaller, making sure every file and folder related only to that app is deleted. It generally removes about 3 gigabytes a week from my main computer, and it hasn't deleted any thing I haven't wanted it to yet. The only downside is that it cost $40 to get a key, but it is totally worth it if you are using your Mac as your primary computer. It mainly deletes outdated stuff, but it allows you to choose what to and what not to delete. It does not constantly monitor your system, it just scans it when you open the app and tell it to. It lets you see what you are deleting just in case you don't want to delete anything.


text:
Q: IOS xcode how to redirect from uiwebview into another controller view contain native code I have an IOS app which shows a UIWebview , i want inside webview a button that permit users to go another view controller inside app that contain native code .. any suggestions ??
thanks in advance ..

Hi Welcome to Webpage

            <input type='button' style='width:90px;height:30px;' onclick='locationChange()' value='VoiceRecorder'>

import UIKit
import CoreLocation

class ViewController: UIViewController  , UIWebViewDelegate , CLLocationManagerDelegate  {
     var locationManager:CLLocationManager!
    @IBOutlet var WebView: UIWebView!
    @IBOutlet var myActivityIndicator: UIActivityIndicatorView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        loadaddress()

    }

    func loadaddress()
    {
        let requestURL = NSURL (string: "http://codersaddicts.com/Mahdi/TPA1/index.php")
        let request = NSURLRequest(url: requestURL as! URL);
        WebView.loadRequest(request as URLRequest)
    }

    func webViewDidStartLoad(_ WebView: UIWebView)
    {
        myActivityIndicator.startAnimating()
    }
    func webViewDidFinishLoad(_ WebView: UIWebView)
    {
        myActivityIndicator.stopAnimating()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Image to show the two views i have created


text:
Q: TikZ Make a graphical balance for equations I'd like to be able to draw a white = inside of the triangle, be able to rotate the balance and the equation and place the equations symmetrical yet not to close to the edge. It's quite hard for me.
\documentclass{beamer}
\usepackage{tikz}
\begin{document}
\begin{frame}
\begin{center}
$2+2$ \hfill $4$
\begin{tikzpicture}
\draw[red!50!blue!70!white,ultra thick](-5.4,1) -- (5.4,1);
\fill[red!50!blue!70!white] (0,0.98) -- (-0.4,0) -- (0.4,0);
\end{tikzpicture}
\end{center}
\end{frame}
\end{document}

A: With the new TABcline option to tabstackengine (2018/03/05 (V2.10)), this becomes a nice exercise.  The support macros \balanceindent and \lever control the indent of text from the ends of the lever and the lever to fulcrum distance, respectively.  The lever thickness is controlled by \fboxrule which is defined locally inside the main macro.  The main routine is
\balance[fulcrum inset]{left terms}{right terms}

The default fulcrum inset is ?.  If it is set to > or <, the lever will be made to tilt in the appropriate direction.
Here's the MWE:
\documentclass{article}
\usepackage[TABcline]{tabstackengine}
\usepackage{graphicx}
\newcommand\Leqtriangle[1][=]{%
  \stackengine{2pt}{\Ltriangle}{$\scriptstyle#1\mkern1mu$}{O}{c}{F}{F}{L}}
\newcommand\Ltriangle{\LARGE$\triangle$}
\newcommand\balanceindent{\kern10pt}
\newcommand\lever{\kern7em}
\newcommand\balance[3][?]{{%
  \TABbinary\TABstackMath\setstackgap{S}{0pt}\fboxrule=1pt\relax%
  \def\bangle{4}% TILT ANGLE
  \def\bsign{}%
  \ifx>#1\def\bsign{-}\else\ifx<#1\else\def\bangle{0}\fi\fi%
  \rotatebox[origin=b]{\bsign\numexpr-\bangle}{%
    \tabularShortstack{lcr}{\mathstrut\balanceindent#2 && #3\balanceindent\\%
    \TABcline{1-3}\lever &%
    \rotatebox[origin=t]{\bsign\numexpr\bangle}{\Leqtriangle[#1]} & \lever}}}}
\begin{document}
\balance[>]{2 + 2(4-3)}{6 - 6/2}

\balance[=]{2 + 2}{4}

\balance[<]{2 + 3}{7}

\balance{y}{42}
\end{document}

A: See the update with a quick generating command at the end of this post.
The center of a triangle could be easily obtained with the barycentric coordinate system provided by TikZ.
Define the three corner nodes of the triangle and say
\node[color=white]  at (barycentric cs:A=1,B=1,C=1) {=};

in order to use weighted vertices (here all having the same weight, which corresponds to the true barycenter of the triangle then.
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{frame}
\begin{center}
$2+2$ \hfill $4$
\begin{tikzpicture}
\coordinate (A) at (0,0.98);
\coordinate (B) at (-0.4,0);
\coordinate (C) at (0.4,0);
\draw[red!50!blue!70!white,ultra thick](-5.4,1) -- (5.4,1);
\fill[red!50!blue!70!white] (A) -- (B) -- (C);
\node[color=white]  at (barycentric cs:A=1,B=1,C=1) {=};
\end{tikzpicture}
\end{center}
\end{frame}
\end{document}

Update
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\begin{frame}
\begin{center}
\begin{tikzpicture}
\def\winkel{20}
\coordinate (A) at (0,0.98);
\coordinate (B) at (-0.4,0);
\coordinate (C) at (0.4,0);
\coordinate (rodleft) at (-5.4,1);
\coordinate (rodright) at (5.4,1);
\coordinate (balancetop) at (0,1);
\coordinate (rotatedleft) at ($(balancetop)-(\winkel:5)$);
\coordinate (rotatedright) at ($(balancetop)+(\winkel:5)$);
\draw[red!50!blue!70!white,ultra thick] (balancetop) -- (rotatedleft);
\draw[red!50!blue!70!white,ultra thick] (balancetop) -- (rotatedright);
\node[rotate=\winkel,above right] (LHS) at ($(rotatedleft) + (\winkel:1)$) {$2+2$};
\node[rotate=\winkel,above left] (RHS) at ($(rotatedright) - (\winkel:1)$) {$3$};
\fill[red!50!blue!70!white] (A) -- (B) -- (C);
\node[font=\large,color=white]  at (barycentric cs:A=1,B=1,C=1) {$\neq$};
\end{tikzpicture}
\end{center}
\end{frame}
\end{document}

2nd update
The macro \equationbalance checks the arguments #3 and #4 and prints either = or \neq, however, the angle must be specified still. I don't find it useful to calculate the angle from the values of #3 or #4 (from the Physics view: the angle would be not constant anyway, if there both sides of the scale hold unequal values)
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{calc}

% First opt arg: angle
% 2nd arg: inward shift of the labels
% 3rd arg: left hand label
% 4th arg: right hand label
\newcommand{\equationbalance}[4][0]{%
  \begin{tikzpicture}
    \def\winkel{#1}
    \coordinate (A) at (0,0.98);
    \coordinate (B) at (-0.4,0);
    \coordinate (C) at (0.4,0);
    \coordinate (rodleft) at (-5.4,1);
    \coordinate (rodright) at (5.4,1);
    \coordinate (balancetop) at (0,1);
    \coordinate (rotatedleft) at ($(balancetop)-(\winkel:5)$);
    \coordinate (rotatedright) at ($(balancetop)+(\winkel:5)$);
    \draw[red!50!blue!70!white,ultra thick] (balancetop) -- (rotatedleft);
    \draw[red!50!blue!70!white,ultra thick] (balancetop) -- (rotatedright);
    \node[rotate=\winkel,above right] (LHS) at ($(rotatedleft) + (\winkel:#2)$) {$#3$};
    \node[rotate=\winkel,above left] (RHS) at ($(rotatedright) - (\winkel:#2)$) {$#4$};
    \fill[red!50!blue!70!white] (A) -- (B) -- (C);
    % Works for simple integer expressions only
    \ifnum\numexpr#3=#4
    \node[font=\large,color=white]  at (barycentric cs:A=1,B=1,C=1) {$=$};
    \else
    \node[font=\large,color=white]  at (barycentric cs:A=1,B=1,C=1) {$\neq$};
    \fi
  \end{tikzpicture}%
}

\begin{document}
\begin{frame}
\begin{center}
\equationbalance[10]{1.5}{2+2}{3}
\end{center}
\end{frame}
\end{document}


text:
Q: iOS VoIP application exit from backround after a while I set my .plist to run the application while background and I've set up the connection like this:
CFReadStreamRef     readStream;
CFWriteStreamRef    writeStream;

//open c socket:
int rc; // ret code of s.c.
int my_socket;
struct sockaddr_in dest_addr;

my_socket = socket(AF_INET, SOCK_STREAM, 0);
assert(my_socket >= 0);

dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(SERVER_LOC_PORT);
dest_addr.sin_addr.s_addr = inet_addr(SERVER_IP);

memset(dest_addr.sin_zero,
       '\0',
       sizeof dest_addr.sin_zero);

rc = connect(my_socket,
             (struct sockaddr *)&dest_addr,
             (socklen_t) sizeof(dest_addr));

if(rc != 0){
    return NO ;
}

NSLog(@"Start connection");

// Open a stream based on the existing socket.  Then configure
// the stream for async operation.

CFStreamCreatePairWithSocket(NULL, my_socket, &readStream, &writeStream);
assert(readStream != NULL);

self.networkStreamIn = (NSInputStream *) readStream;
self.networkStreamOut = (NSOutputStream *) writeStream;

//releasers
CFRelease(readStream);
CFRelease(writeStream);

self.networkStreamIn.delegate = self;
self.networkStreamOut.delegate = self;
BOOL res = [self.networkStreamIn setProperty:NSStreamNetworkServiceTypeVoIP
                   forKey:NSStreamNetworkServiceType];

if(!res){
    NSLog(@"Cannot connect") ;
    // @TODO: Error handling here
}

[self.networkStreamIn scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[self.networkStreamIn open];
[self.networkStreamOut open];

Also I set my stream() to be called when data is received.
Then I read an write from/in server.
It's work. on backgrount too. but after few minutes (in backgound mode only!) the server print into the log "java.net.SocketTimeoutException: Read timed out". and no more connection with the client (iOS device).
I've not set background handler to retiain connection - but it should be work without this handler (I think..)!
Did I missed something with this socket configurations?

A: VoIP app has restrictions at background. In short:

*

*While app is at background, it is suspended most of the time

*While it is suspended, the OS keeps your socket alive

*App wakes up from suspention for: incoming data, network changes and performing KeepAlive to allow the server know its alive

*While Audio is active (There is an active VoIP call), app may run fully at background.

Here is a link to a more detailed answer on another thread:
VoIP app behavior at background


text:
Q: corrupted images after uploading through 2G/GSM network I built an app that take pictures and upload them to THe server, i'm using Apache commons FTP library to upload them.
when i'm using wifi the images are uploaded without any issues...
but when i'm using 2G mobile network to send them half of them the server recieve them as corrupted images.
i set the file type to binary file type.
is there a way to determine whether the images got corrupted or not.

A: In order to determine whether the images got corrupted or not, compare the images received by the server with the corresponding ones on your Android device.
In order to determine why the images got corrupted, you may run WireShark or tcpdump on the server and snoop an upload. Careful examination should reveal if the problem is

*

*within the server software (you see the complete image in the network traces), or

*in the device or the network (you see a broken image in the network traces).

You also may experiment with image sizes (in terms of bytes) and check if there is a size boundary from which on you see problems. That might give clues on where to look further


text:
Q: jhipster react form onChange state Argument of type '{ [x: number]: any; }' is not assignable I'm new to React and having some trouble with jsx when setting state in a form with two fields that does an ajax call to put a json object (response data) in the state's field3. I have the following:
export interface IMyClassState {
    field1: string;
    field2: string;

    field3: object;
}

export class MyClass extends React.Component<IMyClassProps, IMyClassState> {
    state: IMyClassState = {
        field1: '',
        field2: '',

        field3: null
    }

    ...

    onSubmit = e => {
        e.preventDefault();
        ...
    }

    onChange = e => {
        this.setState({ [e.target.name]: e.target.value });
    };

    ...

    render() {
        return(
            <form onSubmit={this.onSubmit}>
                <input type="text" id="field1" name="field1" onChange={this.onChange}/>
                <input type="text" id="field2" name="field2" onChange={this.onChange}/>
            </form>
        );
    }
};

In an example with only two fields I suppose I could just have different onChanges like so:
<input type="text" id="field1" name="field1" onChange={this.onChangeField1}/>
...

but if I had 100 fields it'd be a problem, which is why I'm trying to get the state field's name directly from e.target.name in my onChange. This however, gives me the error:
Argument of type '{ [x: number]: any; }' is not assignable to parameter of type 'IMyClassState | Pick<IMyClassState, "field1" | "field2"

How do I get rid of this error? Is it possible to solve elegantly with a one liner like I've tried?

A: The first part is to fix the type of e. We can use a type query to tell typescript the type is the same as the onChange of input: onChange: JSX.IntrinsicElements['input']['onChange']
The second part is to fix the object literal which is inferred to be { [x: string]: string; }. Ideally we could tell the compiler that e.target.name is a key of IMyClassState
onChange: JSX.IntrinsicElements['input']['onChange'] = (e) => {
    this.setState({ [e.target.name as keyof IMyClassState]: e.target.value });
};

The above code does not work because typescript will still infer the type of the object literal to be { [x: string]: string; }. The only way to get the compiler to infer the type we want is for e.target.name to be cast to a specific field of IMyClassState.
onChange: JSX.IntrinsicElements['input']['onChange'] = (e) => {
    this.setState({ [e.target.name as "field1"]: e.target.value }); // Ok now
};

While it's not ideal to lie to the compiler this is the simplest option. Another option is to just cast the object literal.
onChange: JSX.IntrinsicElements['input']['onChange'] = (e) => {
    this.setState({ [e.target.name]: e.target.value } as any as IMyClassState);
};


text:
Q: T-SQL inconsistent sp_send_dbmail results I have a job set up on a handful of servers (all in the same domain). The job sends an email via sp_send_dbmail, and the subject of the email should look like the following format:
=servername (ip address)= Weekly DB Backup to Azure Report

So as a potential example (obviously replace the 0s with actual IP address of the server SQL is running on):
=SQLMACHINE (000.000.000.00)= Weekly Backup to Azure Report

DBmail is configured, and I created the backup job. The T-SQL job step that sends the email has the following script:
SET NOCOUNT ON
DECLARE @ipAddress NVARCHAR(100)

SELECT @ipAddress = local_net_address
FROM sys.dm_exec_connections
WHERE Session_id = @@SPID;

DECLARE @subjectText NVARCHAR(255) = N'=' +
    CAST(LEFT(@@SERVERNAME, CHARINDEX('\', @@SERVERNAME)-1) AS NVARCHAR) + N'.' +
    CAST(DEFAULT_DOMAIN() AS NVARCHAR) + N' ('+ @ipAddress +
    N')= Weekly DB Backup to Azure Report'

DECLARE @tableHTML NVARCHAR(MAX) = N'this part works fine'

exec msdb.dbo.sp_send_dbmail @profile_name = 'Production Mail',
                             @recipients = 'xxx@xxx.com',
                             @subject = @subjectText,
                             @body = @tableHTML,
                             @body_format = 'HTML'

Each of the 5 servers has the same exact job definition - I have 1 source-controlled definition of the job that I use to create the job on each server.
Each week when the jobs run, most of them kick off an email with the expected subject line. Every couple weeks though, an email comes through with the subject SQL Server Message, which is what happens when no subject has been specified. Each time this happens, it could be on any one of the five servers. I'm not sure what's happening, since it should have a subject each time it executes.
EDIT:
This is happening because the @ipAddress variable is null. No idea why
SELECT @ipAddress = local_net_address
FROM sys.dm_exec_connections
WHERE Session_id = @@SPID;

would return null though...

A: local_net_address will be always NULL if a connection is not using the TCP transport provider. It's likely you use 'Shared memory' in net_transport.
You can force to use TCP when you create a connection, so local_net_address will be populated. E.g. when you open SSMS, you can specify the server name as "tcp:ServerName\InstanceName"
Below also can be used to retrieve the server properties (using TCP transport):
SELECT
   CONNECTIONPROPERTY('net_transport') AS net_transport,
   CONNECTIONPROPERTY('protocol_type') AS protocol_type,
   CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
   CONNECTIONPROPERTY('local_net_address') AS local_net_address,
   CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
   CONNECTIONPROPERTY('client_net_address') AS client_net_address

A: Your @ipAddress value could be null
Replace this code:

 + @ipAddress +

with this code

+ ISNULL(@ipAddress,'0.0.0.0') +

to prove that is the issue.


text:
Q: Brackets appearing when bot sends reply (discord, python) I'm making a 8ball bot on discord -- out of boredom, but that's besides the point. Whenever I get it to send the reply, brackets appear where the answer should just be plain, anyone knows how to fix it?
This is my code
@bot.command(name='8ball', help='Gives the answer to any of your questions')
async def quotelist(ctx):
    quotelist = [
        'As I see it, yes.',
        'Ask again later.',
        'Better not tell you now.',
        'Cannot predict now.',
        'Concentrate and ask again.',
        'Don\'t count on it.',
        'It is certain.',
        'It is decided so.',
    ]

    response = random.choices(quotelist)
    await ctx.send(response)

bot.run("Nxxx")```

A: random.choices returns a list of choices, then discord.py converts the list to a string, which is where the brackets come from. You're looking for random.choice (note the lack of an s), which returns only one element from the list.


text:
Q: How can I simulate a model electronic hole? Suppose I can solve time-dependent Schrödinger equation for several 1D particles (currently 3). I'd like to see, what an electronic hole is and how it behaves — in a series of numerical experiments.
I know that a hole is lack of electron in a sea of occupied electron states, but I think I don't quite understand, what it really is: do I need to have electron repulsion to see any useful effects? Do I need much more electrons for such a simulation than 3? What initial conditions should I use to see the hole? I'm thinking of using a model "crystal" potential with 3 cells — would this be enough?
As an example of what I'd like to actually see is exciton, namely how its wave packet wanders across the crystal. For an electron in conductivity band, taken as a wavepacket, I'd expect it to look like increase in probability density in the place where the wavepacket is located, and for hole it might be a similar decrease in charge density, so I guess the exciton should look like an increase of charge density in a wave packet and decrease around this wave packet. Is it right? Or is it actually invisible as a charge density?
Another example would be seeing excitonic states in band gap, but for this I don't really understand, what to compare it with — should I use some single-particle approximation to compute band structure without excitonic states, and then after computation of true energy states search for extra states in band gap, or how should I go about finding them?

A: I think you're overcomplicating things here.  The whole point of the hole-model is to simplify the picture... instead of trying to model an entire sea of electrons, you model the hole itself.
For example, consider a bubble rising in a glass of cola... yes, you could create a complicated model of all the liquid moving within the glass, but it's much easier to just focus on the way the bubble moves (i.e. the tiny area with no liquid).  In the same way, you can just pretend that the "hole" in the valence band is a single positively-charged particle rather than a gap in the middle of a complicated sea of electrons.  The simplest model then just assigns an effective mass to the hole $m_h^*$, and its motion in the solid is described using a dispersion relation:
\begin{equation}
E_k = \frac{\hbar^2k^2}{2m_h^*}
\end{equation}
The simplest model of an exciton (in a bulk semiconductor) could then treat the hole and an electron as an orbital pair with a reduced mass of:
\begin{equation}
\frac{1}{\mu} = \frac{1}{m_e^*} + \frac{1}{m_h^*}
\end{equation}
The Bohr radius and exciton binding energy for the lowest (1s) exciton state are then given by an analogy with a hydrogen atom:
\begin{equation}
\lambda = \frac{4\pi\epsilon_r\epsilon_0\hbar^2}{\mu e^2}
\end{equation}
and
\begin{equation}
E_b = \frac{\mu e^4}{32\pi^2\hbar^2\epsilon_r^2\epsilon_0^2}
\end{equation}
Note, though that there are several energy bands that a hole can occupy, and the simple effective-mass model breaks down as the kinetic energy becomes larger.
In those cases, you'd need a more sophisticated model, such as $k\cdot p$ theory.
Also, the bulk exciton model only really works if you are considering a single electron-hole pair in a material.
You start to need complicated many-body models if you want to go any further than that.
It is possible, though, to consider single excitons in heterostructures (quantum wells etc) through a variational approach to minimising the binding energy.  See, for example, Chapter 6 in "Quantum Wells, Wires and Dots", P. Harrison, 3rd Ed., Wiley, Chichester (2009).


text:
Q: How to to plot TWO log plots in same figure I want to take two log plots and compare one overlaid on the other.  For linear plots, I can use
     figure;
     Hold on;
     plot(first)
     plot(second)
and they are plotted one over the other. (As expected)
BUT, if I use a log plot, say for a BODE plot, when I use the "Hold on" command, it changes the x-axis to linear and I lose the log scale on the x-axis.
Example Code below
figure;
hold on;
semilogx(omega,20*log10(abs(c_Hs)),'r');  % transfer function #1
semilogx(omega,20*log10(abs(c_HsR)),'b');  % Transfer function #2

so HOW do i prevent "hold on" from changing the log scale to linear ???

A: Place the hold on; expression after the first semilogx call
figure;
semilogx(omega,20*log10(abs(c_Hs)),'r');  % transfer function #1
hold on;
semilogx(omega,20*log10(abs(c_HsR)),'b');  % Transfer function #

Or pass both sets of data to the plotting function:
figure;
semilogx(omega,20*log10(abs(c_Hs)),'r',omega,20*log10(abs(c_HsR)),'b');


text:
Q: migrate fails due to auth.User I'm trying to use rest_framework.authtoken
I'm following this instructions https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
but whenever i try to do python manage.py migrate
authtoken.Token.user: (fields.E300) Field defines a relation with model 'auth.User', which is either not installed, or is abstract.
authtoken.Token.user: (fields.E307) The field authtoken.Token.user was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed.

this error happens
I red error message and thought that I need to install "auth"
so I pip install django-rest-auth
but it didn't work
and this is my part of my settins.py
INSTALLED_APPS = [

    'rest_auth',
    'rest_framework.authtoken',
]
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]
}

it is views.py (i'm working on it so itis not completed)
@api_view(http_method_names=['POST'])
@permission_classes([AllowAny])
@psa()
def exchange_token(request, backend):
    serializer = UserSerializer(data=request.data)

    if serializer.is_valid(raise_exception=True):
        user = request.backend.do_auth(serializer.validated_data['access_token'])

        if user:#drf built in token authentication??
            token, _ = Token.objects.get_or_create(user=user) # drf token authentication
            return Response({'token':token.key})
        else:
            return Response(
                {'errors':{'token':'Invalid token'}},
                status = status.HTTP_400_BAD_REQUEST,
            )

I'm trying to do this to use that "Token.objects~~"
there is no migration file i can fix.. documents just told me to do python manage.py migrate
anyone please inform me what is wrong..

A: please firstly run
 `python manage.py makemigrations`


text:
Q: Resharper: Put opening parenthesis on new line I've seen questions and answers about aligning closing parentheses with ReSharper, but in my case, I'd like to force the opening parenthesis to be on a new line.
For example:
Method(
    param1,
    param2
);

Would become:
Method
(
    param1,
    param2
);

I'm aware this style is unconventional, but because I'm working with CodeDOM, I'm creating a lot of tree-like constructs through method calls, so treating parentheses like curly braces would make the structure much more readable.

A: Found it right after posting...
Enabling all three checkboxes here does what I want:

*

*C# > Line Breaks and Wrapping > Arrangement of Invocations

*

*Prefer wrap before "(" in invocation

*Prefer wrap after "(" in invocation

*Prefer wrap before ")" in invocation


text:
Q: Can you return an 'anonymous struct'? This answer describes constructing 'an anonymous struct' in C#: Is there an equivalent C# syntax for C's inline anonymous struct definition?
var x = new { SomeField = 1, SomeOtherField = "Two" };
Is it valid to return this from a method to avoid having to define a struct explicitly? A comment on that answer says no, but that was 2011...

A: That's not a struct, it's an Anonymous Type in C# (which is actually implemented as a class by the compiler). An anonymous type is declared in local scope, and you cannot pass it as a strong typed class in C# because it is a compiler generated class. Your options are either to use object or dynamic as return types, but you still lose the underlying type.
To sum up your question, the answer is a simple "not the way you want it to work".

A: MSDN says:

Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

So you can return it as an object but afterwards you cannot do too much with them unless you use reflection or dynamics.
If your real intention is to return multiple values use the Tuple<...> type instead:
return Tuple.Create<int, string>(1, "Two");


text:
Q: Autoload is changing Scope of variables included in autoloaded file I'm having some trouble with my php project...
The autoload function:
spl_autoload_register(function ($class_name) {
include 'HTMLClasses/'.$class_name . '.php';});

When autloloading classes from the "HTMLClasses" directory, the variables in the autoloaded file which are included from other files are not in its scope anymore.
someFile.php
require_once $_SERVER["DOCUMENT_ROOT"] . "/config/phpFileIndex.php";
require_once $phpFile['resourcesPaths'];
include_once "../autoload.php";
class SomeClass{}

the problem now is, that when autoloading this class the $phpFile Variable isn't in the scope of this script anymore. It is Global and i can access it by using $GLOBALS but I do not understand why I need this at all, beacause if I include SomeClass manualy, the variable is in the normal scope. In the documentation of spl_autoload_register there is nothing documented about this behavior.
Another problem is that i can't include autoload from here. Even though the autoload.php is in the upper directory. When including the full path from Document_root it works but not relative. And I actually do not understand this. The warning says:
'Warning: include_once(): Failed opening '../autoload.php' for inclusion (include_path='\xampp\php\PEAR') in F:\<path>\HTMLClasses\Template.php on line 4'

I dont know if this is a problem with the code or with my enviorment.
I tried searching for it, but the problem is actually, that I don't know what to search for. If anyone has an Idea about this I would really apreciate it. :)


text:
Q: Existence of a surjective map $h:\alpha\rightarrow [\alpha]^{\lt\omega}$ such that $h \in \tilde{\Sigma}_1^{J_\alpha[E]}$ So there is this exercise in Ralf Schindler's book, which I have problems with and I would appreciate any hints or solutions for it. Also here, $\tilde{\Sigma}_1^{J_\alpha[E]}$ denotes the set of $\Sigma_1$-definable relations with parameters from $J_\alpha[E]$. Also the indices of the $J$-hierarchy here are limit ordinals.

Exercise. Let $M = J_\alpha[E]$ be a $J$-structure. Show that there is a (partial) surjection $h:\alpha\rightarrow [\alpha]^{\lt\omega}$ such that $h \in \tilde{\Sigma}_1^{M}$.

My thoughts:
I tried using different methods to construct this. First because of the $\Sigma_1$-definability clause I tried building an order on $[\alpha]^{\lt\omega}$, and letting $h$ compute the order-type. But the order I used was the usual ordering on finite subsets of ordinals(i.e. $u \lt v \leftrightarrow \max(u \Delta v) \in v$) and may have large order-types below $[\alpha]^{\lt\omega}$.
Then my next idea was to prove this inductively. First we observe that for $\alpha = \omega$, we can use the order-type idea above. For $\alpha = \beta + \omega$, we have a function $h_\beta:\beta\rightarrow [\beta]^{\lt\omega}$ such that $h_\beta \in \tilde{\Sigma}_1^{J_\beta[E]}$ and so $h_\beta \in J_\alpha[E]$ and so we can use it as a parameter in our formula. Now it suffices to extend $h_\beta$ in a $\Sigma_1$ way over $\alpha$ while assuring surjectivity on $[\alpha]^{\lt\omega}$. I did this by doing some codings and I have no problem here. My main issue is where $\alpha$ is a limit of limit ordinals. In that case we can't choose functions as parameters to extend, so I guess it must be done directly.
So my question is: Can my above argument be completed? Or is there some other direct way to prove this?

A: You might consider finding a surjection onto all of $M$ itself, then just restricting to the preimage of $[\alpha]^{<\omega}$ (this is why Schindler notes that the function is partial).  The result is Lemma 2.10 of Jensen's original paper, which can found in full here, where the result is proven.
I unfortunately don't have time to summarize the proof right now, but that should help point you in the right direction.


text:
Q: How can I disable 128 bit ciphers in apache? I am using this SSL Conf:
SSLCipherSuite ALL:!RSA:!CAMELLIA:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4:!SHA1:!SHA256:!SHA384

Please help! I am unable to find any solutions.
When I use ssllabs.com to check my website my cipher is always <100%. So, I heard that disabling 128 bit ciphers will get me to the full %. And I want to be as secure as possible.

A: Instead of listing ALL and then removing what you don't want you could just list the accepted ciphersuites, e.g.
SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384

Also, you shouldn't focus on getting A+ 100% on the SSL Labs test. There's no such thing as 100% security, but only security against a risk. What's your risk model? Focusing on tests might even give you false sense of security. The most useful part of the test starts after the grading. There, you can make a suitable compromise between security and compatibility. Are you willing to lose the visitors with older browsers that do not support any of your ciphersuites?


text:
Q: How to delete rows in Panda DataFrame? I have a list in my pandas data frame and i want to delete all the rows that have a specific value in a columns up to the 10th row.
Something like this,
del df[df.value == 5][:10]
but it's not working
anyone know the proper syntax
thanks


text:
Q: CakePHP 3 missing routes in nested routes setup I am trying to connect nested routes in CakePHP 3.
I am trying to achieve the following routes (in brackets their current state):
GET /api/users/:id/events     (Working)
POST /api/users/:id/events    (Missing Route)

GET /api/events/:id           (Working)
PATCH /api/events/:id         (Missing Route)
DELETE /api/events/:id        (Not tested)

In my routes.php file I have the following:
Router::prefix('api', function ($routes) {

    $routes->connect('/token', ['controller' => 'Users', 'action' => 'token']);

    $routes->resources('Users', function ($routes) {
        $routes->resources('Events', [
            'only' => ['index', 'add']
        ]);
    });

    $routes->resources('Events', [
        'only' => ['view', 'patch', 'delete']
    ]);
});

The routes that aren't working throws a Cake\Routing\Exception\MissingRouteException
The error page also shows a list of connected routes and the ones I would like is not present. Is it possible to create nested resources in the way I have tried or how would I be able to connect the desired routes without manually connecting each?

A: Have a closer look at the docs again, there are no add or patch values that the only option would support, not unless you'd add custom routes with these names to the default resource map.
By default only the following resource routes are supported:

*

*index (= GET)

*view (= GET with /:id)

*create (= POST)

*update (= PUT and PATCH with /:id)

*delete (= DELETE with /:id)

So what you want to use is index and create for the nested Users/Events resource routes, and view, update and delete for the non-nested Events resource routes.
See also

*

*Cookbook > Routing > Creating RESTful Routes > Limiting the Routes Created

*Cookbook > Routing > Creating RESTful Routes > Mapping Additional Resource Routes


text:
Q: Wrong values when reading floats from a text file in c I am reading text file contains values like below

125602365  119653955   126374444   124463807   127312438   128395899

and the below code to read it.
if(!(pvtcheck(0)))
  {
     fscanf(fp,"%f",&deltime);
     printf("\ndeltime0=%f\n",deltime);    ///Actual value is 125602365, but i am getting 125602368.
  }

  if(!(pvtcheck(1)))
  {
      fscanf(fp,"\t%f",&deltime);
      printf("\ndeltime1=%f\n",deltime);///Actual value is 119653955, but i am getting 119653952.
  }
  /// same for pvtcheck(2),pvtcheck(3),pvtcheck(4)
  if(!(pvtcheck(5)))
  {
      fscanf(fp,"\t%f",&deltime);
       printf("\ndeltime5=%f\n",deltime); ///Actual value is 128395899, but i am getting 128395896.
  }

In the Comment i have written output , any solution to not change the values

A: You need to use the double type instead of float, and the %lf format specifier for scanf instead of %f.
double deltime;

fscanf(fp, "%lf", &deltime);
printf("\ndeltime0=%lf\n", deltime);
fscanf(fp, "\t%lf", &deltime);
printf("\ndeltime1=%f\n", deltime);
...

BTW: for printf you can use either %f or %lf they both have the same meaning.
Also read this SO article


text:
Q: Marklogic ServerConnectionException, xdmp:node-replace Marklogic xdmp:node-replace is failing and getting below exception;
MarkLogic: ServerConnectionException, Premature EOF, partial header line read: ''
com.marklogic.xcc.exceptions.ServerConnectionException: Premature EOF, partial header line read: ''
...
Caused by: java.io.IOException: Premature EOF, partial header line read: ''

Some more details;

*

*Marklogic version is 5

*Application is executing xquery via xcc connector

*Not all the xqueries are failing but xdmp:node-replace fails every
time

*Importantly dashboard/diskspace shows Forest reserve having enough
memory but Free space is 0 MB, If this could be the reason then how
other queries are executing and why there is no disk space error in
the marklogic logs.


text:
Q: Significance of partial derivatives in the conversion of unit vectors from Cartesian to Cylindrical Co-ordinate system I was watching a video on the conversion of cartesian unit vectors to cylindrical unit vectors.
I understood till the point where he said
$$
\vec r = r \cos\phi \, \hat\imath_x
+ r \sin\phi \, \hat \imath_y + z \, \hat z
$$
and then he went ahead and partially differentiated $\vec r$ by $r$ to get the unit vector in the direction of $r$ and partially differentiated $\vec r$ by $\phi$ to get the unit vector in the direction of $\phi$.
Why was this partial differentiation done? He explained it was to find the unit vector in the direction of the increase of the parameter.
Is this like a directional derivative where you take a gradient of the scalar function and then take the dot product of the gradient with the unit vector direction in which you want to find the derivative?


text:
Q: Do all positive distributions on $N$ variables factor pairwise? The Hammersley-Clifford theorem says that any positive probability distribution satisfies one of the Markov properties with respect to an undirected graph G if and only if its density can be factorized over the cliques of the graph.  Any edge in a graph is a clique.  Every distribution trivially satisfies the local Markov property with respect to the complete graph.  It seems to follow that any positive distribution must factor pairwise: $$f(x_1,\dots,x_N)=\prod_{N\ge i>j\ge 1}f_{ij}(x_i,x_j)$$ if $f$ is a positive distribution.  This should hold regardless of whether the various $x_i$ are discrete or continuous or from some more exotic measurable space.
That seems surprising to me. A tabular representation of the distribution over $N$ binary variables has $2^N-1$ free parameters, one per configuration less one to make the distribution normalize. But if the distribution must factor into $\frac{N(N+1)}{2}$ pairwise terms, each of which can be represented in tabular form with four parameters, we can represent any distribution with no more than $2N(N+1)\ll 2^N-1$ parameters. Have I missed something subtle (or something obvious)? If the claim that all distributions on $N$ variables must factor pairwise is true, is there a more direct or intuitive proof than invoking Hammersley-Clifford as I did?

A: You're misinterpreting the Hammersley-Clifford theorem.  Every edge is a clique, but not every clique is an edge.  You need to factor over all the cliques, including the complete graph itself.

A: Well, the uniform distribution on $\{(0,1,1), (1,0,1), (1,1,0)\} $ does not factor like that, since it would imply
$$0=f(1,1,1)=\prod_{i, j} f_{i, j}(1,1)\ne 0,$$ a contradiction.
To get a positive example,
let the probability of $(0,1,1)$, $(1,1,0)$, and $(1,0,1)$ each be $\frac{1-\epsilon}{3}$, and the probability of each of the other 5 elements of $\{0,1\}^3$ be $\epsilon/5$.
Then
$$\frac\epsilon{5}=f(1,1,1)=\prod_{i, j} f_{i, j}(1,1)\ge \left(\frac{1-\epsilon}3\right)^3,$$
which is a contradiction for small enough $\epsilon$.


text:
Q: How do you use the [NSDate dateWithTimeIntervalSinceNow:] method? How do you use the [NSDate dateWithTimeIntervalSinceNow:] method?
I would appreciate it if someone could post some example code. (There is no example in the documentation.)

A: NSDate * OneHourAway = [NSDate dateWithTimeIntervalSinceNow:3600]

The argument is in seconds.  3600 = 60 * 60 = 60 minutes = 1 hour

A: If you have an NSDate property called datePicker
then see a possible use of dateWithTimeIntervalSinceNow
-(void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];
   self.datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:60];
}

This will cause the datepicker to allow only dates that are 60 seconds from now


text:
Q: What is difference between .env files and .ini files? which one is better? I am a beginner PHP , I found out that Laravel has .env file to save some configurations and php also have a file format .ini to save config.
I want to ask what is the difference in both, is one is better from another. Should i add dotenv in my core projects also or should i create class/function to access .ini for my config/environment variables.
i want to understand why dotenv is being created as we already had ini file extension system in php?

A: I think there are too many smartasses with nothing else to do. I will use parse_ini_file() and *.ini files. Everything is the same !

A: .env allows loading the configuration to the system environment. Straight loading of INI files does not do this unless you roll your own solution using putenv or similar for all the configuration values. Otherwise you could whichever approach you wish.

A: According to the docs at https://github.com/vlucas/phpdotenv

Why .env?
You should never store sensitive credentials in your code. Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environments – such as database credentials or credentials for 3rd party services – should be extracted from the code into environment variables.
Basically, a .env file is an easy way to load custom configuration variables that your application needs without having to modify .htaccess files or Apache/nginx virtual hosts. This means you won't have to edit any files outside the project, and all the environment variables are always set no matter how you run your project - Apache, Nginx, CLI, and even PHP 5.4's built-in webserver. It's WAY easier than all the other ways you know of to set environment variables, and you're going to love it.
NO editing virtual hosts in Apache or Nginx
NO adding php_value flags to .htaccess files
EASY portability and sharing of required ENV values
COMPATIBLE with PHP's built-in web server and CLI runner

Additionally, there is some extended functionality with Laravel's .env file.  For example, you can reference other variables inside the .env file.
MAIL_USERNAME=admin@server.com
MAIL_FROM_ADDRESS=${MAIL_USERNAME}


text:
Q: rn-fetch-blob Error: RNFetchBlob.fetchBlobForm failed to create request body async postFileUpload(payload) {
    const rnfetchfile = RNFetchBlob.wrap(payload.uri);
    try {
    console.log(
        'POST',
        'https://******.***.**/******/***/upload_*******_file',
        {
          ...this.config,
          'Content-Type': 'multipart/form-data',
        },
        [
          // element with property `filename` will be transformed into `file` in form data
          {
            name: 'files',
            filename: payload.name,
            data: rnfetchfile.replace('file://file:///', 'file://'),
          },
        ],
      );
      const res = await RNFetchBlob.fetch(
        'POST',
        'https://******.***.**/******/***/upload_*******_file',
        {
          ...this.config,
          'Content-Type': 'multipart/form-data',
        },
        [
          // element with property `filename` will be transformed into `file` in form data
          {
            name: 'files',
            filename: payload.name,
            data: rnfetchfile.replace('file://file:///', 'file://'),
          },
        ],
      );
    const response = JSON.parse(res.data);
      console.log('api upload adpostimage', response);
      return response;
    } catch (err) {
      console.log('postFileUpload', err.response, err);
      Toast.show(err.response.data.message, Toast.SHORT);
      throw err.response.data;
    }

res throws error
in console messages are
POST https://******.***.**/******/***/upload_*******_file {Content-Type: "multipart/form-data", Authorization: "Bearer ******.***.*****"}
[{…}]
0:
name: "files"
filename: "*****.pdf"
data: "RNFetchBlob-file://Users/********/tmp/*****/B****.pdf"}

postFileUpload undefined Error: RNFetchBlob.fetchBlobForm failed to create request body
at index.js:313
at MessageQueue.__invokeCallback (MessageQueue.js:483)
at MessageQueue.js:135
at MessageQueue.__guard (MessageQueue.js:384)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:134)
at debuggerWorker.js:69

I am trying to upload a file using rn-fetch-blob and some crazy things happened
rnfetchfile.replace('file://file:///', 'file://'), because of file://file/// outputting which didn't seem right
I think this like mostly ios problem please help me out guys

A: as here said just use decodeURIComponent(uri)
this is my code :
const realPath = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;

const data = [
  {
     name: 'file',
     filename,
     type,
     data: RNFetchBlob.wrap(decodeURIComponent(realPath)),
  },
  {name: 'bla', data: 'bla'}
]

A: Try replacing the file://file:// to '' an empty string..
rnfetchfile.replace('file://file:///', '')

– @Abhishek Ghosh commented is a need trick which will work but the file will not be available in the uri.. your uploaded file wont open
I tried doing
data: decodeURIComponent(rnfetchfile.replace('file://file:///', 'file:///')

and it worked hope this helps


text:
Q: iOS6 Putting Cursor in SPecific Text Field I have three text input fields that I clear after the user has added data to a database:
 self.textMonth.text  = @"";
 self.textTemp.text   = @"";
 self.textCloud.text  = @"";

How to I put the cursor in any one of those fields subsequently?
I have tried a number of the solutions provided elsewhere but none seem to work. Many thanks. EH

A: try this:
[self.textMonth becomeFirstResponder];

A: just make your text field first responder using becomeFirstResponder like....
 [self.textMonth becomeFirstResponder];

to change textfield subsequently use textFieldShouldReturn
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([self.textMonth isFirstReponder])
    {
        [self.textTemp becomeFirstResponder];
    }
    else if([self.textTemp isFirstReponder])
    {
        [self. textCloud becomeFirstResponder];
    }
    else if([self.textCloud isFirstReponder])
    {
        [self.textMonth becomeFirstResponder];
    }
    return YES;
}

Hope it will help to solve your problem

A: Based on conditions you can use becomeFirstResponder
[self.textMonth becomeFirstResponder];
[self.textTemp becomeFirstResponder];
[self.textCloud becomeFirstResponder];


text:
Q: What does ^ mean? When I look through some C++ Code Samples of Microsoft in github.
I saw so many "^"s in the code.
Many Typename's are followed by this "^".
for example, It's like this.
ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView
{
public:
    App();

    // IFrameworkView Methods.
    virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
    virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
    virtual void Load(Platform::String^ entryPoint);

I've searched about this, but can't find out what is this and how to use it
What does ^ mean?


text:
Q: Does the Raspberry PI support WOL (Wake-on-LAN)? I've been contemplating running a Raspberry PI as a carputer. One thing I'm really interested in is whether I could get it to Wake-On-Lan.
My thinking is that I'd like to wake the device up before I start the car so that it can sync up to various feeds, download spotify tunes etc. from the wifi connection from my house so it's ready to rock while it's on the move.

A: No, it doesn't. But the Raspberry Pi draws about 2 watts at idle and with a little effort can be reduced even lower than that. So there's really not much point. As long as you run your car every ten days, you can keep the Pi on all the time with no issues.
It might be worth the effort to rig a device to shut the Pi off if it remains on for a week without the car starting. (Just give the Pi the ability to shut off its power.) That way you can leave the car for several weeks without having to worry about the battery draining.

A: I do understand that full automation of this would be simply sexy and a make of it a "better toy" but I think that a simple and old button with a "on" led would perfectly do the job and the little pi would take a very little time to boot from scratch meanwhile you put your seatbelt on.
And never underestimate the good old retro "Knight Rider" feeling :)