text:
Q: Best RAID type for scanned PDF's I have purchased a Synology DS1010 (5 x 2TB) for use in storing a large number of relatively small scanned documents (PDF) which will need to be retrieved at fairly frequent intervals by multiple users (not same document at same time) Documents will be stored directly from scanning, so will need a quick upload time.
Could anyone recommend a suitable RAID type? The data will be backed up to a secondary smaller NAS box 4x2TB?
Thanks
Paul

A: For that kind of load, where you're doing mostly read but writes need to be quick, your file-system choice will probably matter more than your RAID choice. That said, the Synology DS1010 doesn't offer much choice in that respect. EXT3 seems to be your only choice, and it's OK at handling the "lots of small files" problem.
RAID5 gives you the most bang for your buck, but of course costs the most when writing. However, it sounds like writing will be a small minority of your IO operations. Read speed is what you need, and for that RAID5 is just fine for what you're looking for.
Unless this the kind of document management system where lots of docs get uploaded, but very few are ever looked at again, at which point your primary I/O type is writes. In that case, depending on the actual performance you get in the device, RAID10 is possibly more suited. Testing will tell which is what you want.

A: How much of this will you actually fill within the next 2-3 years?  If you won't consume more than 4TB of data within the lifespan of the equipment, making it RAID10 with a hot spare seems like a no-brainer.
Otherwise, you may need to experiment with RAID5 or RAID6 (if supported) and see whether the performance is sufficient.

A: From a performance perspective it's irrelevant as it only has two GigE nics, from an availability point of view always go with R10, if not then R6 or R1.

A: Whatever your choice, to get top performance you must ensure that the partition table is aligned with the raid stripe size.  I'm not sure if Synology does proper alignment by default, but evidently they use an ext3 filesystem under the hood, so it can be done right, but you may have to do so manually.


text: Q: Eigenvalue of the product of two positive definite matrices while one of them is non-symmetric I'm interested in the eigenvalues of the product of two positive definite matrices $AB$ while A is symmetric (all eigenvalues are real with condition number $m$) and B is not necessarily symmetric (could have complex eigenvalues). By positive definite, I mean $x^\top A x > 0$ holds for any real vector $x$. Particularly, let's say the eigenvalue of B has the form $\lambda_i = a_i + b_i j$ and define $\kappa_B = max_i \frac{b_i}{a_i}$. Then what's the largest possible $\kappa_{AB}$ for $AB$? $m * \kappa_B$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Segue VS didDeselectRowAtIndexPath I am using didDeselectRowAtIndexPath to navigate through different Storyboards like:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let story = ["News","Video","Twitter","Request Info","More"]

    let vc = self.storyboard?.instantiateViewControllerWithIdentifier(story[indexPath.row]) as NewsFeedTableViewController
    self.presentViewController(vc, animated: true, completion: nil)

}

However, the Navigation Bar does not show up when I use this function. But, when I use segue, the Navigation Bar shows up.
Now the Problem is:

*

*Cells in a tableView cannot segue more than 1 storyboard

*Need Navigation Bar to Scroll in the App (which seems to need Segue)

Any solutions through this?

A: You are using presentViewController, that's why you are not getting the NavigationBar, it presents the view modally. Instead of that pushViewController like:
self.navigationController?.pushViewController(vc, animated: true)

Probably in your storyboard the segue type will be push, that's why you are getting the Navigation Bar.
You might be interested in the following:

*

*presentViewController:animated:completion:

*ViewController Programming Guide for iOS

A: You are presenting the next view controller, not pushing it. (at least in case 1) So you have a modal link and no nav controller !
You can either use .pushViewController  or simply performSegue and make sure your segue type is push. I would go for the performSegue and change the identifier name in each switchcase.
And you can still pass data in the prepareForSegue

A: Better to call performSegue in didSelectRow. And perform actions in perpareSegue Method .


text:
Q: How to position a div with width, height on top of a contain background? I have a background image (a car) and I want to make it responsive so the background is going to big the biggest size possible in all resolutions. I managed to do that by setting background-size to contain.
But I also need to place a div on top of a specific area in this image, I want a div to cover the car windshield.

The issue is that I don't know how to calculate where the windshield is going to be due to contain.

Is there a way to predict where the background is going to be? How can I cover the windshield with a div?
If that's not possible, would there be some alternative to contain that would keep the image as big as possible just like the way contain handles it?
Here's a CodePen I made to simulate my scenario: https://codepen.io/brunolm/pen/bKdrGz

A: The challenge about the contain value is that it handles 2 different scenarios. If the aspect ratio of the image is wider than the container, the image will have a height of 100%, and a difficult to calculate width. In the opposite case, the width will be 100%.
So we need to handle the 2 different posibilities in a different way.
Luckily, you are using 100% of the browser, so that we can use a media query on the aspect ratio of the browser window.
Then, calculate the position of the rectangle using the relevant viewport units.
To make the media query change visiblem, I have also modified the color of the div

html, body, .bg {
  width: 100%;
  height: 100%;
  margin:  0;
}
.bg {
  background: url('https://thumbs.dreamstime.com/b/black-white-d-car-nissan-skyline-46715732.jpg') no-repeat;
  background-position: center;
  background-size: contain;
}
.area {
  background: rgba(200, 200, 200, .5);

  position: absolute;
  position: absolute;

  top: calc(50% - 43vh);
  height: 26vh;
  left: calc(50% - 54vh);
  width: 110vh;
}

/* portrait mode */
@media screen and (max-aspect-ratio: 8/5) {
  .area {
      background-color: rgba(200,0,0,0.5);
      top: calc(50% - 28vw);
      height: 17vw;
      left: 14vw;
      width: 71vw;
  }
}

current screen size:

A: You need to add the img and the area div to the same container. Then, use percentages to position them correctly inside the container. By using percentages in the container, when the container is resized, the position of the elements should stay in the same place since they will be responsive in relation to the container and not the page:

html, body {
  width: 100%;
  height: 100%;
}
.car {
  width: 50%;
  display: block;
  margin: 0 auto;
  position: relative;
}

.car img {
  width: 100%;
}
.area {
  width: 70%;
  height: 30%;
  background: rgba(200, 200, 200, .5);
  position: absolute;
  bottom: 0;
  right: 0;
  top: 5%;
  left: 50%;
  margin-left: -35%;
}

I'm using a trick here to center the area div in the container. You give the div a left: 50% and then set a negative left margin that is equal to half the width. So since the width of the area div is 70%, we can use left: 50%; margin-left: -35%; to center it.


text:
Q: Don't see Android SDK and AVD Manager when execute android tool command I'm developing android on Mac OS.
In the first time, I use android tool command (<sdk>/tools/android) to launch Android SDK and AVD Manager as this link: http://developer.android.com/sdk/adding-components.html. It's OK. In Mac OS, the program's UI is same as in Windows as the images in the link.
But now, when I run that command, it only start Android SDK Manager as the image below:

How do I revert it? Please help

A: I downloaded and installed Android 4.0.3 (API 15) today and there is no "avd" tool in the /tools/ or the /platform-tools/ folder. However, you can access the Android Virtual Device Manager (AVD Manager) through the Android SDK Manager.

*

*execute the "android" tool with no arguments in the "Tools" window,

*select "Manage AVDs"

A: From the Terminal change to the <sdk>/tools/ directory and type the following to display the AVD Manager window (I'm using android-sdk r15):
$ android avd

A: Credit to user1450537 who gave this answer:
"I know its a bit late answer but for future generations - this is how its done: Click on Window > Customize perspective > Command Groups Availability tab. Check the "Android SDK and AVD Manager" option and hit the OK button."

A: You can use the command line for opening Android SDK Manager, but make sure Android SDK manager is installed in your machine.
Use this command in terminal: ./android avd

A: I had to add the AVD manager to the menu. in Default Preferences I navigated to
Appearance & Behavior > Menus & Toolbars
I found AVD Manager under
Main Menu > Tools > Android
I clicked on AVD Manager, then clicked "Add After" and found the tools menu, and added the item inside the tools menu. Restarted AndroidStudio, and the menu item was there under a submenu

A: On the Run Configurations screen, there is a "Manager..." button, which will open up the AVD Manager.  You must first select "Automatically pick compatible device..." to enable the "Manager..." button.

A: In the Android tool, you can select from the menu bar Tool then Manage AVDs...

A: Suppose the SDK is installed in the opt folder, you could try the following command:
sudo /opt/android-sdk/tools/android ; exit;

This will open the SDK manager.
You need the sudo as often the storing folder (opt in this case) is protected from writing.

A: I've solved. You are not in java perspective. Open going to Window -> Open Perspective -> Java.

A: You can also add <sdk>/tools to your PATH if you use it often. Open your ~/.bashrc file and add this line:
# <sdk> is path to your SDK, e.g. /Users/akarienta/Library/Android/sdk
export PATH=${PATH}:<sdk>/tools

Then just reload the file by source ~/.bashrc or restart the terminal. Since now you can use commands like these (in whatever location you are):
# opens Android SDK Manager
$ android
# opens Android AVD Manager
$ android avd

A: So you are missing the AVD mannager? This newer update has separate executables for SDK and AVD, so you don't have to wait the SDK to update library. The "AVD manager" executable resides in the same folder as the "SDK manager". Try manualy navigating there. I don't use Mac so I can't help you there, but it should be in the same folder.


text:
Q: Parsing email with Google Apps Script, regex issue? I used to be quite proficient in VBA with excel, but I'm currently trying to do something with Google Scripts and I am well and truly stuck.
Basically, I am trying like to extract data out of a standardised email from Gmail into a Google sheet. There are a couple of other threads on the subject which I have consulted so far, and I can get the body of the email into the sheet but cannot parse it.
I am new to regex, but it tests OK on regex101
I am also brand new to Google Script, and even the debugger seems to have stopped working now (it did before, so would be grateful if anyone can suggest why this is).
Here is my basic function:
function processInboxToSheet() {
  var label = GmailApp.getUserLabelByName("NEWNOPS");
  var threads = label.getThreads();
  // Set destination sheet
  var sheet = SpreadsheetApp.getActiveSheet();
  // Get all emails labelled NEWNOPS
  for (var i = 0; i < threads.length; i++) {
    var tmp,
      message = threads[i].getMessages()[1],  // second message in thread
      content = message.getPlainBody();  // remove html markup
    if (content) {

      // search email for 'of:' and capure next line of text as address
      // tests OK at regex101.com
      property = content.match(/of:[\n]([^\r\n]*)[\r\n]/);

      // if no match, display error
      var property = (tmp && tmp[1]) ? tmp[1].trim() : 'No property';
      sheet.appendRow([property]);
    } // End if
  // remove label to avoid duplication
  threads[i].removeLabel(label)
  } // End for loop
}

I can append 'content' to the sheet Ok, but cannot extract the address text required by the regex. Content displays as follows:

NOPS for the purchase of:
  123 Any Street, Anytown, AN1 1AN
DATE: 05/05/2017
  PRICE: £241,000
Seller's Details
  NAME: Mrs Seller

Thanks for reading :)

