text:
Q: How to copy a directory recursively using hardlinks for each file I want to create a "copy" of a directory tree where each file is a hardlink to the original file
Example: I have a directory structure:
dirA/
dirA/file1
dirA/x/
dirA/x/file2
dirA/y/
dirA/y/file3

Here is the expected result, a "copy" of the directory tree where each file is a hardlink to the original file:
dirB/            #  normal directory
dirB/file1       #  hardlink to dirA/file1
dirB/x/          #  normal directory
dirB/x/file2     #  hardlink to dirA/x/file2
dirB/y/          #  normal directory
dirB/y/file3     #  hardlink to dirA/y/file3

A: On Linux (more precisely with the GNU and busybox implementations of cp as typically found on systems that have Linux as a kernel) and recent FreeBSD, this is how:
cp -al dirA dirB

For a more portable solution, see answer using pax and cpio by Stéphane Chazelas

A: rsync -av --link-dest="$PWD/dirA" dirA/ dirB
If you happen to have rsync already installed this one is a quick simple command. To cope with symlinks you may want to choose among --links, --copy-links, --copy-unsafe-links or --safe-links
From the rsync man page:
--link-dest=DIR         hardlink to files in DIR when unchanged
 -l, --links                 copy symlinks as symlinks
 -L, --copy-links            transform symlink into referent file/dir
--copy-unsafe-links     only "unsafe" symlinks are transformed
--safe-links            ignore symlinks that point outside the tree

Edit:

*

*Fixed the command after the comment by @MichaelR. Thank you!

*Tested as follows on MacOS using rsync 2.6.9

$ cd /tmp && rm -rf a b; mkdir a && touch a/c && echo "xxx" > a/c && rsync -av --link-dest="$PWD/a" a/ b;
$ ls -lR a b
building file list ... done
created directory b
./

sent 74 bytes  received 26 bytes  200.00 bytes/sec
total size is 4  speedup is 0.04
a:
total 8
-rw-r--r--  2 user  wheel  4 Aug 26 16:09 c

b:
total 8
-rw-r--r--  2 user  wheel  4 Aug 26 16:09 c

A: POSIXly, you'd use pax in read+write mode with the -l option:
pax -rwlpe -s /A/B/ dirA .

(-pe preserves all possible attributes of files (in this case only directories) that are copied, like GNU cp's -a does).
Now, though standard, that command is not necessarily very portable.
First, many GNU/Linux-based systems don't include pax by default (even though that's a non-optional POSIX utility).
Then, a number of bugs and non-conformances with a few implementations cause a number of issues with that code.

*

*because of a bug, Solaris 10 pax (at least) doesn't work when using -rwl in combination with -s. For some reason, it seems it applies the substitution to both the original and copied path. So above, it would attempt to do some link("dirB/file", "dirB/file") instead of link("dirA/file", "dirB/file").

*on FreeBSD, pax doesn't create hardlinks for files of type symlink (a behaviour allowed by POSIX). Not only that, but it also applies the substitution to the targets of the symlinks (a behaviour not allowed by POSIX). So for instance if there's a foo -> AA symlink in dirA, it will become foo -> BA in dirB.

Also, if you want to do the same but with arbitrary file paths whose content is stored in $src and $dst, it's important to realise that pax -rwl -- "$src" "$dst" creates the full directory structure of $src inside $dst (that has to exist and be a directory). For instance, if $src is foo/bar, then, $dst/foo/bar is created.
If instead, you want $dst to be a copy of $src, the easiest is probably to do it as:
absolute_dst=$(umask 077 && mkdir -p -- "$dst" && cd -P -- "$dst" && pwd -P) &&
(cd -P -- "$src" && pax -rwlpe . "$absolute_dst")

(which would also work around most of the problems mentioned above but would fail if the absolute path of $dst ends in newline characters).
Now that won't help on GNU/Linux systems where there's no pax.
It's interesting to note that pax was created by POSIX to merge the features of the tar and cpio commands.
cpio is a historical Unix command (from 1977) as opposed to a POSIX invention, and there is a GNU implementation as well (not a pax one). So even though it is no longer a standard command (it was in SUSv2 though), it is still very common, and there's a core set of features you can usually rely on.
The equivalent of pax -rwl would be cpio -pl. However:

*

*cpio takes the list of input file on stdin as opposed to arguments (newline delimited which means file names with newline characters are not supported)

*All files have to be specified (typically you feed it the output of find (find and cpio were developed jointly by the same people)).

*metadata are not preserved (some cpio implementations have options to preserve some, but nothing portable).

So with cpio:
absolute_dst=$(umask 077 && mkdir -p -- "$dst" && cd -P -- "$dst" && pwd -P) &&
(cd -P -- "$src" && find . | cpio -pl "$absolute_dst")

A: In case you are looking for that copy-with-hardlinks feature to make snapshots or backups of (all or part of) your files have a look at rsnapshot.

A: Short answer:
cd $source_folder
pax -rwlpe . $dest_folder

A: @gudmundur-orn's answer is correct, but if you are on BtrFS on Linux cp a --reflink=auto dirA dirB should do the trick, with the difference the files are actually different and changing one doesn't change the other. You can achieve mostly the same with cp -c on a Mac with APFS (auto will do a full copy if not possible, -c will fail).
Any COW file system should be able to do that, but vendors haven't agreed on a standard command line option.


text:
Q: ValueError: Max Value is 52 - Issue with destination excel file So I have hit a wall. I am trying to use Openpyxl to move date from one excel sheet to another, and get his error. For the life of me I can not figure out what I am doing wrong, or a work around to fix it. It seems to be an issue with the destination workbook I am loading. When I use a new empty file it works fine. Any help would be appreciated.
  File "C:\Users\ron\Documents\Python\AndreaMilage2.py", line 43, in <module>
    dest_wb = load_workbook('Destination.xlsx')
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
    reader.read()
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 280, in read
    self.read_worksheets()
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 255, in read_worksheets
    charts, images = find_images(self.archive, rel.target)
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\drawings.py", line 27, in find_images
    drawing = SpreadsheetDrawing.from_tree(tree)
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\descriptors\serialisable.py", line 87, in from_tree
    obj = desc.expected_type.from_tree(el)
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\descriptors\serialisable.py", line 87, in from_tree
    obj = desc.expected_type.from_tree(el)
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\descriptors\serialisable.py", line 87, in from_tree
    obj = desc.expected_type.from_tree(el)
  [Previous line repeated 4 more times]
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\descriptors\serialisable.py", line 103, in from_tree
    return cls(**attrib)
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\drawing\text.py", line 115, in __init__
    self.pitchFamily = pitchFamily
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\descriptors\base.py", line 108, in __set__
    super(Min, self).__set__(instance, value)
  File "C:\Users\ron\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\descriptors\base.py", line 87, in __set__
    raise ValueError('Max value is {0}'.format(self.max))
ValueError: Max value is 52

~~~
from openpyxl import load_workbook
from openpyxl import Workbook
trips = int(input('How many trips?'))

#Load Workbooks and read sheets
src_wb = load_workbook('Source.xlsx')
dest_wb = load_workbook('Destination.xlsx')

src_sheet = src_wb["Trips"]
dest_sheet = dest_wb["Mileage"]

#Importing Date
for i in range(1,trips+1):
    dest_sheet.cell(row=i+7, column=1).value = src_sheet.cell(row=i+23, column=5).value
#Importing Start
for i in range(1,trips+1):
    dest_sheet.cell(row=i+7, column=2).value = src_sheet.cell(row=i+23, column=3).value
#Importing End
for i in range(1,trips+1):
    dest_sheet.cell(row=i+7, column=4).value = src_sheet.cell(row=i+23, column=4).value
#Importing Notes
for i in range(1,trips+1):
    dest_sheet.cell(row=i+7, column=5).value = src_sheet.cell(row=i+23, column=9).value
#Importing Miles
for i in range(1,trips+1):
    dest_sheet.cell(row=i+7, column=10).value = src_sheet.cell(row=i+23, column=2).value

src_wb.save('Source.xlsx')
dest_wb.save('Destination.xlsx')
~~~

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove previous price of products I am using magento 1.9 , i want to know how to remove the previous strikethrough  price of products as shown here https://prnt.sc/orfv5b

A: The strikethrough price is the product price and the other price shown on the page is the discounted price.
If you don't want to show the strikethrough price, then:

*

*Copy the special price

*Put it into the price field

*Remove the value from the special price field

*Save the product

Screenshots attached for reference:

*

*https://nimb.ws/q8Q0Gs

*https://nimb.ws/t2aZ1Y


text:
Q: Is there a way to apply cell format in xlswriter without setting a value? Is there a way to apply cell format in xlswriter without setting a value? And in terms of worksheet.write use of A1 notation, can it be done to a range?
Like:
format = workbook.add_format()
format.set_border(1)
format.set_bold()
worksheet.write(row=0, col=0, format=format)
worksheet.write('A1:C3', format=format)

A: Using worksheet.write() you can not specify a range.  You can put it inside a loop and make use of xlsxwriter.utility.xl_rowcol_to_cell() which would achieve what you're looking for. Here is further explanation and examples involving xlsxwriter.utility.xl_rowcol_to_cell() from xlsxwriter docs.
Also you can format blank cells by entering "" as the second argument in worksheet.write().  I've provided a full working example below along with an image of the expected output.
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

format = workbook.add_format()
format.set_border(1)
format.set_bold()
format.set_bg_color("blue")
format.set_num_format('#,##0')

for i in range (0, 3):
    #we're looping through columns
    for j in range (0, 3):
    #we're looping through rows
        cell_reference = xl_rowcol_to_cell(i, j, row_abs=True, col_abs=True)
        worksheet.write('%s' % (cell_reference), "" ,format)

workbook.close()


text:
Q: why the traefik did not match the url by the path I am using traefik 2.2.1 as my kubernetes ingress controller. Now I have a url need to forward, this is my traefik config right now:
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  creationTimestamp: '2021-09-26T09:10:02Z'
  generation: 4
  name: uat-zhuolian-manage-route
  namespace: dabai-uat
  resourceVersion: '106700291'
  selfLink: >-
    /apis/traefik.containo.us/v1alpha1/namespaces/dabai-uat/ingressroutes/uat-zhuolian-manage-route
  uid: d0b82fab-cd6a-49f0-96dc-f6c0f381bcc5
