text:
Q: Including a library in C, where does it place in the address space? I understand how an address space is partitioned into: code, data, stack and heap. However, I am having trouble mapping what goes to where for a given C code.
I know that:
global variables are in the data section. static variables are in the data section. local variables are in the stack section. dynamic allocated space are in the heap section.
My questions is, when including a library into a program, where does it place in an address space?
I hope this question makes sense..

A: Actually if you have linux based pc, you can check it by yourself in the following way:

*

*create a simple c application with a infinite while loop inside of main().

*compile
$ gcc -o main ./main.c -g

*launch
$ gdb ./main

*Show mapping info
(gdb) r
(gdb) info proc mappings
Mapped address spaces:
      Start Addr           End Addr       Size     Offset objfile
        0x400000           0x401000     0x1000        0x0 /tmp/main
        0x600000           0x601000     0x1000        0x0 /tmp/main
        0x601000           0x602000     0x1000     0x1000 /tmp/main
        0x602000           0x623000    0x21000        0x0 [heap]
  0x7ffff7a0d000     0x7ffff7bcd000   0x1c0000        0x0 /lib/x86_64-linux-gnu/libc-2.23.so
  0x7ffff7bcd000     0x7ffff7dcd000   0x200000   0x1c0000 /lib/x86_64-linux-gnu/libc-2.23.so
  0x7ffff7dcd000     0x7ffff7dd1000     0x4000   0x1c0000 /lib/x86_64-linux-gnu/libc-2.23.so
  0x7ffff7dd1000     0x7ffff7dd3000     0x2000   0x1c4000 /lib/x86_64-linux-gnu/libc-2.23.so
  0x7ffff7dd3000     0x7ffff7dd7000     0x4000        0x0
  0x7ffff7dd7000     0x7ffff7dfd000    0x26000        0x0 /lib/x86_64-linux-gnu/ld-2.23.so
  0x7ffff7fd4000     0x7ffff7fd7000     0x3000        0x0
  0x7ffff7ff6000     0x7ffff7ff8000     0x2000        0x0
  0x7ffff7ff8000     0x7ffff7ffa000     0x2000        0x0 [vvar]
  0x7ffff7ffa000     0x7ffff7ffc000     0x2000        0x0 [vdso]
  0x7ffff7ffc000     0x7ffff7ffd000     0x1000    0x25000 /lib/x86_64-linux-gnu/ld-2.23.so
  0x7ffff7ffd000     0x7ffff7ffe000     0x1000    0x26000 /lib/x86_64-linux-gnu/ld-2.23.so
  0x7ffff7ffe000     0x7ffff7fff000     0x1000        0x0
  0x7ffffffdd000     0x7ffffffff000    0x22000        0x0 [stack]

So we see, that ld-so has placed c library to the addresses 0x7ffff7bcd000 - 0x7ffff7dd5000. The offset field - is an offset in the ELF file itself. We can check which sections corresponds to which offset using readelf:
$ readelf -a /lib/x86_64-linux-gnu/libc-2.23.so | less

Foe example:
 [13] .text             PROGBITS         000000000001f8b0  0001f8b0
       0000000000153214  0000000000000000  AX       0     0     16

That means that .text section have offset 0x1f8b0. From the mapping above, we can conclude that virtual address of the beginning of the .text section in main app address space will be 0x7ffff7bcd000 + 0x1f8b0

A: You are starting from a bad premise:

I understand how an address space is partitioned into: code, data, stack and heap. However, I am having trouble mapping what goes to where for a given C code.

The address space is not partitioned in this way. The address space contains memory. The memory used for stack is indistinguishable from memory used for heap. The only thing that makes a stack a stack is that it is being allocated in the application using a stack pointer. The only thing that makes a heap a heap is that that there is a heap manager in the application. You could allocate memory from a heap and assign it to the the hardware stack pointer and your memory is both heap and stack.
Here is another misconception:

I know that: global variables are in the data section. static variables are in the data section. local variables are in the stack section. dynamic allocated space are in the heap section.

How things worker differs among assemblers, linkers, and systems. However, rational assemblers allow the user to define their own named sections. In many assemblers, I could create Bobs_Data_Section, Freds_Data_Section, and Sams_Data_section and put global variables in each of them.
With most (but not all) compilers, the programmer has no control over how it is going to create sections. There is no guarantee that a compiler is going to put global variables in a section called "data." In fact, global variables and static local variables could be in the same section.
Such "Sections" are generally only input to the linker. The linker groups sections defined by the assembler and compiler together into memory regions with common access attributes. What goes into the linker as, say, a "data" section comes out of the linker as instructions in the executable to create pages that are read/write.

My questions is, when including a library into a program, where does it place in an address space?

So now you have hit the problem of how you are trying to learn how things work. If you view the process address space as just being memory, you can load the library anywhere. The program loader reads the instructions in the executable file and creates pages with the correct attributes (e.g., readonly/noexecute, read/write, readonly/execute) anywhere available in the address space.
If you view the address space as being partitioned into code, data, etc. loading libraries becomes problematic. Which makes  me wonder why schools and books persist in teaching using these nonsensical concepts.


