text:
Q: Story identification, meta-tags? I was wondering which SE site would be best to ask about hardly hearable (for me) quote from (probably) some movie, that I have encountered on some YT clip here.
Movies? Story-identification tag has 3 entries.
Sci-Fi? Story-identification reaching 5k, yet nothing audible indicates it is related to Sci-fi.
Perhaps Music?
Or perhaps we could use meta-tag(s) that filters particular SE site, but is common across multiple SE sites. Or maybe another SE site where additional points could be awarded for directing flow of questions into proper categories, sites? Or without points, just it could be voted inside which group/site/tags fit best.

A: The main problem seems to be, though, that you don't really seem to know where that quote is from at all. It could be a movie, it could be a song, it could be some interview, it could just be some arbitrary YouTube blabber.
This not only makes it hard to guess on which site to ask, it also makes it not a particulalry good question on the respective site you chose to ask it on, since for example Movies & TV doesn't accept story identification at all. Likewise, Music Fans currently rules identification questions completely off-topic.
So while that question might go borderline through on some site with a bit of luck, it does not really seem to be a particularly good fit for any of the SE sites in general.
You might find some success outside of SE, though.


text:
Q: How can I covert .tsv file to xlsx file using vbscript? I need to covert a .tsv file into .xlsx format. Is there a way to do that using vbscript? I tried to find that online but was not able to find what I actually need. I am very new to VBScript. It will be great if someone can help me with this. Thank you in advance.

A: In its simplest form this will work. DisplayAlerts suppresses the save prompts and Visible is only needed if you want to see it happen. This will create its own Excel instance, so it shouldn't interfere with any Excel instance currently open.
Option Explicit

Dim objExcel : set objExcel = CreateObject("Excel.Application")
objExcel.Application.DisplayAlerts = false
objExcel.Visible = true
objExcel.Workbooks.OpenText "c:\users\TEST\desktop\tab_delimited.tsv" ,,,1,,,,,,,True,"|"
objExcel.ActiveWorkbook.SaveAs "c:\users\TEST\desktop\tab_delimited.xlsx", 51
objExcel.ActiveWorkbook.Close
set objExcel = Nothing

redpajama_set_name: RedPajamaStackExchange


text:
Q: igraph initialisation with weights How can I initialise an igraph with weights?
This is what I have
cr = csv.reader(open("atlas.csv","rb"))

mapping = {}
for row in cr:
    if int(row[2]) == 1:
        continue

    source = int(row[0])
    target = int(row[1])

    if source in mapping:
        list = mapping[source]
        list.append(target)
    else:
        mapping[source] = [target]

print mapping

G = Graph(edges = [(v, a) for v in mapping.keys() for a in mapping[v]])
print G

I tried adding weight using edges = (v, a, w) but that doesn't work.

A: According to the documentation, you may use TupleList method:

If you have a weighted graph, you can
  use items where the third item contains the weight of the edge by
  setting edge_attrs to "weight" or ["weight"].

You may also set weights parameter to True:

weights - alternative way to specify that the graph is weighted. If
  you set weights to true and edge_attrs is not given, it will be
  assumed that edge_attrs is ["weight"] and igraph will parse the third
  element from each item into an edge weight. If you set weights to a
  string, it will be assumed that edge_attrs contains that string only,
  and igraph will store the edge weights in that attribute.


text:
Q: REGEX serach and replace HTTP RC's in logs I have a log file with HTTP and other return codes. The blank between the numeric return code and the text that describes the RC is causing me problems normalizing this data for parsing.
Here's a few examples of the data:
rc(200 OK)
rc(403 Unauthorized)
rc()
I want to retain both the numeric RC and the RC text and I want to change the blank to a dash(-). So given the data above, I want this:
rc(200-OK)
rc(403-Unauthorized)
rc()
I think this match pattern works: rc(\d{3}\s but I'm sick to death of sed complaining about everything I try :(
Can someone help please?

A: This seems to do the trick.  It works by capturing the groups on either side of the space you want to replace, then puts them back but with a dash instead.
$ sed -E 's/(rc\([0-9]+)(\s+?)([a-zA-Z0-9]+?\))/\1-\3/g' x.log
rc(200-OK) rc(403-Unauthorized) rc()
$

A: You could capture rc( followed by 3 digits [0-9]{3} in a capturing group followed by matching one or more times a whitespace character \s+.
Then replace with that capturing group followed by a -. Use global /g to replace all occurrences.
$ echo "rc(200 OK) rc(403 Unauthorized) rc()" | sed -E 's/(rc\([0-9]{3})\s+/\1-/g'
rc(200-OK) rc(403-Unauthorized) rc()

Match (rc\([0-9]{3})\s+
Replace \1-
Demo http://rextester.com/VQKA81573


text:
Q: Why do I need to use "to sing" in "I was expecting him to sing"? 1: I was expecting him to sing a song.
2: I was expecting him that he will sing a song.
Is there any rule that states to put ' to ' after 'expecting someone' for something?

A: Expect 'licenses' (permits) both sorts of clause you mention, but you have to follow the syntactic rules for each.

*

*In infinitival clauses the verb is expressed as a 'marked' infinitive—the infinitive form preceded by the marker to. The subject is expressed in object form if it is a pronoun. With expect it is omitted altogether if it is the same as the subject of the main clause.

I expect him to sing a song.
  I expect me  to sing a song.

*A 'content' clause has the same form as an ordinary declarative clause. The verb is expressed as a finite form; the subject is expressed in subject form if it is a pronoun, and it is not omitted. If the subordinator that is employed it precedes the entire clause, including the subject.

I expect (that) I will sing a song.
  I expect (that) he will sing a song.

Note that since a finite (tensed) verb is employed in this clause it must have the tense appropriate to the situation. Your example is a 'future-in-past' situation, where the singing is 'future' in relationship to the past-tense expectation, so you have to say:

I expected (that) he would sing a song.

A: Yeah, this one might be annoying for English learners. You have to use sentence 1, as the other one isn't grammatically correct. 'that he will' is in the future tense, and the first sentence is an infinitive so it works after 'expecting someone'. Thinking about it, there must be a rule that specifies that the infinitive must be used after 'expecting someone', every situation I can think of works like that.


text:
Q: ImageMagick - flatten of more png images I have more PNG images (let's say img1.png, img2_transparent.png, img3.png) and I want them flatten to one image.
Before I flatten them I set (I want second image was slightly transparent):
convert img2_transparent.png -alpha on -channel a -evaluate set 90%

Then I flatten them (order is img1.png, img2_transparent.png, img3.png):
convert *.png -flatten out.png

Result is ok, second "layer" has opacity 90%, BUT whole picture (thus all "three" layers) is "lightened". Colors are not so deep as I don't set alpha to img2_transparent.png.
How can I avoid this?
Thank you

A: If you want the images to show up in equal measure in the resulting image, the general formula is to set the opacity of each layer to
1/(1 + number of layers underneath)

where the base layer is at full opacity. The second image is then at opacity 1/2, the third image at opacity 1/3, the fourth image is at opacity 1/4.
convert base.png \
   \( layer2.png -channel A -fx '0.5'   \) \
   \( layer3.png -channel A -fx '0.333' \) \
   \( layer4.png -channel A -fx '0.25'  \) ....

There is a well explained tutorial on Cambridge in Colour website. Scroll down to AVERAGING IMAGES IN PHOTOSHOP USING LAYERS.


text:
Q: How can I get a function's name by its pointer in Lua? In Lua I've created a pretty printer for my tables/objects.  However, when a function is displayed, it's shown as a pointer.
I've been reading up on Lua Introspection but when I introspect the function with debug.getinfo() it won't return the function's name.  This seems to be due to a scoping issue but I'm not sure how to get around it.
What is the best way to get a function's name using its pointer?  (I understand functions are first class citizens in Lua and that they can be created anonymously, that's fine)

A: when you create the functions, register them in a table, using them as keys.
local tableNames = {}

function registerFunction(f, name)
  tableNames[f] = name
end

function getFunctionName(f)
  return tableNames[f]
end

...
function foo()
  ..
end
registerFunction(foo, "foo")
...

getFunctionName(foo) -- will return "foo"

A: For some reason, it seems to work only with number parameters (that is, active functions on the stack).
The script
function a() return debug.getinfo(1,'n') end
function prettyinfo(info)
    for k,v in pairs(info) do print(k,v) end
end
prettyinfo(a())

prints
name    a
namewhat    global

but if I change the last line to
prettyinfo(debug.getinfo(a, 'n'))

it gives me only an empty string:
namewhat


text:
Q: \fbox inside an imported pdf I have imported a pdf using \includepdf and I want insert an fbox into the pdf (the pdf contains standard content that stays at the bottom).
I have used this code:
\includepdf[pages={1},pagecommand={\begin{tikzpicture}[remember picture, overlay]
  \node at (1, 1) {
    \thispagestyle{empty}
    \fbox{
      \begin{minipage}[t]{\textwidth - 2\fboxsep}
        text in box
      \end{minipage}
    }
  };
\end{tikzpicture}}]{ficha.pdf}

It works but the \fbox frame is not visible. How can I obtain the desired result?

A: \includepdf sets locally the rule width \fboxrule and \fboxsep to zero, so you must reset them:
\documentclass[]{article}
 \usepackage{tikz}
 \usepackage{pdfpages}

 \begin{document}
 \includepdf[
  pages={1},
  pagecommand={
   \thispagestyle{empty}
   \begin{tikzpicture}[remember picture, overlay]
    \node at (1, 1) {
     \fboxrule=0.4pt \fboxsep=3pt
     \fbox{%
       \begin{minipage}[t]{\textwidth - 2\fboxsep}
         text in box
       \end{minipage}
        }
      };
\end{tikzpicture}}]{example-image-A}

 \end{document}

You can also use \node[draw] to draw a frame instead of the fbox.

A: Alternatively, you can use the node's own boundary drawing and \parbox capabilities.
BTW, you should use {\dimexpr \textwidth -2\fboxsep}.  Then again, with overlay exceeding the boundaries is no big deal.
\documentclass{article}
\usepackage{pdfpages}
\usepackage{tikzpagenodes}

\begin{document}
\includepdf[pages={1},pagecommand={\thispagestyle{empty}%
  \begin{tikzpicture}[remember picture, overlay]
    \node[draw,text width=\textwidth] at (current page header area)
      {text in box};
\end{tikzpicture}}]{../blogs/kindle}
\end{document}


text:
Q: Which option is better to extend a feature 1) add a property or 2) create a new table? Suppose i have a Cat domain as shown below.
  class Cat{

     String name
     Integer age

    }

Now i want to add a new feature that will assign tags to cats.
Now i see two options to achieve this.
Option 1
add a property to the Cat domain
class Cat{

 String name
 Integer age
 String tag

}

Option 2
Create a new table
class CatTagAssignment{

 Cat cat
 String tag

 static mapping = {

        id composite: ['cat', 'tag']

    }

}

I am trying to understand which is a better approach or which one should i prefer when i want to add a new feature? I appreciate it if you can offer pros and cons of both approach and whether one approach is always preferable to the other. I appreciate your help! Thanks!

A: Make a tag model (define your tags), and a cattag model (relate tags to cats). Should you ever want to be able to 'tag' something else, it's a simple join table to the new model.
Which to prefer? Ignore code and frameworks and think about what you are modeling.
Tags as a separate entity are more reusable, and a cat remains a cat (is a tag really an attribute of a cat?). Good models should be transferable across database, framework, language.

A: Use the simplest model you can get. Don't use the extra tables for the sake of "object orientation" alone, unless there's no other option.
I would pick 1) as it's the fastest possible way to load objects, although the tag lookup can get a bit tricky (like query)