spec:
  entryPoints:
    - web
  routes:
    - kind: Rule
      match: Host(`zhuolian-pro-manage.example.com`)
      services:
        - name: be-zhuolian-frontend
          port: 80
    - kind: Rule
      match: Host(`zhuolian-pro-manage.example.com`) && Path(`/service`)
      services:
        - name: soa-zhuolian-service
          port: 11032

what I want the traefik to do is that forward the example.com to be-zhuolian-frontend by default. If the request url contains service, for example the url xxx.example.com/service/foo/bar, forward to the backend service soa-zhuolian-service. but now when I request to the url from remote cloud host:
curl --header 'Host:zhuolian-pro-manage.example.com' http://172.19.104.230/service/zhuolian/report/user/captcha -L

shows error:
[root@fat001 ~]# curl --header 'Host:zhuolian-pro-manage.example.com' http://172.19.104.230/service/zhuolian/report/user/captcha -L

<title>404 Not Found</title>

404 Not Found

nginx/1.19.0

it seems the url with service keywords still route to the frontend service, what should I do to fix this problem and make the service match to the backend service successfully?

A: use PathPrefix not path, from official document:

Use Path if your service listens on the exact path only. For instance,
Path: /products would match /products but not /products/shoes.
Use a Prefix matcher if your service listens on a particular base
path but also serves requests on sub-paths. For instance, PathPrefix:
/products would match /products but also /products/shoes and
/products/shirts. Since the path is forwarded as-is, your service is
expected to listen on /products.

so tweak the config like this:
spec:
  entryPoints:
    - web
  routes:
    - kind: Rule
      match: Host(`zhuolian-pro-manage.example.com`) && PathPrefix(`/service`)
      middlewares:
        - name: service-stripprefix
      services:
        - name: soa-zhuolian-service
          port: 11032
    - kind: Rule
      match: Host(`zhuolian-pro-manage.example.com`)
      services:
        - name: be-zhuolian-frontend
          port: 80


text:
Q: why kubernetes dashboard service return json I am access my kubernetes dashboard using this url:
https://kubernetes.example.com/api/v1/namespaces/kube-system/services/kubernetes-dashboard/#/workload?namespace=default

what make me confusing is the return content just json string, not the login page. The json content is :
   {
  "kind": "Service",
  "apiVersion": "v1",
  "metadata": {
    "name": "kubernetes-dashboard",
    "namespace": "kube-system",
    "selfLink": "/api/v1/namespaces/kube-system/services/kubernetes-dashboard",
    "uid": "884240d7-8f3f-41a4-a3a0-a89649545c82",
    "resourceVersion": "133822",
    "creationTimestamp": "2019-09-21T16:21:19Z",
    "labels": {
      "addonmanager.kubernetes.io/mode": "Reconcile",
      "k8s-app": "kubernetes-dashboard",
      "kubernetes.io/cluster-service": "true"
    },
    "annotations": {
      "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"annotations\":{},\"labels\":{\"addonmanager.kubernetes.io/mode\":\"Reconcile\",\"k8s-app\":\"kubernetes-dashboard\",\"kubernetes.io/cluster-service\":\"true\"},\"name\":\"kubernetes-dashboard\",\"namespace\":\"kube-system\"},\"spec\":{\"ports\":[{\"port\":443,\"targetPort\":8443}],\"selector\":{\"k8s-app\":\"kubernetes-dashboard\"},\"type\":\"NodePort\"}}\n"
    }
  },
  "spec": {
    "ports": [
      {
        "protocol": "TCP",
        "port": 443,
        "targetPort": 8443,
        "nodePort": 31085
      }
    ],
    "selector": {
      "k8s-app": "kubernetes-dashboard"
    },
    "clusterIP": "10.254.75.193",
    "type": "NodePort",
    "sessionAffinity": "None",
    "externalTrafficPolicy": "Cluster"
  },
  "status": {
    "loadBalancer": {

    }
  }
}

this is my nginx forward config:
upstream  kubernetes{
    server  172.19.104.231:8001;
}

this is my kubernetes cluster proxy command:
kubectl proxy --address=0.0.0.0 --port=8001 --accept-hosts='^*$'

A: You are accessing the Kubernetes API to get the kubernetes-dashboard Service resource manifest. This is the JSON that you get back.
If you want to access the Service, you need to access the Service itself, not the Kubernetes API. You can do this for example with port forwarding:
kubectl port-forward svc/kubernetes-dashboard 8443:443

And then access the Service with:
curl localhost:8443/#/workload?namespace=default

A: Kubernetes documentation has clearer instructions now on how to deploy and access their dashboard:

*

*https://kubernetes.io/docs/tasks/access-application-cluster/web-ui-dashboard/
I went to 127.0.0.1:8001 at first, and got the API JSON (as per the original question) before noticing the URL given under the kubectl proxy instruction:

*

*http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/.


text:
Q: Find the relative position of a famo.us Surface Is there a way to get the current position of a famo.us Surface?
I mean, after the render tree has done its thing and all modifiers have been multiplied, the surface exists somewhere on the screen. But I can't figure out how to just ask where. Seems a simple enough question.
Specifically, I'm building a kind of scroll view and need to test if a contained surface has moved outside of a bounding box.
It looks like the surface itself has a _matrix property that I could use, but this seems a crude way of doing it.
What am I missing?


text:
Q: how to do If button is pressed, a hardcoded message as an output into label How do I write a command as if a button is pressed there will be a specific sentence as an output to a label on an app.

A: Use this code:
-(IBAction)yourAction:(id)sender
{
    yourLabel.text = @"Button Pressed";
}

A: Here is Proper Controller Code Required
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,retain) UILabel *mylabel;
@property (nonatomic,retain) UIButton *myButton;

@end

@implementation ViewController

@synthesize mylabel,myButton;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    mylabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height*0.11, self.view.frame.size.width, 30)];
    mylabel.translatesAutoresizingMaskIntoConstraints=false;
    [mylabel setTextAlignment:NSTextAlignmentCenter];
    mylabel.text = @"Button Not Pressed";
    [self.view addSubview:mylabel];

    myButton = [[UIButton alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height*0.13, self.view.frame.size.width, 50)];
    myButton.translatesAutoresizingMaskIntoConstraints=false;
    [myButton setTitle:@"Button" forState:UIControlStateNormal];
    [myButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [myButton addTarget:self action:@selector(buttonHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myButton];

}

-(void) buttonHandler:(UIButton*)sender{
    mylabel.text = @"ButtonPressed";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Before Pressing button

After Pressing Button


text:
Q: Expected Value of Students on a Bus There's a question in my probability book that says there are $148$ students on $4$ buses containing $40, 33, 25, 50$ students, respectively. If we let $X$ denote the number of students that were on the bus that a randomly selected student was on. And we let $Y$ be the number of students on the bus of a randomly selected bus driver.
What is $E[X]$ and $E[Y]$?
This is an easy question to answer:
$E[X]=(40^2+33^2+25^2+50^2)(1/148)=39.28$ and $E[Y]=40(1/4)+33(1/4)+25(1/4)+50(1/4) =37$
So $E[X]>E[Y]$ which I wouldn't have guessed.

What's the intuition behind why these are different?

To me it seemed like these answers would be the same.

A: A randomly selected student is more likely to come from a bus with an above-average number of students than from a bus with a below-average number. A randomly selected driver, on the other hand, is equally likely to come from any bus. Thus, the distribution of $X$ is skewed upward from the mean number of students per bus.


text:
Q: Adding Anchor Tag Tracking to Google Universal Analytics I've read all 9 of the articles on SO, but none of them are working. My hope is that someone has a simple answer for this.
We have a site, www.fishales.com. It is a paralax, single page site with 6 different sections. By default, GA doesn't register any of the clicks to the anchor tags. So when you look at the GA dashboard, it shows super high bounce rate, exit rate because people get all the info from 1 page.
Here is what we have added directly before the end body tag:

AS for the menu links, this is the code:

beers

menu

events

Gallery

our story

contact

However, GA has completely stopped working since we implemented this. Any ideas oh wise ones?


text:
Q: How to count the number of objects detected with Template Matching? I was reading the docs about template matching with opencv and python and in the last part about template matching with multiple objects, the code detect the 19 coins on the mario image but, is it possible to count the number of objects detected with some function on python like len() or any opencv method?
Here is the code showed on the tutorial:
http://docs.opencv.org/3.1.0/d4/dc6/tutorial_py_template_matching.html
Template Matching Code:
import cv2
import numpy as np
from matplotlib import pyplot as plt

img_rgb = cv2.imread('mario.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('mario_coin.png',0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

cv2.imwrite('res.png',img_rgb)

And the result is:
Mario Bros & Coins
So, is there any way to count the coins detected on the image and print the number on the terminal?
Something like:
The Template Matching code showed before...

print "Function that detect number of coins with template matching"
>>> 19

A: I found a suitable solution (for my application) in counting unique matches as Ulrich suggested. It's not ideal, but playing with the "sensitivity" normally yields results within +/- 2% for my application.
import cv2
import numpy as np
from matplotlib import pyplot as plt

img_rgb = cv2.imread('mario.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('mario_coin.png',0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)

f = set()

for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

    sensitivity = 100
    f.add((round(pt[0]/sensitivity), round(pt[1]/sensitivity)))

cv2.imwrite('res.png',img_rgb)

found_count = len(f)

A: i made a list of all the matches and for every new match i check if there's an intersection with the bounding box any of the matches in the list:
res = cv.matchTemplate(image,template,cv.TM_CCOEFF_NORMED)
threshold = 0.5
loc = np.where(res >= threshold)
matches = []
for pt in zip(*loc[::-1]):
    intersection = 0
    for match in matches:
        if intersected(match, (match[0] + w, match[1] + h), pt, (pt[0] + w, pt[1] + h)):
            intersection = 1
            break
    if intersection == 0:
        matches.append(pt)
        rect = cv.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)

this is the code to check for an intersection:
def intersected(bottom_left1, top_right1, bottom_left2, top_right2):
    if top_right1[0] < bottom_left2[0] or bottom_left1[0] > top_right2[0]:
        return 0

    if top_right1[1] < bottom_left2[1] or bottom_left1[1] > top_right2[1]:
        return 0

    return 1

A: I used a list to store the very first (x,y) of many same object detections. Then for every (x,y) in the found detections(there must be many detections on the one same object), I calculate the distance between the new (x,y) and every points in the list. If the distance is large enough, it must be the first found of a new detection. Then I put the new (x,y)to the list. It is stupid but really works.
The purpose is to remove the points nearby the (x,y) of the first detection of an object and keep only one point of that 'group', then iterate all the points in loc to locate more 'groups' and find one and the only one point in every group.
import cv2
import numpy as np
import matplotlib.pyplot as plt
import math

def notInList(newObject):
    for detectedObject in detectedObjects:
        if math.hypot(newObject[0]-detectedObject[0],newObject[1]-detectedObject[1]) < thresholdDist:
        return False
    return True

img_rgb = cv2.imread("7.jpg")
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread("face.jpg",0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.85
loc = np.where( res >= threshold)

detectedObjects=[]
thresholdDist=30

for pt in zip(*loc[::-1]):
    if len(detectedObjects) == 0 or notInList(pt):
        detectedObjects.append(pt)
        cellImage=img_rgb[pt[1]:pt[1]+h, pt[0]:pt[0]+w]
        cv2.imwrite("results/"+str(pt[1])+"_"+str(pt[0])+".jpg",cellImage,
        [int(cv2.IMWRITE_JPEG_QUALITY), 50])

A: To anyone still wondering: It's way easier to sort the list "zip(*loc[::-1})" first.
For i.e my script returned found results like this:
(580, 822)
(871, 822)
(1017, 822)
(434, 823)
(726, 823)
(871, 823)
(1017, 823)
7

You'll notice that there's multiple duplication but not just in order. Just simply sorting this with "sorted(zip(*loc[::-1]))" will now make getting distance a piece of cake, by simply calculating adjacent 2 point and check distance on every loop.
By adding condition in loop and check if current point has smaller distance than desired one will get job done nicely. I never learned python properly so I'm not sure this is efficient way or not.. At least this worked for my use case. You can check it out below.
Source code (Github) /
Test Result (Imgur)

Example Code:
    img = np.array( *YOUR_SCREENSHOT_HERE* )
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    template = cv2.imread( *TARGET_IMAGE_HERE* , 0)
    w, h = template.shape[::-1]

    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= precision)

    count = 0
    last_pt = [0, 0]   # Set this negative if target image is at top-left corner.

    for pt in sorted(zip(*loc[::-1])):
        if sqrt(abs(last_pt[0]-pt[0])**2 + abs(last_pt[0]-pt[0])**2) < threshold*min([h, w]):
            continue
        else:
            last_pt = pt
            print(pt)
            count = count + 1
            cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)

    cv2.imwrite('res.png', img)
    return count

A: import time
import cv2
import numpy as np
from PIL import ImageGrab
while True:
count = 0
stop = 0

img = ImageGrab.grab()
img_np = np.array(img)

gray = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)

frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)

