Q:

How can I compile certain files and add flags in a Makefile only when a specific target is selected?

I am currently facing a problem when writing a Makefile for a C project.
In particular, my project should have at least two Makefile targets (target_light and target_full), being target_light the default one.
target_light should compile all my source files, except few ones which require the installation of an external library on the system (which are saved in src/extra, for .c files, and include/extra, for .h files).
target_full should instead compile all the files, including the ones which need the external library. It should also add some flags to CFLAGS and LDLIBS.
I currently have a Makefile similar to the following one:
EXECNAME=MyExecutable

CC=gcc

SRC_DIR=src
OBJ_DIR=obj

SRC_DIR_EXTERNAL_FILES=src/extra
OBJ_DIR_EXTERNAL_FILES=obj/extra

SRC=$(wildcard $(SRC_DIR)/*.c)
OBJ=$(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o)

SRC_EXTERNAL_FILES=$(wildcard $(SRC_DIR_EXTERNAL_FILES)/*.c)
OBJ_EXTERNAL_FILES=$(SRC_EXTERNAL_FILES:$(SRC_DIR_EXTERNAL_FILES)/%.c=$(OBJ_DIR_EXTERNAL_FILES)/%.o)

CFLAGS += -Wall -O2 -Iinclude
LDLIBS += -lpthread -lm

.PHONY: all clean

all: target_light

target_light: CC=gcc
target_light_embedded: CC=x86_64-openwrt-linux-musl-gcc

target_light_debug: CFLAGS += -g
target_light_debug: target_light

target_light target_light_debug target_light_embedded: $(EXECNAME)

$(EXECNAME): $(OBJ_CC)
    $(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
    $(CC) $(CFLAGS) -c $< -o $@

clean:
    $(RM) $(OBJ_DIR)/*.o $(OBJ_DIR_EXTERNAL_FILES)/*.o
    $(RM) $(EXECNAME)
    -rm -rf $(OBJ_DIR)

I'm currently struggling to find a way to add target_full to this Makefile, which should also take into account SRC_DIR_EXTERNAL_FILES OBJ_DIR_EXTERNAL_FILES SRC_EXTERNAL_FILES OBJ_EXTERNAL_FILES, in order to compile the additional files only when requested.
How can I perform this operation? Is there a good way to do so within the Makefile?
My second question is: how can I add, at the same time, flags to both CFLAGS and LDLIBS only when target_full is selected?
I tried writing:
target_full: CFLAGS += -DENABLE_CODE_EXTERNAL_LIB -Iinclude/extra
    LDLIBS += -lext_lib

And then changing the $(EXECNAME) line in:
target_light target_light_debug target_light_embedded target_full: $(EXECNAME)

But the additional LDLIBS flag seems to be always considered, even when target_light is selected.
Should I do something like the following lines, repeating two times target_full?
target_full: CFLAGS += -DENABLE_CODE_EXTERNAL_LIB -Iinclude/extra
target_full: LDLIBS += -lext_lib

Thank you very much in advance.

A:

If target_light and target_full share object files, then when you build target_light it compiles the sources without target_full CFLAGS. When you then build target_full it won't rebuild the existing object files with extra CFLAGS.
Possible solutions:

Build all object files with target_full CFLAGS. This way the object files can be shared between the targets.
Build object files for target_light and target_full with different CFLAGS into different directories. In this case the object files aren't shared between the targets.


Q:

Fill an array, symmetric with respect to its centre

I want to create an array that must be symmetric with respect to the centre of it, as in the following example:
0 1 2 3 4 3 2 1

but, instead of having such simple numbers in the array, I need to fill the array by extracting the i-th number from a Gaussian distribution with mean 0 and variance equal to a function of the index i.
I have tried to use Piecewise, at least to fill the first half of the array, but I don't know how to fill the other half:
KfieldREAL[k_] := Piecewise[{{0, k == 0},
     {RandomVariate[NormalDistribution[mu, Exp[-(2*Pi*k*sigma/L)^2]]],
     0 < k <= n/2}, (*missing part here*)

How can I create an array like that?

A:

How about creating the left half and using its image for the right half.
sigma = .25; L = 300; mu = 1; n = 1000;

left = Table[{k,RandomVariate[NormalDistribution[mu, Exp[-(2*Pi*k*sigma/L)^2]]]}, {k, n/2}];

right = Reverse[left] /. {x_, y_} -> {n - x, y}; (*imaging*)
full = Join[Most[left], right];
ListPlot[full, Frame -> True]

Adding extra elements

Let say you want to put the element x1 [say, (0,0)] at the beginning or end. You can simply put it during the Join.
x1={0,0.0}; x2={n+1,0.0}; (*first and last element in (k,f(k)) format*)
full=Join[{x1},Most[left], right,{x2}];

Note that when using join, you don't use a single element x1, rather a list containing a single element {x1}.
for n=8 it looks like
$
\begin{array}{l l}
 0 & 0.00000 \\
 1 & 1.47757 \\
 2 & 2.29881 \\
 3 & 1.46615 \\
 4 & 1.34819 \\
 5 & 1.46615 \\
 6 & 2.29881 \\
 7 & 1.47757 \\
 9 & 0.00000 \\
\end{array}
$
And your list now has n+1 element. This is because the axis of reflection goes through 4. If you want even number of element then use n+1 for right and omit Most in final.
right = Reverse[left] /. {x_, y_} -> {n + 1 - x, y};
full = Join[left, right];

And the result for n=8 after adding the zeros
x1 = {0, 0.0}; x2 = {n + 1, 0.0};
full = Join[{x1}, left, right, {x2}];

$
\begin{array}{ll}
 0 & 0.00000 \\
 1 & 0.380134 \\
 2 & 1.48306 \\
 3 & 0.509712 \\
 4 & 1.76137 \\ \hline
 5 & 1.76137 \\
 6 & 0.509712 \\
 7 & 1.48306 \\
 8 & 0.380134 \\
 9 & 0.00000 \\
\end{array}
$
Now 4 and 5 has same element and number of elements in your final list iss n+2.


Q:

Inheritance using non-abstract base class

This post is based on the question https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance/11758048#comment15634305_11758048.
Some people said - check whether there is “is-a” relationship. If it is there use inheritance. What I think is there should be a second check for using inheritance. Use inheritance only if the base class is abstract. If the base class need to be instantiated then use composition; not inheritance.
E.g 1. Accountant is an Employee. But I will not use inheritance because a Employee object can be instantiated. (When you talk to business people, they will tell you - Accountant is an Employee. But in OO world Accountant is not (should not be) an employee)
E.g 2. Book is a SellingItem. A SellingItem cannot be instantiated - it is abstract concept. Hence I will use inheritance. The SellingItem is an abstract base class (or interface in C#)
What I am looking for here is an example that will challenge my argument –that is a scenario in which inheritance is better than composition even though the base class is non-abstract (base class can be instantiated). Can you please provide such an example?
Note: It would be more helpful if you can provide a scenario based on Bank domain, HR domain, Retail domain or any other popular domain.
Note: In the design, please assume that we have full control of the code. That is we are not using any external API. Also we are starting from beginning.
I will mark as answered if there is an example that explains a scenario that proves my argument is wrong. It is not a mere discussion on whether to use Composition or Inheritance.
I support @anon answer in https://stackoverflow.com/questions/3351666/why-use-inheritance-at-all?lq=1

The main reason for using inheritance is not as a form of composition - it is so you can get polymorphic behaviour. If you don't need polymorphism, you probably should not be using inheritance.

@MatthieuM. says in Code Smell: Inheritance Abuse

The issue with inheritance is that it can be used for two orthogonal purposes:
interface (for polymorphism)
implementation (for code reuse)

REFERENCE

Employee- Accountant Example https://stackoverflow.com/questions/11759120/issue-in-using-composition-for-is-a-relationship
Selling Item Example  - https://codereview.stackexchange.com/questions/14077/is-it-proper-tpt-inheritance
Programming SOLID Principles
Code Smell: Inheritance Abuse

A:

The entire 'is a' vs 'has a' discussion never made any sense to me. There is already a good definition about when to use inheritance, so called "Liskov substitution principle", which states:

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

The first thing you'll notice is, that it is generally a bad idea to let people with PhD explain a simple problem.
Second, this exactly states when to use inheritance. If I may use Wikipedia's article and apply it to your accountant/employee example:

Liskov's notion of a behavioral subtype defines a notion of substitutability for mutable objects; that is, if Accountant is a subtype of Employee, then objects of type Employee in a program may be replaced with objects of type Accountant without altering any of the desirable properties of that program (e.g., correctness).

The entire Principles paragraph of the Wikipedia article contains some more interesting principles.

Apparently most answers refer to LSP in one way or the other. Baqueta cleverly disguised it as a easy-to-miss-link and Geek edited his post to include LSP seconds before I posted my answer. So, LSP seems to be the most reasonable way to create your hierarachy.

Some examples of where your principle doesn't hold:

bicycle and a mountain bike
circle and a sphere
A button and an image button or toggle button.

In WPF, the concrete System.Windows.Controls.Button has the following subclasses:

CalendarButton
CalendarDayButton

In Java and C#, everything extends directly or indirectly from object, which isn't abstract.
Also in WPF: DatePickerTextBox is a subclass of (the concrete) TextBox. There are lots more examples. These respect LSP and the base class is not abstract.
As an extra note. I think the reason you found this principle is because it is generally a good idea to keep your hierarchy very flat, because inheritance introduces coupling. One or two levels deep is more than enough. Abstract classes will (almost) always be subclassed somewhere, since that is the purpose of making a class abstract, so that others can make it specialized. Most concrete classes don't need to be specialized in any way. That may be the reason you haven't found an example yet.

A:

Although you mentioned in a comment it's not the talk about "composition vs inheritance", I have to return to it. Because composition is better than inheritance If we assume that decoupling is always a good thing (Prefer composition to inheritance?).
Actually it is not always the case. Even if you see that "is a" can be replaced with "has a" or "has a" looks more promising, "is a" has a very nice automatic properties.
Consider any widget hierarchy. Usually everything related to dimension is buried deep at the root. And no matter how long the inheritance path, you can always directly call SetBounds of the instance and pass the instance to a procedure that expects deep base object, the compiler will accept it because from "is a" comes automatic type conversion and access.
But if you convert the inheritance hierarchy into composition hierarchy (technically it is always possible), you will lose convenience in both cases, because you should point to the concrete piece of composition tree in order to change the dimension or provide a procedure with particular class type. Compare
 MyForm.SetBounds(...  // easy because of an "is a"-tree
 MyForm.ScrollingWinControl.WinControl.Control.SetBounds  //complex because of a "has a"-tree

or
 GetSomeInfoOfControl(MyForm) // easy ...
 GetSomeInfoOfControl(MyForm.ScrollingWinControl.WinControl.Control) //complex ...

So despite the price of stronger coupling, inheritance sometimes is much easy to manage and abstract.


Q:

Anywhere vs somewhere

Which one should I use:

Are you going somewhere nice on holiday this year?

or

Are you going anywhere nice on holiday this year?

The presence of the word "nice" bothers me a bit and deters me from using "anywhere".

A:

That's an interesting question.
In a negative polarity context (i.e. a question or negative sentence), any and its compounds (anywhere, anything, anybody) are normally used instead of some etc. But some and its compounds are also possible, with a special meaning.
I think that meaning is specificity.

Did you bring anything?

is a neutral question, but

Did you bring something?

implies that whatever you might have brought is something specific - not necessarily something known to the questioner, but with extra meaning to one or other of the parties.
So

Are you going anywhere nice .. ?

is neutral, but

Are you going somewhere nice .. ?

is suggesting that you (the person being asked) has a special place in mind (not necessarily one that the questioner knows anything about).
The difference is very subtle, though.

A:

Are you going somewhere nice on holiday this year?  Using some makes the destination sound 'definite' and 'intended'.
Are you going anywhere nice on holiday this year?  Using any makes the destination sound 'completely unknown', 'remote' and (at least a little) 'random'.


Q:

how is the abs val of excess of p(n|odd # of parts) OVER p(n|even #of parts) = p(n|distinct odd parts?)

A question in The Elementary Theory Of Partitions asks the reader to show that the absolute value of excess of the number of partitions $n$ with an odd number of parts over the number of those with an even number of parts equals the number of partitions of $n$ into distinct odd parts.
I think that i have seen proof that $|p_{even}(n) - p_{odd}(n)| = p_{do}(n)$ but I do not believe that is what the question is asking, I think it wants: $$\left|\frac{p_{odd}(n)}{p_{even}(n)}\right|=p_{do}(n)$$
Is this what the question asks or am I misunderstanding? If it is true how is it true?

A:

I think they want the equation with the difference, not the quotient.
The “excess of $A$ over $B$” means $A-B$. In other words, the amount by which $A$ exceeds $B$.


Q:

How to run Docker deamon on shared Linux kernel?

I have a problem starting Docker deamon. The root cause of this are missing modules in linux kernel. I don't have possibility to change/update the kernel.
Is there a workaround that would help me start Docker?
If that helps: the goal I want to achieve is to set up a repository of the Docker images. I won't run any containers on that computer.
I'm using Ubuntu 14.04.5 LTS with kernel 3.13.0-042stab12.5 x86_64

A:

You have a few options:
(1) Run a Virtual Machine (hopefully with hardware acceleration), install the docker daemon/registry/whatever you need inside the VM and proxy network connections from the host to the VM.
(2) If you simply want to run a registry, find one that does not require the docker daemon to be installed to run.


Q:

Alternative to mencoder and ffmpeg for timelapse in Raspbian Jessie

mencoder and ffmpeg are no longer included in the Raspbian repositories since Jessie was released. mencoder was previously used in an RPi Foundation tutorial here to compile a timelapse video.
I've seen that avconv can be used to do the same thing, and it is included in Raspbian Jessie, but what command should I use for that?
My folder of stills looks like this:
photo1.jpg  photo2.jpg  photo3.jpg  photo4.jpg  photo5.jpg
photo6.jpg  photo7.jpg  photo8.jpg  photo9.jpg   photo10.jpg
...

The previous command looked like this:
ls *.jpg > stills.txt; mencoder -nosound -ovc lavc -lavcopts vcodec=mpeg4:aspect=16/9:vbitrate=8000000 -vf scale=1920:1080 -o timelapse.avi -mf type=jpeg:fps=24 mf://@stills.txt

How could I do this with avconv or another command that is supported in Raspbian Jessie?

A:

There's a reasonably simple approach given at techedemic.com:
Name all image files sequentially.
avconv can (apparently - I haven't checked) require names with a leading string followed by 0000/0001/0002/etc. Convert your file names using:
ls *.JPG| awk 'BEGIN{ a=0 }{ printf "mv %s myfile%04d.JPG\n", $0, a++ }' | bash

With everything renamed, use the following command to create a clip with the original resolution, and at high quality:
avconv -y -r 10 -i myfile%4d.JPG -r 10 -vcodec libx264 -q:v 3  -vf crop=4256:2832,scale=iw:ih tlfullhiqual.mp4;

Explanation:

-y forces avconv to overwrite any file
-r 10 creates a clip with 10 frames per seconds (for some versions of avconv you have to specify it twice)
-i specifies the input file(s). %4d means any 4 decimal numbers
-vcodec specifies the video codec to be used (H.264 in this case)
-q:v specifies the quality, value ranges from 1 (best) to 31 (worse)
crop= specifies which area of the images will be cropped
scale= indicates how much scaling must take place (in the above example iw:ih
  indicates that the output width and height will be that of the in
  width and in height)
the last parameter is the output file


Q:

Understanding the process of receiving network packets

I started to learn Linux Networking and packets filtering. In the iptables documentation it is stated that:

If a packet is destined for this box, the packet passes downwards in the diagram, to the INPUT chain. If it passes this, any processes waiting for that packet will receive it.

So, suppose there're 3 server apps on a host. Servers A and B are TCP servers, and C is UDP server.
Is it true, that if we receive an UDP packet, at IP level this packet is to be delivered for apps A, B, C? Or sockets of apps A & B wouldn't receive this packet at all?

A:

TCP servers and UDP servers operate in very different ways.
At most one TCP server will listen on a given TCP port (corner cases ignored for the sake of simplicity). Connection requests (encapsulated in IP packets) destined for that port are "accepted" by exactly one process (more accurately, accepted by a process that has a file descriptor corresponding to exactly one listening endpoint). The combination of [remote_address,remote_port] and [local_address,local_port] is unique. A TCP server doesn't really receive "packets", it receives a stream of data that doesn't have any specific relationship to the underlying packets that carry the data (packet "boundaries" are not directly visible to the receiving process). And a TCP packet that is neither a connection request nor associated with any existing connection would simply be discarded.
With UDP, each UDP datagram is logically independent and may be received by multiple listening processes. That is, more than one process can bind to the same UDP endpoint and receive datagrams sent to it. Typically, each datagram corresponds to a single IP packet though it is possible for a datagram to be broken into multiple packets for transmission.
So, in your example: no, a server that is listening for TCP requests (a "TCP server") will never receive a UDP packet. The port namespaces for TCP and UDP are completely separate.


Q:

How to prevent UIKeyboard from dismissing?

I have an accessory view on my keyboard that uses a next and previous button to hop between UITextFields. When the next or previous button is pressed, an IBAction is called which finds the textfield to switch to and then performs
[nextTextField becomeFirstResponder];

Usually this works fine but once in a while the keyboard drops partially and then comes back up. I'm sure this is because becoming first responder dismisses the keyboard and then summons it back up again, and sometimes this happens slowly enough that the keyboard has visually begun dismissing before it is called back.
So how can I stop the keyboard from trying to dismiss?

A:

The keyboard should only dismiss if you've explicitly called for it to dismiss (when you're in the same view). Just ensure there aren't any subsequent calls to:
    [textField resignFirstResponder];
Another option is to conform to the UITextFieldDelegate protocol and implement these methods:
-(void)textViewDidBeginEditing:(UITextView *)textView
-(void)textViewDidEndEditing:(UITextView *)textView

The latter is where you'll want to NOT call your keyboard resigner


Q:

How to modify table and create bins for histogram representation in R

I am a bit new to R and I was experimenting with ggplot.
I have a table like this:
table http://dl.dropbox.com/u/43697/temporary/data_frame.jpg
I would like to modify the table to set bins based on different breaks and record the frequency for each bin:
table http://dl.dropbox.com/u/43697/temporary/data_frame2.jpg
I guess the first thing to do would be to set breaks on the year columns and later transpose them to match the AllotmentID.
Any thoughts?

A:

Without a reproducible example, and no hint of what sort of graph you'd like to make using ggplot2, all I can do is point you in the direction of a useful tool. In this case I suspect you will want to make good use of the function cut, which is usually the go-to tool in R for binning.
cut will return a factor, which you will likely want to pass to table to count the number of observations in each "bin".
EDIT
Here's a very bare bones example. You will want to tinker with it to make the breaks and bins work out the way you want them to:
set.seed(123)
X <- runif(100,30,60)
table(cut(X,breaks=seq(30,60,by=5),labels=paste(as.character(seq(30,55,by=5)),"%",sep="")))


Q:

Usage of varnish cache at the database record level

I'm working with a legacy codebase for a web app with an architecture that they call "widget based". It's basically cached database result sets of data that is to be presented on several "widgets" in different parts of the application.  So, when they update or create a new record, they use a set of rules to know which caches to invalidate so that said record would be presented.
By reading the varnish use case examples, it looks like it's not built to cache database records (like memcache or apc), but a webserver's response itself (AKA, the whole html page).
If my last statement is correct, how can I invalidate only the varnish cache's cache registries for the html pages that shows the new record (basically, cherry-picking what to invalidate)?

A:

You can purge the contents of the cache. This is explained in this section of the documentation Purging and Banning
Basicly you added something like this in the VCL file
acl purge {
        "localhost";
        "192.168.55.0"/24;
}

sub vcl_recv {
        # allow PURGE from localhost and 192.168.55...

        if (req.method == "PURGE") {
                if (!client.ip ~ purge) {
                        return(synth(405,"Not allowed."));
                }
                return (purge);
        }
}

And after restarting the server you can purge pages using the method PURGE.
For example, if you have the following url: http://yourhost.com/widget/a ,
you send a purge request to the same address to remove it from the cache.
You can use the command line utility curl for that as below, but any tool / library that allow to send custom HTTP methods will work:
curl -X PURGE http://yourhost.com/widget/a


Q:

Validating user input to see if in range of numbers, if not loop back to ask for user input again

If the player types in any out of range or invalid values, I want it to loop back to ask him to place his bet again.
I can get this half-way working when I wrap raw_input with int().
However, if say the player accidentally typed a letter or just hit enter without typing anything, it would throw an error, thus stopping the game/script.
So if a player does make a mistake like that, I need it to loop back to "Place your bet" again instead of throwing an error and crashing the script.
def betAmount():
    if number_of_hands == 1:
        if chip_count_player1 > 0:
            global chips_bet
            chips_bet = raw_input("Place your bet!")
            if chips_bet in range(0, chip_count_player1 + 1):
                print "Your bet is within range"
            else:
                print "NOT IN RANGE"
                betAmount()

A:

You need to convert the chips_bet to a number like this
try:
    chips_bet = int(raw_input("Place your bet!"))
except ValueError:
    betAmount()

You are constructing a new list of numbers and then checking if the chips_bet is there in it or not. That is inefficient. You can check like this
if 0 <= chips_bet <= chip_count_player1:

The base idea can be implemented like this
bet = getBet()
...
def getBet(maximum):
    bet = -1
    while (bet < 0) or (bet > maximum):
        try:
            bet = int(raw_input("Place your bet!"))
        except ValueError: pass
    return bet


Q:

Django - Parse XML, output as HTML fragments for iFrame?

I've been asked to quickly put together a small system that takes a Yahoo XML feed, parses it, and creates a HTML fragment based on it.
At the moment, I'm using Django to handle the URL routing, with some Python script, and outputting a bit of HTML in a  (with hardcoded dimensions as inline CSS), that can hopefully be put into an iframe (this part was my half-baked idea).
I've also been asked to throw in a few other bits, like something to parse Twitter XML feeds, Wordpress XML search results etc., that could be re-arranged on a page in iFrames as well.
URLs would be somehting like http://foobar.com/yahoofeed/keyword/dimensions, or  /twitter/keyword/dimensions,where keyword is the search keyword, and dimensions is one of some pre-determined sizings (I suppose if there more parameters, I should be passing these as query strings, as opposed to as virtual subiddirectories as part of the URL, right? Thoughts? Pros/Cons of either?).
However, I'm wondering if this is the best way to do this? It does seem a bit hackish to me, but I'm not really sure. Are there any problems with the current approach?
Cheers,
Victor

A:

Your solution sounds fine.  The nature of your problem is glueing together some bits, so it will always be a bit ad-hoc and hackish (and Python is ideally suited for a job like that).
I would use query strings for anything which:

doesn't represent a permanent resource
represents some kind of query or input option
represents an output option

I'd make an exception to this to provide nice URLs for the simple case, and if an option was always required (and always will be required) then you could make it part of the path.  So I think keeping the keyword as part of the URL is fine, but dimensions should be a query string option.


Q:

Sed command that would ignore any commented match

I'm trying to create a sed command using regex in order to substitute something in a text file only if it is not commented but I'm running into some troubles due to my almost non-existent knowledge of sed's commands.
I found solutions for small parts of the problem but some aren't complete enough or I just cannot put them together. TL;DR version available at the end.
Let's first determinate my ultimate goal
I'd like to match anything (like any regular regex (hehe)) in a text file only if it is NOT commented. As I'd like to do it for multiple languages, let's just take the common C comments.
So, in this case, words or lines can be commented different ways. We have the // to comment only what's next on the line and we also have the /* */ comment block.

Environment
I'm currently working on Mac OSX which only supports POSIX sed but I installed a GNU-sed which I find better. (Thanks to Homebrew. The package is gnu-sed and the command is gsed.) So, both of them are available to me if you prefer using one or another.
I'm writing this assuming a GNU-sed is used.

Ignoring a case
First problem, how to ignore some cases. I found that quite easily in this topic.
Now, the // part seems easy for me to do and I would just have to add an OR ( | ) condition to join it with the other condition.
It would look something like this:
    sed -E "/\/\/.*/! s/foo/bar/" file

Then, if the input file is:
foo
42
test
//foo
//42
//    foo
//something foo
foo
42
something foo
  foo

The output is:
bar
42
test
//foo
//42
//    foo
//something foo
bar
42
something bar
  bar

So now, I'm just going to focus my reflexion on the /* */ comment block only.

Matching through multiple lines
Second problem, how to to make the regex match through multiple lines. Well, I think this is the major problem. I found this topic talking about how to match through only one new line character. Well, it took me a moment to understand how it works. But this part of solution brings me a new problem and new questions.
It can obviously ignore only one new line ( \n ). So I now want to do the same but for an unknown number of lines (from 0 to infinite ( * )). I bet I have to loop through the lines but this is where I'm stuck because I know nothing about sed's commands and it's really awkward to me.
During my searches, I found a little script having the purpose of replacing the tail command and it uses a loop (I guess) but I fail at understanding its functioning.
Make it so it matches only before the */ part
The third part would be to make sure the ignored case only matches things before the end of the comment block ( */ ). So, in the end, the ignore case would only match things between /* and */. The final command would then completely ignore things written inside a commentary block.
I made no real search on this part as I didn't solve the previous point and it appears to me that this */ problem depends on the /* previous problem.

Final part: Putting all this together
Well, it is obvious I completely failed at this at the moment.

TL;DR
My question is: What would be the sed command in order to substitute anything we want in a text file only if it is not commented ?

Appendix
If you know an easier way to do it, using any other language, it's also very welcome. So, if you know how to do it with awk, python or anything else, feel free to share it.

A:

You should not believe them if they tell you it cannot be done. You should believe them, however, if they tell you it's not easy.
sed '\|*/|!{ s|/\*|\n&|              #if ! */ repl 1st /* w/ \n/*
     h;      s|foo|bar|g;/\n/!b      #hold; repl all foo/bar; if ! \n branch
     G;      s|\n.*\n||;:n           #Get; clear difference; :new label
     n;      \|*/|!bn;s|^|\n/*|      #new line; if ! */ branch new label
     };s|*/|\n&|g                    #repl all */ w/ \n*/
       s|foo|&\nbar|g;:r             #repl all foo w/ foo\nbar
       s|\(/\*[^\n]*\)\nbar|\1|g;tr  #repl all /*[^\n]*\nbar w/ foo
       s|foo\n\(b\)|\1|g             #repl all foo\nbar w/ bar
       s|^\n/.||;s|\n||g             #clear any \n inserts