text:
Q: Cloudformation template is unable to execute retrieval of mount target I have the following command in the userdata of my cloudformation template:
MOUNT_TARGET_IP=$(aws efs describe-mount-targets --file-system-id fs-xxxxxxx --query 'MountTargets[*].IpAddress' --output text)
Also in my template, I have the following policy:
MyPolicy:
Type: "AWS::IAM::Policy"
Properties:
  PolicyName: !Sub "${AWS::StackName}_bucket_and_mount_targets_policy"
  PolicyDocument:
    Version: "2012-10-17"
    Statement:
      -
        Effect: "Allow"
        Action: "s3:GetObject"
        Resource: !Sub "arn:aws:s3:::${AuthorizedKeyBucketName}/authorized_keys"
      -
        Effect: "Allow"
        Action: "s3:ListBucket"
        Resource: !Sub "arn:aws:s3:::${AuthorizedKeyBucketName}"
      -
        Effect: "Allow"
        Action: "elasticfilesystem:DescribeMountTargets"
        Resource: "arn:aws:elasticfilesystem:us-east-1:xxxxxxxxxx:file-system/fs-xxxxxxx"
  Roles:
    -
      !Ref MyRole

I am not sure why I am still receiving the following error:
You must specify a region. You can also configure your region by running "aws configure".

When I ssh into the instance, and then configure the region and access keys manually, and then try to execute the above statements, it seems to work just fine.
Any thoughts?

A: Most AWS CLI commands require a region to be configured and you haven't configured one here.
You could change your CLI command to specify a region:
MOUNT_TARGET_IP=$(aws efs describe-mount-targets \
  --file-system-id fs-xxxxxxx \
  --query 'MountTargets[*].IpAddress' \
  --region ... \  # add this
  --output text)

Or you could set the AWS_DEFAULT_REGION variable:
AWS_DEFAULT_REGION=...
export AWS_DEFAULT_REGION
MOUNT_TARGET_IP=$(aws efs describe-mount-targets --file-system-id fs-xxxxxxx \
  --query 'MountTargets[*].IpAddress' --output text)

Or you could have your script run aws configure or otherwise provide the region in ~/.aws/config.
Note that configuring the AWS CLI with access keys is not recommended. You should use IAM Roles instead.


text:
Q: Some RUNs won't work on docker but will when inside a container I've got a Dockerfile for some lua and torch related tasks and I'm trying to install some rocks using luarocks.
FROM ubuntu:14.04
RUN rm /bin/sh && ln -s /bin/bash /bin/sh

RUN apt-get update -y
RUN apt-get install -y curl git

RUN curl -s https://raw.githubusercontent.com/torch/ezinstall/master/install-deps | bash
RUN git clone https://github.com/torch/distro.git ~/torch --recursive
RUN cd ~/torch; ./install.sh

RUN source ~/.bashrc

RUN luarocks install nngraph
RUN luarocks install optim
RUN luarocks install nn

RUN luarocks install cltorch
RUN luarocks install clnn

docker build runs fine up until the first luarocks call: RUN luarocks install nngraph at which point it stops and throws the error:
/bin/sh: luarocks: command not found

If I comment out the luarocks lines, the build runs fine. Using that image, I can create a container and using bash, run luarocks as expected.
Of course, I don't particularly want to have to do this every time I start up the container, so I'm wondering if there's anything I can do to make this work. I have a feeling that this problem has something to do with the line RUN rm /bin/sh && ln -s /bin/bash /bin/sh but I need that to be able to run the line RUN source ~/.bashrc.
Thanks.

A: Each RUN command runs on its own shell and a new layer is committed.
From the Docker documentations:

RUN  (the command is run in a shell - /bin/sh -c - shell
  form)

So when you run luarocks install <app> it will not be the same shell you source your profile.
You have to provide the full path for luarocks to run. See below a modified Dockerfile I successfully run:
FROM ubuntu:14.04
RUN rm /bin/sh && ln -s /bin/bash /bin/sh

RUN apt-get update -y
RUN apt-get install -y curl git

RUN curl -s https://raw.githubusercontent.com/torch/ezinstall/master/install-deps | bash
RUN git clone https://github.com/torch/distro.git ~/torch --recursive
RUN cd ~/torch; ./install.sh

RUN source ~/.bashrc

RUN /root/torch/install/bin/luarocks install nngraph
RUN /root/torch/install/bin/luarocks install optim
RUN /root/torch/install/bin/luarocks install nn
RUN /root/torch/install/bin/luarocks install cltorch
RUN /root/torch/install/bin/luarocks install clnn

For more details see docker RUN documentation here.

A: As Alex da Silva pointed it out, sourcing .bashrc happens in another shell in your Dockerfile.
You could also try that to have your luarocks commands executed in the same shell with your sourced bashrc:
...
RUN source ~/.bashrc && luarocks install nngraph
RUN source ~/.bashrc && luarocks install optim
RUN source ~/.bashrc && luarocks install nn

RUN source ~/.bashrc && luarocks install cltorch
RUN source ~/.bashrc && luarocks install clnn


text:
Q: Make a div sticky to a SVG relative parent Let's say I have an SVG element

SVGArea

And after it I have an img div containing an Icon

IconImg

The structure is like :

  <svg>
   #SOMETHING
  </svg>

On click, the Icon image is placed somewhere in the SVG (according to computed w and y positions).
The problem : the Icon moves each time I scroll up or down or I zoom in/out. The  element doesn't seem to stay fixed or sticky. And I have trid all what I have found in internet :
#IconImg{top:0; position:sticky // or fixed}
#SVGArea{position : relative}

And there is no parent with hidden-flow attribute.
How can I fix that I have my Icon stay in place what ever the scrool or zoom ? Thank you for you thoughts and answers for help.


text:
Q: iOS 11 Safari tries to download .dll file instead of showing HTTP response I've got a server setup with a URL structure like so:
mything.com/services/super.dll?why=doesnt&this=work

This URL returns some plaintext content with Content-Type: text/plain.
On iOS <= 10 and all Android browsers, it works as expected, and I see the plain text response.
On iOS 11, Safari tries to download super.dll. It gives me a screen telling me that super.dll is a Microsoft Windows application with a size of 1KB. I have the option to "Open in 'Files'" and "More...".
I have no idea what's going on under the hood that might cause this. Has anyone else seen this behavior?


text:
Q: Using `gsettings` to block the mounting of USB drives I want to configure Ubuntu (16.04) to prevent users from using removable media, specifically USB drives.
You can prevent automount as per.
gsettings set org.gnome.desktop.media-handling automount false
However, although this action disables auto-mounting of the device, it does not affect use of the device. I.E. as soon as you 'open' the USB icon on the desktop, the device mounts!
Running df upon opening the graphical USB desktop item:
/dev/sdb1             3780564      120   3780444   1% /media/user/xxxx-xxxx
I do not want the device to automount under any circumstances. You could argue that the device is still 'automounting' when you click on the desktop icon, as the user has not explicitly run a command to mount the device. For instance:
sudo mount /dev/sdb1 /media/user/xxxx-xxxx
Is there a schema/key combination in gsettings where I can set a value, in such a way, that only 'root' can use USB devices? In other words, I do not want USB devices to be accessible unless explicitly mounted by root.
I have also found these two answers; one and two.
However, as a relatively inexperienced user, I'm hesitant to implement the instructions as given, as the answer mentions to "blacklist the kernel driver".. whilst I do not doubt the validity of the information given, this gives me the impression that it is really for advanced users only. Likewise, the 'man' page for modprobe refers to "adding/removing modules to the Linux Kernel".
Is this the only way to go about blocking USB access, or is there a Schema/Key combination in gsettings where I can simply set the value of a key as appropriate?
To clarify, I am explicitly referring to USB storage/drives, as I have a keyboard and pointer connected via USB.


text:
Q: Base R on Power 9 CPU working (ppc64le architecture)? There is an r-base package available for the IBM Power9 CPU architecture (ppc64le) on Ubuntu Linux
and I am wondering if R can really be used on this architecture beyond "does-it-run" experiments.
I did use this search engine to find the r-base package:
https://developer.ibm.com/linuxonpower/open-source-pkgs/
Since this architecture is not officially supported by the R consortium: Does anybody successfully use R on this architecture in a production environment?
Edit 1: RStudio Server seems to be running at least within docker (but there is no official support by RStudio):

*

*A Guide to Enable RStudio on IBM Power System

*Running RStudio Server on IBM/Power8
Edit 2: I have found this post at r-devel regarding a solved build failure.


text:
Q: I was working on weather forecast app using openweathermap API. But I am not getting the output I was expecting the outputs like temperature,pressure,etc. But it is not showing.Please help.
#The Error I got is
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\KRUNAL\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "c:\Users\KRUNAL\Desktop\Whether Forecast app\app.py", line 44, in getWhether
    temp = json_data['current']['temp']
           ~~~~~~~~~^^^^^^^^^^^
KeyError: 'current'

#import dependancies (ws1)
from tkinter import *
import tkinter as tk
from geopy.geocoders import Nominatim
from tkinter import ttk, messagebox
from timezonefinder import TimezoneFinder
from datetime import *
import requests
import pytz
from PIL import Image, ImageTk