Template = cv2.imread('image.png' ,0)
w, h = Template.shape[::-1]

res = cv2.matchTemplate(gray, Template, cv2.TM_CCOEFF_NORMED)
threshold = 0.90
loc = np.where(res >= threshold)

font = cv2.FONT_HERSHEY_SIMPLEX

for pt in zip(*loc[::-1]):

    cv2.rectangle(frame, pt, (pt[0] + w, pt[1] + h), (0,0,255) ,2)

    count = count + 1

    print(count)

    stop = 1

cv2.imshow('frame',frame)

if (stop == 1):

    break

A: That is how I did it:
loc = np.where( res >= threshhold)
print(len(loc[0])) #match occurences count

loc is 2D array.


text:
Q: Device list says Chromecast device is in "Casting Backdrop" on HTC Desire 620G I just bought a new HTC Desire 620G phone and tried to run Googlecast sender app.
When it shows the device list, it said Chromecast device is "Casting Backdrop". I tried to cast to Chromecast but the device is still showing background image.
The same sender app can work on another Asus pad and HTC butter fly.
I dunno why...  any recommendation??

A: Oh... the problem got fixed after I update my google play service,


text:
Q: How do I stop the command console from scrolling to the bottom every time there's a new entry? New entries are added automatically, so when I'm trying to scroll up through old entries, I might get close but before I can read anything there's a new entry and it scrolls to the bottom.
I've disabled scroll forward in the properties but all that does is removes all the empty space below the entries. The answer to this problem should be in the properties but I can't see it. Possibly legacy mode?
(Running Windows 10)

A: You move the scroll bar up the window and hold down the left mouse button. It will still try and scroll to the end but it will flash down and back up to the section you've scrolled to. Tried and tested, problem solved :)


text:
Q: Typing a reducer state (holding initialState) by chaining interections together (to build a sorta one-time recursive type) Building this reducer with typescript and are trying to combine a lot of types together to archive something ala this typescript mockup:
type/interface DishOrderState {
  id: string
  withoutIngredients: string[]
  [key: string]: string
  initialState: {
     id: string
     withoutIngredients: string[]
     [key: string]: string
  }
}

a state could look like this
{
  id: '123'
  withoutIngredients: ['tomato'],
  ["BASE"]: 'rice',
  initialState: {
    id: '123'
    withoutIngredients: [],
    ["BASE"]: 'fries'
  }
}

My attempt to archive it looks like this so far:
export type DishActionType =
  | { type: 'REMOVE_INGREDIENT'; ingredient: string }
  | { type: 'ADD_INGREDIENT'; ingredient: string }
  | { type: 'PICK_OPTION'; option: string; choice: string }
  | { type: 'RESET' }
  | { type: 'never' }

interface DishOptions {
  [key: string]: string
}

// https://stackoverflow.com/a/45261035/618099
type DishOrder = DishOptions & {
  id: string
  withoutIngredients: string[]
}

type DishOrderState = DishOrder & {
  initialState: DishOrder
}

function dishOrderReducer(state :DishOrderState, action :DishActionType) :DishOrderState {
  switch (action.type) {
    case 'REMOVE_INGREDIENT':
      return {
        ...state,
        withoutIngredients: [...state.withoutIngredients.push(action.ingredient).sort()],
      }
    case 'ADD_INGREDIENT':
      return {
        ...state,
        withoutIngredients: [...state.withoutIngredients].filter(
          (ingredient) => ingredient != action.ingredient
        ),
      }
    case 'PICK_OPTION':
      return {
        ...state,
        [action.option]: action.choice
      }]
    case 'RESET':
      return {
        ...state.initialState,
        initialState: {...state.initialState}
      }
    default:
      throw new Error(`No action case for this action type: ${action.type}`)
  }
}

But vscode screams at me with
(property) withoutIngredients: string[]
Type '{ withoutIngredients: any[]; id: string; initialState: DishOrder; }' is not assignable to type 'DishOrderState'.
  Type '{ withoutIngredients: any[]; id: string; initialState: DishOrder; }' is not assignable to type 'DishOptions'.
    Property 'withoutIngredients' is incompatible with index signature.
      Type 'any[]' is not assignable to type 'string'.

Hovering over the DishOrderState shows this:
type DishOrderState = DishOptions & {
    id: string;
    withoutIngredients: string[];
} & {
    initialState: DishOrder;
}

A: The problem is you're mixing together specific fields, like id: string, with indexed fields like [key: string] : string.
An indexed field declaration says "there could be an infinite number of additional fields, but they'll all have this kind of key and this kind of value".  Think of it as a wildcard type of description.  That mostly ends up overriding any specific fields you might list.
Beyond that, a couple other observations:
Right now you're writing this reducer the hard way, by writing all the TS types and update logic by hand. You should be using our official Redux Toolkit package to write the reducer, which will drastically simplify the amount of code you have to write in terms of immutable updates and TS types for actions.  Also see our official "Usage with TS" guide page.
Beyond that, the state shape doesn't make much sense. For one thing, why is there a field called initialState nested inside of the state value?  That's very confusing.  Typically there's a variable named initialState defined outside the reducer, standalone, and the reducer references that by itself - it's not nested inside the state value.


text:
Q: How do I modify the legend in a Matlab plot? I would like to draw four circles of two colors. I'm using circle function to draw a circle. I'm facing problem with legend(). It colors the two data with the same color.
function main
clear all
clc

circle([ 10,  0], 3, 'b')
circle([-10,  0], 3, 'b')
circle([ 10, 10], 3, 'r')
circle([-10, 10], 3, 'r')

    % Nested function to draw a circle
    function circle(center,radius, color)
     axis([-20, 20, -20 20])
     hold on;
     angle = 0:0.1:2*pi;

     grid on

     x = center(1) + radius*cos(angle);
     y = center(2) + radius*sin(angle);
     plot(x,y, color, 'LineWidth', 2);
     xlabel('x-axis');
     ylabel('y-axis');
     title('Est vs Tr')
     legend('true','estimated');
    end

end

The following picture shows the problem. Both colored as blue instead one of them is red.

Any suggestions?

A: You can make your function circle() return the plot handles. Store the handles in a vector. In the end, you only call legend() once, after plotting all circles. The first argument in legend are then the function handles which you want to appear in the legend. Something like this:
function main
% clear all % functions have their own workspace, this should always be empty anyway
clc
handles = NaN(1,2);
handles(1,1) = circle([ 10,  0], 3, 'b'); % handle of a blue circle
circle([-10,  0], 3, 'b')
handles(1,2) = circle([ 10, 10], 3, 'r'); % handle of a red circle
circle([-10, 10], 3, 'r')

    % Nested function to draw a circle
    function h = circle(center,radius, color) % now returns plot handle
     axis([-20, 20, -20 20])
     hold on;
     angle = 0:0.1:2*pi;
     grid on
     x = center(1) + radius*cos(angle);
     y = center(2) + radius*sin(angle);
     h = plot(x,y, color, 'LineWidth', 2);
     xlabel('x-axis');
     ylabel('y-axis');
     title('Est vs Tr')
    end

% legend outside of the function
legend(handles, 'true','estimated'); % legend for a blue and a red circle handle
end

The result looks like this:

A: The thing is that you draw 4 things and only  have 2 entries in the legend.
As such it will pick the color of the first four things to color the legend.
Not in the opportunity to try it myself now, but I guess that the easiest 'solution' would be to draw your third circle first and then the second one.
circle([ 10,  0], 3, 'b')
circle([ 10, 10], 3, 'r')
circle([-10,  0], 3, 'b')
circle([-10, 10], 3, 'r')


text:
Q: How to merge dataframes with dask without running out of memory? Merging multiple dask dataframes crashes my computer.
Hi,
I am attempting to merge a long list of csv files with dask. Each csv file contains a list of timestamps when a variable has changed its value, together with the value; e.g. for variable1 we have:
timestamp; value
2016-01-01T00:00:00; 3
2016-01-03T00:00:00; 4