'    <<\INPUT
asfoo   /* asdfooasdfoo

asdfasdfoo
asdfasdfoo
foo */foo /*foo*/ foo
/*.
foo*/
foo
hello

INPUT

OUTPUT
asbar   /* asdfooasdfoo

asdfasdfoo
asdfasdfoo
foo */bar /*foo*/ bar
/*.
foo*/
bar
hello


Q:

Backbone - Declare Default Parameters for a Fetch inside a Model

I have some global parameters that I want to be sent in every time I call a fetch on a collection... my issue is I don't want to declare the data: { ... } every time I fetch.
Is there a way I can provide default parameters inside the Collection itself with the possibility to add more or override some?
For example:
Instead of doing this every time:
this.articlesCollection.fetch({
    dataType: 'jsonp',
    data: {
        deviceType: GlobalVars.deviceType,
        memberId: GlobalVars.memberId,
        authToken: GlobalVars.authToken,
        targetObjectId: userId,
        limit: 50,
        excludeArticleBodies: true,
        excludeViewedItems: false
    },
    success: function() {
        _this.render();
    }
});

I'd like to just provide a one or two parameters and a success function, like this:
this.articlesCollection.fetch({
    data: {
        targetObjectId: userId
    },
    success: function() {
        _this.render();
    }
});

