text:
Q: ON DUPLICATE KEY UPDATE for specific index, or combined indices I have a table on which we've, up until this point, used an ON DUPLICATE KEY UPDATE query to populate and update, with a foreign key(booking_id) from the initial insert being the duplicate index for update cases.
        INSERT INTO ship_docs (booking_id, boarding_date, shipping_date, special_number)

        VALUES (bookingId, boardingDate, shippingDate, specialNumber)

        ON DUPLICATE KEY UPDATE
        boarding_date = boardingDate, shipping_date = shippingDate, special_number = specialNumber;

We now need to introduce a UNIQUE constraint to prevent duplicates of special_number. This query will no longer function as intended, as although on first INSERT the booking_id as an FK will be unique to it's respective table, special_number still has it's potential for collision. Because they are inserted at the same time, the query now updates on the (if it exists) special_number. Is there any reason to pursue hanging onto this method?
I've already split the query into they're individual branches, but is it still possible to get the job done with only one? I understand the non-existence of WHERE clauses in this scenario, and I haven't been able to rationalize an IF statement as a solution as I wouldn't like the query to UPDATE with either incorrect or repeated values, as I am trying to prevent updates on the wrong row, and return information of the rejection, while still being able to edit or update special_number.
Is this attempt to keep this method not worth the benefits, or supposed time saved? Or is there a way to either specify the only DUPLICATE KEY to be used? Or a way to introduce a 'unique pair' index for the conjunction of the booking_id FK and the special_number UNIQUE indices?
Or should I just being doing separate queries.

A: I ended up going the route Akina suggested somewhat. Because the other suggestions wouldn't exactly solve what I was hoping to take care of, and the limitations of the ODKU, for now I've just split it into separate calls, and will most likely come back to in with a stored procedure if need be.


text:
Q: In Javascript how to wait for a function with ajax call to completer before continuing with another function Here is an over view of my js file where I am calling 2 function foo1 and foo2.
function foo1(){
 // do some ajax call which takes random amount of time
}

function foo2(){
 // do something which needs foo1() being already  done
}

foo1();
// reach here only if foo1 is complete
foo2();

ps. I dont want to use jQuery or knockout.
Also have already looked into How to wait for a func...

A: Given you say foo1() is doing ajax, you'd need something like this:
function foo1() {
   $.ajax( ....
       success: function() { foo2(); }
   );
}
function foo2() {
    console.log("foo1() finished");
}

foo1();

So when the ajax call returns (successfully), it'll automatically call foo2(), and the only thing you need to do is call foo1().

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP unlink denied on localhost / windows In portuguese language we use an expression to tell what's going on which is:

this is witchcraft

So, I'm trying to unlink an image, and while I'm writing this topic I'm thinking about the possibility of <img src='url'/> means that the image is open (?).
I have an html table with two columns.
#        |     Image
Delete      Image here displayed
Delete      Image here displayed
etc..       etc...

By clicking "Delete", an AJAX function is performed.
$(".delete").on('click', function(){
    var parent = $(this).parent();
    $.ajax({
        url: 'inc/response.php?type=deleteImage',
        data: {id: $(this).attr('id')},
        type: 'POST',
        success: function(data){
            parent.remove();
        }
    });
});

And the code for deleteImage is the following:
$path = "../images/videos/" . $image->get($_REQUEST['id']);

This returns perfectly the path.
unlink($path);

If the path is incorrect the php log returns:

Error on unlink because file or directory does not exists..

, but the message I'm getting is

PHP Warning:
unlink(../images/videos/): Permission denied in
  C:\xampp\htdocs\newproject\inc\response.php

Since I'm working locally and it's windows, I've set the right administration rights for the folder.
Btw, the folder has the following structure:
images
   > Videos
         > customer_A
         > customer_B
         > customer_C

The Total Control flag is set for EVERY user.
So, what am I doing wrong? Can the problem be because of the image is "open" in the <img src> ?

A: You are trying to remove ../images/videos/ directory. It seems your $image->get($_REQUEST['id']) returns empty.


text:
Q: Cocoa-touch - implementation files? In Xcode, you can view all the header files of the cocoa-touch framework, but I'm just curious to see what some of the implementations look like. Is there a way to see them? They must be on the system somewhere, right? The header doesn't do anything without the implementation.

A: The implementation files are compiled into libraries (binaries) and only the header files are provided. They are your contract or entry-point into those binaries. The iPhone SDK is currently closed-sourse so you won't be able to get access to the implementation files, sorry.

A: You might like to check out this (incomplete) implementation of UIKit for Leopard. It might give you some idea of how things work.


text:
Q: Optional pipping to shell script I want to get the content of stdin in a variable only if something was pipped to the script, the code I'm using is:
input=$(cat)
echo "$@ $input"

Doing echo 'something' | ./script works as expected, but not pipping anything just makes the script waiting indefinitely for input. How do I ignore empty stdin?

A: Testing if something was passed to stdin like this before trying to set a variable seems to solve the problem:
if ! [ -t 0 ]; then
    input=$(cat)
fi


text:
Q: return values from multiple matching rows First off, I'd like to do this without VB if possible, so I don't have to go through the hassle of teaching recipients how to enable macros.
Now, I believe what I'd like to do is simple, but the answer may be complex formula-wise. I'm trying to list out in new columns the values from a specified column in rows which have matching values from two other columns. Sounds tricky I'm sure, but an example should help immensely...
Say I have the following data:
 ------------------
| sts | pos  | bye |
 ------------------
| 0   | QB   | 8   |
| 2   | WR   | 3   |
| 2   | QB   | 10  |
| 0   | QB   | 4   |
| 2   | QB   | 7   |
| 0   | WR   | 11  |
| 2   | WR   | 9   |
| 2   | QB   | 5   |
 ------------------

That's my source. I want to list out the bye value from all rows that have sts = 2, for each respective pos. In other words, from the source data above I'd want to see the following result set:
 --------------------------
| pos | byes               |
 --------------------------
| QB  | 10  | 7  | 5  |    |
| WR  | 3   | 9  |    |    |
 --------------------------

...because those are the bye values in the rows with sts = 2 and pos equal to the corresponding pos in the result table.
Again, I'd like to avoid macros if possible, and just use a formula in the bye cells of the results table.
Hopefully that makes enough sense for you to take a stab at it. Thanks!
FOLLOW-UP:
@Richard-Morgan I attempted to use your formula but can't get it to work. Here is a screenshot of my actual spreadsheet so we can use real cell references:

So sts is B2:B303, pos is D2:D303, and bye is E2:E303. So then I'd like to list out the byes in columns U thru Y. It looks like your answer, if I'm smart enough to implement it, will get me what I need, so any assistance you can provide to get me to the finish line is greatly appreciated!

A: Something along the lines of the following could be used:
{=INDEX(tbl, SMALL(IF(COUNTIF(G$3, $A$2:$A$9)
 *COUNTIF(G$4, $B$2:$B$9), ROW(tbl)-MIN(ROW(tbl))+1), ROW($C1)), COLUMN($C1))}

where the A column is sts, B column is pos, and C column is bye.  The variable tbl is the range of data (not the headers).  G$3 would be the sts filter and G$4 is the pos filter.
Copy the array formula DOWN to find all the matching byes; #NUM! will appear after finding no more matches.  If this bothers your users, you can add an ISERROR or a tricky conditional format that makes the text white on white.
You can then copy over the formula to the next column and enter new filter values.
            G   H
sts Search  2   2
pos Search  QB  WR

            10  3
            7   9
            5   #NUM!
            #NUM!#NUM!