#framework of app (ws2)
root= Tk()#initialize the Tkinter
root.title("Whether App")# givee title to app
root.geometry("890x470+300+300")#first two are dimentions and paremater 300 is extendable limit
root.configure(bg="#57adff")# it is background colour
root.resizable(False,False)#gives information  of resizability

# define getWhether(ws10)
def getWhether():
    city=textfield.get()

    geolocator=Nominatim(user_agent="geoapiExercises")# detect location
    location= geolocator.geocode(city)
    obj = TimezoneFinder()
    result = obj.timezone_at(lng=location.longitude,lat=location.latitude)
    timezone.config(text=result)
    long_lat.config(text=f"{round(location.latitude,4)}°N,{location.longitude}°E")

    #ading time(ws11)
    home=pytz.timezone(result)
    local_time=datetime.now(home)
    current_time=local_time.strftime("%H:%M %p")#gives %H=hour and %M=minutes %p is AM or PM
    clock.config(text=current_time)

    #fetching whether(ws12)
    api="https://api.openweathermap.org/data/2.5/onecall?lat="+str(location.latitude)+"&lon"+str(location.longitude)+"&units=metric&exclude=hourly,&appid=21cd23a616e7b25bc0382c9c18b5f320"
    #created from website
    json_data = requests.get(api).json()

    #whether data(ws14)
    temp = json_data['current']['temp']
    humidity = json_data['current']['humidity']
    pressure = json_data['current']['presssure']
    wind = json_data['current']['wind_speed']
    description = json_data['current']['weather'][0]['description']

    t.config(text=(temp,"°C"))
    h.config(text=(humidity,"%"))
    p.config(text=(pressure,"hPa"))
    w.config(text=(wind,"m/s"))
    d.config(text=description)

#adding icon to app(ws3)
image_icon=PhotoImage(file="Images/logo.png")#getting logo from images folder
root.iconphoto(False,image_icon)

#adding box like thing(ws4)
Round_box=PhotoImage(file="Images/Rounded Rectangle 1.png")
Label(root,image=Round_box,bg="#57adff").place(x=30,y=110)#adding bg color and coordinates

#Adding information(ws5)
label1=Label(root,text="Temperature",font=('Helvetica',11),fg="white",bg="#203243")
label1.place(x=50,y=120)

label2=Label(root,text="Humidity",font=('Helvetica',11),fg="white",bg="#203243")
label2.place(x=50,y=140)

label3=Label(root,text="Pressure",font=('Helvetica',11),fg="white",bg="#203243")
label3.place(x=50,y=160)

label4=Label(root,text="Wind Speed",font=('Helvetica',11),fg="white",bg="#203243")
label4.place(x=50,y=180)

label5=Label(root,text="Description",font=('Helvetica',11),fg="white",bg="#203243")
label5.place(x=50,y=200)

# making search box(ws6)
Search_image=PhotoImage(file="Images/Rounded Rectangle 3.png")
myimage=Label(image=Search_image,bg="#57adff")
myimage.place(x=270,y=120)

weat_image=PhotoImage(file="Images/Layer 7.png")
weatherimage=Label(root,image=weat_image,bg="#203243")
weatherimage.place(x=290,y=127)

textfield=tk.Entry(root,justify='center',width=15,font=('poppins',25,'bold'),bg="#203243",border=0,fg="white")
textfield.place(x=370,y=130)
textfield.focus()

Search_icon=PhotoImage(file="Images/Layer 6.png")
myimage_icon=Button(image=Search_icon,borderwidth=0,cursor="hand2",bg="#203243",command=getWhether)
myimage_icon.place(x=645,y=125)

# making main bottom box(ws7)
frame=Frame(root,width=900,height=180,bg="#212120")
frame.pack(side=BOTTOM)

#making more boxes(ws8)
firstbox=PhotoImage(file="Images/Rounded Rectangle 2.png")
secondbox=PhotoImage(file="Images/Rounded Rectangle 2 copy.png")

Label(frame,image=firstbox,bg="#212120").place(x=30,y=20)
Label(frame,image=secondbox,bg="#212120").place(x=300,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=400,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=500,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=600,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=700,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=800,y=30)

#clock for time syncronization(ws9)
clock=Label(root,font=("Helvica",30,'bold'),fg="white",bg="#57adff")
clock.place(x=30,y=20)

#timezone of the searched city
timezone=Label(root,font=("Helvetica",20),fg="white",bg="#57adff")
timezone.place(x=700,y=20)

long_lat=Label(root,font=("Helvitica",10),fg="white",bg="#57adff")
long_lat.place(x=700,y=50)

#Printing data
t=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
t.place(x=150,y=120)
h=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
h.place(x=150,y=140)
p=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
p.place(x=150,y=160)
w=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
w.place(x=150,y=180)
d=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
d.place(x=150,y=200)

root.mainloop()# to run it in

~~~

#import dependancies (ws1)
from tkinter import *
import tkinter as tk
from geopy.geocoders import Nominatim
from tkinter import ttk, messagebox
from timezonefinder import TimezoneFinder
from datetime import *
import requests
import pytz
from PIL import Image, ImageTk

#framework of app (ws2)
root= Tk()#initialize the Tkinter
root.title("Whether App")# givee title to app
root.geometry("890x470+300+300")#first two are dimentions and paremater 300 is extendable limit
root.configure(bg="#57adff")# it is background colour
root.resizable(False,False)#gives information  of resizability

# define getWhether(ws10)
def getWhether():
    city=textfield.get()

    geolocator=Nominatim(user_agent="geoapiExercises")# detect location
    location= geolocator.geocode(city)
    obj = TimezoneFinder()
    result = obj.timezone_at(lng=location.longitude,lat=location.latitude)
    timezone.config(text=result)
    long_lat.config(text=f"{round(location.latitude,4)}°N,{location.longitude}°E")

    #ading time(ws11)
    home=pytz.timezone(result)
    local_time=datetime.now(home)
    current_time=local_time.strftime("%H:%M %p")#gives %H=hour and %M=minutes %p is AM or PM
    clock.config(text=current_time)

    #fetching whether(ws12)
    api="https://api.openweathermap.org/data/2.5/onecall?lat="+str(location.latitude)+"&lon"+str(location.longitude)+"&units=metric&exclude=hourly,&appid=21cd23a616e7b25bc0382c9c18b5f320"
    #created from website
    json_data = requests.get(api).json()

    #whether data(ws14)
    temp = json_data['current']['temp']
    humidity = json_data['current']['humidity']
    pressure = json_data['current']['presssure']
    wind = json_data['current']['wind_speed']
    description = json_data['current']['weather'][0]['description']

    t.config(text=(temp,"°C"))
    h.config(text=(humidity,"%"))
    p.config(text=(pressure,"hPa"))
    w.config(text=(wind,"m/s"))
    d.config(text=description)

#adding icon to app(ws3)
image_icon=PhotoImage(file="Images/logo.png")#getting logo from images folder
root.iconphoto(False,image_icon)

#adding box like thing(ws4)
Round_box=PhotoImage(file="Images/Rounded Rectangle 1.png")
Label(root,image=Round_box,bg="#57adff").place(x=30,y=110)#adding bg color and coordinates

#Adding information(ws5)
label1=Label(root,text="Temperature",font=('Helvetica',11),fg="white",bg="#203243")
label1.place(x=50,y=120)

label2=Label(root,text="Humidity",font=('Helvetica',11),fg="white",bg="#203243")
label2.place(x=50,y=140)

label3=Label(root,text="Pressure",font=('Helvetica',11),fg="white",bg="#203243")
label3.place(x=50,y=160)

label4=Label(root,text="Wind Speed",font=('Helvetica',11),fg="white",bg="#203243")
label4.place(x=50,y=180)

label5=Label(root,text="Description",font=('Helvetica',11),fg="white",bg="#203243")
label5.place(x=50,y=200)

# making search box(ws6)
Search_image=PhotoImage(file="Images/Rounded Rectangle 3.png")
myimage=Label(image=Search_image,bg="#57adff")
myimage.place(x=270,y=120)

weat_image=PhotoImage(file="Images/Layer 7.png")
weatherimage=Label(root,image=weat_image,bg="#203243")
weatherimage.place(x=290,y=127)

textfield=tk.Entry(root,justify='center',width=15,font=('poppins',25,'bold'),bg="#203243",border=0,fg="white")
textfield.place(x=370,y=130)
textfield.focus()

Search_icon=PhotoImage(file="Images/Layer 6.png")
myimage_icon=Button(image=Search_icon,borderwidth=0,cursor="hand2",bg="#203243",command=getWhether)
myimage_icon.place(x=645,y=125)

# making main bottom box(ws7)
frame=Frame(root,width=900,height=180,bg="#212120")
frame.pack(side=BOTTOM)

#making more boxes(ws8)
firstbox=PhotoImage(file="Images/Rounded Rectangle 2.png")
secondbox=PhotoImage(file="Images/Rounded Rectangle 2 copy.png")

Label(frame,image=firstbox,bg="#212120").place(x=30,y=20)
Label(frame,image=secondbox,bg="#212120").place(x=300,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=400,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=500,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=600,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=700,y=30)
Label(frame,image=secondbox,bg="#212120").place(x=800,y=30)

#clock for time syncronization(ws9)
clock=Label(root,font=("Helvica",30,'bold'),fg="white",bg="#57adff")
clock.place(x=30,y=20)

#timezone of the searched city
timezone=Label(root,font=("Helvetica",20),fg="white",bg="#57adff")
timezone.place(x=700,y=20)

long_lat=Label(root,font=("Helvitica",10),fg="white",bg="#57adff")
long_lat.place(x=700,y=50)

#Printing data
t=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
t.place(x=150,y=120)
h=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
h.place(x=150,y=140)
p=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
p.place(x=150,y=160)
w=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
w.place(x=150,y=180)
d=Label(root,font=("Helvetica",11),fg="white",bg="#203243")
d.place(x=150,y=200)

root.mainloop()# to run it in

~~~


text:
Q: Unexpected header files: I'm getting unexpected header files with the
brew doctor

I tried brew doctor and then I get a huge list of files. I'm not sure if they are safe to delete or how I would delete them in the first place
brew doctor

Alexs-Air:~ alex$ brew doctor
Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry or file an issue; just ignore this. Thanks!