... and have the Collection look something like:
define([
  'underscore',
  'backbone',
  'global',
  'utilities',
  'models/article/ArticleModel'
], function(_, Backbone, GlobalVars, Utils, ArticleModel){

  var ArticlesCollection = Backbone.Collection.extend({

      model: ArticleModel,

      initialize : function(view) {
          this.view = view;
      },

      dataType: 'jsonp',
      data: {
          deviceType: GlobalVars.deviceType,
          memberId: GlobalVars.memberId,
          authToken: GlobalVars.authToken,
          limit: 50,
          excludeArticleBodies: true,
          excludeViewedItems: false
       },

      url : function() {
        return GlobalVars.baseAPIUrl + '/API/GetArticles';
      },

      parse : function(data) {
        return data.Articles;
      }

  });

  return ArticlesCollection;

});

A:

Here's a working jsFiddle with one approach:  http://jsfiddle.net/LEuGq/1/
Basically, you configure both an object of defaultParams and params as properties of your collection, which are used to dynamically compute the correct URL when fetch() is called. This way is probably more in alignment with backbone than changing the API of fetch() to accept parameters, which it is not designed to do.
var ParamCollection = Backbone.Collection.extend({

    defaultParams: {deviceType: 'raceCar', limit: 42},
    params: {},
    url: function() {
      return "/paramcollection?" + $.param(_.defaults(this.params, this.defaultParams));
    }
});
var paramCollection = new ParamCollection();
paramCollection.params.excludeArticleBodies = true;
paramCollection.params.limit = 52;
$("#debug").append(paramCollection.url());


Q:

ASP Photo Processing - List Photo colors

Like the the amazing "histogram" property in Ruby (RMagicK), that computes a list of colors in a photo, in order of frequency - is there anything similar to this for Classic ASP/.NET, in the form of a third-party plugin or component?
Regards

A:

It sounds like RMagick is a derivative of ImageMagick. The Windows version has an installer that allows you to install a COM component. (You will have to check this in the installer for it to be installed).  http://www.imagemagick.org/script/binary-releases.php?ImageMagick=8cvbummutopc2abqtaafa0bu66#windows
This COM component can be used from classic ASP.
I have some classic ASP code that uses ImageMagick, the syntax is a bit unusual. Please note that this won't function on its own, because it depends om some other functions, but it will give you an idea of how to use the COM component:
function DrawPoly(destFile, coordinates, fillcolor, strokecolor)
    ' Draws a single polygon and returns a result-image
    Dim img: Set img = CreateObject("ImageMagickObject.MagickImage.1")
    dim polygon, DrawCommand, DrawResult
        polygon = trim(coordinates)
        polygon = normalizeCoordinates(polygon,10)
        DrawCommand = "polygon " & trim(polygon)
        DrawResult  = img.Convert(Server.Mappath(destFile), "-matte", "-fill", fillColor, "-stroke", strokeColor, "-draw", DrawCommand, Server.Mappath(destFile))
        If Err.Number <> 0 Then Response.Write(Err.Number & ": " & Err.Description & vbCrLf & msgs)
    DrawPoly = destFile
    Set img = nothing
end function

I don't know how to perform a histogram, but I hope this piece of code together with the imagemagick docs will get you there.
Erik


Q:

Start android emulator adb from Jenkins in windows (run instrumented tests, emulator does not appear)

I would like to start emulator from Jenkins to test Android app. This is my setup of the project in jenkins and console output:

When I tried Jenkins android emulator plugin with existing emulator device and his name, setup and output is here:
The build is successful, but I cant see the running emulator when testing is running.
Strange thing of these two options is, that when I start the command line and type these two commands, the emulator is always shown and it is running normally. But from Jenkins, in the second option I cant see it. And first option is stuck. See the screens please.
Can somebody help me with some advice? I have tried many options and I cant figure it out.
Many thanks :)
P.S.: Here are the output texts (in case that somebody would like to copy it)
1)
C:\Program Files (x86)\Jenkins\workspace\Android Sandbox>C:\Users\josef\AppData\Local\Android\Sdk/tools/emulator -avd Nexus_4_API_22 -accel auto
emulator: WARNING: encryption is off
Hax is enabled
Hax ram_size 0x40000000
HAX is working and emulator runs in fast virt mode.

2)
$ C:\Users\josef\AppData\Local\Android\Sdk/tools/android.bat list target
[android] Using Android SDK: C:\Users\josef\AppData\Local\Android\Sdk
$ C:\Users\josef\AppData\Local\Android\Sdk/platform-tools/adb.exe start-server
* daemon not running. starting it now at tcp:5824 *
* daemon started successfully *
$ C:\Users\josef\AppData\Local\Android\Sdk/platform-tools/adb.exe start-server
[android] Starting Android emulator
[android] Erasing existing emulator data...
$ C:\Users\josef\AppData\Local\Android\Sdk/tools/emulator.exe -engine classic -ports 5684,5685 -report-console tcp:5845,max=60 -avd Nexus_4_API_22 -no-snapshot-load -no-snapshot-save -wipe-data -engine auto
emulator: WARNING: encryption is off
Creating filesystem with parameters:
    Size: 69206016
    Block size: 4096
    Blocks per group: 32768
    Inodes per group: 4224
    Inode size: 256
    Journal blocks: 1024
    Label:
    Blocks: 16896
    Block groups: 1
    Reserved block group size: 7