If your users are comfortable with pivot tables, using them would be much easier, I would think.
EDIT
Making the formula "transpose" is a bit tricky and I am not having any breakthrough on how to fix that.  However, if you want to manually edit the column formulas, here is what you want.
(I made the assumption that S is the sts filter.  Maybe you're just doing a count there, but I didn't see where you enter the filter for sts.  If S isn't the sts filter, update the formulas to point to where sts is 2 or whatever.)
U2:
{=INDEX(tbl, SMALL(IF(COUNTIF($S2, $B$2:$B$303)*COUNTIF($R2, $D$2:$D$303),
 ROW(tbl)-MIN(ROW(tbl))+1), ROW($D$1)), COLUMN($D$1))}

V2:
{=INDEX(tbl, SMALL(IF(COUNTIF($S2, $B$2:$B$303)*COUNTIF($R2, $D$2:$D$303),
ROW(tbl)-MIN(ROW(tbl))+1), ROW($D$2)), COLUMN($D$2))}

etc.
This allows the cells to be copied down.
I am sure there is a way to INDIRECT the ROW/COLUMN, but I ran out of time to look at this at the moment.
EDIT 2
If you put a simple number increment somewhere, let's say U1 has 1, V1 has 2, W1 has 3, etc., you could use the following:
{=INDEX(tbl, SMALL(IF(COUNTIF($S2, $B$2:$B$9)*COUNTIF($R2, $D$2:$D$9),
ROW(tbl)-MIN(ROW(tbl))+1), U$1), COLUMN($D$1))}

This will copy down and across.

A: This sounds like a job for pivot tables and go to special. You need to add an ID # column though. Here is one way you could do it:

Then once the blanks are selected using go to special you just need to delete them and shift cells left.

Good Luck.

A: OK I figured out a way to get my desired results. It isn't the cleanest or best way, but it achieves my goal of listing the results horizontally, and avoids macros or pivot tables.
I use a hidden worksheet to list out all the pos and sts values, concatenated as a single value. So...
sts   | pos   | bye
----------------------
2     | QB    | 8
2     | RB    | 5
2     | QB    | 11
0     | WR    | 7
. . .

...becomes....
     D   | E
    -----------
5  | 2QB | 8
6  | 2RB | 5
7  | 2QB | 11
8  | 0WR | 7
     . . .

Then, I have a "shadow" results area that mimics the results area on my front-page worksheet. It looks like so:
     G   | H   | I   | J   | K
    -----------------------------
5  | QB  |     |     |     |     |
6  | RB  |     |     |     |     |
7  | WR  |     |     |     |     | . . .

In H5:H7, I have the following formula:
=IFERROR((ADDRESS(MATCH("2"&$G5,$D$5:$D$305,0)+4,COLUMN($E5),4)),"")

This returns the first cell reference it finds in the concatenated column that starts with 2 and ends with the value in column G (e.g. the formulas in row 5 are looking for "2QB").
Then, in I5:n7 I have the following modified formula:
=IFERROR(ADDRESS(MATCH("2"&$G5,INDIRECT(ADDRESS(ROW(INDIRECT(H5))+1,4)&":$d$"&MAX(305,ROW(INDIRECT(H5))+1)),0)+ROW(INDIRECT(H5)),COLUMN($E5),4),"")

The reason I modify the subsequent columns is to change the range in which the formula is looking for its value to start at the next row after the previously found value. For example, with the data above, the formula in H5 would look for "2QB" in D5:D*n*, and return the first row it finds and attach it to column E, which would be E5.
The formula in I5 would then look for "2QB" starting in D*6* instead of D5, a row after the row referenced in H5's result.
Hopefully that made sense.
So what I end up with in my hidden worksheet is this:
     G   | H   | I   | J   | K
    -----------------------------
5  | QB  | E5  | E7  |     |     |
6  | RB  | E6  |     |     |     |
7  | WR  |     |     |     |     | . . .

Then, on my front page worksheet, I simply get the values (the bye) referenced by the cells in H5:*n*7 using:
=IFERROR(INDIRECT(lookups!H5),"")

...which gives me my final result:
     G   | H   | I   | J   | K
    -----------------------------
5  | QB  | 8   | 11  |     |     |
6  | RB  | 5   |     |     |     |
7  | WR  |     |     |     |     | . . .

Like I said, it's totally convoluted, but it works, and I can always refine it later if I figure out how. :)  Thanks to you who took a swing at this seemingly complex problem for me! I'm sure your answers work beautifully as well.


text:
Q: How to spring bind for multiple level classes like student.userAccount.role? I want to know how to perform spring binding for multiple level class mapping.
I will take an example and explain my problem.
Suppose I have a class hierarchy which says that a Student(POJO) has a UserAccount(POJO) and the useraccount has a role(attribute defined inside UserAccount POJO) I want to display the role in the JSP using JSTL.
So I have one-to-one mapping for student and useraccount I am using Spring MVC and Hibernate at the backend.
I tried searching on the internet for solutions but I really could not find any useful link.
I want to do form based spring binding.
<form:input path = "${student.userAccount.role}" />

This is what I am not sure as I did not find working anywhere on the net.

A: make the form commandName=student and change the path reference
<form:form id="frm" commandName="student" action="/MyController" method="POST">
<form:input path = "userAccount.role" />

Assuming they have been added to the model correctly in the controller.


text:
Q: How can i update the value in the list of ceiling using resttemplate? 1.there is the json list for the controller and the data that what i've been used
[
  {
    "id" : 1,
    "cardname" : "visa gold",
    "cardnumber": "1254***548**54",
    "status" : true,
    "opposed" : false,
    "issueDate" : "21-06-2021",
    "cardbalance" : 200000,
    "validitydate" : "25-06-2021",
    "experationdate" : "30-06-2023",
    "onlinepayment" : true,
    "contactless" : true,
    "withdrawal" : false,
    "ceiling" : [{
      "maxValue" : 10000,
      "minValue" : 500,
      "value" : 100000,
      "currency" : "MAD",
      "type" : "paiment"
    }]

2.and there is my restcontroller code
    @PutMapping("/update/{id}")
    public Ceiling update(@RequestParam Integer id, Card card){
        ParameterizedTypeReference<List<Card>> responseType = new ParameterizedTypeReference<List<Card>>() {};
        ResponseEntity<List<Card>> resp = restTemplate.exchange(GET_CARD, HttpMethod.GET, resp, responseType);
        List<Card> list = resp.getBody();
        return ;
    }

the problem is the put doesn't work the value in the list ceiling , they give me the error : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required Integer parameter 'id' is not present]

A: you have your card Object as a Parameter which contains the response of the json object. You can update the values using the card object.

A: The error message,

Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required Integer parameter 'id' is not present]

which says the id request parameter is not present in the URL.
If you are passing the id as an request parameter, then the URL should be like  /update?id=12345 and controller method should defined like follows,
@PutMapping("/update")
public Card update(@RequestParam(value="id") Integer id, Card card){

    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<Card> request = new HttpEntity<>(card);
    ResponseEntity<Card> response = restTemplate.exchange(GET_CARD, HttpMethod.GET, request, Card.class);
    return response.getBody();
}

NOTE : you have not mentioned any information about the relationship between the Card and Ceiling entities. So just assuming that the GET_CARD endpoint is updating the card which we are passing through REST call and returning the updated Card with the response, I have modified the method body as above.
And if you need to send the id as a path variable, then the URL should be like update/{id} and controller method should be like,
@PutMapping("/update/{id}")
public Card update(@PathVariable("id") Integer id, Card card){

    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<Card> request = new HttpEntity<>(card);
    ResponseEntity<Card> response = restTemplate.exchange(GET_CARD, HttpMethod.GET, request, Card.class);
    return response.getBody();
}


text:
Q: Aggregating by unique identifier and concatenating related values into a string I have a need that I imagine could be satisfied by aggregate or reshape, but I can't quite figure out.
I have a list of names (brand), and accompanying ID number (id).  This data is in long form, so names can have multiple ID's.  I'd like to de-dupicate by the name (brand) and concatenate the multiple possible id's into a string separated by a comment.
For example:
brand            id
RadioShack       2308
Rag & Bone       4466
Ragu             1830
Ragu             4518
Ralph Lauren     1638
Ralph Lauren     2719
Ralph Lauren     2720
Ralph Lauren     2721
Ralph Lauren     2722

should become:
RadioShack       2308
Rag & Bone       4466
Ragu             1830,4518
Ralph Lauren     1638,2719,2720,2721,2722

How would I accomplish this?

A: Let's call your data.frame DF
> aggregate(id ~ brand, data = DF, c)
         brand                           id
1   RadioShack                         2308
2   Rag & Bone                         4466
3         Ragu                   1830, 4518
4 Ralph Lauren 1638, 2719, 2720, 2721, 2722

Another alternative using aggregate is:
result <- aggregate(id ~ brand, data = DF, paste, collapse = ",")

This produces the same result and now id is not a list anymore. Thanks to @Frank comment. To see the class of each column try:
> sapply(result, class)
      brand          id
   "factor" "character"

As mentioned by @DavidArenburg in the comments, another alternative is using the toString function:
aggregate(id ~ brand, data = DF, toString)

A: A nice clean one line in data.table
library(data.table)
setDT(DF)

TWO OPTIONS:
results as a list
DF[ , .(id = list(id)), by = brand]
          brand                       id
1:   RadioShack                     2308
2:   Rag & Bone                     4466
3:         Ragu                1830,4518
4: Ralph Lauren 1638,2719,2720,2721,2722
>

results as a string
DF[ , .(id = paste(id, collapse=",")), by = brand]
          brand                       id
1:   RadioShack                     2308
2:   Rag & Bone                     4466
3:         Ragu                1830,4518
4: Ralph Lauren 1638,2719,2720,2721,2722

Note
Even though the two results appear the same (that is when you print them, they  look identical), they are in fact very different and allow for different functionality.
Namely, using the list option (the first one) allows you to then perform functions on the orignal ids.
The latter will allow you to display the information more easily (including exporting to CSV or excel), but to operate on the id's will require splicing them back.

A: Or using dplyr:
library(dplyr)
DF %>%
  group_by(brand) %>%
  summarise(id = paste(id, collapse = ","))

Where DF is the name of your data.frame.

A: Here's the information in base R:
myby <- by(df$id,df$brand,function(x)paste(x,collapse=","))

The formatting of "by" objects is weird. You can take data.frame(id=c(myby)) and the brands will become rownames:
#                                    id
# RadioShack                       2308
# Rag & Bone                       4466
# Ragu                        1830,4518
# Ralph Lauren 1638,2719,2720,2721,2722

Alternately, if you load the data.table package, this will work:
dt <- data.table(df)
dt[,paste(id,collapse=","),by=brand]
#           brand                       V1
# 1:   RadioShack                     2308
# 2:   Rag & Bone                     4466
# 3:         Ragu                1830,4518
# 4: Ralph Lauren 1638,2719,2720,2721,2722


text:
Q: Python: Write XML processing instructions To create WIX installers from Python, i need to write include.wxi files with parameters.
They consist of XML processing instructions. It should look like this:
<?xml version="1.0" encoding="utf-8"?>
<Include>
  <?define version="3.0.4"?>
  <?define Productcode="{D611455A-2118-415B-829F-D8B16EB4B818}"?>
  <?define Upgradecode="{5E44308A-A383-4A7D-948E-83ECBB4AE300}" ?>
</Include>

So, i am struggeling now at this task.
import xml.etree.ElementTree as ET
        # create the file structure
        data = ET.Element('Include')
        item1 = ET.ProcessingInstruction(define, "TestText=123")

        tree = ET.ElementTree(data)

        tree.write("page.xml",
            xml_declaration=True,encoding='utf-8',
            method="xml")


text: Q: Password protect Chrome settings Is there a way to create a rudimentary hiding of Chrome settings behind a password? I'm looking to prevent modification of extensions specifically. Not looking to password protect Chrome itself, just the settings page.


text:
Q: Scroll when rubber band reaches edge of panel I have a rubber band that captures the cursor. How can I scroll a panel if the cursor reaches the edge of the panel? Let me know if you need more info, I think it explains itself.

A: You need to use the MouseMove event and check if the button is down and the cursor is located close to the edge of the panel.  Say within 5 pixels.  Enable a timer if that's the case, it should tick at ~200 msec.  In the Tick event handler adjust the panel's AutoScrollPosition property to make it scroll.
Keep in mind that the effective mouse position is e.Location plus AutoScrollPosition.


text:
Q: Multiple Image upload in django rest framework How to upload multiple images in DRF. I'm getting all the list of images while looping through it, but it only saves the last one. I want to save all the image and show it in response. Do I have to create separate serializer for Multiple Image serialization?
#models
class ReviewRatings(models.Model):
    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)])
    created_at = models.DateField(auto_now_add=True)
    review = models.CharField(max_length=500, null=True)
    updated_at = models.DateField(auto_now=True)

    def __str__(self):
        return self.product.product_name

class ReviewImages(models.Model):
    review = models.ForeignKey(ReviewRatings, on_delete=models.CASCADE, related_name='review_images', null=True, blank=True)
    images = models.ImageField(upload_to='reviews/review-images', null=True, blank=True)

    def __str__(self):
        return str(self.images)

#Serilaizer
class ReviewImagesSerializer(ModelSerializer):

    class Meta:
        model = ReviewImages
        fields = ["images"]

class ReviewSerializer(ModelSerializer):
    user = SerializerMethodField()
    review_images = ReviewImagesSerializer(many=True)

    class Meta:
        model = ReviewRatings
        fields = [
            "user",
            "rating",
            "review",
            "created_at",
            "updated_at",
            "review_images",
        ]

    def get_user(self, obj):
        return f"{obj.user.first_name} {obj.user.last_name}"