text:
Q: Deriving Bayes risk for squared error loss function I think I must be doing something wrong here because my derived Bayes Risk is incredibly long and cumbersome...
Let $X|p \sim Bin(n,p)$ and $p \sim Beta(a,b)$.
Then $p|X \sim Beta(a+x,b+n-x)$ and the Bayes estimator of $p$ is given by
$$\delta(X) = \frac{a+x}{a+b+n}$$
My goal is to derive the Bayes risk of the Bayes estimator $\delta (X)$. My textbook seems to define (it's not actually clear to me...) Bayes risk under the squared error loss function as
$$E_{X,p} (\delta(X) - p)^2$$
which, I think, we can derive sequentially using the law of total expectation
$$E (\delta(X) - p)^2 = E[ E[(\delta(X) - p)^2|p]]$$
So my attempt to derive Bayes risk has first been to derive
$$E[(\delta(X) - p)^2|p]$$
Using the fact that $X |p \sim bin(n,p)$ and then, after deriving that, finding the total expectation by using $p \sim beta(a,b)$.
However intuitively I think I must be wrong, as the final Bayes risk I arrive at is incredibly long and tedious... and I don't think the textbook would give a problem with such a messy answer.
Is this wrong? And if not, is there any easier way to derive it in this situation?
I looked for similar answers on here for deriving Bayes risk and amazingly couldn't find any other than ddiscussions on the meaning of Bayes risk

A: The decomposition you propose is correct:
\begin{align*}
\mathbb{E} (\delta(X) - p)^2 &= \mathbb{E}[ \mathbb{E}[(\delta(X) - p)^2|p]]\\
&= \mathbb{E}[ \underbrace{\text{var}_p(\delta(X)) + (\mathbb{E}[\delta(X)]-p)^2}_\text{Pythegorean theorem}]\\
&= \mathbb{E}\left[\frac{np(1-p)}{(a+b+n)^2}+\left( \frac{a+np}{a+b+n}-p\right)^2\right]\\
&=\frac{A\mathbb{E}[p^2]+B\mathbb E[p] +C}{(a+b+n)^2}
\end{align*}
from which you should be able to extract a rather simple expression by recovering $A,B,C$ from the decomposition of the squares. If not, the example is processed in my book, The Bayesian Choice [Examples 4.4 and 4.5].

redpajama_set_name: RedPajamaStackExchange


text:
Q: No HDMI sound output on Thinkpad X1 I'm having problems getting my sound to output via HDMI to my TV.
When I go to Sound Settings, the HDMI device does not appear.
~$ aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: PCH [HDA Intel PCH], device 0: CONEXANT Analog [CONEXANT Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 3: HDMI 0 [HDMI 0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 7: HDMI 1 [HDMI 1]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 8: HDMI 2 [HDMI 2]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

I don't know if the video information is helpful, but anyway:
~$ sudo lshw -C video
  *-display
       description: VGA compatible controller
       product: 2nd Generation Core Processor Family Integrated Graphics Controller
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 09
       width: 64 bits
       clock: 33MHz
       capabilities: msi pm vga_controller bus_master cap_list rom
       configuration: driver=i915 latency=0
       resources: irq:46 memory:d0000000-d03fffff memory:c0000000-cfffffff ioport:5000(size=64)

Any suggestions for me?

A: From what I see, you might need to alter your default pulseaudio configuration. Backup the /etc/pulse/default.pa file and the edit it. Look for the part where it says
### Automatically load driver modules edepending on the hardware available
.ifexists module-udev-detect.so
load-module module-udev-detect.so
.else
### Use the static hardware detection module (for systems that lack udev/nal support)
load-module module-detect
.endif

and change it to (try with hw:0,3 to hw:0,7 or hw:0,8 if neccessary - this is based on your aplay -l output):
### Automatically load driver modules edepending on the hardware available
#.ifexists module-udev-detect.so
#load-module module-udev-detect.so
#.else
### Use the static hardware detection module (for systems that lack udev/nal support)
#load-module module-detect
#.endif

load-module module-alsa-sink device=hw:0,3 sink_name=hdmi

Then restart the pulseaudio server. If it's running on per-user basis, type pulseaudio --kill and then pulseaudio --start. If it's running as a system service type sudo service pulseaudio restart. To check that, run ps -ef | grep pulse and see what user (left column) started the pulseaudio application: if it's root, than it's a system service, if it's your user, than use the kill and start method. While experimenting with the configuration files, you can run it with pulseaudio -vvv to see debug information.
Note that this configuration is only to see if you can get the hdmi output to work. After you have found out which hw:0,# to use, for example if your hdmi output works with load-module module-alsa-sink device=hw:0,7 sink_name=hdmi, try uncommenting the loading of module-udev-detect/module-detect modules so that the pulseaudio can detect whatever it detects now, you should end up with something like this:
### Automatically load driver modules edepending on the hardware available
#.ifexists module-udev-detect.so
load-module module-udev-detect.so
.else
### Use the static hardware detection module (for systems that lack udev/nal support)
load-module module-detect
#.endif

load-module module-alsa-sink device=hw:0,7 sink_name=hdmi

I suggest that you use pavucontrol for choosing/viewing the output devices for pulseaudio.

A: Here on an X1 (2017), I can switch between HDMI and analog audio output with the command
pactl set-card-profile 0 output:hdmi-stereo+input:analog-stereo

and I can switch back using
pactl set-card-profile 0 output:analog-stereo+input:analog-stereo

I've found those commands in the arch wiki https://wiki.archlinux.org/index.php/PulseAudio/Examples#Automatically_switch_audio_to_HDMI


text:
Q: How to get live connection status of devices in ThingsBoard? I recently started working with thingsboard in context of my bachelor-thesis. Right know I am trying out different functionalities in order to check which requirements thingsboard already satisfies and which have to be implemented by me.
Within that process I am stuck at the requirement that thingsboard dashboard should give live information about the connectivity status of a registered device (connected, disconnected, active, inactive).
To solve that I've tried out editing the rule chain used by the device profile assigned to the device of interest. Specifically I worked with the message type switch and tried out various action nodes connected to it via ConnectEvent, DisconnectEvent, ActiveEvent and InactiveEvent. What I would like to have is the connectivity status of the device to be stored in an SERVER_SCOPE attribute and then being displayed in the entity widget. All I've achieved is to generate an alarm when disconnected and cleared when (re)connected. I know there is a server side attribute called active that changes true immediately when device connects but it only turns false after the inactivityTimeout expired.
I also checked the ThingsBoard Device Connectivity Status page, the Create Alarm when the Device is offline guide and took long researches but couldn't get it to work.
Do you guys have any solutions or tips for me?
Kind regard.

A: With the help of @JacksonB I managed to solve my problem.
What did I do?

*

*Create a blue Transform-script node.

*Change message type to POST_ATTRIBUTES_REQUEST and add desired attributes.
Here's my code for that:
var newType = "POST_ATTRIBUTES_REQUEST"
msg.connectivity = "connected"
return {msg: msg, metadata: metadata, msgType: newType};

*Than just connect this to an post attribute node in the rule chain like shown in the image.
Link to screenshot of rule chain
No I am able to instantly see if a device is connected or disconnected by displaying the value of that attribute on my dashboard.


text:
Q: FSRM for folder classification by its name I'm going to deploy DAC (Dynamic Access Control) and FSRM (File Server Resource Manager) on Server 2012. The primary goal is to dynamically hide sub-folders with specific name (let say, 'Top Secret') for specific users ('Users').
I see that I can create resource property and manually assign it to folder. I can use FSRM to classify files by its contents or by file names or classify specific, pre-defined folders. However, I don't see a way how to classify folder by its name. Is it possible?
If not, any suggestions how to accomplish my goal?

A: After number of experiments I can conclude that it seems not possible.
Classification works only for files based on their contents and for folders based on their absolute path. File names' patterns can be used only to restrict which files to classify but not as base for classification itself.


text:
Q: Show the existence of a certain subgroup of F2 This is a homework question: I need to find three subgroups of the free group with two generators, $F_2$, with certain properties. I have found the other two by constructing covering spaces of $S^1 \vee S^1$ and using fundamental groups; I don't think that this approach works here:

Show that $F_2$ has an infinite index, free subgroup of rank two.

If anyone could nudge me in the right direction I'd be very grateful!

A: The free group $\mathbb{F}_2$ is the fundamental group of a bouquet of two circles $X:= \mathbb{S}^1 \vee \mathbb{S}^1$. Therefore, if $\hat{X}$ denotes the universal covering of $X$, then the derived subgroup $D := [\mathbb{F}_2,\mathbb{F}_2]$ is the fundamental group of $\hat{X}/D$; $\hat{X}$ and $\hat{X}/D$ are illustrated by figures 1 and 2 respectively.

If $T$ is a maximal subtree of $\hat{X}/D$, then $\{ \text{edges of} \ \hat{X}/D \ \text{not in} \ T\}$ is a free basis of $D$; explicitely, taking the maximal subtree $$T = (\{0\} \times \mathbb{R}) \cup \bigcup\limits_{i \in \mathbb{Z}} \mathbb{R} \times \{i\},$$ we find
$$B=\{a^ib^ja^{-1}b^{-j}a^{1-i},a^{-i}b^jab^{-j}a^{i-1} \mid i>0,j \in \mathbb{Z} \backslash \{0\} \}$$
as a free basis of $D$. In particular, $D \simeq \mathbb{F}_{\infty}$. Finally, $\{ \langle x,y \rangle \mid x \neq y \in B\}$ gives you an infinite family of infinite-index subgroups isomorphic to $\mathbb{F}_2$.


text:
Q: group with multiple ids and sum in mongodb {
            "_id" : ObjectId("59774aa87da165f360b0271a"),
            "createdDate" : ISODate("2017-07-25T13:42:00.000Z"),
            "sourceId" : ObjectId("000000000000000000000000"),
            "fanClubId" : ObjectId("59774aa87da165f360b02719"),
            "coins" : -500,
            "reasonId" : ObjectId("593500980b0cbbe593cd722c"),
            "userId" : ObjectId("597731d3ee99e33e1696de79")
        }

        {
            "_id" : ObjectId("59784c76e8288e1be6dace64"),
            "createdDate" : ISODate("2017-07-26T08:01:58.000Z"),
            "sourceId" : ObjectId("000000000000000000000000"),
            "fanClubId" : ObjectId("59784c76e8288e1be6dace63"),
            "coins" : -500,
            "reasonId" : ObjectId("593500980b0cbbe593cd722c"),
            "userId" : ObjectId("597731d3ee99e33e1696de79")
        }

        {
            "_id" : ObjectId("597734e376f9e53e0e52588a"),
            "createdDate" : ISODate("2017-07-25T12:09:07.000Z"),
            "sourceId" : ObjectId("000000000000000000000000"),
            "fanClubId" : ObjectId("000000000000000000000000"),
            "coins" : 5,
            "reasonId" : ObjectId("593501ff0b0cbbe593cd7236"),
            "userId" : ObjectId("597731d3ee99e33e1696de79")
        }

        db.getCollection('FanCoins').aggregate([{$group : {_id:{userId:ObjectId("597731d3ee99e33e1696de79"),
        reasonId:ObjectId("593500980b0cbbe593cd722c")},coins:{$sum : { $add: ["$coins"]}}}} ])

I used this query to get the result for sum of coins of userId & reasonId, but i'm getting the total sum of userId's. How to do this in mongodb group by.


text:
Q: SSHKit command or Capistrano task to filter/replace tokens on upload I'm using Capistrano to deploy configuration files for a legacy non-Ruby application, that for arcane legacy reasons need to be parameterized with the fully-qualified name of the target host, e.g.
name: myservice-stg
identifier: myservice-stg-1.example.org:8675
baseURI: http://myservice-stg-1.example.org:8675

Apart from that, for a given environment, there's no difference between the config files, so I'd like to be able to just define a template (example uses Mustache but could be ERB or whatever):
name: myservice-stg
identifier: {{fqhn}}:8675
baseURI: http://{{fqhn}}:8675

My current idea for a hack is just to use gsub and a StringIO:
config_tmpl = File.open('/config/src/config.txt')
config_txt = config_tmpl.gsub('{{fqhn}}', host.hostname)
upload!(StringIO.new(config_txt), 'dest/config.txt')

But it seems like there ought to be a more standard, out-of-the box solution.

A: Tools like Ansible and Chef are great for this, but might be overkill if this is all you're trying to do.
Your proposed solution looks fairly standard.  Using ERB (or other templating system) wouldn't be that much more work and provides flexibility/reusability down the road:
template_path = File.open('/config/src/config.txt.erb')
config_txt = ERB.new(File.new(template_path).read).result(binding)
upload! StringIO.new(config_txt), 'dest/config.txt', mode: 0644

ERB:
name: myservice-stg
identifier: <%= host.hostname %>:8675
baseURI: http://<%= host.hostname %>:8675


text:
Q: Settings not opening on Ubuntu 19.10 I recently upgraded to Ubuntu 19.10, but I'm not able to open Settings.

killall gnome-control-center

gives

gnome-control-center: no process found

And also my laptop is hanging many times, I had to press the power button every time to restart.
gnome-control-center --verbose

gives

Segmentation fault (core dumped)

but gnome-control-center --version
gives gnome-control-center 3.34.1

A: It also happened to me when I tried to open Devices section.
Someone pointed out that you can reset the last panel using a terminal:
gsettings set org.gnome.ControlCenter last-panel ''

It does not solve the Devices section issue.

A: try to take a screenshot of your screen, and look at the picture. If the setting is on the right side of the screen that means you have accidentally opened a join screen. You can search for turning a join screen from the terminal. Hope this would help.


text:
Q: I can't seem to get user input to work in my if, elif, else loop in Python So I am working on a program that essentially asks a person if they want to hear a joke; if they say yes, then it will proceed to tell a joke; if they say no, or stop/quit the program will stop; and if they don't say yes or no, it will give them an error message. However, the program seems to just want to proceed on with the joke no matter what they input. I will produce an example of the code.
import sys

print("Want to hear a joke?")
answer = input()
if answer == "Yes" or "yes" or "y":
   print("Here is a joke")
elif answer == "No" or "no" or "n":
   sys.exit("Bye!")
else:
   print("Please input a different response.")

A: This is NOT how you do a conditional
if answer == "Yes" or "yes" or "y": # this will always evaluate to true

do this instead
if answer in ["Yes" ,"yes" , "y"]:
      print "Here is a joke"


text:
Q: Should parsimony really still be the gold standard? Just a thought:
Parsimonious models have always been the default go-to in model selection, but to what degree is this approach outdated? I'm curious about how much our tendency toward parsimony is a relic of a time of abaci and slide rules (or, more seriously, non-modern computers). Today's computing power enables us to build increasingly complex models with ever-greater ability for prediction. As a result of this increasing ceiling in computing power, do we really still need to gravitate toward simplicity?
Sure, simpler models are easier to understand and interpret, but in the age of ever-growing data sets with greater numbers of variables and a shift towards a greater focus on prediction capability, this might no longer even be achievable or necessary.
Thoughts?

A: @Matt's original answer does a great job of describing one of the benefits of parsimony but I don't think it actually answers your question. In reality, parsimony isn't the gold standard. Not now nor has it ever been. A "gold standard" related to parsimony is generalization error. We would like to develop models that don't overfit. That are as useful for prediction (or as interpretable or with minimum error) out of sample as they are in sample. It turns out (because of things laid out above) that parsimony is actually quite a good proxy for generalization error but it's by no means the only one.
Really, think about why we use cross validation or bootstrapping or train/test sets. The goal is to create models with good generalization accuracy. A lot of the time, these ways of estimating out of sample performance do end up choosing models with lower complexity but not always. As an extreme example imagine the oracle hands us the true but extremely complex model and a poor but parsimonious model. If parsimony was really our goal then we would choose the second but in reality, the first is what we would like to learn if we could. Unfortunately a lot of the time that last sentence is the kicker, "if we could".

A: Perhaps have a review of the Akaike Information Criterion, a concept that I only discovered by serendipity yesterday. The AIC seeks to identify which model and how many parameters are the best explanation for the observations at hand, rather than any basic Occam's Razor, or parsimony approach.

A: Parsimony is not a golden start. It's an aspect in modeling. Modeling and especially forecasting can not be scripted, i.e. you can't just hand a script to a modeler to follow. You rather define principles upon which the modeling process must be based. So, the parsimony is one of these principles, application of which can not be scripted (again!). A modeler will consider the complexity when a selecting model.
Computational power has little to do with this. If you're in the industry your models will be consumed by business folks, product people, whoever you call them. You have to explain your model to them, it should make a sense to them. Having parsimonious models helps in this regard.
For instance, you're forecasting product sales. You should be able to describe what are the drivers of sales, and how they work. These must be related to concepts with which business operates, and the correlations must be understood and accepted by business. With complex models it could be very difficult to interpret the results of the model or attribute the differences with actuals. If you can't explain your models to business, you will not be valued by it.
One more thing that is particularly important for forecasting. Let's say your model is dependent on N exogenous variables. This means that you have to first obtain the forecasts of these variables in order to forecast your dependent variable. Having smaller N makes your life easier, so a simpler model is easier to use.

A: Parsimonious models are desirable not just due to computing requirements, but also for generalization performance. It's impossible to achieve the ideal of infinite data that completely and accurately covers the sample space, meaning that non-parsimonious models have the potential to overfit and model noise or idiosyncrasies in the sample population.
It's certainly possible to build a model with millions of variables, but you'd be using variables that have no impact on the output to model the system. You could achieve great predictive performance on your training dataset, but those irrelevant variables will more than likely decrease your performance on an unseen test set.
If an output variable truly is the result of a million input variables, then you would do well to put them all in your predictive model, but only if you have enough data. To accurately build a model of this size, you'd need several million data points, at minimum. Parsimonious models are nice because in many real-world systems, a dataset of this size simply isn't available, and furthermore, the output is largely determined by a relatively small number of variables.

A: Regarding Neural Networks, this topic has been very nicely covered in a recent NeurIPS 2020 paper entitled
The Pitfalls of Simplicity Bias in Neural Networks (Shah et al.).
I totally recommend reading the paper, I think it is very nicely structured and rigorous. Here is an attempt to summarize its main ideas:

*

*The core of the problem is that the field seems to associate simplicity bias to "justify why NNs work well", but not to their "lack of robustness".

*The authors tackle this problem via the design of datasets that comprise multiple predictive features with varying levels of simplicity. These will serve as control variables.

*Following a series of theoretical analyses and targeted experiments, they found that the simplicity bias given by Stochastic Gradient Descent can be extreme, that common approaches to overcome this can fail, and in general, that there is still quite a way to go in order to better understand SB in NNs.
The proposed datasets and methods can serve as a basis for future work in that direction.

This principle of SB for NNs is very much embedded in the Deep Learning culture: See e.g. this video from the Udacity "Deep Learning" course (Vanhoucke et al.), where they use the "stretch pants" analogy. The idea is that instead of trying to guess the right pant size, you start with several extra sizes and "stretch them down" until they fit perfectly. This way, training is seen as reducing the capacity of the model wherever there is room to do so.
The paper above questions the general validity of this principle, showing that when trained with SGD, the pants tend to fit the simpler legs, no matter how many dimensions they have.
So whereas the original question is from 2015, this topic is still extremely current. Particularly, the following OP sentence is right on point:

Today's computing power enables us to build increasingly complex models with ever-greater ability for prediction. As a result of this increasing ceiling in computing power, do we really still need to gravitate toward simplicity?

Since the paper above shows that the ever-growing NN architectures still invariably gravitate towards simpler features when trained with SGD.

I would also like to finish commenting about another bias related to SB, that is Inductive Bias, "the set of assumptions that the learner uses to predict outputs of given inputs that it has not encountered".
Instead of assuming simplicity, inductive bias assumes any other arbitrary property. For example, when training a NN for transcription of piano music, it is safe to assume that all keyboard strokes generate mainly harmonic waveforms that have an onset and decay exponentially. In terms of "no free lunch", correctly applying an inductive bias would translate to getting lunch for a good prize. Physical models are known for their extremely precise and rigorous application of inductive biases.
Another amazing ICLR 2020 paper that treats the systematic introduction of Inductive Bias into NN design and training is
DDSP: DIFFERENTIABLE DIGITAL SIGNAL PROCESSING (Engel et al.)
With application of DDSP techniques it can be observed that introducing inductive biases helps the models satisfactorily solve complex tasks with less capacity, also the SGD convergence is faster and requires less training data.
So again coming back to the OP: While the No Free Lunch theorem states that no algorithm will work better than other for all kinds of problems, inductive biases are a good mechanism to gain performance without sacrificing much interpretability, if you are willing to reduce the set of targeted problems.

A: I think the previous answers do a good job of making important points:

*

*Parsimonious models tend to have better generalization characteristics.

*Parsimony is not truly a gold standard, but just a consideration.

I want to add a few comments that come out of my day to day job experience.
The generalization of predictive accuracy argument is, of course, strong, but is academically bias in its focus.  In general, when producing a statistical model, the economies are not such that predictive performance is a completely dominant consideration.  Very often there are large outside constraints on what a useful model looks like for a given application:

*

*The model must be implementable within an existing framework or system.

*The model must be understandable by a non-technical entity.

*The model must be efficient computationally.

*The model must be documentable.

*The model must pass regulatory constraints.

In real application domains, many if not all of these considerations come before, not after, predictive performance - and the optimization of model form and parameters is constrained by these desires.  Each of these constraints biases the scientist towards parsimony.
It may be true that in many domains these constraints are being gradually lifted.  But it is the lucky scientist indeed that gets to ignore them are focus purely on minimizing generalization error.
This can be very frustrating for the first time scientist, fresh out of school (it definitely was for me, and continues to be when I feel that the constraints placed on my work are not justified).  But in the end, working hard to produce an unacceptable product is a waste, and that feels worse than the sting to your scientific pride.

A: I think this is a very good question.  In my opinion parsimony is overrated.  Nature is rarely parsimonious, and so we shouldn't necessarily expect accurate predictive or descriptive models to be so either.  Regarding the question of interpretability, if you choose a simpler model that only modestly conforms to reality merely because you can understand it, what exactly are you understanding?  Assuming a more complex model had better predictive power, it would appear to be closer to the actual facts anyways.


text:
Q: Google script Error: Argument must be a range (line 74) Here is my function
 function Cool() {   var h = SpreadsheetApp.getActiveSpreadsheet();
 var range = 0;   var count = 1;   var alph = ["A", "B", "C", "D", "E",
 "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
 "T"];   for (i = 0; i < 20; i+=0.5) {
     if (i == 19 && count != 5) {
       i == 0;
       count += 1;
     } else if (i == 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 || 10 || 11 || 12 || 13 || 14 || 15 || 16 || 17 || 18) {
       range = h.getSheets()[0].getRange(alph[i] + count + ":" + alph[i] + count);
       SpreadsheetApp.setActiveRange(range);
       randomize();
     }   } }

that has an error on the
range = h.getSheets()[0].getRange(alph[i] + count + ":" + alph[i] + count);

A: Have you looked at the data you are using ?
here is a slightly modified version of your script with a logger to see what happens and the log result below. I guess you'll understand why you get error messages . It seems your condition simplified syntax doesn't do what you wanted, does it ?
btw what is the final purpose of this script ? could you explain the idea ?
If you wanted to do something only on integer values of i it would be easier to use something like if(i==parseInt(i)) for example...
function Cool() {
  var h = SpreadsheetApp.getActiveSpreadsheet();
  var range = 0;   var count = 1;   var alph = ["A", "B", "C", "D", "E",
 "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
 "T"];   for (i = 0; i < 20; i+=0.5) {
     if (i == 19 && count != 5) {
       i == 0;
       count += 1;
     } else if (i == 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 || 10 || 11 || 12 || 13 || 14 || 15 || 16 || 17 || 18) {
//       range = h.getSheets()[0].getRange(alph[i] + count + ":" + alph[i] + count);
//       SpreadsheetApp.setActiveRange(range);
 Logger.log('i='+i+'  '+alph[i] + count + ":" + alph[i] + count);
 //      randomize();
     }
     }
     }

LOGGER RESULT :
i=0  A1:A1
i=0.5  undefined1:undefined1
i=1  B1:B1
i=1.5  undefined1:undefined1
i=2  C1:C1
i=2.5  undefined1:undefined1
i=3  D1:D1
i=3.5  undefined1:undefined1
i=4  E1:E1
i=4.5  undefined1:undefined1
i=5  F1:F1
i=5.5  undefined1:undefined1
i=6  G1:G1
i=6.5  undefined1:undefined1
i=7  H1:H1
i=7.5  undefined1:undefined1
i=8  I1:I1
i=8.5  undefined1:undefined1
i=9  J1:J1
i=9.5  undefined1:undefined1
i=10  K1:K1
i=10.5  undefined1:undefined1
i=11  L1:L1
i=11.5  undefined1:undefined1
i=12  M1:M1
i=12.5  undefined1:undefined1
i=13  N1:N1
i=13.5  undefined1:undefined1
i=14  O1:O1
i=14.5  undefined1:undefined1
i=15  P1:P1
i=15.5  undefined1:undefined1
i=16  Q1:Q1
i=16.5  undefined1:undefined1
i=17  R1:R1
i=17.5  undefined1:undefined1
i=18  S1:S1
i=18.5  undefined1:undefined1
i=19.5  undefined2:undefined2

EDIT : being curious by nature I did try your code with the suggested IF statement and I get the following log (much nicer;-) but quite useless, a simple for loop with unity increments would do the same...
i=0  A1:A1
i=1  B1:B1
i=2  C1:C1
i=3  D1:D1
i=4  E1:E1
i=5  F1:F1
i=6  G1:G1
i=7  H1:H1
i=8  I1:I1
i=9  J1:J1
i=10  K1:K1
i=11  L1:L1
i=12  M1:M1
i=13  N1:N1
i=14  O1:O1
i=15  P1:P1
i=16  Q1:Q1
i=17  R1:R1
i=18  S1:S1

so the question remains : what was the final goal ?


text:
Q: How to solve such symmetric equations I have the following symmetric system:
$$f_i = \sum_j^n \tau_{ij}c_j^{-1}y_j$$
$$c_j = \sum_i^n \tau_{ij}f_i^{-1}y_i$$
$$\tau_{ij}=\tau_{ji}$$
$$F =
 \left[
 \begin{matrix}
   f_1  \\
   ... \\
   f_n
  \end{matrix}
  \right]
$$
$$C =
 \left[
 \begin{matrix}
   c_1  \\
   ... \\
   c_n
  \end{matrix}
  \right]
$$
and how to solve the $f_i$ and $c_i$?
Does this two equations have the reduced form relationship?
Is there any theory that relate to such kind of symmetric system?
Thank you!


text:
Q: Configure Hot Module Reload for ElectronJS + Vue I have the following repository where I would like to get Hot Module Reload to work.
So far I am able to:

*

*start the app

*compile the app files and run a spectron test using the compiled files

What I'd like to achieve is to alter the webpack configuration accordingly so that I am able to run "npm run dev" for example and have the app start with HMR available.
How can I achieve so with the current webpack settings?
Any other answers around the subject are for react projects, which are most, beyond my understanding, or are using electron-reload, which is not actually what I am looking for.
Why not use Vue CLI?
I attempted Vue CLI and a plugin vue-cli-electron-builder-builder, but faced the following issues:

*

*It does not support mocha

*Simple spectron test takes up to 30 seconds

*If I want to customize anything, I end up with three items or more to learn/read about (Vue CLI, the plugin configurations, the scaffold)

Electron webpack
I initially used this plugin to achieve the same by following the video here. I encountered several issues:

*

*At the time I tried this plugin (3-4 months ago), there was an error during compilation occurring as it would not support the latest Electron version (4.0 was recently released)

*When I tried to understand how to get Spectron to work along, I wasted hours before realizing that I am unable to overwrite/use the NODE_ENV variable, making it even more difficult to set conditionals for various environment (test, development, production).

*When the first issue above was resolved, HMR wasn't working anymore

*Despite following the documentation, certain webpack overrides did not seem to take effect. For instance, I added overlay: true which did effectively render the overlay on error while the App was running. But any attempts to reduce the noise on compilation has no effect. Similarly, it's not easy to determine how to point mocha to the right webpack config (I tried both, pointing at the vendor generated config, or using an extended config on root, but in vain)

As per above, it turns out I spend a huge amount of time encountering issues rather than proceeding with the app idea. All the tools available to make things easier either have issues on Windows, or have known issues with x version of y dependency, or just simply adds overheads that I need to learn at one point to tackle better the setup (for example, electron-webpack in itself is a tool, not just a plugin, going through the documentation is a must since it has its own concept around the project structure and configurations). I spent more time learning side tools than electron itself.
Hence, I would like to know how to get HMR to work on the main and renderer process with a basic example, where, if simple enough, will avoid I believe the need to learn extra tools or face various issues due to versions or OS.
Requirements:

*

*ElectronJS

*Vue

*Relatively fast e2e tests

*Unit tests

*HMR both with main and renderer process

A: my advice to you is as fallow:
first of all separate the Electron & Vue from each other.
the reason its that are both really different projects.
i am telling you that as i have made this journey with very similar project.
the process i have done.
install vue-cli link
npm install -g @vue/cli
run vue ui and you face the fancy vue ui project management.
set what ever you like in the project create process.
after that i have run my code with a conditional to check if we in dev or not.
when i am in dev i point to the vue muck up server.
if (!app.isPackaged) {
   mainWindow.loadURL(`http://localhost:8081`);
   mainWindow.webContents.openDevTools({mode: 'undocked'});
} else {
   mainWindow.loadURL(`file://${__dirname}/index.html`);
}

and in this option the HMR work perfect.


text:
Q: How to bind a column in laravel Builder? I have the following code(Laravel 5.6 PHP 7.0):
$orders = DB::table('orders')
            ->selectRaw('?', ['id'])
            ->get();

In my imagination that code has to perform such sql:
SELECT `id` FROM orders

and has to return a result like:
array [
   0 => {
     "id": "1"
   }
   1 => {
     "id": "2"
   }

unfortunately it returns this:
array [
   0 => {
     "?": "id"
   }
   1 => {
     "?": "id"
   }

But if I run the following code everything works as I want:
$orders = DB::table('orders')
             ->selectRaw('id')
             ->get();

So, my questions are:

*

*Why does the first code returns such a strange result?

*How to bind a column?

A: Its because PDO wraps bound parameters in quotes, so you're SQL would actually be something like:
SELECT 'id' FROM orders

You're selecting the string id, not the column. You cannot bind column names, only values.
To get your query to work, in the same format as what you want, you'd need to do this:
$columns = ['id'];

$orders = DB::table('orders')
        ->select($columns)
        ->get();

If you want to be safer, for example, if you get the column names from a querystring or something, you can do:
$allowedColumns = ['id', 'product_name', 'some_other_field'];
$columns = array_only($request->get('columns'), $allowedColumns);

$orders = DB::table('orders')
        ->select($columns)
        ->get();

If you ever need to have a look at the raw SQL Laravel is generating, and the bound paramters, you can do the following:
$query = DB::table('table_name')->select(['id', 'column1']);

dd($query->toSql(), $query->getBindings());


text:
Q: Loop through all files in a directory and subdirectories using Bash and invoking a php command I'm very new to bash scripts but I was looking to build a script that essentially goes through a directory and its subdirectories and files.
The top level directory would be the location of images so top level may be "293 House Street" and in that would be subdirectories of each room "Bathroom", "Kitchen", etc. and within those sub directories would be images. There may also be images found in the top level.
I want to essentially invoke the PHP command once a file has been found and provide some arguments for the data to be used.
php process_directories.php -a "293 House Street" -p "PATH_OF_FILE" -f "FILE"
-a Would be the Address // This will always be the same for each file found in the current directory.
-p Would be the path of the file
-f Would be the file.
Is there a good way to possibly make a script like this?

A: I don't think that you can do it directly with the command find but you can loop through its results with Bash:
#!/usr/bin/env bash

while IFS= read -d '' -r filepath
do
    dirpath="${filepath%/*}"
    filename="${filepath##*/}"
    php process_directories.php -a "293 House Street" -p "$dirpath" -f "$filename"
done < <(find . -type f -print0)

*

*${filepath%/*} is $filepath but with the last / up to the end removed (that is the directory path).

*${filepath##*/} is $filepath but with the start up to the last / removed (that is the file name).

*find . -type f will output all the files in the current directory and its sub-directories, prefixed with ./, which ensures that the two bullets above work correctly.

*The option -print0 of find combined with read -d '' ensures, by using the NULL byte as separator, that you can process correctly each path (which in Linux filesystems, can be composed of any character but NULL).

Remark: You could also modify your PHP script to do the same things, instead of using the Shell

A: Modify your php script such that it takes the full path as single parameter and extracts the 3 sub-parts (easy). Then, with the find utility:
find "293 House Street" -type f -exec php process_directories.php {} \;

Note: naming process_directories.php a php script that processes a single file is a bit counter-intuitive. Are you sure you will remember what it does in, let's say, one week?


text:
Q: download files once uploaded via script I am creating a simple upload script but once I have uploaded the files If I link to the file with an  I get a server Forbidden error. I have set the permission to 750(have checked and the permissions are correct) so don't understand why this is happening....
Any help would be great, below is my upload script:
if($_POST["upload"]){

//gets current year for path
$year = date('Y');

//path to directory
$path = $_SERVER["DOCUMENT_ROOT"] . '/uploads/' . $year . '/' . strtolower(str_replace(' ','',$_POST["username"])) . '/' . $_POST["month"];

//path to file
$target_path = $path . '/' . basename($_FILES['uploadedfile']['name']);

// $_FILES is the array auto filled when you upload a file and submit a form.
$file_name = $_FILES['uploadedfile']['name']; // file name
$file_tmp  = $_FILES['uploadedfile']['tmp_name']; // actual location
$file_size  = $_FILES['uploadedfile']['size']; // file size
$file_type  = $_FILES['uploadedfile']['type']; // mime type of file sent by browser. PHP doesn't check it.
$file_error  = $_FILES['uploadedfile']['error']; // any error!. get from here

if($file_error == UPLOAD_ERR_NO_FILE){

    print "
Please select a file first
";

} elseif ($file_error == UPLOAD_ERR_INI_SIZE) {

    print "
The file is too large
";

} elseif($file_error == UPLOAD_ERR_PARTIAL){

    print "
An error occured whilst trying to receive the file, please try again.
";

} elseif( !($file_type=="application/pdf")) {

        print "
Your File Type is: ". $file_type." the file type must be PDF
";

} elseif($file_error == 0){

    if(!is_dir($path)){

        mkdir($path, 0750, true);
    }

    move_uploaded_file($file_tmp, $target_path);

    chmod($target_path, 0750);

    print "
The file " . "" . basename($file_name) . "" . " has been uploaded to " . $_POST["username"] . "'s folder
";

}
}

A: Does Apache have access to the files? Try adding a chown line in with the chmod changes.

A: Turns out that the file permission 750 or 777 won't let you download the file but 444 will. Not too sure why this is to be honest but it is working now.
Thanks for all your help guys.
Until next time!


text:
Q: How to find the best fit ellipse to a given set of 2D points? Given a set of $n$ two-dimensional points $\{(x_i, y_i), i=1,.., n\}$ I would like to find the ellipse that best fits them.  The easiest approach I found was what is called the "Equation Error Model", in which we are trying to fit the points to the conic section model:
$$ A x^2 + B xy + C y^2 + D x + E y + F = 0 $$
The coefficients $A,B,C,D,E,F$ are not unique because they can be scaled by any real non-zero number.  Also, for an ellipse, $A$ cannot be zero.  Therefore, we can choose to fix $A = 1$, then we would have to determine the other $5$ coefficients.
Accumulating the data from every point, we will have the linear system
$ G a = b $
where $ a = [B, C, D, E, F]^T$, and
$ G = \begin{bmatrix} x_1 y_1  && y_1^2 && x_1 && y_1 && 1 \\
x_2 y_2  && y_2^2 && x_2 && y_2 && 1 \\
x_3 y_3  && y_3^2 && x_3 && y_3 && 1 \\
\vdots \\
x_n y_n  && y_n^2 && x_n && y_n && 1 \end{bmatrix}\hspace{5pt}, \hspace{25pt} b = \begin{bmatrix} - x_1^2 \\ - x_2^2 \\ - x_3^2 \\ \vdots \\ - x_n^2 \end{bmatrix} $
To solve this linear system for $a$, pre-multiply by $G^T$, you get
$ G^T G a = G^T b $
and finally,
$ a = (G^T G)^{-1} G^T b $
I simulated the above method, and it gave excellent results.  My question is whether there are alternative methods to approach this best fitting ellipse problem.  Your hints, suggestions, and solutions are much appreciated.

A: It's better to fix $A + C = 1$ rather than $A = 1$, for reasons I explained in Least square fit of ellipse worsens with increasing border thickness: $A + C$ is invariant under isometries of $(x, y)$, while $A$ is not.
Here's a diagram using the same data from that question, comparing the ellipse correctly computed with $A + C = 1$ in red vs. incorrectly computed with $A = 1$ in orange.  If you rotated the points, you'd find that the red ellipse matches their rotation exactly, while the orange ellipse wobbles around a bit.

A: The solution you state using the Moore-Penrose pseudoinverse coincides with the solution of the convex optimization problem:
$$\min_{a\in\mathbb{R}^5}||Ga-b||_2.$$
However, it is possible to use different norms for finding the "best" vector $a$. You can use, for instance, the $1$-norm which leads to the following convex optimization problem
$$\min_{a\in\mathbb{R}^5}||Ga-b||_1.$$
Note, however, that this problem does not necessarily have a closed-form optimal solution as in the $2$-norm case and one has to rely to numerical optimization methods for finding the minimizer. Using the $1$-norm has certain advantages over the $2$-norm such as "ignoring outliers" in a better way as it promotes sparsity, that is, it will try to set as many entries of $Ga-b$ as possible to zero.
You may also try the $\infty$-norm as well for fun and solve
$$\min_{a\in\mathbb{R}^5}||Ga-b||_\infty.$$
Those optimizations problems are all convex. In particular, minimizing the $1$-norm and the $\infty$-norm are linear programming problems. They can be solved using standard libraries in Python or Matlab, for instance.


text:
Q: I want to pass 'Filename' as argument to other function call but always it is returning 'None' as value I m developing GUI using PyQT4: Code looks like below -
def fileopening():
    filename = QtGui.QFileDialog.getOpenFileName(mainwindow, 'Select file')
    print(filename)
    return filename

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    mainwindow = QtGui.QWidget()
    ui = Ui_mainwindow()
    ui.setupUi(mainwindow)
    filename = ui.browser.clicked.connect(fileopening)
    print(filename)
    ui.progressBar.setValue(100)
    ui.progesslabel.setText('Kindly fill in the fields and proceed for splitting.')
    ui.splitbutton.clicked.connect(pressed)
    ui.resetparameter.clicked.connect(reset)

    mainwindow.show()
    app.exec_()

When UI is prompted it gives print output as 'None' and from defination of function it gets filename in function call but it is not returning any value. Can anybody suggest what may be the possible reason? I want to pass 'Filename' as argument to other function call but always it is returning 'None' as value.

A: HAve you tried
return QtGui.QFileDialog.getOpenFileName(mainwindow, 'Select file')

You can make the name filename global.
def fileopening():
    global filename
    filename = QtGui.QFileDialog.getOpenFileName(mainwindow, 'Select file')


text:
Q: AVPlayer and black video I'm recording a video in the first UIViewController, writing this video to file and I want to show this video in the second UIViewController but sometimes (quite often) there is just a black frame instead of video.
player.status.rawValue and player.currentItem?.status.rawValue are 0 every time.
The file is here every time, I can process it, so videoURL is ok. I'm getting no errors, just the black screen.
    videoURLAsset = videoAsset as! AVURLAsset
    let videoURL = videoURLAsset.URL

    if playerLayer != nil {
        player = nil
        playerLayer.removeFromSuperlayer()
    }

    player = AVPlayer(URL: videoURL)
    player.volume = 0.0
    playerLayer = AVPlayerLayer(player: player)
    playerLayer.backgroundColor = UIColor.blackColor().CGColor
    playerLayer.frame = CGRectMake(10, 70, screenWidth - 20, screenHeight / 2 - 90)

    self.view.layer.addSublayer(playerLayer)
    player.play()

What is my mistake?


text:
Q: Test record id is change when assertion test class I have a problem with my test class, the test record id is changed when I do system.assertEquals(); , i didn't know why this happen. Is there anything that i miss?
Here my controller
public class BACSPaymentManagerController {
@AuraEnabled
    public static String generateBACSFile(List<Id> selectedPaymentIds, Datetime BACSPaymentDatetime){
        Integer day = BACSPaymentDatetime.day();
        String dayString;
        Integer month = BACSPaymentDatetime.month();
        String monthString;
        Integer year = BACSPaymentDatetime.year();
        String userID = UserInfo.getUserId();
        Date BACSPaymentDate = Date.newInstance(year, month, day);

        if(day > 9)
            dayString = String.Valueof(day);
        else
            dayString = '0'+day;

        if(month > 9)
            monthString = String.Valueof(month);
        else
            monthString = '0'+month;

        String dateLine = 'H,' + year + monthString + dayString + ',' + userID + year + monthString + dayString;
        String terminationString = 'T';
        Integer hour = BACSPaymentDatetime.hour();
        String hourString;
        if(hour > 9)
            hourString = String.Valueof(hour);
        else
            hourString = '0'+hour;

        Integer minute = BACSPaymentDatetime.minute();
        String minuteString;
        if(minute > 9)
            minuteString = String.Valueof(minute);
        else
            minuteString = '0'+minute;
        Integer second = BACSPaymentDatetime.second();
        String secondString;
        if(second > 9)
            secondString = String.Valueof(second);
        else
            secondString = '0'+second;
        String bacsDebitAccountReference = 'SF'+ year + monthString + dayString + hourString + minuteString + secondString;

        Datetime BACSPaymentDatetimeNext4 = BACSPaymentDatetime+4;
        Integer dayNext4 = BACSPaymentDatetimeNext4.day();
        String dayStringNext4;
        Integer monthNext4 = BACSPaymentDatetimeNext4.month();
        String monthStringNext4;
        Integer yearNext4 = BACSPaymentDatetimeNext4.year();

        if(dayNext4 > 9)
            dayStringNext4 = String.Valueof(dayNext4);
        else
            dayStringNext4 = '0'+dayNext4;

        if(monthNext4 > 9)
            monthStringNext4 = String.Valueof(monthNext4);
        else
            monthStringNext4 = '0'+monthNext4;

        bacsDetails__c bacsDetails = bacsDetails__c.getInstance();
        String debitLine = 'D,' + yearNext4 + monthStringNext4 + dayStringNext4 + ',' + bacsDebitAccountReference + ',' + bacsDetails.sortCode__c + '-' + bacsDetails.Account_Number_For_BAS_Debit__c;

        Batch_Reference__c br = new Batch_Reference__c(Name=bacsDebitAccountReference);
        insert br;

        Integer numberOfPayments = 0;
        Decimal totalAmount = 0;

        List<Payment__c> selectedPayment = new List<Payment__c>();
        for(Payment__c pay : [SELECT Id, Name, Amount_Paid__c, Date_Paid__c, Date_Due__c FROM Payment__c WHERE Id IN: selectedPaymentIds]){
            pay.Batch_Reference__c = br.id;
            pay.Date_Paid__c = BACSPaymentDate;
            totalAmount += pay.Amount_Paid__c;
            numberOfPayments += 1;
            selectedPayment.add(pay);
        }
        br.Total_Amount__c = totalAmount;
        br.Number_of_Payments__c = numberOfPayments;
        update selectedPayment;
        update br;

        return '/apex/BACSPaymentFileGenerator?dateLine='+dateLine+'&debitLine='+debitLine+'&id='+br.id;
    }
}

Here my test class
@isTest
public class BACSPaymentManagerControllerTest {
@isTest(SeeAllData=true)
    static void generateBACSFile(){
        Datetime dt = Datetime.newInstance(2018, 5, 1, 8, 0, 0);
        Datetime nextdt = dt+4;
        Account acc = new Account(Name='Aikin Household');
        insert acc;
        system.assert(acc.id!=null);
        Contact con = new Contact(LastName='John Aikin',RSABI_category__c='AB',AccountId=acc.id);
        insert con;
        system.assert(con.id!=null);
        Batch_Reference__c br = new Batch_Reference__c(Name='SF20180501080000');
        insert br;
        Payment__c pay = new Payment__c(Contact__c=con.id,Date_Due__c=system.today(),Payment_Type__c='BACS',Confirm_Payment__c=false,Amount_Paid__c=100,Batch_Reference__c=br.id);
        insert pay;
        system.assert(pay.id!=null);
        List<Id> selectedPaymentId = new List<Id>();
        selectedPaymentId.add(pay.id);

        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u2 = new User(Alias = 'newUser', Email='newuser@testorg.com',
                           EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                           LocaleSidKey='en_US', ProfileId = p.Id,
                           TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com');
        insert u2;
        bacsDetails__c bacsDetails = bacsDetails__c.getInstance();

        String dateLine = 'H,20180501,'+u2.id+'20180501';
        String debitLine='D,20180505,SF20180501000000,'+bacsDetails.sortCode__c + '-' + bacsDetails.Account_Number_For_BAS_Debit__c;

        test.startTest();
        system.runAs(u2){
            String returnString =  BACSPaymentManagerController.generateBACSFile(selectedPaymentId,dt);
            system.assertEquals('/apex/BACSPaymentFileGenerator?dateLine='+dateLine+'&debitLine='+debitLine+'&id='+br.id, returnString );

        }
        test.stopTest();
    }
}

test class exception
System.AssertException: Assertion Failed: Expected: /apex/BACSPaymentFileGenerator?dateLine=H,20180501,0056E0000036LiVQAU20180501&debitLine=D,20180505,SF20180501000000,804121-00792403&id=a1X6E000000c8NqUAI, Actual: /apex/BACSPaymentFileGenerator?dateLine=H,20180501,0056E0000036LiVQAU20180501&debitLine=D,20180505,SF20180501000000,804121-00792403&id=a1X6E000000c8NrUAI

as you can see in the string return it shows the different id parameters

A: The method generateBACSFile is inserting a new Batch_Reference__c record for you and updating the Pay__c object field Batch_Reference__c
Batch_Reference__c br = new Batch_Reference__c(Name=bacsDebitAccountReference);
insert br;

 for(Payment__c pay : [SELECT Id, Name, Amount_Paid__c, Date_Paid__c, Date_Due__c FROM Payment__c WHERE Id IN: selectedPaymentIds]){
        pay.Batch_Reference__c = br.id;
        pay.Date_Paid__c = BACSPaymentDate;
        totalAmount += pay.Amount_Paid__c;
        numberOfPayments += 1;
        selectedPayment.add(pay);
    }

In the test class, don't create a new Batch_Reference__c object as the method is doing it for you. Also, in the assert statement, for verifying the Id of Batch_Reference__c, do a SOQL.
Also, remove the SeeAllData=true as you are creating your own test data.


text:
Q: How do you prototype your software UI? How do you prototype your software UI?
What's your experience?
Could you please share with me?
Thanks in advance!

A: I use Balsamiq
http://www.balsamiq.com/
It's awesome.

A: Pen and paper or a whiteboard. Prefer mockups to be reasonably divorced from the final products look and feel. While discussing interactions and how many clicks it takes to get a job done it's very fast to change paper mock ups and its obvious to all concerned that this doesn't represent the final product being almost finished.
Years ago I was involved in a project where we produced a really detailed GUI mock up that even had some code behind it to simulate the flow of events. It was fantastic for getting the users of the software to give feedback and input. It was then an absolute nightmare for the project because we were constantly behind where the users expected us to be, after all they had already seen it pretty much working, right?
Worst of all, some of that throwaway code ended up being included in the released product and was a nightmare to maintain later (there wasn't much thought put into structuring it originally 'cos it was throwaway, then the user had seen the behavior and it became the de-facto implementation of the logic for a major piece of the system). Yuk.

A: I create html pages with Visual Studio. This could easily be Dreamweaver, FrontPage, NotePad++. To me this has the benefit of the CSS and html being nearly done by time I am finished with the mockup. Usually it is easier and more productive to do your prototype in the tool or technology you plan to create the deliverable in.

A: You can use a GUI editor such as the one in the NetBeans IDE, the QtCreator IDE, or the Xcode IDE, to create a GUI mockup, without implementing handlers for all the GUI events. This GUI can then be evaluated, and possibly redesigned. Once the GUI looks as it should, then events can be properly handled.

A: I have used a combination of tools to do UIs. If the static look and feel is what I am testing then I use a combination of paper and whiteboard sketches. These are quick to do and are easily thrown away once you start working on the more detailed designs. Like "Hamish Smith"  said, you want some degree of separation between your mockups and final product.
When I want to test the interactivity of my designs, I have used paper mockups before, but I prefer to use PowerPoint which provides a better way for users to interact with the application than constantly having me show them the paper sketches of what page a button will take them to and how certain features work. I just set it up so clicking on the buttons or links on a PowerPoint slide takes you to the slide that corresponds to where that button would take you in the real application.
Currently I have been playing around with Microsoft's SketchFlow that is part of Expression Blend, and it is pretty impressive. I haven't played with it a lot though, so I am not yet aware of any limitations it may pose. Also, I tried Balsamiq and it seems like a good application too, but again I haven't used it enough to find its limitations. I want to make it clear though that I am only using them for Interactivity testing to replace PowerPoint, I still think that static mockups are best done with Paper and whiteboards.

A: I recently used a visio add-in at http://www.guuui.com/issues/02_07.php on a project.  The project has 60 or so pages in it, this made drawing the screens pretty easy.


text:
Q: Randomly drawing balls from an urn and putting them back in I'm a little rusty on my probability theory, so this might be an easy question (or not). I'm interested in this for a personal project, not homework. Consider an urn with $N$ balls, each distinguished by a number $1...N$. I pick out balls from the urn indefinitely, for each pick/time step $t$ I record the ball extracted, and put it back in the urn.
Given some integer value $c$, what is the probability that at time/pick $t$, I have picked any single/distinct ball for the $c$'th time?
To be concrete - suppose there are $N=1000$ balls, and $c=4$. I'm interested in the probability that at time $t$ I've picked the same ball (any one of them, not a specific ball) $4$ times. Obviously after $N*(c-1)+1=3001$ picks this will have happened surely, but this is likely to happen before, what is the probability for every time step $t$?
Thanks a lot for the help!

A: If $N$ is large and you make enough draws, then the number of draws $c_i$ of each ball $i$ are essentially independent variables (even though their sum is fixed). Furthermore, if $N$ is large, the numbers $c_i$ are approximately Poisson distributed, with rate parameter $\lambda (t) = t / N$. So you can compute the Poisson probability $p$ that one $c_i$ is less than $c$, and then your probability is approximately $1 - p^N$. I'll do some simulations when I get some time later to show how the approximated probability matches up with the exact probability.


text:
Q: How to get new team members up to date with the project? We are about to hire 1-2 new engineers for the software team (consisting of 3 developers, 1 tester).
What are the steps to integrate them into the team?
My ideas are :

*

*read documentation (coding standards, documents in development methodologies we use)

*get them to read the existing code

*assign them some simple tasks

*at the end, make them responsible for the code part

What else could we do?

The project is in a medical sector (ultrasound system), and is already 5 years going. We have yearly releases, and we are about to finish one release, when we want to add 1-2 engineers.
The project is in the maintenance phase (refactoring legacy code, plus adding new features). Things are pretty much on schedule (more or less).

A: My feeling is that most people's tolerance for reading documentation is fairly low (Good for a day or two, but beyond that they'll probably be itching to do something a bit more hands-on).
I don't think you can really get understanding of an application's code without a reasonable understanding of the application itself.  The software presumably has plenty of functionality which they could 'toy' with as a user; they're going to need to be able to test it eventually, so I'd expect that its fairly important that they know how to install it, configure it and perform common tasks with it
I personally find that a high-level architecture overview is usually quite handy for getting a basic feeling of how things work - Maybe allocate an hour or two of a senior engineer's time (or yourself if necessary?) in their first week simply to go through the basic nuts'n'bolts of the main application.  e.g. understanding all the subsystems and how things are tied together, knowing which bits are handled by 3rd-party software/libraries and which bits need to be maintained in-house. (Unless your organisation has got up-to-date documentation of truly exceptional quality, I'd guess that there's no way they're going to get a grip on that sort of stuff without someone explaining it to them directly using a whiteboard :-) )
As for giving them something "hands on", maintenance/bug chasing tasks might be a good way to get them up to speed for a while (a couple of weeks/months?) - they'll be in situations where specific areas of functionality need to be understood, tested and debugged; helping build up knowledge of the code, the requirements, the tools used by the company, the development processes and the product(s) as a whole while hopefully not needing to soak up too much time from the rest of the development team

A: As the Lead, I spend at least 2 days with new developers. I've found that developing a relationship in which it feels comfortable to ask the inevitable question "how is your progress?" is a MUST. There is fear in any new community to fit in... we hide mistakes, act perfect, make things better than they are, lessen difficulty. A manager spending 2 days with someone will let them know that's not what their culture is about, and allows them to lead by example. New coders need a history lesson about where you came from and how far you are along. Documents just don't do the task justice.

A: I've only been working in industry for 10 months (On placement) but I found the following helped me:

*

*Teaming up with other developers and observing how they tackle issues.

*Testing the software helped, I would need to test feature x which means I read the documentation on feature x. I did this a lot, it helped.

Both of those helped me a fair bit. Good luck.

A: I would go from high level to low.
Demo the app as soon as possible
One of the most important things is that the developer has an idea what they will work on. During the demo, point out some of the things that have been under recent development, and the direction the app is going.
Explain the high level architecture
This is also very important. Allow the new dev to listen and ask questions. Do this as a group exercise with the other devs, who will hopefully chime in and help you out. This will let the new developer know that it is OK to speak up openly and honestly.
Have a great on-boarding document ready
Having a great on-boarding document does not only help new devs, but old ones as well. It can contain expectations, useful links and environment setup information. (I cannot tell you how many times I used our on-boarding to set up my environment when I get a new computer...) This should be well structured and to the point and not linger on and not be a dumping ground for every little detail.
Encourage him/her to ask questions (and be available to answer them)
With the answers, guide them, but do not tell them what to do. Give them hints but allow them to finally figure it out themselves.
Help the other team members welcome the newcomer
There is two sides of the coin when someone joins a team. The team needs to have the tools to welcome the new developer as well.
Let them pick up a small task or two
Allow them to add something new and visible to the project that is demo-able. When it is demoed, call out who did it and what a good job they did. This can really boost self-esteem. The faster they feel like they are adding value, the faster they feel they are part of the team. The faster they will feel empowered to do the best they can.
Encourage them to getting into harder tasks once they feel more and more comfortable
Good candidates will do this naturally.

A: 1) Give them an explanation of your code rules and guidelines. Also give a general explanation of how your application works and the general code structure.
2) Find some small bugs or projects that are largely independent of other code. Explain what needs to be done, where in the code and check on them regularly.
3) Slowly start giving them larger and larger projects while checking them less and less.
4) Sit next to them from time to time. You can learn a lot by just looking how someone else tackles a problem. Small things like "oh, you can look for functions in your code by presing ctrl-." are very useful.
Now, I've found that there are two extremes:

*

*Someone who asks a question every five minutes. "What does this Path.Join  do?". They should Google first for an answer and only come to you when they can't find an answer.

*And the other extreme, someone who works for half a day without asking a single question. They should feel like it's a good thing to ask questions. I just want them to first try it out themselves.

A: Coming from someone who has had to come up to speed on a lot of different codebases in my career, here's what I would suggest:

*

*Spend a short amount of time (maybe a day or two) with activities related to using the product so that they can become familiar with what the product does.  This could be verifying bugs or executing QA test plans or going through user training.

*Work on small, localized bugs.  This gets the engineer familiar with how to build & debug the application without having to deal with learning a lot of the architecture.

*Ideally, write a small new feature that's localized.  This lets them write a chunk of code and as they write it they will become familiar with the surrounding bits of code that their new code needs to work with.

From there, expand the scope and complexity of assignments over time depending on the engineer's experience level and aptitude.  That will let the developer expand their knowledge of the codebase naturally.
I would avoid reading only tasks (documentation or code).  Reading documentation gets really boring really fast and reading random code isn't helpful since they won't have any context to work with.  It's hard enough to read code for code reviews when you already know the product & codebase.  I can't see anything useful coming out of having a brand new engineer just reading the code.

A: One "orientation" flow that I've been through (and found useful) was something along the lines of:

*

*A brief presentation giving the "Big Picture" what the components are, how the fit in and the general architecture.

*An overview of the code, intro to the functions that handle the main logic for the component(s) assigned to me. Covered some stuff related to coding conventions and style.

*A bunch of open issues and low-priority bugs were assigned (which were largely localized to the component assigned to me and fairly simple).

*I was expected to debug through the application and ask for help with stuff that I couldn't decipher.

*After the fix was made, I was walked through the the process (code-review, dev-level testing etc.) of releasing to integration.

*Repeat for the remaining tasks/bugs allocated.

I feel this approach (and variations of it) will be useful because:

*

*This was a more hands-on and relatively independent (constant no hand-holding etc.). So, it provides enough room/time for the new person to get used to the code and the way things are done in the team.

*It is also beneficial to the team as a whole since a couple of low-priority tasks/bugs can be resolved. The person helping out the new people also has more time for dealing with tasks assigned to them since constant hand-holding is not required and time can be specifically scheduled to deal with problems/issue that the new person might face.

A: Initial hires need need a small, but not too small, and well-defined task to work on. This way they can start getting a feel for how the code is structured by trying to figure out how to accomplish their task. In the process questions will come up and at that point you can direct them to documentation or other resources that they can use to help them internalize the code base. It also helps if your develop, commit, deploy cycle is short and they can see the fruits of their labor in action as quickly as possible.