while for variable 2, we have:
timestamp; value
2016-01-02T00:00:00; 8
2016-01-04T00:00:00; 9

The timestamps in each csv can differ (as they are linked to the moment a variable has changed value). As end result, I want to obtain a hdf file in which each variable has as value at each occurring timestamp, forward filled. Hence, something like the following:
timestamp; var1; var2,
2016-01-01T00:00:00; 3 ; nan
2016-01-02T00:00:00; 3 ; 8
2016-01-03T00:00:00; 4 ; 8
2016-01-04T00:00:00; 4 ; 9

Below, I provide the meta code which I am using to achieve this parsing and merging.
# import
from pathlib import Path
from functools import partial
import import dask.dataframe as dd
import dask.bag as db
from dask import delayed
from dask.diagnostics import ProgressBar

# define how to parse the dates
def parse_dates(df):
    return pd.to_datetime(df['timestamp'], format='%Y-%m-%dT%H:%M:%S', errors='coerce')

# parse csv files to dask dataframe
def parse_csv2filtered_ddf(fn_file, sourcedir):
    fn = source_dir.joinpath(fn_tag)
    ddf = dd.read_csv(fn, sep=';', usecols=['timestamp', 'value'],
                      blocksize=10000000, dtype={'value': 'object'})
    meta = ('timestamp', 'datetime64[ns]')
    ddf['timestamp'] = ddf.map_partitions(parse_dates, meta=meta)
    v = fn_file.split('.csv')[0]
    ddf = ddf.dropna() \
        .rename(columns={'value': v}) \
        .set_index('timestamp')
    return ddf

# define how to merge
def merge_ddf(x, y):
    ddf = x.merge(y, how='outer', left_index=True, right_index=True, npartitions=4)
    return ddf

# set source directory
source_dir = Path('/path_to_list_of_csv_files/')

# get list of files to parse
lcsv = os.listdir(source_dir)

# make partial function to fix sourcedir
parse_csv2filtered_ddf_partial = partial(parse_csv2filtered_ddf, source_dir)

# make bag of dataframes
b = db.from_sequence(lcsv).map(parse_csv2filtered_ddf_partial)

# merge all dataframes and reduce to 1 dataframe
df = b.fold(binop=merge_ddf)

# forward fill the NaNs and drop the remaining
#
# please note that I am choosing here npartitions equal to 48 as
#  experiments with smaller sets of data allow me to estimate
#  the output size of the df which should be around 48 GB, hence
#  chosing 48 should lead to partition of 1 GB, I guess.
df = delayed(df).repartition(npartitions=48). \
    fillna(method='ffill'). \
    dropna()

# write output to hdf file
df = df.to_hdf(output_fn, '/data')

# start computation
with ProgressBar():
    df.compute(scheduler='threads')

Unfortunately, this scripts never runs to a successfull end. In particular, monitoring the memory usage I can follow the memory to fully flow up, after which either the computer or the program crashes.
I have tried to use only a single thread, in combination with multiple processes; e.g.
import dask
dask.config.set(scheduler='single-threaded')

in combination with
with ProgressBar():
    df.compute(scheduler='processes', num_workers=3)

also without any success.
Any pointers in the right direction are warmly welcomed.
EDIT
Below, I provide a more concise script which should allow to generate similar data to reproduce the MemoryError.
import numpy as np
import pandas as pd
from dask import delayed
from dask import dataframe as dd
from dask import array as da
from dask import bag as db
from dask.diagnostics import ProgressBar
from datetime import datetime
from datetime import timedelta
from functools import partial

def make_ddf(col, values, timestamps):
    n = int(col) % 2
    idx_timestamps = timestamps[n::2]
    df = pd.DataFrame.from_dict({str(col): values, 'timestamp': idx_time})
    ddf = dd.from_pandas(df, chunksize=100000000)
    ddf = ddf.dropna() \
        .set_index('timestamp')
    return ddf

def merge_ddf(x, y):
    ddf = x.merge(y, how='outer', left_index=True, right_index=True, npartitions=4)
    return ddf

N_DF_TO_MERGE = 55  # number of dataframes to merge
N_PARTITIONS_REPARTITION = 55

values = np.random.randn(5000000, 1).flatten()
timestamps = [datetime.now() + timedelta(seconds=i*1) for i in range(10000000)]
columns = list(range(N_DF_TO_MERGE))

# fix values and times
make_ddf_partial = partial(make_ddf, values=values, timestamps=timestamps)

# make bag
b = db.from_sequence(columns).map(make_ddf_partial)

# merge all dataframes and reduce to one
df = b.fold(binop=merge_ddf)

# forward fill the NaNs and drop the remaining
df = delayed(df).repartition(npartitions=N_PARTITIONS_REPARTITION). \
    fillna(method='ffill'). \
    dropna()

# write output to hdf file
df = df.to_hdf('magweg.hdf', '/data')

with ProgressBar():
    df.compute(scheduler='threads')

which leads up to the following error:

Traceback (most recent call last):
    File "mcve.py", line 63, in
      main()
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\click\core.py", line 764, in call
      return self.main(*args, **kwargs)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\click\core.py", line 717, in main
      rv = self.invoke(ctx)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\click\core.py", line 956, in invoke
      return ctx.invoke(self.callback, **ctx.params)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\click\core.py", line 555, in invoke
      return callback(*args, **kwargs)
    File "mcve.py", line 59, in main
      df.compute(scheduler='threads')
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\base.py", line 156, in compute
      (result,) = compute(self, traverse=False, **kwargs)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\base.py", line 398, in compute
      results = schedule(dsk, keys, **kwargs)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\threaded.py", line 76, in get
      pack_exception=pack_exception, **kwargs)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\local.py", line 459, in get_async
      raise_exception(exc, tb)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\compatibility.py", line 112, in reraise
      raise exc
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\local.py", line 230, in execute_task
      result = _execute_task(task, data)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\core.py", line 119, in _execute_task
      return func(*args2)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\utils.py", line 697, in call
      return getattr(obj, self.method)(*args, **kwargs)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\dataframe\core.py", line 1154, in to_hdf
      return to_hdf(self, path_or_buf, key, mode, append, **kwargs)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\dataframe\io\hdf.py", line 227, in to_hdf
      scheduler=scheduler, **dask_kwargs)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\base.py", line 166, in compute_as_if_collection
      return schedule(dsk2, keys, **kwargs)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\threaded.py", line 76, in get
      pack_exception=pack_exception, **kwargs)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\local.py", line 459, in get_async
      raise_exception(exc, tb)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\compatibility.py", line 112, in reraise
      raise exc
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\local.py", line 230, in execute_task
      result = _execute_task(task, data)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\core.py", line 119, in _execute_task
      return func(*args2)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\dask\dataframe\methods.py", line 103, in boundary_slice
      result = getattr(df, kind)[start:stop]
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\pandas\core\indexing.py", line 1500, in getitem
      return self._getitem_axis(maybe_callable, axis=axis)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\pandas\core\indexing.py", line 1867, in _getitem_axis
      return self._get_slice_axis(key, axis=axis)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\pandas\core\indexing.py", line 1536, in _get_slice_axis
      return self._slice(indexer, axis=axis, kind='iloc')
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\pandas\core\indexing.py", line 151, in _slice
      return self.obj._slice(obj, axis=axis, kind=kind)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\pandas\core\generic.py", line 3152, in _slice
      result = self._constructor(self._data.get_slice(slobj, axis=axis))
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\pandas\core\internals\managers.py", line 700, in get_slice
      bm._consolidate_inplace()
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\pandas\core\internals\managers.py", line 929, in _consolidate_inplace
      self.blocks = tuple(_consolidate(self.blocks))
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\pandas\core\internals\managers.py", line 1899, in _consolidate
      _can_consolidate=_can_consolidate)
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\pandas\core\internals\blocks.py", line 3146, in _merge_blocks
      new_values = np.vstack([b.values for b in blocks])
    File "C:\Users\tomasvanoyen\Miniconda3\envs\stora\lib\site-packages\numpy\core\shape_base.py", line 234, in vstack
      return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
  MemoryError

A: Two things seem odd.

*

*You're calling dask dataframe code from within dask.bag code.

*You seem to be calling merge when perhaps you just want concat?


text:
Q: Swapping Variables by pattern matching? Assume you have 2 Integer Variables a and b
How would you swap them only if a > b by using a match expression?
If a <= b do not swap the ints.
In an imperative language:
if (a > b){
   int temp=a;
   a=b;
   b=temp;
}

Doing the same in ocaml seems surprisingly hard.
I tried
let swap a b =
 match a,b with
  | a,b when a > b -> b,a
  | a,b when a <= b -> a,b

I am trying to do this because in the following function call, I want to make sure that x is the bigger of the two variables.

A: One easy way :
 let swap a b =
     if (a>b) then (b,a)
     else (a,b)

But this is not equivalent to the C code, your C code is swapping the value of the variable - this is how imperative language are doing.
In Ocaml, there is no side-effect (except if you use reference to some int). This swap function will return a tuple whose members are always ordered (the first member will be always smaller than the second order).

A: Without state, you cannot "swap" the values of the variables since the variables are immutable. Your best bet is to use a tuple and introduce new variables in the scope. Example:
let diff a b =
    let (min, max) = if a <= b then (a, b) else (b, a)
    in max - min

You can of course use the same identifiers and shadow the original variables:
let diff a b =
    let (a, b) = if a <= b then (a, b) else (b, a)
    in b - a

It doesn't really help with readability though.

A: Just for reference, if you'd like to swap the values in two refs, it would look like the following:
let swap a_ref b_ref =
  let a, b = !a_ref, !b_ref in
  a_ref := b;
  b_ref := a
;;

which has the type val swap : 'a ref -> 'a ref -> unit.


text:
Q: Display image in another activity after clicking on upload button I want to display my image to another activity after i clicked on the upload button. I have 2 activity (Main and Main2). Currently, I intent the uri to the next activity after selecting a image from gallery. How i intent the uri on my upload button instead?
MainActivity.Java
    private void uploadImage(){
        @Override
       public void onResponse(String s) {
           loading.dismiss();
           Toast.makeText(MainActivity.this, s , Toast.LENGTH_LONG).show();
           Intent i = new Intent(MainActivity.this,Main2Activity.class);
           startActivity(i);
           finish();
       }
   },

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);
            Intent i = new Intent(this,Main2Activity.class);
            i.putExtra("imagepath", filePath.toString());
            startActivity(i);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