#Views
class SubmitReview(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, product_slug):
        data = request.data
        if data["rating"] == "" and data["review"] == "":
        review = ReviewRatings.objects.create(
            user=request.user,
            product=product,
            rating=data["rating"],
            review=data["review"],

        )
        review_images =request.FILES.getlist('review_images')
        rev = ReviewImages()
        for image in review_images:
            rev.review=review
            rev.images = image
            rev.save()

        serializer = ReviewSerializer(review, context={'request':request})
        return Response(serializer.data, status=status.HTTP_201_CREATED)

#Postman

Response I get on the current implementation
{
    "user": "Jackson Patrick Gomez",
    "rating": 4.8,
    "review": "Pendant -1 review by jackson with image uploadss",
    "created_at": "2022-12-05",
    "updated_at": "2022-12-05",
    "review_images": [
        {
            "images": "http://127.0.0.1:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
        }
    ]
}

The response I want to get is like this
{
    "user": "Jackson Patrick Gomez",
    "rating": 4.8,
    "review": "Pendant -1 review by jackson with image uploadss",
    "created_at": "2022-12-05",
    "updated_at": "2022-12-05",
    "review_images": [
        {
            "images": "http://127.0.0.1:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
        },
        {
            "images": "http://127.0.0.1:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
        },
        {
            "images": "http://127.0.0.1:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
        }

    ]
}

I want to upload multiple images.

A: Are you not saving the same object instance over and over?
rev = ReviewImages()
for image in review_images:
    rev.review=review
    rev.images = image
    rev.save()

Create a new instance for every image:
for image in review_images:
    rev = ReviewImages(review=review, image=image)
    rev.save()

A: I have found out the mistake. I was only creating one instance. Hence only one object was getting created.
#Mistake
rev = ReviewImages()
for image in review_images:
    rev.review=review
    rev.images = image
    rev.save()

#Correct
for image in review_images:
    rev = ReviewImages()
    rev.review=review
    rev.images = image
    rev.save()

or

for image in review_images:
    ReviewImages.objects.create(images=image, review=review)


text:
Q: My three.js line geometry is not showing on screen I want to draw lines using three.js, this code is copied from the three.js line documentation but this is not showing any results. I am getting just blank white screen.
const renderer = new THREE.WebGLRenderer({ antialias: true });
const scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.z = 30

const path = new THREE.Path();

path.lineTo(0, 0.8);
path.quadraticCurveTo(0, 1, 0.2, 1);
path.lineTo(1, 1);

const points = path.getPoints();

const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({ color: 0x8B008B });

const line = new THREE.Line(geometry, material);
scene.add(line);

var render = function () {
    requestAnimationFrame(render);
    renderer.render(scene, camera);
}
render();

A: You've created a renderer, but you haven't set its size, nor have you added its canvas to the HTML document.
Follow the example in the "Getting started" section:
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );


text:
Q: Enable static links in JQuery Cycle I'm using the newest version of JQuery Cycle, taking advantage of the custom pagerAnchorBuilder function like so:
pagerAnchorBuilder: function(idx, slide) {
    // return selector string for existing anchor
    return '#nav li:eq(' + idx + ')';

Those list items under #nav are also tied into a Jquery Accordion so when you click on them, a larger background image changes and the accordion drops down to reveal content.
Inside that content I have text links, but they don't work, not sure why, any ideas would be awesome. Thank you!


text:
Q: popen() alternative My question is extension of this one: popen creates an extra sh process
Motives:
1) My program need to create a child which does tail on a file. I need to process the output line by line. That is why I am using popen because it returns FILE *. I can easily fetch single line, do what I need to do and print it.
One problem with popen is that you do not get pid of child (tail command in my case).
2) My program should not exit before its child is done. So I need to do wait; but without pid, I cannot do it.
How can I achieve both the goals?
A possible (kludge) solution: do execvp("tail -f file > tmpfile") and the keep reading that tmpfile. I am not sure how good this solution is, though.

A: Why aren't you using pipe/fork/exec method?
pid_t pid = 0;
int pipefd[2];
FILE* output;
char line[256];
int status;

pipe(pipefd); //create a pipe
pid = fork(); //span a child process
if (pid == 0)
{
// Child. Let's redirect its standard output to our pipe and replace process with tail
 close(pipefd[0]);
 dup2(pipefd[1], STDOUT_FILENO);
 dup2(pipefd[1], STDERR_FILENO);
 execl("/usr/bin/tail", "/usr/bin/tail", "-f", "path/to/your/file", (char*) NULL);
}

//Only parent gets here. Listen to what the tail says
close(pipefd[1]);
output = fdopen(pipefd[0], "r");

while(fgets(line, sizeof(line), output)) //listen to what tail writes to its standard output
{
//if you need to kill the tail application, just kill it:
  if(something_goes_wrong)
    kill(pid, SIGKILL);
}

//or wait for the child process to terminate
waitpid(pid, &status, 0);

A: *

*You can use pipe, a function of the exec* family and fdopen. This is non-standard, but so is popen.

*You don't need to wait. Just read the pipe up to EOF.

*execvp("tail -f file > tmpfile") won't work, redirection is a feature of the shell and you're not running the shell here. Even if it worked it would be an awful solution. Suppose you have read to the end of the file, but the child process has not ended yet. What do you do?

A: You can use wait as it doesn't want a PID to wait for but simply waits for the any child process to exit. If you have created other child processes you can keep track of them, and if wait returns an unknown PID you can assume it's from your popen process.

A: I'm not sure why you need the process ID of the child. When the child exits, your pipe read will return an EOF. If you need to terminate the child, just close the pipe.


text:
Q: How Can I re- write this using Linq? Just a quick question .. How canI re-write this using Linq
var turbo =
            (from t in _cat.Data
                where t.Veh_ID == id && t.Engine == engine
                select t.PartNum).FirstOrDefault();

I have tried  something like this but stuck!
var t = _cat.Data.where (x =>x.Veh_ID == id && x.Engine == engine).Select() // << stuck here

Please help Thank you

A: var turbo = _cat.Data
    .Where(x => x.Veh_ID == id && t.Engine == engine)
    .Select(x => x.PartNum)
    .FirstOrDefault()

A: var turbo = _cat.Data
                .Where (t => t.Veh_ID == id && t.Engine == engine)
                .Select(t => t.PartNum)
                .FirstOrDefault();

A: Here you go
var turbo = _cat.Data.Where(t.Veh_ID == id && t.Engine == engine)
                     .Select(x => x.PartNumber)
                     .FirstOrDefault();


text:
Q: pop up of confirmation box when closing tab/window only Hello i need a pop up message of confirmation when going to close browser/tab only, not when going to click on any link. In my code, it gave me pop up message when i close browser/tab as well as click on any link, which i don't want. I really have no idea how to do it. Can anyone please help me.
My code  is-

© Copyright 2008
 Inc. All rights reserved.

A: Try this:-

    click here

A: Your said event onbeforeunload works perfectly.
window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

See it in action.

A: Tl/Dr
The below code will be completely pseudo-code describing the method you'll need to run through to get this to work.

The first step is that you'll need to add an identifier to all "internal" links within your site. For example, if your page is contact, and there is a link to that page form your home page, you need to distinguish between the types of pages.
function confirmExit() {
    if (!internal_link) {
        // random shit..
        return message
    }
}
var key = "internal_link";
window[key] = false;
var message = "Your custom message. Are you sure you want to blah?";
window.onbeforeunload = confirmExit;
internal_link = false;
$(document).ready(function () {
    if (!window.location.origin) {
        window.location.origin = window.location.protocol + "//" + window.location.hostname
    }

    $("a").each(function () {
        if ($(this)[0].href.indexOf(window.location.origin) == 0) {
            if ($(this).attr("onclick") == "undefined") {
                $(this).attr("onclick", key + " = true")
            } else {
                if ($(this).attr("onclick")) {
                    var e = $(this).attr("onclick");
                    $(this).attr("onclick", e + " " + key + " = true")
                } else {
                    $(this).attr("onclick", key + " = true")
                }
            }
        } else {
            if ($(this).attr("onclick") !== key + " = true" || $(this).attr("onclick") == "undefined") {
                $(this).attr("onclick", key + " = false")
            }
        }
    });

});

The above is what I've used previously and it's worked perfectly. Basically what it does is adds an attribute to internal links (links within your site), then when users navigate around your site, the onbeforeunload runs the confirmExit() function and checks if the internal_link is false, if so, it shows the message otherwise it navigates through the site.

A: Nothing work for me but I made it with some combinations of the above code and from other forums.

The onbeforeunload event will be fired when you submit a form too, so we need to prevent the event.


text:
Q: Need Help to Convert Callbacks to Promise I don't know how to convert this Callback into a Promise (result, error). Can you show me how it's made and explain with comments?
function calcular()
{
        let conta = 0;;
        var N1 = parseInt(document.getElementById("num1").value);
        var opção = document.getElementById("op").value;
        var N2 =  parseInt(document.getElementById("num2").value);

        if (opção === "+")
        {
            conta = N1 + N2;

        }
}

function MostrarResultado(conta)
{

    document.getElementById("result").innerHTML = "O resultado da sua conta é = " + conta;

}

function Executar(callback)
{
    callback(calcular());
}

function xpto()
{
    setTimeout(function() {Executar(MostrarResultado)}, 3000);
}

A: its not 100% clear on what you want but here is a quick example of what i think your asking for
so to make your function use promises instead of callback you could do something like this
function promiseFunction(){
    return new Promise(resolve =>{
        resolve(result);
    }
}

and when you want to get the data that the function returns you could do this
function getInfoFromFunction(){
    promiseFunction(arg).then(result => {
        console.log(result)
    });
}


text:
Q: Ad mobs blocking function I have created multiple applications using Google admob feature,they all are showing ads ,now I wish to create a new application to block all these ads from all the other applications.I would really very helpful , if anyone can suggested the approach to do so,thank you in advance

A: You just need to make the flag "Display ad", which you can turn off on the basis of the recommendations in this answer.


text:
Q: Receive a message from mqtt whilst simultaneously using a timer The project needs to have the light come on, and stay on 5 minutes after the last "ON" signal given by a motion sensor. My main problem is the logic in receiving the on message while in a loop to restart the timer, kinda new to python so here's what I've got so far:
import paho.mqtt.client as mqtt
import time
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)
GPIO.setup(13,GPIO.OUT)

def on_connect(client, userdata, flags, rc):
     print("Connected with result code "+str(rc))
     client.subscribe("Garage/Outside/+/PIR")