Created filesystem with 11/4224 inodes and 1302/16896 blocks
Hax is enabled
Hax ram_size 0x40000000
HAX is working and emulator runs in fast virt mode.
emulator: WARNING: Requested adb port (5685) is outside the recommended range [5555,5586]. ADB may not function properly for the emulator. See -help-port for details.
[android] Emulator reported that the console is available on port 5 684
[android] Waiting for emulator to finish booting...
$ C:\Users\josef\AppData\Local\Android\Sdk/platform-tools/adb.exe -s emulator-5684 wait-for-device shell getprop init.svc.bootanim
[android] Emulator reported that the startup process is 'running'
$ C:\Users\josef\AppData\Local\Android\Sdk/platform-tools/adb.exe -s emulator-5684 wait-for-device shell getprop init.svc.bootanim
[android] Emulator reported that the startup process is 'stopped'
$ C:\Users\josef\AppData\Local\Android\Sdk/platform-tools/adb.exe -s emulator-5684 logcat -v time
[android] Emulator is ready for use (took 31 seconds)
[Gradle] - Launching build.
[Android Sandbox] $ cmd.exe /C '""C:\Program Files (x86)\Jenkins\workspace\Android Sandbox\gradlew.bat"' clean connectedAndroidTest && exit %%ERRORLEVEL%%"
Starting a Gradle Daemon, 2 incompatible and 5 stopped Daemons could not be reused, use --status for details
NDK is missing a "platforms" directory.
If you are using NDK, verify the ndk.dir is set to a valid NDK directory.  It is currently set to C:\Users\josef\AppData\Local\Android\Sdk\ndk-bundle.
If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning.

A:

I recommend using the command lines instead of Android Emulator Plugin. This article is helpful


Q:

Solr Range Buckets and Long URLS

I am looking to see if in Solr 3.4 it is possible to define a range of a field as a field itself so say:
Price : [0-1000]
Price : [1001-*]

That i could simply pass a field name in say PriceLow and PriceHigh for each of these.  I need to return facet count for upto 50 ranges and im concerned i will be limited by length passing them in via HTTP Get.  As the queries i am passing are very long as well.
Thanks
Ben

A:

I think you're looking for something like explained here.
If you have many facet ranges, you can pre-compute the ranges as plain strings in another field during indexing playing around with regex. You can basically create a copyField of the following fieldType, on which every pattern is a different range:
<fieldtype name="priceclass" class="solr.TextField">
  <analyzer>
    <tokenizer class="solr.KeywordTokenizerFactory"/>
    <filter class="solr.PatternReplaceFilterFactory" pattern="^([0-9]{0,2})([\.,][0-9]{1,2})?$" replacement="0 - 99" replace="all" />
    <filter class="solr.PatternReplaceFilterFactory" pattern="^(1[0-9][0-9]|2[0-4][0-9]|)([\.,][0-9]{1,2})?$" replacement="100 - 249" replace="all" />
    <filter class="solr.PatternReplaceFilterFactory" pattern="^(2[5-9][0-9]|[3-4][0-9][0-9])([\.,][0-9]{1,2})?$" replacement="250 - 499" replace="all" />
    <filter class="solr.PatternReplaceFilterFactory" pattern="^([5-9][0-9][0-9])([\.,][0-9]{1,2})?$" replacement="500 - 999" replace="all" />
    <filter class="solr.PatternReplaceFilterFactory" pattern="^([0-9]{4,5})([\.,][0-9]{1,2})?$" replacement="999 -" replace="all" />
  </analyzer>
</fieldtype>

Then you can directly facet on the new copy field making a simple field facet.
This way you can avoid using long urls with many ranges, but if you need to change your ranges you'll need to reindex everything.


Q:

Ubercart and Drupal 7 - hook_add_to_cart

http://www.ubercart.org/docs/api/hook_add_to_cart
I am trying to hook into the add cart functionality of ubercart. I have created stock_control.module and stock_control.info files and enabled the module. In my .module file I have
The first is output but the 2nd is not.
<?php
   dsm('hello1');
     function stock_control_add_to_cart($nid, $qty, $data) {
    dsm('hello2');
     if ($qty > 1) {
    $result[] = array(
  '        success' => FALSE,
  'message' => t('Sorry, you can only add one of those at a time.'),
);
  }
  return $result;
 }

A:

I believe the hook in version 7 is hook_uc_add_to_cart.


Q:

How to undelete or restore deleted all

I have installed free app from appexchange..but I deleted app.now I want to get back app again.what to do .where to restore the app .

A:

It is not possible to restore/undelete a deleted app.
https://developer.salesforce.com/forums/?id=906F0000000MLWGIA4
You might be able to install in from appExchange again.
But data in the app is more difficult.
You can also try and contact Customer Support.
Best regards,
Christian


Q:

How to remove or disable language preferences key from iPad keyboard for specific text field

1
Needs to remove or disable key from iPad keyboard for specific text field, shown in the image

A:

You cannot remove a specific button from keyboard unless you create a custom keyboard. But, there are different kinds of keyboard defined already. What you can do is  manage the keyboard behaviour.
[yourTextField setKeyboardType: UIKeyboardType];


Q:

Can I set the timeout for UdpClient in C#?

I am wondering whether I can set a timeout value for UdpClient receive method.
I want to use block mode, but because sometimes udp will lost packet, my program udpClient.receive will hang there forever.
any good ideas how I can manage that?

A:

There is a SendTimeout and a ReceiveTimeout property that you can use in the Socket of the UdpClient.
Here is an example of a 5 second timeout:
var udpClient = new UdpClient();

udpClient.Client.SendTimeout = 5000;
udpClient.Client.ReceiveTimeout = 5000;

...

A:

What Filip is referring to is nested within the socket that UdpClient contains (UdpClient.Client.ReceiveTimeout).
You can also use the async methods to do this, but manually block execution:
var timeToWait = TimeSpan.FromSeconds(10);

var udpClient = new UdpClient( portNumber );
var asyncResult = udpClient.BeginReceive( null, null );
asyncResult.AsyncWaitHandle.WaitOne( timeToWait );
if (asyncResult.IsCompleted)
{
    try
    {
        IPEndPoint remoteEP = null;
        byte[] receivedData = udpClient.EndReceive( asyncResult, ref remoteEP );
        // EndReceive worked and we have received data and remote endpoint
    }
    catch (Exception ex)
    {
        // EndReceive failed and we ended up here
    }
}
else
{
    // The operation wasn't completed before the timeout and we're off the hook
}

A:

Actually, it appears that UdpClient is broken when it comes to timeouts.  I tried to write a server with a thread containing only a Receive which got the data and added it to a queue.  I've done this sort of things for years with TCP.  The expectation is that the loop blocks at the receive until a message comes in from a requester.  However, despite setting the timeout to infinity:
_server.Client.ReceiveTimeout = 0; //block waiting for connections
_server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);

the socket times out after about 3 minutes.
The only workaround I found was to catch the timeout exception and continue the loop.  This hides the Microsoft bug but fails to answer the fundamental question of why this is happening.


Q:

onClick event won't fire

Sorry for somewhat of a duplicate question, but the valid answers I've seen on other posts match exactly what I've tried and I'm a bit lost.  I'm simply trying to get the onClick event for my button to fire.  It doesn't fire, and zero of the code in my handleClickNewQuote method executes.
I'm sure you can tell I'm extremely new to React and this is just a rough draft of my app if you will.
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';

class App extends Component {
  constructor(props){
    super(props)
    this.state={
      quote: this.quote,
      author: this.author,
      category: this.category
    }
    this.handleClickNewQuote  = this.handleClickNewQuote.bind(this);
    // this.handleClickTweet = this.handleClickTweet.bind(this);
    // this.handleClickSave = this.handleClickSave.bind(this);
  }

  //Fires when app is loaded~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  componentDidMount(){
    axios.get('http://localhost:3001/api/getQuote').then(response =>{
      this.setState({quote: response.data.quote,
                    author: response.data.author,
                    category: response.data.category})
    }).catch(console.log)
  }

  //Fires when NewQuote is clicked, makes API call to server and gets data back

  handleClickNewQuote(){
    axios.get('http://localhost:3001/api/getQuote').then(response =>{
      this.setState({quote: response.data.quote,
                    author: response.data.author,
                    category: response.data.category})
    }).catch(console.log)
    console.log("Button is working?");
  }

  render() {
    return (

{this.state.quote}

{this.state.author}

                <button type="button" className="button-color" id="save-button">Save</button>
                <button type="button" className="button-color" id="tweet-button">Tweet</button>
                <button type="button" className="button-color" id="new-quote-button"  onClick={() => {this.handleClickNewQuote}}>New Quote</button>

    );
  }
}

export default App;

A:

It is because in your arrow function in onClick you are not returning the handleClickNewQuote() function to be ran.
So, if you did the following it would fire:
onClick={() => this.handleClickNewQuote}
However, to simplify this even more we could just remove the wrapping function entirely:
onClick={this.handleClickNewQuote}


Q:

AngularJS & PHP: upload my app on several servers after changes

I develop an angular-php web application which I have it running online, for different users, on 5 different subdomains, such us:

sub1.mydomain.com
sub2.mydomain.com
sub3.mydomain.com
sub4.mydomain.com
sub5.mydomain.com

Problem:
My problem is that I still develop the web-app local and whenever I change files(php, js,tpl.html,css or when add new ones) I have to upload them on each subdomain.
Question:
Is there a way/library/API whatever that I can use to make something like package (with the updated or new files) and just call it from each subdomain url , and make the appropriate updates?
Or should I just copy them to each subdomain?
Do I make myself clear, in other words just like on cms systems that we press the update button and we update a component/module.
If anyone knows a way of doing that please enlight me. Thanks.
I tried to depict what i mean.

A:

What you are describing is called deployment.
There are a lot of ways to create a deployment mechanism so there is not a single answer to your question. Depends of the tools that you are using, the servers where your app is hosted, etc.
If not, I advise you to use Git to make versions of your app (with Github or Gitlab) and automate the deployment process when you push a new piece of code.
You can make your own scripts to deploy or use online services (surely what you need because of "systems that we press the update button").
I can't advice you one particular service but you would find what you need in Googling "deployment automation github".


Q:

How does feign obtain header data for the requested interface

I am requesting an interface with feign and need to get the Headers value  for that interface.
I have used feign for the requested interface headers transfer parameters before, pass token to headers:
@RequestMapping(method = RequestMethod.GET, value = "/api/get-store-list")
List<Store> getStoreList(@RequestHeader("Authorization") String Authorization);

However, this interface puts the amount of data in the x-total-count of headers, so I still need to get the value of x-total-count.
How do I get the value of x-total-count.