A: You can do this as below:
define a class level variable:
   String filePathString = null;

private void uploadImage(){
 @Override
                public void onResponse(String s) {
                    loading.dismiss();
                    Toast.makeText(MainActivity.this, s , Toast.LENGTH_LONG).show();
                    Intent i = new Intent(MainActivity.this,Main2Activity.class);
                    startActivity(i);
                    finish();
                }
            },

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);
            Intent i = new Intent(this,Main2Activity.class);
            filePathString = filePath.toString();
            i.putExtra("imagepath", filePath.toString());
            startActivity(i);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

And then set OnClickListener on your button:
uploadButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
     Intent i = new Intent(this,Main2Activity.class);
     i.putExtra("imagepath", MainActivity.this.filePathString);
     startActivity(i);
    MainActivity.this.finish();
    }
});

A: You can change the Uri variable to a class level variable to store the uri result obtained from the onActivityResult
private Uri filePath;

 if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        filePath = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);

            imageView.setImageBitmap(bitmap);
            Intent i = new Intent(this,Main2Activity.class);
            i.putExtra("imagepath", filePath.toString());
            startActivity(i);

        } catch (IOException e) {
            e.printStackTrace();
        }

and then in your button you can pass the Uri as:
Intent i = new Intent(this,Main2Activity.class);
            i.putExtra("imagepath", filePath.toString());
            startActivity(i);

A: try this code
first put uri as string in intent.
intent.putExtra("imageUri", imageUri.toString());

and then in second activity just convert back to string like this
Uri myUri = Uri.parse(extras.getString("imageUri"));

A:  Uri filePath = data.getData();
                String[] projection = {MediaStore.MediaColumns.DATA};
                Cursor cursor = managedQuery(filePath, projection, null, null,
                        null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();

                String selectedImagePath = cursor.getString(column_index);
    Then pass selectedImagePath in the intent like below
    Intent i = new Intent(this,Main2Activity.class);
            i.putExtra("imagepath", filePath.toString());
            startActivity(i);


text:
Q: How do I specify an index for a TextField in Django with a MySql backend? I've got a model defined in Django that looks (in part) like this:
class Info(models.Model):
    information = models.TextField(max_length = 32, null = True, db_index = True)

However, when I try syncdb with a MySql backend, I get Failed to install index for app.Info model: (1170, "BLOB/TEXT column 'information' used in key specification without a key length")
How can I fix this?

A: The answer is to specify the field as a CharField, not a TextField.
class Info(models.Model):
    information = models.CharField(max_length = 32, null = True, db_index = True)


text:
Q: Why does the creation of a vector of BGL graphs gives a segmentation fault? I have two classes : Signal for my graph edges and Logic for my graph vertices. The types ivl_net_logic_t and ivl_signal_t come from IcarusVerilog. The classes are declared in header files :
class Logic
{
private:
    std::string name;
    ivl_net_logic_t log;

public:
    Logic(ivl_net_logic_t L);
    ~Logic();

    ivl_net_logic_t getLogic() { return log; }
    void setName(std::string &n) { name = n; }
    std::string getName() { return name; }
}

class Signal
{
private:
    ivl_signal_t signal;

public:
    Signal(ivl_signal_t sig);
    /* Signal(); */
    ~Signal();

    ivl_signal_t getSignal();
}

In another header file I also included Boost Graph Library headers and I defined my Graph structure :
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/graph/dominator_tree.hpp>
#include <boost/iostreams/operations.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/graphml.hpp>
#include <boost/graph/copy.hpp>

typedef typename boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, Logic, Signal> Graph;
typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;
typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIterator;
typedef typename boost::graph_traits<Graph>::edge_iterator EdgeIterator;

In a .cc file I wrote a basic function just to check my graph :
void printGraph(Graph &g)
{
    std::cout << "num_vertices(g) = " << num_vertices(g) << std::endl;
    std::cout << "num_edges(g) = " << num_edges(g) << std::endl;

    std::cout << "Vertices = [ ";
    VertexIterator vi, vend;
    for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi)
        std::cout << g[*vi].getName() << " ";
    std::cout << "]" << std::endl;

    std::cout << "Edges = [" << std::endl;
    EdgeIterator ei, end;
    for (boost::tie(ei, end) = edges(g); ei != end; ++ei)
    {
        Vertex s = source(*ei, g);
        Vertex t = target(*ei, g);
        std::cout << g[s].getName() << " --> " << g[t].getName() << std::endl;
    }
    std::cout << "]" << std::endl;
}

Now in my main code, I create my graph g and I try to move it in a vector :
Graph g;

/**
 * Add vertices in g and for any vertex v in g, g[v] is a Logic object.
 * Add edges in g and for any edge e in g, g[e] is a Signal object.
 */
printGraph(g);

std::vector<Graph> graph_tracks = {g};

Doing this, the compiler said there was an error with the edge property at the line where I insert g in the vector, because the class Signal had no constructor that required no argument :
/usr/include/boost/graph/detail/adjacency_list.hpp:2190:43: error: no matching function for call to 'Signal::Signal()'
 2190 |       typename Config::edge_property_type p;
      |                                           ^
includes/Signal.hpp:17:2: note: candidate: 'Signal::Signal(ivl_signal_t)'
   17 |  Signal(ivl_signal_t sig);
      |  ^~~~~~
includes/Signal.hpp:17:2: note:   candidate expects 1 argument, 0 provided
includes/Signal.hpp:8:7: note: candidate: 'Signal::Signal(const Signal&)'
    8 | class Signal
      |       ^~~~~~
includes/Signal.hpp:8:7: note:   candidate expects 1 argument, 0 provided

So I created the constructor which I commented here in the definition of the Signal class. Also I changed
std::vector<Graph> graph_tracks = {g};

for
std::vector<Graph> graph_tracks;
graph_tracks.push_back(g);

Now it compiles and it prints the graph but I get a Segmentation fault just when I push g in the vector. Anyone can help ?

A: Your problem is highly likely memory corruption. The cause is in code not shown.
Here's your code made self-contained, and simplified/modernized in spots. It works fine and runs clean under sanitizers:
Live On Coliru
#include <iostream>
#include <string>

struct ivl_net_logic_t {};
struct ivl_signal_t {};

class Logic {
    std::string     name_ = "unnamed";
    ivl_net_logic_t log_;

  public:
    Logic(ivl_net_logic_t L = {}) : log_(std::move(L)) {}

    Logic(Logic const&) = default;
    ~Logic()            = default;

    ivl_net_logic_t const& getLogic() const { return log_; }
    void                   setName(std::string n) { name_ = std::move(n); }
    std::string const&     getName() const { return name_; }

    friend auto nameMap(auto const& g) { return get(&Logic::name_, g); }
};

class Signal {
    ivl_signal_t signal_;

  public:
    Signal(ivl_signal_t sig = {}) : signal_(std::move(sig)) {}
    Signal(Signal const&) = default;
    ~Signal()             = default;

    ivl_signal_t const& getSignal() { return signal_; }
};

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>

using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, Logic, Signal>;
using Vertex         = boost::graph_traits<Graph>::vertex_descriptor;
using Edge           = boost::graph_traits<Graph>::edge_descriptor;
using VertexIterator = boost::graph_traits<Graph>::vertex_iterator;
using EdgeIterator   = boost::graph_traits<Graph>::edge_iterator;

void printGraph(Graph const& g, std::ostream& os = std::cout) {
    os << "num_vertices(g) = " << num_vertices(g) << "\n";
    os << "num_edges(g) = " << num_edges(g) << "\n";

    os << "Vertices = [ ";
    for (auto v : boost::make_iterator_range(vertices(g)))
        os << g[v].getName() << " ";
    os << "]\n";

    os << "Edges = [\n";
    for (auto e : boost::make_iterator_range(edges(g))) {
        Vertex s = source(e, g), t = target(e, g);
        os << g[s].getName() << " --> " << g[t].getName() << "\n";
    }
    os << "]" << std::endl;
}

int main() {
    Graph g(5);
    g[0].setName("foo");
    g[1].setName("bar");
    g[2].setName("baz");
    g[3].setName("qux");
    g[4].setName("quux");

    add_edge(0, 1, g);
    add_edge(1, 4, g);
    add_edge(4, 2, g);
    add_edge(2, 0, g);

    printGraph(g);
    print_graph(g, nameMap(g), std::cout << "\n---\nOr directly using boost:\n");

    {
        std::vector<Graph> graph_tracks{g};
    }
    {
        std::vector<Graph> graph_tracks;
        graph_tracks.push_back(g);
        graph_tracks.push_back(g);

        for (auto& element : graph_tracks)
            printGraph(element, std::cout << "\n---\nVector element: ");
    }

    printGraph(g, std::cout << "\n---\nStill fine: ");
    print_graph(g, nameMap(g), std::cout << "\n---\nAnd using boost:\n");
}

Prints the expected output:
num_vertices(g) = 5
num_edges(g) = 4
Vertices = [ foo bar baz qux quux ]
Edges = [
foo --> bar
bar --> quux
quux --> baz
baz --> foo
]

---
Or directly using boost:
foo --> bar
bar --> quux
baz --> foo
qux -->
quux --> baz

---
Vector element: num_vertices(g) = 5
num_edges(g) = 4
Vertices = [ foo bar baz qux quux ]
Edges = [
foo --> bar
bar --> quux
quux --> baz
baz --> foo
]

---
Vector element: num_vertices(g) = 5
num_edges(g) = 4
Vertices = [ foo bar baz qux quux ]
Edges = [
foo --> bar
bar --> quux
quux --> baz
baz --> foo
]

---
Still fine: num_vertices(g) = 5
num_edges(g) = 4
Vertices = [ foo bar baz qux quux ]
Edges = [
foo --> bar
bar --> quux
quux --> baz
baz --> foo
]

---
And using boost:
foo --> bar
bar --> quux
baz --> foo
qux -->
quux --> baz

Summary/Notes
Use sanitizers to your advantage! Chances are that if you run your code under ASAN/UBSAN, you will immediately find the cause. Alternatively, reduce your code to eliminate possible causes. As you can see from my answer, at some point the error goes away.
Note that you talk about "moving graphs" where your code shows no moves. If you move things, references may become stale. Check all places where you keep references to objects that may cease to be valid.
Also note that you return many things by value where they could be const&, members weren't const-correct, the property classes smell a bit of "Quasi Classes", and so on. I've simplified a lot of that, but I'd probably suggest more like: http://coliru.stacked-crooked.com/a/3c914a1dd015c371


