text:
Q: Adaptive moving average - top performance in R I am looking for some performance gains in terms of rolling/sliding window functions in R. It is quite common task which can be used in any ordered observations data set. I would like to share some of my findings, maybe somebody would be able to provide feedback to make it even faster.
Important note is that I focus on the case align="right" and adaptive rolling window, so width is a vector (same length as our observation vector). In case if we have width as scalar there are already very well developed functions in zoo and TTR packages which would be very hard to beat (4 years later: it was easier than I expected) as some of them are even using Fortran (but still user-defined FUNs can be faster using mentioned below wapply).
RcppRoll package is worth to mention due to its great performance, but so far there is no function which answers to that question. Would be great if someone could extend it to answer the question.
Consider we have a following data:
x = c(120,105,118,140,142,141,135,152,154,138,125,132,131,120)
plot(x, type="l")

And we want to apply rolling function over x vector with variable rolling window width.
set.seed(1)
width = sample(2:4,length(x),TRUE)

In this particular case we would have rolling function adaptive to sample of c(2,3,4).
We will apply mean function, expected results:
r = f(x, width, FUN = mean)
print(r)
##  [1]       NA       NA 114.3333 120.7500 141.0000 135.2500 139.5000
##  [8] 142.6667 147.0000 146.0000 131.5000 128.5000 131.5000 127.6667
plot(x, type="l")
lines(r, col="red")

Any indicator can be employed to produce width argument as different variants of adaptive moving averages, or any other function.
Looking for a top performance.

A: Somehow people have missed the ultra fast runmed() in base R (stats package). It's not adaptive, as far as I understand the original question, but for a rolling median, it's FAST! Comparing here to roll_median() from RcppRoll.
> microbenchmark(
+   runmed(x = x, k = 3),
+   roll_median(x, 3),
+   times=1000L
+ )
Unit: microseconds
                 expr     min      lq      mean  median      uq     max neval
 runmed(x = x, k = 3)  41.053  44.854  47.60973  46.755  49.795 117.838  1000
    roll_median(x, 3) 101.872 105.293 108.72840 107.574 111.375 178.657  1000

A: December 2018 update
Efficient implementation of adaptive rolling functions has been made in
data.table recently - more info in ?froll manual. Additionally an efficient alternative solution using base R has been identified (fastama below). Unfortunately Kevin Ushey's answer does not address the question thus it is not included in benchmark.
Scale of benchmark has been increased as it pointless to compare microseconds.
set.seed(108)
x = rnorm(1e6)
width = rep(seq(from = 100, to = 500, by = 5), length.out=length(x))
microbenchmark(
  zoo=rollapplyr(x, width = width, FUN=mean, fill=NA),
  mapply=base_mapply(x, width=width, FUN=mean, na.rm=T),
  wmapply=wmapply(x, width=width, FUN=mean, na.rm=T),
  ama=ama(x, width, na.rm=T),
  fastama=fastama(x, width),
  frollmean=frollmean(x, width, na.rm=T, adaptive=TRUE),
  frollmean_exact=frollmean(x, width, na.rm=T, adaptive=TRUE, algo="exact"),
  times=1L
)
#Unit: milliseconds
#            expr          min           lq         mean       median           uq          max neval
#             zoo 32371.938248 32371.938248 32371.938248 32371.938248 32371.938248 32371.938248     1
#          mapply 13351.726032 13351.726032 13351.726032 13351.726032 13351.726032 13351.726032     1
#         wmapply 15114.774972 15114.774972 15114.774972 15114.774972 15114.774972 15114.774972     1
#             ama  9780.239091  9780.239091  9780.239091  9780.239091  9780.239091  9780.239091     1
#         fastama   351.618042   351.618042   351.618042   351.618042   351.618042   351.618042     1
#       frollmean     7.708054     7.708054     7.708054     7.708054     7.708054     7.708054     1
# frollmean_exact   194.115012   194.115012   194.115012   194.115012   194.115012   194.115012     1

ama = function(x, n, na.rm=FALSE, fill=NA, nf.rm=FALSE) {
  # more or less the same as previous forloopply
  stopifnot((nx<-length(x))==length(n))
  if (nf.rm) x[!is.finite(x)] = NA_real_
  ans = rep(NA_real_, nx)
  for (i in seq_along(x)) {
    ans[i] = if (i >= n[i])
      mean(x[(i-n[i]+1):i], na.rm=na.rm)
    else as.double(fill)
  }
  ans
}
fastama = function(x, n, na.rm, fill=NA) {
  if (!missing(na.rm)) stop("fast adaptive moving average implemented in R does not handle NAs, input having NAs will result in incorrect answer so not even try to compare to it")
  # fast implementation of adaptive moving average in R, in case of NAs incorrect answer
  stopifnot((nx<-length(x))==length(n))
  cs = cumsum(x)
  ans = rep(NA_real_, nx)
  for (i in seq_along(cs)) {
    ans[i] = if (i == n[i])
      cs[i]/n[i]
    else if (i > n[i])
      (cs[i]-cs[i-n[i]])/n[i]
    else as.double(fill)
  }
  ans
}

Old answer:
I chose 4 available solutions which doesn't need to do to C++, quite easy to find or google.
# 1. rollapply
library(zoo)
?rollapplyr
# 2. mapply
base_mapply <- function(x, width, FUN, ...){
  FUN <- match.fun(FUN)
  f <- function(i, width, data){
    if(i < width) return(NA_real_)
    return(FUN(data[(i-(width-1)):i], ...))
  }
  mapply(FUN = f,
         seq_along(x), width,
         MoreArgs = list(data = x))
}
# 3. wmapply - modified version of wapply found: https://rmazing.wordpress.com/2013/04/23/wapply-a-faster-but-less-functional-rollapply-for-vector-setups/
wmapply <- function(x, width, FUN = NULL, ...){
  FUN <- match.fun(FUN)
  SEQ1 <- 1:length(x)
  SEQ1[SEQ1 <  width] <- NA_integer_
  SEQ2 <- lapply(SEQ1, function(i) if(!is.na(i)) (i - (width[i]-1)):i)
  OUT <- lapply(SEQ2, function(i) if(!is.null(i)) FUN(x[i], ...) else NA_real_)
  return(base:::simplify2array(OUT, higher = TRUE))
}
# 4. forloopply - simple loop solution
forloopply <- function(x, width, FUN = NULL, ...){
  FUN <- match.fun(FUN)
  OUT <- numeric()
  for(i in 1:length(x)) {
    if(i < width[i]) next
    OUT[i] <- FUN(x[(i-(width[i]-1)):i], ...)
  }
  return(OUT)
}

Below are the timings for prod function. mean function might be already optimized inside rollapplyr. All results equal.
library(microbenchmark)
# 1a. length(x) = 1000, window = 5-20
x <- runif(1000,0.5,1.5)
width <- rep(seq(from = 5, to = 20, by = 5), length(x)/4)
microbenchmark(
  rollapplyr(data = x, width = width, FUN = prod, fill = NA),
  base_mapply(x = x, width = width, FUN = prod, na.rm=T),
  wmapply(x = x, width = width, FUN = prod, na.rm=T),
  forloopply(x = x, width = width, FUN = prod, na.rm=T),
  times=100L
)
Unit: milliseconds
                                                       expr       min        lq    median       uq       max neval
 rollapplyr(data = x, width = width, FUN = prod, fill = NA) 59.690217 60.694364 61.979876 68.55698 153.60445   100
   base_mapply(x = x, width = width, FUN = prod, na.rm = T) 14.372537 14.694266 14.953234 16.00777  99.82199   100
       wmapply(x = x, width = width, FUN = prod, na.rm = T)  9.384938  9.755893  9.872079 10.09932  84.82886   100
    forloopply(x = x, width = width, FUN = prod, na.rm = T) 14.730428 15.062188 15.305059 15.76560 342.44173   100

# 1b. length(x) = 1000, window = 50-200
x <- runif(1000,0.5,1.5)
width <- rep(seq(from = 50, to = 200, by = 50), length(x)/4)
microbenchmark(
  rollapplyr(data = x, width = width, FUN = prod, fill = NA),
  base_mapply(x = x, width = width, FUN = prod, na.rm=T),
  wmapply(x = x, width = width, FUN = prod, na.rm=T),
  forloopply(x = x, width = width, FUN = prod, na.rm=T),
  times=100L
)
Unit: milliseconds
                                                       expr      min       lq   median       uq      max neval
 rollapplyr(data = x, width = width, FUN = prod, fill = NA) 71.99894 74.19434 75.44112 86.44893 281.6237   100
   base_mapply(x = x, width = width, FUN = prod, na.rm = T) 15.67158 16.10320 16.39249 17.20346 103.6211   100
       wmapply(x = x, width = width, FUN = prod, na.rm = T) 10.88882 11.54721 11.75229 12.19790 106.1170   100
    forloopply(x = x, width = width, FUN = prod, na.rm = T) 15.70704 16.06983 16.40393 17.14210 108.5005   100

# 2a. length(x) = 10000, window = 5-20
x <- runif(10000,0.5,1.5)
width <- rep(seq(from = 5, to = 20, by = 5), length(x)/4)
microbenchmark(
  rollapplyr(data = x, width = width, FUN = prod, fill = NA),
  base_mapply(x = x, width = width, FUN = prod, na.rm=T),
  wmapply(x = x, width = width, FUN = prod, na.rm=T),
  forloopply(x = x, width = width, FUN = prod, na.rm=T),
  times=100L
)
Unit: milliseconds
                                                       expr       min       lq   median       uq       max neval
 rollapplyr(data = x, width = width, FUN = prod, fill = NA) 753.87882 781.8789 809.7680 872.8405 1116.7021   100
   base_mapply(x = x, width = width, FUN = prod, na.rm = T) 148.54919 159.9986 231.5387 239.9183  339.7270   100
       wmapply(x = x, width = width, FUN = prod, na.rm = T)  98.42682 105.2641 117.4923 183.4472  245.4577   100
    forloopply(x = x, width = width, FUN = prod, na.rm = T) 533.95641 602.0652 646.7420 672.7483  922.3317   100

# 2b. length(x) = 10000, window = 50-200
x <- runif(10000,0.5,1.5)
width <- rep(seq(from = 50, to = 200, by = 50), length(x)/4)
microbenchmark(
  rollapplyr(data = x, width = width, FUN = prod, fill = NA),
  base_mapply(x = x, width = width, FUN = prod, na.rm=T),
  wmapply(x = x, width = width, FUN = prod, na.rm=T),
  forloopply(x = x, width = width, FUN = prod, na.rm=T),
  times=100L
)
Unit: milliseconds
                                                       expr      min       lq    median        uq       max neval
 rollapplyr(data = x, width = width, FUN = prod, fill = NA) 912.5829 946.2971 1024.7245 1071.5599 1431.5289   100
   base_mapply(x = x, width = width, FUN = prod, na.rm = T) 171.3189 180.6014  260.8817  269.5672  344.4500   100
       wmapply(x = x, width = width, FUN = prod, na.rm = T) 123.1964 131.1663  204.6064  221.1004  484.3636   100
    forloopply(x = x, width = width, FUN = prod, na.rm = T) 561.2993 696.5583  800.9197  959.6298 1273.5350   100

A: For reference, you should definitely check out RcppRoll if you have only a single window length to 'roll' over:
library(RcppRoll) ## install.packages("RcppRoll")
library(microbenchmark)
x <- runif(1E5)
all.equal( rollapplyr(x, 10, FUN=prod), roll_prod(x, 10) )
microbenchmark( times=5,
  rollapplyr(x, 10, FUN=prod),
  roll_prod(x, 10)
)