A: This is how I go about

*

*Give them some tasks which are related to the project.(e.g.: If your
project is database application ask them to just create an
application to connect with the database and perform some simple
operation.)

*When you find they have understood the idea of working, give them a demo of the Project

*Ask them to read the documentation.

*Make them familiar with the coding styles and standards

*Later give them some debugging exercises(to know the flow of the project).

*Ask them to fix a point that you have already fixed (just to find out their logic with it).

*Finally make them a part of the project.

Remember : no matter how much you try, until and unless the joinee understands the project completely you wont be able to get work done most efficiently out of him.

A: Number one - first learn how to use the software to discover what problems it solves from the user's perspective. If it doesn't have a UI (e.g. its a backend service or something), let them use whatever interface is available to consume it. Getting a fresh take on a user's view of your software is always good, and it might help the new employee to see things that you can't, due to you being embedded in the project already.
After this, a good first project might be something like an add-on or new module to add to the software, minimizing the amount of knowledge needed of the existing codebase. Writing something new is always going to be easier than performing a bug fix, which might require lots of changes across many source files. In my opinion, giving a new employee a bug fix task will probably turn them off your company.

A: Your outline to familiarize the new ones with the project seems reasonable. But keep in mind that they will have a lot to learn in the beginning. This is usually an overwhelming situation. You will have to be patient and answer the same questions repeatedly. This is normal, new developers have to learn a lot, don't underestimate this. If you get angry about these repeated questions you'll risk that they will not ask and try to find out things alone which maybe very slow at best but frequently impossible. Also they will have to learn the lingo. Most teams projects develop their own language. When explaining consciously try to avoid the lingo. Explain this stuff like you would explain it to your mom. Again, be patient.
Additionally, you could try to integrate them with the others already on the team by trying some assessment center style tasks e.g. build a bridge in 45 min from 4 sheets of paper supporting a coffee cup. We use this technique in a practical course in software engineering to get a group of 8 students to break the ice before they work on a single project for 3 weeks. It helps to speed up the team forming phases.