text:
Q: Determine the remainder Determine the remainder when $2^{2018}$ is divided by $55$

A: 1-method. We will use the following congruences:
$$2^6\equiv 64\equiv 9 \pmod{55};\\
9^2\equiv 81\equiv 26 \pmod{55};\\
26^2\equiv 676\equiv 16 \pmod{55}$$
to solve the main problem:
$$2^{2018}\equiv (2^6)^{336}\cdot 2^2\equiv (9^2)^{168}\cdot 2^2\equiv (26^2)^{84}\cdot 2^2\equiv (2^6)^{56}\cdot 2^2\equiv\\
(9^2)^{28}\cdot 2^2\equiv (26^2)^{14}\cdot 2^2\equiv (2^6)^9\cdot 2^2\equiv (9^2)^4\cdot 9\cdot 2^4\equiv \\
(26^2)^2\cdot 9\cdot 2^4\equiv (2^6)^2\cdot 9\equiv 9^2\cdot 9\equiv 26\cdot 9\equiv 220+14\equiv 14\pmod{55}.$$
2-method. Based on the Euler's theorem: we have $\varphi(55)=40$ and:
$$2^{\varphi(55)}\equiv 2^{40}\equiv 1 \pmod{55} \Rightarrow \\
2^{2018}\equiv (2^{40})^{50}\cdot 2^{18}\equiv 2^{18}\equiv (2^{6})^3\equiv 9^3\equiv 9^2\cdot 9\equiv 26\cdot 9\equiv 220+14\equiv 14\pmod{55}.$$
P.S. You can learn the theorem as well as the modular arithmetic operations.

A: As Carmichael Function $\lambda(55)=20$ and $(55,2)=1$ and $2018\equiv-2\pmod{20}$
$$2^{2018}\equiv2^{-2}\pmod{55}$$
Now as $14\cdot4\equiv1\pmod{55},4^{-1}\equiv14$


text:
Q: When to use Repository vs Service vs Trait in Laravel? To avoid code duplication in Laravel, I want to have a method that is used by multiple Controllers, it inserts some rows in database and also updates some data in another table.
I thought of using Repository, but I read somewhere that Repository is better used for retrieving data and shouldn't be used for inserting.
So I'm going to use Traits now. but I'm a bit confused...
Could some one please explain in a simple way what is the best usage for each of these (Repository/Service/Trait) and how are they different?

A: Traits
Are an alternative approach to inheritance that solves some limitations of single class inheritance, which PHP uses. This is commonly used to share similar logic across models. Let's imagine a couple of models have a Company relationship.
trait HasCompany {
   public function company() {
       return $this->belongsTo(Company::class);
   }
}

Now the user can easily share code from the trait, by the keyword using. This is an example and most often a more complex use case would be needed for it to make sense.
class User {
   use HasCompany;
}

Repositories
Repositories is a design pattern to abstract data layers from the application. Your logic should not care about how you store data, so if you wanted to change from Mysql to Mongodb, you would only swap out the repository and not have to change business logic.
Very opinionated here, but this is not a fitting design pattern for Laravel. Laravel has Eloquent and the database layer is therefor already abstracted. Repositories is sometimes used for Laravel applications, but rather an outlier, than a common sight. One of the main reasons for repositories, is to be data implementation agnostic, which already exists and you can swap between SQL servers flawlessly. Also Eloquents features like ::find(), scopes etc. feels like a replacement for Repositories and is quirky to use at the same time.
If you use Doctrine as the ORM, which you can in Laravel, it is the core of their architecture and should be used.
It sometimes occur that the repository pattern is used to encapsulate business logic, with a similar approach to a service approach or action pattern.
Services
Is commonly used for a place to store business logic or the building blocks of your actions in your application. In traditional MVC design, Controllers should only handle input. Normally you would put your logic in Models, but they get "fat" very quickly, when this happens services is a common place to put business logic. Sometimes also named actions or commands, which is similar but a little bit different approaches.
One of the core things it solves, is to make your business logic reusable. Imaging filtering all users by an active flag, when you retrieve it in its controller.
public function all() {
    return User::where('active', true)->get();
}

Now you have your business logic, that enforces that you only work on active users, later you want to notify all active users with an email, by notifications using a command.
class NotifyUsers extends Command {
    public function handle() {
        foreach (User::where('active', true)->get() as $user) {
            $user->notify();
        }
    }
}

Now you manually have to keep business logic up to date. Next time you add a second condition or change the logic, you have to change the code in two places. In a big application where this code block is used often, it can make it quite hard to maintain the conditions without forgetting one of the places. If you make a service with this logic, you can easily utilize the same business logic across the application. While one have one place to change the code, if this logic had to change.
class UserService {
    public function all() {
        return User::where('active', true)->get();
    }
}

Everywhere you want to use this business logic getting active users, you can use the service. Therefor only having one place to maintain the logic. A call can be as simply as resolve(UserService::class)->all(). Example of the updated logic with services would be.
// controller
public function all(UserService $userService) {
    return $userService->all();
}

// command
class NotifyUsers extends Command {
    public function handle(UserService $userService) {
        $userService->all()->each->notify();
    }
}

Conclusion
The world is not black and white, you have to figure out your own approach. My advice is, do not spend time on Repositories, Laravel has a lot of features to handle data related operations scopes, getters setters etc. that conflicts with the Repository design pattern. See if a service like design approach suits you and you can utilize em. Traits is not as much an architectural design pattern, as it is a Class inheritance alternative, simply to share logic between classes.


text:
Q: Dynamically add h1 in header How do i dynamically add a value for h1 in my header in jQuery Mobile to make it from

to this

Page Title

A: Try This:
$("div[data-role='header']").find('h1').html('Page Title')

With id:
$("div[data-role='header']").find('#h1ID').html('Page Title')

A: $('[data-role*=header] > h1').html('some content')


text:
Q: how to move the image on left side for showing the details when hover I have used three images within a div. If I hover over the image, then the image should move slowly to the left side and the details should show up on the right side.
Then, if the cursor moves away, the image should move to its old position.
My Code is below.
In Html:

Details of the image initially it should hide

css file
.ch-grid li .person-profile nav ul li {
    display: inline-block !important;
    height: 56px !important;
    margin: 0px !important;
    width: 36px !important;
}

.ch-img-1 {
    background-image: url(../images/image.png);
}

.bioinfo {
    display: none;
    background: rgba(246,246,246, 0.8);
    font-size: 10px;
    padding: 15px 3px 3px 3px;
    text-align: justify;
}

Jquery:
$('.ch-grid > li').hover(function() {
            $(this).css({position: 'relative', marginRight: 120});
            $(this).children('.bioinfo').show('slow').css({display: 'inline-block'});
}, function() {
     $(this).css({position: 'relative', marginRight: -10});
    $('.bioinfo').hide();

});

A: If I understand correctly, you should be looking to do something like this.
I've changed the $(this) selector you were using, to be a little more specific to the element that is being moved. Rather than the entire li , we are selecting the .ch-item of the hovered li.
Additionally, the .hide() .show() methods have been changed to .fadeIn() and .fadeOut().
In our animations, we can return the element back to its original position by moving it to 0px. We can do this because the element is relatively positioned, and not absolutely positioned. If you have any questions let me know!
http://jsfiddle.net/2ZKG3/8/
$('.ch-grid li').hover(function () {
    $('.ch-item', this).stop().animate({'left': '-100px'}, 300);
    $('.bioinfo', this).stop().fadeIn(300).css('display','inline-block');
}, function () {
    $('.ch-item', this).stop().animate({'left': '0px'}, 300);
     $('.bioinfo', this).stop().fadeOut(300);
});

.ch-img-1 {
    position: relative;
    background-image: url(https://lh4.googleusercontent.com/9Difi9bypu9-FoUsfFWpX6odYLLjXQk_q0aPxZBSFynecMOSLoKRKWRWIfZdXRGOdXMZCahrLBG6vWrwIeT-A26iDjTucgFVCP0Fuzr79BHW5kLJ3sw);
    width: 100px;
    height: 100px;
    background-size: 100px;
    display: inline-block;
    z-index: 2;
}
.bioinfo {
    display: none;
    background: rgba(246, 246, 246, 0.8);
    font-size: 10px;
    padding: 10px 20px;
    text-align: justify;
    position: absolute;
    left: 50px;
    margin-top: 20px;
}

Let me know if that isn't the desired effect you are going for. Hope this helps!

A: $(this).animate({'left' : '-30px' }, 1000, function() { });
Use animate.


text:
Q: In Javascript, How to use a (global) function inside an object? The function would do complex stuff and would be used when creating objects So, I was thinking of creating a function which does some stuff, and later use the same function inside different objects created later.
In the code below are two instances: Testing (01) and commenting out (02), and vice versa.
"use strict";

function fullName() {
    return this.firstName + " " + this.lastName;
}

const person = {
    firstName: "Anant",
    lastName: "Ghotale"
    completeName: fullName.call(person) // (01) does not work
};

//person.completeName = fullName.call(person); (02) this works

console.clear();
console.log(person.completeName);

(02) works, but (01) doesn't.
That is to say, creating a new property outside person while using call to put this = person works, but not inside it.
These are my questions:

*

*How do I use (call) a function inside an object?

*Is this a foolish endeavour, to call a function inside an object? Is there a better way to do the same task?

A: You probably want to use a getter for this.

function fullName() {
  return this.firstName + " " + this.lastName;
}

const person = {
  firstName: "Anant",
  lastName: "Ghotale",
  get completeName() {
    return fullName.call(this)
  }
};

console.log(person.completeName)


text:
Q: How to use the `db` variable from other controllers in AccountController? I need to use Identity in my application. I don't know how to change the User table. So I decided to create an additional model Avatar for images.
public class Avatar
    {
        [Required]
        [DataType(DataType.MultilineText)]
        public string ImagePath { get; set; }

        [Required]
        public string UserId { get; set; }

        [Required]
        public int AvatarId { get; set; }
    }

In Register action of AccountController I want to add default avatar for all users:
// POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    Avatar defaultAvatar = new Avatar { UserId = User.Identity.GetUserId(), ImagePath = "default.png"};
                    db.Avatars.Add(defaultAvatar);
                    db.SaveChanges();
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            return View(model);
        }

But I have an error: The name 'db' does not exist in the current context. I chose the correct way to realization of my idea? Or is there an easier way?