gives me
> library(RcppRoll)
> library(microbenchmark)
> x <- runif(1E5)
> all.equal( rollapplyr(x, 10, FUN=prod), roll_prod(x, 10) )
[1] TRUE
> microbenchmark( times=5,
+   zoo=rollapplyr(x, 10, FUN=prod),
+   RcppRoll=roll_prod(x, 10)
+ )
Unit: milliseconds
     expr        min         lq     median         uq         max neval
      zoo 924.894069 968.467299 997.134932 1029.10883 1079.613569     5
 RcppRoll   1.509155   1.553062   1.760739    1.90061    1.944999     5

It's a bit faster ;) and the package is flexible enough for users to define and use their own rolling functions (with C++). I may extend the package in the future to allow multiple window widths, but I am sure it will be tricky to get right.
If you want to define the prod yourself, you can do so -- RcppRoll allows you to define your own C++ functions to pass through and generate a 'rolling' function if you'd like. rollit gives a somewhat nicer interface, while rollit_raw just lets you write a C++ function yourself, somewhat like you might do with Rcpp::cppFunction. The philosophy being, you should only have to express the computation you wish to perform on a particular window, and RcppRoll can take care of iterating over windows of some size.
library(RcppRoll)
library(microbenchmark)
x <- runif(1E5)
my_rolling_prod <- rollit(combine="*")
my_rolling_prod2 <- rollit_raw("
double output = 1;
for (int i=0; i < n; ++i) {
  output *= X(i);
}
return output;
")
all.equal( roll_prod(x, 10), my_rolling_prod(x, 10) )
all.equal( roll_prod(x, 10), my_rolling_prod2(x, 10) )
microbenchmark( times=5,
  rollapplyr(x, 10, FUN=prod),
  roll_prod(x, 10),
  my_rolling_prod(x, 10),
  my_rolling_prod2(x, 10)
)

gives me
> library(RcppRoll)
> library(microbenchmark)
> # 1a. length(x) = 1000, window = 5-20
> x <- runif(1E5)
> my_rolling_prod <- rollit(combine="*")
C++ source file written to /var/folders/m7/_xnnz_b53kjgggkb1drc1f8c0000gn/T//RtmpcFMJEV/file80263aa7cca2.cpp .
Compiling...
Done!
> my_rolling_prod2 <- rollit_raw("
+ double output = 1;
+ for (int i=0; i < n; ++i) {
+   output *= X(i);
+ }
+ return output;
+ ")
C++ source file written to /var/folders/m7/_xnnz_b53kjgggkb1drc1f8c0000gn/T//RtmpcFMJEV/file802673777da2.cpp .
Compiling...
Done!
> all.equal( roll_prod(x, 10), my_rolling_prod(x, 10) )
[1] TRUE
> all.equal( roll_prod(x, 10), my_rolling_prod2(x, 10) )
[1] TRUE
> microbenchmark(
+   rollapplyr(x, 10, FUN=prod),
+   roll_prod(x, 10),
+   my_rolling_prod(x, 10),
+   my_rolling_prod2(x, 10)
+ )

> microbenchmark( times=5,
+   rollapplyr(x, 10, FUN=prod),
+   roll_prod(x, 10),
+   my_rolling_prod(x, 10),
+   my_rolling_prod2(x, 10)
+ )
Unit: microseconds
                          expr        min          lq      median          uq         max neval
 rollapplyr(x, 10, FUN = prod) 979710.368 1115931.323 1117375.922 1120085.250 1149117.854     5
              roll_prod(x, 10)   1504.377    1635.749    1638.943    1815.344    2053.997     5
        my_rolling_prod(x, 10)   1507.687    1572.046    1648.031    2103.355    7192.493     5
       my_rolling_prod2(x, 10)    774.381     786.750     884.951    1052.508    1434.660     5

So really, as long as you are capable of expressing the computation you wish to perform in a particular window through either the rollit interface or with a C++ function passed through rollit_raw (whose interface is a bit rigid, but still functional), you are in good shape.


text:
Q: javascript - Show data in loop with html tags I have an array of objects. Each object contain few parameters. What I am trying to do is to run over the array and get from each cell the data and present it on a tabel/grid.
Example code
function addButton(){
    var phoneNumber = document.getElementById("phoneNumber").value;
    var email = document.getElementById("email").value;
    var typeNotification = document.getElementById("typeNotification").value;
    var valueNumber = document.getElementById("valueNumber").value;
    var delayLimit = document.getElementById("delayLimit").value;
    var timeStart = document.getElementById("timeStart").value;
    var timeEnd = document.getElementById("timeEnd").value;

    var notify = {
        typeNotification : typeNotification,
        email : email,
        delayLimit : delayLimit,
        timeStart : timeStart,
        timeEnd : timeEnd,
        valueNumber : valueNumber,
        phoneNumber : phoneNumber
    };

    var notificationList = [];
    notificationList.push(notify);
    console.log(notificationList);

    var notificationListLength = notificationList.length;
    for(var i = 0;i < notificationListLength;i++){

                    1 of 2

                    2 of 2

                    1 of 3

                    2 of 3

                    3 of 3

    }
}

Inside the loop it gives me error with the Tags.
As you can see, when the user press the AddButton it gets all the data and restore it in object, then I add the object into Array, and then I run on the array and get from each cell of the array the data and I want to show it in Grid.
Like I said it gives me error inside the loop with the tags.
Any idea how can I solve it?

A: You need to build up the output of html/tags you want, then add that to a targeted element on the page, like so:

<button onclick="addButton()">Add</button>

As you can see, you can adjust the output before you add it to the target.
I have made all the properties in notificationList strings to save time, but in your example, they would be made up of other elements on the page.
Here is a working example: https://jsfiddle.net/14o8n30u/6/
--EDIT--
Here is the same thing, but this time a table gets updated, using javascript builtin table functions:
<button onclick="addButton()">Add</button>

On mine, I used random data for illustration purposes, but in yours the data will be built from elements on the page.
Note that you have to keep the notificationList outside the addButton, or it gets reset to an empty array each time the button is clicked.
When the page loads, the table head and body are populated.
Then when the addButton is clicked, the table body is emptied, then a new notification is added to the notificationList.
Then, inside the forEach, which loops over the notifications, all the notifications get their own row added at the top of the table (i.e. the entire table body is repopulated each time addButton is clicked).
You may not need to populate your own table header, but if you do, you can see how in this example.
Here it is working (I couldn't get it to work on jsfiddle for some reason): https://codepen.io/leonsegal/pen/oyKBQb
Hope that helps

A:    var notificationListLength = notificationList.length;
   var html_data = '';

    for(var i = 0;i < notificationListLength;i++)
    {
       html_data += '

                            1 of 2

                           2 of 2

                       1 of 3

                       2 of 3

                       3 of 3

';
         }
  /* Make a div(id="html_div") when you need display data */
  document.getElementById("html_div").innerHTML  = html_data ;

redpajama_set_name: RedPajamaStackExchange


text:
Q: If occured said times for said condition From the table below I would like to know if at least two ethiopians took part in marathon in Amsterdam.
Any tips appreciated.

A: So with some help I figured it out
cities_with_2_eth <- df |>
  filter(nation == "ETH") |>
  group_by(Venue) |>
  summarize(n = n()) |>
  filter(n >= 2)
cities_with_2_eth_names <- unique(cities_with_2_eth$Venue)
cities_with_2_eth_fin <- df[df2$Venue %in% cities_with_2_eth_names,]

Credit goes to guys from discoRd


text:
Q: How to connect mssql with php 7.2.5 I've worked with a system on Ubuntu server 17. But after I've upgraded to 18.04 LTS, my mssql connection stopped working.
This is my following program line:
$serverName = "IP OF MY SERVER";
$connectionOptions = array(
    "Database" => "DB NAME",
    "Uid" => "USER",
    "PWD" => "PASSWORD"
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//Select Query
$tsql = "SELECT @@Version as SQL_VERSION";
//Executes the query
$getResults = sqlsrv_query($conn, $tsql);
//Error handling

if ($getResults == FALSE)
    die(FormatErrors(sqlsrv_errors()));

sqlsrv_free_stmt($getResults);

function FormatErrors($errors) {
    /* Display errors. */
    echo "Errors:
";

    foreach ($errors as $error) {
        echo "SQLSTATE: " . $error['SQLSTATE'] . "
";
        echo "Code: " . $error['code'] . "
";
        echo "Message: " . $error['message'] . "
";
    }
}

The current version of my php is 7.2.5.
What should I do considering that everything is updated?

A: In the last version I hadn't to manually install the ssql driver.
But in the newest version of Ubuntu it's necessary.
After installed by following these procedures PROCEDURES it has working again.

A: You can connect this way.
Syntax
 connection mysql_connect(server,user,passwd,new_link,client_flag);
EX
<?php
     $dbhost = 'localhost:3306';
     $dbuser = 'guest';
     $dbpass = 'guest123';
     $conn = mysql_connect($dbhost, $dbuser, $dbpass);
     if(! $conn ) {
        die('Could not connect: ' . mysql_error());
     }
     echo 'Connected successfully';
     mysql_close($conn);
  ?>


text:
Q: Custom Routing with ASP.NET Web API Suppose that I have a nested one to many-type hierarchy database as follows:
One Region has many Countries; each Country has many Cities; a City must belong to one and only one country.
Abstracting this information into a RDBMS is a trivial exercise, but (to my mind) the most sensible REST endpoint to return a list of countries for a given region id would be something like the following:
HTTP GET http://localhost/Region/3/Countries

By default, the .NET Web API's routing would be, at best, http://localhost/Countries/Region/3 or http://localhost/Region/Countries/3.
Is there a sensible naming-convention I should follow, or is the routing customisable enough to allow URIs to take any shape I like?

A: Routings should be quite flexible - the question would be how you'd like to serve the data. Do you have one controller in mind or multiple?
If you had a RegionController I don't see why you couldn't configure a route:
routes.MapHttpRoute(
    name: "CountryList",
    routeTemplate: "{controller}/{regionId}/countries"
);

And a corresponding method:
public CountryCollection Get(int regionId)

Or am I missing something in your question? Where does your default routing come from?
Have a look at their documentation:
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

A: The routing should be customizable enough to get the URLs you're looking for. Assuming you want URLs in the form 'http://localhost/Region/3/Countries', you could register this custom route:
config.Routes.MapHttpRoute("MyRoute", "Region/{regionId}/Countries", new { controller = "Region", action = "GetCountries" });

This would dispatch requests to the 'GetCountries' action on the 'RegionController' class. You can have a regionId parameter on the action that gets model bound automatically for you from the URI.
You may want to look online for the attribute routing package for WebAPI since it may be more appropriate in your case.


text:
Q: How to continue loop when the file is not found I am trying to print the list of files in the date range set by the user.
This is my sample files: Note that there is no "2015-01-01" in the file

If I input range from 2015-01-02 to 2015-01-05 it will print the list if files. But if I input from 2015-01-01 to 2015-01-05 it will result in an error:
OSError: (2, 'No such file or directory', '\\2015-01-01')

Is it possible to have try-except-pass or continue so that my loop will still continue and prints 2015-01-02 to 2015-01-05. And just deny the file not found.
This is my current code:
FileNameList = []
date = start_date
while date <= end_date:
    folder_name = date.strftime(DATE_FORMAT)
    data_folder = path.join(pathDir, folder_name)
    #print data_folder

    for filefolder in os.listdir(data_folder):
        filefolder = data_folder + "\\" + filefolder

    FileNameList.append(filefolder)

    date += delta_one_day

for filefolder in FileNameList:
    for file in os.listdir(filefolder):
        if ".txt" in file:
            filename = filefolder + "\\" + file
            print filename

A: You could try/except the loop, but a better solution might be to only append existing directories to your list in the first place:
# your code and while loop here

if os.path.isdir(data_folder):
    for filefolder in os.listdir(data_folder):
        filefolder = data_folder + "\\" + filefolder

    if os.path.isdir(filefolder):
        FileNameList.append(filefolder)

Putting a for loop inside a try/except block can get a little messy, since you won't be able to continue the loop where you left off in the case that an exception occurs. But if you do want to stick with the EAFP strategy:
for filefolder in FileNameList:
    try:
        files = os.listdir(filefolder)
    except OSError:
        # You could log/print a warning here if you need.
        continue
    for file in files:
        if ".txt" in file:
            filename = filefolder + "\\" + file
            print filename

A: You gave the answer yourself.
try:
    #handles the file
except OSError:
    pass # or log it if needed.

A: You could surround the os.listdir call with a  try except:
try:
    for filefolder in os.listdir(data_folder):
        filefolder = data_folder + "\\" + filefolder
except OSError:
    pass

A: You can use the continue statement :
The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
 #!/usr/bin/python

for letter in 'Python':     # First Example
   if letter == 'h':
      continue
   print 'Current Letter :', letter

var = 10                    # Second Example
while var > 0:
   var = var -1
   if var == 5:
      continue
   print 'Current variable value :', var
print "Good bye!"

This will produce following result:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Good bye!

A: Below is an example where we check that the directory exists before progressing with the for loop.
It may be considered more 'pythonic' to use a try, except block, however I believe that in this instance a simple check is cleaner (just my opinion).
for filefolder in FileNameList:
    # CHECK THAT THE DIRECTORY EXISTS HERE
    if not os.path.isdir(filefolder):
        continue # this instruction will immediately jump to the next for loop iteration, effectively skipping the current iteration.
    for file in os.listdir(filefolder):
        if ".txt" in file:
            filename = filefolder + "\\" + file
            print filename


text:
Q: Issue during reading a CSV file has me stumped I'm trying to write a method that simply reads in a CSV file and stores the data from the file. Here is a link to a screenshot of the CSV file I am trying to read in, and the code for this method:
http://i.imgur.com/jsGTg.png
public static void correctPrices(String correctfile) {

    String data;
    Date date;
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

    File correctedfile = new File(correctfile);
    Scanner correct;

    try {

        correct = new Scanner(correctedfile);

        correct.nextLine(); //to avoid reading the heading
        ArrayList<Date> correctdate = new ArrayList<Date>();
        ArrayList<String> correctdata = new ArrayList<String>();

        while (correct.hasNext()) {

            correctdata.add(correct.nextLine());
            //data = correct.nextLine();
            //String[] corrected = correct.nextLine().split(",");
            //date = formatter.parse(corrected[0]);
            //correctdate.add(date);

        }

        for (int i = 0; i < correctdata.size(); i++) {

            System.out.println(correctdata.get(i));

        }

    }

    catch (FileNotFoundException ex) {

        Logger.getLogger(DataHandler.class.getName()).log(Level.SEVERE, null, ex);

    }

}

As expected, this code would output the last 2 lines of the file. However, when I un-comment data = correct.nextLine(); in the while loop, the output will only return the second line of the CSV, and not the last line. I'm a little baffled by this? All I've tried to do was to store the line into another variable, why would the last line be omitted? Thanks for your help and time, let me know if you need any additional info!

A: The problem is, when you call correct.nextLine(), it reads in a line and then increments a pointer in the file to where you are reading. Since you call that multiple times in the loop, it increments the pointer multiple times, skipping lines.  What you should do is just read the line once, in the beginning of the while loop using
data = correct.nextLine();

and then replace correct.nextLine() everywhere else it appears in the loop with data.
In other words, your while loop would look like
while (correct.hasNext())
{
    data = correct.nextLine();
    correctdata.add(data);
    String[] corrected = data.split(",");
    date = formatter.parse(corrected[0]);
    correctdate.add(date);
}


text:
Q: Rendering a array retrieve from a promise service to the page is pretty slow. How to solve it? I am developing a small project with angular 4, and I am trying to retrieve data from google firebase. The brief description of this project's architecture is:
app-component: inject a login service using firebase.auth().signInWithEmailAndPassword to distinguish if the user is able to login or not. When login success, it will be redirected to the home-component.
home-component:  inject a company service, and using firebase.database().ref().child("COMPANY").once("value") to get data from firebase.
However, when I retrieve the data (an object array) from firebase, and pass to the variable bind to the html page, it renders the array VERY SLOWLY. It costs 30 sec. or more to display data on the page.
If I did something wrong? Or how come the performance was so terrible?

Here is the code slice:
HomeComponent.ts

import { Component, OnInit } from '@angular/core';
import { CompanyService } from '../Service/CompanyService';
@Component({
....
})
export class HomeComponent implements OnInit {
   companies : Object[];
   constructor(private service : CompanyService) {
   }
   ngOnInit() {
     this.service.getAllData()
         .then((result : Object[]) => {
                this.companies = result;
                //this.companies = [ { "CODE": "APTG", "NAME": "APTG Inc." }, { "CODE": "CHT", "NAME": "CHT Inc." }, { "CODE": "FET", "NAME": "FET Inc." }, { "CODE": "T STAR", "NAME": "T STAR Inc." }, { "CODE": "TWM", "NAME": "TWM Inc." } ];
          })
          .catch((error : any) => {
                console.log("error=",error);
          });
       }
}

CompanyService.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Promise } from 'es6-promise';
import 'rxjs/add/operator/toPromise';
import * as firebase from 'firebase';

@Injectable()
export class CompanyService {

    constructor(private http:Http){

    }

    db : any = firebase.database().ref();

    getAllData(){

      return this.db.child("COMPANY")
                        .once("value")
                        .then(function(snapshot){

                          return Promise.resolve(snapshot.val());
                        })
                        .catch(function(error){

                          return Promise.reject(error);

                        });

    }

}

HomeComponent.html

{{companies | json}}


text:
Q: Set UILabel length according to NSString size in pixel : Objective C In my iPad app I am showing scrolling UILabel with text that will be fetched from the web service and the text size of the same need to be set Dynamic. My problem is that I will have to set the width of the UILabel according to the length of the text to be fetched from the web service.
I have tried all or most of the solutions possible but in vain.
Say if the NSString where I am storing the string fetched from the server is with 300 characters,it shows 2270 as width using the following code.
CGFloat width =  [ScrollingLabel.text sizeWithFont:ScrollingLabel.font].width;

ScrollingLabel.frame = CGRectMake(1024,720,width,45);

But then also I am not getting half of the string in the app.

A: I could get the solution of my problem just by multiplying the width with 2 that was been resulting with the code :
CGFloat width =  [ScrollingLabel.text sizeWithFont:ScrollingLabel.font].width;

ScrollingLabel.frame = CGRectMake(1024,720,width,45);

A: Actually the best way to accomplish this is to write a category of UILabel and add the method:
- (CGFloat)expectedWidth
{
    CGSize size = [self.text sizeWithFont:self.font
                        constrainedToSize:CGSizeMake(FLT_MAX,self.bounds.size.height)
                            lineBreakMode:self.lineBreakMode];

     return size.width;
}


text:
Q: Send and get data with socket.io with an other javascript file nodejs and express Lets say I have a JavaScript file that needs to communicate with other JavaScript file. So I could use this data in different javascript file.
In this case I have a game_server.js. In the gameserver.js I have two variables which I would like to use in the gamecore.js

var host // host of the game
var client // client that had joined the game

I would like to send them to the socket.io in de app.js and then use this variables in the game_core.js. So I can have data about the host and the client.
In the gamecore class i would like to have something like this

game_core.prototype.getPlayerInformation = function(data) {
    this.host = data.host
    this.client = data.client
}

It is all about getting information from the serverside to the clientside and the best way to do it is trough socket.io but i really don't know how
Also in the game_server script there is a instance for a game

game_server.createGame = function(player) {
   //Create a new game instance
   var thegame = {
       id : UUID(),                //generate a new id for the game
       player_host:player,         //so we know who initiated the game
       player_client:null,         //nobody else joined yet, since its new
       player_count:1              //for simple checking of state
   };

In the game_core the instance of a game is declared

var game_core = function(game_instance) {
    //Store the instance, if any
    this.instance = game_instance;
}

So it should be possible to get the player_host and player_client?

A: server.js
var app = require('express')()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

server.listen(80);

var Game_core = function(){}
Game_core.prototype.getPlayerInformation = function(data)
{
  this.host = data.host
  this.client = data.client
  return {host: this.host, client: this.client}
}

var game_core = new Game_core()

io.sockets.on('connection', function (socket) {

  socket.emit('login', game_core.getPlayerInformation);

});

client.js
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('login', function(data){
     console.log(data); // {host: xx, client: xx}
  })

</script>


text:
Q: how to run a github pulled project with laravel? i just cloned a project from bitbucket with sourcetree. Now i am trying to run it with laravel. I started my cmd with administrator rights and i am in the right directory of the project. Now when i try to do the 'composer update' command i get this error in my command line :

i know this topic was been discussed before but i couldn't find the answer in them for me. This must have something to do with the fact that me and my friend are making this laravel project together and we are using source tree with bitbucket as a version control system , he can run the project on his computer but when i pull it , it stopped working. Is there annything i need to keep in in mind when using laravel with git ?

A: I had the same problem when i cloned the repository from github.
what id did is

Composer Install

using the terminal in my app directory. It worked A1!
hope this helps

A: You may have to use composer install because laravel by default exludes the following directories from git:
/vendor
/node_modules
.env

Which could be causing your error
Another similar question was asked here covering the same error: Laravel 4: Fatal error: Class 'Patchwork\Utf8\Bootup' not found in autoload.php


text:
Q: Duplicate post in multiple loops on wordpress page I am trying to create multiple loops in wordpress without any repeat post.
this is the code that I have now, where I have added in the first loop
<?php $do_not_duplicate = $post->ID?>

and i have added this in the rest of loops
<?php if( $post->ID == $do_not_duplicate ) continue; ?>

but still showing the post repeated,
please you can help me
thanks
here all of the code

<?php query_posts('cat=8,6,3,2&posts_per_page=4&orderby=rand'); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php $do_not_duplicate = $post->ID; ?>

    <?php the_post_thumbnail(); ?>

<?php endwhile; else: ?>

Sorry, there are no posts to display

<?php endif; ?>

<?php rewind_posts(); ?>

<?php query_posts('category_name=articulo&showposts=1&post_type=post&orderby=date'); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php if( $post->ID == $do_not_duplicate ) continue; ?>

    <?php the_post_thumbnail(); ?>

<?php endwhile; else: ?>

Sorry, there are no posts to display

<?php endif; ?>

<?php rewind_posts(); ?>

<?php query_posts('cat=8,6,3,2&posts_per_page=4&orderby=rand'); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php if( $post->ID == $do_not_duplicate ) continue; ?>

    <?php the_post_thumbnail(); ?>

<?php endwhile; else: ?>

Sorry, there are no posts to display

<?php endif; ?>

<?php rewind_posts(); ?>

<?php query_posts('cat=8,6,3,2,1,4,5,9&posts_per_page=100&orderby=rand'); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php if( $post->ID == $do_not_duplicate ) continue; ?>

    <?php the_post_thumbnail(); ?>

<?php endwhile; else: ?>

Sorry, there are no posts to display

<?php endif; ?>

A: Try using the below code. The basic idea is to store the post ids that are displayed in an array. And while you are in any other loop on the page, Check whether the id exists in the array or not. If the id exists, it means we do not have to show the post.
<?php query_posts('cat=8,6,3,2&posts_per_page=4&orderby=rand'); ?>

<?php $ids_done = array();  ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

$current_post_id = get_the_ID();

if( !in_array($current_post_id,$ids_done) ){ // display only if not a repeated post

    <?php the_post_thumbnail(); ?>

}

<?php $ids_done[] = $current_post_id; ?>

<?php endwhile; else: ?>

Sorry, there are no posts to display

<?php endif; ?>


text:
Q: How to add clickable checkboxes in dompdf? Is it possible to insert clickable checkboxes into PDFs with dompdf? If so, how?
What I mean by 'clickable' is that in the PDF itself, when the user clicks on the checkbox, the checkbox should then become ticked or unticked (depending on its previous state).
I've tried . The checkbox does appear in the PDF but it is static - you cannot interact with it.
Thanks


text:
Q: Prove an identity in a Combinatorics method It is a combinatorics proof. Anyone has any idea on how to prove
$$\sum \limits_{i=0}^{l} \sum\limits_{j=0}^i (-1)^j {m-i\choose m-l} {n \choose j}{m-n \choose i-j} = 2^l {m-n \choose l}\;$$
We need to prove this equation holds for all $l$.
I know that $\sum {n \choose j}{m-n \choose i-j}$ equals to ${m \choose i}$ but has no idea if there is a $(-1)^j$, it seems like a PIE but actually not....
Could anyone help me move forward in the process?

A: It   is convenient  to use the coefficient of operator $[z^n]$ to denote the coefficient of $z^n$ in a series. We   can write    this way
\begin{align*}
[z^m](1+z)^n=\binom{n}{m}\tag{1}
\end{align*}

We obtain
  \begin{align*}
\sum_{i=0}^l&\sum_{j=0}^i(-1)^j\binom{m-i}{m-l}\binom{n}{j}\binom{m-n}{i-j}\\
&=\sum_{i=0}^l\binom{m-i}{m-l}\sum_{j=0}^\infty(-1)^j[z^j](1+z)^n[u^{i-j}](1+u)^{m-n}\tag{2}\\
&=\sum_{i=0}^l\binom{m-i}{m-l}[u^i](1+u)^{m-n}\sum_{j=0}^{\infty}(-1)^ju^j[z^j](1+z)^n\tag{3}\\
&=\sum_{i=0}^l\binom{m-i}{m-l}[u^i](1+u)^{m-n}(1-u)^n\tag{4}\\
&=\sum_{i=0}^{\infty}[z^{m-l}](1+z)^{m-i}[u^i](1+u)^{m-n}(1-u)^n\tag{5}\\
&=[z^{m-l}](1+z)^m\sum_{i=0}^\infty(1+z)^{-i}[u^i](1+u)^{m-n}(1-u)^n\tag{6}\\
&=[z^{m-l}](1+z)^m\left(1+\frac{1}{1+z}\right)^{m-n}\left(1-\frac{1}{1+z}\right)^n\tag{7}\\
&=[z^{m-l}](1+z)^m\cdot\frac{(2+z)^{m-n}}{(1+z)^{m-n}}\cdot\frac{z^n}{(1+z)^n}\\
&=[z^{m-n-l}](2+z)^{m-n}\\
&=[z^{m-n-l}]\sum_{j=0}^{m-n}\binom{m-n}{j}2^jz^{m-n-j}\tag{8}\\
&=2^l\binom{m-n}{l}
\end{align*}

Comment:

*

*In (2) we apply (1) to the binomial coefficients of the inner series and set the upper limit of the index $j$ to $\infty$ without changing anything since we add only zeros.

*In (3) we use the linearity of the coefficient of operator, do some rearrangements to prepare for the next step and use the rule
\begin{align*}
[u^{p-q}]P(u)=[u^p]u^qP(u)
\end{align*}

*In (4) we apply the substitution rule
\begin{align*}
A(u)=\sum_{j=0}^\infty a_ju^j=\sum_{j=0}^\infty u^j[z^j]A(z)\\
\end{align*}

*In (5) we apply (1) to the binomial coefficient of the first series

*In (6) we do again some rearrangement similar to (3)

*In (7) we apply the substitution rule again

*In (8) we select the index $j=l$ to obtain the term with power $m-n-l$

A: Suppose we seek to verify that
$$\sum_{p=0}^l\sum_{q=0}^p (-1)^q
{m-p\choose m-l} {n\choose q} {m-n\choose p-q}
= 2^l {m-n\choose l}$$
where $m\ge n$ and $m-n\ge l.$
This is
$$\sum_{p=0}^l {m-p\choose m-l} \sum_{q=0}^p (-1)^q
{n\choose q} {m-n\choose p-q}.$$
Now introduce the integral
$${m-n\choose p-q} =
\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{p-q+1}} (1+z)^{m-n} \; dz.$$
Note that  this vanishes when $q\gt p$  so we may extend  the range of
$q$ to infinity, getting for the sum
$$\sum_{p=0}^l {m-p\choose m-l}
\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{p+1}} (1+z)^{m-n}
\sum_{q\ge 0} (-1)^q
{n\choose q} z^q
\; dz
\\ = \sum_{p=0}^l {m-p\choose l-p}
\frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{p+1}} (1+z)^{m-n}
(1-z)^n
\; dz.$$
Introduce furthermore
$${m-p\choose l-p} =
\frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{l-p+1}} (1+w)^{m-p} \; dw.$$
This too vanishes when $p\gt l$ so we may extend $p$ to infinity, getting
$$\frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{l+1}} (1+w)^{m}
\\ \times \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z} (1+z)^{m-n}
(1-z)^n
\sum_{p\ge 0} \frac{w^p}{z^p} \frac{1}{(1+w)^p}
\; dz
\; dw.$$
The geometric series converges when $|w/z/(1+w)|\lt 1.$ We get
$$\frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{l+1}} (1+w)^{m}
\\ \times \frac{1}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z} (1+z)^{m-n}
(1-z)^n
\frac{1}{1-w/z/(1+w)}
\; dz
\; dw
\\ = \frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{l+1}} (1+w)^{m}
\\ \times \frac{1}{2\pi i}
\int_{|z|=\epsilon}
(1+z)^{m-n}
(1-z)^n
\frac{1}{z-w/(1+w)}
\; dz
\; dw.$$
Now from the convergence we  have $|w/(1+w)|<|z|$ which means the pole
at $z=w/(1+w)$  is inside  the contour $|z|=\epsilon.$  Extracting the
residue yields (the pole at zero has disappeared)
$$\frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{l+1}} (1+w)^{m}
\left(1+\frac{w}{1+w}\right)^{m-n}
\left(1-\frac{w}{1+w}\right)^n
\; dw
\\ = \frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{l+1}}
(1+2w)^{m-n}
\; dw
\\ = 2^l {m-n\choose l}.$$