A:

Feign has the headers in the Response object, and that can be the return value:
public interface Swapi {
    @RequestLine("GET /people/{id}/")
    Response personResponse(@Param("id") int person);
}

Now you can call headers() on the result. That, of course, leaves you with the body as a string, which is not pretty. Let’s try something more Feign like.

@Data
public class Person {
    String name;
    int height;
    int mass;
}

public interface Swapi {
    @RequestLine("GET /people/{id}/")
    Person person(@Param("id") int person);
}

Now the headers are hidden again, but they are still available to the decoder, which is the place that I will plug in:
@RequiredArgsConstructor
public class HeaderReadingDecoder implements Decoder {

    private final Decoder wrappedDecoder;

    @Override
    public Object decode(Response response, Type type) throws IOException {
        var server = response.headers().getOrDefault("server",
            List.of("")).iterator().next();
        System.out.println("server = " + server);
        var etag = response.headers().getOrDefault("etag",
            List.of("")).iterator().next();
        System.out.println("etag = " + etag);
        return wrappedDecoder.decode(response, type);
    }
}

Of course, System.out is evil, but I really don’t know yet what you want to do with that header value. It’s up to you. Now you can use this with:
Swapi swapi = Feign.builder()
    .decoder(new HeaderReadingDecoder(new JacksonDecoder()))
    .target(Swapi.class, "https://swapi.co/api");
Person person = swapi.person(2);
System.out.println("person = " + person);

And you will get:
server = cloudflare
etag = "3a58f420395ff0deed943e331d3bf74b"
person = Person(name=C-3PO, height=167, mass=75)


Q:

Import database with SSDT programmatically

I have a situation where I need to copy everything out of a database (except data) and deploy it to a new database. I am currently doing this by importing from the existing database into SSDT and then publish the project to the new database.
I want to know if there is a way I can do this programmatically. Ideally I would like to have a process in place where I can give the process the name of the database to copy from, the name of the database to copy to, and then the process  would just automatically carry out the import and export.
What might be a good way to do this?

A:

SSDT is powered by a library called the Data-Tier Application Framework (also known as DacFX).  DacFX is a public API that you can use to extract and publish dacpac files.  You can find a copy of DacFX in Program Files under Visual Studio or SQL Server in a directory something like this:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\130
C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin

You can download the latest version of DacFX here:
https://www.microsoft.com/en-us/download/details.aspx?id=51672
Note that when you install DacFX it's also necessary to install its dependencies, SqlSysClrTypes and SqlDom, which can be found in the System Requirements section of the above download page.
To use DacFX to extract and publish a dacpac file, you can use SqlPackage.exe, like so:
C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin\SqlPackage.exe /a:extract /scs:"Data Source=YOURSERVER;Initial Catalog=YOURDB;Integrated Security=true" /tf:C:\temp\yourdb.dacpac
C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin\SqlPackage.exe /a:publish /tcs:"Data Source=YOURSERVER;Initial Catalog=YOUROTHERDB;Integrated Security=true" /sf:C:\temp\yourdb.dacpac
Alternately, you can use DacFX programmatically using the Microsoft.SqlServer.Dac API, like so:
using Microsoft.SqlServer.Dac;
class Program
{
    static void Main(string[] args)
    {
        DacServices ds = new DacServices("Data Source=YOURSERVER;Initial Catalog=YOURDB;Integrated Security=true");
        ds.Extract(@"C:\temp\yourdb.dacpac", "YOURDB", "AppName", new System.Version());
        using (DacPackage dp = DacPackage.Load(@"C:\temp\yourdb.dacpac"))
        {
            ds.Deploy(dp, "YOUROTHERDB");
        }
    }
}


Q:

Inserting/updating huge amount of rows into SQL Server with C#

I have to parse a big XML file and import (insert/update) its data into various tables with foreign key constraints.
So my first thought was: I create a list of SQL insert/update statements and execute them all at once by using SqlCommand.ExecuteNonQuery().
Another method I found was shown by AMissico: Method
where I would execute the sql commands one by one. No one complained, so I think its also a viable practice.
Then I found out about SqlBulkCopy, but it seems that I would have to create a DataTable with the data I want to upload. So, SqlBulkCopy for every table. For this I could create a DataSet.
I think every option supports SqlTransaction. It's approximately 100 - 20000 records per table.
Which option would you prefer and why?

A:

You say that the XML is already in the database. First, decide whether you want to process it in C# or in T-SQL.

C#: You'll have to send all data back and forth once, but C# is a far better language for complex logic. Depending on what you do it can be orders of magnitude faster.
T-SQL: No need to copy data to the client but you have to live with the capabilities and perf profile of T-SQL.

Depending on your case one might be far faster than the other (not clear which one).
If you want to compute in C#, use a single streaming SELECT to read the data and a single SqlBulkCopy to write it. If your writes are not insert-only, write to a temp table and execute as few DML statements as possible to update the target table(s) (maybe a single MERGE).
If you want to stay in T-SQL minimize the number of statements executed. Use set-based logic.
All of this is simplified/shortened. I left out many considerations because they would be too long for a Stack Overflow answer. Be aware that the best strategy depends on many factors. You can ask follow-up questions in the comments.


Q:

How can I duplicate this JS variable and change the text used?

I have the following piece of JS which helps build a basic news page with a filter from a mySQL database. It created the heading, main copy and date created, I also need to add a "read more" link at the bottom for each news item that is created, the link will be the same as the link in the heading, but will need to say "read more" instead of using the heading.
Updated - working:
var base_href = '/go/media~';
 function makeTable(data) {

    var tbl_body = "";
    $.each(data, function (index, row) {
            var tbl_row = "";
            $.each(row, function (k, v) {
                    if(k == 'heading' && 'id' in row) {
                            v = '
' + v + '
';
                    }
                    tbl_row += "

"
                            + v + "

";

            });
            tbl_footer = 'read more';
            tbl_body += "
" + tbl_row + tbl_footer + "
";

    });
    return tbl_body;
}

A:

Could you not just create a tbl-footer. Something on the lines of this
tbl_footer += "read more";
...
tbl_body += "
" + tbl_row + "
" + tbl_footer + "
";

You have the data come back from your SQL database, the data that is return't most hold something that is related to where the article is on your web server.
My code is just a shot at what you may have inside of data, but that should help you out.
Update
tbl_footer = "read more";
tbl_body = "
" + tbl_row + "
 " + tbl_footer + "
";

simple jsFiddle : https://jsfiddle.net/qeLkq0rb/ this code will not work for you because I have updated some values to be hard coded, it is just showing you how to get your code working :)


Q:

How can I make new PDF from PDF Form file

I'd like to make a registration confirmation. My idea is filling PDF form, making new non-fillable PDF from old file and send to client by mail. I can send mail but I don't know how make new (non-fillable) pdf file.
Thank you for response

A:

maybe mPDF github mPDF or website


Q:

Ignore characters with regex in cucumber step definition