def on_message(client, userdata, msg):
     if msg.payload.decode() == "ON":
          GPIO.output(13,GPIO.HIGH)
          print("Light is on")
          startTime = time.perf_counter()
     endTime = startTime
     while True:
          print(endTime, startTime)
          endTime += 1
          time.sleep(1)
          if endTime - startTime >= 60:
               GPIO.output(13,GPIO.LOW)
               print("Light is off")

client = mqtt.Client()
client.connect("192.168.0.160",1883,60)

client.on_connect = on_connect
client.on_message = on_message

client.loop_forever()

A: You can not make blocking calls in the on_message callback, this function needs to return as soon as possible to allow the MQTT client to continue to receive messages and to handle pings to/from the broker.
If you want to do long running tasks as the result of a received message then you need to run that task on a separate thread.
So you need to move the while True: loop needs to be moved.


text:
Q: Storing Fn types gives error: cast requires that ... is borrowed for 'static` Here is a small code sample representing the problem I currently have. CmdMap stores some logic from Trait types that should be triggered by a String key. This logic requires a context that is provided with the Arg instance. In this Arg instance, we may need mutable references to some objects (represented here by Printer).
Here's the code:
use std::collections::HashMap;

struct Cmd {}

pub trait Trait<T> {
    fn execute(args: T) -> Result<(), String>;
}

impl<'a> Trait<Arg<'a>> for Cmd {
    fn execute(arg: Arg) -> Result<(), String> {
        arg.printer.print("execute".to_string());
        Ok(())
    }
}

struct Printer {
    name: String,
}

impl Printer {
    pub fn print(&mut self, msg: String) {
        self.name = "print".to_string();
        println!("{}: {}", self.name, msg);
    }
}

struct Arg<'a> {
    pub printer: &'a mut Printer,
}

type Callback<T> = dyn Fn(T) -> Result<(), String>;

struct CmdMap<T> {
    pub map: HashMap<String, Box<Callback<T>>>,
}

impl<T> CmdMap<T> {
    pub fn try_execute(&self, name: String, arg: T) {
        self.map[&name](arg);
    }
}

fn test() {
    let mut map: CmdMap<Arg> = CmdMap {
        map: HashMap::new(),
    };
    map.map.insert("test".to_string(), Box::new(Cmd::execute));

    let mut printer: Printer = Printer {
        name: "".to_string(),
    };

    loop {
        map.try_execute(
            "test".to_string(),
            Arg {
                printer: &mut printer,
            },
        );
    }
}

The compiler complains:
error[E0499]: cannot borrow `printer` as mutable more than once at a time
  --> src/lib.rs:57:26
   |
47 |     map.map.insert("test".to_string(), Box::new(Cmd::execute));
   |                                        ---------------------- cast requires that `printer` is borrowed for `'static`
...
57 |                 printer: &mut printer,
   |                          ^^^^^^^^^^^^ mutable borrow starts here in previous iteration of loop
...
58 |         map.try_execute("test".to_string(), Arg { printer: &mut printer });
   |                                                            ^^^^^^^^^^^^ mutable borrow starts here in previous iteration of loop

I don't undersand why the compiler complains here. The first error cast requires that printer is borrowed for 'static, doesn't make sense to me as I'm storing Fn types that need to borrow printer for the time of their execution only.
Am I missing something?


text:
Q: Group sequential design, repeatability/ reliability/ intra-class correlation coefficient (ICC) and sample size calculation I want to test a survey taken by two nurses on the number of patients and determine the intra-class correlation coefficient/reliability. I want to determine the sample size for the analysis which will have multiple interim analysis.
The minimum acceptable reliability (ICC) (p0) is 0.7 and expected reliability (ICC) is 0.85. The power is 80% and overall alpha is 0.05. How do I determine the number of patients needed for this analysis at each interim analysis.


text:
Q: my group_by and mutate functions are not properly working I want to use the max function for each Item in my dataframe, but when I use group_by, it outputs the Items for each Area. I should just have a distinct set of Items though-not duplicate Items. When I replace mutate with summarize, the output is correct; however, I need the Area along with Item and max.
food <- read_csv("data/FAO.csv") %>%
  filter(Element == "Food") %>%
  select(Area, Item, Y2010) %>%
  group_by(Item) %>%
  na.omit() %>%
  mutate(max = max(Y2010))

A: You can select which value of Area you want from each Item.
For example, to select first item you can do :
library(dplyr)

food <- read_csv("data/FAO.csv") %>%
  filter(Element == "Food") %>%
  group_by(Item) %>%
  summarise(max = max(Y2010),
            Area = first(Area))

Or use Area in group_by :
library(dplyr)

food <- read_csv("data/FAO.csv") %>%
  filter(Element == "Food") %>%
  group_by(Item, Area) %>%
  summarise(max = max(Y2010))


text:
Q: Why is rotation about the y axis in $\mathbb{R^3}$ different from rotation about the x and y axis. In my textbook for a counterclockwise rotation about the x-axis we have $\begin{pmatrix}
1 & 0 & 0\\
0 & \cos\theta & -\sin\theta \\
0 & \sin\theta & \cos\theta
\end{pmatrix}$
For rotation about the z-axis we have
$\begin{pmatrix}
\cos\theta & -\sin\theta & 0 \\
\sin\theta & \cos\theta & 0 \\
0 & 0 & 1
\end{pmatrix}
$. Now for rotation about the y-axis it's listed as $\begin{pmatrix}
\cos\theta & 0 & \sin\theta \\
0 & 1 & 0 \\
-\sin\theta & 0 & \cos\theta
\end{pmatrix} $. I can see that they changed it to the rotational matrix for a clockwise matrix but it says right infront of these 3 matrices that they are all for counterclockwise rotations so I'm not entirely sure what's going on.

A: They are all three the same rotation direction. The thing at play here is orientations of coordinate systems.
What right rotation (if you point your right hand thumb along the axis and close your other fingers they will point to the direction of the rotation) around the X-axis does is rotate the Y axis towards the Z axis if XYZ is a right oriented coordinate system (if you take your right hand you can point the thumb in X direction, index finger in Y direction and middle finger in the Z direction).
Now similar is true for rotation about the Z axis, it rotates the X axis towards the Y axis because ZXY is also a right oriented coordinate system.
In fact reordering the axis by rotating/shifting the axes preserves the orientation so XYZ, YZX and ZXY are all positive oriented systems (but just swapping two axes makes it the opposite orientation - giving left orientation). You can also note that swapping twice gets back to the original orientation (all of XYZ, YZX and ZXY can be obtained by swapping two axes).
Now look at what happens to a matrix when you swap axes, then you swap both corresponding columns and rows. And if you do it twice you see that you actually arrive at the three possible matrixes (you can also rotate column- and row- wise if that suits your mind better).

A: If you sight back along the positive $y$-axis toward the origin with the positive $z$-axis pointed upward, the positive $x$-axis points to the left. I.e., taken by itself, the $xz$-plane has a left-handed coordinate system. This means that negative angles correspond to counterclockwise rotations, which is why the third rotation matrix looks like it's backwards.
Another way to convince yourself that the matrix is correct is to look at the effect of a counterclockwise rotation through an angle of $\pi/2$: this takes the positive $x$-axis onto the negative $z$-axis and the positive $z$-axis onto the positive $x$-axis. If you plug $\pi/2$ into the third matrix, you'll see that its first column is $(0,0,-1)^T$ and its third column is $(1,0,0)^T$ just as required.

A: In two dimensions the notion of clockwise and counter clockwise is well defined because all observers of the plane observe it from one direction only. In three dimensions you have two equally legitimate points of view: When rotating around the $z$-axis, for example, you may choose to place an observer at $(0,0,1)$, for whom the rotation about the $z$-axis you wrote will seem as counter clockwise, or you could put an observer at the opposite point $(0,0,-1)$ for whom the same rotation will seem a clockwise rotation. In your case, the rotation for the $y$ axis looks "wrong" to you because you are observing it's effect from the point $(0,-1,0)$. To "see" it correctly, switch to the opposite point, $(0,1,0)$.

A: If you write down your axes by going from one axis to the axis which is left of it, you get
$x$, $z$, $y$.
If you continue, you get $x$, $z$, $y$, $x$, $z$, $y$.
Now, observe that your three matrices are just $3\times3$ sub-matrices of
\begin{equation*}
\begin{pmatrix}
 1 & 0            & 0             & 1 & 0            & 0             \\
 0 & \cos(\theta) & -\sin(\theta) & 0 & \cos(\theta) & -\sin(\theta) \\
 0 & \sin(\theta) & \cos(\theta)  & 0 & \sin(\theta) & \cos(\theta)  \\
 1 & 0            & 0             & 1 & 0            & 0             \\
 0 & \cos(\theta) & -\sin(\theta) & 0 & \cos(\theta) & -\sin(\theta) \\
 0 & \sin(\theta) & \cos(\theta)  & 0 & \sin(\theta) & \cos(\theta)
\end{pmatrix}
\end{equation*}
which is just the usual rotation matrix together with three copies. And these sub-matrices come in the order $x$, $z$, $y$.


text:
Q: Laravel 5 authentication files duplications Hi everyone I am trying to create two different signup/login forms and i want to auth both of them.Since laravel 5 come with default Auth scripts ,I am trying to duplicate the scripts for another signup and login page but I don't know whether is the good idea.Anyone who have idea on how can i approach this is welcomed. Thanks

A: It is easy to reuse Laravel's authentication logic because it has been implemented as a trait. In order to add authentication logic to a controller do one of the following in the controller:
//For Laravel 5.1:
class YourController {
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
}

//For Laravel 5.0:
class Controller {
    use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
}

This will add authentication actions to your controller - see trait's code for more details or visit http://laravel.com/docs/5.0/authentication and http://laravel.com/docs/5.1/authentication


text:
Q: Microsoft Excel VBA Scripting: Recursive column matching Sub NewMacro()
Dim endRow As Long
endRow = Sheet1.Range("A999999").End(xlUp).Row
For i = 1 To endRow
 If Sheet1.Range("A" & i).Value = Sheet1.Range("F" & i).Value Then
    Sheet1.Range("K" & i).Value = "Yes"     Else
    Sheet1.Range("K" & i).Value = "No"
End If
Next i
End Sub

This will compare column A with column F and displays the result in column K.
What I need is if this value is true, then like the above it should compare column B with column G, column C with column H and so on......and should display the results in next column. Please help.

A: I think you need a loop on the columns:
Sub NewMacro()
    Dim endRow As Long
    Dim i As Long
    Dim c As Long
    With Sheet1
        endRow = .Range("A" & .Rows.Count).End(xlUp).Row
        For i = 1 To endRow
            For c = 1 To 5
                If .Cells(i, c).Value = .Cells(i, c + 5).Value Then
                    .Cells(i, c + 10).Value = "Yes"
                Else
                    .Cells(i, c + 10).Value = "No"
                End If
            Next c
        Next i
    End With