Warning: Unbrewed header files were found in /usr/local/include.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected header files:
  /usr/local/include/node/android-ifaddrs.h
  /usr/local/include/node/libplatform/libplatform-export.h
  /usr/local/include/node/libplatform/libplatform.h
  /usr/local/include/node/libplatform/v8-tracing.h
  /usr/local/include/node/node.h
  /usr/local/include/node/node_api.h
  /usr/local/include/node/node_api_types.h
  /usr/local/include/node/node_buffer.h
  /usr/local/include/node/node_object_wrap.h
  /usr/local/include/node/node_version.h
  /usr/local/include/node/openssl/aes.h
  /usr/local/include/node/openssl/archs/BSD-x86/opensslconf.h
  /usr/local/include/node/openssl/archs/BSD-x86_64/opensslconf.h
  /usr/local/include/node/openssl/archs/VC-WIN32/opensslconf.h
  /usr/local/include/node/openssl/archs/VC-WIN64A/opensslconf.h
  /usr/local/include/node/openssl/archs/aix-gcc/opensslconf.h
  /usr/local/include/node/openssl/archs/aix64-gcc/opensslconf.h
  /usr/local/include/node/openssl/archs/darwin-i386-cc/opensslconf.h
  /usr/local/include/node/openssl/archs/darwin64-x86_64-cc/opensslconf.h
  /usr/local/include/node/openssl/archs/linux-aarch64/opensslconf.h
  /usr/local/include/node/openssl/archs/linux-armv4/opensslconf.h
  /usr/local/include/node/openssl/archs/linux-elf/opensslconf.h
  /usr/local/include/node/openssl/archs/linux-ppc/opensslconf.h
  /usr/local/include/node/openssl/archs/linux-ppc64/opensslconf.h
  /usr/local/include/node/openssl/archs/linux-x32/opensslconf.h
  /usr/local/include/node/openssl/archs/linux-x86_64/opensslconf.h
  /usr/local/include/node/openssl/archs/linux32-s390x/opensslconf.h
  /usr/local/include/node/openssl/archs/linux64-s390x/opensslconf.h
  /usr/local/include/node/openssl/archs/solaris-x86-gcc/opensslconf.h
  /usr/local/include/node/openssl/archs/solaris64-x86_64-gcc/opensslconf.h
  /usr/local/include/node/openssl/asn1.h
  /usr/local/include/node/openssl/asn1_mac.h
  /usr/local/include/node/openssl/asn1t.h
  /usr/local/include/node/openssl/bio.h
  /usr/local/include/node/openssl/blowfish.h
  /usr/local/include/node/openssl/bn.h
  /usr/local/include/node/openssl/buffer.h
  /usr/local/include/node/openssl/camellia.h
  /usr/local/include/node/openssl/cast.h
  /usr/local/include/node/openssl/cmac.h
  /usr/local/include/node/openssl/cms.h
  /usr/local/include/node/openssl/comp.h
  /usr/local/include/node/openssl/conf.h
  /usr/local/include/node/openssl/conf_api.h
  /usr/local/include/node/openssl/crypto.h
  /usr/local/include/node/openssl/des.h
  /usr/local/include/node/openssl/des_old.h
  /usr/local/include/node/openssl/dh.h
  /usr/local/include/node/openssl/dsa.h
  /usr/local/include/node/openssl/dso.h
  /usr/local/include/node/openssl/dtls1.h
  /usr/local/include/node/openssl/e_os2.h
  /usr/local/include/node/openssl/ebcdic.h
  /usr/local/include/node/openssl/ec.h
  /usr/local/include/node/openssl/ecdh.h
  /usr/local/include/node/openssl/ecdsa.h
  /usr/local/include/node/openssl/engine.h
  /usr/local/include/node/openssl/err.h
  /usr/local/include/node/openssl/evp.h
  /usr/local/include/node/openssl/hmac.h
  /usr/local/include/node/openssl/idea.h
  /usr/local/include/node/openssl/krb5_asn.h
  /usr/local/include/node/openssl/kssl.h
  /usr/local/include/node/openssl/lhash.h
  /usr/local/include/node/openssl/md4.h
  /usr/local/include/node/openssl/md5.h
  /usr/local/include/node/openssl/mdc2.h
  /usr/local/include/node/openssl/modes.h
  /usr/local/include/node/openssl/obj_mac.h
  /usr/local/include/node/openssl/objects.h
  /usr/local/include/node/openssl/ocsp.h
  /usr/local/include/node/openssl/opensslconf.h
  /usr/local/include/node/openssl/opensslv.h
  /usr/local/include/node/openssl/ossl_typ.h
  /usr/local/include/node/openssl/pem.h
  /usr/local/include/node/openssl/pem2.h
  /usr/local/include/node/openssl/pkcs12.h
  /usr/local/include/node/openssl/pkcs7.h
  /usr/local/include/node/openssl/pqueue.h
  /usr/local/include/node/openssl/rand.h
  /usr/local/include/node/openssl/rc2.h
  /usr/local/include/node/openssl/rc4.h
  /usr/local/include/node/openssl/ripemd.h
  /usr/local/include/node/openssl/rsa.h
  /usr/local/include/node/openssl/safestack.h
  /usr/local/include/node/openssl/seed.h
  /usr/local/include/node/openssl/sha.h
  /usr/local/include/node/openssl/srp.h
  /usr/local/include/node/openssl/srtp.h
  /usr/local/include/node/openssl/ssl.h
  /usr/local/include/node/openssl/ssl2.h
  /usr/local/include/node/openssl/ssl23.h
  /usr/local/include/node/openssl/ssl3.h
  /usr/local/include/node/openssl/stack.h
  /usr/local/include/node/openssl/symhacks.h
  /usr/local/include/node/openssl/tls1.h
  /usr/local/include/node/openssl/ts.h
  /usr/local/include/node/openssl/txt_db.h
  /usr/local/include/node/openssl/ui.h
  /usr/local/include/node/openssl/ui_compat.h
  /usr/local/include/node/openssl/whrlpool.h
  /usr/local/include/node/openssl/x509.h
  /usr/local/include/node/openssl/x509_vfy.h
  /usr/local/include/node/openssl/x509v3.h
  /usr/local/include/node/pthread-barrier.h
  /usr/local/include/node/stdint-msvc2008.h
  /usr/local/include/node/tree.h
  /usr/local/include/node/uv-aix.h
  /usr/local/include/node/uv-bsd.h
  /usr/local/include/node/uv-darwin.h
  /usr/local/include/node/uv-errno.h
  /usr/local/include/node/uv-linux.h
  /usr/local/include/node/uv-os390.h
  /usr/local/include/node/uv-posix.h
  /usr/local/include/node/uv-sunos.h
  /usr/local/include/node/uv-threadpool.h
  /usr/local/include/node/uv-unix.h
  /usr/local/include/node/uv-version.h
  /usr/local/include/node/uv-win.h
  /usr/local/include/node/uv.h
  /usr/local/include/node/v8-debug.h
  /usr/local/include/node/v8-inspector-protocol.h
  /usr/local/include/node/v8-inspector.h
  /usr/local/include/node/v8-platform.h
  /usr/local/include/node/v8-profiler.h
  /usr/local/include/node/v8-testing.h
  /usr/local/include/node/v8-util.h
  /usr/local/include/node/v8-value-serializer-version.h
  /usr/local/include/node/v8-version-string.h
  /usr/local/include/node/v8-version.h
  /usr/local/include/node/v8.h
  /usr/local/include/node/v8config.h
  /usr/local/include/node/zconf.h
  /usr/local/include/node/zlib.h

A: Sorry I'm little bit late, but I had the same problem. First brew uninstall node
brew uninstall node

then I removed the Unbrewed files and then downloaded node again.
sudo rm -rf /usr/local/include/node/android-ifaddrs.h
sudo cleanup
brew install node
brew doctor

Hope it helps!


text:
Q: Cannot overwrite Cache-Control in PHP I've moved a older site to a new server, and the client has found a very odd behaviour.
Very close to the end, I have this code:
if (!$this->cache) {
    header('Expires: '.gmdate('d M Y H:i:s', 946684800).' GMT');
    header('Cache-Control: no-cache');
    header('Pragma: no-cache');
}

Now the odd thing is the Cache-Control line doesnt work.
After packet sniffing I see this:
Expires: 01 Jan 2000 00:00:00 GMT
Cache-Control: max-age=300, public
Pragma: no-cache

The order of the headers is exactly how I set them, but the Cache-Control is completely different. I've grepped my code for any mention of cache-control and there is only that mention, and another one designed to force caching in a different file but it is a different line to what I'm seeing so it cant be the culprit.
Does anyone know why Cache-Control is changing?

A: If you are using sessions, it's possible that PHP is overwriting them. Take a look at session_cache_limiter() in the manual.
Alternatively, you can try setting those headers after you call session_start().
(Edit: I missed the bit about "Very close to the end," so maybe this isn't your problem.)

A: I think you are running Squid, you should check its config for:
header_replace Cache-Control max-age=300, public


text:
Q: Select option by text I'm having trouble setting my selects to some default values that come in through ajax
Here's a fiddle: http://jsfiddle.net/helto/wycLZ/
Here's the code:
HTML:

Condition:
<select id="condition">
    <option selected="true" style="display:none;">Choose</option>
</select>

JS:
var conditions = [{
id: 1,
name: "New"
}, {
id: 2,
name: "Good"
}, {
id: 3,
name: "Poor"
}];
$.each(conditions, function (key, value) {
var cond = '<option value="' + value.id + '">' + value.name + '</option>';
$('#condition').append(cond);
});

$('#condition option[text="New"]').attr('selected', 'selected');

Its this last line that's giving me trouble, I want to select the option based on the text

A: You could use :contains:
$('#condition option:contains("New")').prop('selected', true);

Or .filter():
$('#condition option').filter(function() {
    return this.text === 'New';
}).prop('selected', true);

:contains will match News as well, so I'd go with .filter()

A: You should use $('#condition option:contains("New")').prop('selected', true); which takes advantage of jQuery's :contains() Selector
Here is a jsFiddle demo


text:
Q: How to use *ngFor parent index as a parameter in a nested *ngfor Im trying to pass my parent index to a nested ngFor so i can access an array: "name1, name2, etc"
<ion-item *ngFor="let b of banca ; let i = index">
   <ion-select>
       <ion-select-option *ngFor="let n of name + [i+1]" [value]="n">{{n}}</ion-select-option>
   </ion-select>
</ion-item>

Error:

Cannot find a differ supporting object 'undefined1' of type 'string'.
NgFor only supports binding to Iterables such as Arrays.

I´ve tried different combinations but i can't figure it out. How is the correct syntax to pass the value?
Thanks!

A: Although the question is not entirely clear what you are trying to do could never work.In your example name0 is the list,then name1 and name2, etc. The error says "Undefined1" is not an array because not even name exists. If what you want to do is iterate an array inside the initial array you can do
  <ion-item *ngFor="let b of banca ; let i = index">
   <ion-select>
      <ion-select-option *ngFor="let n of b.name[i]" [value]="n.attribute"></ion-select-option>
   </ion-select>
</ion-item>

where attribute is anything you got in that array


text:
Q: Row count and column count not showing correctly in VBA I am trying to select all rows and columns so that i can apply Pivot. There are 12327 rows in all and 7 columns. But LastRow2 and LastCol2 both display row count value ie 12327 but actual count of column is only 7.
With Sheet2
    LastRow2= .Cells(.Rows.Count, 1).End(xlUp).Row
    LastCol2= .Cells(1, .Columns.Count).End(xlToLeft).Column
  Set PRange2= .Range("A1", .Cells(LastRow2, LastCol2))
End With

MsgBox LastCol2 & " " & LastRow2

This is second pivot in my table, this code shows correct values in first pivot table code.

A: Well, there are a few possible traps:

*

*The documentation of Range.End is not very good. It tells you, it gives the same result as some keyboard combination - that is far from a clear definition. That's why I really try to avoid Range.End altogether and use Find instead (inside some udf).

*Since it is not clearly documented, it may very well have a different definition of "last" and of "empty". Let me be more clear:

*

*If your range is more than one column, whose last row will it pick?

*If your cell had changes in formatting, do you consider it empty? Does Range.End treat it the same way?
Hope this helps. I'm not allowed to comment, just to answer, to that's what I had to do ;)
Best,
YeOldHinnerk