I'm trying to capture the digits inside a value using regex whilst ignoring the characters.
Feature Step: Then the '1st' 'elementName' repeating group is displayed on the 'webPage' page
I want to take the '1' from the '1st' value and ignore the characters left in the string. As I have no use for the characters in what I'm trying to achieve.
Current Step Def:
Then(/the 'areaINeedHelp' '([^"]*)' repeating group is displayed on the '([^"]*)' page

A:

You need a back reference that captures the number, but omits the number suffix:
Then(/the '(\d+).{2}' '([^']*)' repeating group is displayed on the '([^']*)' page/

Also change [^"]* to [^']* in the other two back references, since you are using single quotes around the step arguments instead of double quotes.


Q:

"No Top file or external nodes data matches found" setting up gitfs with SaltStack

I've setup git on an nfs server. The salt master auto-mounts the folder containing the git repository on boot. I have copied .sls files, templates and scripts to the git directory and added them to git.
I have added the following to the master config file, according to the guide here:
fileserver_backend:
  - git

gitfs_remotes:
  - file:///mnt/git-repo

I am in doubt about what to set file_roots to, but have tried both
- /srv/salt

and
- /mnt/git-repo

with same result: "No Top file or external nodes data matches found"
SaltStack version is 0.17.4, OS is SLES 11.2.
Does anyone know where I have gone wrong?

A:

Cloning the repository gave the following message "Warning: You appear to have cloned an empty repository". (thanks @Jason Zhu) It did this because although the files were added to the repository, they were not committed.
To solve the problem I:

removed file_roots from the master config file, since it is not needed when you use gitfs (thanks @basepi)
restarted the salt-master, to enforce changes to master config file (thanks @Utah_Dave)
committed the added files to the repository


Q:

Selecting based on string in a list C# LINQ

So I have a class named event which contains a List ListofInvites, It has email addresses of different user(another class which has a emailid property), now I want to select all the  events based on whether the listofinvites string contains that specific email
I have tried this but i'm getting an error
var userEmailID = this.User.Identity.GetUserName();

var events = this.dataBase.Events
       .OrderBy(e => e.DateAndTime)
       .Where(e => e.listOfInvites.Contains(userEmailID))
       .Select(EventViewModel.ViewModel);

Yeah sorry  I was in a hurry last night when i posted this
So I have this event class
public class Event
{
    public Event()
    {
        this.IsPublic = true;
        this.DateAndTime = DateTime.Now;
    }
    [Key]
    public int EventID { get; set; }

    [Required]
    [MaxLength(200)]
    public string Title { get; set; }

    [Required]
    public DateTime DateAndTime { get; set; }

    public string AuthorId { get; set; }
    public int Duration { get; set; }
    public string Description { get; set; }
    public string OtherDetails { get; set; }
    [MaxLength(200)]
    public string Location { get; set; }
    public bool IsPublic { get; set; }
    public IEnumerable<string> listOfInvites { get; set; }

    public string  InviteList { get; set; }
}
}

the error i'm getting is
System.NotSupportedException: 'The specified type member 'listOfInvites' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.'

A:

In the Event entity, you are declaring a IEnumerable<string> property (listOfInvites) while list of primitive types is not supported in Entity Framework and since this property is not mapped to a database column you cannot use it in a where expression.
You need to create another entity (therefore table) for ListOfInvites with a foreign key to the Event entity.


Q:

Thermodynamics of spontaneous protein folding: role of enthalpy changes

I'm trying to get clear why protein folding occurs spontaneously.
$$\ce\Delta G=\Delta H-T\Delta S$$
According to thermodynamics the ΔG should be negative for a process to occur spontaneously.
When a protein folds the ΔS (Entropy) is decreasing, because the protein gets more ordered. However I think the forming of the bonds (disulfide and other weak interactions) counterbalance this unfavourable rising entropy by forming an enthalpy (ΔH) which thus would result in a negative ΔG.
However I saw some other explanation online which didn't apply the Gibbs free energy formula to the protein but instead to the water. Because the water is more ordered when the protein is unfolded it would be favourable according to the second law of thermodynamics to fold the protein because after folding the water molecules can move more freely --> higher entropy -->negative ΔG --> spontaneous folding.
So my question is which of these two (or maybe both) are the cause of the spontaneous folding of proteins?

A:

Summary

The first explanation is commonly encountered.
The second explanation cannot be correct, as it stands, as it ignores the free energy change in the protein.
A modification of the second explanation (perhaps what was intended) is that it is necessary to consider the protein folding and change in the water as being coupled, in which case the overall free energy change — the sum of the two considered separately — is the determinant of protein folding. The assertion would then be that a negative free-energy change in the water system is the deciding factor. This view has been persuasively advocated on the basis of experimental measurements.

Free energy change in individual transformations
It is standard practice in biochemistry to consider the Gibbs Free Energy of transformation of the sort A → B in isolation in determining whether it will proceed spontaneously. A chemical reaction for which ΔG is negative may generate heat (i.e. have a negative enthalpy change (ΔH) ) which affects its aqueous surroundings, but it seems justified to consider the reaction in isolation as there is no sense that the change in the vibration of the water molecules is driving or coupled to the reaction.
This approach has been applied to the structural change of protein folding with the conclusion (consistent with the first explanation) that the change in enthalpy (ΔH) is sufficient to produce a negative ΔG and hence drive protein folding (Citation 1, below).
Free energy change in coupled transformations
Many biochemical changes involve transformations which individually have a positive free energy change, but are made possible by coupling to another reaction with negative free energy change, of greater magnitude:

A → B , ΔG1 = +x
C → D , ΔG2 = –y

If y>x and these two reactions are coupled (generally through a complex reaction path on an enzyme) , then we have:

A + C → B + D , ΔGoverall = –ve

See also Berg et al.
Although one can reject the second explanation in the question as it stands because it ignores the free energy change in the protein folding, perhaps it was intended to mean that the folding of the protein (A → B) should be considered as coupled to the change in the environment of the water (C → D), and that the negative ΔG for the aqueous environment made a greater contribution to the overall ΔG than that for the protein folding.
Is it valid to consider these two systems as coupled? In the original version of my answer I argued against this point of view, but am no longer convinced by my own arguments. The water environment is clearly essential for the hydrophobic effect — the burying of the hydrophobic residues in the centre of the protein away from the water. This is evident if one considers the same protein in a hydrophobic environment such as a cell membrane — it would not fold. In membrane proteins it is hydrophobic residues that are exposed to the lipid bilayer and it is their interiors that sometimes have hydrophilic channels.
So in this coupled system, what is the determinant of the negative free energy change? Minikel (Citation 2, below) asserts that there is no net enthalpy change for the protein folding, and it is the entropy effect on the ΔG for the aqueous environment that drives the folding. He indicates that this view is supported by differential scanning colorimetry and, although he doesn’t cite references, there is a recent (if rather complex) review of this topic by Christopher M. Johnson.
Citation 1: Assertion of role of ΔH of protein
The following explanation, taken from Essential Biochemistry, treats the protein folding in isolation and asserts that change in enthalpy is sufficient to produce a negative free energy change:

The folding of a protein also provides an example of the "ΔH" and "–TΔS" terms competing with one another to determine the ΔG of the folding process. As described above, the change in entropy of the protein as it folds is negative, so the "–TΔS" term is positive. However, in addition to entropic effects there are enthalpic contributions to protein folding. These include hydrogen bonding, ionic salt bridges, and Van der Waals forces. An input of thermal (heat) energy is required to disrupt these forces, and conversely when these interactions form during protein folding they release heat (the ΔH is negative). When all of these entropic and enthalpic contributions are weighed, the enthalpy term wins out over the entropy term. Therefore the free energy of protein folding is negative, and protein folding is a spontaneous process.

Citation 2: Rebuttal of role of ΔH of protein and assertion of role of water
The following explanation, taken from on-line lecture notes of  of Eric V. Minikel of Harvard University, rebutting the point of view above:

An incorrect and simplistic view of protein folding is as follows. An unfolded protein has high configurational entropy but also high enthalpy because it has few stabilizing interactions. A folded protein has far less entropy, but also far less enthalpy. There is a tradeoff between H and S here. Note that because ΔG = ΔH - TΔS, increased temperature weights the S term more heavily, meaning that higher temperature favors unfolding.
That entire explanation only considers the energy of the protein and
  not that of the solvent. In fact, hydrophobic domains of a protein
  constrain the possible configurations of surrounding water (see
  explanation above), and so their burial upon folding increases the
  water’s entropy. Moreover, it turns out that the hydrogen bonding of
  polar residues and the backbone is satisfied both in an unfolded state
  (by water) and in a folded state (by each other). Therefore enthalpy
  is “zero sum,” and protein folding is driven almost entirely by
  entropy.


Q:

how to make a div transparent without affecting the child in CSS 3?

how to make a div transparent without affecting the child in CSS 3
here's my HTML code:

    SEARCH

and here's the CSS:-
#header{
   background-color:#000;
   width:1349px;
   height:60px;
   position:fixed;
   z-index:2;
   opacity:0.7;
   }
#icon{
   float:left;
   padding:10px;
   }
li{
   display:inline;
  }
#header img{
   width:35px;
   height:35px;
  }
#search{
   float:right;
   color:#e5e5e5;
   padding:20px;
   font-size:20px;
  }

so, I want to make the #header div tranparent and fixed without affecting the #icon and #search div.

A:

Instead of using opacity, use rgba() like background: rgba(0,0,0,.7) where a stands for alpha/opacity. So change the below block of code like
#header{
   background-color: rgba(0,0,0,.7); /* 0.7 Opacity for black */
   width:1349px;
   height:60px;
   position:fixed;
   z-index:2;
}


Q:

Where can I find non-rectified stereo satellite imagery?

I'm looking for free (as in beer and as in commercial-use-friendly freedom) sources of stereo satellite imagery. I assume that such imagery should not be rectified since that would remove the benefits of having a stereo image pair, i.e. the geometry of the resulting images would be nearly identical.
So far I found a usable IKONOS dataset from the May 2008 China earthquake from the University of Maryland's Global Land Cover Facility (GLCF).
Do you know of any other stereo free satellite image sources besides GLCF?

A:

These probably aren't exactly the droids you're looking for, but the ASTER DEM is constructed using stereographic correlation.  Hirano et al describe the process for creating the DEM using stereo pairs.
The only problem with ASTER is that its stereographic capabilities come from specific off-nadir tasked data collection.  So unless you want to shell out big bucks, you're going to have to make do with whatever stereo pairs have already been collected.
The availability of ASTER data has also changed over time, I think because its a joint USA/Japan sensor.  According to this page, you can get any L1B ASTER data from over the USA for free via the LPDAAC, but L1A and non-USA scenes are only available to certified NASA users through WIST.
I hope that helps!

A:

[Rewritten]
For satellite imagery, the USGS Earth Resources Observation and Science Center is a good place to start looking. From that page, there are two special web portals you can use to search for satellite image tiles---Glovis and EarthExplorer. While they're similar, I tend to use Glovis for ASTER and EarthExplorer for Landsat. But I believe they are nearly equivalent.
No matter how you approach your search, the key to achieving stereo parallax is overlapping exposures from different vantage points. So focus on identifying nearly cloud-free tiles with overlap in your area of interest.
In this Glovis screenshot I'm searching ASTER imagery. You can distinguish areas of overlap between the tiles, and it stands to reason that you could achieve stereo parallax from either 1) sequential tiles along any flightline, 2) neighbor tiles from a parallel flightline, or 3) exposures for the same position from different times. However I'm not 100% sure about that third suggestion. While exposures from different times should create stereo parallax (the satellite doesn't pass through the exact same position), I suspect it may be impossible to perceive.

Similarly, in this EarthExplorer screenshot, I'm searching Landsat imagery. The same principals apply; although, because the swaths are wider, it may be difficult to find overlapping tiles for an exact area of interest.


Q:

set of left cosets is group with product operation iff $H$ is normal

If $H$ is a subgroup of $G$ prove that the set $G/H$ of left cosets is a group with product $(aH)(bH) = (abH)$ if and only if $H$ is a normal subgroup of $G$.
attempt: Suppose coset multiplication is well defined.
Let $g\in G$, and $h\in H$. THen $1*H = hH$. Then we have $g^{-1}H = (1*H)(g^{-1}H) = (hH)(g^{-1}H) = (hg^{-1}H)$ so that $hg^{-1} \in g^{-1}H$ and $ghg^{-1} \in H$.
Conversely,suppose H is a normal subgroup of G. Then
we wills how the set $G/H$ of left cosets is  a group with product $(aH)(bH) = (abH)$.
1)associative: (aH * bH)cH = (ab)H * cH = (ab)cH
and  aH(bH * cH) = aH* (bc)H = a(bc)H.
2)Identity: 1H*gH = gH = gH * 1H for all $g\in G$
thus, $H = 1*H$ is the identity for coset multiplication.
3) inverse: $(gH)(g^{-1}H) = (1H) = g^{-1}*gH = 1*H$ for all $g \in G$
thus $(gH)^{-1} = g^{-1}H$
Can someone please verify this is correct? Any feedback or better way of approaching this would really be appreciated it.
Thank you.

A:

Suppose $H$ is a normal subgroup of $G$.  Then $ghg^{-1} \in H$ for all $h \in H$.
Choosing coset representatives, $h_1$, $h_2$, using the normality of $H$ and the closure of $H$ under multiplication ($h_ih_j \in H$), we can write
$$(ah_1)(bh_2) = ab(b^{-1}h_1b)h_2 = ab(h_3h_2) =ab(h_4).$$
This shows that $(aH)(bH) = (ab)H$.  With a well-defined operation on the cosets you can proceed as above to confirm associativity, identity, and inverses.


Q:

Python Mechanize set cookie

This below code works.
cookiejar =cookielib.LWPCookieJar()
br.set_cookiejar(cookiejar)

c0 = cookielib.Cookie(version=0, name='_mobile_sess', value='BAh7ByIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7ADoQX2NzcmZfdG9rZW4iLTY4YWYxODc5ZmVlNTRhMDM4YzUwN2VjMmNiMWJkMjZlMTIxNDViNWM%3D--a18dca22d18735ebb9c4f91f595bae999e138f5e', port=None, port_specified=False, domain='.twitter.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=True, expires=1531884528, discard=False, comment=None, comment_url=None, rest={'HTTPOnly': None}, rfc2109=False)

cookiejar.set_cookie(c0)

However, due to some reason, I have to to store c0 as a string.
So actually, c0 is a unicode string
c0 = u"cookielib.Cookie(version=0, name='_mobile_sess', value='BAh7ByIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7ADoQX2NzcmZfdG9rZW4iLTY4YWYxODc5ZmVlNTRhMDM4YzUwN2VjMmNiMWJkMjZlMTIxNDViNWM%3D--a18dca22d18735ebb9c4f91f595bae999e138f5e', port=None, port_specified=False, domain='.twitter.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=True, expires=1531884528, discard=False, comment=None, comment_url=None, rest={'HTTPOnly': None}, rfc2109=False)"

so that
cookiejar.set_cookie(c0)

return error
if cookie.domain not in c: c[cookie.domain] = {}

AttributeError: 'Text' object has no attribute 'domain'

How do I fix this problem? How do I convert unicode string c0 to "something" that cookiejar.set_cookie(c0) can accept?

A:

You can use the exec statement to execute the string stored in c0
exec "c0 = " + c0

For example:
>>> exec u"print('hello')"
hello

See: How do I execute a string containing Python code in Python?


Q:

How to align text differently inside a single inline element with CSS?

This should be interesting. Here's what I'm trying to do with CSS:

The words "An Example Alignment" should be in a single
 element.
The word "Alignment" should be on the second line (easy with a
 tag).
The word "An" should be smaller than the other words (easy with a  tag).

So we have:

An Example
Alignment

But here's the catch:

I would also like to align the first letters of the 2nd and 3rd words with each other vertically, and that's where I run into problems.

Here's what it should look like: http://jsfiddle.net/Baumr/H2Pzr/
But that's an ugly solution as there are two
 elements.
Any ideas of how to do this with CSS by keeping the HTML the same? Very curious to hear. Thank you in advance.
P.S. I could also put "An" into a separate , but I would prefer to keep everything in a single
.)