A: The return value of .match() is an array. The first captured group, containing the address, will be at index 1.
Based on the following line after your call to .match(), it looks like the tmp variable should have been assigned that array, not the property variable.
var property = (tmp && tmp[1]) ? tmp[1].trim() : 'No property';

That line says, if .match() returned something that isn't null and has a value at index 1, then trim that value and assign to property, otherwise assign it the string 'No property'.
So, try changing this line:
property = content.match(/of:[\n]([^\r\n]*)[\r\n]/);

To this:
tmp = content.match(/of:[\n]([^\r\n]*)[\r\n]/);

A: Thanks Kevin, I think I must have changed it while debugging.
The problem was with my regexp in the end. After a bit of trial and error the following worked:
tmp = content.match(/of:[\r\n]+([^\r\n]+)/);


text:
Q: Loop of a list of items with javascript I read that to improve the performance of jquery should avoid use because some things are slowing down a bit.
Among these is the method each() and that it would be appropriate to use a for loop ... (according to the web article I read, the method each() takes roughly 10 times greater than for loops javascript)..
I'm trying to used js but I have some problems: /
Jquery
$('#block-system-main-menu li').each(function () {
        var text= ($(this).children('a').text());
        if (text == 'Map' || text== 'Vul' || text== 'Equa'){
            $(this).children('a').append('');
        }
    });

Javascript
var voce= $('#block-system-main-menu li');
for(var i=0; i< voce.length; i++) {
        var text= (voce[i].children('a').text());
        if (text == 'Map' || text== 'Vul' || text== 'Equa'){
            voce[i].children('a').append('');
        }
    }

but the loop does not work and I do not understand why ....
Thanks!

A: Your problem is here. Compare:
var text= ($(this).children('a').text());

with:
var text= (voce[i].children('a').text());

In the first case, you are creating a jquery object with $(this). In the second case you aren't. voce[i] gives you an HTML element which does NOT have a function called children. So you should get an error there. To make it work, you'd need to create a jquery object from voce[i]. Something like:
var text = $(voce[i]).children('a').text();

Or as @GuerasArnaud suggests in his answer:
var text= voce.eq(i).children('a').text();

However, in all likelihood the for versus each probably isn't what's slowing your code down. You should actually profile your code and identify the bottlenecks in your code.
While when you read "x is slower than y" it's something that you should certainly keep in mind, you should also try to understand where it's applicable and actually important. I wouldn't completely avoid each in all cases, because sometimes the convenience and readability of your code is going to be more important that a micro-optimization of your codes performance in a non-critical section of code.
Also note that in your linked tutorial, you've latched on to the point of for vs each while missing the point of Cache. ALWAYS. So in your jquery code you are creating the $(this) object twice (although it's not quite as important in this case because you aren't using a selector and it depends on how often your if clause evaluates to true, but it's still a cost that gains you nothing in return).
So your loop would be better if you had this:
$('#block-system-main-menu li').each(function () {
    var children = $(this).children('a');
    var text = children.text();
    if (text == 'Map' || text== 'Vul' || text== 'Equa'){
        children.append('');
    }
});

Or for the for loop:
var voce= $('#block-system-main-menu li');
for(var i=0; i< voce.length; i++) {
    var children = $(voce[i]).children('a');
    var text = children.text();
    if (text == 'Map' || text== 'Vul' || text== 'Equa'){
        children.append('');
    }
}

But again, unless voce.length is very large I doubt you'll find any significant difference in real-world performance.

A: voce is a jQuery object but voce[i] is a HTMLNode Element, and it doesn't have a .children() method. If you want to stay in 'jquery like' you should use .eq()
var text= voce.eq(i).children('a').text();

A: So I have benchmarked the jQuery each against fixed JS for loop with jQuery methods and added a vanilla JS solution: http://jsperf.com/jquery-each-for-loop
On my machine jQuery.each vs JS for are very close to each other with vanilla JS outperforming both by quite a large margin.
The code without jQuery:
var voce = [].slice.call( document.querySelectorAll('#block-system-main-menu li'));
/* prepare the span to use .appendChild instead of innerHTML += */
var span = document.createElement('span');
    span.style.cssText = 'float:right; margin-right: 15%; line-height: inherit';
    span.className = 'fa fa-chevron-right';

for(var i=0;i<voce.length;i++){
   /* get the textContent with innerText fallback */
   var text = voce[i].textContent || voce[i].innerText;
   if (text == 'Map' || text == 'Vul' || text == 'Equa') {
       /* forEach to keep compatibility with .children('a') method which returns a collection.
          Could be optimized further if you know you need to modify a single element */
       [].forEach.call( voce[i].querySelectorAll('a'), function(a){
           a.appendChild( span.cloneNode() );
       })
   }
}


text:
Q: How would I display more than once? I am working on a dice game, which requires me to display 6 dice randomly. The problem I am getting is that when ever I push the button to execute the code, it will only display the randomly selected dice ONCE even if I tell it to choose 6 random dice. My question is: How would I repeat numbers in my code, so that the dice will display if the same die (single die) is selected more than once?
   if val == 1:
        show.blit(die1, (150,50))
    elif val == 2:
        show.blit(die2, (250,50))
    elif val == 3:
        show.blit(die3, (150,150))
    elif val == 4:
        show.blit(die4, (250,150))
    elif val == 5:
        show.blit(die5, (150,250))
    elif val == 6:
        show.blit(die6, (250,250))

Here is the rest of the code for this code:
## gDieClass.py

import pygame
from pygame.locals import *
from random import randint

show = pygame.display.set_mode((500,500))
die1 = pygame.image.load('Dice1.tga')
die2 = pygame.image.load('Dice2.tga')
die3 = pygame.image.load('Dice3.tga')
die4 = pygame.image.load('Dice4.tga')
die5 = pygame.image.load('Dice5.tga')
die6 = pygame.image.load('Dice6.tga')

class graphic_die(object):

    # class that displays a graphical rep. of 6 sided die

    def __init__(self, size, surf, pos):

        # define some values
        self.SURF = surf
        self.POS = pos
        self.SIZE   = size

        self.__DIESURF = pygame.Surface((size, size), flags=SRCALPHA, depth=32)
        self.__DIESURF.fill((0, 0, 0, 0))

        self.value = 1

        ## Dice Colors
        self.die_color  = (0,0,0,0)

        self.__RADIUS = self.SIZE//10
        __HSIZE  = self.SIZE//2
        __QSIZE  = self.SIZE//4
        self.PIPRAD = self.SIZE//10

        # create Pips/Dots in standard places

    def __drawBackground(self):

        # create square with rounded corners
        pygame.draw.circle(self.__DIESURF, self.die_color, (self.__RADIUS, self.__RADIUS), self.__RADIUS)
        pygame.draw.circle(self.__DIESURF, self.die_color, (self.SIZE - self.__RADIUS, self.__RADIUS), self.__RADIUS)
        pygame.draw.circle(self.__DIESURF, self.die_color, (self.__RADIUS, self.SIZE - self.__RADIUS), self.__RADIUS)
        pygame.draw.circle(self.__DIESURF, self.die_color, (self.SIZE - self.__RADIUS, self.SIZE - self.__RADIUS), self.__RADIUS)

        pygame.draw.rect(self.__DIESURF, self.die_color, Rect((self.__RADIUS, 0), (self.SIZE - 2 * self.__RADIUS, self.SIZE)))
        pygame.draw.rect(self.__DIESURF, self.die_color, Rect((0, self.__RADIUS), (self.SIZE, self.SIZE - 2 * self.__RADIUS)))

    def __makePip(self, point):

        # helper function to make pips
        pygame.draw.circle(self.__DIESURF, self.pip_color, point, self.PIPRAD)

    def setRandValue(self):
        self.value = randint(1, 6)

    def __drawValue(self, val):

        self.__drawBackground()

        # Creates PIPs at Value
        if val == 1:
            show.blit(die1, (150,50))
        if val >= 2:
            show.blit(die2, (250,50))
        if val >= 3:
            show.blit(die3, (150,150))
        if val >= 4:
            show.blit(die4, (250,150))
        if val >= 5:
            show.blit(die5, (150,250))
        if val >= 6:
            show.blit(die6, (250,250))

    def display(self):
            self.__drawValue(self.value)
            self.SURF.blit(self.__DIESURF, self.POS)

A: if die1, die2, etc each represent a die, well you are only showing only one of those with that code, try with
if val >= 1:
    show.blit(die1, (150,50))
if val >= 2:
    show.blit(die2, (250,50))
if val >= 3:
    show.blit(die3, (150,150))
if val >= 4:
    show.blit(die4, (250,150))
if val >= 5:
    show.blit(die5, (150,250))
if val == 6:
    show.blit(die6, (250,250))


text:
Q: Issue with function calculating wrong answers when asked to process vector inputs vs. stand alone user inputs Function Overview
I have created a function to calculate directional changes between consequetive bearings (which was calculated from my latitude and longitude data).
The bearings are always relative to the North-South line (i.e., number of degrees away from north), and thus in parallel to one another and are ethier positive (0 -> +180) or negitive (0 -> -180). I have accounted for the signs (positive or negitive) and the 'magnitude' (>90 or <90) of the bearings which has allowed me to create 'rules' using basic trig to calculate directional changes.
The function evaluates two consequtive bearings (i.e., A --- TO --- B), classifies thier direction (positive or negitive) and the bearing values (>90 or <90). It uses these classifications to determine which 'rule' to use and then calculates directional change using the calculation associated with that rule. See the function below:
The Function
analyzeGPS_DirectionChange <- function(bearingVec1, bearingVec2) {

  a1 <- ifelse (bearingVec1 >= 0.00, "positive", "negitive")
  a2 <- ifelse (bearingVec2 >= 0.00, "positive", "negitive")
  Bearing_Signs <- paste(a1, a2)

  b1 <- ifelse (abs(bearingVec1) < 90.00, "less", "greater")
  b2 <- ifelse (abs(bearingVec2) < 90.00, "less", "greater")
  Bearing_Values <- paste(b1, b2)

  print(Bearing_Signs)
  print(Bearing_Values)

  if (Bearing_Signs == "positive positive" && Bearing_Values == "less less") {
      Direction_Change <- (90 - bearingVec1) + (90 + bearingVec2)
      } else if (Bearing_Signs == "positive positive" && Bearing_Values == "less greater") {
      Direction_Change <- (180 - bearingVec2) + bearingVec1
      } else if (Bearing_Signs == "positive positive" && Bearing_Values == "greater less") {
      Direction_Change <- 180 - ((bearingVec1 - 90) + (90 - bearingVec2))
      } else if (Bearing_Signs == "positive positive" && Bearing_Values == "greater greater") {
      Direction_Change <- (bearingVec1 - 90) + (180 - bearingVec2) + 90
  }

  if (Bearing_Signs == "positive negitive" && Bearing_Values == "less less") {
      Direction_Change <- 180 - (abs(bearingVec2) + bearingVec1)
      } else if (Bearing_Signs == "positive negitive" && Bearing_Values == "less greater") {
      Direction_Change <- 180 - (90 + (90 - bearingVec1) + (180 - abs(bearingVec2)))
      } else if (Bearing_Signs == "positive negitive" && Bearing_Values == "greater less") {
      Direction_Change <- 90 - ((bearingVec1 - 90) + abs(bearingVec2))
      } else if (Bearing_Signs == "positive negitive" && Bearing_Values == "greater greater")  {
      Direction_Change <- 180 - ((180 - bearingVec1) + (180 - abs(bearingVec2)))
  }

  if (Bearing_Signs == "negitive positive" && Bearing_Values == "less less") {
      Direction_Change <- 180 - (abs(bearingVec1) + bearingVec2)
      } else if (Bearing_Signs == "negitive positive" && Bearing_Values == "less greater") {
      Direction_Change <- 180 - (90 + (90 - abs(bearingVec1)) + (180 - bearingVec2))
      } else if (Bearing_Signs == "negitive positive" && Bearing_Values == "greater less") {
      Direction_Change <- 90 - ((abs(bearingVec1) - 90) + bearingVec2)
      } else if (Bearing_Signs == "negitive positive" && Bearing_Values == "greater greater")  {
      Direction_Change <- 180 - ((180 - abs(bearingVec1)) + (180 - bearingVec2))
  }

  if (Bearing_Signs == "negitive negitive" && Bearing_Values == "less less") {
      Direction_Change <- (90 - abs(bearingVec2)) + (90 + abs(bearingVec1))
      } else if (Bearing_Signs == "negitive negitive" && Bearing_Values == "less greater") {
      Direction_Change <- (180 - abs(bearingVec2)) + abs(bearingVec1)
      } else if (Bearing_Signs == "negitive negitive" && Bearing_Values == "greater less") {
      Direction_Change <- (180 - abs(bearingVec1)) + abs(bearingVec2)
      } else if (Bearing_Signs == "negitive negitive" && Bearing_Values == "greater greater")  {
      Direction_Change <- (abs(bearingVec1) - 90) + 90 + (180 - abs(bearingVec2))
  }

 return(Direction_Change)

}