A: Certain controllers that you generate through a template get a private YourDbContext db = new YourDbContext(); member. This lets you access the database in any action method.
If you want that in your AccountController as well, you need to add that declaration there too.
Or rather wrap it in a using block:
using (var db = new YourDbContext())
{
    db.Avatars.Add(defaultAvatar);
    db.SaveChanges();
}

A: You must instantiate the DbContext in your controllers constrctor.
public class YourController : Controller
{
    private readonly ApplicationDbContext _db;
    public YourController()
    {
        _db = new ApplicationDbContext;
    }

    //Optional: Poor man's dependency injection for unit test
    //Also I highly recommend to have a look at IOC containers.
    public YourController(ApplicationDbContext db)
    {
        _db = db;
    }
}


text:
Q: Big data solution for frequent queries I need a big data storage solution for batch inserts of denormalized data which happen infrequently and queries on the inserted data which happen frequently.
I've gone through Cassandra and feel that its not that good for batch inserts, but an OK solution for querying. Also, it would be good if there was a mechanism to segregate data separately based on a data attribute.

A: As you mentioned Cassandra I will talk about it:
Can you insert in an unbatched way or is this impossed by the system? If you can insert unbatched, Cassandra will probably be able to handle it easily.
Batched inserts should also be handable by Cassandra nodes, but this won't distribute the load properly among all the nodes (NOTE: I'm talking about load balancing, not about data balance, which will be only depending on your partition key setup). If you are not very familiar with Cassandra you could tell us your data structure and your query types and we could suggest you how to use Cassandra's data model to fit it.
For the filtering part of the question, Cassandra has clustering keys and secondary indexes, that are basically like adding another column configuration to the clustering key so that you have both for querying.


text:
Q: I need to add button to keyboard like following picture image is at following location
http://www.freeimagehosting.net/uploads/e50107df44.jpg
please help me.
i will be thank full to you.

A: That's actually trivial.  What you have there is just a UIToolbar perched above the keyboard -- it's not attached to the keyboard in any way at all, except to the extent that you program it to be.
The biggest problem with doing one that way is that if the keyboard slides in and out, you probably want the toolbar to do the same, which requires some careful coordination of the animation speed.
More specifically, you want to trigger the appearance of the toolbar in
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

and its disappearance in the method invoked with the Termine button is touched.
Do you need more details?

A: Actually that looks like the new-in-3.0 UIWebView form autofill bar. I'm sure it is internally implemented like you say, a UIToolbar that appears when the keyboard does but you cannot add any more buttons to it. I'm not sure if that is what sagar is asking for or not though.


text:
Q: Loopback-4 Mocking injection i'm using loopback-4, looking for help to mock the @inject declared at class level.
Please find below code.
import { repository } from '@loopback/repository';
import { AddressRepository } from './address.repository';
import { Address } from './address.db.model';

export class AddressService {
    @repository(AddressRepository) private addressRepo: AddressRepository;

    async getAddresses(): Promise<Address[]> {
      return this.addressRepo.find();
    }
}

i am trying to mock through @loopback/testlab.StubbedInstanceWithSinonAccessor but its not working, as i am not using constructor injection. tried with below approach but it wont allow.
let addressRepo: StubbedInstanceWithSinonAccessor<AddressRepository>;
const addressService = new AddressService(addressRepo);

can some one help in mocking @injector which is not declared at constructor level?
thank you in advance.

A: Since your dependency is declared as a property, you need to provide the stubbed implementation via a property setter.

*

*Make your property public so that it can be changed from outside.
export class AddressService {
  @repository(AddressRepository)
  public addressRepo: AddressRepository;

  // ...
}

*Use a regular property setter in your tests.
let addressRepo: StubbedInstanceWithSinonAccessor<AddressRepository>;
const addressService = new AddressService();
addressService.addressRepo = addressRepo;


text:
Q: Migrate Express 2.5 app to Express 4.12 I am using the code found in this repo.
I want to migrate from Express 2.5 to 4.12 so I have taken the original Express 2.5 app.js and tried to integrate it with the new Express 4.12 app.js:
var express = require('express');
var ExpressBrute = require('express-brute');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var arr = require('./compiler/compilers');
var sandBox = require('./compiler/DockerSandbox');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