A:

I would use two span classes in the same H1 tag:

    An Example
    Alignment

Then update your CSS accordingly:
h1 {
    font-size: 30px;
}

span.small-text {
    font-size: 20px;
}

.line-two{
    display:block;
    margin-left: 31px;
}

You don't even need the
 since you can just display the second span as display:block;
Updated fiddle here: http://jsfiddle.net/H2Pzr/6/


Q:

Should web farms be concerned with TLS handshake overhead

I have a web farm where the web servers are responsible for negotiating the secure connections. Does anyone else with a web farm go out of their way to reduce TLS handshake overhead by ensuring that TLS resume handshakes are supported?  And if so, why?
We are switching from a sticky session to a more balanced load balancing algorithm.  We are concerned that we will lose the benefit of the TLS resume feature.
Assuming every connection from a client goes to a different webserver, we are assuming a full TLS handshake will be required.  I don't know the overhead, but if we are looking at 20ms round trip it would appear that the full handshake will take 3x or so as long to complete.

A:

I don't know how large the OPs web server farm is, but for most smaller / midsized installations I find it cleanest and simplest to handle all TLS/SSL on the load balancer. So you have:
Internet (HTTPS req) -> L7 HTTPS proxy LB -> plain HTTP on LAN -> webserver

o3 Magazine had a good writeup on how relatively easy this is with nginx, and what performance numbers you can expect. f5 posted a commentary on the benefits of using a commercial appliance for SSL acceleration instead of a DIY solution (IMHO somewhat biased).
Note that you'll need your web servers to inspect X-Forwarded-For and X-FORWARDED_PROTO headers and handle the connection correctly.
Most installations should get by fine with a single HTTP & HTTPS load balancer, or a pair of load balancers in active/passive configuration for HA. In this setup handshake resume is a non-issue, as there is only one SSL/TLS endpoint (which typically will automatically support handshake resume).


Q:

Decode URL Safe Base64 in JavaScript (browser side)

I am using Gmail's API to get emails from my account. The body of the message is delivered in a "URL safe base64" format. What is the best way to decode this for use? I have found some nodejs solutions, but no client side ones. window.atob does not work since it is URL safe.
Thanks for any help.

A:

For posterity,
atob(data.replace(/_/g, '/').replace(/-/g, '+'))

As stated by the spec https://tools.ietf.org/html/rfc4648#section-5 however because this uses atob() it does not support unicode characters and thus requires a polyfill.

A:

Finally found it. This does URL Safe decoding
https://github.com/dankogai/js-base64


Q:

Questions about acceptance rule of Metropolis algorithm

I have a question concerning about one step in the Metropolis algorithm. The algorithm proceeds as following,