A: These were my formula and used with several new comers - these steps proven to be highly effective.
a) All new developers will be given some introduction about the project requirements and development processes for 2 days.
b) Assigning 3 weeks task of writing Junit tests for the code which does not have enough coverage.
c) Once 3 is done,  assign small tasks
d) Assign complex tasks and done.

A: I think just assign some small tasks, ask them to write a few unit tests, make them debug some regression fails. Nothing too big or demanding, but enough to have them on their feet.
You should also assign a senior developer, preferably per new developer who could help mentor the candidate.
And yes, make them document what they are learning about the system. I am assuming here that you have some sort of internal wiki pages. If not it's definitely a must in both the long and short run - surprisingly fast way to have people ramp up. Wiki pages should not contain just the code documentation, but also stuff like known limitations (this is software :D), workarounds, time/memory performance metrics etc.

A: Don't explain only the good practices and standards of coding, but explain how the read code is structured. Explain what the software is supposed to do and how this is or will be achieved.
They will not understand until there is some job to do, so I suggest will to split into two parts, one before they start the real work, and the part two, after they started to work. They will look in some code or documentations and think "WTF!?". When this occurs, someone will be accompanying them and explaining the minor details.


text:
Q: Connecting two tables with codeigniter First of all i am new here & sorry if this question sounds silly, here's my question.
I have two tables like this
1.jobseets
2.jobsheet_tasks
the table jobsheets stores some basic information like customer, date & the jobsheet_tasks only stores the tasks  related to each job sheet.
on "jobsheets_tasks" table. the id of the "jobsheets" that belongs tasks belongs it is storing for reference purpose
here are my tables
tabels
there can be one more more tasks under a job sheet.
Relation
in order to get the information in both tables i have written the following query.
public function get_jobsheets() {
$this->db->select('jobsheets.id, jobsheets.vehicle_number, jobsheets_tasks.task');
$this->db->from('jobsheets');
$this->db->join('jobsheets_tasks', 'jobsheets_tasks.jobsheet_id = jobsheets.id');

$query = $this->db->get();

if($query->num_rows() > 0) {

  foreach ($query->result()as $row){

   $data[] = $row;

  }
return $data ;
  }

}