var store = new ExpressBrute.MemoryStore(); // stores state locally, don't use this in production
var bruteforce = new ExpressBrute(store,{
  freeRetries: 50,
  lifetime: 3600
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components',  express.static(path.join(__dirname, '/bower_components')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

app.all('*', function(req, res, next)
{
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');

  next();
});

function random(size) {
  //returns a crypto-safe random
  return require("crypto").randomBytes(size).toString('hex');
}

app.post('/compile',bruteforce.prevent,function(req, res)
{

  var language = req.body.language;
  var code = req.body.code;
  var stdin = req.body.stdin;

  var folder= 'temp/' + random(10); //folder in which the temporary folder will be saved
  var path=__dirname+"/"; //current working path
  var vm_name='virtual_machine'; //name of virtual machine that we want to execute
  var timeout_value=20;//Timeout Value, In Seconds

  //details of this are present in DockerSandbox.js
  var sandboxType = new sandBox(timeout_value,path,folder,vm_name,arr.compilerArray[language][0],arr.compilerArray[language][1],code,arr.compilerArray[language][2],arr.compilerArray[language][3],arr.compilerArray[language][4],stdin);

  //data will contain the output of the compiled/interpreted code
  //the result maybe normal program output, list of error messages or a Timeout error
  sandboxType.run(function(data,exec_time,err)
  {
    //console.log("Data: received: "+ data)
    res.send({output:data, langid: language,code:code, errors:err, time:exec_time});
  });

});

//app.use('/editor', function(req, res)
//{
//  res.render('editor');
//});

module.exports = app;

If I run then start express DEBUG=myapp npm start it all works fine except when I go to compile code in the app itself (refer repo) when a post request is fired I receive a 404 in response, I am also getting a 404 in the developer console. Any ideas, I assume the error is around this line of code:
app.post('/compile',bruteforce.prevent,function(req, res)

A: In the end the answer was to move all of this code to the bottom but still above module.exports = app;:
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


text:
Q: Questions on dihedral group and orthogonal group I am learning dihedral groups in my abstract algebra course. My teacher leaves us the following exercise. I can work out the first three parts only and I cannot even understand the question in part 5. Please feel free to offer help.
Question:

Let $O(2, \mathbb{R}) = \{ A \in GL(2, \mathbb{R}) : A A^t = I \}$,
  i.e. the orthogonal group. $GL(2, \mathbb{R})$ is the set containing
  all invertible $2 \times 2$ matrices with real entries.

*

*Prove that $O(2, \mathbb{R})$ is a subgroup of $GL(2, \mathbb{R})$.

*Consider $D_n$, the dihedral group. Prove that $D_n \subset O(2, \mathbb{R})$.

*Prove that $SO(2, \mathbb{R})$, the set of all $A \in O(2, \mathbb{R})$ such that $det(A) = 1$, is a subgroup of $O(2,
 \mathbb{R})$.

*Show that every element in $O(2, \mathbb{R})$ is of the form either $ \left(\begin{array}{ccc}cos \theta & sin \theta  \\-sin
 \theta & cos \theta  \end{array} \right) $ or $
 \left(\begin{array}{ccc}0 & 1  \\1 & 0  \end{array} \right) $$
 \left(\begin{array}{ccc}cos \theta & sin \theta  \\-sin \theta & cos
 \theta  \end{array} \right) $ for some $\theta \in \mathbb{R}$.

*Let $n \geq3$ be an integer. Consider the regular $n$-gon $\Gamma_n$ in $\mathbb{R}^2=\mathbb{C}$ whose vertices are the $n$
  points $(cos\frac{2\pi k}{n}, sin\frac{2 \pi k}{n})$. Prove that $D_n
 = \{ A \in O(2, \mathbb{R}): A(\Gamma_n)=\Gamma_n\}$.

The first three parts are trivial. I have successfully shown all of them. But what about question 4 and 5? Thanks in advance.

A: For part four, write down
$$
\begin{bmatrix} a & b \\ c & d \end{bmatrix}\begin{bmatrix} a & c \\ d & d \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}
$$
and consider two cases:

*

*$a = 0$

*$a \ne 0$

The first will lead you to
$$
\begin{bmatrix} 0 & \pm 1 \\ \pm 1 & 0 \end{bmatrix}
$$
The second will lead you to $c = -b$, and $a^2 + c^2 = 1$. Set $\theta = atan2(c, a)$, and observe that for this $\theta$, $a = q\cos \theta, c = q\sin \theta$ ... and then that $q = \pm 1$. That pretty much handles part 4.
Once you've done that, part 5 should not be too bad. The subgroup $G$ of $O(2, R)$ specified certainly contains rotation by $h = 2\pi k / n$, and hence all its powers. Since its $n$th power is the identity, you've got a $Z/nZ$ in $G$. It also contains a flip about a horizontal axis. That's the order-2 element of $D_n$. Now all you have to do is set of a mapping and prove it's an isomorphism.
Post-comment edit:
I'm not sure how you've defined $D_n$. I think of it as a group with two generators $a$ and $b$, and relations $a^n = b^2 = e$ and $bab = a^{-1}$. Others say "it's the group of symmetries of a regular $n$-gon." I'm sure there are other definitions. If you go with my definition, you need to find a map from $D_n$ to the subgroup $G$, and since $a$ and $b$ are generators, you just need to show where to send those. You send $a$ to
$$
f(a) = \begin{bmatrix} \cos u & -\sin u \\ \sin u & \cos u \end{bmatrix}
$$
where $u = 2\pi /n$. You then compute $f(a^k) = f(a)^k$, for $k = 1, 2, \ldots$ and show none of these is the identity until  $f(a^n) = I_2$.
Then you send $b$ to an element of order $2$ in $G$ ... like reflection through the $x$ axis, i.e.
$$
f(b) = \begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}
$$
Now confirm that $f(b)^2 = I_2$, thus checking that the second "relation" holds.
Finally, you need to check that $f(bab) = f(a)^{-1}$, which is just a bunch of matrix multiplication.
Once you've done this, you know that $f$ is a homomorphism, it's kernel is $\{e\}$, and the only question is "is it surjective?". To prove surjectivity, suppose that $M$ is a matrix in $O(n)$ that preserves $\Gamma_n$. Call the points of $\Gamma_n$ $v_0, \ldots, v_n$, where $v_k$ corresponds to $2\pi k/n$.
Then $M v_0 = v_k$ for some $k$. Let $M_k$ be "rotation through angle $2\pi k/n$", i.e., $f(a^k)$. Then we have
$$
M_k^{-1} M v_0 = v_0
$$
which is a matrix in $O(2)$ that holds fixed the horizontal axis. That makes it have to be
$$
\begin{bmatrix} 1 & 0 \\ 0 & \pm 1 \end{bmatrix}
$$
If it's the identity, then $M = M_k = f(a^{k}$, so $M$ is in the image of $f$.
If it's the other matrix, which happens to be $f(b)$, then we have
$$
f(a^{-k}) M = f(b) \\
M = f(b) f(a^{k})
$$
and once again $M$ is in the image of $M$. So $f$ is surjective, injective, and a homomorphism. Thus it's an isomorphism onto a subgroup of $O(2)$.

A: Part 4 Note that translating the condition $AA^T = I$ into statements about the rows and columns of $A$ simply says that $A$ is orthonormal iff its columns form and orthonormal basis of $\mathbb{R}^2$ (with respect to the usual inner product). Since the first column of $A$ has unit length, we can write it as $$(\cos \theta, -\sin \theta).$$ The second column must be orthogonal to this and have unit length, and so must be able to write it as
$$\pm (\sin \theta, \cos \theta)$$
for some choice of $\pm$. The choice $+$ leads to the first form, and the choice $-$ leads (after an appropriate change of parameter) to the second.
Part 5 This is somewhat involved, and partly depends on what definition you're using for $D_n$ in the first place. But even without knowing that we can get starting by identifying explicitly the subgroup of $O(n)$ that maps $\Gamma_n$ to itself: Any element $A \in O(n)$ such that $A(\Gamma_n) = \Gamma_n$ must in particular send the point $(1, 0)$ to one of the other vertices of $\Gamma_n$, say, to $\left(\cos \frac{2\pi k}{n}, \sin \frac{2\pi k}{n}\right)$, and by definition, this is the first column of $A$. By the above characterization, this determines the second element up to sign. There are $n$ possibilities for $k$, and each leads to two possibilities for $\pm$, giving a total of $2n$ matrices, and checking directly shows that all of these do indeed map $\Gamma_n$ to $\Gamma_n$.


text:
Q: Force emacs to use Texlive 2012 instead of 2009 I am using Ubuntu 12.04 with Emacs 23.3.1 for handling .tex files. The default installation of Texlive in Ubuntu is version 2009, and I just upgraded to Texlive 2012: in my /usr/local/texlive directory, I can see the 2012 folder containing the files for the latest version. Also there is a folder called "texmf-local" which I believe is for texlive 2009.
My question is: when I use emacs to open a .tex file and pdflatex it, it produces error, from which (after C-c C-l to see the error output) I realized that emacs is still using Version 3.1415926-1.40.10 (TeX Live 2009/Debian). How can I force emacs to handle .tex files by the latest texlive 2012 instead of 2009? Do I need to edit the .emacs file or there are other ways to change the setting?
I appreciate your kindly help!

A: You just need to adjust your PATH environment variable and put your texlive 2012 directory first.  This could be either done by modifying your shell setup, so Emacs will pickup modified PATH, or you can change it from Emacs with command (change path accordingly to your setup - I don't remember right now how TeXLive organizes bin directories):
(setenv "PATH" (concat "/usr/local/texlive/bin/:" (getenv "PATH")))

Just put this line in your ~/.emacs file...


text:
Q: Elements overlapping on top of each other in relativeLayout I have created an Activity and used RelativeLayout which comes in by default in Android Studio.
I am trying to place a button just before my TextView but I am unable to do that.
Here is the result:

Here is my code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity">

    <TextView
        android:id="@+id/heading"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:id="@+id/button"
        android:text="@string/sachin_jain"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_alignLeft="@+id/heading"
        android:layout_alignTop="@+id/heading"
        android:layout_centerHorizontal="true"
        />

</RelativeLayout>

Looks like I am missing something. Any help would be appreciated!!

A: The solution I have found out is: Use android:layout_below instead of android:layout_alignTop / android:layout_alignRight
<TextView
    android:id="@+id/heading"
    android:text="My First Activity with Relative Layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    />

<Button
    android:id="@+id/button"
    android:text="Save"
    android:layout_width="300px"
    android:layout_height="wrap_content"
    android:layout_below="@id/heading"
    android:layout_margin="20px"
    android:layout_centerHorizontal="true"
    />

Here is the screenshot:

A: I guess you want a button first and a textview second. Then you can do something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MyActivity">

<TextView
    android:id="@+id/heading"
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

<Button
    android:id="@+id/button"
    android:text="@string/sachin_jain"
    android:layout_width="wrap_content"
    android:layout_height="20dp"
    android:layout_alignRight="@+id/heading"
    android:layout_alignTop="@+id/heading"
    android:layout_centerHorizontal="true"
    />

</RelativeLayout>

Your problem was that you had:
 android:layout_alignLeft="@+id/heading"
    android:layout_alignTop="@+id/heading"

in your button that made both the view align top of eachother.


text:
Q: Speed up Join tables Working to join 3 tables i manage to get my results when joining the first two:
SELECT so.id, so.title, so.cat, sr.img
FROM extended_details AS so
JOIN details AS sr ON so.id = sr.id
LIMIT 6

The problem comes when i try to join a third table like so:
SELECT so.id, so.title, so.cat, sr.img
FROM extended_details AS so
JOIN details AS sr ON so.id = sr.id
JOIN scores AS se ON sr.id = se.id
ORDER BY score_sec DESC
LIMIT 6

This seems to take forever and i never get my results, each table have around 300k ids and i've tried correlated subqueries but i'm afraid this could take longer.
The problem seems to be at ORDER BY since running
SELECT so.id, so.title, so.cat, sr.img, se.score
        FROM extended_details AS so
        JOIN details AS sr ON so.id
        JOIN scores AS se ON se.id = sr.id
        LIMIT 6

does not have a problem.

A: Given the lack of detail in the question, no information about primary keys, unique or other indexes...
We suspect the absence of suitable indexes is causing a very inefficient execution plan.

Suggestions:

*

*Add some appropriate indexes.

*Use EXPLAIN to see the execution plan for the query.

*Without a suitable index, the ORDER BY col is going to require a "Using filesort" operation on a (reportedly) large set.

*the LIMIT clause is applied as nearly the last step, after the entire resultset is sorted.


text:
Q: How to handle transient/application failures in Apache Flink? My Flink processor listens to Kafka and the business logic in processor involves calling external REST services and there are possibilities that the services may be down. I would like to replay the tuple back into the processor and Is there anyway to do it? I have used Storm and we will be able to fail the tuple so that the the tuple will not be acknowledged. So the same tuple will be replayed to the processor.
In Flink, the tuple is being acknowledged automatically once the message is consumed by Flink-Kafka Consumer. There are ways to solve this. One such way is to publish the message back to the same queue/retry queue. But I am looking for a solution similar to Storm.
I know that Flink's Savepoint/Checkpoint will be used for fault tolerance. But in my understanding, the tuples will be replayed win case of the Flink's failure. I would like to get ideas on how to handle transient failures.
Thank you

A: When interacting with external systems I would recommend to use Flink's async I/O operator. It allows you to execute asynchronous tasks without blocking the execution of an operator.
If you want to retry failed operations without restarting the Flink job from the last successful checkpoint, then I would suggest to implement the retry policy yourself. It could look the following way:
new AsyncFunction<IN, OUT>() {
    @Override
    public void asyncInvoke(IN input, ResultFuture<OUT> resultFuture) throws Exception {
        FutureUtils
            .retrySuccessfulWithDelay(
                () -> triggerAsyncOperation(input),
                Time.seconds(1L),
                Deadline.fromNow(Duration.ofSeconds(10L)),
                this::decideWhetherToRetry,
                new ScheduledExecutorServiceAdapter(new DirectScheduledExecutorService()))
            .whenComplete((result, throwable) -> {
                if (result != null) {
                    resultFuture.complete(Collections.singleton(result));
                } else {
                    resultFuture.completeExceptionally(throwable);
                }
            })
    }
}

with triggerAsyncOperation encapsulating your asynchronous operation and decideWhetherToRetry encapsulating your retry strategy. If decideWhetherToRetry returns true, then resultFuture will be completed with the value of this operation attempt.
If resultFuture is completed exceptionally, then it will trigger a failover which will cause the job to restart from that last successful checkpoint.


text:
Q: FlashDevelop - change default choice for autocompleted classes Sometimes there is a name conflict between classes in two different libraries, but I almost exclusively use one over the other. Unfortunately, the one I am using is not showing up as the first entry and I have to press the down arrow to pick it.
How can I change the one that shows up first by default?

A: This is not currently possible using FlashDevelop.  You can see a response from the developer in this forum post with a similar question here: Sorting Types in CodeCompletion


text:
Q: Can I compute correlation between two images using imfilter in matlab? Suppose I want to perform correlation between two images. I know there is a function normxcorr2 which can be used to find the correlation between two images (img1, img2) like this
C = normxcorr2(img1, img2)

But can I find the correlation using imfilter? Does this command perform correlation?
corr = imfilter(img1, img2, 'corr','replicate');

When I run the imfilter command and use the imshow() command to output the resulting image, I can see that it is different from what I get when I output the resulting image using normxcorr2 command.The image generated through normxcorr2 looks more like what i would expect from the correlation of the two images. What's the difference between these two methods?

A: There are differences between named functions in MATLAB. To be more specific, imfilter function performs a single convolution, and the normxcorr2 performs correlation between two signals (images). To read more about the difference between convolution and correlation this link may help.
There are also other functions in MATLAB namely xcorr2 to calculate cross-correlation and filter2 for FIR filtering of img1 by img2.


text:
Q: Good books on stochastic partial differential equations? I have a system of 2 PDEs, one with a probabilistic right side, and kind of stuck on what to read about those things.. Any good books around? Both analytical (if any) and numerical methods are welcome.
I have some PDE literature and some SDE literature, but need to figure out SPDEs... Thanks!

A: On the analytical side, I like a lot the book A Concise Course on Stochastic Partial Differential Equations by Prevot and Roeckner. It is a very well written introduction to SPDEs.
Besides this, I know a couple of people who are very fond of Stochastic Equations in Infinite Dimensions by da Prato and Zabczyk.