End Sub

This compares column A with F, column B with G, column C with H, column D with I and column E with J.  Results are placed in columns K, L, M, N and O respectively.
This is equivalent to using the formula =IF(A1=F1,"Yes","No") in cell K1 and copying it across and down.

And a version which will update columns with "Yes", but stop as soon as it reaches a "No":
Sub NewMacro()
    Dim endRow As Long
    Dim i As Long
    Dim c As Long
    With Sheet1
        endRow = .Range("A" & .Rows.Count).End(xlUp).Row
        For i = 1 To endRow
            For c = 1 To 5
                If .Cells(i, c).Value = .Cells(i, c + 5).Value Then
                    .Cells(i, c + 10).Value = "Yes"
                Else
                    .Cells(i, c + 10).Value = "No"
                    Exit For
                End If
            Next c
        Next i
    End With
End Sub


text:
Q: Regex group words seperated by whitespace I have a question concerning Regex and I hope to get some help. I have a bootstrap code containing several expressions like [col md-6 lg-2] or just [col md-6]. However the amount of columns is not fixed and I can have like [col x y z] or even more.
I'd like to achieve a match with groups like:
Group 1: x
Group 2: y
Group 3: z
... and so on.
Some help would be much appreciated
best regards

A: You'll want to separate your group with preg_replace_callback then split the found string on spaces. Something like this should do it
$return = '';
preg_replace_callback('/\[col \K[^\]]+/', function($match){
    $GLOBALS['return'] = preg_split('/\s+/', $match[0], -1, PREG_SPLIT_NO_EMPTY);
}, '[col md-6 lg-2]');
print_r($return);

https://3v4l.org/koKFH
This \[col \K is looking for the literal string [col then the \K tells the regex to forget it matched that for the capturing. The [^\]]+ then captures everything until the next ]. We then use that found group in the callback to separate on whitespaces (\s).


text:
Q: visual studio 12 windows phone application development I am new for windows phone application development. when start a new windows phone application and press ok i get error as 'no windows phone version supported'.
my os is windows 7 and i use visual studio 12.
- how start a windows phone application in visual studio 12 with windows 7 os.
- how add windows sdk error messagefor the visual studio.
start a project

A: Hi at first I also had that problem, you have to upgrade to windows 8, it is not possible to run wp8 on windows 7.
Hope it has helped.


text:
Q: Pandas groupby on two column and create new column in excel based on result I have excel file which i am reading in jupyter.
It has three column :
1) Webinar ID: (66 unique value)
2) Email: email id of participants (which can log out in session and join again so duplicate email id for same webinar id)
3) Time in session (minutes): participant present in session, since he might log out and again log in, there are multiple entries.
Code Used:
data_group = data.groupby(['Webinar ID', 'Email'])
data_group['Time in Session (minutes)'].sum()
I want to create new column in excel and store Sum of Time in Session (minutes) information for same - Webinar ID and Email
Thanks!!

A: IIUC, you wish to create a new column with the sum of times per webinar group and email.
Let's use groupby with transform:
data['Sum Session Minutes'] = (data.groupby(['Webinar ID','Email'])['Time in Session (minutes)']
                                   .transform('sum'))


text:
Q: Resampling to get equal predictive power per observation Cross posted from data science due to lack of response
This is probably a thing I am just not searching for correctly, but essentially my idea is this: given some machine learning classification $C$ based on an input dataset $D$, certain observations in $D$ are more likely to be misclassified than others because they are "less common".  So what we would want to do is oversample observations like that, until $C$ is trained such that all observations have the probability of being classified correctly.
Is there a resampling method that does such a thing?  My idea would be to

*

*train classifier $C$ on base dataset $D$

*take all observations misclassified by $C$ in $D$ and insert into new dataset $D'$

*retrain $C$ on $D = D + D'$ (or add a new batch with $D'$ in SGD etc)

*iterate that way until some convergence happens

Has someone formalized something along these lines?  Intuitively, we want to overweight under-represented types of data.
Update: An additional thought I had that something along these lines might be useful in Q-learning - that instead of just randomly exploring off-policy, explore in areas where the model is less confident.

A: What you're describing is a classic class imbalance problem. You can find related work here and a scikit-learn specific package here.
If what you want is to focus the power of your model into the misclassified instances, you might want to look into boosting which will do just that.
Boosting is an ensemble approach in which, roughly, each subsequent learner is trained on the mistakes made by the previous one, by maintaining a weight for each example that get increased every time the example is misclassified, and decreased otherwise.


text:
Q: Docker build image Prestashop I'm a Docker beginner. I have pull and configured, installed Prestashop in my docker container.
I would like to build an image with this config.
How can I do?
Thanks.

A: To build a container you would have to run docker build -t myawsome_container:1.0.0 . (providing that you are in the directory where your Dockerfile is located)
Now to run your container you would want to run docker run myawsome_container:1.0.0


text:
Q: Mysql query to find user details of all users who commented on a post? I am new to sql joins. I have three tables: Users, Posts, Post_Comments. Every time a new user comments on a post its user_id along with post_id is saved in the Post_Comments table. Now I want to query the database which will find out names of all the users who have commented on a single post let's say whose id is 2.

A: This looks like joins:
select u.*
from users u
inner join post_comments pc on pc.user_id = u.user_id
where pc.post_id = 2

If a user may comment more than once on a given post, you can use exists to avoid duplicates in the result set:
select u.*
from users u
where exists (
    select 1 from post_comments pc where pc.user_id = u.user_id and pc.post_id = 2
)


text:
Q: D language cast operator overload problem I'm playing with D2 at the moment, I would like to write some simple program but i'm stuck with operator cast overload...I have a Vector class that can be cast to Normal :
class Vector {
    public float x,y,z;
    this(in float x, in float y, in float z){
        this.x = x;
        this.y = y;
        this.z = z;
    }

    //..............

    Normal opCast(T)() if (is(T == Normal)){
        return new Normal(this.x,this.y,this.z);
    }
}

If i write something like
immutable Vector v = cast(immutable(Vector))new Vector(0F, 0F, 0F);

the compiler complains that :
"template instance opCast!(immutable(Vector)) does not match template declaration opCast(T) if (is(T == Normal))"
If I omit the cast:
immutable Vector v = new Vector(0F,0F,0F);

the message changes, but the program does not compile:
"cannot implicitly convert expression (new Vector(0F,0F,0F)) of type Vector to immutable(Vector)"
If I omit the cast operator overload in the Vector class all compile just fine.
Put in a different way...How can I assign or cast an instance to an immutable 'var'?

A: you should not overload opCast normally.
commonly methods named toTypename are used for object that knows how to convert itself to another.
Normal toNormal () { return new Normal (x, y, z); }

A: You have two solutions:

*

*A pretty solution is what Trass3r already mentioned in his comment: Treat immmutable(Vector) as its own data type (it is), and call its constructor.

*A somewhat uglier solution is to use assumeUnique() on the object you want to cast. I think you might need to import a library (std.exception, if I'm not wrong).


text:
Q: Is there any way to resize ubuntu root partition without restarting I want to resize the main ubuntu partition but i dont want to use a boot-drive and i don't have another OS on my pc

A: You are essentially saying "I want to change my bicycle tire, but I don't want to get off my bicycle."
No, you cannot move or shrink a mounted root partition safely.

A: You certainly can't resize your Linux partition while it is in use - in fact I don't think gparted will let you resize a mounted partition at all. The Linux partition must be mounted if you're using it as the os so it can't be possible using conventional tools.
I'd answer this by asking you - why would you want to do that? It's actually very easy to do it from a live usb session, and that is pretty safe. If you've recently installed Ubuntu you probably have the required usb to do it.
Any other method will almost certainly be harder and riskier. As per the answer above, you're doing major work on your vehicle whilst travelling - maybe even more like changing the chassis but keeping the gearbox and engine whilst driving!


text:
Q: Boost Graph: What happens when calling remove_vertex on vertex with degree > 0 From the boost graph manual for the function remove_vertex

It is assumed that there are no edges to or from vertex u when it is removed. One way to make sure of this is to invoke clear_vertex() beforehand.

What happens if you do call remove_vertex() on a vertex that is connected to other vertices? Does it lead to undefined behavior?
From the quote in the manual it would seem that something bad will happen. If so why does it not throw an exception when called in this way?

A: Apart from some algorithms and utilities, the Boost Graph Library in general does not throw exceptions, especially when accessing or modifying the structure of a graph. I guess this decision has been made due to performance reasons.
I'd compare this API model to STL. In STL violating a pre-condition leads to undefined behavior rather than to throwing an exception.


text:
Q: почему не работает case в bash Необходимо используя case иметь возможность вызывать (выполнять) каждую операцию в отдельности, а также выполнить весь код в за один раз.
Вот код:
#!/bin/bash

printf "введит что хотите выполнить: "
read

case $Nomer in #Выполняем заданное действие

    "0")
        # Выполняем разом все действия
    nomer_1
    nomer_2
    nomer_3
    ;;
           #выполняется каждое действие поотдельности
   "1")
    nomer_1
    ;;

   "2")
    nomer_2
    ;;

   "3")
    nomer_3
    ;;
#esac