text:
Q: Getting Response 403 When signing an Amazon Request I am trying to send an email through amazon SES without the SDK so I can send emails asynchronously in Python. I am using amazon's v4 signing method on their site here: https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html, but I'm not having any luck sending emails without the SDK. The output is:
RESPONSE++++++++++++++++++++++++++++++++++++
Response code: 403

<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
  <Error>
    <Type>Sender</Type>
    SignatureDoesNotMatch
    <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message>
  </Error>
  <RequestId>a19a5fa1-3228-11e9-b2bc-ddb6d8a1cb1c</RequestId>
</ErrorResponse>

Process finished with exit code 0

Here is the block of code generating that response:
import datetime
import hashlib
import hmac
import urllib.parse
import requests
method = 'GET'
service = 'ses'
host = 'email.us-east-1.amazonaws.com'
region = 'us-east-1'
endpoint = 'https://email.us-east-1.amazonaws.com/'

def sign(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def getSignatureKey(key, dateStamp, regionName, serviceName):
    kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'aws4_request')
    return kSigning

access_key = '<my access_key here>'
secret_key = '<my secret_key here>'
my_email = 'my email here'

t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d')
canonical_uri = '/'
canonical_headers = 'host:' + host + '\n'
signed_headers = 'host'
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'

canonical_querystring = '''Action=SendEmail
&Source=%s%40gmail.com
&Destination.ToAddresses.member.1=%s%40gmail.com
&Message.Subject.Data=This%20is%20the%20subject%20line.
&Message.Body.Text.Data=Hello.%20I%20hope%20you%20are%20having%20a%20good%20day''' % (my_email, my_email)

canonical_querystring += '&X-Amz-Algorithm=AWS4-HMAC-SHA256'
canonical_querystring += '&X-Amz-Credential=' + urllib.parse.quote_plus(access_key + '/' + credential_scope)
canonical_querystring += '&X-Amz-Date=' + amz_date
canonical_querystring += '&X-Amz-Expires=30'
canonical_querystring += '&X-Amz-SignedHeaders=' + signed_headers

payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
string_to_sign = algorithm + '\n' +  amz_date + '\n' +  credential_scope + '\n' +  hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()
signing_key = getSignatureKey(secret_key, datestamp, region, service)
signature = hmac.new(signing_key, (string_to_sign).encode("utf-8"), hashlib.sha256).hexdigest()
canonical_querystring += '&X-Amz-Signature=' + signature
request_url = endpoint + "?" + canonical_querystring

print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
print('Request URL = ' + request_url)
r = requests.get(request_url)

print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
print('Response code: %d\n' % r.status_code)
print(r.text)

This is basically Amazon's code for generating a signature copied and pasted from their docs. Does anyone know what I'm doing wrong in signing my requests to amazon?
Edit* I changed the canonical_querystring to be alphabetical like so:
canonical_querystring = '''Action=SendEmail
&Destination.ToAddresses.member.1={}%40gmail.com
&Message.Body.Text.Data=Hello.%20I%20hope%20you%20are%20having%20a%20good%20day
&Message.Subject.Data=This%20is%20the%20subject%20line.
&Source={}%40gmail.com'''.format(my_email, my_email)

It is still giving me the same error though. Everything else in the query string is alphabetized, or "canonically ordered".

A: Your canonical query string is not canonical.
You have Action... Source... Destination... Message but all of the parameters need to be lexically ordered.

Step 3: Create the canonical query string.
[...]
The parameters must be sorted by name.

This ordering is the reason why the value is called canonical.  It's necessary because the relative positions of query string parameters aren't necessarily guaranteed.  The parameters don't need to be sorted in the actual query string accompanying the request, but they do need to be sorted here, for signing.
Since a given request can have only one possible valid signature, the parameters are sorted before signing to remove the ambiguity that might otherwise arise if a user agent or proxy rearranged the query parameters or ordered them arbitrarily when building the URL (as might be expected if, for example, the parameters are passed to the UA as an unordered hash/dictionary structure).


text:
Q: Strange error downloading files with Node.JS This is the Node.JS code, it has two parts. The first one is in the main server file:
app.get('/download/:photo', function (req, res){

   dbs.imagenschema.find({ _id: req.params.photo }, function (err, imagen){

     if (err) throw assert.ifError(err);;

     var file = __dirname + '/public/users/' + imagen.auid + '/' + imagen.name;

     var filename = path.basename(file);
     var mimetype = mime.lookup(file);

     res.setHeader('Content-disposition', 'attachment; filename=' + filename);
     res.setHeader('Content-type', mimetype);

     var filestream = fs.createReadStream(file);
     filestream.pipe(res);

   });

});

The other part is the dbs.imagenschema, but that part is very simple, it's just the schema for the images exported from dbs module.
This is te button that when is clicked, the download starts:
<a href="/download/<%= photo._id %>">
  <button class="btn btn-inverse">  Download</button>

But, when I click it, I receive this error:
TypeError: Cannot read property 'background' of null
  at eval (eval at <anonymous> (/root/pixgalery/node_modules/ejs/lib/ejs.js:234:12), <anonymous>:30:4196)
  at /root/pixgalery/node_modules/ejs/lib/ejs.js:239:15
  at Object.exports.render (/root/pixgalery/node_modules/ejs/lib/ejs.js:277:13)
  at View.exports.renderFile [as engine] (/root/pixgalery/node_modules/ejs/lib/ejs.js:303:22)
  at View.render (/root/pixgalery/node_modules/express/lib/view.js:75:8)
  at Function.app.render (/root/pixgalery/node_modules/express/lib/application.js:500:10)
  at ServerResponse.res.render (/root/pixgalery/node_modules/express/lib/response.js:717:7)
  at /root/pixgalery/app.js:181:15
  at Promise.<anonymous> (/root/pixgalery/db.js:237:27)
  at Promise.<anonymous> (/root/pixgalery/node_modules/mongoose/lib/promise.js:133:8)

So, I think is because of this:
app.get('/:user/:id', function (req, res){

  dbs.getimage(req.params.id, req.params.user, function (user, img, fav, comments){

    if (img.type == 'music') {

      res.render('music.ejs', {

            user: user,
            photo: img,
            req: req.session.user,
            fav: fav,
            comments: comments

        });

    } else{

      res.render('photo.ejs', {

            user: user,
            photo: img,
            req: req.session.user,
            fav: fav,
            comments: comments

      });

    }

  });

});

Maybe the server thinks that the /download/fooid is a request for the code I've writted above, because, the /download/fooid doesn't send any response with an EJS file, so, is impossible to get an error like that. Any solution for this?
Thank's advance!

A: You have to make sure the /download/:photo route is declared before the /:user/:id route, otherwise the latter will also match /download/fooid, thinking that download is the user parameter and fooid is the id parameter (with Express, matching occurs in order of declaration: the first route which matches a request will get to handle it).
So:

// first this...
app.get('/download/:photo', ...);

// ...and then this.
app.get('/:user/:id', ...);


text:
Q: Multiway Systems Rules List Management I'm working with a multiway system and I have a number of different mutation rule lists. I need an efficient way of managing which rule lists I apply.
Here is the basic multiway system code that I'm using:

MWStep[rule_List, slist_List] :=
  Union[Flatten[Map[Function[s, Map[MWStep1[#, s] &, rule]], slist]]];

MWStep1[p_String -> q_String, s_String] :=
  Map[StringReplacePart[s, q, #] &, StringPosition[s, p]];

MWEvolveList[rule_, init_List, t_Integer] :=
  NestList[MWStep[rule, #] &, init, t];

StepNtimes[Rule_, string_, n_] := (
   i = 1;
   Subfunc[x_] := MWStep[Rule, x];
   Results = Flatten[NestList[Subfunc, string, n]] )

So for example, with a rules list "M1", I might do
StepNtimes[M1, SampleString, 5]

But say I have Rule lists M1,M2,M3,M4,...,MK
And I want to apply them in different patterns and save the results after each application.
That is, if
ResultSetA = StepNtimes[M1, SampleString, 5]
ResultSetB = StepNtimes[M2, ResultSetA, 5]

...
I want
FinalResults = Flatten[{ResultSetA, ResultSetB, ...}]

Nested Functions? Composition?

A: k[{data_, {}}] := {}
k[{data_, rulez_}] := k[{Sow@StepNTimes[data, rulez[[1]], 5], Rest@rulez}]
Reap@k[{data, {M1, M2}}]

(* {{}, {{StepNTimes[data, M1, 5], StepNTimes[StepNTimes[data, M1, 5], M2, 5]}}} *)


text:
Q: Nav bar on behind pictures when you scroll but i don't want to use z-index My nav bar is behind my images when i try and scroll but i don't want to use z index because i have a lightbox that when you click the image it opens to a bigger image and when the bigger image opens if i have a zindex of 2 then it overlaps the big image in my lightbox. Any help would be great!
Edit: I tried putting the lightbox to an index of 9000 when my nav bar is zindex 1 but this happens:
Nav bar above lightbox:

I would like my nav bar to be behind my lightbox but when i scroll the images don't go over my nav bar.

/** LIGHTBOX MARKUP **/

.lightbox {
 /** Default lightbox to hidden */
 display: none;

 /** Position and style */
 position: fixed;
 z-index: 2;
 width: 100%;
 height: 100%;
 text-align: center;
 top: 0;
 left: 0;
 background: rgba(0,0,0,0.8);
}

.lightbox img {
 /** Pad the lightbox image */
 max-width: 100%;
 max-height: 95%;
 margin-top: 2%;
}

.lightbox:target {
 /** Remove default browser outline */
 outline: none;

 /** Unhide lightbox **/
 display: block;
}

#wrapper {
 width: 90%;
 height: 950px;
 background-color: rgba(155,155,155,0.05);
 margin: auto;
}

#nav-bar {
 width: 90%;
 height: 60px;
 background-color: white;
 opacity: 0.8;
 position: fixed;
 box-shadow: 0 4px 10px -2px rgba(0,0,0,0.1);
 z-index: 0;
}

#nav-bar-portfolio {
 width: 90%;
 height: 60px;
 background-color: white;
 opacity: 0.8;
 position: fixed;
 box-shadow: 0 4px 10px -2px rgba(0,0,0,0.1);
}

#main-content-index {
 height: 900px;
 padding-top: 80px;
 padding-left: 20px;
 padding-right: 20px;
}

#main-content-portfolio {
 height: 100%;
 padding-top: 80px;
 padding-left: 20px;
 padding-right: 20px;
}

.nav-text {
 float:left;
 padding-top: 10px;
 padding-left: 20px;
}

h3 {
 font-size: 25px;
 font-family: helvetica, sans-serif;
 display: inline;
 text-align: left;
}

h4 {
 display: inline-block;
 font-family: helvetica, sans-serif;
 font-size: 13px;
}

nav {
 padding-right: 20px;
 float: right;
 box-shadow: solid black 100px;
}

nav li {
 display: inline-block;
 padding: 15px;
}

nav a {
 font-family: helvetica, sans-serif;
 font-size: 14px;
 color: black;
 transition: opacity .5s ease-in-out;
}

nav a:hover {
 text-decoration: none;
 opacity: 0.2;
}

/* __________________________________________
Main Area
__________________________________________ */

.welcome-banner {
 display: block;
 margin-left: auto;
 margin-right: auto;
}

#portfolio-button {
 width: 150px;
 height: 50px;
 padding-top: 15px;
 padding-left: 30px;
 background-color: rgba(0, 0, 0, 1);
 color: white;
 border-radius: 10px;
 display: block;
 text-decoration: none;
 font-family: helvetica, sans-serif;
 margin: 40px auto;
 transition: opacity .5s ease-in-out;
}

#portfolio-button:hover {
 opacity: 0.3;

}

/* __________________________________________
Footer
__________________________________________ */

#footer {
 width: 100%;
 height: 50px;
 text-align: center;
 background-color: black;
 clear: both;
 padding-top: 15px;
}

.div-left  {
 float: left;
}

.div-left p {
 color: white;
 font-family: helvetica, sans-serif;
 font-size: 13px;
 padding-left: 20px;
}

.div-center {
 margin: 0 auto;
 width: 100%;
}

.div-center p {
 color: white;
 font-family: helvetica, sans-serif;
 font-size: 13px;
}

.div-center a {
 color: white;
 font-family: helvetica, sans-serif;
 font-size: 13px;
 padding-left: 10px;
 text-decoration: none;
 transition: opacity 0.5s ease-in-out;
}

.div-center a:hover {
 opacity: 0.3;
}

.div-right {
 float: right;
}

.div-right ul li  {
 display: inline-block;
}

.div-right ul li a {
 color: white;
 font-family: helvetica, sans-serif;
 font-size: 13px;
 text-decoration: none;
 padding-right: 20px;
 transition: opacity 0.5s ease-in-out;
}

.div-right ul li a:hover {
 opacity: 0.3
}

/* Portfolio */

.main-box {
 background-color: rgba(0, 0,0, 0.05);
 width: 300px;
 height: 400px;
 text-align: center;
 float: left;
 margin-left: 50px;
 margin-top: 10px;
 margin-bottom: 20px;
}

.project-icons {
 padding: 10px;
 filter: grayscale(100%);
 -webkit-filter: grayscale(100%);
 transition: filter 0.6s ease;
 -webkit-transition: -webkit-filter 0.6s ease;
}

.project-icons:hover {
 filter: grayscale(0);
 -webkit-filter: grayscale(0);
}

.project-text {
 padding: 10px;
 font-family: helvetica, sans-serif;
 font-size: 16px;
}

.project-text-caption{
 font-size: 10px;
 font-family: helvetica, sans-serif;

}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <link rel="stylesheet" type="text/css" href="css/animate.css">
 <link rel="stylesheet" type="text/css" href="css/base.css">
 <link rel="stylesheet" type="text/css" href="css/styles.css">

Kyle Du Preez

| PORTFOLIO

 Home

 About

 Portfolio

 Contact

Greek Alphabet Poster

Typography

Pre Media Poster

Large Format

Hamilton Marathon Poster

Typography

Movie Poster

Large Format

Crayola Packaging

Packaging Design

Laing Homes

Brochure Design

 2016 - Kyle Du Preez

Home

About

Portfolio

Contact

 LinkedIn: https://ca.linkedin.com/in/kyledupreez

A: If you don't want to use z-index,
I think you need to re-order the sequence of DOM. Thus, move your navigation to the bottom, and add top: 0
http://plnkr.co/edit/53wQYQmvPR3fcdKfoZjI?p=preview
#nav-bar {
    width: 90%;
    height: 60px;
    background-color: white;
    opacity: 0.8;
    position: fixed;
    top: 0;
    box-shadow: 0 4px 10px -2px rgba(0,0,0,0.1);
    z-index: 0;
}


text:
Q: How to know if a plant has fully grown? I have a BlockBreakEvent and need to know if the breaked block is a fully grown wheat seed.
My code so far is:
@EventHandler
public void onBreak(BlockBreakEvent e) {
    Player player = e.getPlayer();
    String name = player.getName();
    if (e.getBlock().getType() == Material.WHEAT) {
        // ...
    }

}

Right now my if is also entered when the  block is not fully grown yet. So how can I edit this condition to also check for the seed being fully grown?
I am using CraftBukkit 1.15.2.

A: You can read the "age" like this:
final Ageable ageable = (Ageable) event.getClickedBlock().getState().getBlockData();
if (ageable.getAge() == 7)
{
    // wheat is full grown.
};

I got the information from this page but wanted to preserve it here in case the link dies.


text:
Q: Boost.Asio HTTP Server Session Closing I have a http server based on Boost.Asio Example HTTP Server 2 (using an io_service-per-CPU design)
Each Request gets parsed, checked if it's a POST-Request, if Path is correct, if Content-Length Header is present, if one of these conditions is not correct, I generate a Bad-Request Response.
As everything is okay, I send a OK Response.
That's how it gets started.
int main(int argc, char* argv[])
{
  try
  {
    http::server s("127.0.0.1", "88", 1024);
    s.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }
  return 0;
}

Now I made a quick C# app which starts 16 Threads and each Thread sends continuously in a while(true)-Loop POST-Requests to this server.
A while it runs smoothly and fast. Then at some point of time the server gets unresponsive (Cannot connect to remote server).
A cause for this could be that the sessions from the server don't get closed properly.
Here's the code for Bad-Request/OK Responses:
void session::handle_request()
{
  //Generate OK Response
  reply_ = reply::stock_reply(reply::ok);
  //Send OK Response
  boost::asio::async_write(client_socket_, reply_.to_buffers(),
    boost::bind(&session::handle_client_write, shared_from_this(),
      boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));
}

void session::send_bad_request()
{
  //Generate Bad Request Response
  reply_ = reply::stock_reply(reply::bad_request);
  //Send Bad Request Response
  boost::asio::async_write(client_socket_, reply_.to_buffers(),
    boost::bind(&session::handle_client_write, shared_from_this(),
      boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));
}

And the handle_client_write which both trigger:
void session::handle_client_write(const boost::system::error_code& err, size_t len)
{
  if (!err) {
    //Dummy Error Code Var
    boost::system::error_code ignored_ec;
    //Shutdown socket
    client_socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
    client_socket_.close();
    //std::cout << "Closed" << ignored_ec.message() << "\n";
  }
  else {
    std::cout << "Error: " << err.message() << "\n";
  }
}

Like I said, at some point it gets unresponsive and after little time it responses again.


text:
Q: best way to statistically detect anomalies in data our webapp collects huge amount of data about user actions, network business, database load, etc etc etc
All data is stored in warehouses and we have quite a lot of interesting views on this data.
if something odd happens chances are, it shows up somewhere in the data.
However, to manually detect if something out of the ordinary is going on, one has to continually look through this data, and look for oddities.
My question: what is the best way to detect changes in dynamic data which can be seen as 'out of the ordinary'.
Are bayesan filters (I've seen these mentioned when reading about spam detection) the way to go?
Any pointers would be great!
EDIT:
To clarify the data for example shows a daily curve of database load.
This curve typically looks similar to the curve from yesterday
In time this curve might change slowly.
It would be nice that if the curve from day to day changes say within some perimeters, a warning could go off.
R

A: Take a look at Control Charts, they provide a way to track changes in your data visually and specify when the data is "out of control" or "anomalous".  They are heavily used in manufacturing to ensure quality control.

A: This question is impossible to answer without knowing much more about the particular data  you have. For an overview of what kinds of approaches exist, see Anomaly Detection: A Survey by Chandola, Banerjee, and Kumar.

A: This depends so much on what the data is. Take a statistics class and learn the basics first. This isn't usually an easy or simple problem.

A: Bayesian classification might help you find some anomalies in your data, depending on the type of data and how good you train your Bayesian filter.
There is even one available as a web service @ uClassify.com.


text:
Q: Perforce Checkpoint Notification We have a job scheduled in crontab that does create a nightly checkpoint; however, we want to notify a DL or group as soon as a new checkpoint file, "p4_1.ckp.XXXX.gz," is added under "/p4/1/checkpoints."
I appreciate your help.


text:
Q: RNN implementation about time series using python I want to develop an RNN model with one layer and LSTM to forecasting the next day and the next 30 days. The data is from 2014 to 2019 and the head of data is in the image below.enter image description here. I am using the daily_count column to predict the number of incidents for next day of this column.
The code to predict the next day is this:
train_size=int(0.8*len(data_rnn)) #80-20 split
data_train=data_rnn.iloc[:train_size,1].values
data_test=data_rnn.iloc[train_size:,1].values

scaler = MinMaxScaler()
data_train = scaler.fit_transform(data_train.reshape(-1, 1))

x_training_data = []
y_training_data =[]

for i in range(30, len(data_train)): #look back=30 days
   x_training_data.append(data_train[i-30:i, 0])

   y_training_data.append(data_train[i, 0])

x_training_data = np.array(x_training_data) #shape=(863,30)
y_training_data = np.array(y_training_data) #shape=(863,)

x_training_data = np.reshape(x_training_data, (x_training_data.shape[0],
                                           x_training_data.shape[1],
                                           1))

rnn = Sequential()
rnn.add(LSTM(units = 45, return_sequences = False, input_shape =
 (x_training_data.shape[1], 1))) #45 neurons
rnn.add(Dropout(0.2))
rnn.add(Dense(units = 1))
rnn.compile(optimizer = 'adam', loss = 'mape')
rnn.fit(x_training_data, y_training_data, epochs = 100, batch_size = 32)

unscaled_training_data =data_rnn.iloc[:train_size,1]
unscaled_test_data = data_rnn.iloc[train_size:,1]
all_data=data_rnn.iloc[:,1]

x_test_data = all_data[len(all_data) - len(data_test) - 30:].values

x_test_data = np.reshape(x_test_data, (-1, 1))
x_test_data = scaler.transform(x_test_data)

final_x_test_data = []

for i in range(30, len(x_test_data)):

    final_x_test_data.append(x_test_data[i-30:i, 0])

final_x_test_data = np.array(final_x_test_data)

final_x_test_data = np.reshape(final_x_test_data, (final_x_test_data.shape[0],
                                           final_x_test_data.shape[1], 1))
predicts = rnn.predict(final_x_test_data) #predictions

Because I am new in deep learning I have some questions.
A) The above code is complete to forecasting the next day of the data or does need some additions?
B) To predict the next 30 days what I must change in the code?
C) For the same data, I have created an XGBoost model with 40 features such as the month, the day of the month, weekday, the max temperature of the day, number of incidents for previous days, etc. Can I use these in the RNN model as input to improve the performance of the model and if yes, what changes I must do in the code with a total of 40 features without the daily_count column.
D) Any advice I would appreciate.
Thanks in advance.