Issue
When I use the function, it evaluates the bearing inputs correctely (I have included the print statements so that you can easily assess this). See below the working example (I checked it and others manually by hand to double check the math and assignment ect...)
analyzeGPS_DirectionChange(bearingVec1 = 100.6587, bearingVec2 = 24.66356)

[1] "positive positive"
[1] "greater less"
[1] 104.0049

However, when I run two vectors through the function which represent consequtive points some are calculated correctly and others are errors. See below for example:
bearingVec1 <- c(1.988956, 100.658682, 24.663563, 122.423408, -30.556419, 14.702280, -74.235212, -5.619550, 78.729953, -135.463404, -2.600200)
bearingVec2 <- c(100.658682, 24.663563, 122.423408, -30.556419, 14.702280, -74.235212, -5.619550, 78.729953, -135.463404, -2.600200, -6.733987)

analyzeGPS_DirectionChange(bearingVec1, bearingVec2)

 [1] "positive positive" "positive positive" "positive positive" "positive negitive" "negitive positive" "positive negitive"
 [7] "negitive negitive" "negitive positive" "positive negitive" "negitive negitive" "negitive negitive"
 [1] "less greater" "greater less" "less greater" "greater less" "less less"    "less less"    "less less"    "less less"
 [9] "less greater" "greater less" "less less"
 [1]  81.33027 255.99512  82.24015 332.97983 134.74130 268.93749 111.38434  95.65050 394.19336  47.13680 184.13379

At first sight it seems to have worked, however there are a few errors in the actual value answers, see the first example above which calculated correctly when I entered the bearing values manually - those numbers correspond to bearingVec1[2] and bearingVec2[2] in the sample data I provided.
I do not know why it is incorrectly calculating when I provide the function with vectors. Please help me solve this issue!

A: The problem arises from if in combination with &&. From the help of  &&

'&' and '&&' indicate logical AND and '|' and '||' indicate
       logical OR.  The shorter form performs elementwise comparisons in
       much the same way as arithmetic operators.  The longer form
       evaluates left to right examining only the first element of each
       vector.

That is your if clause will always fall back to the first element. Not what you want.
ifelse on the other hand is vectorized. So you could either replace all your if clauses by ifelse constructs, which may become very tricky given all your nested ifs.
Another solution would be to use any form of loop to pass only single values to your function. This approach is however, not very elegant and you are not fully exploiting the builtin capabilities of R to deal with vectors and may be significantly slower than rewriting your function to deal with vectors properly, but you can readily use your function:
 purrr::map2_dbl(bearingVec1, bearingVec2, analyzeGPS_DirectionChange)
 # [1]  81.33027 104.00488  82.24016  27.02017 134.74130  91.06251 248.61566
 # [8]  95.65050  34.19336  47.13680 175.86621

Another option is to use Vectorize which vectorizes your function (basically by doing a mapply under the hood):
 Vectorize(analyzeGPS_DirectionChange)(bearingVec1, bearingVec2)
 # [1]  81.33027 104.00488  82.24016  27.02017 134.74130  91.06251 248.61566
 # [8]  95.65050  34.19336  47.13680 175.86621