and i am showing the data in my view like this.
<?php
foreach($result as $jobsheet)  {

  ?>

          <?php echo  $customer->id;?>
          <?php echo  $customer->vehicle_number;?>
          <?php echo  $customer->task;?>
 <?php } ?>

and the output is like this
[wrong output][3]
the query works, but the thing is  as you can see in the above image the tasks named 1 & 2 are belongs to a one job sheetete which job sheet id is 61.
in the view the tasks belongs to same job sheets shown as separate rows, i want to show the data like this.
[correct output][3]
tasks of same job sheet one after another.
please assist me to achieve this. please provide your solutions in code level.
Thanks.

A: As my Understanding If your query working fine then check the syntax of foreach loop table... Close the
 tag
<?php
foreach($result as $jobsheet)  {
 ?>

          <?php echo  $customer->id;?>
          <?php echo  $customer->vehicle_number;?>
          <?php echo  $customer->task;?>

 <?php } ?>

A: You can try this function in your controller.....
  public function get_jobsheets() {
      $this->db->select('jobsheets.id, jobsheets.vehicle_number, GROUP_CONCAT(jobsheets_tasks.task) as task');
      $this->db->from('jobsheets');
      $this->db->join('jobsheets_tasks', 'jobsheets_tasks.jobsheet_id = jobsheets.id');
      $this->db->group_by('jobsheets.id, jobsheets.vehicle_number');
      $this->db->order_by('jobsheets.id', 'desc');
      $query = $this->db->get();
      if($query->num_rows() > 0) {
          foreach ($query->result()as $row){
              $data[] = $row;
          }
          return $data ;
      }
  }


text:
Q: Adding a Widget : what to put in plugin URL I am signing up to add a widget to wordpress.org here: http://wordpress.org/extend/plugins/add/
What do I put for the field "Plugin URL"?
Would that URL be the svn repository I am currently hosting my widget (a personal svn repo)  or would that be a URL of a website where the widget is being used?

A: When adding a plugin to WordPress.org plugin repository you need to host the plugin somewhere (anywhere) and that is the "Plugin URL" so the good guys at WordPress could download it, test it and approve it to be listed.
so just upload it to your host and enter the url to the zip file.
Once it gets approved you will get access to http://plugins.svn.wordpress.org/your_plugin_name/ using your WordPress.org user name and password.

Here's some handy links to help you
  get started.
Using Subversion with the WordPress
  Plugins Directory
  http://wordpress.org/extend/plugins/about/svn/
FAQ about the WordPress Plugins
  Directory
  http://wordpress.org/extend/plugins/about/faq/
WordPress Plugins Directory readme.txt
  standard
  http://wordpress.org/extend/plugins/about/readme.txt
readme.txt validator:
  http://wordpress.org/extend/plugins/about/validator/

this is what you get in the "WordPress.org Plugins Request Approved" email notification.
Hope This helps.

A: Plugin URL points to a resource where you describe your plugin. It could be a blog post, a GitHub repository or a dedicated website. You may even leave it out.
The value is not used by the WP people to approve your plugin; so it should not link to a zip archive.


text:
Q: Choose a tools to documents REST API I actually use Doxygen to document my php REST application and I just discover Apiary & Swagger witch seem to be good tools to document API...I want to know if there is a way to generate documentation automatically using one of this tools (apiary or swagger ) based on the code comments?

A: Using swagger-php you can generate the documentation automatically from a collection of php scripts documented using annotations.
Swagger-PHP is decently documented here: http://zircote.com/swagger-php/
A working example can be found on github: https://github.com/zircote/swagger-php/tree/master/Examples/Petstore
Regarding the generation of the json file containing the documentation check my answer here: https://stackoverflow.com/a/31178997/2853903


text:
Q: Chrome [Version 87.0.4280.88] won't open - Jan 2021. Does anyone know the download to fix this? Version 87.0.4280.88 (Official Build) (64-bit) - Jan 2021 latest
Chrome works great at first until I start my Angular application, and create a new PDF File.  Subsequent attempts to open Chrome through my shortcut on Desktop or Task Bar shows it trying to do something, but nothing shows.
I was able to track it down to what I thought was my Virus software (WebRoot) because, when I disabled it, this problem vanished. That seemed odd and a possible WebRoot bug, but in fact as I read more about these kinds of issues, I found that Chrome is affected by file locks being put onto the new file by WebRoot so that it can (later) run a scan and then releasing that lock.
I proved that this is the root cause, by simply deleting newly created files using file explorer. After doing that, the browser worked flawlessly.
Symptoms
Open up task manager and you will see many instances of 'Google Chrome' running.
Chrome acknowledges this bug and is working on a fix

Google Chrome has fixed a bug that enabled antivirus programs on Windows 10 to lock newly created files. The patching of the bug means antivirus programs running on Windows would no longer block new files generated by the Chrome web browser, such as bookmarks.

Chrome is set to auto-update.  But the current version download 87.0.4280.88 does not work.

A: Work Around

*

*First try to run your antivirus, the idea being it will unlock the file.

*If that doesn't work, delete any newly created files using file explorer, this should immediately allow for new instances.

*You may also try to click on the Magnifying Glass and then from  Top Apps area, click Google Chrome there, not sure why this works.

Clean up hung Instances

*

*Use 'Exit', by clicking on the three dots '...' in upper right hand corner of any visible Chrome instance. This will get rid of all Chrome tasks.

Here's a PowerShell script that stops all chrome instances.
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
    exit;
}
Stop-Process -Name chrome
Stop-Process -Name GoogleCrashHandler
Stop-Process -Name GoogleCrashHandler64

Note: rebooting you computer works too, but not recommended because problem will come back forcing frequent time consuming reboots.
Bug fix
Not out yet, but will be one subsequent to Version 87.0.4280.88

A: The fix was to install the latest version of Chrome. Which is Version 88.0.4324.150 (Official Build) (64-bit)
Note: Microsoft Edge opens much faster than Chrome does now.


text:
Q: Closing Firefox Window or current Tab Using Java Script How can i close a Firefox Window or current Tab Using Java Script? I tried the following code, but it doesn't work....
window.close();

Please anyone help me!!!!

A: in JS, basically:
window.close();

or
self.close();

for more information, take a look at this and this.

A: You only can close windows you have opened yourself and in most browsers the user will be prompted and ask for permisson, at least if the window has already a history.
var myWindow= window.open(address, "title", "width=300,height=400,left=100,top=200");
myWindow.close();


text:
Q: Javascript - Switch always returning default In a project I am converting scores to grades. In order to do so I have used a switch statement that checks if the score is between certain thresholds. The problem is that every case returns the default value.
The case arguments seem to be correct to me. Because if I test them outside of the switch statement they return a correct true or false value console.log(score >= 1 && score < 1.8)

const getLabelForScore = (score) => {
  let label = '';
  switch (score) {
    case (score < 1):
      label = 'F';
      break;
    case (score >= 1 && score < 1.8):
      label = 'E';
      break;
    case (score >= 1.8 && score < 3):
      label = 'D';
      break;
    case (score >= 3 && score < 4.2):
      label = 'C';
      break;
    case (score >= 4.2 && score < 5):
      label = 'B';
      break;
    case (score >= 5):
      label = 'A';
      break;
    default:
      label = 'No Grade';
  }

  return {
    score: score,
    label,
  };
};