text:
Q: Manually add providers for jaxb in a resteasy application I have a rest application where I am using resteasy and jaxb to produce json output
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("/data")
public MyResponse getData {
    return new MyResponse("my response"); // Just stubbing this
}

@XmlRootElement(name = "response")
@JsonInclude(Include.NON_NULL)
public class MyResponse {
    private String data;

    public MyResponse(String data) {
        this.data = data;
    }
    public String getData() {
        return data;
    }
    public void setData(String data) {
        this.data = data;
    }
}

I am not using the web.xml but creating a RestApplication which extends Application and overriding the getSingletons and getClasses method.
Now I am not sure which jaxb provider classes I need to add to make the above working, I mean to do the json serialization.
I get the following error
Could not find MessageBodyWriter for response object of type:MyResponse of media type: application/json

Could you let me know which  classes I need to add manually(the providers) to make this work?


text:
Q: Combine or merge JSON on node.js without jQuery I have multiple JSON like those
var object1 = {name: "John"};
var object2 = {location: "San Jose"};

They are not nesting or anything like that. Just basically different fields. I need to combine them into one single JSON in node.js like this:
{name: "John", location: "San Jose"}

I can use jQuery just fine. Here is a working example in the browser:
http://jsfiddle.net/qhoc/agp54/
But if I do this in node.js, I don't want to load jQuery (which is a bit over use, plus node.js' jQuery doesn't work on my Windows machine).
So is there a simple way to do things similar to $.extend() without jQuery?

A: If using Node version >= 4, use Object.assign() (see Ricardo Nolde's answer).
If using Node 0.x, there is the built in util._extend:
var extend = require('util')._extend
var o = extend({}, {name: "John"});
extend(o,  {location: "San Jose"});

It doesn't do a deep copy and only allows two arguments at a time, but is built in.  I saw this mentioned on a question about cloning objects in node: https://stackoverflow.com/a/15040626.
If you're concerned about using a "private" method, you could always proxy it:
// myutil.js
exports.extend = require('util')._extend;

and replace it with your own implementation if it ever disappears.  This is (approximately) their implementation:
exports.extend = function(origin, add) {
    if (!add || (typeof add !== 'object' && add !== null)){
        return origin;
    }

    var keys = Object.keys(add);
    var i = keys.length;
    while(i--){
        origin[keys[i]] = add[keys[i]];
    }
    return origin;
};

A: Underscore's extend is the easiest and quickest way to achieve this, like James commented.
Here's an example using underscore:
var _ = require('underscore'), // npm install underscore to install
  object1 = {name: "John"},
  object2 = {location: "San Jose"};

var target = _.extend(object1, object2);

object 1 will get the properties of object2 and be returned and assigned to target.
You could do it like this as well, depending on whether you mind object1 being modified:
var target = {};
_.extend(target, object1, object2);

A: There is an easy way of doing it in Node.js
var object1 = {name: "John"};
var object2 = {location: "San Jose"};

To combine/extend this we can use ... operator in ECMA6

var object1 = {name: "John"};
var object2 = {location: "San Jose"};

var result = {
  ...object1,
  ...object2
}

console.log(result)

A: A normal loop?
function extend(target) {
    var sources = [].slice.call(arguments, 1);
    sources.forEach(function (source) {
        for (var prop in source) {
            target[prop] = source[prop];
        }
    });
    return target;
}

var object3 = extend({}, object1, object2);

That's a basic starting point. You may want to add things like a hasOwnProperty check, or add some logic to handle the case where multiple source objects have a property with the same identifier.
Here's a working example.
Side note: what you are referring to as "JSON" are actually normal JavaScript objects. JSON is simply a text format that shares some syntax with JavaScript.

A: You can also use this lightweight npm package called absorb
It is 27 lines of code, 1kb and uses recursion to perform deep object merges.
var absorb = require('absorb');
var obj1, obj2;

obj1 = { foo: 123, bar: 456 };
obj2 = { bar: 123, key: 'value' }

absorb(obj1, obj2);

console.log(obj1); // Output: { foo: 123, bar: 123, key: 'value' }

You can also use it to make a clone or only transfer values if they don't exist in the source object, how to do this is detailed in the link provided.

A: It can easy be done using Object.assign() method -
 var object1 = {name: "John"};
 var object2 = {location: "San Jose"};
 var object3 = Object.assign(object1,object2);
 console.log(object3);

now object3 is { name: 'John', location: 'San Jose' }

A: Use spread operator. It is supported in Node since version 8.6

const object1 = {name: "John"};
const object2 = {location: "San Jose"};

const obj = {...object1, ...object2}

console.log(obj)
//   {
//     "name": "John",
//     "location": "San Jose"
//   }

A: If you need special behaviors like nested object extension or array replacement you can use Node.js's extendify.
var extendify = require('extendify');

_.extend = extendify({
    inPlace: false,
    arrays : 'replace',
    isDeep: true
});

obj1 = {
    a:{
        arr: [1,2]
    },
    b: 4
};

obj2 = {
    a:{
        arr: [3]
    }
};

res = _.extend(obj1,obj2);
console.log(JSON.stringify(res)); //{'a':{'arr':[3]},'b':4}

A: Lodash is a another powerful tool-belt option for these sorts of utilities.  See: _.merge() (which is recursive)
var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};
_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

A: Use merge.
$ npm install merge

Sample code:
var merge = require('merge'), // npm install -g merge
    original, cloned;

console.log(

    merge({ one: 'hello' }, { two: 'world' })

); // {"one": "hello", "two": "world"}

original = { x: { y: 1 } };

cloned = merge(true, original);

cloned.x.y++;

console.log(original.x.y, cloned.x.y); // 1, 2

A: You should use "Object.assign()"
There's no need to reinvent the wheel for such a simple use case of shallow merging.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj);       // { a: 1, b: 2, c: 3 }
console.log(o1);        // { a: 1, b: 2, c: 3 }, target object itself is changed
console.log(obj === o1) // true

Even the folks from Node.js say so:

_extend was never intended to be used outside of internal NodeJS modules. The community found and used it anyway.
It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign.

Update:
You could use the spread operator
Since version 8.6, it's possible to natively use the spread operator in Node.js. Example below:
let o1 = { a: 1 };
let o2 = { b: 2 };
let obj = { ...o1, ...o2 }; // { a: 1, b: 2 }

Object.assign still works, though.

**PS1**: If you are actually interested in **deep merging** (in which internal object data -- in any depth -- is recursively merged), you can use packages like [deepmerge][4], [assign-deep][5] or [lodash.merge][6], which are pretty small and simple to use.