Generate a proposed new sample value  from the jumping distribution $Q(x'|x_t)$
Calculate the acceptance ratio $a = \frac{P(x')}{P(x_t)}$
If $a\geq 1$, accept $x'$ by setting $x_{t+1}= x'$
Else, accept $x'$ with probability $a$. That is, pick a uniformly distributed random number $r$ between 0 and 1, and if $r\leq a$ set $x_{t+1}=x'$, else set $x_{t+1} = x_t$

I feel unclear about step 4, in step 4 if we have $a<1$, which means $P(x_t)>P(x')$, $x'$ is further away from the large mass of the density than $x_t$. However, we are not dumping $x'$ directly, we leave it to a 'gamble' to decide its go or stay. This gamble is the uniform distribution, a random draw from uniform distribution then compare it with $a$. I do not understand what's happening here. Why won't we just dump $x'$, why we have to give it a chance to 'nature'?

A:

The scheme you propose is strictly ascending the probability gradient. Think what would happen: you would end up at $x$ such that $P(x)$ is maximal and you would stay there for ever. In the end, the sample you generate would consist mostly of $x$, whatever the size of the sample, so the distribution of that sample would not be close to $P$.
Also bear in mind that the probability to simulate could be bimodal. In that case, it is beneficial to accept an $x$ with low probability to be able to go from one mode to the other.
Actually, it is OK to accept an $x$ with low $P(x)$, as long as the overall acceptance ratio is not bigger than $P(x)$. That this is the case with the Metropolis-Hastings is a little hard to prove though.


Q:

Which IOS build setting would reference to the Derived Data Directory

I have the following directory:
~/Library/Developer/Xcode/DerivedData/xxxxx-fybqdtdocnlinnazwwmhclbrodjm/Build/Products/Debug-iphonesimulator/xxxxxx.app
And I need to use something like:
"THIS_DERIVEDDATA_DIR"/xxxxxx.app
Where THIS_DERIVEDDATA_DIR is the build setting I am looking for. Any help is really appreciated.
thx

A:

What you are looking for is not build setting but Xcode preferences. You can set your own or locate to your derived data fold in Xcode -> Preferences -> locations ..


Q:

How to show that the delay margin is zero if the open loop gain $|L(i\infty)| \geq 1$?

How to show that the delay margin is zero if the open loop gain $|L(i\infty)| \geq 1$ ?
Where $L(s)$ is the open loop transfer function and the delay margin is the amount of time delay for the system to be on the verge of instability.
Hint: Using the Nyquist Contour.

A:

Nyquist's stability criterion requires that the number of times $L(i\omega)$ encircles $(-1|0)$ equals the number of poles in the open right half plane.
For a non-vanishing delay $T_d \neq 0$, $L(i\omega)e^{-i\omega T_d}$ encircles $(-1|0)$ infinitely often since $\lim\limits_{\omega \rightarrow \infty}|L(i\omega)| \ge 1$, by proposition. Given a finite number of poles we fail to fulfill the stability criterion.


Q:

Seperate values based on property value and show with javascript

I have an array that looks like this:
var array = [[
    { "loc": {} },
    { "distance": 6.4 },
    { "zip1": "06120" },
    { "zip2": "06095" },
    { "group": 1 },
    { "weight": 1119 }
], [
    { "loc": {} },
    { "distance": 6.41 },
    { "zip1": "06095" },
    { "zip2": "06120" },
    { "group": 2 },
    { "weight": 41976 }
], [
    { "loc": {} },
    { "distance": 6.41 },
    { "zip1": "06095" },
    { "zip2": "06120" },
    { "group": 1 },
    { "weight": 41976 }
]];

Now I want to take the array values based on the property values for show in HTML.
Expected output is split into array with "group" property. I also need to store in HTML with based on group, as shown in the example below:
group 1:
  all zip1's under group 1
group 2:
  all zip1's under group 2

I tried using a loop but I didn't manage to get the right answer:
for (var k = 0; k < array.length; k++) {
    var array1 = array[k];
    if (flag[array1[2]["zip1"]]) continue;
    flag[array1[2]["zip1"]] = true;
    output2.push(array1);
}

So help me to find split the array show in HTML with group wise

A:

Using reduce, you can create an object with each group value as key and an array of zip1 as values like this:
Then loop through the Object.entries, to create the HTML:

const array = [[{"loc":{}},{"distance":6.4},{"zip1":"06120"},{"zip2":"06095"},{"group":1},{"weight":1119}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":2},{"weight":41976}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":1},{"weight":41976}]];

const merged = array.reduce((r, a) =>{
  const { group } = a.find(n => n.group)
  const { zip1 } = a.find(n => n.zip1)
  r[group] = r[group] || []
  r[group].push(zip1)
  return r;
},{})

const output = document.getElementById('output');

Object.entries(merged).forEach(([group, zips]) => {
  const h1 = document.createElement('h1');
  h1.innerHTML = "group " + group

  const span = document.createElement('span');
  span.innerHTML = `Zip1 - ${zips} (in group - ${group})`;

  output.appendChild(h1)
  output.appendChild(span)
})


Q:

SQL omit columns with all same value

Is there a way to write a SQL query to omit columns that have all of the same values? For example,
row    A    B
1      9    0
2      7    0
3      5    0
4      2    0

I'd like to return just
row    A
1      9
2      7
3      5
4      2

A:

Although it is possible to use SQL to find if all rows in a column have identical values, there is no way to make a fixed SQL statement not return a column based on the content of the query.
Here is how to find out if all items in a column have identical values:
SELECT COUNT(row)=COUNT(DISTINCT B) FROM my_table

You can run a preliminary query to see if a column needs to be displayed, and then form the query dynamically, including the column only when you need it.


Q:

Вывод массива в обратном порядке

function yearsBirthDayList() {
 var data = new Array();

 for(i = 1905; i < 1998; i++) {
  data.push([i, i]);
 }

 return data;
}

Массив выводится в порядке:
[[1905,1905]-[1997,1997]]

Как сделать чтобы он выводился в обратном порядке?
[[1997,1997]-[1905,1905]]

A:

Первое, что приходит на ум.
var source = [1, 2, 3],
    inverse;

inverse = source.reduce(function (carrier, element) {
    carrier.unshift(element);
    return carrier;
}, []);

// inverse = [3, 2, 1]

upd второе, что приходит на ум:
var source = [1, 2, 3];
source.reverse();

обратите внимание, что в этом случае исходный массив будет модифицирован (в то время как в первом примере создается второй массив). Чтобы создать новый, можно воспользоваться slice с первого же элемента:
var source = [1, 2, 3],
    inverse;

inverse = source.slice(0).reverse();


Q:

How can I finished one view's constrains before other view generate

Now, I am going to generate a titleview that its height is variable for the tableHeaderView.so i need to confirm the titleview's hegiht before the tableview generate
//titleView
JMProductTitleView *titleView = [[JMProductTitleView alloc]initWithFrame:CGRectMake(0, 0, JMDeviceWidth, 300)];
titleView.delegate = self;
JMProductDetailModel *model = [JMPorductDetailTool createProductDetailModel];
titleView.model = model;
_titleView = titleView;

//
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, JMDeviceWidth, JMDeviceHeight) style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
tableView.tableHeaderView = titleView;
[self.view addSubview:tableView];
_tableView = tableView;

A:

You can try using [self.view layoutIfNeeded]. It will force the view to layout all the constraints.


Q:

integration question very short help me?>

I am not sure if i should solve this with integration by partial fracions
So,Im in the middle of solving an exercise but I got here $-u^3/(2+2u^2) $..
how to integrate this by partial fraction?
how do I solve its integral in the shortest way? or is INTEGRATION BY PARTIAL FRACTIONS the only way?
by the way,can you show me a way to solve this type of integrals very fast?

A:

HINT: $$\frac{u^3}{1+u^2}=u-\frac{u}{1+u^2}$$
No partial fractions are needed, and you should discover this right away if you attempt to use them, since you must first divide out to get a fraction whose numerator has lower degree than its denominator.


Q:

best way to add unpredictable time strings in python3?

a project I'm building takes different time lengths from album tracklists in as strings, and I want to add them up cumulatively. The inputs can vary in unpredictability, such as the following list of input time strings:
inputs = ['0:32', '3:19', '11:22']

So I would want to add all these times up like so:
0:32 + 3:19 + 11:22 = = 15:13
I need to make sure the resulting time is a valid timestamp, so incrementing the second/minute/hours realistically is necessary
I figured the best way to do this would be to convert each string time to a python datetime object, but I'm having trouble thinking of how to do this realistically, since all my knowledge and examples I can find of converting a string to a datetime use hard-coded datetime templates, such as:
datetime_str = '09/19/18 13:55:26'
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')

I need to identify multiple different possible string-times, such as :
0:32  = %m:%S
23:19 = %M:%S
01:22:23 = %H:%M:%S
01:2:23 = %H:%m:%S

is there a way to automate this process of adding up multiple different timestamps? My thought process was take the time-string, convert to datetime, convert that datetimeObject to seconds, add them up, then convert it back to dateTime HH:MM:SS format. But I'm getting hung up on how many different possible time inputs I can receive. Any advice is much appreciated as to how I can solve this problem

A:

If you know that they all follow this format, it should be doable to parse manually:
def add_times(inputs):
    total_secs=0
    for input in inputs:
        chunks = map(int, reversed(input.split(':')))
        total_secs += sum(chunk*60**i for i,chunk in enumerate(chunks))

    return "{}:{}:{}".format(total_secs//3600, (total_secs%3600)//60, total_secs%60)

print(add_times( ['0:32', '3:19', '11:22']))

gives me 0:15:13.


Q:

Angular (4): ngFor in batches?

I have an array of objects called applicationArray with 12 'application' elements. I need to show these application by using bootstrap div.row and div.col-sm-4 in batches of 3 application per row.
Something like this:

      <application></application>

      <application></application>

      <application></application>

Is it somehow possible to use ngFor and tell it to divide the array into batches and display it dynamically?
Thank you!

A:

You could have a function that splits it into batches in the component, then render each batch in the template:
Template:

           {{application.number}}

Component:
 batches = [];

   ngOnInit(){
     this.splitIntoBatchesOfThree(this.applicationArray);
   }

   constructor() {}

   splitIntoBatchesOfThree(applicationArray)
   {
    while(applicationArray.length) {
        this.batches.push(applicationArray.splice(0,3));
    }
  }

Here's a plunker: https://plnkr.co/edit/prkYEaDc8rpJI1hR8tqE?p=preview


Q:

how to generate a graph using 'random' and 'networkX' libraries?

I have an assignment where I have to create a graph using the random library with for loops and also compute the probability whether there is an edge between two vertices. The body of the code is as given below.
How can I construct an graph?
# generate edges in G_rand at random:
for i in range(0,k) :
    for j in range(0,i) :
        # Add an edge between vertices i and j, with probability edge_probab
        # ...

A:

Here is a possible solution:
import random
import networkx as nx

edge_probability = 0.3
n_nodes = 10

G = nx.DiGraph()

G.add_nodes_from(range(n_nodes))

for u in G.nodes:
    for v in G.nodes:
        if random.random() < edge_probability:
            G.add_edge(u, v)


Q:

applicationwillfinishaunching handler not working applescript xcode

My on applicationWillFinishLaunching_(aNotification) handler isn't working. It works with my "xib" IB, but it doesn't work with my ".storyboard" IB. Where in the IB should I look? I have searched quite a bit looking for anything that says "applicationWillFinnishLaunching" but no luck. The handler only works if my main storyboard is an ".xib" file but when I make it a ".storyboard" it doesn't work.

A:

Create a new project and check the connection you see in the image below.
Then try to find if the same connection is broken in your project and recreate it.


Q:

Declare array with constant (not literal) as dimension specifier

The following code works, but to easily change the size of the array and the index range of the loops, can the variable max be used to specify the dimensions of the array?
fn main() {
    let max: i64 = 3;

    let mut arr2: [[f64; 3]; 3] = [[0.0; 3]; 3]; //replace 3 by max?
    // let mut arr2: [[f64; max]; max] = [[0.0; max]; max]; //does not work

    let pi: f64 = 3.1415926535;
    let max2 = max as usize;

    for ii in 0..max2 {
        for jj in 0..max2 {
            let i = ii as f64;
            let j = jj as f64;
            arr2[ii][jj] = ((i + j) * pi * 41.0).sqrt().sin();
            println!("arr2[{}][{}] is {}", ii, jj, arr2[ii][jj]);
        }
    }
}

Using the commented out line for the declaration I get this error:
error[E0513]: no type for local variable 10
 --> <anon>:6:32
  |
6 |     let mut arr2: [[f64; max]; max] = [[0.0; max]; max]; //does not work
  |                                ^^^

A:

Arrays in Rust must be declared with a fixed size known at compile time.
If the size is indeed known at compile time, then define a constant instead of a variable:
const MAX: usize = 3;

If the size is not known at compile time, use a Vec instead.


Q:

Where does c++ store the size of fix sized array?

This problem is a follow up from Declaring array of int
Consider the following program:
#include <iostream>
#include <string>

int main()
{
  int x[10];
  std::cout << sizeof(x) << std::endl;
  int * y = new int [10];
  std::cout << sizeof(y) << std::endl;
  //delete [] y;
}

sizeof(x) prints 40 (total size), sizeof(y) prints 8 (pointer size)
It looks interesting, to me int x[10] is no different than y except it is located in the stack. Where does c++ actually stored the size of x? Does c++ get it from the stack? Or a fix sized array is treated as a struct with size internally?

A:

The size of an array doesn't need to be stored, the compiler itself knows how big it is because it's part of the type.
When you dynamically allocate an array as you did with y in your example, the size of the array does need to be stored somewhere so that delete[] can do the right thing. But this is an implementation detail that isn't accessible to the program.

A:

You have two different types:
int x[10];

This declares a type of int[10]. As you can see, the size of the array is part of the type.
int * y;

This is a pointer to an int. It will have size equivalent to the size of a pointer on your system. Your system appears to have 64 bit pointers (commonplace now).

Here's a little trick you can do in C++17:
template<class T>
std::enable_if_t<std::is_pointer_v<T>> foo(T ptr)
{
    std::cout << "Called foo for a pointer type" << std::endl;
}

template<class T, int N>
void foo(T (&arr)[N])
{
    std::cout << "Called foo for an array type of size " << N << std::endl;
}

We defined two functions named foo. The first one uses type traits to only enable itself for pointer types, and the second one is for array types (by reference).
We can call them from main:
int x[10];
int * y = nullptr;
foo(x);
foo(y);

And get output that looks like this:

Called foo for an array type of size 10
Called foo for a pointer type

Runnable code

Edit: Mark Ransom gave a good aside about the size of the array allocated for y, and I'll throw in a little piece, too. While it is indeed an implementation detail, what's common is that the implementation of the memory allocator (like malloc or new) under the hood will write this value to the start of the memory block that it allocates.
That way, when you call delete, you don't have to know how many bytes to delete; the deallocator (free or delete) can check the start of the memory block for how big it is. So an allocation for, say 1 byte, may actually allocate more than 1 byte. (Again, this is only one way it can be done)


Q:

How to add a sticky footer to this HTML template while preserving the layout?

Is it possible to add a sticky footer to this HTML template that works in IE compatibility mode and is cross browser compatible?
I tried adding the Ryan Fait sticky footer, but everything seems to break when I add it.
Can't use the sticky footer that uses 100% height on the parent container and then uses a negative top margin for the footer and pulls it back up into the viewport since that'll eliminate the ability to see the background color between the footer and the main content. Can't inject a backgournd colored spacing div in there either to suffice since the template uses rounded corners and that would seem to make it difficult.
I also tried this 'top border soak up sticky footer' similar to the Ryan Fait method, but I coudln't get that to work either.

A:

Solved. Basically, like you said I applied the Ryan Fait sticky footer and did the following:
-moved the footer outside of the wrapper and the header inside the wrapper.
-removed the padding from the body.
-removed the top margin, bottom border, box shadow, (and bottom rounded corners) from the footer.
-pulled the wrapper margin up an extra pixel (.063em) to account for the top border of the footer.
-added padding-bottom:10px; to the #innerwrap to get the div spacing I was looking for (like it says on the Ryan Fait page).
-made the width and margin of the footer match the wrappers.


Q:

Python's __loader__, what is it?

I've seen the term __loader__ floating around some Python files and I can't find any documentation on it aside from a few brief descriptions about it's purpose, but they still don't provide enough information for me to get a good understanding of it. All I know is that it has something to do with importing modules, other than that I'm completely at a loss. What does it do? When is it used? How can I use it if at all?

A:

What is __loader__?

__loader__ is an attribute that is set on an imported module by its loader.  Accessing it should return the loader object itself.
In Python versions before 3.3, __loader__ was not set by the built-in import machinery.   Instead, this attribute was only available on modules that were imported using a custom loader.
However, this functionality changed in Python 3.3 because of PEP 0302.  Now, __loader__ is available on every module that is imported:
>>> # Python 3.3 interpreter
>>> import os
>>> os.__loader__
<_frozen_importlib.SourceFileLoader object at 0x01F86370>
>>>

What is a loader?

A loader is an object that is returned by a finder. It uses its load_module() method to load a module into memory.  importlib.abc.Loader is an example of an abstract base class for a loader.

What is a finder?

A finder is an object that uses its find_module() method to try and find the loader for a module.  importlib.abc.Finder is an example of an abstract base class for a finder.  Note however that it is deprecated in favor of importlib.abc.MetaPathFinder and importlib.abc.PathEntryFinder.

How can I use it, if at all?

The main use of __loader__ is for introspection.  However, there are two other common uses:

__loader__ may be used to gather data on a specific module's loader.
In Python versions before 3.3, __loader__ could be used with hasattr to check whether or not a module was imported with the built-in import machinery:
>>> # Python 3.2 interpreter
>>> import os
>>> hasattr(os, '__loader__')
False
>>>

If hasattr(os, '__loader__') had returned True, it would mean that the os module was imported using a custom loader.  Since it did not, it means that the module was imported using the built-in import machinery.
Note: The above test will not work in Python 3.3+ because of the changes made by PEP 0302.