console.log(getLabelForScore(3.15));
console.log(getLabelForScore(2.50));
console.log(getLabelForScore(4.75));

A: The switch isn't comparing what you think.  Consider the value here:
switch (score) {

So score is 3.15.  Then consider the value here:
case (score >= 3 && score < 4.2):

The case value is true.  Since 3.15 === true is false, the case is not satisfied.
You can potentially make this work by doing:
switch (true) {

Then your case conditions should compare correctly.  But honestly I think this makes the code less clear.  The semantics of what you're expressing are "if X then A, else if Y then B, else..."  There's nothing inherently wrong with if statements:
if (score < 1) {
  label = 'F';
} else if (score >= 1 && score < 1.8) {
  label = 'E';
} //...


text:
Q: When I modulate a JSP file, Can I include its javascript functions like this? If there's a JSP file like this,
...

...

...

...

...

I want to modulate "#header" part into another JSP file.
But there's a Javascript function connected to a click event on "#header".
In this situation, is it okay to make & include a new JSP file looks like underneath?
I think it's not looking good, because in this way, there could be several 'script' tags between html codes.
So I want to hear what you're thinking about this.
If there's a better way, please let me know.
Thank you.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

...

...
<%@ include file="header.jsp" %>

...

...

...


text:
Q: python argparse how to continue the program after the [-h] command? I am using argparse to write an interpreter. And facing a problem.
while True:
    cmd = input('>>>')
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', help='foo')
    parser.parse_args(cmd.split())

when I type the [-h] command, it exits the program.
>>>-h
usage: test.py [-h] [-f F]

optional arguments:
-h, --help  show this help message and exit
-f F        foo

Now, I just want that 'show this help message' but not 'exit'. So how can I do, please?

A: This can be done by erasing the predefined help command and adding an own:
import argparse

while True:
    cmd = input('>>>')
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('-h', '--help', action='store_true',
            help = 'show this help message')
    parser.add_argument('-f', help='foo')
    args = parser.parse_args(cmd.split())
    if args.help:
        parser.print_help()


text:
Q: Reconstructing a sine wave using square waves and Möbius inversion: L² convergence? Let $s$ be the ("square wave") $1$-periodic real function such that $s(x) = 1$ if $0<x<\frac{1}{2}$ and $s(x) = -1$ if $\frac{1}{2}<x<1$ (and maybe $s(0)=s(\frac{1}{2})=0$ for the sake of definitiveness, but I'll only be using $s$ a.e.).  In $L^2(\mathbb{R}/\mathbb{Z})$, we have
$$
s(x) = \frac{4}{\pi} \sum_{m=0}^{+\infty} \frac{\sin(2(2m+1)\pi x)}{2m+1}
\tag{*}
$$
by a straightforward computation of its Fourier coefficients.  Now the Fourier coefficients in question are multiplicative, so I'd like to use the Möbius inversion formula to reconstruct the sine wave using the square waves $s(kx)$, namely, I would like to state:
$$
\frac{4}{\pi} \sin(2\pi x) = \sum_{m=0}^{+\infty} \frac{\mu(2m+1)\,s((2m+1)x)}{2m+1}
\tag{†}
$$
where $\mu$ is the Möbius function.  Unless I am mistaken, (†) is clear if we just demand weak $L^2$ convergence of the RHS.  But I don't know how to say more.  Specifically:

Main question: Is there (norm) $L^2$ convergence in (†)?

Bonus points: What can be said about convergence almost everywhere?  For even more credits, what can be said about convergence for a particular $x$ (maybe every $x\not\in\mathbb{Q}$)?  For super extra credits, discuss uniform convergence (I know the Gibbs phenomenon prevents uniform convergence in (*), but I don't see why this would forbid it in (†)).
Here is a graph of the partial sum for $m\leq 12$ of the RHS of (†):

Remarks:

*

*Graphs, as well as a rendering as a sound wave (which is interesting, if not very pleasant to listen to) of the first few partial sums of the RHS of (†) are given in this Twitter thread.

*Lest anyone make the same mistake I made when thinking about this problem at first, the $s(kx)$ are not orthogonal in $L^2(\mathbb{R}/\mathbb{Z})$.  (In fact, applying Gram-Schmidt to the $s(kx)$ produces a rather unexpected sequence of functions: see here for some graphs.)

*I have a feeling this might be related to the question (which has independent interest) of finding an upper bound on $\sum_{k|n,\;k\leq B\;}\mu(k)$ as a function of $n$ and independently of $B$.  Maybe I should ask this as a separate question?

*The fact that the value at $0^+$ of the RHS of (†) converges to $0$ is equivalent to the prime number theorem, so the extra credits probably depend on some number theory, but I don't know what to think about mere $L^2$ convergence.


text:
Q: data recovery with testdisk I'm trying to recover my data after a bad installation. On my laptop I had 2 partitions: Windows and Media. Now I'm trying to recover the content of the Media partition and this is what the amazing TestDisk has found: 2 Media partitions.
I don't know which should be the next step and I'm afraid to do experiments in order to no loose all my data from Media partition.

A: You will find some useful solutions in these two questions, including instructions on how to proceed with testdisk:

*

*Recover files from External HDD to DVD+RW using Photorec

*How do I recover my accidentally lost Windows partitions after installing Ubuntu?

A: Its obvious to show two partitions and maybe more... that is due to making the same partition before the current state with the same characteristics but differ in the end
sector.
Anyway, You are making recovery so why you are afraid?!
Just move on and choose anyway one. when the recovery process is complete the testdisk will prompt you with the result and asks you were to save the recovered data...
What i wanna say to you that testdisk will not write to the recovered partition so even you choose a wrong one, this will not hurt your data.. so you can choose the other then.


text:
Q: Working on select checkbox on one click of particular div I am working on select all checkbox and I am new at this I found some solutions but its not working.
I want to select all check box of perticular div
I have 2 divs and there is separate select all checkbox for each div.
My problem is when I select one select all checkbox whole checkboxes get selected of both divs instead of this checkboxes of that div should be get selected only. Here is my code:

$('#selectall').change(function() {
  if ($(this).prop('checked')) {
    $('input').prop('checked', true);
  } else {
    $('input').prop('checked', false);
  }
});
$('#selectall').trigger('change');

$('#selectall2').change(function() {
  if ($(this).prop('checked')) {
    $('input').prop('checked', true);
  } else {
    $('input').prop('checked', false);
  }
});
$('#selectall2').trigger('change');

Select All
  <input id='selectall' type="checkbox">
1.

  <input type="checkbox">2.
  <input type="checkbox">3.
  <input type="checkbox">4.
  <input type="checkbox">5.
  <input type="checkbox">

Select All
  <input id='selectall2' type="checkbox">
1.

  <input type="checkbox">2.
  <input type="checkbox">3.
  <input type="checkbox">4.
  <input type="checkbox">5.
  <input type="checkbox">

A: Your 'input' selector is selecting every input in the document. Select only inputs that are siblings of the clicked element instead, with the siblings() method:

$('#selectall').change(function() {
  if ($(this).prop('checked')) {
    $(this).siblings().prop('checked', true);
  } else {
    $(this).siblings().prop('checked', false);
  }
});
$('#selectall').trigger('change');

$('#selectall2').change(function() {
  if ($(this).prop('checked')) {
    $(this).siblings().prop('checked', true);
  } else {
    $(this).siblings().prop('checked', false);
  }
});
$('#selectall2').trigger('change');

Select All
  <input id='selectall' type="checkbox">
1.

  <input type="checkbox">2.
  <input type="checkbox">3.
  <input type="checkbox">4.
  <input type="checkbox">5.
  <input type="checkbox">

Select All
  <input id='selectall2' type="checkbox">
1.

  <input type="checkbox">2.
  <input type="checkbox">3.
  <input type="checkbox">4.
  <input type="checkbox">5.
  <input type="checkbox">

But it would be more elegant to give your select-all checkboxes classes instead of IDs, and then you can select them both at once:

$('.selectall').change(function() {
  if ($(this).prop('checked')) {
    $(this).siblings().prop('checked', true);
  } else {
    $(this).siblings().prop('checked', false);
  }
});

Select All
  <input class='selectall' type="checkbox">
1.

  <input type="checkbox">2.
  <input type="checkbox">3.
  <input type="checkbox">4.
  <input type="checkbox">5.
  <input type="checkbox">

Select All
  <input class='selectall' type="checkbox">
1.

  <input type="checkbox">2.
  <input type="checkbox">3.
  <input type="checkbox">4.
  <input type="checkbox">5.
  <input type="checkbox">

A: Simplest.
No change to HTML and can handle a reload

$('[id^=selectall]').change(function() {  // id begins with selectall
  var chk = $(this).prop('checked');      // is it checked?
  $(this).siblings().prop('checked',chk); // set all its siblings
}).change(); // trigger now in case of reload

Select All
  <input id='selectall' type="checkbox">
1.

  <input type="checkbox">2.
  <input type="checkbox">3.
  <input type="checkbox">4.
  <input type="checkbox">5.
  <input type="checkbox">

Select All
  <input id='selectall2' type="checkbox" checked>
1.

  <input type="checkbox">2.
  <input type="checkbox">3.
  <input type="checkbox">4.
  <input type="checkbox">5.
  <input type="checkbox">


text:
Q: Center text in Canvas Android I would like to center my text (tp-TextPaint) in the rectangle speech bubble figure that I have drawn on the canvas. Does any one have any idea? I have achieved it using canvas.drawText() but I want to get it using staticLayout so that the text resizes when I resize the canvas width and height. Below is my code.
@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    drawPath.reset();

    drawPath.moveTo(0, 0);
    drawPath.lineTo(getWidth(), 0);
    drawPath.lineTo(getWidth(), 100);
    drawPath.lineTo((getWidth()/2) +20, 100);
    drawPath.lineTo(getWidth()/2, 140);
    drawPath.lineTo((getWidth()/2)-20, 100);
    drawPath.lineTo(0, 100);
    drawPath.lineTo(0, 0);

    canvas.drawPath(drawPath, drawPaint);

    TextPaint tp = new TextPaint();
    tp.setColor(Color.BLACK);
    tp.setTextSize(25);
    tp.setAntiAlias(true);

    StaticLayout sl = new StaticLayout("" + s, tp, getWidth(),Alignment.ALIGN_CENTER, 1.0f, 0.0f, true);
     sl.draw(canvas);

     }

A: Try it:
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
canvas.drawText("Hello", xPos, yPos, textPaint);

A: this may help you...
public static void drawText(Canvas canvas, Paint paint, String text) {
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    int x = (canvas.getWidth() / 2) - (bounds.width() / 2);
    int y = (canvas.getHeight() / 2) - (bounds.height() / 2);
    canvas.drawText(text, x, y, paint);
}