**PS2**: Keep in mind that **Object.assign doesn't work with 0.X versions of Node.js**. If you are working with one of those versions (_you really shouldn't by now_), you could use `require("util")._extend` as shown in the Node.js link above -- for more details, check [tobymackenzie's answer to this same question](https://stackoverflow.com/a/22286375/36272).

A: I see that this thread is too old, but I put my answer here just in logging purposes.

In one of the comments above you mentioned that you wanted to use
  'express' in your project which has 'connect' library in the
  dependency list. Actually 'connect.utils' library contains a 'merge'
  method that does the trick. So you can use the 3rd party
  implementation without adding any new 3rd party libraries.

A: Here is simple solution, to merge JSON.
I did the following.

*

*Convert each of the JSON to strings using JSON.stringify(object).

*Concatenate all the JSON strings using + operator.

*Replace the pattern /}{/g with ","

*Parse the result string back to JSON object
var object1 = {name: "John"};
var object2 = {location: "San Jose"};
var merged_object = JSON.parse((JSON.stringify(object1) + JSON.stringify(object2)).replace(/}{/g,","))

The resulting merged JSON will be
{name: "John", location: "San Jose"}

A: The below code will help you to merge two JSON object which has nested objects.
function mergeJSON(source1,source2){
    /*
     * Properties from the Souce1 object will be copied to Source2 Object.
     * Note: This method will return a new merged object, Source1 and Source2 original values will not be replaced.
     * */
    var mergedJSON = Object.create(source2);// Copying Source2 to a new Object

    for (var attrname in source1) {
        if(mergedJSON.hasOwnProperty(attrname)) {
          if ( source1[attrname]!=null && source1[attrname].constructor==Object ) {
              /*
               * Recursive call if the property is an object,
               * Iterate the object and set all properties of the inner object.
              */
              mergedJSON[attrname] = zrd3.utils.mergeJSON(source1[attrname], mergedJSON[attrname]);
          }

        } else {//else copy the property from source1
            mergedJSON[attrname] = source1[attrname];

        }
      }

      return mergedJSON;
}

A: You can use Lodash
const _ = require('lodash');

let firstObject = {'email' : 'email@email.com};
let secondObject = { 'name' : { 'first':message.firstName } };
_.merge(firstObject, secondObject)

A: A better approach from the correct solution here in order to not alter target:
function extend(){
  let sources = [].slice.call(arguments, 0), result = {};
  sources.forEach(function (source) {
    for (let prop in source) {
      result[prop] = source[prop];
    }
  });
  return result;
}

A: You can do it inline, without changing any variables like this:
let obj1 = { name: 'John' };
let obj2 = { surname: 'Smith' };
let obj = Object.assign({}, obj1, obj2); // { name: 'John', surname: 'Smith' }

A: Let object1 and object2 be two JSON object.
var object1 = [{"name": "John"}];
var object2 = [{"location": "San Jose"}];

object1.push(object2);

This will simply append object2 in object1:
[{"name":"John"},{"location":"San Jose"}]


text:
Q: Print output until key pressed This seems like a simple problem, but I can't seem to solve it. I need to print output (from a variable) to the console, until the user presses any key. The printing is done in a while loop as such:
int i;
while((i=input.read())!=-1){
  System.out.print((char)i);
}
input.close();

The problem is that the input stream never reaches it's end, only waits for more characters to come in, thus blocking any more code from executing. It will be quite obvious to the user when to stop the output, so I am fine with giving that responsibility to the user. It doesn't matter how the user tells the application to stop, as long as it is quick, (eg pressing space, enter, or any other specific key is fine).
Thanks in advance,
vikarjramun

A: The first solution I came up with was threading the console input. The thread updates a variable accessable by the printing code so you can check it before each print statement.
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;

public class RunUntilKeyPressed {
    static AtomicBoolean hasUserPressedKey = new AtomicBoolean(false);

    public static void main(String[] args) {

        Thread t = new Thread(() -> {
            Scanner scan = new Scanner(System.in);
            System.out.println(scan.next());
            hasUserPressedKey.set(true);
            scan.close();
        });
        t.start();

        while(!hasUserPressedKey.get()) {
           System.out.println(hasUserPressedKey);
        }
    }
}

This code will run until the user presses Any Key (except space) and Enter as that is when the scan.next() method gets input.


text:
Q: Remove permalink from images when inserting into post In previous versions of WP, we were able to remove permalink from images while we were inserting images into post.
But now there is no obvious option to do so. How can it be achieved?

A: When you insert an image to the post you see Add media modal dialog. It has a field named Link URL with three buttons underneath, including None to remove the link.
Screenshot:

A: When inserting images into posts and pages in WP 4.4, change the Link To under ATTTACHMENT DISPLAY SETTINGS to None.

A: I found this plugin to add an option to use an external link: http://wordpress.org/extend/plugins/wp-gallery-custom-links/screenshots/


text:
Q: Testing Spring Boot REST json result I have some problem with checking json result
UserControllerTest class
package com.serwis.controller;

import com.serwis.PraktykiApplication;
import com.serwis.model.User;
import com.serwis.repository.UserRepository;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.RestTemplate;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(PraktykiApplication.class)
@WebIntegrationTest
public class UserControllerTests {

    @Autowired
    private UserRepository userRepository;

    User user;

    private MockMvc mockMvc;

    @Before
    public void setUp(){
        user = new User("login1","password","email");
        userRepository.deleteAll();
        userRepository.save(user);

        this.mockMvc = standaloneSetup(new UserController()).build();
    }

    @Test
    public void createUser() throws Exception {
        this.mockMvc.perform(get("/user/findall/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.login", is("login1")));
        System.out.println(userRepository.findAll());
    }

}

User class
package com.serwis.model;

import javax.persistence.*;

import java.util.Arrays;
import java.util.Set;

@Entity
@Table(name="User")
public class User {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(name="id")
    private long id;

    @Column(name="login")
    private String login;

    @Column(name="password")
    private String password;

    @Column(name="email")
    private String email;

    @Column(name="avatar")
    private byte[] avatar;

    public User(){}

    public User(String login, String password, String email) {
        this.login = login;
        this.password = password;
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", login='" + login + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", avatar=" + Arrays.toString(avatar) +
                '}';
    }

    public long getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public byte[] getAvatar() {
        return avatar;
    }

    public void setAvatar(byte[] avatar) {
        this.avatar = avatar;
    }

}

UserRepository class
package com.serwis.repository;

import com.serwis.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public interface UserRepository extends CrudRepository<User, Long>{
}

userController class
package com.serwis.controller;

import com.serwis.model.User;
import com.serwis.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Jodanpotasu on 2016-07-24.
 */
@Controller
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/user/create")
    @ResponseBody
    public String create(String email, String login, String password) {
        String userId = "";
        try {
            User user = new User(email, login, password);
            userRepository.save(user);
            userId = String.valueOf(user.getId());
        } catch (Exception ex) {
            return "Error creating the user: " + ex.toString();
        }
        return "User succesfully created with id = " + userId;
    }

    @RequestMapping("/user/findall/")
    @ResponseBody
    public Iterable<User> findAll() {
        return userRepository.findAll();
    }

    @RequestMapping("/user/delete")
    @ResponseBody
    public String delete(long id) {
        User deleted = userRepository.findOne(id);
        userRepository.delete(id);
        return "USER DELETED: " + deleted;
    }

    @RequestMapping("/user/update")
    @ResponseBody
    public String update(long id, String login, String password, String email) {
        User beforeUpdate = userRepository.findOne(id);

        User afterUpdate = userRepository.findOne(id);
        afterUpdate.setLogin(login);
        afterUpdate.setEmail(email);
        afterUpdate.setPassword(password);
        return "BEFORE UPDATE: \n" + beforeUpdate + " <br> AFTER UPDATE: " + afterUpdate;
    }
}

it should be like

[{"id":1,"login":"login1","password":"password","email":"email","avatar":null}]

But i still have error output
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

and that is full output
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at com.serwis.controller.UserControllerTests.createUser(UserControllerTests.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:253)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.NullPointerException
    at com.serwis.controller.UserController.findAll(UserController.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
    ... 43 more

Spring boot version: 1.3.6 is there another better way to test json?

A: Here is my working class
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(PraktykiApplication.class)
@WebIntegrationTest
public class UserControllerTests {

    @Autowired
    private UserRepository userRepository;

    User user;

    private MockMvc mockMvc;

    @Autowired
    UserController userController;

    @Before
    public void setUp(){
        user = new User("login1","password","email");
        userRepository.deleteAll();
        userRepository.save(user);

        this.mockMvc = standaloneSetup(userController).build();
    }

    @Test
    public void createUser() throws Exception {
        this.mockMvc.perform(get("/user/findall/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$[0].login", is("login1")));
        System.out.println(userRepository.findAll());
    }
}

it seems that spring boot did not see
this.mockMvc = standaloneSetup(new UserController()).build();


text:
Q: Convert outerXml to OpenXmlElement I know how to convert an OpenXmlElement to outer xml by using the OpenXmlElement.OuterXml function but is it possible to do the opposite without knowing what kind of OpenXmlElement it's going to be?
For example I have the outerXml of a table, paragraph and run.  Then is it possible to do something like:
new OpenXmlElement(unknownXml)

I saw the constructor of the OpenXmlElement is kept protected.
I'm not asking for any dirty switch statements or something like that.
---------------- Edit ------------------
I have come up with my own solution.  I've created a library that does the conversion without using a dirty switch statement :-)
The library can be found here: https://github.com/LucBos/OpenXmlFactory
The usage of the library is described here: http://www.lucbos.net/2012/01/reconstructing-openxml-element-from-xml.html

A: You can make a generic OpenXmlElement by reading a stream from an XElement into a new OpenXmlElement. However, afik there isn't a clean way to get the appropriate type.


text:
Q: How to calculate percentage of column using pandas pivot_table() I am attempting to get the frequency of objects per version expressed as a percentage.
Input dfsof = pd.read_clipboard()
file     version     object
path1    1.0         name
path1    1.0         session
path1    1.0         sequence
path2    2.01        name
path2    2.01        session
path2    2.01        sequence
path3    2.01        name
path3    2.01        session
path3    2.01        earthworm

Using the following, I am able to get frequency of each file.
dfsof.pivot_table(index=['object'], values=['file'], columns=['version'], aggfunc=len, fill_value=0, margins=True)
             file
version      1.0    2.01    All
object
 earthworm   0      1       1
 name        1      2       3
 sequence    1      1       2
 session     1      2       3
All          3      6       9

I want to divide each count per object/version by the total number of distinct files for that version. Using the expected return table as an example, earthworms shows up in the input only once for version 2.01, so I expect 0% for version 1.0 and 50% for version 2.01 since only one of the files has that value.
Using dfsof.groupby('version')['file'].nunique() returns the frequency of files per version, which is the denominator for each of object/version in the table above. What I am struggling with is how to apply the denominator values to the pivot_table. I have seen examples of this using grand totals and subtotals but I can't seem to find nor figure out how to divide by the unique number of files per version. Any help would be greatly appreciated.
version
1.00    1
2.01    2

Expected return
             path
version      1.0    2.01    All
object
 earthworm   0%     50%     1
 name        100%   100%    3
 sequence    100%   50%     2
 session     100%   100%    3
All          3      6       9

A: IIUC, you need to aggregate as 'nunique', then perform some recomputation:
# aggregate using nunique
out = dfsof.pivot_table(index=['object'], values=['file'], columns=['version'],
                        aggfunc='nunique', fill_value=0, margins=True)

# compute and save sum of nunique
All = out.iloc[:-1].sum()
# update values as percentage
out.update(out.iloc[:-1, :-1].div(out.iloc[-1, :-1]).mul(100))

# assign sum of nunique
out.loc['All'] = All

print(out)

Output:
            file
version      1.0   2.01 All
object
earthworm    0.0   50.0   1
name       100.0  100.0   3
sequence   100.0   50.0   2
session    100.0  100.0   3
All          3.0    6.0   9