text:
Q: Trying to figure out if any of the textboxes in a collection of textboxes have duplicate values (Visual C# 2010) I'm automatically generating text boxes on a form based on a parameter in an Oracle Database.  The user enters data in the format "A14/3".  I've already got code putting all of the textboxes in a collection.
var sortedTextboxes = panel1.Controls
                    .OfType<TextBox>() // get all textboxes controls
                    .OrderBy(ctrl => ctrl.Text); // order by TabIndex
foreach (TextBox txt in sortedTextboxes)
{
    //parse and check format
}

I need to figure out how to check for duplicates.  I'm sorting by text, so all of the values will be in alphabetical order.  Can I just check the current textbox's value with the previous textbox's value?  If so, how can I do that?

A: You can get duplicate textboxes and their content if you group your results based on Text and then get only those items whose count is greater than 1. Like:
var sortedTextboxes = panel1.Controls
                    .OfType<TextBox>() // get all textboxes controls
                    .GroupBy(r => r.Text)
                    .Where(grp=> grp.Count() > 1)
                    .Select(grp => new
                    {
                        DuplicateText = grp.Key,
                        DuplicateTextBoxes = grp.Select(r => r).ToList(),
                    });

A: You could insert all the values into a hashset of strings then compare your text box collection count against the hashset collection count.  If the are the same, you have no duplicates
var hash = new HashSet<string>();
foreach(var textBox in textBoxes){
    if(hash.contains(textBox.Value){
        break;

    hash.add(textBox.Vaule);
}
if(hash.Count != textBoxes.Count){
    //duplicate
}

A: Change your code to save previous text box id
var sortedTextboxes = panel1.Controls
                .OfType<TextBox>() // get all textboxes controls
                .OrderBy(ctrl => ctrl.Text); // order by TabIndex

var preTextboxId="";
foreach (TextBox txt in sortedTextboxes)
{
//parse and check format
if ( preTextboxId == txt.id)
{
    //duplicate
}
else
{
    add text box
}
preTextboxId = txt.id

}


text:
Q: Terraform import app engine failed due to 403 When attempting to run an import of an existing app-engine default service, it fails due to a 403
terraform import google_app_engine_standard_app_version.frontpage app/<project-name>/default
The terraform service account is both owner and Appengine Admin (for good measure), IAP proxy and IAP proxy is disabled.
constraints/appengine.disableCodeDownload  is not enforced at the org Level.
google_app_engine_standard_app_version.frontpage: Refreshing state... [id=apps/app/services/<project-name>/versions/default]
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: 2020/01/21 10:10:27 [DEBUG] Waiting for state to become: [success]
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: 2020/01/21 10:10:27 [DEBUG] Google API Request Details:
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: ---[ REQUEST ]---------------------------------------
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: GET /v1/apps/app/services/<project-id>/versions/default?alt=json HTTP/1.1
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Host: appengine.googleapis.com
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: User-Agent: HashiCorp Terraform/0.12.19 (+https://www.terraform.io) Terraform Plugin SDK/1.4.0 terraform-provider-google/3.4.0
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Content-Type: application/json
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Accept-Encoding: gzip
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5:
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5:
2020-01-21T10:10:27.517-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: -----------------------------------------------------
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: 2020/01/21 10:10:28 [DEBUG] Google API Response Details:
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: ---[ RESPONSE ]--------------------------------------
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: HTTP/2.0 403 Forbidden
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Alt-Svc: quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Cache-Control: private
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Content-Type: application/json; charset=UTF-8
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Date: Tue, 21 Jan 2020 15:10:28 GMT
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Server: ESF

2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Vary: Origin
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Vary: X-Origin
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: Vary: Referer
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: X-Content-Type-Options: nosniff
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: X-Frame-Options: SAMEORIGIN
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: X-Xss-Protection: 0
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5:
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: {
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5:   "error": {
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5:     "code": 403,
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5:     "message": "The caller does not have permission",
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5:     "status": "PERMISSION_DENIED"
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5:   }
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5: }
2020-01-21T10:10:28.532-0500 [DEBUG] plugin.terraform-provider-google_v3.4.0_x5:
Error: Error reading AppEngineStandardAppVersion "apps/app/services/<project-id>/versions/default": googleapi: Error 403: The caller does not have permission

A: I was calling an incorrect resource,  I needed to include version ID as well.
terraform import google_app_engine_standard_app_version.frontpage {{project}}/{{service}}/{{version_id}}


text:
Q: AngularJS Bootstrap Collapsable Treeview I'm attempting to work the selected answer over at this Stack Overflow question into my AngularJS app.  In particular, the JQuery code block
$(function () {
    $('.tree li:has(ul)').addClass('parent_li').find('>span').attr('title', 'Collapse this tree');
    $('.tree li.parent_li >span').click(function (e) {
        console.log("test");
        var children = $(this).parent('li.parent_li').find(' > ul > li');
        if (children.is(":visible")) {
            children.hide('fast');
            $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
        } else {
            children.show('fast');
            $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
        }
    e.stopPropagation();
    });
});

It appears to work for the first line, as the spans I'm using do have "Collapse this tree" as their tooltip.  However, the console.log statement is never fired.  I've tried inspecting the element through the browser debugger and all looks fine.  I've tried adding the angularJS-generated classes into the JQuery above, as well as tried both $().click and $().on('click') functionality but neither seemed to work.
I also tried toying around with ng-click and just putting this manually on each span but once I got inside the JQuery it had no idea which element had pressed it even through I was passing the ID through the function parameters.
Has anyone had any luck getting this to work with Angular?
I've seen a few places suggest directives for recursively managing the trees but my tree structure doesn't necessarily lend itself to automation since it's based off of our object model.

A: Here's a plunkr using the answer mentioned in my comment that handles a collapsing tree.
I basically just added collapsing to the directive template:

  {{item.hideChildren ? '+' : '-'}}

  {{item.label}}

      <tree-node item="child"></tree-node>


text:
Q: git pushes repository successfully but files don't upload to remote server I am newbie to git system and trying to set up git system (using git-scm) between my local computer (OS: Windows) and server (server provider: hostinger.com). I don't want any middle man like github or other servers.
To test my git system, i have created a new repository, added a test file to it, committed, and pushed it to remote bare repository, all with no error. However, my test file doesn't show up on server, there is just bare repository folder on the server. I have done all git commands on same bash to show you results:

The only thing that is not on the picture is, I uploaded a simple "new 1.txt" file to d:/wamp64/www/test/ location manually after using "git init" command. As a result, there is just "wp.git" folder on the server but not "new 1.txt" file. What am I missing?

A: Seems like I had the wrong ideas about git system. For the newbies trying to do what i was trying:
ssh u266881589@194.5.156.43 -p 65002 "git clone /home/u266881589/domains/mezegurmanams.lt/public_html/wp.git /home/u266881589/domains/mezegurmanams.lt/public_html/test"

Adding this last command does the trick for me, however it is not what i really want. As I have learnt, Git is not appropriate for deployment or to sync files like i was trying to do. Especially for binary files like image files etc. it becomes another problem. Conclusion, using git for just development and something like "rsync" to synchronize files is a better solution


text:
Q: Creating a general list of ascending and descending numbers using list comprehension I am trying to generate a list containing a mixture of ascending and descending numbers.
e.g., say you have n=5.  I want to generate a list/array based on n such that you have:
[0,1,2,3,4,3,2,1,0]

using list comprehension.
I tried doing this:
print [[i+j] for i in range(n)for j in range(n,-1,-1)]

but I can't seem to get it right.

A: I know you specified you wanted a list comp, but is it really necessary?
list(range(5)) + list(reversed(range(4)))

(python 3 syntax)
Or, in python2:
range(5) + range(4)[::-1]

or
range(5) + range(3,-1,-1)

I think the first one is more readable, but ymmv.

A: In [27]: n = 5

In [28]: [n-1-abs(i-n+1) for i in range(n*2-1)]
Out[28]: [0, 1, 2, 3, 4, 3, 2, 1, 0]

Update
This one might be more clear
In [36]: [n-abs(i) for i in range(-n,n+1)]
Out[36]: [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]

A: One-liner:
[i if i < n else 2*(n-1)-i for i in range(2*(n-1) + 1)]

More efficient:
_top = 2*(n-1)
[i if i < n else _top-i for i in range(_top + 1)]


text:
Q: Find all triples of natural numbers $x$, $y$, $z$ such that $x+2y+2z=xyz$.
Find all triples of natural numbers $x$, $y$, $z$ such that $x+2y+2z=xyz$.

I found a solution, but it involves a lot of case work. Can someone help me find a solution which doesn't involve a lot of case work?

A: Let $x$, $y$ and $z$ be natural numbers satisfying
$$x+2y+2z=xyz.$$
If $xyz=0$ then $x=y=z=0$, so suppose $x,y,z>0$. A bit of algebra shows that
$$(xy-2)(xz-2)=x^2+4.\tag{1}$$
Of course without loss of generality $y\leq z$. If $x=1$ then the above simplifies to
$$(y-2)(z-2)=5,$$
and so $y=3$ and $z=7$. Otherwise $x\geq2$ and then from $y\leq z$ it follows that
$$(x+1)^2>x^2+4=(xy-2)(xz-2)\geq(xy-2)^2,$$
and hence that $x\geq xy-2$, or equivalently $2\geq x(y-1)$. This means that either $x=y=2$, in which case $z=3$, or $y=1$, in which case $(1)$ simplifies to
$$(x-2)(xz-2)=x^2+4.\tag{2}$$
Clearly $x\neq2$, and so from the identity
$$xz-2=\frac{x^2+4}{x-2}=x+2+\frac{8}{x-2},$$
we see that $x-2$ divides $8$, so $x-2\in\{1,2,4,8\}$. Plugging these values into $(2)$ yields
\begin{eqnarray*}
1\cdot(3z-2)&=&13,\\
2\cdot(4z-2)&=&20,\\
4\cdot(6z-2)&=&40,\\
8\cdot(10z-2)&=&104.
\end{eqnarray*}
The first three have the solutions $z=5$, $z=3$ and $z=2$, respectively, and the last has no integral solution.
In summary, up to permutation of $y$ and $z$, the solutions $(x,y,z)$ are
$$(0,0,0),\quad(1,3,7),\quad(2,2,3),\quad(3,1,5),\quad(4,1,3),\quad(6,1,2).$$

A: We have: $y = \dfrac{x+2z}{xz-2}\ge 1\implies x+2z\ge xz-2\implies 2z+2\ge xz-x = x(z-1)\implies x \le \dfrac{2z+2}{z-1}$. Of course the case $z = 1$ warrants a separate consideration and it's not hard to solve for this case as you have down to $2$-variable equation in $x,y$ only and you can isolate either $x$ or $y$ and take care of the case when a fraction is an integer. So for $z > 1$, then $x \le \dfrac{2z+2}{z-1} \le 3$ when $z \ge 5$. Thus you have to consider cases $z = 1,2,3,4$ first as well. And when $z \ge 5$, you have $x = 1,2,3$ and treat each case again. So in brief, it seems that's what amounts to and you have to be willing to work hard this time to treat about $10$ cases !

A: "OP" equation is:
$x+2y+2z=xyz$  ---(1)
Eqn. (1) has parameteric solution's shown below.
$(x,y,z)=(3k^2+1)/(k),(3k),(1/k)$
For, $k=1$, we get: $(x,y,z)=(4,3,1)$
& for, $k=1/3$, we get: $(x,y,z)=(4,1,3)$
Another parametrization is:
$(x,y,z)=(4k^2+2)/(k),(2k),(1/k)$
For, $k=1$, we get: $(x,y,z)=(6,2,1)$
& for, $k=1/2$, we get: $(x,y,z)=(6,1,2)$


text:
Q: Do I need a framework to use dependency injection? I want to start practising dependency injection in C++ to make my code more testable, however after some googling I found articles which say I must use some framework for dependency injection. Is it so? Why does one need such a framework? Why can't I inject dependencies either by subclassing and passing dependencies in constructor by reference or pointer or by passing the class I want to use as dependency as template parameter?

A: Dependency Injection is a software design pattern which allows you to avoid dependencies to concrete classes. A Dependency container has the responsibility of object creation and to pass/inject dependencies into dependent objects. If you use a DI container your application delegates the responsibility of composing your object graph to a separate service. It provides the infrastructure to create your application in a consistent way and it forces conventions (especially interesting when you want to reuse it in different projects/teams and to force a consistent way to construct the object graph).
Poor-man's DI (e.g. constructor injection: passing a parameter by reference to constructor) is a valid way to do dependency injection.
// Edit: A DI-container also manages the lifecycle of your objects/services.


text:
Q: pseudo-selector :before not positioning correctly in IE9,10 I've encountered a problem that eludes me. I have an absolutely positioned pseudo-selector :before inside of a relatively positioned container that is positioned correctly in everything but IE9 and 10.
I've spent some time researching the problem and tried to implement thirtydot's solution mentioned here.
Here's a sample of the code: http://jsfiddle.net/66d25/20/
In all other browsers, the quotes appear correctly in the top left corner of the containing blockquote paragraph. In IE9/10 the quotes are improperly positioned in the middle top of the quote bubble.
I tried to add overflow:visible to the containing p tag but that didn't fix the problem. I have also included my scss below. Any insights into this problem would be greatly appreciated.
    blockquote {
        border-left: none;
        padding: 0;
        margin: 2em 0 1em 0;
        position: relative;
        &:after, &:before {
            top: 100%;
            border: solid transparent;
            content: '';
            height: 0;
            width: 0;
            position: absolute;
            pointer-events: none;
            display:block;
        }
        p {
            color: shade($charcoal, 20%);
            margin: 0;
            background: #fff;
            @include border-radius(5px);
            @include box-shadow(inset 0 2px 0 rgba(70, 130, 180, 0.7), -5px -4px 25px rgba(0, 0, 0, 0.3));
            font-size: emCalc(17px);
            color: adjust-lightness($charcoal, 20%);
            font-weight: 400;
            line-height: 1.5em;
            font-style: italic;
            text-indent: 2em;
            position: relative;
            padding: 1em;
            overflow:visible;
            &:before {
                content: "\201C";
                font-family: serif;
                font-style: normal;
                font-weight: 700;
                position: absolute;
                font-size: 5.5em;
                top: 15px;
                left: -50px;
                color: $blue;
                text-shadow: 7px 14px 10px rgba(0, 0, 0, 0.1);
                display: block;
                height: 25px;
                width: 25px;
            }
        }

        footer {
            padding-top: 1em;
            cite {
                text-align: right;
                text-transform: uppercase;
                font-weight: 700;
                font-size: 1.25em;
                font-style: normal;
                color: $vblue;
                text-shadow: 0 1px 1px rgba(255,255,255,0.7);
                &:before {
                    content: '';
                }
            }
            &:before {
                content: '';
                position: absolute;
                border-style: solid;
                border-width: 15px 15px 0;
                border-color: #FFFFFF transparent;
                display: block;
                width: 0;
                z-index: 1;
                margin-left: -15px;
                bottom: 33px;
                left: 80%;
            }

        }
    }

A: Removing:
p {
    text-indent: 2em;
}

solves the issue on IE11: http://jsfiddle.net/66d25/22/
To position the quote back where you intend to place it can be achieved with:
p {
    text-indent: 34px; /* font-size is 17px so 2em=34px*/
}

Demo: http://jsfiddle.net/66d25/23/
So the problem is with em unit and it's fine with pixels. Go figure why IE does that...


text:
Q: Channel:mychannel received discovery error:access denied Failed to evaluate transaction: Error: DiscoveryService: mychannel error: access denied I am using Hyperledger fabric 2.2 on ubuntu. I am trying to create REST API using express.js with the help of this article.
My fabric network and apiserver.js is on same server.

*

*Does that mean that i can use localhost instead of the IP address of fabric host by the given suggestion in mentioned article.

if i can use local host there is no need to change connection profile right?
so, i tried to query using the command curl http://localost:8080/api/queryallcars
but i got errors curl: (7) Failed to connect to localhost port 8080: Connection refused
& error: [DiscoveryService]: send[mychannel] - Channel:mychannel received discovery error:access denied
Failed to evaluate transaction: Error: DiscoveryService: mychannel error: access denied
Also, I have enabled discovery: { enabled: true, asLocalhost: true} in apiserver.js file.
where am i doing wrong?.
Thank You in Advance!
UPDATE: Answer given by @Jerome O'Mahony worked for me!.

A:
if i can use local host there is no need to change connection profile right?

Just remember that everytime that you build your network, a new client connection profile (CCP) file will be created. Therefore, you will have to copy the most recent version to where your connection code for the API is. Also you will need to perform the register Admin and Register User for your wallet (delete the old ones). You can either copy the CCP file or else create  a symbolic link in your API code that points to the latest version in the peer directory under organizations.
Is your REST API actually running on port 8080. Create a test page that returns "Hello World" in JSON so that you can at least verify that the mechanics of the API work before worrying about whether it can connect to Hyperledger.
Also, it is best to use a small command line test program to see if you can connect to, and query,  the Hyperledger network before adding the complication of adding an API in between.


text:
Q: How do I contact the maintainers for apt-config-icons and variants? I have been having some hassles installing Ubuntu 20.04 LTS under my Windows 10 Home WSL1 services, but I've narrowed down the culprit to apt-config-icons and its derivatives.
It took a couple days of install-break-wipe-repeat cycles to identify exactly what was breaking my WSL Ubuntu 20.04 apt cache, but I eventually narrowed it down.
If any of those packages get installed under WSL1, you can't update your apt cache any more.
How do I get this information to them?

A: See the output of
apt-cache show apt-config-icons

That is
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Matthias Klumpp <mak@debian.org>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug


text:
Q: My own personal Div 100% height nemisis - jquery tabs It seems like you're nobody here until you've got your own "how can I get div to expand to height 100%" question, here's mine - (I hope it is original and helpful).
With reference to my attempts so far http://jsfiddle.net/prQcc/3/ - I have, in a jquery tab, two divs as side by side columns. I want these divs to expand to the height of the jquery tab. The closest I've come is what you see in the fiddle - the column divs expand, but to the height of the 'page', not the height of the containing Tab div.

A: Your #tabs-1 is getting set to the height of #tabs, but #tabs has a ul taking up space at its top, so #tabs-1 gets pushed down below the bottom of #tabs by the height taken up by the ul.
Changing your #tabs-1 to position absolutely off of the #tabs corrects the issue, though padding and borders on #tabs is creating a small scroll bar to still appear. For modern browsers, the easiest way to correct that is using box-sizing:
#tabs {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}


text:
Q: How to simulate pressing enter in a bash script This is my first bash script. I want to run a script five times, the script is located in the same folder that this script will be located. My problem is that I cannot find how to simulate pressing enter. Since this script needs to load the data first it takes two seconds after running it, then it prompts you to press enter. I want to simulate doing this five times. How can I do the 3 second delay and press enter after? Any other problems with my script?
#!/bin/bash

for i in {1..5}
do
   ./clientScript.py
   #Press enter after a 3 second pause
done

A: this should work:
echo | ./clientScript.py

it simply outputs a \n to the stdin of your python script.


text:
Q: NSString Retain Count Whats the retain count of the NSString in the below mentioned Code snippet?
self.a = @"abcd"; // self.a is a NSString with (nonatomic, Strong) Attributes

NSLog(@"Retain Count of A == %d",(int)[self.a retainCount]);

self.b = self.a;// self.b is a NSString with (nonatomic, Strong) Attributes

NSLog(@"Retain Count of A == %d",(int)[self.a retainCount]);
NSLog(@"Retain Count of B == %d",(int)[self.b retainCount]);

[self.a release];

NSLog(@"Retain Count of A == %d",(int)[self.a retainCount]);
NSLog(@"Retain Count of B == %d",(int)[self.b retainCount]);

//Similarly whats the retain count if:
self.b = [self.a retain];

A: @"abcd" is a string literal. It is stored as a constant. If you were to log [@"abcd" class] then you'd get __NSCFConstantString (though such is an empirical observation; the class name is not guaranteed). retain, release, etc are no-ops on a constant string as it inherently has the same lifetime as the application. In practice, as vikingosegundo says, you get NSUIntegerMax.
You're using properties so what will actually happen depends on your property type.
With self.b = self.a what you'd expect is:

*

*the getter self.a returns [[string retain] autorelease], so retain count is incremented for the lifetime of the current autorelease pool;

*the setter self.b = retains the string, so the retain count is incremented again, for the lifetime of selfs ownership of the string.

So two increments if you check during the lifetime of the autorelease pool, one long-term increment.
Manual calls to retain and release do exactly what you'd think.
Under ARC you don't manually get to call any of these things, including retainCount and the various retains and releases may be optimised out. A famous case is that something in the autorelease pool that is subsequently retained can be removed from the pool. So self.b = self.a may end with the retain count up by only one and the string not sitting in the autorelease pool, if the optimiser feels like it.
The rule when using manual reference counting is fairly simple:

*

*if you have an owning reference — one returned by a new, alloc, retain or copy — then release or autorelease the reference;

*if you have a non-owning reference — i.e. any other sort, most commonly though that'll be from a vanilla getter — then don't release the reference. But don't necessarily expect it to be valid beyond the lifetime of the current autorelease pool.

The return [[a retain] autorelease] pattern comes from the observation that self may have a shorter lifetime than the pool.


text:
Q: Is modifying the User Agent potentially dangerous? I'm working on an hybrid mobile application, and I'd really benefit of having the app version, OS build and screen sizes of the users that issue our API, just to know if issues come up due to a poorly developed feature or a bugfix that can't fulfill everyone's problems. That way, in a semi transparent procedure I'd be able to track this. I've been testing it with some users, and it works like a charm in ones, but others complain about strange errors that occur upon downloading files from our CDNs.
Could modifying the User Agent affect the download requests for a server, and only affect specific users?
PS: I decided to change the user agent, since some of the info I want is "native code related", and setting that in the user agent would mean no change in the current API calls.

A: The easiest way to find out is to disable the User-Agent customization and see if the problem goes away :) .
In general, User-Agent is not guaranteed to be what you set.  For example, a corporate firewall might use deep packet inspection to rewrite User-Agent and reduce browser entropy.
Philosophically, I think modifying User-Agent to include additional logging information is a bad idea because it violates the single responsibility principle  (as applied to data - hear me out).  Assume everyone's browser is standards-compliant.  (Your hybrid app is compliant, right? :) )  On mobile devices, User-Agent has a well-defined responsibility: to indicate the user's preference for mobile or desktop rendering.  Google says:

HTTP redirection is a commonly used to redirect clients to device-specific URLs. Usually, the redirection is done based on the user-agent in the HTTP request headers.

Is it ridiculous that a 109-byte (for me) string serves to convey a single bit of information?  Sure, but that's the world we live in.
Rewriting User-Agent to add logging information gives that string a second responsibility.  That means your servers, CDN, logging tools, and everything else have to know about (or at least tolerate) both the logging information and the mobile/desktop intent information.  Whenever you want to change the logging info, you have to make sure you're not breaking anything related to rendering intent, and vice versa.
Even though it may be a pain now, do yourself and those who maintain your code a favor: don't overload User-Agent.  Splitting responsibilities to keep your code simple and loosely coupled will pay for itself many times over by saving time, reducing stress, and preventing hair loss.


text:
Q: How to make a join and search in data using codeigniter and Php I make a join between two tables using codeigniter framework and this is my query:
public function SearchDataUnderCondition($firsttable,$secondtable,$data)
{

    $this->db->select("atm.* , tender.status as tenderstatus");
    $this->db->from($firsttable);
    $this->db->join($secondtable,'atm.id_tender=tender.id');
    $this->db->where('tenderstatus','1');
    $this->db->like('serial', $data);
    $sql = $this->db->get();
    return $sql->result();

}

I am using database model when is remove
$this->db->where('tenderstatus','1');

from my code operation done  and i get result but I want to  make search under this condition.  what is my problem?

A: Try this
$this->db->where('tender.status','1');

I think, we can not aliases in where clause

A: Try this

public function SearchDataUnderCondition($data)
{

    $this->db->select('atm.* , tender.status');
    $this->db->from('atm');
    $this->db->join('tender','atm.id_tender=tender.id');
    $this->db->where('tender.status','1');
    $this->db->like('serial', $data);
    $sql = $this->db->get();
    return $sql->result();

}

A: Using aliases (and also making sure you want and WHERE AND LIKE clause):
        $fist_table = 'atm';
        $second_table = 'tender';

        $this->db->select('aliasone.* , aliastwo.status as "tenderstatus"');
        $this->db->from("$first_table as aliasone");
        $this->db->join("$second_table as aliastwo", "aliastwo.id = aliasone.tender_id");
        $this->db->where('aliastwo.status','1');
        $this->db->like('serial', $data);
        return $this->db->get();


text:
Q: Connect landline phone to pc and retrieve number of incoming call I have made a simple php application which searches the details of people by inputting their phone number in the application. Now I want to extend its functionality that my landline phone is connected to my pc and whenever a call comes then the php application should fetch details of the related incoming number from database and display it. Now to implement this I need to get the number of that incoming call.
How can I connect landline to my pc? (I think a phone modem will be required but I am not sure.)
How can I get the number of that incoming call?

A: If the landphone is connected to the Server on which PHP resides, then ask PHP to read log files generated by asterisk (if you are using Asterisk on a Linux server to handle the incoming calls). No idea about other Operating Systems or solutions.

A: PHP doesn't have access to hardware for security issues. So you can't know if there's an incoming call.


text:
Q: Rendering bugs when SoftKeyboard closes I have the following problem:
I have a FrameLayout with a main Fragment, which is always shown, and some overlay "extra" fragments which are shown or not, depending on the state of the application. (This Layout is used on tablets)
Now, if the user initiates a dialog with an EditText, this causes the SoftKeyboard to appear.
The Dialog and the Keyboard(No matter which type of dialog, I tried AlertDialog and DialogFragment) overlays the other Fragments.
So far, so good.
But when the dialog is finished and the keyboard closes, my whole application is pushed a bit up and down in an animation, and then there are several rendering bug in the ActionBar and at the bottom edges of my fragments.
This happens only if the keyboard overlaid exactly one of my "extra" fragments. (If it overlays two fragments, then everything is good).
Anyone an idea how to get rid of this?
Configuring android:windowSoftInputMode does not help.

A: You can adjust your keyboard in fragment using
getActivity().getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);


text:
Q: What classes/interfaces i will need to implement and Activity like "Setting" in android 3.1? I am wondering if i could implement setting activity in my own application just looking like the Built-in Setting application in android 3.1.
as you know Built-in Setting application looks like:

What concepts and classes i will need to accomplish my own activity same like this default one.
For example i need some options on the left side, on clicking each option on left i could pick up/see its values on right side..
My desired activity look like this:

Please explain the layout design in general (and in brief if possible). Any tutorials, any documentation or relavent example will be highly helpfull..

A: What you are looking for, are Fragments.
Fragments can be used to fill a part of the screen, while doing something else entirely in a different one.
In your example you can create a main activity that contains two Fragments.  One Fragment controls the list on the left, the other one controls the main content area for your options.
By replacing the current Fragment in your content area with a different one on the press of a button, you can achieve the behavior you are looking for.
For the options menu, it looks like a PreferenceFragment.
Sadly I can't provide any example code right now, but here is a tutorialthat should help you get started:

*

*Android User Interface Design: Working With Fragments

A: Try PreferenceActivity or better still google for "preference android"


text:
Q: When invoking R Shiny App that uses conditional panels, how to prevent all panels from flashing by before settling on first panel? Below is almost-MWE code. Issue is when opening and invoking the App, other conditional panels (tabs) flash by before settling on the first panel (tab) labeled "About". This works fine (should show "About" tab first), but everything flashing by first is sloppy. How do I keep everything from flashing by?
From my research there are cursory solutions like "place everything under renderUI" which I don't understand how to do.
Here's the MWE code (very stripped down but it illustrates the issue):
library(shiny)
library(shinyMatrix)
library(shinyjs)

matrix1.input <- function(x){
  matrixInput(
    x,
    value = matrix(c(0.2), 4, 1, dimnames = list(c("A","B","C","D"),NULL)),
    rows = list(extend = FALSE,  names = TRUE),
    cols = list(extend = FALSE, names = FALSE, editableNames = FALSE),
    class = "numeric")}

vector.base <- function(x,y){
  a <- rep(y,x)
  b <- seq(1:x)
  c <- data.frame(x = b, y = a)
  return(c)}

ui <-
  pageWithSidebar(
    headerPanel("Model"),
    sidebarPanel(
      conditionalPanel(condition="input.tabselected==1"),
      conditionalPanel(
          condition="input.tabselected==2",
          sliderInput('periods','Input periods:',min=1,max=120,value=60),
          matrix1.input("base_input"),
          useShinyjs(),
          actionButton('showPerfVectorBtn','Show'),
          actionButton('hidePerfVectorBtn','Hide'),
          actionButton('resetPerfVectorBtn','Reset'),
          hidden(uiOutput("Vectors"))
      ) # close conditional panel
    ), # close sidebar panel
    mainPanel(
      tabsetPanel(
        tabPanel("About",value=1),
        tabPanel("Dynamic",value=2,plotOutput("graph1")),
        id = "tabselected"
      ) # close tabset panel
    ) # close main panel
  ) # close page with sidebar

server <- function(input,output,session)({

  periods        <-  reactive(input$periods)
  base_input     <-  reactive(input$base_input)
  vector_input   <-  reactive(input$vector_input)

  observeEvent(input$periods|input$base_input,{
    updateMatrixInput(session,"vector_input",
      value=matrix(c(input$periods,input$base_input[1,1]),1,2))})

  output$Vectors <- renderUI({
    input$resetPerfVectorBtn
    tagList(matrix1.input("Plot"))
    }) # close render UI

  observeEvent(input$showPerfVectorBtn, {shinyjs::show("Vectors")})
  observeEvent(input$hidePerfVectorBtn, {shinyjs::hide("Vectors")})

  output$graph1 <- renderPlot(
    if(input$showPerfVectorBtn == 0)
      plot(vector.base(periods(),input$base_input[1,1]))
    else plot(vector.base(periods(),input$base_input[1,1])))
}) # close server

shinyApp(ui, server)

A: Moving conditional panels from ui section to server section, using ouputUI and renderUI, does eliminate flash-by of other items when invoking the App, making the App appear more professional. Below is the resolved code where I take the above MWE code and move conditional panel items to renderUI. Please note the commented section toward the bottom under server, labeled "run observeEvent in renderUI".  I originally had that without wrapping it in renderUI and when moving conditional panels to renderUI without also wrapping that observeEvent in renderUI, the App would crash. Wrapping that observeEvent in renderUI solved the issue. It sort of makes sense to link it to renderUI too, but that was solution was derived through trial/error without my fully understanding why it works. I hope this doesn't cause problems later!!
library(shiny)
library(shinyMatrix)
library(shinyjs)

matrix1.input <- function(x){
  matrixInput(
    x,
    value = matrix(c(0.2), 4, 1, dimnames = list(c("A","B","C","D"),NULL)),
    rows = list(extend = FALSE,  names = TRUE),
    cols = list(extend = FALSE, names = FALSE, editableNames = FALSE),
    class = "numeric")}

vector.base <- function(x,y){
  a <- rep(y,x)
  b <- seq(1:x)
  c <- data.frame(x = b, y = a)
  return(c)}

ui <-
  pageWithSidebar(
    headerPanel("Model"),
    sidebarPanel(
      uiOutput("Panels")
    ), # close sidebar panel
    mainPanel(
      tabsetPanel(
        tabPanel("About",value=1),
        tabPanel("Dynamic",value=2,plotOutput("graph1")),
        id = "tabselected"
      ) # close tabset panel
    ) # close main panel
  ) # close page with sidebar

server <- function(input,output,session)({

  periods        <-  reactive(input$periods)
  base_input     <-  reactive(input$base_input)
  vector_input   <-  reactive(input$vector_input)

  output$Panels <- renderUI({
    tagList(
      conditionalPanel(condition="input.tabselected==1"),
      conditionalPanel(
        condition="input.tabselected==2",
        sliderInput('periods','Input periods:',min=1,max=120,value=60),
        matrix1.input("base_input"),
        useShinyjs(),
        actionButton('showPerfVectorBtn','Show'),
        actionButton('hidePerfVectorBtn','Hide'),
        actionButton('resetPerfVectorBtn','Reset'),
        hidden(uiOutput("Vectors")),
      ) # close conditional panel
    ) # close tagList
  }) # close renderUI

  output$Vectors <- renderUI({
    input$resetPerfVectorBtn
    tagList(matrix1.input("Plot"))
  }) # close render UI

  # run observeEvent in renderUI
  renderUI({
    observeEvent(input$periods|input$base_input,{
      updateMatrixInput(session,"vector_input",
                        value=matrix(c(input$periods,input$base_input[1,1]),1,2))})
  }) # close renderUI

  observeEvent(input$showPerfVectorBtn, {shinyjs::show("Vectors")})
  observeEvent(input$hidePerfVectorBtn, {shinyjs::hide("Vectors")})

  output$graph1 <- renderPlot(
    if(input$showPerfVectorBtn == 0)
      plot(vector.base(periods(),input$base_input[1,1]))
    else plot(vector.base(periods(),input$base_input[1,1])))
}) # close server

shinyApp(ui, server)


text:
Q: Why the name of my  is not changing with the for loop? I'm working with django and I need to create dynamically some links . My code is,
{% for node in Last_val_nodes %}
    {{node.0}}
{% endfor %}

The links showed are ok, if for example I have a list of 3 nodes like, ['Node X','Node A','Node P'] I can see the three perfectly.
But now I want to know what link has been clicked. For this I'm using jquery,
$('.nodeInfo').click(function(){
    var name = $('.nodeInfo').attr("name");
    alert(name);
});

But when I click it always alert the first node name, in this case "Node X". Why is not writing a different name for every one? How can I know the link clicked if it is created dynamically?
Thank you

A: Django isn't at fault here at all. Inside your event handler, $('.nodeInfo') selects a collection of all elements with the CSS class nodeInfo, regardless of which element actually received the click event; the .attr method picks the first of these and returns the value of its name attribute. Instead you should write
$('.nodeInfo').click(function(){
    var name = $(this).attr("name");
    alert(name);
});

This will pick the correct element. In fact, you can even dispense with jQuery here and just write this.name instead of $(this).attr("name"). (This may fail to be directly applicable to other attributes.)
(Also remember not to use a fat-arrow function as the event handler, as those inherit this from their surrounding scope.)


text:
Q: How is sscanf different from scanf in the following statements? I came across the following statement while I was going through a C program for client/server message handling in Unix.
int main(int argc, char* argv[])
{
    (void)sscanf(argv[1],"%d",&port);
}

It would be helpful if you can explain the above statement.
Edit: I don't know why people feel my question is not clear... I just wanted to know that if scanf takes input from keyboard then the above statement sscanf also does the same job indirectly. Is that correct?

A: sscanf() reads formatted input from a string.
scanf() reads formatted input from stdin.
So in your example sscanf reads from the first argument of the program and saves it in the variable port.
As a little example what sscanf does:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    int day;
    char str[100];

   strcpy(str, "21" );
   sscanf(str, "%d", &day);

   printf("day: %d", day);

   return(0);
}

Output:
day: 21

A: scanf() parses data from program input (stdin / "keyboard").
sscanf() parses data from a provided string.

A: scanf() function reads data from stdin into the locations given by each entry in the argument list.
sscanf() function reads data from a string(in your case argv[1]) into the location given(port in your case)

A: The scanf() function reads input from the standard input stream stdin.
The sscanf() function reads its input from the character string pointed to by its first argument.


text:
Q: How to recursively read Hadoop files from directory using Spark? Inside the given directory I have many different folders and inside each folder I have Hadoop files (part_001, etc.).
directory
   -> folder1
      -> part_001...
      -> part_002...
   -> folder2
      -> part_001...
   ...

Given the directory, how can I recursively read the content of all folders inside this directory and load this content into a single RDD in Spark using Scala?
I found this, but it does not recursively enters into sub-folders (I am using import org.apache.hadoop.mapreduce.lib.input):
  var job: Job = null
  try {
    job = Job.getInstance()
    FileInputFormat.setInputPaths(job, new Path("s3n://" + bucketNameData + "/" + directoryS3))
    FileInputFormat.setInputDirRecursive(job, true)
  } catch {
    case ioe: IOException => ioe.printStackTrace(); System.exit(1);
  }
  val sourceData = sc.newAPIHadoopRDD(job.getConfiguration(), classOf[TextInputFormat], classOf[LongWritable], classOf[Text]).values

I also found this web-page that uses SequenceFile, but again I don't understand how to apply it to my case?

A: I have found that the parameters must be set in this way:
.set("spark.hive.mapred.supports.subdirectories","true")
.set("spark.hadoop.mapreduce.input.fileinputformat.input.dir.recursive","true")

A: If you are using Spark, you can do this using wilcards as follow:
scala>sc.textFile("path/*/*")

sc is the SparkContext which if you are using spark-shell is initialized by default or if you are creating your own program should will have to instance a SparkContext by yourself.
Be careful with the following flag:
scala> sc.hadoopConfiguration.get("mapreduce.input.fileinputformat.input.dir.recursive")
> res6: String = null

Yo should set this flag to true:
sc.hadoopConfiguration.set("mapreduce.input.fileinputformat.input.dir.recursive","true")

A: connector_output=${basepath}/output/connector/*/*/*/*/*

works for me when I've dir structure like -
${basepath}/output/connector/2019/01/23/23/output*.dat

I didn't have to set any other properties, just used following -
sparkSession.read().format("csv").schema(schema)
                    .option("delimiter", "|")
                    .load("/user/user1/output/connector/*/*/*/*/*");


text:
Q: Can a Majorana field $\psi$ be charged under some $U(1)$ with a charge other than zero? I know Majorana particles have to be electrically neutral because electric charged is conserved.
My question, however, is whether at all a Majorana field $\psi$ be charged under any $U(1)$ (other than $U(1)$ of electromagnetism) with a nonzero $U(1)$ charge? If yes, how? Doesn't the defining condition $\psi=\psi^c$ always mathematically constrain all $U(1)$ charges to be zero? Let me explain why I think so. Suppose, we assign a nonzero U(1) charge $\alpha$ to the field $\psi$ so that $$\psi^\prime=e^{i\alpha}\psi.$$ What is the charge of the field $\psi^c$? It can be easily seen that $$\psi^{c\prime}=C\bar{\psi^\prime}^T=C\gamma^{0T}\psi^{\prime *}=e^{-i\alpha}C\bar{\psi}^T=e^{-i\alpha}\psi^c.$$
Therefore, for any $U(1)$ charge $\alpha$ assigned to the field $\psi$, the complex-conjugated field $\psi^c$ will have the charge $-\alpha$. What does it imply for a Majorana particle where $\psi=\psi^c$? It necessarily implies that $\alpha=0$ i.e., Majorana fields cannot be charged under any U(1) group. Therefore, it is not at all possible to assign a nonzero $U(1)$ charge for this fields. Am I missing something here?
If my conclusion is correct, what does it mean to say that a Majorana mass violates $U(1)$ quantum number (such as lepton number) by 2 units? I must be missing some caveat. What is that?

A: Majorana field can not be charged under the U(1) group. However, it can be charged under the $\mathbb{Z}_2$ subgroup of U(1). Under the $\mathbb{Z}_2$ transformation, $\psi\to\psi'=-\psi$, any Majorana fermion Hamiltonian (such as the Majorana mass $m\psi\psi$) should be invariant under this $\mathbb{Z}_2$ symmetry, which is also called the fermion parity symmetry. Therefore we can assign a $\mathbb{Z}_2$ quantum number (i.e. the fermion parity) to the Majorana field, which is the lepton number modulo two. In other words, the lepton number is not conserved for the Majorana fermion, but it can only change by 2, so the parity of the lepton number is still conserved.
In the derivation, the charge conjugation condition $\psi'=\psi'^{c}$ requires:
$$e^{\mathrm{i}\alpha}\psi=e^{-\mathrm{i}\alpha}\psi^c=e^{-\mathrm{i}\alpha}\psi,$$
which implies
$$e^{\mathrm{i}\alpha}=e^{-\mathrm{i}\alpha}.$$
This equation has two solutions: $\alpha=0$ and $\alpha=\pi$. The solution of $\alpha=\pi$ corresponds to the non-trivial $\mathbb{Z}_2$ charge. In general, all composite fields made out of the Majorana field (such as $\psi_a\psi_b\psi_c\cdots$) can carry the $\mathbb{Z}_2$ charge. Let $q=0,1$ be the $\mathbb{Z}_2$ charge, then a charge-$q$ operator $O_q$ transforms under the $\mathbb{Z}_2$ symmetry as
$$O_q\to O'_q=e^{\mathrm{i}q\pi}O_q.$$
One can see the Majroana field $\psi$ itself has $q=1$, which has one unit of lepton number (modulo two). However it is meaningless to talk about the U(1) lepton number of the Majorana fermion, because the U(1) symmetry has been broken down to $\mathbb{Z}_2$. So more presicely, we should say the Majorana field is fermion parity odd (meaning that it carries one unit of the $\mathbb{Z}_2$ quantum number). The Majorana mass $m_{ab}\psi_a\psi_b$, the interaction $V_{abcd}\psi_a\psi_b\psi_c\psi_d$ and all other terms that appear in the Hamiltonian have $q=0$, which are fermion parity even (meaning that they do not carry the $\mathbb{Z}_2$ quantum number).

A: Let me write it down as an answer. Yes, Majorana neutrino cannot be charged under $U(1)$, including global $U(1)_L$ of Lepton number. What we mean by violation of $L$: the processes, like neutrinoless double beta decay, sensitive to the Majorana mass term will violate $L$ by two units, which for the given example corresponds to the production of two electrons, and (surprise!) no neutrinos.


text:
Q: What causes "flushing %s elements"? I'm experimenting with custom polymer elements in Dart using the Dart Editor. I haven't been able to figure out why, but I often get this printed in the output:
flushing %s elements (http://localhost:8080/packages/polymer/src/js/polymer/polymer.js:12)

My elements show up for a brief second after launching the app but then disappear whenever this message is displayed. What is causing this? The only thing I was able to find online was this issue.
EDIT: I just realized that the fact that my elements are not being displayed might not be related to this message, but I would still like to know what it means.


text:
Q: A conjectured identity for generalized Fibonacci polynomials Let $k$ be a positive integer. Consider the generalized Fibonacci  polynomials $f_{n}$ which satisfy the recursion $f_{n}=xf_{n-1}+sf_{n-k}$ with initial values $f_{n}=x^n$ for $0\le{n}<k.$
It seems that for $0\le {r,t}<k$
$$\sum_{j=0}^n {\binom{j+t-r-1}{j}s^jf_{k(n-j)+r}}=x^{r-t}f_{kn+t}.$$
Is there a simple proof of this fact?

A: In the mean-time I have seen that this result follows from the formulae
$$\sum_{j} {\binom{r}{j}(-s)^j f_{n+r-kj}}=x^r f_{n}$$
and
$$x^r \sum_{j} {\binom{r+j-1}{j}s^j f_{kn-kj}}=f_{kn+r},$$
which can be proved by induction.


text:
Q: Internet connection doesn't exist I'm not familiar with Ubuntu at all, however, today I received a USB with Ubuntu installed on it from my employer that I should be working on.
The problem is that, despite having my PC connected to an ethernet cable, the internet connection is just nonexistent when I boot up the Ubuntu from the USB.
I had tried using said USB on a PC and laptop from another family member and the internet works just fine as long as an ethernet cable is attached.
Therefore, I thought something must be wrong with my PC and I stupidly reset it (which naturally yielded no positive outcome). All I got from the IT department was advice to reset my router or try a different USB port.
Due to the fact that my access to the OS is most likely limited by my employer, I can't even look at my network settings or do any research/basic troubleshooting while using the booted up Ubuntu (even when I tried taking a look at the network settings on the other PC where I managed to connect to the internet, nothing appeared).
I'm unable to look at any settings overall, just basic things like accessibility.
In the "About" of the OS the following version of Ubuntu is shown: "Ubuntu 18.04.2 2021.11.16 customized using Cubic on 2021-11-16 10:25"
I hope someone is able to tell me if there is a possibility to work around this and what could maybe be the cause of the internet connection not being recognized.
Thanks!


text:
Q: Kubuntu 16.10 + Plasma 5.8 - can't add UK keyboard layout properly! How can I add UK keyboard layout to my Kubuntu 16.10 on Plasma 5.8?
When I first installed my Kubuntu, I had the US keyboard layout selected and installed into the system.
But now I am using a UK keyboard on Microsoft Universal Foldable Keyboard. I have tried to installed to UK keyboard layout from Keyboard section. But it does not work properly. For instance:

*

*When I type shift+2 I should get a " but I get a @ instead.

*When I type shift+' I should get a @ but I get a " instead.

*When I press the hash key I can't get the symbol but nothing shows.

But:

*

*when I press shift+3 I do get £

*When I press shift+4 I do get $
Any ideas why and how I can fix this?
This is what I added to the keyboard layout:

Did I miss anything??
I have tried to change this file below manually but still no luck:
$ sudo nano /etc/default/keyboard

Content:
# KEYBOARD CONFIGURATION FILE

# Consult the keyboard(5) manual page.

XKBMODEL="pc105"
XKBLAYOUT="gb"
XKBVARIANT=""
XKBOPTIONS=""

BACKSPACE="guess"

NOTE 1:
However, I found something very strange - the keyboard layout did change to the UK keyboard layout on my USB US keyboard, but not changed on my Microsoft Universal Foldable Keyboard! It is only changed to a semi-UK keyboard layout. Why!??

A: The problem is not coming from the Kubuntu/ Ubuntu. It is from the Microsoft Universal Foldable Keyboard.
I have to switch the the OS to Windows on the keyboard in order to have the UK keyboard layout!
Hope this will help others who use Microsoft's.


text:
Q: How can I prevent users to upload the same product twice in WordPress? I have a problem: my team is uploading the same product twice without notice. Is there any solution to stop that? Or any plugin I can install to prevent this kind of problem?
There are plugins such as a spreadsheet to delete duplicated products but it doesn't prevent duplication of the product. Rather than I want to prevent the duplication of product titles...


text:
Q: How to use sem_trywait()? How can I test whether a semaphore blocked?
i try function sem_trywait() but it not wokring, i dont now why, can you help me please?
Example is here(Example program that uses semaphores to solve sleeping barber problem.): http://users.dickinson.edu/~braught/courses/cs354s00/classes/code/SleepBarber.src.html
I want use sem_trywait() to detect, is semaphore blocket:
 void *customer(void *number) {
    int num = *(int *)number;

    //there is my problem...
    //you must waiting to free semaphore...
    while(sem_trywait(&waitingRoom)){
        printf("Semaphore is full you must wait!");
    }

    // Wait for space to open up in the waiting room...
    sem_wait(&waitingRoom);
    printf("Customer %d entering waiting room.\n", num);

    // Wait for the barber chair to become free.
    sem_wait(&barberChair);

    // The chair is free so give up your spot in the
    // waiting room.
    sem_post(&waitingRoom);

    // Wake up the barber...
    printf("Customer %d waking the barber.\n", num);
    sem_post(&barberPillow);

    // Wait for the barber to finish cutting your hair.
    sem_wait(&seatBelt);

    // Give up the chair.
    sem_post(&barberChair);
    printf("Customer %d leaving barber shop.\n", num);
}

The proble is in while loop
while(sem_trywait(&waitingRoom)){
    printf("Semaphore is full you must wait!");
}

I dont know how to use it. Thank you.

EDIT1:
void *customer(void *number) {
    int num = *(int *) number;

    // Leave for the shop and take some random amount of
    // time to arrive.

    printf("Customer %d arrived at barber shop.\n", num);

    if (sem_trywait(&waitingRoom) == 0) {
        // Wait for space to open up in the waiting room...
        sem_wait(&waitingRoom);
        printf("Customer %d entering waiting room--------------------------------------------.\n", num);

        // Wait for the barber chair to become free.
        sem_wait(&barberChair);

        // The chair is free so give up your spot in the
        // waiting room.
        sem_post(&waitingRoom);

        // Wake up the barber...
        printf("Customer %d waking the barber.\n", num);
        sem_post(&barberPillow);

        // Wait for the barber to finish cutting your hair.
        sem_wait(&seatBelt);

        // Give up the chair.
        sem_post(&barberChair);
        printf("Customer %d leaving barber shop.\n", num);
    } else {
        printf("leaving barber shop %d\n", num);
        customer(&num);
        //sem_wait(X);
    }

}

A: First a general warning, I'll get to your exact problem lower down. Do not use sem_trywait unless you have a very specific reason to do so and a very good understanding of semaphores and locking in general. This applies to all locking functions, mutexes, rwlocks, etc. If there's a "try" version of the lock function it's there for very specific situations that don't apply to 99% of the users.
sem_wait will wait for the semaphore in the most efficient way possible. You spinning in while loop around sem_trywait will achieve almost (but not exactly) the same thing as sem_wait except that you'll do it very inefficiently wasting CPU time and possibly blocking others from releasing the semaphore.
sem_trywait and other "try" locking functions are there for situations where you can't afford to wait for the lock and you'd rather fail the operation than wait until the lock becomes available. Very few applications actually have requirements like this. This might be happen in hard real-time systems or in some very complex locking schemes where failing is the only way to avoid lock ordering problems.
Most applications don't have this problem. Your example code for example doesn't have this problem at all. The first sem_wait will do what you need. If you just want to log a message when the semaphore is taken what you want to do is something like this:
if (sem_trywait(X) == 0) {
    printf("semaphore acquired\n");
} else {
    printf("need to wait for semaphore\n");
    sem_wait(X);
}

The problem with your code is that you first trywait and after that succeeds, you wait again, this is incorrect since if trywait succeeds it means that it did the same thing as sem_wait.

A: Don't test with the while loop. Try waiting just once and check the result.
result = sem_trywait(...);
if (result == -1) {
    // Check one of: EAGAIN, EDEADLK, EINTR, EINVAL
}

Then decide to loop if you need to wait more.


text:
Q: .Net and plugin architectures Following on from Jeff and Joel's discussions of plugin architectures.
Plugins in C++ (using runtime loaded dlls) are always a bit of a pain. You have to do a lot of ground work to enable them and then the plugin must also be written in C++, often even with the same compiler. COM objects and ActiveX solved some of these problems but introduced a few of their own.
Then to add say, a python interface, to a C++ app is a large amount of work.
Am I correct in thinking that all libraries (or assemblies or whatever you call them) written in one .Net language can always be called from another .Net language? And can objects an data types be automatically transferred between them?
Presumably since all .Net languages also use Winforms (or WPF) for the gui, then giving plugins access to the main app's gui is also relatively simple.
Sorry if this is a rather obvious point  I'm just an old fashioned C++ programmer. But the ease of reusing existing C++ libraries via C++/CLI has convinced me that C#/.Net might be worth more investigation.
Edit - thanks, I was looking to discuss if plugins were a reason to go .Net . Being able to write ironpython while having my business users able to write a simple plugin in VB and technical users be able to craft something clever in F# without me doing any more work seemed a good reason to switch from C++

A:
Am I correct in thinking that all libraries (or assemblies or whatever you call them) written in one .Net language can always be called from another .Net language? And can objects an data types be automatically transferred between them?

Yes. In .NET, the cross-language compatibility is possible because of CTS (Offer a set of common data types for use across all .NET compliant languages and ensures type compatibility) and CLS (Defines a set of minimum standards that all .NET language compilers must conform to, and thus ensures language interoperability). During compilation, a source code of any .NET-compliant language is converted to Intermediate Language code by the respective language compiler. As all .NET assembly (EXE or DLL) exists as intermediate language, they can interoperate between them. All .NET compliant languages use the same data types and are represented as .NET types only. Therefore whether you are using int in C# or Integer in Visual Basic .NET, in IL it is represented as System.Int32.              [Source]

A: If you are looking for plug-ins libraries in .NET, there are a couple of options I am aware of:

*

*From Microsoft there is MEF

*From Novell (Mono) there is Mono.Addins
Both are open source, so you can see how they went about creating a plug-in environment.

A: The main problem with plugins under .Net is not the ability to call the code from plugin's dll (and interop with it), but safety issues. Those can be solved as well, you can look here (ones of sample that is linked there also should present a very simple host + plugin) How to create a Plugin Model in .NET with Sandbox?
And for interoperability between .Net languages - there's no problem with that.
Shared gui - I've done this with Winforms, and it wasn't very hard, although I don't know if it would be also that easy under WPF, I've never tried it though.

A: Yeah , you can achieve all of them through Reflection
there are articles about c# plug-in structure such as this one


text:
Q: Reducing Size of Linux Kernel Image I am working on ARM V7 architecture based Embedded Board with only 128 MB of flash memory and i want to fit Bootloader Image, Linux Kernel Image as well as root file system inside it, for this my primary target is to reduce the size of the boot loader and Linux Kernel image,
I have done the following optimizations for reducing kernel size,
     1. Deleted all the printk messages from displaying which reduced some memory,
     2. Turning off Sysfs Support decreased the size of the kernel substantially,
     3. Booting without procfs is one more work around i tried, but many pseudo
        file systems require it.

I want to know all the possible techniques for optimization and reducing the size of the linux kernel.
I request to provide any references.

A: Compared to 128 MB of flash, the size of your bootloader and kernel images should be comparatively quite small, and your root filesystem be the biggest part. So why do you focus on reducing the size of your bootloader and kernel, instead of looking at what is probably the biggest part: your root filesystem.

A: Probably you should remove unneeded configs (network, security, unneeded drivers, ...).
"CC_OPTIMIZE_FOR_SIZE" should be enabled.
Enable kernel compression (for example: HAVE_KERNEL_BZIP2), ramdisk compression (for example: RD_BZIP2) and initramfs compression (INITRAMFS_COMPRESSION_BZIP2).

A: I would suggest converting your file system to either jffs2 or yffs if you have not already done so.


text:
Q: I accidentally committed a sensitive password into source control I accidentally committed a sensitive password into source control before pushing to the central repository.
I removed the password from my code and did git add -A . && git commit --amend and then git push origin master.
Is there any trace of the sensitive password in Git? In other words, when you run git commit --amend, does Git have any trace of the commit containing the sensitive data?
(I changed the password just to be sure.)

A: You'll first need to interactively rebase and remove the commit. This guide has some more information. This is done via git rebase -i --root master.
After locally rebasing, you will then need to force-push the commit to the remote. Note that this will mess up history on all cloned copies of the remote repository. You'll ideally need to remove the working copies completely and git clone them again. To force-push: git push --force origin master.

A: If you didn't push before amending the commit, there is no trace of the password in the remote.
However, the sensitive password still exists in your local repo until the commit gets garbage collected. git reflog will show you the commit that still contains the password. Running git gc will trigger the garbage collecting and remove the said commit from your local repo too.
More info on git gc: https://www.kernel.org/pub/software/scm/git/docs/git-gc.html

A: Assuming that the commit that contained the password was the latest commit when you did git commit --amend, then the password should be totally removed. You can confirm this by checking out the relevant commits and looking for the password.


text:
Q: How does the C compiler (clang) enforce const? With Clang, the following :
#include <stdio.h>

int main(void)
{   double const x = 1.234;
    double *p = (double *) &x;
    /* Same with double *p = &x; but with a mere warning from clang
       Clang++ does raise an error in this case.
    */
    *p = 5.678;

    printf("*p = %f\n", *p);
    printf(" x = %f\n", x);

    if (&x == p) {
        printf("&x = %p\n", &x);
        printf(" p = %p\n", p);
    }

    return 0;
}

gives the output:

*p = 5.678000  x = 1.234000  &x = 00000080288FFEA8  p = 00000080288FFEA8

How exactly does the compiler do this? How can the compiler successfully compile and avoid, say, the following output:

*p = 5.678000  x = 5.678000 &x = 00000080288FFEA8  p = 00000080288FFEA8

A: The behaviour on modifying an object which was originally const via a cast which removes that const is undefined.
Whether or not a compiler warns you about undefined behavior is up to the compiler. To do so in full generality is impossible.
Optimising compilers will make assumptions based on the fact that your program does not contain undefined behaviour. The Clang output is consistent with it substituting 1.234 for x in that printf call; that's legitimate since x is not allowed to change.

A: Bathsheba hypothesized that the compiler could be passing in hard-coded values to printf.  I figured I'd look at the generated assembly and see if we could verify the hypothesis.
I made a few slight modifications to the code in question: Changed the doubles to ints to make it easier to understand what I'm seeing in the assembly, and I also added another print statement adding the values together.
Compiled with clang -std=c11 -g -O2
#include <stdio.h>

int main(void)
{   int const x = 1;
    int *p = (int *) &x;
    *p = 2;

    printf("*p = %d\n", *p);
    printf(" x = %d\n", x);
    printf(" x + p = %d\n", x + *p);

    if (&x == p) {
        printf("&x = %p\n", (void *)&x);
        printf(" p = %p\n", (void *)p);
    }

    return 0;
}

disassembled code (just main section):
0000000000400510 <main>:
  400510:   53                      push   %rbx
  400511:   48 83 ec 10             sub    $0x10,%rsp
  400515:   c7 44 24 0c 02 00 00    movl   $0x2,0xc(%rsp)
  40051c:   00
  40051d:   bf 10 06 40 00          mov    $0x400610,%edi
  400522:   be 02 00 00 00          mov    $0x2,%esi <----- hard-coded 2 passed in
  400527:   31 c0                   xor    %eax,%eax
  400529:   e8 c2 fe ff ff          callq  4003f0 <printf@plt>
  40052e:   bf 19 06 40 00          mov    $0x400619,%edi
  400533:   be 01 00 00 00          mov    $0x1,%esi <----- hard-coded 1 passed in
  400538:   31 c0                   xor    %eax,%eax
  40053a:   e8 b1 fe ff ff          callq  4003f0 <printf@plt>
  40053f:   bf 22 06 40 00          mov    $0x400622,%edi
  400544:   be 03 00 00 00          mov    $0x3,%esi <----- hard-coded 3 passed in (2+1)
  400549:   31 c0                   xor    %eax,%eax
  40054b:   e8 a0 fe ff ff          callq  4003f0 <printf@plt>
  400550:   48 8d 5c 24 0c          lea    0xc(%rsp),%rbx
  400555:   bf 2f 06 40 00          mov    $0x40062f,%edi
  40055a:   31 c0                   xor    %eax,%eax
  40055c:   48 89 de                mov    %rbx,%rsi
  40055f:   e8 8c fe ff ff          callq  4003f0 <printf@plt>
  400564:   bf 38 06 40 00          mov    $0x400638,%edi
  400569:   31 c0                   xor    %eax,%eax
  40056b:   48 89 de                mov    %rbx,%rsi
  40056e:   e8 7d fe ff ff          callq  4003f0 <printf@plt>
  400573:   31 c0                   xor    %eax,%eax
  400575:   48 83 c4 10             add    $0x10,%rsp
  400579:   5b                      pop    %rbx
  40057a:   c3                      retq
  40057b:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)

The compiler is, indeed, passing in hard-coded values.


text:
Q: Search by month and year in Entity Framework I have this method where I want to get all inserted records in Database passing month and year. I want to filter the DB by passed month and year. This is what I tried but returns nothing:
//The model
public class HomeVM
{
    public string Tecnico { get; set; }

    [DisplayFormat(DataFormatString = "{MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime Mese { get; set; }
}

public IActionResult Search(HomeVM homeVM)
{
   var tecnico = _db.Tecnici
       .Where(m => m.Id == homeVM.Attivita.Tecnico)
       .Select(m => m.Surname+ " " + m.Name)
       .FirstOrDefault();

   var month= homeVM.Mese;

   var result = _db.VW_ATTIVITA_DAILY.Where(m => m.Data == month && m.Tecnico == tecnico).ToList();
}

result is 0, the result is not right.
How can I get all inserted records passing month and year?

A: try this code:
public IActionResult Search(HomeVM homeVM)
{
   var tecnico = _db.Tecnici
       .Where(m => m.Id == homeVM.Attivita.Tecnico)
       .Select(m => m.Surname+ " " + m.Name)
       .FirstOrDefault();

   var result = _db.VW_ATTIVITA_DAILY.Where(m =>
 m.Data.Year == homeVM.Mese.Year
  &&m.Data.Month == homeVM.Mese.Month
 && m.Tecnico == tecnico).ToList();
}

m.Tecnico == tecnico looks very suspisous to me too. I would like to see your
VW_ATTIVITA_DAILY and Tecnici EF classes