text:
Q: Downvoters and comments I know this point is apparently already treated in this question.
Being the second time I get downvoted with an answer containing the same amount of informations of another answer which get upvoted (and "heavily"), I began to think that the idea to be forced to explain a downvote is good.
But in an environment frequented also by poor-minded people (retaliators, friends-cluster and alike), and thus hostile, I understand downvoters prefer to stay secret, if they want, like explained in comments.
While this saves good downvoters from silly persons, on the other hand protects also bad downvoters and does not help improving answers, nor the OP to evaluate answers and decide which is better (supposing the OP is a good honest OP).
So the modified idea is: downvoters must give a reason, but this reason can be read only by the OP who made the question and it is likely interested in having more clues to evaluate the content of an answer (I think this is more important for beginners who sometimes choose as better answer one that seems to solve their problem, but indeed it will be a source of other problems, while other more correct answers are not taken into account since seen as "too complex"). (Extra idea: the OP can remove the downvote if the reason does not satisfy him/her, e.g. a reason containing just "a reason", just to fill it, is not a good reason... or maybe the OP can give a vote to the reason, and we could think about mechanisms where votes for the reasons influence someway the reputation...)
Of course, people with imagination can imagine evil scenarios where it is not desiderable th OPs have such information (e.g. there's no way to avoid they share it at least outside SO), but these scesarios are side by side with those where, say, upvoters vote up answers given by high-reputation guys (since they trust them) without reading the answer at all, and downvoters vote down since the answerer had commented "against" their comments or answers... (and many more, like clusters of friends voting each other answers)

A: Individual upvotes/downvotes are irrelevant. If the problem is the reputation lost, an upvote far outweighs several downvotes, so it's a bit silly to complain about that. If the problem is the possibility to be wrong and not finding out why, don't worry, if you really are and is enough activity in the question, you'll get your reason sooner or later. If the problem is the psychological impact of being downvoted, you need to grow a pair. Downvotes happen, and they might come merely because somebody didn't like your gravatar, or because they felt offended because you used a religious allegory or any other pity reason, as the people that vote upon posts is just that, people.
There is no way to catch "good" downvoters and "bad" downvoters, as there is no such thing. If your answer is good, it will garner upvotes fast enough, and even it might get a higher score merely because people that saw -1 ranked answers have the urge (IMO misplaced) to upvote.
Personally I avoid leaving comments when downvoting generally because most downvotable answers belong to users that complain, bitch and moan to you about that, sometimes following you or engaging in mass downvoting. Harmless, but annoying.
Also, even if you could "out bad downvoters", what would you do with that?
Simply take downvotes like rain, love and shit. It just happens.

A: Hmm... clearly the incentive Jeff provided for downvote comments hasn't worked well enough. I liked his solution at the time, and I still think anything more draconian is a bad idea. I don't think people should be forced to comment on a downvote, nor do I think the system should be rewired in the way you suggest to satisfy what I consider a niche concern.
I agree with @Gnoupi that the only real solution is to not get worked up about downvotes. They happen. People disagree with you or sometimes you really are wrong even if you can't see it. I know that's happened to me on more than one occasion; I posted something I was sure was right, then got sk00led.
That said... perhaps a happy compromise can be obtained. I counter-suggest the following feature:
Modify the current popup that occurs on a downvote such that it occurs for all downvotes regardless of reputation. Modify the contents of the popup to read "Please add a comment explaining why you downvoted this Question/Answer:" along with a text box that gains focus immediately. Two buttons complete the modification: "Submit Comment" and "Leave No Comment"; hopefully their functions are obvious from their titles. Finally, allow any click outside the box to close the box, along with a timer that will close it if no text has been typed into the box in, say, 20 seconds.
This makes downvoting a two step process, forcing every downvoter to consider submitting a comment while not forcing them to actually leave a comment.
Again, I do not consider this a high priority issue; I'm just trying to find some compromise that might work while remaining non-intrusive.

A: Gnoupi and voyager cover the general case, so I'll tackle your "extra ideas". As for downvote explanations being shown to the question author only, I don't see it as being any different than the general case, a downvoter doesn't need to appeal their opinion to the author any more than to whoever is being downvoted. So I still redirect to Gnoupi.
Downvotes are an expression of the opinion of whoever cast them. An opinion does not have to be "satisfactory" to anyone in order to exist, so there's no reason the author of a question should be able to undo them. That's why, among other things, not even moderators can change votes. It's simply against the spirit of the system. This is also why the "reliability" of such downvotes is not of any concern to the author of the question. If the author wants to take downvotes into consideration, then the author should evaluate the answer personally. The author should be able to judge whether an answer is helpful to the author by merit of the answer itself, whether or not the downvotes are "reliably given".
As far as rewarding reputation for downvote explanations, there is no reason why a downvote explanation is worth more than, say, an upvote explanation, or any kind of fixer comment that isn't tied with a downvote. For example, there are often times that I will make comments, both here and on SO, which may sound like a downvote explanation (and the post is indeed downvoted), but I didn't cast the downvote. All I wanted to do was suggest some explanation why a downvote may have been, or point out a flaw in the post. And these may lead to the post getting fixed. The only way I'd receive reputation for this act, under your suggestion, would involve me downvoting, but I didn't find it necessary to cast a downvote. Is my contribution worth less because I didn't cast a downvote?
Ultimately, regardless of whether you are the author of the question or the author of the answer that got downvoted, there are two courses of action that you can take when you get a downvote without a reason, or without a satisfactory one. You can check to see if the answer is indeed flawed, and fix it appropriately. And if you don't see any flaws, then disregard that downvote, because a good answer will get upvotes from the people who responsibly analyze these things. But that person who downvoted you is entitled to their opinion exactly the same as anyone else is entitled to upvote you without reason.
EDIT
Hooboy, you've given me a lot to have to respond to. Rather than worry about fitting it in comments, I'll just edit my post body. If you want to skip past all of the lengthy stuff, do so but please go to the last two paragraphs. Those are the most important ones here that summarizes the faults in your suggestion.

Addressing comments 4-6, that this is an "extra suggestion" is the reason I wrote my answer, I wanted to explicitly address your extra suggestions. You are casting the OP in some radiant light that implies they know absolutely what is good and what is not, which is entirely incorrect. The point of votes is to show the community's interpretation of an answer. Just because someone asked the question, it does not give them any right to decide whether someone's opposition to an answer is appropriate or not, no matter the explanation for that. And there is definitely no "moral binding" here. The question asker came to get an answer to a question, not to personally evaluate the opinions of others. The explanations of others is helpful in identifying how useful a particular answer may be, but it isn't the OP's responsibility to point out what is right and wrong in votes. Why should the OP have to judge this when the whole point of asking the question is to get a right answer?
You specifically suggested that the OP be able to reward a good explanation for a downvote with reputation. Your exact quote is "maybe the OP can give a vote to the reason, and we could think about mechanisms where votes for the reasons influence someway the reputation". Since these OP-only reasons only show up for downvotes, this is very much going to reward people for downvoting and explaining rather than those who just explain flaws, so I'm not wrong there.
I agree that the OP can always benefit from explanations of downvotes. In fact, anyone who has the same problem can benefit from it. But you're casting such things in such a positive light without paying heed to the problems that arise. If, for example, only the OP can see a particular comment explanation, and someone gives a reliable sounding explanation because that user, as they understand the answer, believes there is a fundamental flaw with the answer, the OP can consequently choose to follow that advice and avoid that answer. However, that user may be completely wrong about the answer, and if the OP doesn't know this, then there is no way for anyone to explain that. So an otherwise perfectly serviceable answer can be overlooked because of "reliability". Ultimately, the reason that a downvote is an "opinion" and not a "fact" (which the fact that answers are facts is completely irrelevant) is because it can only be given in the experience that the caster has. There are cases where someone can be 100% certain that their downvote is appropriate based on their knowledge, even when the answer may in fact be useful. And the OP, who let's not forget is asking the question in the first place, may not know this. This is why the most important thing a user should do is evaluate answers. Explanations for downvotes help, but they are unnecessary, a good evaluation of an answer can identify the flaws if they exist. And if they don't exist, then you don't need to understand why one user thought it wasn't useful to know that you yourself found it useful.
You also make a faulty assumption in the end of your comment stream that upvotes are always about correctness and rightness. A lot of people also give upvotes for reasons like "It's a good thing you suggested this particular method for this part". Not all questions and answers are clear-cut one-part solutions. Or maybe "Oh, hey, I was investigating this other problem and it turns out that this component you used was helpful to me". These answers were useful to people, but not necessarily to the author. There are also upvotes for friendliness, pity, and other less reputable reasons, just the same as there are bad reasons that people downvote. Upvotes are no more sacred than downvotes are.

The ultimate thing to draw from this is, requiring comments does not actually strengthen the system. The reasons that it, in general, is not useful is explained by all the other answers here. Making it visible only to the OP also doesn't necessarily strengthen it - the OP, just like the people who cast votes in the first place, is no less prone to incorrectly understanding things. So there is no ensured benefit to this. Anyone who would give good explanations for downvotes doesn't need to be forced in the first place, and certainly doesn't need to reserve it for just the OP.
It is fundamentally better that such reasons be out in the open to all users, so that anyone can evaluate the reason and, in the fact of downvotes made on faulty assumptions, correct the comment with their own knowledge contribution. This kind of thing will actually benefit the OP far more than just letting them see one user's opinion. Which is why the score of a post is the votes cast by the community.

A: It's a duplicate It's not an exact duplicate, but these points still stand:

*

*Downvoting is good 95% of the time. It helps separating bad answers/questions from the good ones. Adding a constraint to downvoting will decrease downvoting as a whole.

*The remaining 5% are due to silly revenge votes, but honestly, who cares. Had 2 ones last week, I'll live. If the phenomenon is wider, like a large number of downvotes in a short time, it will anyway be reverted by an automatic process, every night.

*Forcing people to add a comment won't prevent them from putting "blablabla -1". Nothing will. If they don't want to explain why they spent one point of their reputation to downvote you, they won't, even if forced.

Addendum to 1: if you force people to input a reason, it is a constraint, and it will reduce the number of downvotes in general. There are many cases in which I will quickly downvote, to show disagreement, without time to explain why. There are times when the reason was told by someone else, in which case I downvote and upvote the comment. I don't see why i should be forced to write "like this one said".
Besides, if you force people to put a personal comment, read only by the OP, then they won't write it in public under the post. Which means someone else coming after will most likely write the same, etc.
I agree, everyone agrees, that getting a downvote on what seemed valid without a comment is harsh and unpleasant. But it's really an edge case, and forcing people to comment won't solve the problem, only make the system less pleasant to use.
The only solution is to care less about downvotes.


text:
Q: Simplifying vector norms in a proof Consider the optimization problem
$$
\min _{y \in \mathbb{R}^{n}} f(y):=\frac{1}{2}\|A y-b\|_{2}^{2}
$$
Let y be a feasible solution and $y^{*}$ be the optimal solution. The goal is to prove that
$$
f(y)-f\left(y^{*}\right)=\frac{1}{2}\left\|A y-A y^{*}\right\|_{2}^{2}, \forall y \in \mathbb{R}^{n}
$$
I am getting confused when simplifying vector norm terms, which I think is necessary in this proof. My attempt:
$$f(y)=\frac{1}{2}\|A y-b\|_{2}^{2}$$
$$f(y^{*})=\frac{1}{2}\|A y^{*}-b\|_{2}^{2}$$
So,
$$\frac{1}{2}\|A y-b\|_{2}^{2} - \frac{1}{2}\|A y^{*}-b\|_{2}^{2} = \frac{1}{2}\left\|A y-A y^{*}\right\|_{2}^{2}$$
$$\left(\|Ay\|_{2}^{2} - 2\|Ay\|_2\|b\|_2 + \|b\|_2^{2}\right)-\left(\|Ay^{*}\|_{2}^{2} - 2\|Ay^{*}\|_2\|b\|_2 + \|b\|_2^{2}\right) = \|A y-A y^{*}\|_{2}^{2}$$
$$\|A y\|_2^{2} - \|A y^{*}\|_2^{2} = \|A y-A y^{*}\|_{2}^{2}$$
$$\|A y-A y^{*}\|_{2}^{2} = \|A y-A y^{*}\|_{2}^{2}$$
Not very sure about the last two steps. Maybe an application of the Triangle Inequality here?

A: *

*Because $y^*$ is optimal for the unconstrained optimization problem, we must have $\nabla f(y^*)=0$, i.e. $$A^\top (Ay^*-b)=0.$$

*You expanded the norms incorrectly: $\|v-w\|_2^2 = \|v\|_2^2 - 2 v^\top w + \|w\|_2^2$ (the middle term is not $\|v\|_2 \|w\|_2$).

Note that
$$\|Ay-b\|_2^2 - \|Ay^* - b\|_2^2
= \|Ay\|_2^2 - 2 b^\top Ay - \|Ay^*\|_2^2 + 2 b^\top A y^*$$
and
$$\|Ay-Ay^*\|_2^2 = \|Ay\|_2^2 + \|Ay^*\|_2^2 - 2 y^\top A^\top A y^*.$$
It suffices to show the difference is zero. The difference (halved) is
\begin{align}
&\|Ay^*\|_2^2 - y^\top A^\top A y^* + b^\top Ay - b^\top A y^*
\\
&= \|Ay^*\|_2^2 - y^\top \underbrace{A^\top (Ay^*-b)}_{=0} - b^\top A y^*
\\
&= \|Ay^*\|_2^2 - b^\top A y^*
\\
&= (y^*)^\top \underbrace{A^\top (Ay^* - b)}_{=0}\
\\
&= 0.
\end{align}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Design pattern fu for converting between subclasses We are writing a hierarchy of classes that implement various ways to represent languages. There is a base LanguageCode class with several subclasses, including ISO1LanguageCode for ISO 639-1 codes (example: 'en'), ISO2LanguageCode for ISO 639-2 codes (example: 'eng'), and HumanReadableLanguageCode (example: 'English'). At any time, we need to be able to convert between any two of the subclasses. Is there some design pattern magic we could use here to help?
Note:
Our first idea was to standardize the base class and make each subclass write a conversion routine between itself and the standard on the base class. That way, to convert between ISO2LanguageCode and HumanReadableLanguageCode, use LanguageCode as a bridge.

A: There is only one set of languages. Each language has an -1 code, a useless -2 code, and a -3 code. And a human-readable name. So make one enum with accessors to return the different codes, and multiple lookup static methods.


text:
Q: I can not get the data from my server after having sent a file thought sockets I have a problem when I try to send an Acknowledgment after receiving data.
To resume the situation, I have a client that have a file to send to my server that is listening. When the server receive this file it returns an acknowledgment file. And here is my problem. When my server send the ACK file my client don't get it and just stand here and don't do anything else.
server.py
import socket
import signal
import os

# "all" interfaces
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 8000

BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"

# Setting Dicionnaries for HL7 ACK Requirements
MSH = {3:'HOSPITAL', 4:'RESULTS', 5:'LAB400', 6:'RESULTS',7:'20201030084524',9:'ACK', 10:'1452357', 11:'P',12:'2.2', 15:'AL', 16:'NE', 17:'CHE'}
MSA = {1:'AA', 2:'1722178'}

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# test the binding
try:
    socket.bind((SERVER_HOST, SERVER_PORT))

except socket.error as error:

    print('Bind failed. Error Code : '
          + str(error[0]) + ' Message '
          + error[1])

    exit()

def signal_handler(sign, frame):

    print('[*] Shutting down')
    exit(0)

while signal.signal(signal.SIGINT, signal_handler):

    # connection limit(5 connection try then deny)
    socket.listen(5)

    print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")

    # accept the connection if there is any
    client_socket, address = socket.accept()

    # Below code is executed if sender is connected
    print(f"[+] {address} is connected.")

    # get what the client is sending
    received = client_socket.recv(BUFFER_SIZE).decode()

    filename, fileSize = received.split(SEPARATOR)

    #convert to integer
    fileSize = int(fileSize)

    # remove absolute path if there is
    filename = os.path.basename(filename)

    # start receiving the file from the socket and writing to the file stream
    with open(f".\\Files\\{filename}", "wb") as f:

        while True:

            # read 1024 bytes from the socket (receive)
            bytes_read = client_socket.recv(BUFFER_SIZE)

            if not bytes_read:

                # file transmitting is done
                print(f"[+] File transfert is done")
                print(f"[+] File saved")
                break

            # write to the file the bytes we just received
            f.write(bytes_read)

    myfile = open(".\\Files\\ack.hl7", "rb")
    client_socket.send(myfile.read())

    client_socket.close()

    socket.close

client.py
import socket
import os
import random

SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096

HOST = "127.0.0.1"
PORT = 8000

files = ["test1.HL7","test2.HL7","test3.HL7","test4.HL7","test5.HL7","test6.HL7","test7.HL7","test8.HL7"]

# fileName = f".\\ClientFiles\\{files[random.randrange(1,8)]}"

fileName = f".\\ClientFiles\\{files[0]}"

filesize = os.path.getsize(fileName)

socket = socket.socket()

print(f"[+] Connecting to {HOST}:{PORT}")

socket.connect((HOST, PORT))

print("[+] Connected.")

socket.send(f"{fileName}{SEPARATOR}{filesize}".encode())

# opening file
with open(fileName, "rb") as f:
    while True:
        # reading bytes
        bytes_read = f.read(BUFFER_SIZE)
        if not bytes_read:
            # Transmitting is done
            break
        # send all the buffer
        socket.sendall(bytes_read)
print(f"[+] File {fileName} sent")

data = socket.recv(BUFFER_SIZE)

print(data)

print("[*] Closing")
socket.close()

I cannot figure out why it doesn't work
Here is my files that need to be transferred(it's some HL7 V2.5.1 btw)
Ack.hl7
MSH|^~\&|HOSPITAL|RESULTS|LAB400|RESULTS|20201030084524||ACK|1452357|P|2.2
MSA|AA|1722178

testFile.hl7
MSH|^~\&|ADT1|MCM|LABADT|MCM|198808181126|SECURITY|ADT^A04|MSG00001|P|2.4
EVN|A01-|198808181123
PID|||PATID1234^5^M11||JONES^WILLIAM^A^III||19610615|M-||2106-3|1200 N ELM STREET^^GREENSBORO^NC^27401-1020|GL|(919)379-1212|(919)271-3434~(919)277-3114||S||PATID12345001^2^M10|123456789|9-87654^NC
NK1|1|JONES^BARBARA^K|SPO|||||20011105
NK1|1|JONES^MICHAEL^A|FTH
PV1|1|I|2000^2012^01||||004777^LEBAUER^SIDNEY^J.|||SUR||-||1|A0-
AL1|1||^PENICILLIN||PRODUCES HIVES~RASH
AL1|2||^CAT DANDER
DG1|001|I9|1550|MAL NEO LIVER, PRIMARY|19880501103005|F||
PR1|2234|M11|111^CODE151|COMMON PROCEDURES|198809081123
ROL|45^RECORDER^ROLE MASTER LIST|AD|CP|KATE^SMITH^ELLEN|199505011201
GT1|1122|1519|BILL^GATES^A
IN1|001|A357|1234|BCMD|||||132987
IN2|ID1551001|SSN12345678
ROL|45^RECORDER^ROLE MASTER LIST|AD|CP|KATE^ELLEN|199505011201

What I've tried so far
On my client
I've tried to recreate a socket in the case that it wasn't able to respond
try:
    data = socket.recv(BUFFER_SIZE)
    print(data)
except:
    # recreate the socket and reconnect
    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.connect(HOST, PORT)
    data = socket.recv(BUFFER_SIZE)
    print(data)

A: I could reproduce and understand your problem.
The underlying cause is that TCP is a stream protocol. That means that the only guarantee is that all the bytes that are sent from one side will the received in the same ordre by the  peer. But packets mays be concatenated or splitted by any element on the network, including the protocol stack of either side.
So in server.py, this is wrong:
# get what the client is sending
received = client_socket.recv(BUFFER_SIZE).decode()

filename, fileSize = received.split(SEPARATOR)

#convert to integer
fileSize = int(fileSize)

because received can contain the beginning of the data...
The robust way would be:
# get what the client is sending
received = client_socket.recv(BUFFER_SIZE)

filename, bytes_read = received.split(SEPARATOR.encode())
fileSize = bytes(itertools.takewhile(
    lambda i: bytes((i,)).isdigit(), bytes_read))
bytes_read = bytes_read[len(fileSize):]
#convert to integer
fileSize = int(fileSize)
filename = filename.decode()

And you will have the beginning of the data (as bytes) in bytes_read and should write it immediately:
# start receiving the file from the socket and writing to the file stream
with open(f".\\Files\\{filename}", "wb") as f:
    f.write(bytes_read)

    while True:
        ...

But that is not all. Still in server.py the reading loop will not return an empty buffer until the peer closes or better shutdowns the socket.
So in client.py you must signal the end of transmission:
print(f"[+] File {fileName} sent")

socket.shutdown(SHUT_WR)   # tells peer that nothing will be sent any more

data = socket.recv(BUFFER_SIZE)


text:
Q: Splitting two merged floating point numbers using sed/awk I have sequences appearing in a file as
2282.641.33712e+06

which I want to split into the respective floating point numbers as
2282.64 and 1.33712e+06.

The floating point number with the e+06
contains a single leading digit before the decimal.
Could this be done with sed / awk ?

A: Here's one way. Requires gawk for the gensub function
gawk 'BEGIN {
    a = "2282.641.33712e+06"
    separated = gensub("(\\.[0-9]+)([0-9]\\.)", "\\1,\\2", "g", a)
    n = split(separated, nums, ",")
    for (i=1; i<=n; i++) print nums[i]
}'

2282.64
1.33712e+06

That looks for a dot followed by some digits followed by a digit followed by a dot, then inserts a comma in the appropriate place.

A: This sed one-liner might do the trick:
sed 's/[0-9]\.[0-9]/ &/2' file

or by matching only the dots:
sed 's/.\./ &/2' file


text:
Q: Using an if function in controller I'm trying to make an application to store played FIFA games.
Now I'm already able to make accounts, store games, etc. But when I'm storing a game into the DB, I would also like to store the winner and loser of the game in a way that I can use the count function later to count how many wins or losses a user has.
Controller:
class GamesController < ApplicationController
    before_action :authenticate_user!, exept: [:index, :show]

    def index
        @games = Game.all
    end

    def new
        @game = current_user.games.build
        @user_options = User.all.map{|u| [ u.user_name, u.id ] }
    end

    def create
        @user_options = User.all.map{|u| [ u.user_name, u.id ] }

        @game = Game.new(game_params)
        @game.home_team_user_id = current_user.id

        if @game.home_score > @game.away_score
            @game.winner_id = @game.home_team_user_id
            @game.loser_id = @game.away_team_user_id
        else if @game.home_score < @game.away_score
            @game.winner_id = @game.away_team_user_id
            @game.loser_id = @game.home_team_user_id
        else
        end

        if @game.save
            redirect_to games_path, :notice => "Successfully added game!"
        else
            render 'index'
        end
    end

    def show
        @games = Game.all
    end

    def destroy
        @game = Game.find(params[:id])
        @game.destroy
        redirect_to games_path
    end

    private
    def find_game
        @game = Game.find(params[:id])
    end

    def game_params
        params.require(:game).permit(:home_team_user_name, :home_score, :away_team_user_name, :away_score, :home_team_user_id, :away_team_user_id, :winner_id, :loser_id)
    end
end
end

View:

Submit New Match

      <%= simple_form_for(@game) do |f| %>
      <%= f.text_field :home_score, :placeholder => "Your score" %>
      <%= f.text_field :away_score, :placeholder => "Your Opponents score" %>

Opponent:

      <%= f.select(:away_team_user_id, @user_options) %>

 <%= f.submit "Submit Match", class: "btn-submit" %>
      <% end %>

Is this the correct way to make this calculation? Or do you have other suggestions?
If this is the correct way, then why do I get this error when I try to submit the form:

undefined local variable or method `game_params' for

As you can see in the controller, the game_params is not missing. I've added an end at the end though, because this gave an error to load the form.

A: The issue is caused by:
else if @game.home_score < @game.away_score

It should be:
elsif @game.home_score < @game.away_score

Then you can remove one of the last two end
This was causing issues with the method beginnings/endings and conditional beginnings/endings.

A: Models in MVC are responsible for enforcing the business logic. So this calculation should be happening in your model - not in the controller.
class Game < ActiveRecord::Base

  # ...

  belongs_to :winner, class_name: 'User' # or Team or whatever
  belongs_to :loser, class_name: 'User'

  before_validation :evaluate_score!, if: -> { home_score.present? }

  private

    def evaluate_score!
      self.winner = home_score > away_score ? home_team_user : away_team_user
      self.loser = home_score < away_score ? home_team_user : away_team_user
    end
end

Additionally this line is inefficient:
@user_options = User.all.map{|u| [ u.user_name, u.id ] }

Since it pulls the entire records out of the DB and then loops through them in memory. You could use @user_options = User.pluck(:username, :id) but it is not necessary since rails has great helpers for creating inputs from collections:
<%= f.collection_select(:away_team_user, User.all, :id, :user_name) %>

Simple Form has an association helper method which pimps up the Rails collection_* helpers:
<%= f.association :away_team_user, collection: User.all, label_method: :user_name %>

*

*https://github.com/plataformatec/simple_form


text:
Q: is there a way to make a background scroll down while some content stay in the middle at all time? I'm trying to do something like (in js, html, sass) :

*

*when I scroll the page down my layers (ground, sky, space, ...) go down

*my content (that will be a rocket going in the sky) stay in the middle of the screen and will move     to the sides like if it were to be flying (that will be for later)

*some elements will move on the layers (like asteroids going from right to left or something) (for later)

So here are some ideas of code I tried but this seem odd and do not work as intended; as you can see, the layers are scrolling as intended, but they are not all showing for whatever reason, they seem to fill all the page size but they shouldn't and i'm going round and round about this on the internet and no one seem to have done something like this.

// Functions
detectPageVerticalPosition = () => {
  pageVerticalPosition = pageYOffset;
};

getDivs = () => {
  for (
    let div = document.getElementsByTagName("div"), i = 0; i
 {
  for (let i = 0; i < layerVerticalArray.length; i++) {
    layerVerticalArray[i].style.bottom = -1 * pageVerticalPosition + "px";
  }
};

// End Functions

// Variables
var pageVerticalPosition = 0,
  layerVerticalArray = new Array();
// End Variables

// Events
window.onload = e => {
  getDivs();
  // console.log(layerVerticalArray);
};

window.onscroll = e => {
  detectPageVerticalPosition();
  moveLayers();
};
// End Events
body {
  margin: 0;
}

#page {
  position: relative;
  height: 20000px;
  width: 100%;
}

#rocket-container {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

#rocket-container #rocket {
  position: absolute;
  width: 100px;
  height: 100px;
  left: calc(50% - 50px);
  top: calc(50% - 50px);
}

#background-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background-color: red;
  overflow: hidden;
}

#background-container .layer-vertical {
  width: 100%;
  height: 3500px;
}

#background-container #layer-vertical-1 {
  position: absolute;
  background-color: blue;
}

#background-container #layer-vertical-1 #cloud-1 {
  outline-style: dashed;
  right: 0px;
}

#background-container #layer-vertical-1 #cloud-2 {
  outline-style: dotted;
  bottom: 0px;
}

#background-container #layer-vertical-2 {
  background-color: green;
}

#background-container #layer-vertical-3 {
  background-color: purple;
}

.cloud {
  position: absolute;
  width: 180px;
  height: 120px;
  background-image: url(../images/cloud.png);
}

      Layer 1

      Layer 2

      Layer 3

STAY MIDDLE

    [1]: https://via.placeholder.com/180/120

A: So, here's what i found in order to fix this (jsfiddle: http://jsfiddle.net/kjrte2sd/2/)
i used some jquery to make the background-container scroll down as intended instead of each elements scrolling down by himself.
now the page div is gone and the body handle the sizing of the whole thing.
i guess the answer was simpler than i expected it to be.

var winHeight = $(window).innerHeight();

$(document).ready(() => {
  $(".layer-vertical").height(winHeight);
  $("body").height(winHeight * $(".layer-vertical").length);
});

window.addEventListener("resize", e => {
  $(".layer-vertical").height($(window).innerHeight());
});

$(window).on("scroll", () => {
  $("#background-container").css("bottom", $(window).scrollTop() * -1);
});
body {
  margin: 0;
  padding: 0;
}

#rocket-container {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

#rocket-container #rocket {
  position: absolute;
  width: 100px;
  height: 100px;
  left: calc(50% - 50px);
  top: calc(50% - 50px);
}

#background-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
}

#background-container .layer-vertical {
  width: 100%;
}

#background-container .layer-vertical h1 {
  width: 100px;
  position: relative;
  display: block;
  margin: 0 auto;
  text-align: center;
  top: 50%;
}

#background-container #layer-vertical-1 {
  background-color: green;
}

#background-container #layer-vertical-2 {
  background-color: red;
}

#background-container #layer-vertical-3 {
  background-color: white;
}

#background-container #layer-vertical-4 {
  background-color: pink;
}

#background-container #layer-vertical-5 {
  background-color: yellow;
}

5

4

3

2

1

STAY MIDDLE


text:
Q: Teiid sql query with chinese character I want to ask a question about a data virtualization system called teiid,
When I create a query like this:
SELECT teiid2602.KC.{**some chinese character**}
FROM teiid2602.KC
WHERE teiid2602.KC.id is not null;

the teiid system returns the message:
odbc_exec(): SQL error: [unixODBC]ERROR: TEIID30504 KK: 1054 TEIID11008:TEIID11004 Error executing statement(s): [Prepared Values: [] SQL: SELECT g_0.`mobile`, g_0.`{**some chinese character**}` FROM `teiid2602`.`KC` AS g_0]
org.teiid.jdbc.TeiidSQLException: TEIID30504 KK: 1054 TEIID11008:TEIID11004 Error executing statement(s): [Prepared Values: [] SQL: SELECT g_0.`mobile`, g_0.`{**some chinese character**}` FROM `teiid2602`.`KC` AS g_0];
Error while executing the query, SQL state S0022 in SQLExecDirect

But I can run this query on my MySQL workbench, so I wonder whether Teiid support Chinese character query or not, or is anyone meet the similar problem and know how to fix it.

A: The Teiid SQL parser treats the following characters as letters: latin letters a-z and A-Z, and also the unicode range of \u0153-\ufffd. Anyway if Teiid generated the final output SQL query which contains the names in chinese, it definitely supports the particular letters you used for the field name.
So the problem may be about the mysql itself or about the output query generated (in the original query you provided there's no reference to 'mobile' field while the generated query contains it).
Anyway, the best way to find out what is the problem is to copy the generated query from the log and try to execute it directly on MySQL.


text:
Q: Child access parent isolated scope: cell content access cell scope I may be a bit confused about scope (I've read a lot of tutorials about it, but at this point I don't understand how to make this thing), anyway, this is what I'm trying to do:
I have a table with various cells

      Bla 1
      <input ng-if="myTableCellStatus.editing" type="text" name="value" value="Bla 1">

      Bla 2
      <input ng-if="myTableCellStatus.editing" type="text" name="value" value="Bla 2">

      Bla 3
      <input ng-if="myTableCellStatus.editing" type="text" name="value" value="Bla 3">

      Bla 4
      <input ng-if="myTableCellStatus.editing" type="text" name="value" value="Bla 4">

And my-table-cell directive
angular.module('myApp').
  directive('myTableCell', [
    ->
      require:  '^myTable'
      restrict: 'AC'
      scope: {}
      link: ($scope, element, attrs, myTable) ->
        # XXX: I have some code here that allows me to access the cell from myTable
        #      I change the status from there
        myTable.addCell(
          changeStatus: (status) ->
            $scope.$apply ->
              $scope.myTableCellStatus.editing = status
          cell: element
        )
        $scope.myTableCellStatus =
          editing: false

  ])

Now, my idea was: make my-table-cell a directive with isolated scope. Then access it in its child to show/hide various elements.
Is this possible? In my code, looks like I can't in any way bind to any value of my-table-cell scope, probably because it's isolated.
Considering I'm confused, a code example about it would be lovely, I initially thought this would be the right approach, but now looks like I'm completely wrong.

A: Isolate scope is good most of the time, but in your case it won't help. If you want to have HTML inside your directive and you want to expose custom properties to those HTML elements (e.g. myTableCellStatus) - and since this HTML is not coming from your directive's template - you need a "normal" (i.e. non-isolate) scope:
app.directive('myTableCell', function () {
    return {
        ...
        scope: true,
        link: function postLink(scope, element, attrs, myTable) {
            ...
            scope.myTableCellStatus = {editing: false};
        }
    };
});

See, also, this short demo.

A: When you define an isolated scope for your directive, you are defining a private sandbox for your scope variables. Variables defined or referenced from the isolated scope will not use scope inheritance to resolve bindings.
To fix this, you can either pass in your models into your isolated scope from your parent scope through the element attributes. In your directive definition:
scope: {
      myTableCellStatus: '='
}

This sets up a two-way model binding between the myTableCellStatus variable resolved on parent scope and the scope variable on your isolated scope with the same name.
Or you can reference $parent inside your link function:
  $scope.$parent.myTableCellStatus

This works because you are referencing the parent scope from your isolated scope, which does use scope inheritance to resolve bindings.
[EDIT]
It might be obvious now that if you reference $parent, you are reaching out from your isolated scope and into your parent scope, which if shared will bind to the same model across all your directives.  This would work if you're inside a an ng-repeat, since it creates a child scope.  But if you're not inside a child directive, the model would be shared.


text:
Q: How to ensure that an SPI master sends exactly 16 clock pulses to the slave? I'm using this current sensor: TLI4970-D050T4 According to the datasheet:

How can the SPI master send exactly 16 clock pulses to the slave, so I don't receive the 0's?
When I'm reading this sensor, I get a lot of 0's. So, I thought that it might be the reason, that I'm sending more than 16 clocks pulses. I'm using an STM32 Nucleo running at 2 MHz, but the SPI clock has been prescaled to 1 MHz. I would appreciate any advice. This is the code that I use to read the sensor and calculate current:
while (1)
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);
HAL_SPI_Receive(&hspi1, (uint8_t *)&SPIRx, 2, 10);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);
motorCurrent=motor_current();

float motor_current() {

    float Iout;
    float BIout;
    int16_t Bit15;
     Bit15 = SPIRx&0x8000;
            if(Bit15==0x8000){
                HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_SET);
            }
            else {
                BIout= SPIRx&0x1FFF;
                Iout = (BIout-4096)/80;
            }
        return Iout;
     }

A: You are using HAL_SPI_Receive() wrong, second parameter should be your buffer not SPI register. Other potential problem is that you have short timeout (fourth parameter) with slow SPI clock.
You can also make living easier if you look at your hspi1 configuration and change data size to 16 bits.
EDIT
If second parameter is your buffer and not SPI register, that I would still increase timeout and check if HAL_SPI_Receive() return success or error.


text:
Q: Binding LongProperty to internal changes of ListProperty I have got three classes:
class A {
    //Duration in seconds
    private val durationProperty = SimpleLongProperty(300)
    var duration by durationProperty
}

class B(list: List<A>) {
    private val aClassesProperty = SimpleListProperty(list.observable())
    val aClasses by aClassesProperty
}

class C(classB: B, repetitions: Int){
    private val bClassProperty = SimpleObjectProperty(classB)

    private val repetitionsProperty = SimpleIntProperty(repetitions)
    val repetitions by repetitionsProperty
}

Now I would like, to create and bind durationProperty inside class B as sum of class A durationProperty (which will be sensitive to adding new class A instance into list and changing any duration of already present instance) and similarly in class C - durationProperty as duration of classB multiplied by repetitions.

A: I don't know kotlin, but the answer should be easy to translate.
You need to use an 'extractor' to handle this, using:
FXCollections#observableArrayList(Callback<E, Observable[]> extractor)

Like:
ObservableList<A> list = FXCollections.observableArrayList(item -> new Observable[] {item.durationProperty});

list.addListener((InvalidationListener) observable -> {
    //Update you sum here
});

The extractor causes any changes to the given observable array of each item in the list to trigger both the InvalidationListener and ListChangeListener of the list to be fired.

A: SephB's solution is correct, but finally I used one from there. I found it a little bit more elastic even though there is a lot of boilerplate.


text:
Q: In R, how do you subset rows of a dataframe based on values in a vector I'd like to generate a subset based on factor values contained in a vector. I've included my working code for a simple example. However, what if I have many columns (>10) and I don't wish to list each column using "|" (OR), is there a better way to do this? My example below uses LETTERS but I am dealing with factors (people's names).
set.seed(37)
df <- data.frame(id1=sample(LETTERS, 20),id2=sample(LETTERS, 20))
L <- c("A","B","E")
subset(df, id1 %in% L | id2 %in% L )
   id1 id2
2    B   V
10   C   B
11   F   A
14   A   F
19   E   S

A: You can use Reduce to construct the OR condition:
subset(df, Reduce("|", lapply(df, `%in%`, L)))

#   id1 id2
#2    B   V
#10   C   B
#11   F   A
#14   A   F
#19   E   S

Or use rowSums to check if there is any letter matching in each row:
subset(df, rowSums(sapply(df, `%in%`, L)) != 0)

#   id1 id2
#2    B   V
#10   C   B
#11   F   A
#14   A   F
#19   E   S

A: df[sort(unique(unlist(lapply(df, function(x) which(x %in% L))))),]
#   id1 id2
#2    B   V
#10   C   B
#11   F   A
#14   A   F
#19   E   S


text:
Q: Efficient XML parsing for 25GB data My aim is to parse 25 GB of XML data. An example of such a data is given below:
<Document>
<Data Id='12' category='1'  Body="abc"/>
<Data Id='13' category='1'  Body="zwq"/>
.
.
<Data Id='82018030' category='2' CorrespondingCategory1Id='13' Body="pqr"/>

However..considering the data I have of "25 GB"...my approach is quite inefficient. Please suggest some way to improve my code or an alternate approach. Also kindly include a small example code to make things clearer.

A: You might find that a SAX parser works better for this task. Rather than building a DOM, a SAX parser turns the XML file into a stream of elements and calls functions you provide to let you handle each element.
The good thing is that SAX parsers can be very fast and memory-efficient compared to DOM parsers, and some don't even need to be given all the XML at once, which would be ideal when you have 25 GB of it.
Unfortunately, if you need any context information, like "I want tag <B> but only if it's inside tag <A>," you must maintain it yourself, since all the parser gives you is "start tag <A>, start tag <B>, end tag <B>, end tag <A>." It never explicitly tells you that tag <B> is inside tag <A>, you have to figure that out from what you saw. And once you have seen an element, it's gone unless you remembered it yourself.
This gets very hairy for complex parsing jobs, but yours is probably manageable.
It happens that Python's standard library has a SAX parser in xml.sax. You probably want something like xml.sax.xmlreader.IncrementalParser.

A: My first suggestion from looking at your question would be to use a relational database such as MySQL or sqlite. It wouldn't be hard to get your XML data into this form, and then querying on that data would be both more straightforward and faster.

A: Your initial algorithm runs in O(n^2), which will be very slow for 25GB of data.  Ideally you will get it down to O(n) or O(n log n).  In the absence of any other information about the data (like whether category 1 or 2 is smaller, etc), you can do something like this (which is O(n)):
from lxml import objectify
f=open('myfile25GB', 'r')
text=f.read()
root=objectify.fromstring(text)

cat_one_bodies = {}
for e in root.attrib['Document'].row:
    category = int(e.attrib['category'])
    body = e.attrib['Body']
    if category == 1:
        e_id = int(e.attrib['Id'])
        cat_one_bodies[e_id] = body
    else: #Assuming there are only 2 categories
        cat_one_id = int(e.attrib['CorrespondingCategory1Id'])
        print "Cat1 Body: '%s' Cat2 Body: '%s'" % (body, cat_one_bodies[cat_one_id])

Although this doesn't parse your file, hopefully it shows you the idea.  It potentially uses quite a bit of memory (since it's maintaining all the category1 bodies in the dictionary), so that may be a consideration.

A: In XSLT 3.0 (draft) as currently implemented in Saxon-EE, you can write a streaming transformation that solves this problem as follows:
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:map="http://www.w3.org/2005/xpath-functions/map">
<xsl:mode streamable="yes"/>
<xsl:template match="/">
  <xsl:iterate select="Document/Data">
    <xsl:param name="map" select="map{}"/>
    <xsl:choose>
      <xsl:when test="@category='1'">
        <xsl:next-iteration>
          <xsl:with-param name="map" select="map:put($map, string(@Id), string(@Body))"/>
        </xsl:next-iteration>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="'Cat1 Body: ',
                              $map(@CorrespondingCategoryId), 'Cat2 Body', @Body"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:iterate>
</xsl:template>

I haven't tested this (it's late at night on the eve of a four-day holiday...) but if you are interested in pursuing this approach I'll be happy to help. XSLT 3.0 is still a draft spec and fairly fluid. Its focus is on solving problems like this one using a streaming approach that handles very large documents using bounded memory. Saxon-EE 9.4 implements a snapshot of the spec.

A: If the IDs are in ascending order, then you can roll out your own function that reads an element at any position in a file. Then you can just scan the entire file and for every element you can find the corresponding one using binary search algorithm. The thing will run in O(n log n) while still using negligible amount of memory.

A: Try and use iterparse from lxml. I think it will suit the problem which you wish to handle.


text:
Q: How to secure Ajax link requests? Imagine the next scenario: a user wants to register to a webpage and fills a form. While he is filling the form, jQuery keeps checking through a regular expression if fields are valid, etc...
Taking the email as the primary key which the user will use after registering to login, the email field needs to be checked with Ajax to let the user know if that email is registered or not. I want to check it with Ajax to avoid sending the full form and emptying it, refreshing page, etc...
So, when the user has ended filling the email field, the Ajax request is sent to the server, something like the next link:
example.com/check.php?email=abcdefg@gmail.com

When check.php receives the email, it asks the database if it exists or not and returns a message like: User already exists if user exists or null if user does not exist.
The question is: if someone digs through my .js and finds out links similar to that, they could use that link to send a large number of requests to find out if those random emails exist. This could lead to heavy use of the database or in the worst cases even crashing and private information leaks.
Someone could do a huge for loop to check emails like:
//Getting the response of the next links
example.com/check.php?email=aaaaaaa@gmail.com // Returns null
example.com/check.php?email=aaaaaab@gmail.com // Returns null
example.com/check.php?email=aaaaaac@gmail.com // Returns null
example.com/check.php?email=aaaaaad@gmail.com // Returns User already exists

------------------------------------------------------------------------------------------------------------------------------------
Since i last accepted the answer, i kept investigating this and found the solution to avoid this behaviour. The following code is for JAVA but the logic can be applied to any other server-side language.
Before doing ANY ajax request to the server, I request a token to the server. This token looks like this fmf5p81m6e56n4va3nkfu2ns8n it is made by a simple method, it can, however, be more complex, but this is good to go.
public String getToken() throws UnsupportedEncodingException {
    return new BigInteger(130, new SecureRandom()).toString(32);
}

When requesting the token, the server does not only return the token, but also a small script that in case someone uses browser to inspect element (and browser navbar) and such the script will run and the token will be cleared. Servlet returns something like this:
_html += ""
    + ""
    + ""
    + ""
    + "[" + token+ "]"
    + ""
    + "";

First empties the body then navigates back to wherever we want. javascript/jquery will however, catch the entire content as string, then I simply extract the string between [ and ]. This token is only available for the next request, so every AJAX request will have its unique token. On the 2nd reques the token just used is deleted.
After I get the token I append it as parameter to whatever link i request, something like this:
ajaxRequestObjet = $.ajax({
    url: "http://localhost:8084/mywebsite.com/servlet", //<-- local tomcat server
    method: "POST",
    data: "type=AJAX&page=some-article&token=fmf5p81m6e56n4va3nkfu2ns8n"
});

This method works fine against someone who inspects the website manually and try to use the links, but what about java/php/IIS servers that do this automaticly?
For this ask for header! Something like this:
boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

It will be true only and only if XMLHttpRequest exists....
There is one last thing to keep in mind. Make sure 'Access-Control-Allow-Origin' header is NOT present in your app to make sure that any javascript NOT in your server wont get the server resources. If this header does not exist, chrome will return this:
XMLHttpRequest cannot load http://localhost:8084/mywebsite.com/servlet. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

Java server was in tomcat and I had another apache for this tests, this is the small html present in apache which gave the error above:

A: You could protect against brute force attacks with something similar to CSRF tokens:
Assign a server-generated ID to every client session. Each request to check.php should include this ID.
check.php should reject requests that do not include an ID, or include an ID that the server did not generate (to prevent attacks with spoofed IDs). It should also rate limit on ID - if a given ID has made a request in (say) the last second, or a given ID makes more than n requests in a 10 second interval, it should return an error response. This protects against requests from a single session arriving from several IP addresses.
You should also rate limit by IP address to prevent brute-forcing by opening a large number of web application sessions.
There isn't much you can do to prevent an attacker looking up a single, or small number, of specific email addresses - it's an inherent risk with this type of validation.

A: One approach to resolve this problem could be this:
Suppose you have ajax request calling your server to receive a response from a particular user or client. You can have a table in your database where you provide a unique token for every user or hash value that can be checked every time user makes an ajax request to the server. If the token value matches the user request value than he is a genuine user. You can also record his number of request on the table to ensure he is making legitimate requests. I acknowledge the fact that it may slow down your app performance, but it will be safe option to consider. Note: you need to retrieve the token on your HTML page to send it with ajax.
Please comment to know more. I have been using this approach and there is no problem until now.
Example:

A: While you can not control this 100%... there are a few options..
Try using the same methods that people use with Captcha scripts..
Basically when the user loads the form / page.. You generate a random string/id in their PHP session and store it.. When they send the ajax requests, have your ajax check also append the string/id and require it before allowing a check to perform else return a header of 500 or something..
Using this approach with sessions, you could set a allowed limit of checks (say 5) and once the user has tried more than 5 checks, They are required to reload the page or perform a human check (eg Captcha).. Then it resets their count.. Even allow a total of say 30 within 1 hour / per IP or something.
Also use smart events to trigger when the ajax check is done, eg field/tab change or on a button press.. Or when a valid email is detected.. but say .com.au would trigger twice.
Basically this way, even if someone sniffed your JS files and tried to automate the email checker.. It would require them finding a way to append the string/id that you generate and also limit their amount of requests performed.
Beyond this, there is not to much more you can do easily.. But there are still a few other idea's.
Most of them would work around using a PHP session / cookie.. Say for example if they check and find 3 email addresses.. Then again you set that as a limit and force them to require a manual submission or something.
See how the above suggestion goes for you, any questions do feel free to ask. But may take me a day or two to reply as weekend.. Also research how Captcha scripts work as plenty of source code for them.. As they work on the same idea.
Time Delays will simply look bad / make your site appear slow / bug the user with waiting for a response.
You need to limit the amount of look up's per session / ip address.. Otherwise there is always a way to get past these checks.. Basically once they hit a limit.. Force the user/ip/session to wait a few minutes/hours and verify them with a Captcha script so it can not be scripted...
Javascript Security / Hiding The Source
While you can not do this truly, you can do certain things generate the JS using a PHP page with a JS header.. so  and this allows PHP to check for a valid session.. So stops external requests to an extent.. But this is mostly useful for allowing JS to be only available behind a membership/login..
Multiple Checks / If Possible In This Case
Depending on your approach, is this for a user to check if they already have an account? If so.. you could combine the email check with something like their name/country/age/dob ... So they would need to select two or three correct matching values before being able to get a check/response from the ajax call?
Maybe not in your case, but just thought would add this as well.

A: The JavaScript code on your website is executed on the computer of the user, so there is no way you could stop him from digging through your code. Even if you use a code obfuscator (for example, https://www.javascriptobfuscator.com/), the hacker could debug your application and record all requests send to the server.
Everything security-relevant has to happen on the server. You could limit the amount of requests from a specific IP address.

A: This type of attack can be treated the same as any other brute force attack, where the only effective solution is to use a Captcha. But of course, Captchas are a detriment to UX, so you have to consider if the additional security is worth it, especially for an attack that is very unlikely to happen anyway. That said, you may want to use a Captcha on your registration form anyway, to prevent bots from creating accounts.
This sort of attack has a huge cost for little reward for the attacker. There are billions of possible email addresses to test for. It could only be worth going to great lengths such as this, if the site in question was particularly sensitive, such as some kind of adult site, where the attacker hopes to blackmail users that he finds.
CloudFlare
Not as good as a Captcha solution but the brute force attack might be detected and prevented by CloudFlare's DDoS system. Also, CF can force Tor users to solve a Captcha before accessing your site, which would prevent an attacker from using Tor as a vehicle for the attack.
IP Rate Limiting
Rate limiting on an IP basis has problems because if an attacker decided to undertake a task as huge as this, he will likely be using a Botnet or some other system of multiple machines to launch the attack.
Consider a large organisation such as a University, where all users share the public IP. One of the users launches an attack on your site, and you block his IP, and in the processes blocking everyone else. This countermeasure could actually be used to launch a DoS attack.
Session ID/CRSF Token
Definitely not a solution because the attacker needs to simply make a request to the page first, to obtain the token. It's an additional request to make but only an inconvenience for the attacker.

A: First of all: I'd URL-encode the mail-address. 'example.com/check.php?email=' . urlencode(abcdefg@gmail.com)
Ad your question: when check.php is called, you can

*

*check, if the user's session and his IP have sent a request during the last seconds

*if not, write the user's session, the user's IP plus the current timestamp to a helper-table plus to a cookie and hit your DB

*if yes, block the request

But I'm afraid this won't help you from fraud because everyone can check your JavaScript and if someone want's to exploit this, he will find ways.

A: check.php should depending on the setup either only be accessible internally, or verify from where the connection is made. Take a look at this previous question- I hope it might be what you're looking for. how to verify the requesting server in php?

A: You could use a CSRF token and exit early from your script if you detect that no or an invalid CSRF token. Almost (if not all) PHP frameworks come with support for this.
Also check this question from the security community: https://security.stackexchange.com/questions/23371/csrf-protection-with-custom-headers-and-without-validating-token


text:
Q: Is there a way to check registry definitions in Forefront on remote systems? After playing with the script found in This Thread yesterday, I found that the script did exactly what I was looking for. However, I need to run these checks on remote systems on our network. I spent a few hours altering the script, but could not get it to run on the checks against the specified computers. I'm quite new to scripting, so I'm probably not seeing the glaring mistake. Can anyone assist with this? Any assistance would be much appreciated.
When ran, the script does not break with any errors. It does prompt for a system name, which is intended and will break if the name is incorrect or the system is not online. If the specified machine is online, the script will proceed to echo values. However, the values that are returned are of the local system and not of the remote.
 strInput = UserInput( "Enter System Name:" )
 WScript.Echo "You entered: " & strInput

 Function UserInput( myPrompt )
     If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then
                WScript.StdOut.Write myPrompt & " "
         UserInput = WScript.StdIn.ReadLine
     Else
        UserInput = InputBox( myPrompt )
     End If
 End Function

 strComputer = strInput
 Set objWMIService = GetObject("winmgmts:" _
  & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
 'Option Explicit
 FCS_REGKEY_ROOT = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft Antimalware"

 Dim SCAN_KEY, SIGNATUREUPDATES_KEY
 Dim AV_VERSION_VALUE, AS_VERSION_VALUE, ENGINE_VERSION_VALUE, AV_DATE, AS_DATE
 Dim LAST_SCAN_TIME, LAST_SCAN_TYPE, INSTALL_PATH_VALUE
 SCAN_KEY=FCS_REGKEY_ROOT & "\Scan"
 SIGNATUREUPDATES_KEY = FCS_REGKEY_ROOT & "\Signature Updates"
 INSTALL_PATH_VALUE= FCS_REGKEY_ROOT & "\InstallLocation"
 AV_VERSION_VALUE= SIGNATUREUPDATES_KEY &"\AVSignatureVersion"
 AS_VERSION_VALUE= SIGNATUREUPDATES_KEY &"\ASSignatureVersion"
 ENGINE_VERSION_VALUE= SIGNATUREUPDATES_KEY &"\EngineVersion"
 AV_DATE= SIGNATUREUPDATES_KEY &"\AVSignatureApplied"
 AS_DATE= SIGNATUREUPDATES_KEY &"\ASSignatureApplied"
 LAST_SCAN_TIME= SCAN_KEY & "\LastScanRun"
 LAST_SCAN_TYPE= SCAN_KEY & "\LastScanType"

 '************ MAIN ************
 Dim AV_Version, AS_Version, EngineVersion, ProductVersion
 Dim AV_BuildDate, AS_BuildDate, LastScanTime, LastScanType
 Dim objShell
 set objShell      = CreateObject("WScript.Shell")

 '============ Get current info ============
 AV_Version = objShell.RegRead(AV_VERSION_VALUE)
 AS_Version = objShell.RegRead(AS_VERSION_VALUE)
 EngineVersion = objShell.RegRead(ENGINE_VERSION_VALUE)
 AV_BuildDate = BinaryToDate( objShell.RegRead(AV_DATE) )
 AS_BuildDate = BinaryToDate( objShell.RegRead(AS_DATE) )
 ProductVersion = GetProductVersion(INSTALL_PATH_VALUE)
 LastScanTime = BinaryToDate( objShell.RegRead(LAST_SCAN_TIME) )
 LastScanType = GetScanType( objShell.RegRead(LAST_SCAN_TYPE) )

 '============  Display summary info ============
 WScript.echo "Microsoft Forefront Client Security version:  " & ProductVersion
 WScript.echo "Engine version:  " & EngineVersion
 WScript.echo "Antivirus Definition:  Version " & AV_Version & " created on " & AV_BuildDate
 WScript.echo "Antispyware Definition:  Version " & AS_Version & " created on " & AS_BuildDate
 WScript.echo "Last scan:  " & LastScanTime & " (" & LastScanType & ")"

 '************ END MAIN ************

 '===============================================================
 'Function BinaryToDate will covert a binary DATE_TIME structure into a Variant date set to the local time
 '  Parameter: bArray - a VARIANT array of bytes
 '  Return: a VARIANT date
 Function BinaryToDate(bArray)
 dim Seconds,Days,dateTime
 Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
  Seconds       = bArray(7)*(2^56) + bArray(6)*(2^48) + bArray(5)*(2^40) + bArray(4)*(2^32) _
                      + bArray(3)*(2^24) + bArray(2)*(2^16) + bArray(1)*(2^8) + bArray(0)
  Days            = Seconds/(1E7*86400)
  dateTime.SetVarDate   CDate(DateSerial(1601, 1, 1) + Days ), false
  BinaryToDate = dateTime.GetVarDate ()
 End Function

 '===============================================================
 'Function GetProductVersion will query a registry key for the file location and then return the version from the filesystem
 '  Parameter: strRegPath - path to the registry pointing to the installation location
 '  Return: a VARIANT string containing the product version
 Function GetProductVersion(regPath)
  const FILE_TO_CHECK = "\msmpeng.exe"
  dim strFilePath, objFSO
  strFilePath = objShell.RegRead(regPath) & FILE_TO_CHECK
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  GetProductVersion = objFSO.GetFileVersion(strFilePath)
  Set objFSO = Nothing
 End Function

 '===============================================================
 'Function GetScanType will return a string with the scan type that corresponds to the enum
 '  Parameter: iScanType - type of scan
 '  Return: a VARIANT string containing text type of scan
 Function GetScanType(iScanType)
  Select case(iScanType)
    Case 1 : GetScanType= "Quick Scan"
    Case 2 : GetScanType= "Full Scan"
    Case Else GetScanType= "Invalid Scan type"
  End Select
 End Function


text:
Q: Player on Player collision in pygame I'm trying to create a collision detection between 4 controllable characters on an RPG battle map. Here is the function I'm using
def player_collission(Lord_x,Lord_y,Journeyman_x,Journeyman_y,Archer_x,Archer_y,
                  Cleric_x,Cleric_y):
print("Running")
if abs(Lord_x - Journeyman_x) <= 0 and abs(Lord_y - Journeyman_y) <= 0:
    print("Colission detected")
    return True
elif abs(Lord_x - Archer_x) <= 0 and abs(Lord_y - Archer_y) <= 0:
    print("Colission detected")
    return True
elif abs(Lord_x - Cleric_x) <= 0 and abs(Lord_y == Cleric_y) <= 0:
    print("Colission detected")
    return True
elif abs(Journeyman_x - Archer_x) <= 0 and abs(Journeyman_y - Archer_y) <= 0:
    print("Colission detected")
    return True
elif abs(Journeyman_x - Cleric_x) <= 0 and abs(Journeyman_y - Cleric_y) <= 0:
    print("Colission detected")
    return True
elif abs(Archer_x - Cleric_x) <= 0 and abs(Archer_y == Cleric_y) <= 0:
    print("Colission detected")
    return True
else:
    return False #I didnt use classes so it has alot of if statements

if player_up:
    p_collide = player_collission(Lord_x,Lord_y,Journeyman_x,Journeyman_y,Archer_x,Archer_y,
                  Cleric_x,Cleric_y)
    if current_player == "lord":
        if p_collide != True:
            Lord_y -= tile_increment
        if Lord_y <= 0:
            Lord_y = 50

What happens is that the characters still move into each other but it detects the collision after it has already moved into each other and freezes all movement. I'm not sure how to re arrange it to make it work properly.

A: You detect collision when it has already happened. This is why you see characters overlapping.
Instead, you should detect if a collision is going to happen, an prevent a motion that would lead to that.
An example:
def move(coords, velocity):
  """Moves coords according to velocity."""
  x, y = coords  # Unpack a 2-tuple.
  vx, vy = velocity
  return (x + vx, y + vy)

tom_coords = (0, 0)  # Tom is in the corner.
tom_v = (1, 1)  # Tom moves by diagonal.

jerry_coords = (5, 0)  # Jerry is a bit away from Tom.
jerry_v = (0, 1)  # Jerry moves vertically.

while True:
  new_tom_coords = move(tom_coords, tom_v)  # Tom moves without fear.
  new_jerry_coords = move(jerry_coords, jerry_v)
  if new_jerry_coords == new_tom_coords:  # Would be a collision!
    new_jerry_coords = jerry_coords  # Back to previous tile.
    vx, vy = jerry_v
    jerry_v = (-vx, -vy)  # Jerry runs back.
    print("Collision imminent, Jerry runs away!")
  else:
    jerry_coords = new_jerry_coords  # Only update if no collision.
  # Could also check collisions with walls, etc.
  tom_coords = new_tom_coords
  # Not inside pygame, so just print it and wait for a key press.
  print('Tom:', tom_coords, 'Jerry:', jerry_coords)
  input("Enter to continue, Ctrl+C to stop ")

Run it in and see how Tom and Jerry come close to each other but never occupy the same tile.


text:
Q: Selector to extract element value of type different tagName There is String on my web page which looks as "@Account9 Hey Dude". @Account9 is a link, 'Hey Dude' is span. Please help me to create Selector to extract this  "@Account9 Hey Dude".
note: Can find something like selenium "normalize-space" method.

        @Account9

 Hey Dude

A: To create a selector that extracts the inner text of the provided markup:

    @Account9

 :Hey Dude</span

you need to find the first parent of these elements (div class="XYZ123 and span class="ABCxyz123") , specify CSS selector for it and call innerText property.
const targetText = await Selector('<parent_of_these_elements>').innerText;


text:
Q: Determinant from a Rank r perturbation from Golub paper In the following paper:

Restricted Rank Modification of the Symmetric Eigenvalue Problem: Theoretical Considerations

on page 79, Golub et al. have the following set of equations:
$f(\lambda) = \text{det}(I_r - U^T(\lambda - \Lambda)^{-1}U) \quad ... (1) \\
\quad =1 + \sum_{k=1}^r (-1)^k \sum_{\tau_k=1}^r\sum_{j_k=1}^n\frac{(\text{det}U_{j_1,...,j_k;\tau_1,...,\tau_k})^2}{(\lambda - \lambda_{j_1})...(\lambda - \lambda_{j_k})} \quad ... (2)$
where,
$\text{det}U_{j_1,...,j_k;\tau_1,...,\tau_k} = \begin{bmatrix}e^T_{j_1}\\ \vdots\\e^T_{j_k}\end{bmatrix} U \begin{bmatrix}e_{\tau_1}&\ldots& e^T_{\tau_k}\end{bmatrix}$,
and $\Lambda = \text{diag}(\lambda_1,...\lambda_n)$ are the eigenvalues for a matrix $A = Q\Lambda Q^T \in \mathbb{R}^{n \times n}$ and $V=QU$
However I am not sure how he goes from one line to the other (i.e. from Equation (1) to Equation (2)).
Golub et al. state that is fairly trivial and it exploits the multi-linearity property of the determinant, however I cannot seem formulate the steps.
Let me know if you require any further information.


text:
Q: Evaluation of Euler's q-function Euler prove the Pentagonal number theorem, which is about the denominator of the generating function for the partition function $p(n)$, that is
$$\phi(q)=\prod_{k=1}^\infty(1-q^k)=\sum_{n=-\infty}^\infty(-1)^nq^{(3n^2-n)/2}$$
My question is: can we determine the a closed form of $\phi(q)$ for special rational values of $q$? (e.g., $\phi(1/2)$ or $\phi(1/3)$)


text:
Q: Oracle SQL to JSON I'm trying to convert a query to JSON format, so I can use it with streaming data. I searched in the oracle documentations how to do it, but I'm getting this error on line 6, what could it be?

Error: ORA-00406: the COMPATIBLE parameter must be 12.0 or greater
00406. 00000 -  "COMPATIBLE parameter needs to be %s or greater"
*Cause:    The COMPATIBLE initialization parameter is not high
enough to allow the operation. Allowing the command would make
the database incompatible with the release specified by the
current COMPATIBLE parameter.

Oracle documentation: https://oracle-base.com/articles/19c/json_object-enhancements-19c
When I run the query that return the database version comes 19.0.0.0
SELECT
     JSON_OBJECT(h.loca_nm_local, j.cllo_nm_cluster_log) AS json_data
FROM
     db1.local         h
     LEFT JOIN db1.local_cluster i ON h.loca_sq_local = i.loca_sq_local
     LEFT JOIN db1.cluster_log   j ON i.cllo_sq_cluster_log = j.cllo_sq_cluster_log
WHERE
    ( j.cllo_nm_cluster_log LIKE '%NEB%'
    OR j.cllo_nm_cluster_log LIKE '%SOB%'
    OR j.cllo_nm_cluster_log LIKE '%BC%'
    OR j.cllo_nm_cluster_log LIKE '%BS%'
    OR j.cllo_nm_cluster_log LIKE '%BUZ%'
    OR j.cllo_nm_cluster_log LIKE '%ES-%'
    OR j.cllo_nm_cluster_log LIKE '%LBR-%'
    OR j.cllo_nm_cluster_log LIKE '%ES0%' )

A: As the error states, in order to use that function, you must have a minimum COMPATIBLE parameter of "12.0" You can check your current value for the COMPATIBLE parameter with the following query:
Select name,value
from v$parameter
where name like 'comp%';

You can read the details around the COMPATIBLE parameter here in the oracle documentation, including how to change it (and the ramifications of doing so):
https://docs.oracle.com/en/database/oracle/oracle-database/19/upgrd/what-is-oracle-database-compatibility.html


text:
Q: Python call function with list from loop I have a function getloantype(account_no) which I would like to call. The account numbers are in a list ['10101-2','10101-2', '10101-3'] and I would like the function to run one by one through all the account numbers and put all the results into another list. However, I cannot seem to get my code to run.
What I do: first, I get the user to input his userID and use it to fetch all the bank accounts that he owns from SQL database:
userid = input("Please enter user id")

conn=create_connection()
def getacct(userid):
    query = """\
        select Account_Number
        from User_Account
        where UserID = '{}'
        """ .format(userid)

    return (execute_read_query (conn, query))

account_no = getacct(userid)

As such, the account numbers would end up being in a list [account_no]. Next, I will need to use the account number to fetch his Loan ID. From this part comes the first question. Am I supposed to code it as getloanid(account_no) or getloanid(x) whereby x is for x in account_no ?
def getloanid(x):
    query = """\
        select SUBSTRING(LoanID, 1, 2)
        from Account_Delinquency
        where Account_Number = '{}'
        """ .format(account_no)

    return (execute_read_query (conn, query))

From here, I assume that I should do a nested for loop but the way I coded it, the list remains empty.
loanlist = []

for i in account_no:
    for x in i:
        getloanid(x)
        loanlist.append(i[0])

I have also tried this which would return error :

'NoneType' object is not iterable

mylist = []
loanlist = []

for i in account_no:
    mylist.append(i[0])

for x in mylist:
    a = getloanid(x)
    for i in a:
        loanlist.append(i[0])

How can I code it such that I can call the function getloantype(account_no) with all the account numbers in the list account_no = getacct(userid) and have all the results be appended into a new list [loanlist]?

A: It is not so clear the structure of your program, and data returned from functions, but if I can undestand, a possible simple solution could be somthing like this:
result_list = [getloantype(account_no) for account_no in account_list]


text:
Q: Open jQuery accordion panel with link (outside of acccordion) Still new to jQuery!
I have an accordion that was built with the jQuery UI 1.10.1. It's pretty basic; the first item is showing by default, and the others are hidden until clicked on. I'd like to use links that exist above a jQuery accordion to open a certain accordion panel when clicked. It looks something like this:
Link1  Link2  Link3
| Accordion Header 1  |
| Accordion content 1 showing|
| Accordion Header 2  |
| Accordion content 2 hidden |
| Accordion Header 3  |
| Accordion content 3 hidden |
..so that when you click on "Link2", it hides Accordion content 1 and shows Accordion content 2.
I've searched the site and none of the answers seemed fitting.
Thanks

A: You could probably use a different method for linking the button to the header sections, I just used the id from the button.
But essentially:
$( "#accordion" ).accordion();

$('.section-button').on('click', function(){
  var header = $('#accordion').find('.' + this.id);
  header.click();
});

Demo here

A: As of Jul 1st 2018, if you run into this you can do:
$('#accordion').accordion({active:0})

Replace the 0 with the index of the tab. 0 will open the first, 1 the next etc..


text:
Q: How to store special characters (', ", &, etc) in mysql database, so they can be searchable? Im having a small problem with storage of special characters like quotes, double quotes and ampersands. I put every POST request through mysql_real_escape_string(), and when I add a string like "That '70s Show" it gets stored as "That '70s Show" in the mysql DB. When I echo it out, it works fine... but when I try to run a % $string % search for "That '70s Show", it will not find the record. I have magic_quotes disabled.
How can I get around this?

A: It looks like the problem is that you're not just running the incoming data that you store in the database through mysql_real_escape_string(), but also htmlentities() or a relative.  Is that the case?  If so, quit. :)

A: Quoted from Mysql reference doc
There are several ways to include quote characters within a string:

*

*A "'" inside a string quoted with "'"  may be written as "''".

*A """ inside a string quoted with """  may be written as """".

*Precede the quote character by an escape character ("\").

*A "'" inside a string quoted with """ needs no special treatment and need
not be doubled or escaped. In the same way, """ inside a string quoted
with "'" needs no special treatment.
The following SELECT statements demonstrate how quoting and escaping work:
mysql> SELECT 'hello', '"hello"', '""hello""', 'hel''lo', '\'hello';
+-------+---------+-----------+--------+--------+
| hello | "hello" | ""hello"" | hel'lo | 'hello |
+-------+---------+-----------+--------+--------+

Refer : http://dev.mysql.com/doc/refman/5.0/en/string-syntax.html


text:
Q: Syntax error for nested condtionals in SQL I'm pretty new to redshift and I've been trying to to do a nested case when condition here, yet I get a syntax error

ERROR:  syntax error at or near ")"

in this line of SQL:
ELSE ROUND((last_bid * positions), 2))

I'm not sure what's wrong, since I'm familiar with Python and I'm pretty sure this is how nested conditions work
SELECT
    *,
    CASE
       WHEN asset_type = 'EQUITY'
          THEN (CASE
                   WHEN positions < 0 THEN ROUND((positions * last_ask), 2)
                   ELSE ROUND((last_bid * positions), 2))
          ELSE ROUND((positions * last_ask/100), 2)
    END AS MARKET_VALUE
FROM
    base_report

A: You should end the nested CASE, like that:
ELSE ROUND((last_bid * positions), 2)
END
)

A: SELECT *,

    CASE
    WHEN asset_type = 'EQUITY' THEN
    (
    CASE
    WHEN positions < 0 THEN
    ROUND((positions * last_ask), 2)
    ELSE ROUND((last_bid * positions), 2)
    END )
    ELSE ROUND((positions * last_ask / 100), 2)
    END AS MARKET_VALUE
FROM base_report

Please do let me know if this works

A: Please try this:
SELECT *

     , CASE
        WHEN asset_type ='EQUITY' THEN
        (CASE
        WHEN positions < 0 THEN ROUND((positions * last_ask),2)
        ELSE ROUND((last_bid * positions),2) end)

        ELSE ROUND((positions * last_ask/100),2)
      END  as MARKET_VALUE

FROM base_report


text:
Q: Как определить повторение буквы в строке на языке Golang Функция должна определить есть ли повторяющиеся буквы (английские) без учета регистра в строке. Язык Golang.
Мой код:
func IsIsogram(word string) bool {
   return regexp.MatchString(`([a-z]).*\1`, word.toLowerCase())
}

Компилятор ругается на регулярное выражение. Не пойму почему, ведь оно составлено верно.

A: В текущей (1.14) версии языка Go отсутствует поддержка многих возможностей в регулярных выражениях, в том числе, обратная ссылка на группы.
Задача решена так:
package isogram

import (
    "strings"
    "unicode"
)

// IsIsogram determines if a word or phrase is an isogram.

func IsIsogram(word string) bool {
    var bitset uint32 = 0
    for _, c := range strings.ToLower(word) {
        if unicode.IsLetter(c) {
            if index := c - 'a'; bitset&(1<<index) == 0 {
                bitset |= 1 << index
            } else {
                return false
            }
        }
    }
    return true
}

A: Так как Golang не поддерживает обратных ссылок (которые используются в представленном регулярном выражении \1), то в ответе с SO предлагают использовать golang-pkg-pcre, с более полной поддержкой регулярных выражений.

Просто регулярное выражение для поиска повторяющихся букв (от двух) с использованием обратной ссылки на группу
(.)\1+


text:
Q: Searching through many excel files in same folder (C#) This is what I want to accomplish:
I have a worksheet in excel with about 100 product IDs as well as the products' corresponding price and supplier (let's call that worksheet_1).  I would like the price and supplier to be automatically updated every time a purchase order is placed into a folder for that product. Each purchase order is an excel file with information including the product ID, supplier, price and date.
Here is the general logic:
One by one, the program will read each product ID from worksheet_1 using a while loop.  I will then have the program search for the product ID in every purchase order in the folder mentioned previously.  This is the part I am most unsure about, because the number of files in the folder will be variable (as purchase orders are added regularly) and most purchase orders in the folder will be within subfolders.  Anyway, for each instance of the product ID found in a purchase order; the date, supplier and price will be sent to an SQL database. The price and supplier that correspond to the most recent date will then be put back into the original excel worksheet_1.
First and foremost I would like to know how to read all the excel files from the same folder (but different subfolders) so that I can search for a particular product ID.  I think once I get that piece I can figure the rest out, but let me know if something is wrong with my logic or if there is an easier way.
Thanks

A: To search a directory and its subfolders, try Directory.GetFiles - http://msdn.microsoft.com/en-us/library/ms143316.aspx
public static string[] GetFiles(
    string path,
    string searchPattern,
    SearchOption searchOption
)

foreach (string fil in Directory.GetFiles(dir, "*.xls"))
{
  //do some stuff with your .xls files
}


text:
Q: js doesn't work I have an rails application, yesterday I tested all my js and it worked fine, now I make some changes on it and js doesn't work correctly (the code from application.js doesn't execute correctly, the thickbox plugin still works fine), the funny thing is that I get my yesterday version from backup and now the same js problem appears, I check it in chrome and firefox4, anyone has some guesses?
js code:
$(window).load(function(){
var count;
$.getJSON("/carts/on_card", function(data){
    count = data;
    $("#products_count").text(count);
});

$("#first_element").removeClass("page_item");
$("#first_element").addClass("current_page_item");
});

$(document).ready(function(){

var count;

$(".add_to_card").click(function(){
    $.getJSON("/carts/on_card", function(data){
        count = 0;
        count = data;
    });

    $("#products_count").text(count);
});

$(".removable").click(function(){
    $(this).remove();
});

$(".page_item").click(function(){
    $(".current_page_item").removeClass("current_page_item");
    $(".current_page_item").addClass("page_item")

    $(this).removeClass("page_item");
    $(this).addClass("current_page_item");
})
});

A: Are you familiar with the cache mechanism? Maybe you are seeing same results because the JS in the cache is still the incorrect one? Or in the other direction - the yesterday's version also contains a bug, but yesterday you were testing the page when the older (correct) JavaScript was still in the cache?
If cache is not the problem here, maybe some other script or HTML is currently different and interacts with the code in a different way than previously (some scripts require specific classes or attributes to be added to the elements they should process).
Anyway, did anything else change since it worked? Maybe you installed some plugin? Maybe you changed URLs? Maybe location of the script? Tell us more.


text:
Q: Why does the Weyl vector $\rho = \sum_{\lambda_i\in\Lambda_W} \lambda_i = \dfrac 12 \sum_{\alpha_i \in\Lambda_R^+}\alpha_i$ represents vacuum? I was reading https://arxiv.org/pdf/1003.2861.pdf, and in p.5, just below equation (3.1), it was written that

The state $|\rho\rangle$ associated with the Weyl vector $\rho$ corresponds to the vacuum (no Wilson loop inserted).

Here $\rho$ is given by $\sum_{\lambda_i\in\Lambda_W} \lambda_i = \dfrac 12 \sum_{\alpha_i \in\Lambda_R^+}\alpha_i$. I was puzzled why this is true. I would think like, why is the vacuum not represented by $|0\rangle$?
I read from math.stackexchange that somehow this $\rho$ is called Weyl vector and is some kind of $0$ in certain kind of cohomology, and appears in the equation of the (affine) action $w\cdot \lambda = w(\lambda + \rho)-\rho$ of the Weyl group.
Can you help me put the bits and pieces together and tell me a complete picture why the quote is true? Thank you.


text:
Q: Spark Model serving: How to compute the state just once, then keep the state to answer all real-time requests? (recommendation engine) I try to implement a recommendation engine using Kafka to collect real-time click data and then process it using Spark Structured Streaming. My problem is about how to server predictions in near real-time using this streaming dataframe.
What works fine is: collecting click data, sending to Kafka, subscribing from Spark, using Strcutured Streaming to compute a dataframe which describes the 'state of a visitor'. Now having this streaming dataframe, there are just few lines of code (business logic) telling which is the best recommendation.
Now my problem is: how do I put this in production. I could create a mlflow.pyfunc model. But this would not contain the 'state of a visitor' dataframe. When looking at model serving frameworks, I understand that every inference request would create an independent runtime which would have to do the whole data pipeline again.
My idea would be to have 1 Spark instance which would:

*

*create this streaming dataframe

*wait for incoming request and answer those by using the dataframe from (1.)

Is this a reasonable approach? If yes: How do I set this up? If no: What is the preferred way to do real-time recommendations?


text:
Q: How do you insert characters into middle of string? C++ The purpose of this code is to insert an x in between repeating letters. For example, if I were to input "CoolBoolFallmoose", the output would be "CoxolBoxolFalxlmoxose".
The code is also supposed to make an even number of pairs of letters, so if there is an odd amount of characters, an x is added to the end of the string. An example for this would be if we had "ball", it would become "balxlx" to make even pairs: "ba" "lx" "lx".
This is the code I have so far:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main(){
    string cipher, plain, paired = "";
    cout << "input plaintext(no spaces, lowercase):\n";
    cin >> plain;

    for (int i=0;i<plain.length();i++){
        if (plain[i]==plain[i+1]){
            plain.insert(i,'x');
        }
        paired[i]=paired[i];
        cout<<paired[i];
    }

    if (paired.length() % 2!= 0){
        paired=+'x';
    }

    cout<<paired<<endl;
    return 0;
}

The output I get is just the same as my input, no "x" added in any place.
The issue I am having is, every time I try to use the append() or insert() function for strings, I get an error from my compiler, which is xCode. Is there another way to solve this code?
EDIT: The error says:

No matching member function to call for insert

It also comes up for append().

A: I don't really know what you wanted to do with this part:
paired[i]=paired[i];
cout<<paired[i];

but otherwise the logic is good. Here is my take on it, x is a counter:
#include <iostream>
#include <string>
using namespace std;

int main(){
    string m,n;
    int x = 0;

    cout << "Input: " << endl;
    getline(cin, m);

    for(int i = 0;i < m.length();i++){
        x++;
        n = n + m[i];
        if(m[i] == m[i+1]){
            n = n + 'x';
            x++;
        }
    }
    if((x % 2) != 0){
        n = n + 'x';
    }
    cout << n;

    return 0;
}

A: If you look at the available overloads of std::string::insert(), you will see that your statement plain.insert(i,'x'); does not match any of them, hence the compiler error.  The overloads that takes a single char require either:

*

*an index and a count (you are omitting the count)

*an iterator and an optional count
There is, however, a couple of overloads that take just an index and a value, but they require a const char* or a std::string, not a single char.
Also, paired[i]=paired[i]; is a no-op. Except in your case, since paired has a size() of 0 since you never append anything to paired, so actually any access to paired[...] is undefined behavior.
Try this instead:
#include <iostream>
#include <string>
using namespace std;

int main(){
    string plain, paired;
    cout << "input plaintext(no spaces, lowercase):\n";
    cin >> plain;

    paired = plain;
    for (string::size_type i = 1; i < paired.size(); ++i){
        if (paired[i] == paired[i-1]){
            paired.insert(i, 1, 'x');
            // or: paired.insert(paired.begin()+i, 'x');
            // or: paired.insert(i, "x");
            // or: paired.insert(i, string{'x'});
            // or: paired.insert(paired.begin()+i, {'x'});

            ++i; // skip the x just inserted
        }
    }

    if (paired.size() % 2 != 0){
        paired += 'x';
    }

    cout << paired << endl;
    return 0;
}

Demo

A: A couple of points
First, Although the string.insert function says it takes an int as its first argument it really  wants an iterator in this case.
Second, you are inserting elements into your "plain" string which increases its length and you have plain.length within your loop so you create an infinite loop.
Third, insert inserts BEFORE the index so you need to add 1 to I.
The code below will work for your loop:
Int len = plain.length();

Int count = 0;

for (int i = 0;  i < len + count; i++)
   {
       If (plain[i] == plain[i + 1])
          {
             plain.insert(plain.begin() + (i +1), 'X');
             ++count;
          }
   }

cout << plain;

And as, mentioned below, if you want to handle spaces you can use getline(cin, plain) instead of cin.


text:
Q: How to print out each bit of a floating point number? I am trying to print out each bit of a floating point number in C.
I am able to do it for integers with this:
int bit_return(int a, int loc)

// Bit returned at location
{
  int buf = a & 1<<loc;

  if (buf == 0)
    return 0;
  else
    return 1;
}

The compiler wouldn't compile if I replaced int a with float a.
Is there a solution for this?

Copy and reformat your comment below
OK, for people who are not clear, I post my whole code here:
#include <stdio.h>
#include <stdlib.h>

int bit_return(int a, int loc) // Bit returned at location
{
  int buf = a & 1<<loc;
  if (buf == 0)
    return 0;
  else
    return 1;
}

int main()
{
  int a = 289642; // Represent 'a' in binary
  int i = 0;
  for (i = 31; i>=0; i--)
  {
    printf("%d",bit_return(a,i));
  }
  return 0;
}

A: Thanks to Pascal Cuoq for his comment. I finally figure out how to solve my own problem. Yes, just assign address of the float number to a pointer to integer then dereference it.
Here is my code solution:
#include <stdio.h>

// bit returned at location
int bit_return(int a, int loc)
{
    int buf = a & 1<<loc;

    if (buf == 0) return 0;
    else return 1;
}

int main()
{
    //11000010111011010100000000000000
    // 1 sign bit | 8 exponent bit | 23 fraction bits
    float a = -118.625;
    int *b;
    b = &a;

    int i;
    for (i = 31; i >= 0; i--)
    {
        printf("%d",bit_return(*b,i));
    }

    return 0;
}

A: Cast the address of your float to the address of an int of the same size, and pass that int to your existing function.

A: static void printme(void *c, size_t n)
{
  unsigned char *t = c;
  if (c == NULL)
    return;
  while (n > 0) {
    --n;
    printf("%02x", t[n]);
  }
  printf("\n");
}

void fpp(float f, double d)
{
  printme(&f, sizeof f);
  printme(&d, sizeof d);
}

*

*A note on float parameters
Be sure you have the prototype for fpp() in scope when you call it or you will invoke an obscure K&R C vs ANSI C issue.

Update: binary output...
  while (n > 0) {
    int q;
    --n;
    for(q = 0x80; q; q >>= 1)
      printf("%x", !!(t[n] & q));
  }

A: In C language, the term "bit" refers to an element of binary positional representation of a number. Integral numbers in C use binary positional representation, which is why they have "bits". These are the bits you "see" by means of bitwise operators (logical and shifts). Floating-point numbers do not use that representation. Moreover, representation of floating-point numbers is not defined by the language specification, In other words, floating-point numbers in C do not have "bits", which is why you won't be able to access any of their "bits" by any legal means of the language, and which is why you can't apply any bitwise operators to floating-point objects.
Having said that, I'd suspect that you might be interested in physical bits representing a floating-point object. You can reinterpret the memory occupied by the floating-point object (or any other object) as an array of unsigned char elements and print the bits of each of the unsigned char objects. That will give you the map of all physical bits representing the object.
However, this won't be exactly equivalent to what you have in your code above. Your code above prints the bits of value representation of an integral object (i.e it is the logical bits I described above), while the memory reinterpretation approach will give you the bits of the object representation (i.e. the physical bits). But then again, floating-point numbers in C don't have logical bits by definition.
Added later: I feel that understanding the difference between the concepts of physical and logical bits might not be an easy task for some readers. As another example that might help to promote the understanding, I'd like to note that there's absolutely nothing that would preclude a perfectly compliant C implementation on ternary hardware, i.e. hardware that does not have physical binary bits at all. In such implementation bitwise operations would still work perfectly fine, they would still access binary bits, i.e. elements of [now only imaginary] binary positional representation of each integral number. That would be the logical bits I'm talking about above.

A: The following code assumes floats and pointers are the same size, which is true on many systems:
float myfloat = 254940.4394f;
printf("0x%p", *(void**)(&myfloat));

A: While from comments it seems that outputing the bits of the internal representation may be what was wanted, here is code to do what the question seemed to literally ask for, without the lossy conversion to int some have proposed:
Outputing a floating point number in binary:
#include <stdio.h>
#include <stdlib.h>

void output_binary_fp_number(double arg)
{
    double pow2;

    if ( arg < 0 ) { putchar('-'); arg = -arg; }
    if ( arg - arg != 0 ) {
        printf("Inf");
    }
    else {
        /* compare and subtract descending powers of two, printing a binary digit for each */
        /* first figure out where to start */
        for ( pow2 = 1; pow2 * 2 <= arg; pow2 *= 2 ) ;
        while ( arg != 0 || pow2 >= 1 ) {
            if ( pow2 == .5 ) putchar('.');
            if ( arg < pow2 ) putchar('0');
            else {
                putchar('1');
                arg -= pow2;
            }
            pow2 *= .5;
        }
    }

    putchar('\n');

    return;
}

void usage(char *progname) {
    fprintf(stderr, "Usage: %s real-number\n", progname);
    exit(EXIT_FAILURE);
}

int main(int argc, char **argv) {
    double arg;
    char *endp;

    if ( argc != 2 ) usage(argv[0]);
    arg = strtod(argv[1], &endp);
    if ( endp == argv[1] || *endp ) usage(argv[0]);

    output_binary_fp_number(arg);

    return EXIT_SUCCESS;
}

A: If you want to use your bit_return function on a float, you can just cheat:
float f = 42.69;

for ....
   bit_return((int) f, loc)

The (int) cast will make the compiler believe you're working with an integer, so bit_return will work.
This is essentially what Pascal was suggesting.
EDIT:
I stand corrected by Pascal. I think this will conform with his latest comment:
bit_return (*((float *) &f), loc)

hope I got it right that time.
Another alternative (with fewer parentheses) would be to use a union to cheat on the data type.

A: I have included code which produces hexadecimal output that I think may help you understand floating-point numbers.  Here is an example:

double: 00 00 A4 0F 0D 4B 72 42 (1257096936000.000000)     (+0x1.24B0D0FA40000 x 2^40)

From my code example below, it should become obvious to you how to output the bits.  Cast the double's address to unsigned char * and output the bits of sizeof(double) chars.
Since I want to output the exponent and significand (and sign bit) of a floating-point number, my example code digs into the bits of the IEEE-754 standard representation for 64-bit 'double precision' floating pointing point in radix 2.  Therefore I do not use sizeof(double) other than to verify that the compiler and I agree that double means a 64-bit float.
If you would like to output the bits for a floating-point number of any type, do use sizeof(double) rather than 8.
void hexdump_ieee754_double_x86(double dbl)
{
    LONGLONG ll = 0;
    char * pch = (char *)≪
    int i;
    int exponent = 0;

    assert(8 == sizeof(dbl));

    // Extract the 11-bit exponent, and apply the 'bias' of 0x3FF.
    exponent = (((((char *)&(dbl))[7] & 0x7F) << 4) + ((((char *)&(dbl))[6] & 0xF0) >> 4) & 0x7FF) - 0x3FF;

    // Copy the 52-bit significand to an integer we will later display
    for (i = 0; i < 6; i ++)
        *pch++ = ((char *)&(dbl))[i];
    *pch++ = ((char *)&(dbl))[6] & 0xF;

    printf("double: %02X %02X %02X %02X %02X %02X %02X %02X (%f)",
           ((unsigned char *)&(dbl))[0],
           ((unsigned char *)&(dbl))[1],
           ((unsigned char *)&(dbl))[2],
           ((unsigned char *)&(dbl))[3],
           ((unsigned char *)&(dbl))[4],
           ((unsigned char *)&(dbl))[5],
           ((unsigned char *)&(dbl))[6],
           ((unsigned char *)&(dbl))[7],
           dbl);

    printf( "\t(%c0x1.%05X%08X x 2^%d)\n",
            (((char *)&(dbl))[6] & 0x80) ? '-' : '+',
            (DWORD)((ll & 0xFFFFFFFF00000000LL) >> 32),
            (DWORD)(ll & 0xFFFFFFFFLL),
            exponent);
}

Nota Bene: The significand is displayed as a hexadecimal fraction ("0x1.24B0D0FA40000") and the exponent is display as decimal ("40").  For me, this was an intuitive way to display the floating-point bits.

A: Print the integer part, then a '.', then the fractional part.
float f = ...
int int_part = floor(f)
int fraction_part = floor((f - int_part) * pow(2.0, 32))

You can then use your bit_return to print x and y. Bonus points for not printing leading and/or trailing zeros.

A: I think the best way to address this question is to use an union
unsigned f2u(float f)
{
    union floatToUnsiged{
    float a;
    unsigned b;
    }test;

    test.a = f;
    return (test.b);
}


text:
Q: Concentration of salts I would like to know the answer about this question. As you know, the concentration of salts in the ocean tends to increase with the depth. In the Marianas Trench there is more salt dissolved per liter than in the middle height of the ocean. The more down you go, more salt per liter of water (probably due to pressure). My question is the following: if I could bring the salts from the surface down to the bed of the ocean, would the water increase her salinity or through dilution, diffusion, the ocean would repristinate the same gradient of salinity?

A: I read that because of gravitation, in a long long (long?) time, the ions will precipitate down at the bottom. Something reproducible faster in the centrifuge, like that separates proteins or DNA from liquids.