text:
Q: Is the function $f(x,y) = \sin(\frac{r}{\theta}), f(0,0) = 0$ continous at the point $ (0,0)$? Is the function $f(\theta,r) = \sin(\frac{r}{\theta}), f(0,0) = 0$ continous at the point $(0,0)$
To clarify, $\theta$ and $r$ are the vector $(\theta,r)$'s polar coordinates. Someone told me that the answer to my question is yes, but it looks like there is a series $(x_n,y_n)$ that tends to $0$ s.t. $\theta = r $, contradicting continuity. Any help would be appreciated!

A: No, $\sin(r/\theta)$ is not continuous. The function $f(x, y) = r \sin(\theta)$ is continuous, however -- perhaps there was a miscommunication.
(To prove it's not continuous, pick $\theta = \pi/2$ and $r_k = 1/(4k+1)$. Then $\theta_k / r_k$ is $\pi/2$ (mod $2 \pi$), so $f$ is one at all these points, but $0$ at their limit.


text:
Q: How to find if an IP address falls in a range specified using a pattern? - ASP.NET If I have an IP address: 192.100.100.2 and need to ensure that it falls within a range specified using wildcard patterns.
The patterns can be either:

 1. 192. *. *. *
 2. *. *. *. *
 3. 192.1**. *.2

So essentially, an asterisk or three asterisks specify the valid range. Is there something built in in ASP.NET I can use to validate the IP address or would this be more of a custom validation?

A: As @AtoMerZ said, just convert your patterns to regular expressions:
    ''//Patterns to search for
    Dim Patterns() As String = {"192.*.*.*", "*.*.*.*", "192.1**.*.2"}

    ''//Test IP
    Dim TestIP = "192.100.100.2"

    ''//Loop through each pattern
    For Each P In Patterns
        ''//Swap two asterisk for two regex digits (\d\d) and one asterisk for one or more digits. Also escape the period
        Trace.WriteLine(System.Text.RegularExpressions.Regex.IsMatch(TestIP, P.Replace("**", "\d\d").Replace("*", "\d+").Replace(".", "\.")))
    Next

A: Convert it to string and use Regex.Match

A: Use this validation expression
ValidationExpression="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
example code
<asp:TextBox ID="TextBox1" runat="server" Width="321px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Validate" />

<asp:RegularExpressionValidator ValidationExpression="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
    ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid IP !" ControlToValidate="TextBox1"></asp:RegularExpressionValidator>


text:
Q: Facebook audience network does not log impressions in android We have integrated the Audience Network Facebook SDK to our android app.
When testing locally, the ads are requested and filled properly.
When the app was released to production, impressions numbers are very less as compared to the fill rate. Our fill rate is very high but the dashboard is showing 0 impressions.
Using our own analytic tools, we are 100% sure that users are receiving and viewing ads. What might be the problem here?


text:
Q: Separating javascript code of my html page I have this code working:
<!DOCTYPE html>

   <button onclick="newQR()">Gerar QRcode</button>

Now I am trying to divide creating a js file and putting the script code inside.
Right now my code is:
html file
<!DOCTYPE html>

  <button onclick="newQR()">Gerar QRcode</button>

javascript file (that it is inside a paste called js)
  function newQR() {
   var x = Math.floor((Math.random() * 99999999999999999) + 1);
   document.getElementById('qrcode').src = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x + "&size=[500]x[500]&ecc=L&qzone=4&format=png";
 }

Why it is not working anymore?

A: I would assume it is because you link your javascript file after you have the function called. I would rather have the javascript reference in the head.
<!DOCTYPE html>

  <button onclick="newQR()">Gerar QRcode</button>

A: Your javascript is linked relatively instead of absolutely:

to

Verify that your JS is viewable in the browser by navigating to /js/script.js. If it's still not working, check your console for errors (right click > inspect element)


text:
Q: "ImproperlyConfigured: Error loading psycopg2 module" after migrate I'm getting this error
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 440, in execute
    self.check()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 478, in check
    include_deployment_checks=include_deployment_checks,
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/model_checks.py", line 28, in check_all_models
    errors.extend(model.check(**kwargs))
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py", line 1183, in check
    errors.extend(cls._check_long_column_names())
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py", line 1588, in _check_long_column_names
    connection = connections[db]
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/utils.py", line 240, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 24, in <module>
    raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Symbol not found: __cg_jpeg_resync_to_restart
  Referenced from: /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libTIFF.dylib
  Expected in: /Library/PostgreSQL/9.4/lib/libJPEG.dylib
 in /System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libTIFF.dylib

Can you please tell me where I am going wrong?
BTW, my psycopg2 is working fine as a standalone module.

A: this statement solved everything: export DYLD_LIBRARY_PATH=''

A: You have to be more precisely with your Question.
First of all, your error is :
ImproperlyConfigured: Error loading psycopg2 module

When do you get this error? (what command you run?)
What is your settings.py looking like?
Also you should format your Question better, it's a pain to read this Traceback!
I know this is more a comment then an answer, but i don't had enough reputation for that.


text:
Q: Laravel Queue Getting Duplicate Values I am using laravel queue to get laters record of users
If two users use the same functaion at same time , the values get replicated
this is my code on controller
.......
SendInvitation::dispatch($email,$name,$nhs_number,$appInfo,$userInfo)->onQueue('high');
........

SendInvitation on quaue code
public function handle()
    {
        try {

        $user = User::orderBy('created_at','DESC')->first();

        if($user != null){
            $enu_id = $user->invitation_id;

        }else{
            $enu_id = "EAA-0001-1";
        }
        $strArray = explode('-', $enu_id );
        $x = $strArray[0];
        if($strArray[0] == $x){
            if($strArray[1] < 9999){
                $get_id = $strArray[1];
                $e_id = $x.'-'.$get_id.'-';
            }else{
                $x++;
                $e_id = $x.'-0001-';
            }
        }else{
            if($strArray[1] < 9999){
                $x++;
                $get_id = $strArray[1];
                $e_id = $x.'-'.$get_id.'-';

            }else{
                $x++;
                $e_id = $x.'-0001-';
            }
        }
      }
    }
   ..........

I am getting the latest users $enu_id and
with a algorithum i am incrementing it
Its working fine....
my problem is if two users register at the same time the both gets the same id
it is wrong , that's why i have used Queaue
Is there any way not to stop overlapping until a queue gets over?
Thank you ....

A: use Group By
Example:
myModel::orderBy('created_at','DESC')->groupBy('user_id')->first();


text:
Q: Present simple or Future simple to answer question about schedule I learned that we should use present simple to talk about schedules. However, if people were to ask me when will my flight leave. How should I respond?
A. My flight will leave at 1:00 pm.
B. my flight leaves at 1:00 pm.
This question is too specific that I can only ask with an example, so I could not find it anywhere on the internet.
Where I learned: https://youtu.be/Z19NAX_gWxI at 8:20

A: They mean the same here, it's just a matter of choice.
For present simple, apart from the usage for "the present", such as facts, habits, temporary situations... etc, we can also use it for "the future".
We use the present simple to talk about the future when we are discussing a timetable or a fixed plan.
For instance:

*

*What time does the show start?

*The train arrives at eight.

*School starts at 7 o'clock. Don't be late!

We can use "will" to talk about future facts.
For instance:

*

*The sun will rise at 6:40 tomorrow.

*The prize will be given to the best player.

*I will not discuss anything related to politics or religion.

In your example, the flight departure time is both a fixed timetable and a future fact, thus both ways are acceptable.
P.S. There are many different ways to express the same thing.

*

*My flight will leave at 1:00 pm.

*My flight leaves at 1:00 pm.

*My flight is leaving at 1:00 pm.

*My flight is going to leave at 1:00 pm.

Sources
"The train will leave" vs. "is going to leave" vs. "leaves" vs. "is leaving" from ELU Stack Exchange
Using the Future Simple Tense from Oyster English
When Should I Use The Present Simple Tense? from Perfect English Grammar


text:
Q: Prove that $f(x)$ is not continuous at any point Let $f:R->R$ be defined by
\begin{equation} f(x)= \left\{ \begin{array}{cc} [x] & \text{if} & x \quad \text{rational}\\\\ [x]+3 & \text{if} &x \quad \text{irrational}\\ \end{array} \right. \end{equation}
where $[x]$ is the greatest integer less than or equal to $x$.
(Example: $[0.5]=0$, $[2]=2$, $[-0.2]=-1$)
Prove that $f(x)$ is not continuous at any point. I know I have to use $Sn$ as a sequence and $C$ as an integer. The sequence I'm using is $Sn=C+\frac{(-1)^n}{n}$. Case 1 will be when $C$ is an integer and case 2 will be when $C$ is an arbitrary point. So far I have:
Let $Sn$ be a sequence such that $lim Sn=C$ where $C$ is not an integer. Then $lim[Sn]=[C]$.

A: If your function is continous then:
$\forall \epsilon >0, \exists \delta > 0 : |x-a|<\delta \implies |f(x) - f(a)|<\epsilon$ must be true.
Let $\epsilon = \frac 12$
for all $x,$ and all $\delta>0$ there is both an irrational and a rational value for $a\in (x, x+\delta)$
And for one of those $|f(x) - f(a)| > \epsilon$
$f(x)$ is not continuous at any $x.$

A: Perhaps you are looking for something that involves a sequence $S_n \rightarrow C$, for which it is not the case that the sequence $f(S_n) \rightarrow f(C)$. In this case, I reckon that the two situations to deal with are $C \in \mathbb{Q}$ and $C \not\in \mathbb{Q}$. The result then follows from the following fact: for every real number $C$, there is both a sequence of only rational numbers that converges to $C$, and a sequence of only irrational numbers that converges to $C$. For example, if $C \in \mathbb{Q}$, then the constant sequence $C, C, C, \ldots \rightarrow C$ consists of all rational elements, whereas the sequence $C + \sqrt{2}/n \rightarrow C$ consists of all irrational elements. If $f$ were continuous, then we would need $f(C)$ to be both $[C]$ and $[C] + 3$, a contradiction. I will leave the case of $C \not\in \mathbb{Q}$ to you.


text:
Q: Why do I have different display resolution options for two different 27" 4K Dell monitors? I'm on an M1 Mac mini and have two displays plugged in, one via a TB/USB-C cable and the other via HDMI.
I want to match them for resolution of menus and palettes at the fourth (of five) resolutions but the intermediate resolutions macOS is offering me are different for each monitor… even thought they are bth native 4K displays (see table for details).
What can I do to change the intermediate display options? Is this associated with the cables at all?

EDIT TO show display preferences when "Option" key is help clicking "Scaled":

A: Have you updated the firmware of the monitors? Sometimes there are updates.

While adequate for the majority of users, these five resolution choices (default and scaled) are missing several "in-between" display options, as well as "low resolution" modes, such as a true 2560×1440 that must be upscaled by the monitor and may be necessary for testing or software compatibility purposes. Thankfully, these resolutions are still accessible, and here's how to access them.
Press and hold the Option key on your keyboard, and then click the "Scaled" option again. (Source)

Have you tried keeping the Default resolution for both monitors and changing the resolution of the individual applications?
Finder resolution for instance can be changed by going to the Home folder > right-click > Show View Options and then changing the icon/text size to your preference. Changing the settings at the Home folder will change all subfolder view options.


text:
Q: calling Wcf rest Service in Angular JS with in the function is not working with $http Hi iam trying to call the Wcf rest service when change the list item in angular JS
here is my sample code
 function sample($scope, $http) {

$http({
    url:     'http://localhost/DataFlow.InternalServices/Service.svc/rest/GetClientValues',
   headers: { 'MyCustomHttpHeader': xmlInput }
}).
    success(function (data) {
        var ClientsData = angular.fromJson(eval("(" + data.GetClientValuesResult + ")"))
        $scope.availableClients = ClientsData.ListData;
    });

$scope.selectedClients = [];

$scope.loadEntities = function (selectedItem) {
    sToken = GenerateToken();
    var selClients = "";
    for (var i = 0; i < selectedItem.length; i++) {
        selClients = selClients + "," + selectedItem[i].ClientID;
    }
    var selectedClients = selectedItem[0].ClientID;
    xmlInput = "<security_token><token>" + sToken + "</token><drawer_id>0000000000</drawer_id><clients>" + selClients + "</clients></security_token>"
    $http({
        url: 'http://localhost/DataFlow.InternalServices/Service.svc/rest/GetEntityByClient',
        headers: { 'MyCustomHttpHeader': xmlInput }
    }).
    success(function (data) {
        $scope.availableEntities = [];
        var EntityData = angular.fromJson(eval("(" + data.GetEntityListValuesByClientResult + ")"))
        $scope.availableEntities = EntityData.ListData;
    });
    $scope.selectedEntities = [];

};

on calling of loadEntites i need to call service again and refresh the items but with the above techinique its always loading previous list only.
how do i reload the latest data.


text:
Q: Show that any graph has an independent set of size at least $\frac{n^2}{2m+n}$ I am trying to show that any graph with n vertices and m edges has an independent set of size at least: $$\frac{n^2}{2m+n}$$
I have already shown that any graph has an independent set of size at least:
$$\sum_{i=0}^n \frac{1}{d(v_i) + 1}$$
where $d(v_i)$ is the degree of vertex $v_i$.
I am trying to deduce the first result from what I have already shown.
I know that $$\sum_{i=0}^n {(d(v_i) + 1)} = 2m + n$$ by the handshaking lemma and I reckon this will be helpful, however I'm struggling to combine it with $\sum_{i=0}^n \frac{1}{d(v_i) + 1}$ to prove the required result.
Any help much appreciated!

A: Hint
You would be done if you could show that
$$
\sum_i \frac1{d(v_i)+1}\ge \frac{n^2}{2m+n}
$$
Letting $f(x)=\frac1{x+1}$, the LHS is $\sum_i f(d(v_i))$. Use the face that the function $f(x)$ is convex.


text:
Q: How to give app permission to create Azure Logic App I am trying to use Microsoft.Azure.Management.Logic.LogicManagementClient to programmatically create a Logic App workflow in Azure. Authentication has already worked, but when I call logicManagementClient.Workflows.CreateOrUpdateAsync(), I am getting a CloudException saying that the client does not have authorization to perform action 'Microsoft.Logic/workflows/write'.
How can I give the app the required permissions?
I have already given it (in the Azure Portal) all permissions for Azure AD and Microsoft Graph. But when I try to add permissions for Windows Azure Service Management API (which I assume is the relevant API here), it says "No application permissions available":

A: You need to give your app at least Contributor access to the resource group via the Access Control (IAM) tab.
To manage Azure resources through the ARM API, you always need a role via RBAC.

A: I did this via PowerShell. I assigned the Contributor role to my App Registration. Here are the commands.
az login

az account set --subscription "YOURSUBSCRIPTIONNAME"

NOTE: Had to create Resource Group in Portal, Use the Application (client) ID of the App Registration Client
New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName Application(client)ID -ResourceGroupName YOURRESOURCEGROUPNAME


text:
Q: "Something went wrong: parameters are of unsupported type" when calling a function I am working on a website for a school project and I am making a review generator. I believe hat the error is something due to an incorrect data type being passed the function but im not sure why. So far this is what i have for this part of the code:
truckReviewCreationSQL = """
        INSERT INTO truckReviews (reviewID, truckID, user, comment, sosRating, qatRating, vfmRating, reply)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    """

def ReviewGenerator():
        db = sqlite3.connect('D:\\Documents\\wlayton\\My Documents\\Coding\\Year 12\\FA 2\\FA2 - Food Truck Website\\truckDB.db')
        cursor = db.cursor()
        global trucksTable
        print("here")
        for truck in trucksTable:
            counter = 0
            numberReviews = random.randint(50,150)
            print("here")
            while counter < numberReviews:
                sos = random.randint(1,3) #Speed of service
                qat = random.randint(1,3) #quality and taste
                vfm = random.randint(1,3) #value for money
                comment = ""
                logedIn = "Review-Robot"
                RatingID = db.cursor().execute("SELECT reviewID + 1 FROM truckReviews ORDER BY reviewID DESC LIMIT 1").fetchone()
                if RatingID == None:
                    RatingID = 0
                else:
                    RatingID = RatingID[0]
                cursor.execute(truckReviewCreationSQL, (RatingID, int(truck[0]), logedIn, comment, sos, qat, vfm, "",)) #adds review to db
                db.commit()
                counter = counter + 1
            print("here - tru") #<------------------------------------ The error pops up after here
            TruckRatingUpdate(truck[0]) #<-------- truck[0] is the id of a truck eg. 116
            print("here - finish tru")

This is the function it is calling upon:
ratingTableUpdate = """
        UPDATE truckRating
        SET numReviews == ?
        SET reviewAvg == ?
        WHERE truckID == ?
    """

 def TruckRatingUpdate(truckID):
        db = sqlite3.connect('D:\\Documents\\wlayton\\My Documents\\Coding\\Year 12\\FA 2\\FA2 - Food Truck Website\\truckDB.db')
        cursor = db.cursor()
        numberReviews = db.cursor().execute("SELECT count(truckID) FROM truckReviews WHERE truckID = ?", truckID).fetchone()
        print(str(numberReviews) + " and " + str(numberReviews[0]))
        if numberReviews[0] > 0:
            sosRating = db.cursor().execute("SELECT sosRating FROM truckReviews WHERE truckID = ?", truckID).fetchall()
            qatRating = db.cursor().execute("SELECT qatRating FROM truckReviews WHERE truckID = ?", truckID).fetchall()
            vfmRating = db.cursor().execute("SELECT vfmRating FROM truckReviews WHERE truckID = ?", truckID).fetchall()
            Total = 0
            for rating in sosRating:
                Total = Total + rating[0]
            for rating in qatRating:
                Total = Total + rating[0]
            for rating in vfmRating:
                Total = Total + rating[0]
            average=Total/(numberReviews[0]*3)
            print("here")
            cursor.execute(ratingTableUpdate, (numberReviews[0], average, truckID,)) #updates review in db
            db.commit()

This is the function it is calling upon and upon calling it i gives the error "Something went wrong: parameters are of unsupported type" so im assuming what i am trying to pass the TruckRatingUpdate(truckID) function is not allowed or incorrect. it is supposed to calculate the average rating for the truck through its reviews then update the SQL table with the new values.
Thanks,
Will

A: You have incorrect SQL syntax in ratingTableUpdate. There should just be one SET clause, with the columns separated by ,.
But there's no need for all these separate queries, as you can use UPDATE-FROM to update TruckRating directly from TruckReviews
def TruckRatingUpdate(truckID):
    db = sqlite3.connect('D:\\Documents\\wlayton\\My Documents\\Coding\\Year 12\\FA 2\\FA2 - Food Truck Website\\truckDB.db')
    cursor = db.cursor()
    cursor.execute('''UPDATE TruckRatings
        SET numReviews = x.num, x.ReviewAvg as av
        FROM (
            SELECT COUNT(*) as num, AVG(sosRationg + qatRating + vfmRating) AS av
            FROM TruckReviews
            WHERE TruckId = ?) AS x
        WHERE TruckID = ?''', (TruckID, TruckID))
    db.commit()


text:
Q: Best metrics on exotic R^4 What is known about the existence of complete metrics with good properties (e.g., Einstein, constant scalar curvature, etc...) on exotic ${\bf R}^4$s?  Note, that some exotic ${\bf R}^4$s have non-complete Kähler-Einstein metrics being open subsets of ${\bf C}P^2$.
One could also ask the much simpler question if there are any more or less explicitly constructed complete metrics on some exotic ${\bf R}^4$s, maybe with bounded curvature or satisfying some other decent condition?
There are some obvious obstructions to good metrics on exotic ${\bf R}^4$s arising from Hopf-Rinow, Cheeger-Gromoll splitting, etc.  What is known about "non-obvious" obstructions?


text:
Q: Prove that $(p-1)! \equiv (p-1) \pmod{1+2+3+\cdots+(p-1)}$
Given a prime number $p$ , establish the congruence:
  $$(p-1)! \equiv (p-1) \pmod{1+2+3+\cdots+(p-1)}$$

I have proceeded like this:
$$\begin{align*}&(p-1)! \equiv (-1) \pmod{p} \quad \quad \quad \text{by Wilson's Theorem}\\
&(p-1)! \equiv 0 \pmod{\frac{p-1}{2}} \end{align*}$$
Then I know that I have to apply Chinese remainder theorem but I don't have a thorough understanding of it.So please give me an elaborate answer to this question with respect to Chinese remainder theorem.

A: One more way to think of this is that Wilson's Theorem says
$$
(p-1)!-(p-1)\equiv0\pmod{p}\tag{1}
$$
and because $(p-1)!\equiv p-1\equiv0\quad\left(\!\bmod\frac{p-1}{2}\right)$
$$
(p-1)!-(p-1)\equiv0\quad\left(\!\bmod\frac{p-1}{2}\right)\tag{2}
$$
Since $\left(p,\frac{p-1}{2}\right)=1$, the Chinese Remainder Theorem says
$$
(p-1)!-(p-1)\equiv0\quad\left(\!\bmod p\cdot\frac{p-1}{2}\right)\tag{3}
$$

A: Note that $1 + 2 + ... + p-1 = \frac{p(p-1)}{2}$ and you can assume that $p > 2$ is odd.
You have a congruence $$ x = (p-1)! \equiv -1 (\bmod p)$$ $$ x = (p-1)! \equiv 0 (\bmod (p-1)/2) $$
Denote $m = p(p-1)/2$ and $m_1 = p , m_2 = (p-1)/2$. Denote $n_i = m/m_i$.
The Chinese Remainder Theorem goes as follows (to our simple case): to solve $x \equiv a_i (\bmod m_i)$ we have to use the fact that $n_i,m_i$ are coprime and thus there are $s_i$ and $r_i$ such that $s_i n_i + r_i m_i = 1$.
In our case you can check that $$ 1 \cdot p - 2 \cdot (p-1)/2 = 1$$ so $n_1 = (p-1)/2 , s_1 = -2$ and $n_2 = p , s_2 = 1$. The general solution is $$x \equiv \sum_{i}a_i s_i n_i \quad (\bmod m)$$ and in our case:
$$ (p-1)! \equiv -1 \cdot (-2)(p-1)/2 + 0 \cdot 1 \cdot p \equiv p-1 \quad (\bmod \frac{p(p-1)}{2})$$
A general layout of the Chinese algorithm can be found in English Wikipedia though the algorithm in the Hebrew Wikipedia is clearer to my taste.

A: First of all, to get the formalities out of the way, since $p$ and $\frac{p-1}{2}$ are relatively prime, there is a unique evaluation$\pmod {p\cdot\frac{p-1}{2}}$ which corresponds to the two remainders you have. Once you're there, we have
$$
(p-1) \equiv 0 \pmod{\frac{p-1}{2}}
$$
as well as
$$
(p-1) \equiv (-1) \pmod p
$$
Which means that $(p-1)$ and $(p-1)!$ fulfills the same relations, hence they must be congurent$\pmod {p\cdot\frac{p-1}{2}}$.


text:
Q: Can we display details of branch owner who committed the change along with last committed date in Hygieia We have 4 projects in GIT hub. Lets assume them as A1, A2, A3 & A4. For all the four projects we have setup corresponding Multibranch jenkins pipeline jobs. Once I setup dashboard I would like to display data of no.of commits in a week, last committed date with owner. Jenkins URL etc. Is it possible with Hygieia?
And also kindly let me know if I can make use of any other database other than Mongo DB.

A: Yes. On hygieia 'repo widget', when you click the data points in graph - it will show your COMMIT INFO such as HASH, AUTHOR, MESSAGE and DATE/TIME


text:
Q: how to pipe PID of java app into a command? I have a command that takes a pid and operates on it.
Works great.
lsof -p 1112| wc -l

But when I use the approach to pipe in the pid, that I normally use, it fails because this is a java app:
lsof -p (ps -e | grep logstash) | wc -l

it fails to work, because java apps do not show up by their name in ps -e, rather they show up as java. (Which doesn't help, because there are multiple java apps)
You can see logstash 7 up from the bottom of this output from ps aux
498       1795 16.9 50.7 551391388 12422888 ?  Sl   Dec14 1425:36 /usr/bin/java
root      1896  0.0  0.0  80900  3344 ?        Ss   Dec14   0:01 /usr/libexec/po
postfix   1901  0.0  0.0  81152  3360 ?        S    Dec14   0:00 qmgr -l -t fifo
root      1926  0.0  0.0 183032  1792 ?        Ss   Dec14   0:00 /usr/sbin/abrtd
root      1938  0.0  0.0 116880  1260 ?        Ss   Dec14   0:00 crond
root      1957  0.0  0.0  21108   492 ?        Ss   Dec14   0:00 /usr/sbin/atd
root      1992  0.0  0.0   4064   512 tty1     Ss+  Dec14   0:00 /sbin/mingetty
root      1994  0.0  0.0   4064   516 tty2     Ss+  Dec14   0:00 /sbin/mingetty
root      1996  0.0  0.0   4064   512 tty3     Ss+  Dec14   0:00 /sbin/mingetty
root      1998  0.0  0.0   4064   516 tty4     Ss+  Dec14   0:00 /sbin/mingetty
root      2000  0.0  0.0   4064   516 tty5     Ss+  Dec14   0:00 /sbin/mingetty
root      2002  0.0  0.0   4064   512 tty6     Ss+  Dec14   0:00 /sbin/mingetty
logstash 37916 10.7  2.2 4767300 553372 ?      SNsl Dec19 167:39 /usr/bin/java -
root     37972  0.0  0.0      0     0 ?        S    Dec19   1:12 [flush-253:2]
postfix  47810  0.0  0.0  80980  3384 ?        S    13:30   0:00 pickup -l -t fi
root     48006  0.0  0.0      0     0 ?        S    14:00   0:00 [flush-253:3]
root     48064  0.1  0.0 104616  4592 ?        Ss   14:04   0:00 sshd: root@pts/
root     48066  0.0  0.0 108352  1828 pts/0    Ss   14:04   0:00 -bash
root     48083  0.0  0.0 110240  1136 pts/0    R+   14:05   0:00 ps aux

What is the way to grep out the pid for logstash ?

A: You can hack around the problem, by passing a random option to the process when starting it like this:
$ ls
Hello.class
$ java -Dprocess_name=Logstash_or_whatever Hello
$ ps -e | grep process_name=Logstash_or_whatever

What do you think? Ugly but workable?

A: We established two solutions:
var1=`pgrep -f logstash`; ls -al /proc/$var1/fd |wc -l

or, more hack,
ls -al /proc/`pgrep -f logstash`/fd |wc -l

Note the use of back ticks.


text:
Q: SWFObject Error in FF & IE, works fine in Chrome I've noticed that I have a strange issue on my website when using Autoviewer (a flash gallery). I never noticed the issue before and I swear it was working fine up until a few months ago, but my gallery will load fine in Chrome, but display the incorrect dimensions in IE and FF.
Here's the error I receive in IE:
Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E)
Timestamp: Mon, 19 Sep 2011 07:30:23 UTC

Message: 'SWFObject' is undefined
Line: 114
Char: 3
Code: 0
URI: http://mikegreenephotography.com/sports/sports.html

Message: 'SWFObject' is undefined
Line: 125
Char: 3
Code: 0
URI: http://mikegreenephotography.com/sports/sports.html

In FF I get:
SWFObject is undefined
var fo = new SWFObject("autoviewer.swf", "autoviewer", "100%", "75%", "8", "#181818");

In Chrome the site works fine. I don't get it. I appreciate any help.

A: If you look at the http responses for your site, you're getting a 404 for the swfobject.js file:
Request URL:http://mikegreenephotography.com/swfobject.js
Request Method:GET
Status Code:404 Not Found

You need to put the swfobject.js file in that location, or update your HTML to reflect the correct location.
Change this line:
<script type="text/javascript" src="../swfobject.js"></script>

To this:
<script type="text/javascript" src="/sports/swfobject.js"></script>

And it will work just fine.


text:
Q: How to stop Cairo Dock minimizing Conky on Show Desktop? Every time I use Cairo Dock Show Desktop add-on Conky minimizes:

I've read about the own_window_type override option on .conkyrc and it seems to work for some people but it doesn't work for me. Conky won't show up if I use this option (it is currently set to own_window_type normal).
Any suggestions?

.conkyrc
# Conky settings #
background no
update_interval 1

cpu_avg_samples 2
net_avg_samples 2

override_utf8_locale yes

double_buffer yes
no_buffers yes

text_buffer_size 2048
#imlib_cache_size 0

temperature_unit fahrenheit

# Window specifications #

own_window yes
own_window_type normal
own_window_transparent yes
own_window_hints undecorate,sticky,skip_taskbar,skip_pager,below

border_inner_margin 0
border_outer_margin 0

minimum_size 200 250
maximum_width 200

alignment tr
gap_x 35
gap_y 55

# Graphics settings #
draw_shades no
draw_outline no
draw_borders no
draw_graph_borders no

# Text settings #
use_xft yes
override_utf8_locale yes
xftfont Neuropolitical:size=8
xftalpha 0.8
uppercase no

temperature_unit celsius

default_color FFFFFF

# Lua Load  #
lua_load ~/.lua/scripts/clock_rings.lua
lua_draw_hook_pre clock_rings

TEXT
${font Neuropolitical:size=42}${time %e}
${goto 100}${font Neuropolitical:size=18}${color FF3300}${voffset -75}${time %b}
${font Neuropolitical:size=10}${color FF3300}${voffset 15}${time %A}${color FF3300}${hr}
${goto 100}${font Neuropolitical:size=15}${color FFFFFF}${voffset -35}${time %Y}
${font Neuropolitical:size=30}${voffset 40}${alignc}${time %H}:${time %M}
${goto 175}${voffset -30}${font Neuropolitical:size=10}${time %S}
${voffset 10}${font Neuropolitical:size=11}${color FF3300}${alignr}HOME${font}
${font Neuropolitical:size=13}${color FFFFFF}${alignr}temp: ${weather http://weather.noaa.gov/pub/data/observations/metar/stations/ LQBK temperature temperature 30} °C${font}
${hr}
${image ~/.conky/logo.png -p 165,10 -s 35x35}
${color FFFFFF}${font Neuropolitical:size=8}Uptime: ${uptime_short}
${color FFFFFF}${font Neuropolitical:size=8}Processes: ${processes}
${color FFFFFF}${font Neuropolitical:size=8}Running: ${running_processes}

${color FF3300}${goto 125}${voffset 27}CPU
${color FFFFFF}${goto 125}${cpu cpu0}%
${color FF3300}${goto 125}${voffset 55}RAM
${color FFFFFF}${goto 125}${memperc}%
${color FF3300}${goto 125}${voffset 56}Swap
${color FFFFFF}${goto 125}${swapperc}%
${color FF3300}${goto 125}${voffset 57}Disk
${color FFFFFF}${goto 125}${fs_used_perc /}%
${color FF3300}${goto 130}${voffset 55}Net
${color FFFFFF}${goto 130}${downspeed eth0}
${color FFFFFF}${goto 130}${upspeed eth0}

${color FF3300}${font Neuropolitical:size=8}${alignr}${nodename}
${color FF3300}${font Neuropolitical:size=8}${alignr}${pre_exec cat /etc/issue.net}  $machine
${color FF3300}${font Neuropolitical:size=8}${alignr}Kernel: ${kernel}
${hr}

A: Use:
own_window_type panel

using panel instead of normal or override should fix your problem, i.e. keep your conky window visible through show_desktop function calls from cairo dock (or other programs)
See below extract from the conky documentation for other settings:
from:   http://conky.sourceforge.net/config_settings.html

if own_window is yes, you may specify type normal, desktop, dock,
  panel or override (default: normal). Desktop windows are special
  windows that have no window decorations; are always visible on your
  desktop; do not appear in your pager or taskbar; and are sticky across
  all workspaces. Panel windows reserve space along a desktop edge, just
  like panels and taskbars, preventing maximized windows from
  overlapping them. The edge is chosen based on the alignment option.
  Override windows are not under the control of the window manager.
  Hints are ignored. This type of window can be useful for certain
  situations.

A: I know this is an old question but for an updated answer in 2022 on Ubuntu 22.04.1,
own_window_type desktop

does the job, as opposed to the accepted answer says to use panel. Panel would take a dedicated space on the screen and it won't let you maximize any other window over it. So use desktop to solve this issue if you are using newer versions of Conky and Ubuntu.
Edit: Apparently the definition had the same information ever since but for some reason the accepted answer has panel as the answer. Just wanted to clarify and acknowledge the definition.
From: https://conky.cc/config_settings#own_window_type

Desktop windows are special windows that have no window decorations;
are always visible on your desktop; do not appear in your pager or
taskbar; and are sticky across all workspaces. Panel windows reserve
space along a desktop edge, just like panels and taskbars, preventing
maximized windows from overlapping them. The edge is chosen based on
the alignment option.


text:
Q: PlayOnLinux won't install anything (17.10) After installing Ubuntu 17.10 from scratch, I installed WineHQ and PlayOnLinux following the instructions on the official websites. Then, in PlayOnLinux I installed the Wine version required by my Windows program and after that tried to install that program itself. But PlayOnLinux seems to finish the installation without even starting it: several seconds after I select the .exe file to install, it simply displays the shortcut creation menu (without any files to create a shortcut for) and that's it. And the list of installed programs remains empty, of course. Trying to install other Windows programs gives the same result. What could be wrong?

A: It seems this version (Ubuntu 17.10) isn't supported any more.
Please see Ubuntu release cycle schedules here.
I suggest to do a clean install of 18.04 or upgrade your system to 18.04 LTS. Because this is a long term supported version, it will serve you well until the end of Q3 2020.
Consider to back up your system and data, things may go wrong during install/upgrade.
You can download the installer of 18.04 LTS from here.
Also try to avoid 18.10, because the support for ubuntu 18.10 will also end within a year, leaving you in a similar situation like 17.10.

A: Make sure you are simulating the correct version of Windows. When PoL is being finicky I either reboot Windows from inside PoL or reboot the computer itself.


text:
Q: sshpass & svn commit in script: Works when script run manually, fails when run with Cron I have written a Bash script that I use to automatically update certain files that I store on SourceForge and GitHub. Near the end of the file, I have two commands that Rsync the updated files to SourceForge and Svn Commit them to GitHub, respectively (before anyone asks, I have my reasons for using Svn rather than Git).
My problem is that while the script does what it needs to do when I run it manually, the line of code that commits the changes to GitHub fails with an authentication error.
I have programmed the script to output the contents of Stderr into a log file. This is the contents of that file after I run the script manually and it works:
auto_update_svn.bash:
17 Sep 2018 18:42 UTC
SSHPASS searching for password prompt using match "assword"
SSHPASS read: Authentication realm: <https://github.com:443> GitHub
SSHPASS read:

SSHPASS read: Password for 'XJDHDR':
SSHPASS detected prompt. Sending password.
SSHPASS read: *
<"SSHPASS read: *" repeated another 25 times
SSHPASS read:

SSHPASS read:

This is what that log says after I run the script through Crontab and it fails:
auto_update_svn.bash:
16 Sep 2018 14:00 UTC
svn: E215004: Authentication failed and interactive prompting is disabled; see the --force-interactive option
svn: E215004: Commit failed (details follow):
svn: E215004: No more credentials or we tried too many times.
Authentication failed
svn: E200042: Additional errors:
svn: E120191: Error running context: The requested authentication type(s) are not supported

From what I can see, sshpass is not running when I run it with Cron and so Svn doesn't receive a password. Strange because a few lines earlier, I use sshpass with Rsync to send file to SouceForge and that works when the script is run through Cron. One solution I've often seen is related to the Path environment variable in Cron being limited. I fixed this in my case with this line near the top of my script but it doesn't help in my case: PATH=$PATH:$(grep 'PATH=' /etc/environment | sed 's/^.*=// ; s/\"//g')
This is what I have in my Crontab:
0 14 *   *   *        /bin/bash /home/svn/xjdhdr-random-code/Bash/auto_update_svn.bash

And this is the contents of my script:
#!/bin/bash

PATH=$PATH:$(sed -n '/PATH=/s/^.*=// ; s/\"//gp' '/etc/environment')

sDateTime=$(date -u +"%d %b %Y %H:%M")
{
        # Commit changes
        #   SourceForge
        sshpass -f "$HOME/sourceforge_password.txt" rsync -qcruz -e ssh --exclude=.svn '/home/svn/xjdhdr-random-code/' \
                'xjdhdr@frs.sourceforge.net:/home/frs/project/xjdhdr-random-code/'

        #   GitHub
        svn status '/home/svn/xjdhdr-random-code/' | grep ^\? | cut -c2- | while IFS='' read -r sFile
        do
                svn add "$sFile"
        done
        sshpass -v -f "$HOME/github_password.txt" svn commit --username=XJDHDR --no-auth-cache \
                -m 'Automatic update of Adblock, Bash + blocklist files' '/home/svn/xjdhdr-random-code'
} 2> '/tmp/stderr-contents-auto_update_svn.txt'

if [ -f '/tmp/stderr-contents-auto_update_svn.txt' ]
then
        errors+=$(cat '/tmp/stderr-contents-auto_update_svn.txt')
        rm -f '/tmp/stderr-contents-auto_update_svn.txt'
fi

if [ -n "$errors" ]
then
        printf 'auto_update_svn.bash:\n%s UTC\n'"$errors"'\n\n' "$sDateTime" >> '/home/error_reports_to_email.txt'
fi

A: I managed to find the cause of my problem and solution.
First, the cause. SSHPass requires that the program run through it must prompt for a password, which it will then supply to the prompting program. Svn commit, in turn, will prompt for a password if one hasn't been supplied through a command line switch and is running in an interactive environment. This is why I was observing what I observed; when running the script manually, svn was running in an interactive environment. Conversely, when svn is run through Cron, it detects that the environment is not interactive. Hence, it does not prompt for a password and SSHPass can't do anything.
The solution in this case is to add the switch --force-interactive to svn's command. Thus, the relevant line in my script now says:
sshpass -v -f "$HOME/github_password.txt" svn commit --username=XJDHDR --no-auth-cache --force-interactive \
        -m 'Automatic update of Adblock, Bash + blocklist files' '/home/svn/xjdhdr-random-code'

Another possible solution would be to add the --password switch to the svn command with the password in question and avoid using SSHPass entirely. In my case, this wouldn't work because that would require adding the password in plain text to the script. This causes two problems for me. First, the script is accessible by every user account on the server I have this script running whereas the password file used by SSHPass is only readable by the user account that is used to execute the script. Second, this script is one of the files that is uploaded to my SourceForge and GitHub repositories.


text:
Q: Awk, tail, sed or others - which one faster for big files? I have scripts for big log files. I can check all line and do something with tail and awk.
Tail:
tail -n +$startline $LOG

Awk:
awk 'NR>='"$startline"' {print}' $LOG

And checking time, tail working 6 mins 39 seconds, awk working 6 mins 42 seconds. So two commands do same thing / same time.
I don't know how to do with sed. Sed can be faster than tail and awk? Or maybe other commands.

Second question, I use $startline and every time continue remains from the last line. For example:
I use script line this:
10:00AM -> ./script -> $startline=1 and do something -> write line number to save file(for ex. 25),
10:05AM -> ./script -> $startline=26(read save file +1) and do something -> write line number save file(55),
10:10AM -> ./script -> $startline=56(read save file +1) and do something ....

But when script is running, checking all lines and when see $startline, doing something. And it's a little slow because of huge files.
Any suggestions for it be faster?
Script example:
lastline=$(tail -1 "line.save")
startline=$(($lastline + 1))
tail -n +$startline $LOG | while read -r
do
....
done
linecount=$(wc -l "$LOG" | awk '{print $1}')
echo $linecount >> line.save

A: tail and head are tools especially created for this purposes, so the intuitive idea is that their are quite optimized for it. On the other hand, awk and sed can perfectly do it because they are like a Swiss Army knife, but this is not supposed to be its best "skill" over the multiple others that they have.
In Efficient way to print lines from a massive file using awk, sed, or something else? there is a nice comparison on methods and head / tail is seen as the best approach.
Hence, I would go for tail + head.

Note also that if it is not only the last lines, but a set of them within the text, in awk (or in sed) you have the option to exit after the last line you wanted. This way, you avoid the script to run the file until the last line.
So this:
awk '{if (NR>=10 && NR<20) print} NR==20 {print; exit}'

is faster than
awk 'NR>=10 && NR<=20'

If your input happens to contain more than 20 lines.

Regarding your expression:
awk 'NR>='"$startline"' {print}' $LOG

note that it is more straight forward to write:
awk -v start="$startline" 'NR>=start' $LOG

there is no need to say print because it is implicit.


text:
Q: How to limit frame rate for all games on Linux Mint? Affected OS

*

*Linux Mint 19.1 "Tessa" - Cinnamon (64-bit), based on Ubuntu 18.04 LTS. (Unimportant, but later updated to 19.3 version.)
the above system was later upgraded to:

*Linux Mint 20.2 "Uma" - Cinnamon (64-bit), based on Ubuntu 20.04 LTS. (This is my primary OS now.)

Related Hardware

*

*CPU: Intel, Core 7th gen (Kaby Lake), i7-7700HQ, base clock 2.80 GHz, max Turbo Boost 3.80 GHz, Smart Cache 6 MB

*GPU: NVIDIA, GeForce GTX 1060, Max-Q Design, 6 GB GDDR5 VRAM

*Screen: 4K laptop 15.6 inch display (UHD 3840 x 2160)

Problem
There are about 200 - 300 FPS while playing any non-GPU-heavy game(s), so I'm thinking there is a lot of power being wasted, and my hardware is overheating if such a game is in the foreground for many hours straight. Additionally, even if I don't pay the electricity bills, I think my hardware is more prone to fault if playing on a maximum frame rate, which in ordinary games can be the above-stated, hardly believable, 200 - 300 FPS.

Question
How can I set an FPS limit for all games on my Nvidia-based hardware? If possible even, to name a few such games?
For example, NOT an advertisement, Hexcells franchise uses so little GPU, and I tested my solution below on these games.

A: NVIDIA-specific solution
Disclaimer: The use of an official driver package from the repository, NOT from a PPA, is recommended by me. You can learn how to install or update your drivers in my other question here: How to install the latest Nvidia drivers on Linux Mint 20

Important Notice
Disclaimer: This solution has been verified and tested only on one Ubuntu 18.04 or 20.04 based system. If you have an older one, DO NOT FOLLOW; use caution on newer versions too.

Solution for Ubuntu 18.04 and 20.04 based systems
This solution utilizes V-Sync (Vertical Synchronization). If you don't like using it, this solution is not for you.
Thank you, Xander, for the comment on enabling V-Sync. With this hint, I was able to find out, that I only need to do the following steps.

*

*Create the following new (if not yet existing) file in your favorite text editor:
/etc/modprobe.d/nvidia-drm-nomodeset.conf

*Put this single line in there, save and close the file; in case the file exists already, then ensure this line is there:
options nvidia-drm modeset=1

*Update all of your initramfs images with:
sudo update-initramfs -u -k all

or if you only want to test it, you can update just the latest image with:
sudo update-initramfs -u

*Reboot your system.

*The V-Sync shall be on now, verify with:
sudo cat /sys/module/nvidia_drm/parameters/modeset

It will say:

*

*Y
if V-Sync is On

*

*N
if V-Sync is Off

You should be done now, capped to your display refresh rate (usually 60).
In spite, I am satisfied with this solution, feel free to add your own (AMD-specific, Intel-specific, whatever...) to make this question useful for others.


text:
Q: Is it possible to calculate a coordinate with these conditions? enter image description hereI'm studying about algorithms for GPS or several surveying problems.
I want to know is it possible to solve the problem below.
We know

*

*Global coordinates of two points.

*Bearings, azimuths and distances of the two points above from certain unknown point X.
(It is such a local coordinate system.)

and the goal is

*

*Find the global coordinate of the unknown point

So, I tried to find the transformation matrix from the global coordinate system to the local coordinate system which has a origin at X. But, than I have to find the rotation matrix with 3 angles. So, I want to know is it possible to find that 3 angles with the given conditions.
I appreciate any of your help. Please understand me if there are strange sentences because I'm not good at English.

I hope this image helps you to understand this problem.

A: If you know azimuth and distance from a single known point to an unknown point you can determine its coordinates. Knowing its distance from a second known point and its azimuth as seen at that known point is unnecessary. The two points and the north pole are vertices of a spherical triangle. You know the length of the side from the known point to the pole (90 degrees minus the known point's latitude), you also know the length of the side from point to point, and you know the included angle between those sides (the azimuth of the unknown point as seen at the known point). Using the law of cosines for spherical triangles you can find the length of the third side (from the pole to the unknown point) and subtracting that length from 90 degrees gives you the unknown's latitude. Then using the law of sines for spherical triangles find the angle at the pole which gives the difference in longitude between known and unknown.


text:
Q: Clustering points around already known cluster centers I have a set of points (~1000) and a set of cluster centers (~100). I now want to cluster the set of points taking the already known cluster centers into account. All clusters should start out from the already known cluster centers growing outwards collecting all points less than x meters away from the closest point already inside the cluster.
I now have the following pretty standard PostGIS dbscan query:
WITH clusters AS (
  SELECT
    landmark_id, coordinate,
    ST_ClusterDBSCAN(coordinate, eps := (30 / 111111.0), minpoints := 10) OVER() AS cluster_id
  FROM landmarks
  WHERE coordinate IS NOT NULL
)
SELECT
  cluster.id, cluster.landmark_ids,
  ST_Centroid(cluster.geometry) AS coordinate,
  ST_AsGeoJSON(cluster.geometry) AS geometry
FROM (
  SELECT
    cluster_id AS id,
    array_agg(landmark_id) AS landmark_ids,
    ST_ConvexHull(ST_Collect(coordinate)) AS geometry
  FROM clusters
  WHERE cluster_id IS NOT NULL
  GROUP BY cluster_id
) AS cluster;

Any pointers how I can adapt the above query or write another query to do what I want without resorting to procedural code (if so I would appreciate some pointers about that as well)?

A: By already in the cluster, I wasn't sure if you meant those picked up by the first cluster or including those you would recursively pick up.
This solution only compares against the original cluster, doesn't try to do based on recursive cluster matching.  That would require a recursive query, and I question if it would yield any better answers.
Also not sure why you decided to go with convexhull to compute your centroid against, I would assume you'd want the true centroid, which can be done against the ST_Collect output.
WITH cluster1 AS (
  SELECT
    landmark_id, coordinate,
    ST_ClusterDBSCAN(coordinate, eps := (30 / 111111.0), minpoints := 10) OVER() AS cluster_id
  FROM landmarks
  WHERE coordinate IS NOT NULL
),
clustered AS ( SELECT * FROM cluster1 WHERE cluster_id IS NOT NULL )
clusterall AS (
SELECT
    l.landmark_id, l.coordinate, c.cluster_id
 FROM landmarks AS l
    CROSS JOIN
    -- find closest cluster
        LATERAL (SELECT cluster_id
                FROM clustered AS c
            ORDER BY  c.coordinate <-> l.coordinate LIMIT 1 ) AS c
    -- only look for landmarks not matched to a cluster
    WHERE l.landmark_id NOT IN(SELECT c.landmark_id FROM clustered AS c)
UNION ALL
SELECT c.landmark_id, c.coordinate, c.cluster_id
    FROM cluster1
)
SELECT
  cluster.id, cluster.landmark_ids,
  ST_Centroid(cluster.geometry) AS coordinate,
  ST_AsGeoJSON(cluster.geometry) AS geometry
FROM (
  SELECT
    cluster_id AS id,
    array_agg(landmark_id) AS landmark_ids,
    ST_ConvexHull(ST_Collect(coordinate)) AS geometry
  FROM clusterall
  GROUP BY cluster_id
) AS cluster;


text:
Q: ul Tags> li I want to get the number of tags In the source, we want to find the number of li.q_basket_area belonging to ul#side-recent-area.
The value displayed in the console log is 3 instead of 5.
The console outputs 5 correctly.
$newAt(".recent_number").text('['+ nodesSameClass +']');

In the above case, the value of nodesSameClass is 3.
The style of the diplaynone class is display:none!important;
Is this affected? What's wrong?
Thank you in advance.

var parent = document.getElementById("side-recent-area");
var nodesSameClass = parent.getElementsByClassName("q_basket_area");
console.log(nodesSameClass.length);
.displaynone {display:none!important;}

                product

                    (eng : )

                product

                    (eng : )

                product

                    (eng : )

                product

                    (eng : )

                product

                    (eng : )

A: Well the result is not wrong. Check Terry's post how to exclude, anything that you do not wish to get as an element. It answers your question exactly.
An alternative as a solution in a single line is by using querySelectorAll.
var l = document.querySelectorAll( 'ul#side-recent-area li.q_basket_area:not(.displaynone)' ).length;
console.log( l ); // run this to get the result

A: When you select for elements whose class matches q_basket_area, JS will return all the nodes regardless of whether they are visible or not. If you want to filter the node collection such that only visible nodes remain, you will need to:

*

*Convert the node collection into an array

*Filter the array, by checking the computed style of the element individually to see if their display property is set to "none"
In JavaScript, this can be done as follow:

*

*Use Array.prototype.slice.call(<NodeCollection>) to convert the collection into an array

*Filter the array by checking the computed display property, accessible using window.getComputedStyle(<YourElement>).display, and checking if it matches the string "none" or not.

var parent = document.getElementById("side-recent-area");
var nodesSameClass = parent.getElementsByClassName("q_basket_area")

var visibleNodes = Array.prototype.slice.call(nodesSameClass)
   .filter(function(element) {
     return window.getComputedStyle(element).display !== 'none';
  });

console.log(visibleNodes.length);

See the snippet below as a proof-of-concept demo:

var parent = document.getElementById("side-recent-area");
var nodesSameClass = parent.getElementsByClassName("q_basket_area")

var visibleNodes = Array.prototype.slice.call(nodesSameClass)
   .filter(function(element) {
     return window.getComputedStyle(element).display !== 'none';
  });

console.log(visibleNodes.length);
.displaynone {display:none!important;}

                product

                    (eng : )

                product

                    (eng : )

                product

                    (eng : )

                product

                    (eng : )

                product

                    (eng : )

If you are familiar with the ES6 syntax, things get a lot easier:
const parent = document.getElementById("side-recent-area");
const nodesSameClass = parent.getElementsByClassName("q_basket_area")

const visibleNodes = Array.from(nodesSameClass)
   .filter(element => window.getComputedStyle(element).display !== 'none');

console.log(visibleNodes.length);

The difference is that:

*

*You can use const instead of var

*You can use Array.from to convert a NodeCollection into an Array

*You can use arrow functions in the callback of Array.prototype.filter() method

A: You can also use CSS to get the count of list items:
check out: https://www.w3schools.com/css/css_counters.asp

li {
 counter-increment: section
}

ul:after {
 content: "Item Count:" counter(section) "";
 margin-top: 2rem;
 display: block;
}

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.

List item.