function nomer_1 {
for i in {1..100};    #создаем файлы
do echo  $(( $RANDOM % 8999 + 1000 )) > /home/BBB/2021-11-25/File$i;done  #рандомно создаем числа сохраняем их в вновь созданные файлы
cat /home/BBB/2021-11-25/* | while read y    #просмотр содержимого файлов из папки
do
echo "$y"
echo "$y" >> /home/BBB/2021-11-25/s    #выводит содержимое на экран, сохраняем все числа из созданных файлов File$i в файле s
done
}

function nomer_2 {
sum=0    #переменная для сложения всех чисел
g=0      #переменная для счетчика
A=0      #переменная в которой сохраняем сумму первой половины чисел
B=0      #переменнная в которой сохраняем сумму второй половины чисел
C=0      #переменная в которой сохраняется самое большое число
#for i in ${mass[@]}
for i in `cat /home/BBB/2021-11-25/s`;   # открываем файл s в котором содержатся числа
do
sum=$((sum+i))    #складываем все числа
let g+=1          #создали счетчик который увеличивается на +1 при каждом проходе цикла
if [[ $g -le 5 ]]; then   #условие в котором говорим что если счетчик меньше или равен 4, тогда числа складваем в переменной A
    A=$(( $A + $i ))
elif [[ $g -ge 6 ]]; then #условие в котором говорим что если счетчик больше или равен 5, тогда числа складваем в переменной B
    B=$(( $B + $i ))
fi
if [[ $A > $B ]]; then     #сравниваем суммы чисел из A и B и выводим если условие верное
C="$A самое большое число лежит в первой чаcти"
#echo "A больше B: $A"
elif [[ $B > $A ]]; then   #сравниваем суммы чисел из B и А и выводим если условие верное
C="$B самое большое число лежит во второй части "
#echo "B больше A: $B"
fi
#echo "$i" "$sum" "$g" "$A" "$B"
done
echo "$A сумма первых 50 чисел" "$B сумма вторых 50 чисел"
echo "$C"    #выводим наибольшее число
}

function nomer_3 {
min=9999
max=0
for i in {1..100}
do
    value=`cat /home/BBB/2021-11-25/File$i`
    if [[ "$value" -lt "$min" ]]
    then
        min=$value
        name="File$i"
    elif [[ "$value" -gt "$max" ]]
    then
        max=$value
        name1="File$i"
    fi
done
echo "Минимальное значение $min найдено в файле $name"
echo "Максимальное значение $max найдено в файле $name1"
echo "Минимальное значение $min найдено в файле $name" >> /home/BBB/2021-11-25/2021-12-30.result
echo "Максимальное значение $max найдено в файле $name1" >> /home/BBB/2021-11-25/2021-12-30.result
}
#rm -f /home/BBB/2021-11-25/*  #с помощью этой строки мы удаляем все что создалось в директории

esac

выдает такую ошибку:
введит что хотите выполнить: 0
./Podsget: line 32: syntax error near unexpected token `nomer_1'
./Podsget: line 32: `function nomer_1 {'

A: Вопрос решен.
Вот код
#!/bin/bash

echo -n "введите слово: "
read Slov  # в переменную Slov попадает слово которое ввел пользователь
B=("WD")    # в этой переменной храниться слово для сравнения

for i in 1; do
if [[ "$Slov" = "$B" ]]; then   #сдесь мы сравниваем введенное слово с те что должно быть
    echo "cool"   # программа может продолжать работать
else
    echo "ввод неверен"   # программа должна полностью остановиться
    exit 1  #в случае если слово введено неверно скрипт полность прекращает работу
fi
done

echo -n "введит что хотите выполнить: "  #здесь мы вводим номер операции которую хотим выполнить
read Nomer

function nomer_1 {
for i in {1..100};    #создаем файлы
do echo  $(( $RANDOM % 8999 + 1000 )) > /home/BBB/2021-11-25/File$i;done  #рандомно создаем числа сохраняем их в вновь созданные файлы
cat /home/BBB/2021-11-25/* | while read y    #просмотр содержимого файлов из папки
do
echo "$y"
echo "$y" >> /home/BBB/2021-11-25/s    #выводит содержимое на экран, сохраняем все числа из созданных файлов File$i в файле s
done
}
echo "$y"

function nomer_2 {
sum=0    #переменная для сложения всех чисел
g=0      #переменная для счетчика
A=0      #переменная в которой сохраняем сумму первой половины чисел
B=0      #переменнная в которой сохраняем сумму второй половины чисел
C=0      #переменная в которой сохраняется самое большое число
for i in `cat /home/BBB/2021-11-25/s`;   # открываем файл s в котором содержатся числа
do
sum=$((sum+i))    #складываем все числа
let g+=1          #создали счетчик который увеличивается на +1 при каждом проходе цикла
if [[ $g -le 5 ]]; then   #условие в котором говорим что если счетчик меньше или равен 4, тогда числа складваем в переменной A
    A=$(( $A + $i ))
elif [[ $g -ge 6 ]]; then #условие в котором говорим что если счетчик больше или равен 5, тогда числа складваем в переменной B
    B=$(( $B + $i ))
fi
if [[ $A > $B ]]; then     #сравниваем суммы чисел из A и B и выводим если условие верное
C="$A самое большое число лежит в первой чати"
elif [[ $B > $A ]]; then   #сравниваем суммы чисел из B и А и выводим если условие верное
C="$B самое большое число лежит во второй части "
fi
done
echo "$A сумма первых 50 чисел" "$B сумма вторых 50 чисел"
echo "$C"    #выводим наибольшее число
}

function nomer_3 {
min=9999  #самое большое число которое может быть минимальным
max=0    #самое маленькое число которое может быть максимальным
for i in {1..100}
do
    value=`cat /home/BBB/2021-11-25/File$i` #читаем поочереди все файлы
    if [[ "$value" -lt "$min" ]]    #ищем самое маленькое число
    then
        min=$value    #записываем в переменную самое маленькое число
        name="File$i" #находим файл в котором храниться самое маленькое число
    elif [[ "$value" -gt "$max" ]]  #ищем самое большое число
    then
        max=$value # записываем в переменную самое большое число
        name1="File$i" #находим файл в котором храниться самое большое число
    fi
done
echo "Минимальное значение $min найдено в файле $name"
echo "Максимальное значение $max найдено в файле $name1"
echo "Минимальное значение $min найдено в файле $name" >> /home/BBB/2021-11-25/$(date +%Y-%m-%d).result
echo "Максимальное значение $max найдено в файле $name1" >> /home/BBB/2021-11-25/$(date +%Y-%m-%d).result
}

case $Nomer in #Выполняем заданное действие

    "0")
        # Выполняем разом все действия
    nomer_1
    nomer_2
    nomer_3
    ;;
        #Выполнение команд по отдельности
   "1")
    nomer_1
    ;;

   "2")
    nomer_2
    ;;

   "3")
    nomer_3
    ;;

esac      #заканчивает работу case

tar cfvz WD.$(date +%Y-%m-%d).tar.gz /home/BBB/Podsget /home/BBB/2021-11-25/* #создаем архив со всеми файлами
rm -f /home/BBB/2021-11-25/*   #удаляем все созданные файлы в директории /2021-11-25


text:
Q: Difference between "smart" and "clever" What is the difference between smart and clever?
As far as I understand the latter is offensive. But the Cambrige Dictionary gives similar definitions of smart and clever.

A: The two are virtually identical, and in most uses, as strong case could be made for either one. However, clever seems to imply level of originality and imagination, where smart could just be well thought out.
A good example of the difference, is illustrated in this apocryphal story about NASA:

During the space race in the 1960's, NASA was faced with the huge problem of how to write in the vacuum and weightlessness of space. There is an email that makes the rounds stating that NASA spent $1.5 millin dollars developing a "space pen," and that the Russians facing the same problem simply used a pencil.

In the preceding story the Americans are smart and the Russians are clever.
I think because of this difference, clever is the one used sarcastically much more than smart.  Similarly to calling someone a genius to imply stupidity.

A: The difference, the way I see it and emphasized, is that smart always implies intelligence, while clever does not (it implies that something is made in a way that is very effective; which can directly imply intelligence).
This is supported by etymologies and dictionaries.
Smart comes from sharp referring to wit, and this meaning is mostly kept. However these days in BrE the sense of BrE neat/AmE sharp and attractive seems to be prevalent and the meaning of intelligent is perceived as Americanism. This dictionary entry seems quite good.
Clever on the other hand comes from a low word that comes from handy, dexterous. Although not a primary meaning of the word, it did not get lost, as it is possible to say that someone has clever hands, meaning skillful hands; where saying that someone has smart hands would need to be explained by the context. Also, see the dictionary.
Here are some examples where you can not substitute clever with smart

I have a clever place to hide a car.
  Bill's very clever with his hands.
  The mechanism is very clever.

Although there is a significant difference between BrE and AmE I believe that in recent years the meanings are getting closer to each other and this particularly due to many new clever gadgets and especially smart devices.

A: Neither of them is offensive.
Technically, a smart person is an educated person, someone with a lot of knowledge. This knowledge may come from education or experience, but it's there.
A clever person is someone who can figure out almost any situation. It doesn't necessarily mean he has the required knowledge, but he's handy, so he can always solve whatever comes his way.
Should I over-emphasize this, just for the sake of your better understanding the difference, a smart person knows the theory, a clever person knows the practice.

A: I've noticed that there is a slight difference between typical British and American usage of these words.  In the U.S., clever usually implies a certain amount of ingenuity, while smart implies general intelligence or knowledge.  There is a feeling of lightness to clever; it is usually used for "little" things like a quick wit in conversation.  A typical good student would be referred to as smart, while a trickster might be called clever.
However, in the U.K. it seems more common to use clever to mean either ingenious or generally intelligent.  That is, clever is used both for the American sense of clever as well as the American sense of smart.  British smart can mean exactly the same as clever, but it seems clever is the preferred term.  This relegates smart (in typical use) to something more akin to "wise" or "sensible".


text:
Q: How does loss extracly work in keras when using train_on_batch? I am confused about loss in keras when using 'train_on_batch'.
See my model below (a implementation of triplet)
Sometimes my model outputs Nan, and the loss still shows something like 0.4.
And after some iterations, the encoder always shows the same output regardless what the input is.
And in that situation the loss of the triplet model should be 0.5 (see function bpr_triplet_loss below), but keras tells the loss is something like 0.1 or 0.2, even sometimes greater than 1 or smaller than 0. Why?
Is it because gradient exploding problem occurs and then the model is broken?
    ter_input = Input(shape=self.img_shape)
    ter_input_pos = Input(shape=self.img_shape)
    ter_input_neg = Input(shape=self.img_shape)

    ed = self.encoder()
    ter_encoded = ed(ter_input)
    pos_encoded = ed(ter_input_pos)
    neg_encoded = ed(ter_input_neg)

    def bpr_triplet_loss(X):
        positive_item_latent, negative_item_latent, user_latent = X
        # BPR loss
        loss = 1.0 - K.sigmoid(
            K.sum(user_latent * positive_item_latent, axis=-1, keepdims=True) -
            K.sum(user_latent * negative_item_latent, axis=-1, keepdims=True))
        return loss

    loss_layer = Lambda(bpr_triplet_loss, output_shape=(1,))([pos_encoded, neg_encoded, ter_encoded])

    def identity_loss(y_true, y_pred):
        return K.mean(y_pred - 0 * y_true)

    self.triplet_net = Model(
        input=[ter_input, ter_input_pos, ter_input_neg],
        output=loss_layer)
    self.triplet_net.compile(loss=identity_loss, optimizer=Adam(0.0001, beta_1=0, beta_2=0.99, decay=0.00001))  # Adam()


text:
Q: Trouble retrieving attributes UPDATE - please see a resolution at the end, all I need now is an explanation.
Despite searching I could not find the same question
I created a custom Viewpager and defined a custom attribute in attrs.xml
In the view pager constructor when I try and retrieve the attribute I cannot get a meaningful value. I tried using
abstract int     getAttributeIntValue(String namespace, String attribute, int defaultValue)

Return the integer value of 'attribute'.
public MyViewPager(Context context, AttributeSet attrs) {
    Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeUnsignedIntValue("http://schemas.android.com/apk/res-auto","view_pager_type",9));
    Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","view_pager_type",9));
    Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","view_pager_type"));
    Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","garbage"));

As you can see the attrs.getAttributeValue did a string but it is not meaningful to me.
This is the output from the log statements - 9 is the default if not found, I do not undertand what the @213 number is
ViewPagerType:9
ViewPagerType:9
ViewPagerType:@2131230723
ViewPagerType:null

This is my attrs.xml
<resources>
    <declare-styleable name="AutoResizeTextView">
        <attr name="ttf_name" format="string"/>
    </declare-styleable>
    <declare-styleable name="ViewPagerType">
       <attr name="view_pager_type" format="integer"/>
   </declare-styleable>
</resources>

This is my layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

<org.rh.ellierides.MyViewPager xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/textPager"
    app:view_pager_type="@integer/text_viewpager"
    android:orientation="horizontal"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="24"
    tools:context=".Main">

This is integer.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="text_viewpager">1</integer>
    <integer name="image_viewpager">2</integer>
</resources>

I think I will just create two separate viewpagers but I would still like to understand this.

Update I found a resolution but do not understand why the first one did not work so please still answer
    TypedArray a = null;
    try {
        a = getContext().obtainStyledAttributes(attrs, R.styleable.ViewPagerType);
        int viewpagerType = a.getInt(R.styleable.ViewPagerType_view_pager_type, 9);
        Log.d(Constant.TAG, "viewpagerType:" + viewpagerType);
    } finally {
        if (a != null) {
            a.recycle(); // ensure this is always called
        }
    }

A: The following Works but as I said above please explain it to me. What are the attrs which are passed to the constructor ?
    TypedArray a = null;
    try {
        a = getContext().obtainStyledAttributes(attrs, R.styleable.ViewPagerType);
        int viewpagerType = a.getInt(R.styleable.ViewPagerType_view_pager_type, 9);
        Log.d(Constant.TAG, "viewpagerType:" + viewpagerType);
    } finally {
        if (a != null) {
            a.recycle(); // ensure this is always called
        }
    }


text:
Q: how to create dataframe like this (provide daily first trip record) by using R I want to change my dataframe like this. How can I do it in R? Do I need double For loops to achieve this ?
ID  DATE        Origin
1   01/01/2012  A
1   01/01/2012  B
1   01/01/2012  C
1   01/02/2012  A
1   01/02/2012  B
1   01/02/2012  C
1   01/03/2012  A
1   01/03/2012  B
1   01/08/2012  A
2   01/01/2012  D
2   01/01/2012  C
2   01/01/2012  B
2   01/04/2012  D
2   01/04/2012  C
2   01/06/2012  D
3   01/03/2012  F
3   01/03/2012  G
3   01/09/2012  F
3   01/09/2012  G

 ID DATE        Origin
    1   01/01/2012  A
    1   01/02/2012  A
    1   01/03/2012  A
    1   01/08/2012  A
    2   01/01/2012  D
    2   01/04/2012  D
    2   01/06/2012  D
    3   01/03/2012  F
    3   01/09/2012  F

(I only want to remain the record like this one ↑)
(daily first trip record for each passenger)
no matter how many travels he did in one day just remain the first one

A: aggregate(Origin ~ ID + DATE, data=x, FUN='[', i=1)
##   ID       DATE Origin
## 1  1 01/01/2012      A
## 2  2 01/01/2012      D
## 3  1 01/02/2012      A
## 4  1 01/03/2012      A
## 5  3 01/03/2012      F
## 6  2 01/04/2012      D
## 7  2 01/06/2012      D
## 8  1 01/08/2012      A
## 9  3 01/09/2012      F

Group by ID and DATE, taking the first value for Origin in each group.


text:
Q: Appending deployment.properties to enable TLS I need to be able to append everyone's deployment.properties file to add additional lines to enable all versions of TLS. Big enterprise uses multiple different versions of Java and also multiple different departments use different exceptions. I have attempted to append the file using powershell but it inserts line spaces between each letter.
this is the only PS script i found that is able to insert into the file.
echo "`r`n deployment.security.SSLv3=true" >> "c:\users\%userprofile%\AppData\LocalLow\Sun\Java\Deployment\deployment.properties"

Here is the code i need to insert
# Advanced Security Settings\Use TLS 1.0
deployment.security.TLSv1=true
deployment.security.TLSv1.locked
# Advanced Security Settings\Use TLS 1.1
deployment.security.TLSv1.1=false
deployment.security.TLSv1.1.locked
# Advanced Security Settings\Use TLS 1.2
deployment.security.TLSv1.2=false
deployment.security.TLSv1.2.locked
# Miscellaneous\Place Java icon in system tray
# Miscellaneous\Java Quick Starter
deployment.system.tray.icon=false
deployment.system.tray.icon.locked

I just need to know how I can do it via a script or powershell for the entire enterprise. with out replacing the original deployment.properties file and with proper formatting.
Thanks guys!

A: The $env:userprofile\AppData\LocalLow\Sun\Java\Deployment\deployment.properties" file has (presumably) ANSI (or UTF-8) encoding.
On the other hand, about_Redirection help topic says:

… When you are writing to files, the redirection operators use
  Unicode encoding. If the file has a different encoding, the output might not be formatted correctly…

To redirect content to non-Unicode files, use the Out-File or Add-Content cmdlet with its Encoding parameter. For instance, something like
$CodeToInsert = @'
# Advanced Security Settings\Use TLS 1.0
deployment.security.TLSv1=true
deployment.security.TLSv1.locked
# Advanced Security Settings\Use TLS 1.1
deployment.security.TLSv1.1=false
deployment.security.TLSv1.1.locked
# Advanced Security Settings\Use TLS 1.2
deployment.security.TLSv1.2=false
deployment.security.TLSv1.2.locked
# Miscellaneous\Place Java icon in system tray
# Miscellaneous\Java Quick Starter
deployment.system.tray.icon=false
deployment.system.tray.icon.locked
'@
$FilePath = "$env:USERPROFILE\AppData\LocalLow\Sun\Java\Deployment\deployment.properties"

Add-Content -Path $FilePath -Value $CodeToInsert -Encoding default

See also

*

*Add-Content for FileSystem,

*Out-File, and

*PowerTip: Use Here-Strings with PowerShell.

Note: you can query the file.encoding property or Charset.defaultCharset() to find the current default encoding in Java.
For the entire enterprise, you could configure above script to Run Once on user logon.


text:
Q: How can I remove the zero that appears after the decimal point I have declared two float variables for addition purpose...
So, the user can input 2.2+2.2 and get 4.4
And sometimes the user will enter 2+2 and will get 4.0>> this zero needs to be deleted.
I can't use the round method nor converting the whole result into an integer.
My Actual code is here:
holder.txtTotalViews.setText(new StringBuilder().append(new java.text.DecimalFormat("#").format(Float.parseFloat(trendingVideoList.get(position).getTotal_views())/1000)).append("K ").append(activity.getString(R.string.lbl_views)));

I need to calculate total views of video into K format like 10K and 10.5K.
I have problem to remove zero from 10.0K.

A: My Issue is resolved by changing decimal format of the code:
Thanks to @Jyoti now my code:
I need to change my new java.text.DecimalFormat("#") to new java.text.DecimalFormat("#.#") like this.
holder.txtTotalViews.setText(new StringBuilder().append(new java.text.DecimalFormat("#.#").format(Float.parseFloat(trendingVideoList.get(position).getTotal_views())/1000)).append("K ").append(activity.getString(R.string.lbl_views)));

A: You can make a common function like this:
// No need to re-create decimal format instance. Keep this outside of the function.
DecimalFormat decimalFormat = new DecimalFormat("#.#");
public String numberToString(float number){
    if(number == (int) number){
        return Integer.toString((int) number);
    }
    return decimalFormat.format(number);
}


text:
Q: How to exclude the first 10 sheets from a spreadsheet? This script here loops through the sheet names and changes the names to match the value in A1. How can I exclude the first 10 sheet names from the execution instead of providing the specific sheet names to be excluded?
function onEdit() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();

  // Array holding the names of the sheets to exclude from the execution
  var exclude =["Sheet1","Sheet2","Sheet3","Article","Frontpage","Logos","Sheet4","Sheet5","Sheet6","Sheet10"];

for(var s in allsheets){
var sheet = allsheets[s];
var oldName = sheet.getName();
var newName = sheet.getRange(1,1).getValue();
if (newName.toString().length>0 && newName !== oldName) {
sheet.setName(newName);

// Stop iteration execution if the condition is meet.
if(exclude.indexOf(sheet.getName())==-1) continue;
  }

} // end of loop

} // end of function

A: Solution
As getSheets() method returns an Array of Sheet instances, you have access to every method designed for iterating over arrays and thus do not need for...in (if want to be able to break out of the loop or use continue statement, use for...of instead).
Use slice()
The simplest would be using slice method - it returns a partial copy of the array without modifying the original. The method call accepts two arguments, both optional:

*

*0-based start index

*0-based end index (end is exclusive)

var arr = ['Sh1', 'Sh2', 'Sh3', 'Sh4', 'Sh5', 'Sh6', 'Sh7', 'Sh8', 'Sh9', 'Sh10', 'Sh11', 'Sh12'];
var relevantSheets = arr.slice(10); //simply slice everything after sheet 10
console.log(relevantSheets); //should log [Sh11, Sh12]

Use splice()
splice() method is very similar to the first one, but allows to "permanently" exclude elements from the array. Just configure it to remove first N elements and do not replace them:

var arr = ['Sh1', 'Sh2', 'Sh3', 'Sh4', 'Sh5', 'Sh6', 'Sh7', 'Sh8', 'Sh9', 'Sh10', 'Sh11', 'Sh12'];
arr.splice(0, 10); //0-based start and end indices (end is exclusive);
console.log(arr); //should log [Sh11, Sh12]

Refer to documentation for an in-depth explanation. In short, this method accepts an indefinite amount of arguments:

*

*Required: 0-based index to start from

*Optional: 0-based index to end before (if not provided or greater than length of the Array the method is called on, removes every element starting from start index)

*Optional: Comma separated list of elements to replace removed items

Note that the method mutates (changes) the original array.

Use forEach()
A more modern approach if you need some side-effects to happen for each element, is using forEach method and checking if index is greater than 10 (array indices are 0-based, hence 9 in sample):

var arr = ['Sh1', 'Sh2', 'Sh3', 'Sh4', 'Sh5', 'Sh6', 'Sh7', 'Sh8', 'Sh9', 'Sh10', 'Sh11', 'Sh12'];

var res = [];

arr.forEach(function(element, index) {
  if (index > 9) {
    res.push(element); //push to test Array;
    //iterable code goes here;
  }
});

console.log(res); //should log ['Sh11','Sh12']

Note that forEach method callback function accepts three arguments:

*

*Required: Array element to iterate over;

*Optional: 0-based index of element currently looped over;

*Optional: Array over which the loop iterates;

Please refer to documentation to better understand how this Array method works. Also, refrain from using a for...in loop in contexts where order of iteration is relevant.
Notes

*

*You do not need to stop iteration after there are no more
Sheet instances in an Array - the loop will terminate upon finishing iterating over the last element.

References

*

*slice() method

*forEach() method

*splice() method

*getSheets() method

*for...of loop

A: Instead of using for(var s in allsheets){
user for(var s=10;i<allsheets.length;i++) {


text:
Q: How common is it to plot linear transforms on continuous spaces? I came across a question asking how the proof that the transform $f(g) = g(x-a) + g(x+a)$ was Hermitian worked. I was a bit surprised that the proof was symbolic, because if you plot out the coefficients it's obvious.
By "plot out the coefficients" I mean "treat the point (x, y) as the flow from input=y to output=x". In the case of f$(g) = g(x-a) + g(x+a)$, the flows are from $x-a$ to $x$ and from $x+a$ to $x$. If we set $a$ to 2 w.l.o.g., then points matching $(x-2, x)$ and $(x+2, x)$ will have coefficient 1 while all other points will have coefficient 0. So we get two lines:

(The lines differing in color is an artifact of how I plotted the coefficients; they both represent coefficients equal to 1.)
This is just a continuous version of your typical finite matrix grid-of-numbers representation. Noting that the coefficients are not affected by transposing (mirroring about the x=-y axis), we see that the transform must be Hermitian.
The fact that the original proof was done symbolically made me wonder if it's common to plot the coefficients of linear transforms on $\mathbb{R}$ the way I'm doing. Are there gotchas? Are there better ways?
Other examples:
Phase (arg) of the Fourier transform's coefficients (contour plot):

LaPlace transform coefficients (contour plot):


text:
Q: How to tick a checkbox that has text with a url link in Selenium C# This is the code im triying to access

    <input payoneer="CheckBox" type="checkbox" name="ctl00$plcMainArea$SignDocument_4_2" validate="validate" data-rule-required="true" data-msg-required="This field is required." hidefocus="hidefocus" class="field-data" id="SignDocument_4_2" data-sign-document-type="4_2"> I agree to the
    Electronic Disclosures
    Privacy Policy

Im triying to find the element by ID and click the checkbox that's on it
driver.FindElement(By.Id("SignDocument_4_2")).Click();

This is the Exception i get
System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=unknown error: Element is not clickable at point (257, 955). Other element would receive the click: ...
  (Session info: chrome=48.0.2564.116)
  (Driver info: chromedriver=2.20.353145 (343b531d31eeb933ec778dbcf7081628a1396067),platform=Windows NT 6.1 SP1 x86_64)
  Source=WebDriver
  StackTrace:
       at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
       at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
       at OpenQA.Selenium.Remote.RemoteWebDriver.InternalExecute(String driverCommandToExecute, Dictionary`2 parameters)
       at OpenQA.Selenium.Remote.RemoteWebElement.Execute(String commandToExecute, Dictionary`2 parameters)
       at OpenQA.Selenium.Remote.RemoteWebElement.Click()
       at Payoneer.Exam.Main(String[] args) in c:\Users\Alberto Chocron\Documents\Visual Studio 2013\Projects\PayoneerTest\Payoneer\Program.cs:line 105
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

A: The error Element is not clickable at point (257, 955). Other element would receive the click means the element you want to click at is not visible for Selenium. To simulate movement to the element use MoveToElement from Actions class
IWebElement checkbox = driver.FindElement(By.Id("SignDocument_4_2"));
Actions actions = new Actions(driver);
actions.MoveToElement(checkbox).perform();
checkbox.Click();

You can also try sending click to checkbox parents
driver.FindElement(By.ClassName("checkbox")).Click();
// or
driver.FindElement(By.ClassName("radio")).Click();

Another option is using java script click
IWebElement checkbox = driver.FindElement(By.Id("SignDocument_4_2"));
IJavascriptExecutor executor = (IJavascriptExecutor)driver;
executor.ExecuteScript("arguments[0].click();", checkbox);

A: First of all, see that you are using proper try and catch block or the method is getting thrown properly and secondly, actually the point is not getting detected. so try
            string checkboxXPath = "//input[contains(@id, SignDocument_4_2')]"
            IWebElement elementToClick = driver.FindElement(By.XPath(checkboxXPath));
            elementToClick.Click();


text:
Q: Vanilla MySQL access from Ruby 1.9 on Snow Leopard I am running Ruby 1.9 (ruby 1.9.1p376 (2009-12-07 revision 26041) [i386-darwin10]) on Slow Leopard (installed via MacPorts).
I then installed the Ruby MySQL client library via MacPorts:
install rb19-mysql
Trying to use it I get the following error:

db.rb:4:in `initialize': wrong number of arguments(4 for 0) (ArgumentError)
    from db.rb:4:in `new'
    from db.rb:4:in `'

My code:
require 'mysql'
require 'pp'

dbh = Mysql.new("localhost", "testuser", "testpass", "test")
puts "Server version: " + dbh.get_server_info

It seems like I am missing something very basic here.
Did I install the right client library?
I am using it correctly?
Am I missing some other dependencies?
Would appreciate if someone could point me in the right direction.
Thanks!

A: What you're looking for is:
dbh = Mysql.real_connect("localhost", "testuser", "testpass", "test")

A: I have never written a line of Ruby in my life so maybe I'm going to embarrass myself, but don't you have to initialize Mysql first? I'm quite sure the fact that the function expects 0 parameters means it doesn't exist yet.
In the test file of the package you mention (you got me curious), I see the following line:
 assert_nothing_raised{@m = Mysql.init}

your syntax seems to be correct, however. From the same test file
assert_nothing_raised{@m = Mysql.new(@host, @user, @pass, @db, @port, @sock, @flag)}

I would assume you need to do a Mysql.init() first.
If I'm wrong, let me know and I'll remove the answer.

A: Your code looks solid to me; it matches the examples given on the rb19-mysql homepage very well.
my = Mysql.new(hostname, username, password, databasename)
st = my.prepare("insert into tblname (col1,col2,col3) values (?,?,?)")
st.execute("abc",123,Time.now)
st.prepare("select col1,col2,col3 from tblname")
st.execute
st.fetch  # => ["abc", 123, #<Mysql::Time:2005-07-24 23:52:55>]
st.close

Which would seem to indicate that there's probably something not quite right with the port install.  There were all kinds of issues with MacPorts not working properly after snow leopard upgrades - are you falling victim to this?  I had to rebuild all my ports before they worked properly.
Also (and I know this is like religion to some people), you might want to consider ditching the MacPort version and just grab the MySql gem.  For whatever reason, using the gems has been a far more pleasurable experience for me.
Hope that helps - good luck!


text:
Q: Displaying data at runtime without GUI? When i'm working with most projects, from winforms, consoles, WPF, if needed i can print out any information i want to check more easily at run time using a messagebox or the likes;
MessageBox.Show(whateveriwannashow);

However, i'm now working on a windows service, which doesn't allow for the presence of any sort of GUI. What direction should i head in to show some information? Does VS2010 have a built in feature for this sort of stuff?

A: System.Diagnostics.Trace is your new best friend.  Trace is output directly to the output window in Visual Studio, can be send to the logger or can be viewed using free third-party tools like SysInternals DebugView.
For debug work it beats logging hands down.  here's why:

*

*It won't leave great big log files on your drive.  This means you can be really granular with trace and not leave big files on the disk.

*If nothing is listening to the trace output it is basically lost in the ether.

*You can watch the output in real-time using DebugView (and Exe with no external dependencies)

*If you want to log it you can simply add a trace listener to your logger

*It's easy to set up

*It writes to the output window by default.

A: You have a few options:
Database Log: Preferably the service should write to the database log and you should write a separate application that can display the entries and help you make sense of them. This approach can be problematic however because if the database goes down you'll lose any log entries that should have been made in the mean time.
File Log: More reliable writing but more difficult to access from multiple locations. Unless you plan on putting them into some central log folder that's used by a number of other applications it can be easy to forget where they reside and consequently they're usually ignored.
In Memory Log: Allowing a client application to communicate with the service and get some log information can be a good approach but then there's no permanent record. Depending on how soon someone would notice if the service went down this approach may not be the best.
In the end, each approach has it's benefits. Personally I prefer to write to the database first and cascade to a file log when the database writes fail. In memory logs would be strictly reserved for debug messages and would flush out old entries once it got up to something sizable.

A: You should use logs.
How about logging using a third party library that abstracts how the text log is physically stored?
You could then configure your service app.config to use any sort of log output:

*

*database

*rolling flat file

*XML file

*windows event log

without having to modify your code.
You could use Enterprise Library or log4net for instance.

A: For (semi)persistent information, I fully agree with Spencer. But if you need some quick runtime info for debugging/tracing purposes, you can "hijack" a commandline window and write to it.
protected override OnStart(string[] args)
{
    int processId;
    IntPtr ptr = GetForegroundWindow();
    GetWindowThreadProcessId(ptr, out processId);
    var process = Process.GetProcessById(processId);

    if (String.CompareOrdinal(process.ProcessName, "cmd") == 0)
    {
        // Hijack an existing foreground cmd window.
        AttachConsole(process.Id);
    }
    else
    {
        // Or create a new one
        AllocConsole();
    }
}

protected override OnStop()
{
    FreeConsole();
}

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AllocConsole();

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool FreeConsole();

[DllImport("kernel32", SetLastError = true)]
static extern bool AttachConsole(int dwProcessId);

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

Then you can use the console for your output, ideally with 3rd party logging systems like log4net. In my scenario the setup looked like:
//Enable log4net logging into the console
ConsoleAppender appender = new ConsoleAppender {Layout = new SimpleLayout()};
BasicConfigurator.Configure(appender);

But that part is log4net-specific. You should be able to use even Console.Write(), although it's much harder to set up.
What I like about this is that you can "bind" it to commandline/config parameters of the service and the 3rd party logger will just switch logging from its default location to the console, if you set it up so. No need to do any further checks in code. Also you can do this anywhere - in your dev machine, on a remote server...
Anyway, as I said in the beginning, if you don't really need realtime information, I'd stick with Spencer's advice.