text:
Q: How to get next point in Highcharts tooltip how can I access to the next point of the series from the tooltip formatter.
Because I want to do a sum between both points.
Like this.y + next.y.
But I don't know how to have an access to the next point.
If someone have an answer. Thanks

A: This need to be done in a few steps:

*

*get x-index according to x-value: var index = this.series.xData.indexOf(this.x);

*now get y-value: var nextY = this.series.yData[index+1];
And all you need to do is to sum values, like this: var sum = this.y + nextY;.


text:
Q: Producing numeric sequences in R using standard patterns I am working on a project where I need to enter a number of "T score" tables into R. These are tables used to convert raw test scores into standardized values. They generally follow a specific pattern, but not one that is simple. For instance, one pattern is:
34,36,39,42,44,47,50,52,55,58,60,63,66,68,
71,74,76,79,82,84,87,90,92,95,98,100,103,106

I'd prefer to use a simple function to fill these in, rather than typing them by hand. I know that the seq() function can create a simple seqeuence, like:
R> seq(1,10,2)
[1] 1 3 5 7 9

Is there any way to create more complex sequences based on specific patterns? For instance, the above data could be done as:
c(34,seq(36:106,c(3,3,2)) # The pattern goes 36,39,42,44,47,50,52 (+3,+3,+2)

...however, this results in an error. I thought there would be a function that should do this, but all my Google-fu has just brought me back to the original seq().

A: Here is a custom function that should work in most cases. It uses the cumulative sum (cumsum()) of a sequence, and integer division to calculate the length of the desired sequence.
cseq <- function(from, to, by){
  times <- (to-from) %/% sum(by)
  x <- cumsum(c(from, rep(by, times+1)))
  x[x<=to]
}

Try it:
> cseq(36, 106, c(3,3,2))
 [1]  36  39  42  44  47  50  52  55  58  60  63  66  68  71  74  76  79  82  84  87  90  92  95  98
[25] 100 103 106

> cseq(36, 109, c(3,3,2))
 [1]  36  39  42  44  47  50  52  55  58  60  63  66  68  71  74  76  79  82  84  87  90  92  95  98
[25] 100 103 106 108

A: Here is a non-iterative solution, in case you need a specific element of the sequence
f <- function(x){
 d <- (x) %/% 3
 r <- x %% 3
 31 + d*8 + c(0,3,5)[r+1]
}

> f(1:10)
 [1] 34 36 39 42 44 47 50 52 55 58

A: This could be done using the cumsum (cumulative sum) function and rep:
> 31 + cumsum(rep(c(3, 2, 3), 9))
 [1]  34  36  39  42  44  47  50  52  55  58  60  63  66  68  71  74  76  79  82
[20]  84  87  90  92  95  98 100 103

To make sure sure the sequence stops at the right place:
> (31 + cumsum(rep(c(3, 2, 3), 10)))[1:28]
 [1]  34  36  39  42  44  47  50  52  55  58  60  63  66  68  71  74  76  79  82
[20]  84  87  90  92  95  98 100 103 106

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add multiple overlay? I have 1 command to add gif overlay on video, and it works. Then I want to add a gif to the bottom right of the video and a logo in the middle left of the video. How can I do this?
My command:
ffmpeg -nostdin -y -i input.mp4 -ignore_loop 0 -i snow.gif -filter_complex "[0:v][ckout]overlay[out];[1:v]colorkey=0x000000:1.0:1.0[ckout]" -shortest -map [out] -map 0:1 -pix_fmt yuv420p -c:a copy -c:v libx264 -crf 18 output.mp4

A: How to add multiple overlay
ffmpeg -nostdin -y -i input.mp4 -ignore_loop 0 -i snow.gif -ignore_loop 0 -i bottom_right.gif -i logo.png -filter_complex "[1:v]colorkey=0x000000:1.0:1.0[fg];[0][fg]overlay=shortest=1[bg1];[bg1][2]overlay=main_w-overlay_w:main_h-overlay_h:shortest=1[bg2];[bg2][3]overlay=0:(main_h-overlay_h)/2,format=yuv420p[v]" -map "[v]" -map 0:a? -c:v libx264 -crf 18 -c:a copy -movflags +faststart output.mp4

See overlay filter documentation and How to add and position watermark with ffmpeg?.
How to add audio filters to above command
ffmpeg -nostdin -y -i input.mp4 -ignore_loop 0 -i snow.gif -ignore_loop 0 -i bottom_right.gif -i logo.png -filter_complex "[1:v]colorkey=0x000000:1.0:1.0[fg];[0][fg]overlay=shortest=1[bg1];[bg1][2]overlay=main_w-overlay_w:main_h-overlay_h:shortest=1[bg2];[bg2][3]overlay=0:(main_h-overlay_h)/2,format=yuv420p[v];[0:a]asetrate=9.9/10*44100,atempo=10/9.9,lowpass=f=2500,highpass=f=400[a]" -map "[v]" -map "[a]" -c:v libx264 -crf 18 -c:a aac -movflags +faststart output.mp4


text:
Q: Add unparsable cruft to ASP.NET MVC JsonResult In light of posts such as these:
JSON unparseable cruft: Why so serious?
Why do people put code like "throw 1; <dont be evil>" and "for(;;);" in front of json responses?
Why does Google prepend while(1); to their JSON responses?
I would like to follow the advice laid out in the following answer: How should web app developers defend against JSON hijacking?
Is there an easy way to add an unparsable cruft to JSON responses built using System.Web.Mvc.JsonResult? The security.se post suggests that I use </* at the beginning of the response.

A: You could write a custom action result to perform this:
public class SafeJsonResult: JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Write("</*");
        base.ExecuteResult(context);
    }
}

and then use it instead of the default one:
public ActionResult Index()
{
    return new SafeJsonResult
    {
        Data = new { Foo = "bar" },
        JsonRequestBehavior = JsonRequestBehavior.AllowGet,
    };
}


text:
Q: What features does Cmake have that make+pkg-config doesn't? Lets me clarify the question in the title:
What features does Cmake have that make + pkg-config doesn't, besides platform independency.
Context:

*

*I code only for Linux systems, and use for my projects (gnu)make associated with pkg-config

*I know CMake is the de-facto standard today for large projects, and I have used it many times (as an "end-user").

Why am I asking this:
I have noticed that some (?) large projects dropped support for pkg-config to rely only on CMake.
See Opencv here for example, where it is said that "Pkg-config has very limited functionality".
Considering only Linux-based builds, what can I do with CMake that I cannot do with make+pkg-config, besides platform independency? Or is it only about that?
This is a real question, because I never encountered a situation where I felt I was missing some feature, but I feel like I could be missing something.
Please no opinion-based answers, facts only.
Edit: to clarify what I am asking for (I know CMake is a bit a "higher-level" tool than make): it seems that some think that
"Pkg-config has very limited functionality". My question can be reworded as "what functionalities lacks pkg-config?".


text:
Q: How can I modify this RegEx pattern to capture the info I want? This is my RegEx pattern: \b\d+\w{0,2}\s\w+(\s\w+)?\b
I am trying to capture the street number, street name, and street type in the following test addresses:
N1 2XQ, Flat 2, 325 Upper Street, London
SE15 1TX, 1 Penarth Street, London
KT9 2EY, 158 Bridge Road, Chessington, Surrey
NW10 4HP, 32AB Springwell Avenue, London
SW6 4DP, 16 St Maur Road, London
SW6 6NZ, Flat 19 Elm Lodge, 75 Stevenage Road, London
KT11 2BT, 11 Fairbourne, Cobham, Surrey
SW6 4BS, 24 Crondace Road, London
KT12 3LJ, 3b Ambleside Avenue, Walton on Thames
SW9 0NR, 66 Cranworth Gardens, London
FLat 5, 12 Ellerker Gardens
SW17 7JN, Flat F23, Du Cane Court, Balham High Road, Balham, London
1 Aragon Close, Enfield, Middlesex, EN2 8WL
SW16 4JF, 34 Norbury Rise, London

The problem: It matches post certain post codes as well. I do not understand why because I specify my RegEx pattern to start with a digit.I would also like to be able to capture the dash and unit number in the following address:
121-135 Green Lanes

A: As discussed on the comments section  . The input is mal-formatted and therefore it is a little unclear as to what is it that we need capture  . If the file was properly spitted by comma , the below regex will just need to capture  what is inside the commas - excluding commas.
/(?<=\,).+?(?=,)/

tested it here : rublar.com

Edit : Tried it like this too , but you just can not cover all variations.
\s+\d[0-9]+(?:\w+)?\s+\w+\s((:?\w+)?){0,2}(?=\,)


text:
Q: In R separate values in one column into two columns I have a three-column dataset df1 with this data:
ID  Age Games
1   36  10
2   36  15
3   36  20
4   36  30
1   37  40
2   37  50
3   37  35
4   37  45

Here is the dput for the df1 dataset:
structure(list(ID = c(1, 2, 3, 4, 1, 2, 3, 4), Age = c(36, 36,
36, 36, 37, 37, 37, 37), Games = c(10, 15, 20, 30, 40, 50, 35,
45)), class = "data.frame", row.names = c(NA, -8L))

I want the data to be appear the way shown in the table below where the games for each ID's Age 36 and Age 37 values are now in separate columns:
ID  Age36 Age37
1    10     0
2    15     0
3    20     0
4    30     0
1     0    40
2     0    50
3     0    35
4     0    45

My goal is to create from the second table a line chart with two line graphs, one for the Age36 games for each ID and the other for the Age 37 games, using pivot_longer to prepare the data for input into ggplot2 (unless you can recommend a better way of doing that).

A: Simply follow this code
library(tidyverse)

df %>% mutate(row = row_number()) %>%
  pivot_wider(id_cols = c(row, ID), names_from = Age, values_from = Games, values_fill = 0L) %>%
  select(-row)

# A tibble: 8 x 3
     ID  `36`  `37`
  <dbl> <dbl> <dbl>
1     1    10     0
2     2    15     0
3     3    20     0
4     4    30     0
5     1     0    40
6     2     0    50
7     3     0    35
8     4     0    45

Explanation:  Since your ID column is not unique we have to create a dummy ID column by using row_number() and in last we can unselect it.


text:
Q: Synchronize project in Eclipse with SVN only source files not others like jar I am synchronizing code of my project to repo's project. I am interested in only .java files which I made new or made changes..not .jar files.
however when I use synchronize with repo's it shows all source files and .jar files as well,
I just want to see .java files (changed & added).
I am using Eclipse and SVN.

A: On my Subclipse version 1.8.4, there is no filter action to set which resources to show. You may want to check if the latest version supports this (version 1.10.5 as of today) http://subclipse.tigris.org/subclipse_1.10.x/changes.html.
However, in the Synchronize view, you can right-click a resource and select "Remove from View". This way you can remove everything except the folder containg your .java files.
If you then edit another .java file it should automatically appear in the Synchronize view to show that it has been changed/added. However if you modify a file of other type (e.g. an XML file or a Jar file gets updated), it will re-appear and you have to remove it from view again.


text:
Q: Basic Error Propagation: Do we use the formula of the original equation to calculate uncertainty? This is a very basic question. I have been asked to find the uncertainty for $F_{c,th}=\frac{4\pi^2mr}{T^2}$. What would be the formula for $\delta F_{c,th}$ given that $m$, $r$ and $T$ are measured values.
What I tried: I only calculated uncertainty based on the operations between the measured variables. After using uncertainty rules, I got: $$F_{c,th}= \frac{\delta r}{|r|}+\frac{\delta m}{|m|}+2\frac{\delta T}{|T|}$$ Is this correct?

A: The left side should be $\frac {\delta F_{c,th}}{F_{c,th}}$  You took the log and then the differential on the right and should do the same on the left.


text:
Q: SQL Server 2012 Express - Logs? Newbie question.
I have a SQL Server 2012 Express. Each day we do a full backup and get it FTP'd off site using a 3rd party tool. We don't need incremental backups or other things. If there is a problem, then entire database would get restored, which is fine.
To keep the size of the database small, how do I clean out the logs that I don't need. I noticed they are getting big.


text:
Q: specific fill order in geom_area Happy new year! Consider this simple example:
> df <- tibble(type = c('0_10','0_9','0_8','0_10','0_9','0_8','1_10','1_9','1_8','1_10','1_9','1_8'),
+        time = c(1,1,1,2,2,2,1,1,1,2,2,2),
+        value = c(2,3,4,2,3,6,-2,-3,-4,-2,-3,-5))
> df
# A tibble: 12 x 3
   type   time value
   <chr> <dbl> <dbl>
 1 0_10      1     2
 2 0_9       1     3
 3 0_8       1     4
 4 0_10      2     2
 5 0_9       2     3
 6 0_8       2     6
 7 1_10      1    -2
 8 1_9       1    -3
 9 1_8       1    -4
10 1_10      2    -2
11 1_9       2    -3
12 1_8       2    -5

I am creating a plot that stacks the values of value over time, by type. I would like to obtain the same color for the type 0_10 and 1_10, another color for 0_9 and 1_9 and another color for 0_8 and 1_8.
Unfortunately, ggplot does not seem to use the factor ordering I am asking for. You can see below that 0_10 is purple while 1_10 is green... They should have the same color.
mylevels = c('0_10','0_9','0_8','1_10','1_9','1_8')

df %>%
  ggplot(aes(x = time)) +
  geom_area(inheris.aes = FALSE,
            data = . %>%  dplyr::filter(str_detect(type, '0_')),
            aes(y = value,
                fill = factor(type, levels = mylevels)),
            position = 'stack', color = 'black')+
  scale_fill_viridis_d() +
  geom_area(inheris.aes = FALSE,
            data = . %>%  dplyr::filter(str_detect(type, '1_')),
            aes(y = value, fill = factor(type, levels = mylevels)),
            position = 'stack', color = 'black')

Any idea?
Thanks!

A: I'd create a new column from the last numbers from your type column for the fill. and create groups by type.
library(tidyverse)
df <- tibble(type = c('0_10','0_9','0_8','0_10','0_9','0_8','1_10','1_9','1_8','1_10','1_9','1_8'), time = c(1,1,1,2,2,2,1,1,1,2,2,2), value = c(2,3,4,2,3,6,-2,-3,-4,-2,-3,-5))

df %>%
  mutate(colvar = gsub("^*._","", type)) %>%
  ggplot(aes(x = time)) +
  geom_area(aes(y = value,
                fill = colvar,
                group = type),
            position = 'stack', color = 'black') +
  scale_fill_viridis_d()

If you want to visualise your information of your first "type number", you need to make it another aesthetic, for example alpha:
update new colvar variable as factor with ordered levels
df %>%
  mutate(colvar = factor(gsub("^*._","", type), levels = 8:10),
         alphavar =  as.integer(substr(type, 1, 1))) %>%
  ggplot(aes(x = time)) +
  geom_area(aes(y = value,
                fill = colvar,
                group = type,
                alpha = alphavar),
            position = 'stack', color = 'black') +
  scale_fill_viridis_d() +
  scale_alpha_continuous(breaks = 0:1, range = c(0.7,1) )


text:
Q: Jenkins Pipeline - Create file in workspace (Windows Slave) For a number of reasons, it would be really useful if I could create a file from a Jenkins pipeline and put it in my workspace. If I can do this, I could avoid pulling in some repositories where I'm currently pulling them in for just one or two files, keep those files in a maintainable place, and I could also use this to create temporary powershell scripts, working around a limitation of the solution described in https://stackoverflow.com/a/42576572
This might be possible through a Pipeline utility, although https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/ doesn't list any such utility; or it might be possible using a batch script - as long as that can be passed in as a string

A: You can do something like that:
node (''){
  stage('test'){
    bat """
      echo "something" > file.txt
    """
    String out = readFile(file.txt).trim()
    print out // prints variable out groovy style
    out.useFunction() // allows running functions loaded from the file
    bat "type %out%" // batch closure can access the variable
  }
}


text:
Q: Centos - Can not remove file as Root (no error, nothing) as stated in title, I cannot remove file from centos as the root user.
rm filename.php
rm: remove regular empty file 'filename.php'? y

Nothing happens, file still in place
OS: CentOS Linux release 7.3.1611 (Core)
I tried
rm -f

I also tried
find -name .... -delete .
I also checked dmesg and nothing related there.
I also made a new file in same directory and remove it without any problems.
UPDATE. I can edit this file, but once I try to remove it, file becomes empty but still there.
I checked if this file is used by any processes and its not.


text:
Q: On pressing chrome extension shortcut, operation keeps on performing if the shortcut key is pressed When I press a shortcut assigned to a chrome extension, as long as shortcut keys is pressed, the operations keeps on performing. I have tried it with multiple extension. Is it intentional behaviour? Do extension developer need to handle it on their end? Or not?

A: Is it intentional behaviour as when you open a text editor, you keep on pressing any key and see its echo on monitor :-)
This is unless the developer has planned a different behavior


text:
Q: Check if Minimum interval between time is 2 hours with jQuery Im using the car rental plugin and need to modify it in a way that if the rental time chosen by customer is less than 2 hours, to give him a message, pop up or any kind of message, that he needs to choose time minimum 2 hours for rental.
You can see the example here: http://envato.bestsoftinc.net/wp-car/
I need to make sure that there is at least 2 hour difference between pick up date field and drop off date field, if not, I need to show him message and not let him click on the Search Button. Any ideas how I can achieve that with jQuery or Regular Javascript please?
Thank you

A: this is the basic logic for it, try implement this with your site.
i found moment.js is really helpful with js time date obj you can give it a try
if($('#checkInDate').value() === $('#checkOutDate').value) [

if both date is the same date, than
       var checkInTime = $('#checkInTime').value();
       var checkOutTime = $('#checkInTime').valeu();

get time value
       if(checkOutTime > checkInTime) {

checkOutTime must be later than checkInTime when it's the same date
           if(checkOutTime - checkInTime > 2) {

if duration is more than 2 than this value is ok
               alert('ok');

this fail 3rd if statement
           } else { alert('error must less than 2 ');  }

this fail 2nd if statement
       } else {alert('error checkout must bigger than checkin'); }

end 1st if statement that check for same date
}


text:
Q: AttributeError: module 'QuantLib' has no attribute 'date' I use Anaconda and jupyter notebook.
I installed Quantlib in an environment.
I run the following piece of code and get an AttributeError
import QuantLib as ql

calculation_date = ql.date(9,1,2008)
ql.Settings.instance().evaluationDate = calculation_date

The following error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-3ded7a4b7cb5> in <module>()
----> 1 calculation_date = ql.date(9,1,2004)
      2 ql.Settings.instance().evaluationDate = calculation_date

AttributeError: module 'QuantLib' has no attribute 'date'

How can I fix this problem?

A: I think it requieres caps? You should use Date instead of date
import QuantLib as ql
calculation_date = ql.Date(9,1,2008)
ql.Settings.instance().evaluationDate = calculation_date


text:
Q: Update d3 data element after chart is drawn I am working off of the d3 "Calendar View" example and would like to display 1 year at a time with some buttons to progress or regress the year being shown. In this example all of the data (years 1990-2010) arrive with the d3.csv call and is being rendered in a chart defined by...
var svg = d3.select("body")
  .selectAll("svg")
  .data(d3.range(1990, 2011))
  .enter().append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");

I would like to be able to update the data attribute on the d3 class and update the chart via a clickable event.
For example maybe showing the year 2010 is default like this...
var svg = d3.select("body")
  .selectAll("svg")
  .data(d3.range(2010, 2011))
  .enter().append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");

and i just want to modify the data element to d3.range(2009, 2010) on an event and redraw the chart.
I've tried removing and re-rendering the chart but haven't had success. There must be an easier way to do this.

A: In your code above you are only ever calling enter which is designed to add new elements to the DOM. There's a really good article from the author Mike Bostock called 3 Little Circles that explains how the enter/exit/update pattern works (note that it was for v3 though).
const join = d3
    .select("body")
    .selectAll("svg")
    .data(d3.range(2010, 2011), d => d);

First thing to note is that we've provided a key function to .data(). In this case the key is literally the value d which will return 2010 and 2011 for the two data points.
join.exit().remove();

Get rid of the old calendars!
join.enter()
    .append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")")
    .merge(join)
    ... do more stuff

The next importing bit you're missing is to update the existing stuff. You do that by taking your enter selection and calling merge(join). That gives you all the new and updated items so you can start changing attributes/styles or do further nested joins on.


text:
Q: How can I change java version on local linux server I built my NetBeans web project with Java 1.5 successfully, however; my linux server supports / uses Java 1.4 and Java 1.5 (as well as JBoss 4.0.2).
When I check the version of my project ( java -version ) it says that the current version is Java  1.4.2. However, I don't want to change the "JAVA_HOME" setting on the server because other projects need to use this version.
I want my project to use Java 1.5 from the server...
An idea as to how I should go about doing this? Is there a configuration that I can change?
I have this error:

java.lang.UnsoupportedClassVersionError:  bad Version in .class file

A: You need Java 1.5 version installed in your Linux server.
Next, run the following set of commands in your terminal/command prompt:

*

*JAVA_HOME="{fix-me}"

*export JAVA_HOME

*export PATH = $JAVA_HOME/bin:$PATH

In the place holder {fix-me} specify the path of Java 5 that is installed in the Linux machine.
This would only temporarily set the Java version to 5 until the terminal/command prompt session is alive. So you need not worry about disturbing other projects.


text:
Q: Google One Tap SignIn with cognito Google is Discontinuing Google Sign-In JavaScript Platform Library for web.
but Cognito is still using the old library.
so how can I implement One-tap sign-up with my react web app?

A: Cognito only needs to verify the ID Token (docs).
To my understanding, this is done using the Google Auth Library, which is not getting deprecated. The Google Sign-In JavaScript Library, which is being deprecated, is a different library.


text:
Q: How to count nested collection from database using Entity Framework I'm making my first Asp.net Mvc application - Forum System.
I'm trying to display how many posts and threads there are in sub category.
This are my tables:
public class Category
{
   private ICollection<SubCategory> subCategories;

   public Category()
   {
       this.subCategories = new HashSet<SubCategory>();
   }

   public int Id { get; set; }

   public string Name { get; set; }

   public virtual ICollection<SubCategory> SubCategories
   {
       get { return this.subCategories; }
       set { this.subCategories = value; }
   }
}

public class SubCategory
{
    private ICollection<Thread> threads;

    public SubCategory()
    {
        this.threads = new HashSet<Thread>();
    }

    public int Id { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public int CategoryId { get; set; }

    public virtual Category Category { get; set; }

    public virtual ICollection<Thread> Threads
    {
        get { return this.threads; }
        set { this.threads = value; }
    }
}

public class Thread
{
    private ICollection<Post> posts;

    public Thread()
    {
        this.posts = new HashSet<Post>();
    }

    public int Id { get; set; }

    public string Title { get; set; }

    public virtual SubCategory SubCategory { get; set; }

    public int SubCategoryId { get; set; }

    public virtual ICollection<Post> Posts
    {
        get { return this.posts; }
        set { this.posts = value; }
    }

    public string AuthorId { get; set; }

    public virtual ApplicationUser Author { get; set; }
}

public class Post
{
    public int Id { get; set; }

    public string Content { get; set; }

    public int ThreadId { get; set; }

    public virtual Thread Thread { get; set; }

    public string AuthorId { get; set; }

    public virtual ApplicationUser Author { get; set; }
}

this is my view:
    @model IEnumerable<ForumSystem.Web.ViewModels.Home.IndexCategoryViewModel>
@{
    ViewBag.Title = "Home Page";
}

    @foreach (var category in Model)
    {

@category.Name

            @foreach (var subCat in category.SubCategories)
            {

                        <h7>
                            @subCat.Title
                        </h7>

@subCat.Description

@category.ThreadsCount threads

@category.PostsCount posts

            }

    }

@category.ThreadsCount and PostsCount are not working.
I can get easy threads count in view with @subCategory.Threads.Count, but I can't get posts count.
In controller I have tried many things.
The code in the moment is :
public ActionResult Index()
    {
        var threadScount = this.Data
                           .SubCategories
                           .All()
                           .SelectMany(x => x.Threads)
                           .Count();

        var postsCount = this.Data
                        .Threads
                        .All()
                        .SelectMany(x => x.Posts)
                        .Count();

        var model = this.Data
                    .Categories
                    .All()
                    .Select(c => new IndexCategoryViewModel
                    {
                        Name = x.Name,
                        SubCategories = c.SubCategories,
                        ThreadsCount = threadScount,
                        PostsCount = postsCount,
                    })
                    .ToList();

        return this.View(model);
    }

But this gives me all threads and posts count, not specific for each subCategory.
Thanks in advance.

A: I believe what you're looking for is this:
var model = this.Data
    .Categories
    .Select(c => new IndexCategoryViewModel
    {
        Name = c.Name,
        SubCategories = c.SubCategories,
        ThreadsCount = c.Threads.Count(),
        PostsCount = c.Threads.Sum(t => t.Posts.Count()),
    })
    .ToList();

Here you create nested queries to count threads and posts for each category. You don't need the threadsCount and postsCount since they store overall counts and not per-category counts.
NOTE
I assume that Threads property exists on category class and Posts property exists on thread class. Otherwise you'll need to have predicates to associate posts with threads and threads with categories. Most commonly they would be ids, in which case the code would look similar to this:
var model = this.Data
    .Categories
    .Select(c => new IndexCategoryViewModel
    {
        Name = c.Name,
        SubCategories = c.SubCategories,
        ThreadsCount = this.Data
            .Threads
            .Count(t => t.CategoryId == c.Id),
        PostsCount = this.Data
            .Posts
            .Count(p => this.Data
                .Threads
                .Any(t => p.ThreadId == t.Id && t.CategoryId == c.Id)
            ),
    })
    .ToList();

Notice that I also skipped all .All() calls since they seem redundant, although I'm not sure what they do so you can throw it back in there if necessary.

A: Try this, also you will need to change the ViewModel to reflect requirements
public ActionResult Index()
{
    var model = from subCategory in this.Data.SubCategories
                select new SubCategoryViewModel
                {
                    Name = subCategory.Category.Name,
                    SubCategory = subCategory,
                    ThreadsCount = subCategory.Threads.Count(),
                    PostsCount = subCategory.Threads.SelectMany(c => c.Posts).Count(),
                })
                .ToList();

    return this.View(model);
}

A: Create view models that represent what you want to display
public class SubCategoryVM
{
  public string Title { get; set; }
  public string Description { get; set; }
  public int ThreadsCount { get; set; }
  public int PostCount { get; set; }
}

public class CategoryVM
{
  public string Name { get; set; }
  public List<SubCategoryVM> SubCategories { get; set; }
}

Controller
public ActionResult Index()
{
  var model = this.Data.Categories.Select(c => new CategoryVM
  {
    Name = c.Name,
    SubCategories = c.SubCategories.Select(s => new SubCategoryVM
    {
      Title = s.Title,
      Description = s.Description,
      ThreadsCount = s.Threads.Count,
      PostsCount = s.Threads.SelectMany(t => t.Posts).Count;
    })
  });
  return View(model);
}

View
@model IEnumerable<CategoryVM>
@{
  ViewBag.Title = "Home Page";
}

  @foreach (var category in Model)
  {

@category.Name

      @foreach (var subCategory in category.SubCategories)
      {

            <h7>
              // The following line in your view makes no sense
              // @subCat.Title
              // Assuming you have method: public ActionResult Details(string title) in SubCategoryController, then
              @Html.ActionLink(subCategory.Title, "Details", "SubCategory", new { title = subCategory.Title }, null)
            </h7>

@subCategory.Description

@subCategory.ThreadCountthreads

@subCategory.PostCountposts

      }

  }


text:
Q: Google Drive API not displaying thumbnail I have an app that uses the Google Drive API, and I need to display the thumbnails. But when I pass the link to an <img> tag it responds with a 404, but if I open the link manually in another tab in my browser it display just fine

A: *

*You want to put the thumbnail of the file retrieved from Google Drive to your HTML.

*

*The thumbnail link is retrieved by Drive API.

*When you put it and open the HTML, 404 is returned. But when you directly access to the URL of the thumbnail link, you can see the image on your browser.

I believe your goal and your issue like above. For this, how about this answer?
Issue and workaround:
From your situation, I think that when you directly access to the thumbnail link, you might have logged in Google Account. By this, the image can be seen. And also, I thought that you might have used the following thumbnail link. This is the thumbnail link retrieved by Drive API.
https://docs.google.com/feeds/vt?gd=true&id={fileId}&v=1&s=###&sz=s220

Unfortunately, it seems that this link cannot be directly used at the HTML of outside. So in order to use the thumbnail at the HTML of outside, how about changing the endpoint?
Modified endpoint:
https://drive.google.com/thumbnail?sz=w640&id={fileId}

*

*Please replace {fileId} of your file ID.

*w640 means 640 pixels in the width. If you want to change the height, please useh instead of w.

*Please share publicly the file you want to retrieve the thumbnail. It's On - Anyone with the link. By this, above link can be used. Please be careful this.
Note:

*

*When the following HTML is used with the above link, the thumbnail can be seen.
<img src="https://drive.google.com/thumbnail?sz=w640&id={fileId}">


text:
Q: Try...Catch block which handles the triggered error for excel data that is not in the right format when imported So I have a code-block that currently checks to see whether an excel file is present at a given location and if present, imports its contents into a list-box. If absent, it triggers an error message. I'm using the Try...catch code block to execute this.
I want to trigger an error message when the data to be imported is not in the appropriate format. The code block is below. Any help will be deeply appreciated.
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles butImport.Click
     Dim MyFileDialog As New System.Windows.Forms.OpenFileDialog

    ' Configure the dialog to show both text and excel files
    ' Set its title and set the filename field blank for the moment.
    MyFileDialog.Filter = "(*.xlsx)|*.xlsx"
    MyFileDialog.Title = " Open an excel file"
    MyFileDialog.FileName = ""
    ' Show the dialog and see if the user pressed ok.

    If MyFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
        ' Check to see if they selected a file and that it exists.

        If File.Exists(MyFileDialog.FileName) Then

            Dim strFile As String = MyFileDialog.FileName
            Dim textextension As String
            Dim testFile As System.IO.FileInfo
            Try
                ' Setup a file stream reader to read the text file.

                textextension = Path.GetExtension(strFile)
                If textextension = ".xlsx" Then
                    Dim oExcel As Object = CreateObject("Excel.Application")
                    Dim oBook As Object = oExcel.Workbooks.Open(strFile)
                    Dim oSheet As Object = oBook.Worksheets(1)
                    Dim i As Integer
                    Dim cellA As String
                    Dim cellB As String
                    Dim cellC As String
                    Dim cellD As String
                    Dim cellE As String
                    lstGradeLength.Items.Add("Grade (in Radians)" & vbTab & "   Length (in Miles)" & vbTab & vbTab & "Radius (in Feet)" & vbTab & vbTab & "Super-elevation (in Decimal)" & vbTab & vbTab & "Angle (in Degrees)")
                    For i = 0 To AscW(lstGradeLength.Items.Count.ToString()(i = i + 1)) - 1

                        cellA = "A" & Convert.ToString(i + 1)
                        cellB = "B" & Convert.ToString(i + 1)
                        cellC = "C" & Convert.ToString(i + 1)
                        cellD = "D" & Convert.ToString(i + 1)
                        cellE = "E" & Convert.ToString(i + 1)
                        cellA = oSheet.Range(cellA).Value
                        cellB = oSheet.Range(cellB).Value
                        cellC = oSheet.Range(cellC).Value
                        cellD = oSheet.Range(cellD).Value
                        cellE = oSheet.Range(cellE).Value
                        If cellA = "" And cellB = "" And cellC = "" And cellD = "" And cellE = "" Then
                            Exit For
                        Else
                            RichTextBox1.AppendText(cellA & " " & cellB & " " & cellC & " " & cellD & " " & cellE & vbCrLf)

                        End If
                    Next
                    oExcel.Quit()
                    Dim m As Integer
                    For m = 1 To CInt(UBound(RichTextBox1.Lines))
                        ReDim Preserve Grade(m)
                        ReDim Preserve Length(m)
                        ReDim Preserve Radius(m)
                        ReDim Preserve Superelevation(m)
                        ReDim Preserve Angle(m)
                        Grade(m) = RichTextBox1.Lines(m - 1).Split(" ").First
                        Length(m) = RichTextBox1.Lines(m - 1).Split(" "c)(1)
                        Radius(m) = RichTextBox1.Lines(m - 1).Split(" "c)(2)
                        Superelevation(m) = RichTextBox1.Lines(m - 1).Split(" ")(3)
                        Angle(m) = RichTextBox1.Lines(m - 1).Split(" ")(4)
                        lstGradeLength.Items.Add(Grade(m) & vbTab & vbTab & vbTab & Length(m) & vbTab & vbTab & vbTab & Radius(m) & vbTab & vbTab & vbTab & Superelevation(m) & vbTab & vbTab & vbTab & Angle(m) & vbCrLf)
                        butGradeLength.Enabled = False
                    Next
                    testFile = My.Computer.FileSystem.GetFileInfo(strFile)

                    lblPath.Text = testFile.FullName

                    txtNumSections.Text = lstGradeLength.Items.Count - 1
                End If

            Catch ex As FileNotFoundException

                ' If the file was not found, tell the user.

                MessageBox.Show("File was Not found. Please try again.")

            End Try

        End If
    Else
        txtNumSections.Text = ""
        butImport.Enabled = True
        butGradeLength.Enabled = True
        butClear.Enabled = True
        Exit Sub
    End If

    butImport.Enabled = False
    butCompute.Enabled = True
End Sub

A: Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles butImport.Click
    Dim MyFileDialog As New System.Windows.Forms.OpenFileDialog

    ' Configure the dialog to show only excel files
    ' Set its title and set the filename field blank for the moment.
    MyFileDialog.Filter = "(*.xlsx)|*.xlsx"
    MyFileDialog.Title = " Open an excel file"
    MyFileDialog.FileName = ""
    ' Show the dialog and see if the user pressed ok.

    If MyFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
        ' Check to see if they selected a file and that it exists.

        If File.Exists(MyFileDialog.FileName) Then

            Dim strFile As String = MyFileDialog.FileName
            Dim textextension As String
            Dim testFile As System.IO.FileInfo
            Try
                'Setup a file stream reader to read the excel file.
                textextension = Path.GetExtension(strFile)
                If textextension = ".xlsx" Then
                    Dim oExcel As Object = CreateObject("Excel.Application")
                    Dim oBook As Object = oExcel.Workbooks.Open(strFile)
                    Dim oSheet As Object = oBook.Worksheets(1)
                    Dim i As Integer
                    Dim cellA As String
                    Dim cellB As String
                    Dim cellC As String
                    Dim cellD As String
                    Dim cellE As String
                    lstGradeLength.Items.Add("Grade (in Radians)" & vbTab & "   Length (in Miles)" & vbTab & vbTab & "Radius (in Feet)" & vbTab & vbTab & "Super-elevation (in Decimal)" & vbTab & vbTab & "Angle (in Degrees)")
                    For i = 0 To AscW(lstGradeLength.Items.Count.ToString()(i = i + 1)) - 1

                        cellA = "A" & Convert.ToString(i + 1)
                        cellB = "B" & Convert.ToString(i + 1)
                        cellC = "C" & Convert.ToString(i + 1)
                        cellD = "D" & Convert.ToString(i + 1)
                        cellE = "E" & Convert.ToString(i + 1)
                        cellA = oSheet.Range(cellA).Value
                        cellB = oSheet.Range(cellB).Value
                        cellC = oSheet.Range(cellC).Value
                        cellD = oSheet.Range(cellD).Value
                        cellE = oSheet.Range(cellE).Value
                        If cellA = "" And cellB = "" And cellC = "" And cellD = "" And cellE = "" Then
                            Exit For
                        Else
                            RichTextBox1.AppendText(cellA & " " & cellB & " " & cellC & " " & cellD & " " & cellE & vbCrLf)

                        End If
                    Next
                    oExcel.Quit()
                End If
            Catch ex As FileNotFoundException

                ' If the file was not found, tell the user.

                MessageBox.Show("File was not found. Please try again.")

            End Try

            Try
                'Setup a file stream reader to read the excel file.
                textextension = Path.GetExtension(strFile)
                If textextension = ".xlsx" Then

                    Dim m As Integer
                    For m = 1 To CInt(UBound(RichTextBox1.Lines))
                        ReDim Preserve Grade(m)
                        ReDim Preserve Length(m)
                        ReDim Preserve Radius(m)
                        ReDim Preserve Superelevation(m)
                        ReDim Preserve Angle(m)
                        Grade(m) = RichTextBox1.Lines(m - 1).Split(" ").First
                        Length(m) = RichTextBox1.Lines(m - 1).Split(" "c)(1)
                        Radius(m) = RichTextBox1.Lines(m - 1).Split(" "c)(2)
                        Superelevation(m) = RichTextBox1.Lines(m - 1).Split(" ")(3)
                        Angle(m) = RichTextBox1.Lines(m - 1).Split(" ")(4)
                        lstGradeLength.Items.Add(Grade(m) & vbTab & vbTab & vbTab & Length(m) & vbTab & vbTab & vbTab & Radius(m) & vbTab & vbTab & vbTab & Superelevation(m) & vbTab & vbTab & vbTab & Angle(m) & vbCrLf)
                        butGradeLength.Enabled = False
                    Next
                    testFile = My.Computer.FileSystem.GetFileInfo(strFile)

                    lblPath.Text = testFile.FullName

                    txtNumSections.Text = lstGradeLength.Items.Count - 1
                End If
            Catch ex As Exception
                ' If the data is in an incorrect format, tell the user.

                MessageBox.Show("Data is in incorrect format")
            End Try
            lstGradeLength.Items.Clear()
        End If
    Else
        txtNumSections.Text = ""
        butImport.Enabled = True
        butGradeLength.Enabled = True
        butClear.Enabled = True
        Exit Sub
    End If

    butImport.Enabled = False
    butCompute.Enabled = True
End Sub

A: While it is good to have at least one generic exception handler, I don't see the point of catching FileNotFoundException since you are testing the file existence with If File.Exists(MyFileDialog.FileName) Then just before. Of course plenty of bad things can happen during program execution but I don't think there is any reason to handle this exception in particular since it is unlikely to happen.
And in fact if this condition is not met: If File.Exists(MyFileDialog.FileName) Then then your program does not even alert the user, it just resets a few UI controls. A simplified view of your block is like this:
If MyFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
    ' Check to see if they selected a file and that it exists.

    If File.Exists(MyFileDialog.FileName) Then
        ...
    End If
Else
    txtNumSections.Text = ""
    butImport.Enabled = True
    butGradeLength.Enabled = True
    butClear.Enabled = True
    Exit Sub
End If

I am not sure this is what you want. If you let the user pick a file, but they play games by removing or renaming the file maybe you should alert them, not just ignore this little problem. At least the program is not going to crash on this exception but it is still an unexpected condition.


text:
Q: Classification of subalgebras of composition algebras Let $F$ be an algebraically closed field. It is known that the only composition algebras over $F$ are $F$ itself, the direct sum $F\oplus F$ (also called split-complexes), the algebra of $2\times 2$ matrices (or split-quaternions) $M_2(F)$, and Zorn's vector-matrix algebra (or split-octonions) $Zo(F)$. The elements of these four algebras admit a respective description in terms of $2\times 2$ matrices or generalized versions of such, namely:
$$\begin{pmatrix} a & 0 \\ 0 & a\end{pmatrix}, \begin{pmatrix} a & 0 \\ 0 & b\end{pmatrix}, \begin{pmatrix} a & b \\ c & d\end{pmatrix}, \begin{pmatrix} a & (b,c,d) \\ (e,f,g) & h\end{pmatrix},$$
where $a,b,\ldots,h$ are arbitrary elements of $F$, and in the last case we use the modified matrix multiplication described in this article, which is nonassociative.
All four algebras are clearly subalgebras of the biggest one $Zo(F)$, if we identify any $x$ in the upper-right and lower-left corners with the vector $(x,0,0)$. There exist other subalgebras (necessarily not composition), namely the dual numbers $F[\varepsilon]$ where $\varepsilon^2=0$, the upper triangular $2\times 2$ matrices $B_2(F)$ (apparently also called ternions), and the sextonions $Se(F)$. A matrix representation for these subalgebras is respectively
$$\begin{pmatrix} a & b \\ 0 & a\end{pmatrix}, \begin{pmatrix} a & b \\ 0 & c\end{pmatrix}, \begin{pmatrix} a & (b,c,0) \\ (d,0,e) & f\end{pmatrix}$$
(for the last one see here). There is yet another subalgebra that I found by trial and error, that I guess we could call the "quintonions" $Qui(F)$. A matrix representation is
$$\begin{pmatrix} a & (b,0,0) \\ (0,c,d) & e\end{pmatrix}.$$
My question is

Is this list exhaustive? Do there exist any other subalgebras of composition algebras (unital, properly containing $F$ as a subalgebra) not isomorphic to the ones already described ($F$, $F[\varepsilon]$, $F\oplus F$, $B_2(F)$, $M_2(F)$, $Qui(F)$, $Se(F)$, $Zo(F)$)?

(By the way, have these quintonions been described anywhere in the literature?)

A: I finally found an answer online, I'll post it here in case someone finds it of value. The classification above is incomplete: there exist three more subalgebras of $Zo(F)$. I had missed them because I foolishly thought that all subalgebras of the same dimension were isomorphic.
Subalgebras of the split-octonions over $\mathbb{R}$ were classified two years ago in this paper. We can get the corresponding classification over its algebraic closure $\mathbb{C}$ by tensoring with it (thus identifying some of the algebras).
Discarding the completely nilpotent ones (since they don't properly contain the base field as required), and if I didn't make any mistake, we recover all algebras described in the question, plus three more. The new ones are (note that although the paper originally deals with $\mathbb{R}$, the following constructions are valid over any field):

*

*The three-dimensional "bidual numbers" $F[\varepsilon, \varepsilon']$ with two orthogonal nilpotents $\varepsilon^2 = \varepsilon'^2 = \varepsilon\varepsilon'=0$.

*The four-dimensional Grassmann algebra $\Lambda(F^2)$.

*The "biduals" over $F\oplus F$, i.e. $(F\oplus F)[\varepsilon, \varepsilon']$, another four-dimensional algebra.
A matrix representation is given by
$$\begin{pmatrix} a & (b,0,0) \\ (0,c,0) & a\end{pmatrix}, \begin{pmatrix} a & (b,0,0) \\ (0,c,d) & a\end{pmatrix}, \begin{pmatrix} a & (b,0,0) \\ (0,c,0) & d\end{pmatrix}$$
respectively. Interestingly, none of them can be embedded in $M_2(F)$ despite being associative.


text:
Q: How to find intersecting features from inside a drawn polygon I have drawn a polygon and I want to get all the intersecting features. But here I got stuck and not able to proceed.When I run the code it allows me to draw the polygon in the map. But I am not very sure how to get all the intersecting features from that geometry.
Can you please help me. Here is what I did.
IMxApplication pMxApp = null;
IActiveView activeView = default(IActiveView);

pMxApp = (IMxApplication)m_application;

IMxDocument m_MxDoc = (IMxDocument)m_application.Document;
activeView = (IActiveView)(Map)m_MxDoc.FocusMap;

IMap pMap = default(IMap);
ISpatialReference pSpatialRef = default(ISpatialReference);

pMap = m_MxDoc.FocusMap;
pSpatialRef = pMap.SpatialReference;

IScreenDisplay m_pDisplay = activeView.ScreenDisplay;

ESRI.ArcGIS.Display.IScreenDisplay screenDisplay = activeView.ScreenDisplay;

screenDisplay.StartDrawing(screenDisplay.hDC, (System.Int16)
ESRI.ArcGIS.Display.esriScreenCache.esriNoScreenCache); // Explicit Cast
ESRI.ArcGIS.Display.IRgbColor rgbColor = new
ESRI.ArcGIS.Display.RgbColorClass();
rgbColor.Transparency = 000;

ESRI.ArcGIS.Display.IColor color = rgbColor; // Implicit cast.
ESRI.ArcGIS.Display.ISimpleFillSymbol simpleFillSymbol = new
ESRI.ArcGIS.Display.SimpleFillSymbolClass();
simpleFillSymbol.Color = color;

ESRI.ArcGIS.Display.ISymbol symbol = simpleFillSymbol as
ESRI.ArcGIS.Display.ISymbol; // Dynamic cast.
ESRI.ArcGIS.Display.IRubberBand rubberBand = new
ESRI.ArcGIS.Display.RubberPolygonClass();
ESRI.ArcGIS.Geometry.IGeometry geometry = rubberBand.TrackNew(screenDisplay,
symbol);
screenDisplay.SetSymbol(symbol);
screenDisplay.DrawPolygon(geometry);

m_pDisplay.FinishDrawing();
geometry.SnapToSpatialReference();

ISpatialFilter spatialFilter = new SpatialFilter();
spatialFilter.Geometry = geometry;
spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

IElement element = new PolygonElementClass();
element.Geometry = geometry;


text:
Q: How do I validate a form being filled out in Backbone? So I have a new form set up it saves temporarily and all but I want it to only be able to update when it is validated otherwise show some errors. This is during the view section for the saveEdits event Any clue as to what I am doing wrong?
This is my main.js file
(function () {
    window.App = {
        Models: {},
        Collections: {},
        Views: {},
        Templates: {},
        Router: {}

    };

    // MODEL
    App.Models.User = Backbone.Model.extend({
        defaults: {
            firstName: 'first',
            lastName: 'last',
            email: 'Email',
            phone: '222',
            birthday: '07/22/1980'
       },

        validate: function (attrs) {

            if (!attrs.firstName) {
                return 'You must enter a real first name.';
            }
            if (!attrs.lastName) {
                return 'You must enter a real last name.';
            }
            if (attrs.email.length < 5) {
                return 'You must enter a real email.';
            }
            if (attrs.phone.length < 10 && attrs.phone === int) {
                return 'You must enter a real phone number, if you did please remove the dash and spaces.';
            }
            if (attrs.city.length < 2) {
                return 'You must enter a real city.';
            }
        },

        initialize: function() {
             this.on('invalid', function (model, invalid) {
                console.log(invalid);
            });
        }

    });

    //var userModel = new App.Models.User();

    //VIEW
    App.Views.User = Backbone.View.extend({
        el: '#user',
        //model: userModel,
        //tagName: 'div',
        //id: 'user',
        //className: 'userProfile',
        //template: _.template($("#userTemplate").html()),
        //editTemplate: _.template($("#userEditTemplate").html()),

        initialize: function (){

        },

        render: function() {
            this.template = Handlebars.compile($("#userTemplate").html());
            this.editTemplate = Handlebars.compile($("#userEditTemplate").html());

            this.$el.html(this.template(this.model.toJSON()));
            return this;
        },

        events: {
            'click button.edit': 'editProfile',
            'click button.save': 'saveEdits',
            'click button.cancel': 'cancelEdits'
        },

        editProfile: function () {
            this.$el.html(this.editTemplate(this.model.toJSON()));

        },

        saveEdits: function () {
            var form = $(this.el).find('form#updateUser');
            this.model.set({

                firstName : form.find('.firstName').val(),
                lastName : form.find('.lastName').val(),
                email: form.find('.email').val(),
                phone: form.find('.phone').val(),
                birthday: form.find('.birthday').val()

            });

            this.model.validate();

            this.render();

        },

        cancelEdits: function() {
            this.render();
        }

    });
    //start history service
    Backbone.history.start();

    var user = new App.Views.User({model: new App.Models.User()});
    user.render();
})();

It works fine until I insert the this.model.validate and an error shows up stating this:
Uncaught TypeError: Cannot read property 'firstName' of undefined

A: You don't call validate explicitly -- it's meant called by the Backbone framework:

By default validate is called before save, but can also be called before set if {validate:true} is passed.

So to fix the code in the OP, use validate: true in the call to set:
this.model.set({
    firstName : form.find('.firstName').val(),
    // ...
}, { validate: true });

Note that, if you wanted to call validate, then you have to pass it the attrs parameter, as in this.model.validate(this.model.toJSON());


text:
Q: Интерполяция выражений Начал изучать JS.
Почему не работают выражения в строке htmlCode?

function generateColor() {
 return "#" + Math.floor(Math.random() * 16777215).toString(16);
}

function circle() {
 var r = Math.random() * 100 + 50,
      d = r * 2,
      color = generateColor(),
      htmlCode = '

';
  document.write(htmlCode);
}
circle();

A: Замените ' на `:

function generateColor() {
 return "#" + Math.floor(Math.random() * 16777215).toString(16);
}

function circle() {
 var r = Math.random() * 100 + 50,
      d = r * 2,
      color = generateColor(),
      htmlCode = `<div style="width: ${d}px; height: ${d}px; background-color: ${color}; border-radius: 50%;"></div>`;
  document.write(htmlCode);
}
circle();


text:
Q: In PDF, font-face appears to be loading from URL, but is not displayed My Django app uses WeasyPrint to generate PDFs on demand. I am using WeasyPrint 52.4 and Django 3.2.
I have been using system fonts, which has been working great. Now I'm trying to use local fonts. For now, I'm loading static assets through localhost, pointing to Django's static server, so I can watch the requests come in and make sure the right things are being loaded.
Here is how WeasyPrint is being called:
font_config = weasyprint.fonts.FontConfiguration()
css = weasyprint.CSS(url='http://localhost:8000/static/kits/static/report.css', font_config=font_config)
return weasyprint.HTML(
    string='
Hello world
',
    encoding='utf-8',
).write_pdf(
    stylesheets=[css],
    font_config=font_config,
)

Here is my CSS:
@font-face {
  font-family: 'foobar';
  src: url(http://localhost:8000/static/Oxygen-Regular.ttf) format('truetype');
  font-weight: 400;
}

@font-face {
  font-family: 'foobar';
  src: url(http://localhost:8000/static/Oxygen-Bold.ttf) format('truetype');
  font-weight: 700;
}

:root {
  font-family: 'foobar', sans-serif;
  color: red;
}

The text is correctly colored red, so I know the CSS is being loaded. I can see from my server logs that the requests for the fonts are successful, which indicates to me that WeasyPrint is fetching the fonts correctly:
2021-04-07 09:57:32,147 INFO    "GET /static/mycss.css HTTP/1.1" 200 5748
2021-04-07 09:57:32,193 INFO    "GET /static/Oxygen-Regular.ttf HTTP/1.1" 200 46440
2021-04-07 09:57:32,200 INFO    "GET /static/Oxygen-Bold.ttf HTTP/1.1" 200 47096

But the PDF is showing the fallback sans-serif font. What am I missing?


text:
Q: How to compare two columns instead of values using medoo framework I want to compare two columns of medoo rather its values.
$issues = $database->select("issues","*",[
       "AND" => [
           "projectid" => 1,
           "estimated_hrs[<]" => "timespent"
       ]
    ]);

But getting an error while doing so.Is there any solution??

A: Check out columns relationship here: https://medoo.in/api/where
$database->select("post", [
        "[>]account" => ["author_id" => "user_id"],
    ], [
        "post.id",
        "post.content"
    ], [
        "AND" => [
            // Connect two column with condition sign like [=], [>], [<], [!=] as one of array value
            "post.restrict[<]account.age",

            "account.user_name" => "foo",
            "account.email" => "foo@bar.com",
        ]
    ]
);

// WHERE "post"."restrict" < "account"."age" AND "account"."user_name" = 'foo' AND "account"."email" = 'foo@bar.com'


text:
Q: Como utilizar múltiplas condições dentro de um if Já tentei de várias maneiras, agrupando com () de todas as formas que imaginei, criando uma variável e chamando ela na condição etc, mas consigo encontrar onde estou errando.
$(function() {
    $('#id1').change(function(){
       if (($(this).val() == '3' || '4') && ('id2' == '5')) {
       $('#div1').fadeIn('slow');
       $('#div2').hide();
        }
       else if ($(this).val() == '6' || '7') {
           $('#div1').hide()
       }
        else {
           $('#div2').hide();
           $('#div1').hide();
        }
    });
});

Já tentei assim também:
var tip = document.getElementById("#id2").val;
       if (($(this).val() == '3' || '4') && (tip == '5'))

E agrupando diferente:
if ($(this).val() == '3' || '4' && 'id2' == '5')

Ou
if (($(this).val() == '3' || '4') && 'id2' == '5')

Segue um https://jsfiddle.net/gustavox/6e7yo7y2/2/ com o exemplo.

A: Os operadores lógicos avaliam os booleanos retornados nos predicados, eles devem devem ser usados entre duas expressões (as quais resultam um booleano), ou booleanos propriamente ditos (true ou false)
Você está errando nessa condição:
($(this).val() == '3' || '4')

ela deve ficar da seguinte forma:
($(this).val() == '3' || $(this).val() == '4')

Segue a correção de seu fiddle : https://jsfiddle.net/7t9u4yeq/
Observações sobre o seu fiddle:
1º erro
A linha var tip = document.getElementById("#id2").val; está errada, pois para se recuperar o valor de um select list usando javascript deve-se retornar o valor da opção selecionada, então no caso ficaria:
var tip = document.getElementById("id2").options[e.selectedIndex].value

ou usando-se jquery
var tip = $("#id2").val();

2º erro
As condições como já falado nessa reposta
3º erro
O evento deve ser capturado quando qualquer um dos dois dropdowns for modificado, entao deve ser adicionado mais um seletor ao evento
$('#id1, #id2').change(function(){}

Como agora o evento pode ser chamado em qualquer um dos dropdowns devemos mudar na condição aonde usamos $(this).val(), para $('id1').val()


text:
Q: How replace contex-param values in web.xml with maven? I want to create one maven profile that will search web.xml in all project that will used it and replace necessary values in web.xml. I do not want to insert maven properties in web.xml, but just create one profile for all projects that contains web.xml. For example I want replace javax.faces.PROJECT_STAGE value:
<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Production</param-value>
</context-param>

to
<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>

I want to create one profile that will search web.xml and do necessary replaces, but without modification original web.xml to:
<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>${maven.property}</param-value>
</context-param>

Is that possible with maven?

A: It would be better use maven itself
https://community.jboss.org/wiki/HowToConfigureJavaEEApplicationToApplyDifferentSettingsinWebxmlEtcForVariousEnvironmentsByMaven


text:
Q: How do I use more than one OpenID? I have more than one OpenID as I have tried out numerous.  As people take up OpenID different suppliers are going to emerge I may want to switch provinders.  As all IDs are me, and all are authenticated against the same email address, shouldn't I be able to log into stack overflow with any of them and be able to hit the same account?

A: In addition to the meta tag sample by Otto, you should be aware whether your provider supports OpenID 2.0 (there are numerous improvements). If it does use meta tags as the following:
<link rel="openid2.provider" href="http://www.loginbuzz.com/provider.axd" />
<link rel="openid2.local_id" href="http://example.loginbuzz.com/" />
<link rel="openid.server" href="http://www.loginbuzz.com/provider.axd" />
<link rel="openid.delegate" href="http://example.loginbuzz.com/" />

A good idea would also be to use secure links, but this could limit some relying parties from signing in. This could however be solved by providing a XRDS document.
The really neat thing about XRDS is that you are able to specify multiple providers in this document. Say you have a bunch of different accounts all with different providers supporting different extensions. The relying party are then able to select the best match by itself.
In the XRDS document you could also specify multiple URLs for each service, so that https is used when appropriate.
I would also recommend buying an i-name as it by design is more secure (the canonical ID - the i-number - associated with an i-name belongs to you even if the i-name expires).

A:
@prakesh
As long as you associate all of them
  to the same email address, i would
  think it would lead you to same
  account.
But whats your experience?

When I tried it out I got a whole new account with 0 rep and no steenkin badges. So at the moment SO does not allow multiple OpenID's to be associated with the one account

A: I think each site that implements OpenID would have to build their software to allow multiple entries for your OpenID credentials.  However, just because a site doesn't allow you to create multiple entries doesn't mean you can't swap out OpenID suppliers.
How to turn your blog into an OpenID
STEP 1: Get an OpenID. There a lots of servers and services out there you can use. I use http://www.myopenid.com
STEP 2: Add these two lines to your blog's main template in-between the <HEAD></HEAD> tags at the top of your template. Most all blog engines support editing your template so this should be an easy and very possible thing to do.
Example:

<link rel="openid.server" href="http://www.myopenid.com/server" />
<link rel="openid.delegate" href=http://YOURUSERNAME.myopenid.com/ />

This will let you use your domain/blog  as your OpenID.
Credits to Scott Hanselman and Simon Willison for these simple instructions.
Switch Your Supplier
Now that your OpenID points to your blog, you can update your link rel href's to point to a new supplier and all the places that you've tied your blog's OpenID will use the new supplier.

A:
Doesn't using multiple open-id providers sort of undermine the point of open id?

No. Say you are using a Yahoo OpenID, but you decide to move to Google instead. Multiple OpenIDs per account allows you to associate your account with the Google OpenID, then deauthorize the Yahoo OpenID.

A: Doesn't using multiple open-id providers sort of undermine the point of open id?

A: The key here is to not change identities, ever.
Change providers, but not identities. (this is like real life)
So new users to OpenID should first consider what their identity could be.
Users that already have some kind of website they own should choose this URL and users without a website have these options:

*

*Get something like a blog to get a URL

*Buy an i-name (or a domain name)

*or use an identity provider supplied URL

In the case of the identity provider supplied URL, users need to be aware that if in the future they choose to delegate or change identities in some way that its essentially a new identity and that multiple identity support with RPs (and OPs) is limited (required usually to re-associate a local account on an RP site to a different OpenID identity).


text:
Q: pass Var from one javascript class to another I have a controller and a view class.In my controller class I have this code. I am trying to get the AccNo which is passed in the url. I know this code works fine for retrieving the account number, but I now need to pass the Var in to the view class.
    getURLParameter : function(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
    },

    // Parse URL parameters
    parseAndSetURLParameters : function(){

        var accNo    = this.getURLParameter('accNo');

    },

A: First of all you might want to have a look at jQuery.sap.getUriParameters.
To make variables available to a view the easiest and most convenient way is to use a JSONModel like this:
parseAndSetURLParameters: function() {
  var oModel = new sap.ui.model.json.JSONModel({
    accNo: jQuery.sap.getUriParameters().get("accNo");
  });
  this.getView().setModel(oModel, "view");
}

and in your XMLView:
<Text text="{view>/accNo}" />

Or even more generically you could just pump all uri-parameters in a JSONModel and set it right on your Component (be aware that I use internal api ('mParams') here):
new sap.ui.model.json.JSONModel(jQuery.sap.getUriParameters().mParams);

BR
Chris


text:
Q: Query with two dates in mongoose and return documents that match? I have a mongoose collection who's schema looks like this:
"date_from": {type: Date, required: true},
"date_to": {type: Date, required: true},
"num_guests": {type: Number, required: true},
"children": {type: Number, required: true},

Now I have to search for documents that are between the range of "date_from" to "date_to" based on the dates I provide.
Now, I figured out this bit of code which does most of what I need.
 model.find({_id: req.body._id,
                $and:[{date_from: {$gte: "2020-04-26T06:50:45.079+00:00",$lte: "2020-05-01T06:50:45.079+00:00"}},
{date_to: {$lte: "2020-05-01T06:50:45.079+00:00"}}]
            })

but I ran into a problem with this code when: In my collection there is a document which has "date_from": "2020-04-04" to "date_to":"2020-04-08". Now when I query with $gte: "2020-04-03" and $lte: "2020-04-09", I get the document but when I change it to $gte: "2020-04-05" and $lte: "2020-04-09", I receive an empty array. But I still need to get that document because technically it is still within $gte: "2020-04-05" and $lte: "2020-04-09". How would I do that?
This scenario can be best explained by:
I have a hotel room booked for 12-04-2020 to 24-04-2020 now if someone looks up all bookings between 16-04-2020 to 20-04-2020 then they should see the booking that has been made between 12 to 24.
I looked through the other related questions to find an answer but I did not find anything much.


text:
Q: How to add a Button in the SpreadsheetView table How can I create a object(Button,Checkbox) in my table?
    GridBase grid = new GridBase(20, 20);

    ObservableList<ObservableList<SpreadsheetCell>> rows = FXCollections.observableArrayList();
    for (int row = 0; row < grid.getRowCount(); ++row) {
        final ObservableList<SpreadsheetCell> list = FXCollections.observableArrayList();
        for (int column = 0; column < grid.getColumnCount(); ++column) {
            list.add(new ObjectType().createCell(row, column, 1, 1, new Button("CLICK")));
        }
        rows.add(list);
    }
    grid.setRows(rows);
    SpreadsheetView spv = new SpreadsheetView(grid);

Output in the table:
Button@79280814[styleClass=button]'CLICK'
Button@3ad2325d[styleClass=button]'CLICK'

A: I think i have found it :)
1-)
 SpreadsheetCellBase cell = new SpreadsheetCellBase(row, column, 1, 1);

                        cell.setGraphic(new Button("Test Button"));

                        list.add(cell)

2-)
SpreadsheetCell cellIndex = SpreadsheetCellType.STRING.createCell(row, column, 1, 1,null);

                    cellIndex.setGraphic(new Button("Test Button"));

                    cells.add(cellIndex);


text:
Q: What is the required format for an Ajax GET response? I am having a major problem trying to add an element to a response stream sent by an Arduino application in reply to an AJAX request. I have a message getting through successfully, but when I add an extra component to it, the message is not read. By monitoring the Ethernet traffic with Wireshark, I have determined that the additional element is not being completely terminated.
The code I am using is:
void SendTags(EthernetClient cl) {
  String value;      // stores value read from analog onputs
  int count;         // index for 'for' loops
  int str_length;
  char msg_chrs[0];

  Serial.println("Debug 395 - sending title and tags");
  cl.write("<?xml version = \"1.0\" ?>\r\n");

  Str = "<app_data>\r\n";
  str_length = Str.length()+1;
  Str.toCharArray(msg_chrs, str_length);
  cl.write(msg_chrs);

  Str = "<tags>\r\n";
  str_length = Str.length()+1;
  Str.toCharArray(msg_chrs, str_length);
  cl.write(msg_chrs);

  for (count = 0; count < di_count; count++) {
    value = di_sig_tag[count];
    Str = "<DI_TAG>" + value + "</DI_TAG>\r\n";
    str_length = Str.length()+1;
    Str.toCharArray(msg_chrs, str_length);
    cl.write(msg_chrs);
 }

 //(similar code sections omitted for simplicity)

  Str = "</tags>\r\n";
  str_length = Str.length()+1;
  Str.toCharArray(msg_chrs, str_length);
  cl.write(msg_chrs);

//  Str = "<title>\r\n";
//  str_length = Str.length()+1;
//  Str.toCharArray(msg_chrs, str_length);
//  cl.write(msg_chrs);

//  Str = "<pr_name>" + pr_name + "</pr_name>\r\n";
//  str_length = Str.length()+1;
//  Str.toCharArray(msg_chrs, str_length);
//  cl.write(msg_chrs);

//  Str = "</title>\r\n";
//  str_length = Str.length()+1;
//  Str.toCharArray(msg_chrs, str_length);
//  cl.write(msg_chrs);

  Str = "</app_data>\r\n";
  str_length = Str.length()+1;
  Str.toCharArray(msg_chrs, str_length);
  cl.write(msg_chrs);

  Serial.println("Debug 462 - End of SendTags()");
}

In Wireshark, the elements being transmitted successfully are displayed using the HTTP protocol and are structured with one element per package, each package terminating in "\r\n" as expected.:

If I enable the suspect code, the HTML header is:

And the portion of the message with the relevant text is:

As you can see, the closing ">" and the terminating "\r\n" are not being transmitted. I have generated the inserted elements by cutting and pasting the successful elements and then editing as appropriate, and have also tried a number of permutations of String and char[] variables, all without success. But from the Wireshark trace the problem is between the Arduino code and the Ethernet link.
Any ideas or comments would be gratefully appreciated.

A: For the record, (and anyone who might be interested), the working solution I have adopted is:
void SendTags(EthernetClient cl)
{
  String value;      // stores value read from analog onputs
  int count;         // index for 'for' loops
  int str_length;
  char msg_chrs[0];

  Serial.println("Debug 395 - sending title and tags");
  cl.write("<?xml version = \"1.0\" ?>\r\n");
  cl.write("<app_data>\r\n");
  cl.write("<tags>\r\n");

  for (count = 0; count < di_count; count++)
  {
    value = di_sig_tag[count];
    Str = "<DI_TAG>" + value + "</DI_TAG>\r\n";
    ethWrite(Str, cl);
 }

  for (count = 0; count < do_var_count; count++)
  {
    value = do_sig_tag[count];
    Str = "<DO_TAG>" + value + "</DO_TAG>\r\n";
    ethWrite(Str, cl);
  }

    for (count = 0; count < ai_count; count++)
  {
    value = ai_sig_tag[count];
    Str = "<AI_TAG>" + value + "</AI_TAG>\r\n";
    ethWrite(Str, cl);
  }

  for (count = 0; count < ao_count; count++)
  {
    value = ao_sig_tag[count];
    Str = "<AO_TAG>" + value + "</AO_TAG>\r\n";
    ethWrite(Str, cl);
  }

  cl.write("</tags>\r\n");
  cl.write("<title>\r\n");

  Str = ("<PR_NAME>" + pr_name + "</PR_NAME>\r\n");
  ethWrite(Str, cl);

  cl.write("</title>\r\n");
  cl.write("</app_data>\r\n");

  Serial.println("Debug 462 - End of SendTags()");
}

void ethWrite(String st, EthernetClient cl)
{
  int st_length = st.length()+1;
  char msg_chrs[st_length];
  Str.toCharArray(msg_chrs, st_length);
  cl.write(msg_chrs);
}

So far, this is doing what I want and seems to be reasonably efficient coding.  Thanks to @gre-gor for comments - put me on the right track. My excuse is that I am working simultaneously in javascript (which does allow expanding arrays) and c++ (which doesn't).


text:
Q: fitting left censored models using software for right censored data When analyzing a lognormal data with left-censored values using a regression model, I have read that you can use methods that fit right-censored data but "flip" the data by subtracting from some large constant. Why does this work? Why are the coefficients the same?
This link describes the NADA package: "The routines in NADA for R internally flip the original data by subtraction from a large
constant, in order to produce right-censored values that can be input to survival analysis
routines."
The survreg library in R has the option for "type=left", but I am not clear on the correspondence, and I would like to see the equations and make survreg match NADA.

A: If the only censoring is left censoring, as you can have with chemical concentrations that are below a detection limit, that "time"-reversal (here, concentration-reversal) method will work for getting nonparametric, Kaplan-Meier-type curves. With left censoring, Klein and Moeschberger suggest in Section 5.2

instead of measuring time from the origin we fix a large time $\tau$ and define new times by $\tau$ minus the original times. The data set based on these reverse times is now right-censored and the estimators in sections 4.2–4.4 can be applied directly.

That's not, however, the way that the NADA package handles parametric regression models. For that, according to the manual page for cenlme():

This routine is a front end to the survreg routine in the survival package

which directly uses the appropriate contributions to the likelihood from left-censored observations in a parametric model.


text:
Q: Parsing json in PHP returning blank I am sending a JSON string (correctly recieved from the facebook api) to PHP using ajax.  When I try and parse the JSON string it adds extra characters to the string and when I try and obtain a value from the string I get nothing.
Here is the json as returned from facebook:
{"id":"redacted","email":"redacted","first_name":"redacted","gender":"female","last_name":"redacted","link":"redacted","locale":"en_US","name":"redacted","timezone":-6,"updated_time":"2014-12-17T23:10:00+0000","verified":true}

Here is the ajax:
$.ajax({
                       type: "POST",
                       url: "signupfacebookajax.php",
                       data: { theresponse: JSON.stringify(response) },
                       success: function(crap){ console.log(crap)}
                       });
                });

Here is the code on the php page signupfacebookajax.php:
$response = $_POST['theresponse'];
$jsondecode = json_decode($response);
$facebook_id = $jsondecode->id;
echo $facebook_id;

Noting is returned at all.  While troubleshooting I noticed that the JSON string looks odd after decoding it.  Here is what I get after decoding the string after passed by ajax.
{\"id\":\"redacted\",\"email\":\"redacted\",\"first_name\":\"redacted\",\"gender\":\"female\",\"last_name\":\"redacted\",\"link\":\"redacted\",\"locale\":\"en_US\",\"name\":\"redacted\",\"timezone\":-6,\"updated_time\":\"2014-12-17T23:10:00+0000\",\"verified\":true}

A: Have you tried disabling magic quotes??? It looks like your php.ini has
magic_quotes_gpc = On

for more read Disable Magic Quotes
To disable it just replace On with Off
magic_quotes_gpc = Off


text:
Q: how to output convex_hull polygon of points shapefile i have a shapefile of more than 8 points and i have written a code get the convex_hull geometry of of the points and output it as a shapefile using fiona. however the code returns an error saying:
ERROR:TypeError: expected string or bytes-like object
from shapely.geometry import MultiPoint, point, shape
from fiona.crs import from_epsg
outshape = fiona.open(".cache\ca2_points\ca2_points.shp")
with fiona.open('.cache/mew.shp', 'w', 'ESRI Shapefile', outshape.schema.copy(), outshape.crs)   as output:
    for feat in output:
        feat = MultiPoint([shape(point['geometry']) for point in fiona.open(outshape)])
        output.write(feat)


text:
Q: Obstructions to non-separable geometry I'm curious about generalizations of Euclidean geometry to non-separable spaces.
Specifically, my question would be: Which are the obvious obstructions to having a model of (some considerable fraction) of Hilbert axioms, where the base topological space is non-separable?
Even more particularly,

what would a "Suslin plane" look like?

With this term I mean the cartesian product of two Suslin lines.
This was my original question, but then I realized that perhaps non-separability would be a prior obstacle.
I was playing a little bit with the long line, trying to define a wide plane. It's kinda evident that an obvious, "affine" approach (that is, trying to define a line as something like $ax + by =0 $) will not work here.


text:
Q: Android: calling number without user init? For something like a 'help I can't get up' app -- is there a way for a user to set a contact number, and then for the app to call that number in the future WITHOUT the user initiating the dialout?  I've tried the below but there seems to be a problem:
 private void callPhone(){
            if(phoneNumber.length()>0){
                try {
                       Intent intent = new Intent(Intent.ACTION_CALL);
                       intent.setData(Uri.parse("tel:"+phoneNumber));
                       startActivity(intent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Problem calling number.", Toast.LENGTH_LONG).show();
                    }
                //startActivityForResult(new Intent(Intent.ACTION_CALL, Uri.parse("tel:+"+phoneNumber)), 1);
            }

        }

A: To get the permission that you need to place calls without using the dialer and requiring the user to confirm the call, you must set either the CALL_PHONE or CALL_PRIVILEGED permissions in your AndroidManifest.xml file depending on your needs.
<uses-permission android:name="android.permission.CALL_PHONE" />

or
<uses-permission android:name="android.permission.CALL_PRIVILEGED" />


text:
Q: Move file with name causes error 5, invalid procedure call or argument It seems I have some problems with the hard drive itself. It's acting strange. Some files appear duplicates and I delete the duplicates. A few minutes later i refresh the directory and they are back. Refresh again and they are gone. Files are visible on one computer but not the other. I will try to trouble shoot it and see where what the issue is. Thanks for all the help so far it may be more than one problem acting together.
I have used this code to rename and move files from one location to another on my network drive.
The video files are named 00001, 00002 etc.. and since the counter resets i need to rename the files to something that can work on a harddrive.
So all files are renamed to <date> <time>.MTS
This code used to work but now it just stoped working by some reason.
Sub MoveFiles()
    Dim r As Integer
    r = 2 'first line of files
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Do Until IsEmpty(Cells(r, "A")) Or IsEmpty(Cells(r, "B"))
        dirPath = Cells(r, "C") + "\" + Cells(r, "B")
        If objFSO.FileExists(dirPath) Then
            ' file exist output error message
            MsgBox ("Filen finns redan!!! " + Cells(r, "A") + "   " + Cells(r, "B"))
        Else
            FromName = ActiveWorkbook.Path + "\" + Cells(r, "A")
            ToName = Cells(r, "C") + "\" + Cells(r, "B")

            ' none of the methods below work.
            Name FromName As ToName
            Name ActiveWorkbook.Path + "\" + Cells(r, "A") As Cells(r, "C") + "\" + Cells(r, "B")
        End If
        r = r + 1
    Loop

End Sub

Since the code does not create the error message that the ToName exsists then it's not a "duplicate" issue.
If I run the following code
If objFSO.FileExists(ActiveWorkbook.Path + "\" + Cells(r, "A")) Then
    MsgBox "test"
End If

I get the message box, which means that FromName file exsists.
So in short the file exsists and the filename that it will become does not exsist. Also the paths (directories) exsist as they are created in a earlier sub(). And I have double checked it. So what can be the problem?
I'm completly lost here.
Edit; Workbook picture added:

A: This should do it (not tested — YMMV):
Option Explicit

Sub MoveFiles()
    Dim rownum As Long
    rownum = 2 'first line of files
    Dim objFSO As Object        ' Required because of Option Explicit
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Dim FromName as String
    Dim ToName as String

    Do Until IsEmpty(Cells(rownum, "A")) Or IsEmpty(Cells(rownum, "B")) or rownum > 1048576
        ToName = CStr(Cells(rownum, "C")) + "\" + CStr(Cells(rownum, "B"))
        If objFSO.FileExists(ToName) Then
            ' file exist output error message
            MsgBox ("Filen finns redan!!! " + Cells(rownum, "A") + "   " + Cells(rownum, "B"))
        Else
            FromName = ActiveWorkbook.Path + "\" + CStr(Cells(rownum, "A"))

            ' none of the methods below work.
            '' Name FromName As ToName
            '' Name ActiveWorkbook.Path + "\" + Cells(rownum, "A") As Cells(rownum, "C") + "\" + Cells(rownum, "B")

            objFSO.MoveFile FromName, ToName

        End If
        rownum = rownum + 1
    Loop

End Sub

A few things changed:

*

*Option Explicit: always use it at the top of every VBA file.

*Never use Integer — use Long instead.

*With Option Explicit, you have to have Dim statements for every variable.  This prevents you from accidentally creating a new variable because of a typo in a variable's name.

*in the Do loop, include a sanity check on rownum so you don't try to access a nonexistent row.

*Only assign ToName once, and save its value.

*Use FileSystemObject.MoveFile to rename.

*Use CStr() to make sure the value you get from Cells() is a String.  That will reduce the risk of unpleasant surprises due to unexpected input data.

This question is not an exact duplicate, but may also have some helpful information.


text:
Q: How do you add environment variables to a python scrapy project? dotenv didn't work I'm having trouble incorporating an IP address into a format string in my Python Scrapy project. I was trying to use python-dotenv to store sensitive information, such as server IPs, in a .env file and load it into my project, instead of hardcoding it.
I added python-dotenv to the settings.py file of my Scrapy project, but when I run a function that should use the values stored in os, I get an error saying that it can't detect dotenv. Can someone help me understand why this is happening and how to properly incorporate an IP address in a format string using python-dotenv in a Python Scrapy project?

A: It is difficult to help figure out what you might be doing wrong with the limited information you have provided. However here is a general example of how one might use python-dotenv with a scrapy settings.py file.
First create a .env file and add your IP
.env
IPADDRESS = SUPERSECRETIPADDRESS

Finally in your settings.py file you need to import dotenv and then run dotenv.load_dotenv() and then you can get the ip address from the environment variable.
settings.py
import os
import dotenv

dotenv.load_dotenv()

IP_ADDRESS_SCRAPY_SETTING = os.environ["IPADDRESS"]

print(IP_ADDRESS_SCRAPY_SETTING)

output:
SUPERSECRETIPADDRESS

Note:  Make sure that the .env file is in the same directory as the settings.py file or it is in one of it's parent/ancestor directories.
So if your settings.py file is in

*

*/home/username/scrapy_project/scrapy_project/settings.py
then that means the .env file can be in one of the following:

*

*/home/username/scrapy_project/scrapy_project/.env

*/home/username/scrapy_project/.env

*/home/username/.env

*/home/.env

*/.env
Otherwise it will not be able to find the file.


text:
Q: Convenient notation, or something more? A little while ago I happened across a curious formula that blew my mind (no idea what it's called):
$e^{\frac{d}{dx}}f(x)=f(x+1)$
I played around with it a bit and managed to prove it using the Taylor expansion of the exponential and a bit of trickery with the arguments, so I have no issue with it's accuracy.
My question: Is this just convenient notation (to avoid writing out the Taylor series summation) or does it have well defined meaning in and of itself? I tried rearranging and evaluating the derivative inside the exponential for a trial function ($f(x)=x^2$) and it came out with nonsense.

A: It's much more than convenient notation, but to see what's going on it helps to write it in a more general form as
$$e^{t \frac{d}{dx}} f(x) = f(x + t).$$
This is a version of the exponential map in Lie theory. $\frac{d}{dx}$ can be interpreted as a vector field on $\mathbb{R}$, and $e^{t \frac{d}{dx}}$ can be interpreted as the one-parameter group of diffeomorphisms of $\mathbb{R}$ given by flowing along the vector field. Passing from one to the other is an important operation in Lie theory, differential geometry, and functional analysis, at the very least.


text:
Q: Remove Double quotes from text when exporting csv file via PhpExcel and open it with notepad I am exporting the csv file using PhpExcel but when I open it with notepad it shows Double quotes around the text. I do not want these double quotes.
Can anyone help me?
Below is demo output from that file:
"Credits","Modified_User","Plain_Course_Name","Popular_Courses","ISBN_9","ISBN_7","Course_Number","ISBN_8","Book_2_REQUIRED_or_OPTIONAL","ISBN_5","ISBN_6","Course_Status","ISBN_3","ISBN_4","Book_9_REQUIRED_or_OPTIONAL","Bookstore_2_Course_Status","ISBN_2",

to generate csv, I am using below code:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'csv');
If I use following code then the output in notepad is correct but it will change the data order in excel csv file.
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV')->setDelimiter(',')
                                                              ->setEnclosure('"')
                                                              ->setLineEnding("\r\n")
                                                              ->setSheetIndex(0)
                                                              ->save(__DIR__.'/'.$file_name);

A: So, from what I understand of PHPExcel, the text enclosure is set by default to use ", which is why you are having " around your text in your file. The second snippet of code hits on directly what you need though, so you were close!
You should be able to use $createWriter->setEnclosure('') in order to print your items without double quotes.
In your code that would look something like this:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV')->setDelimiter(',')
                                             ->setEnclosure(' ')
                                             ->setLineEnding("\r\n")
                                             ->save(__DIR__.'/'.$file_name);

I'm not sure if you need the setLineEnding, especially if it is one line. Perhaps for later parsing you might. I hope that this information helps out!
There is additional documentation on the subject on their gitHub: https://github.com/PHPOffice/PHPExcel/blob/develop/Documentation/markdown/Overview/10-Reading-and-Writing.md


text:
Q: Coxeter Groups and representations of $ + $ type Background:
A Coxeter group is generated by reflections, which all have the real eigenvalues $ \pm 1 $, so intuitively it makes sense that all the representations would be real. Certainly every Coxeter group must have one faithful real valued irrep, since every finite Coxeter group is just a Euclidean reflection group.
Question:
I have noticed that all the irreps of a finite Coxeter group are of $ + $ type (I have not checked every finite Coxeter group but this seems to be the pattern) (by $ + $ type I mean they have Frobenius-Schur indicator $ +1 $). I would imagine this fact (if true) is well know. Does anyone know an explanation/proof/reference for this?
Follow Up Question:
More generally, does anyone know any necessary or sufficient (or necessary and sufficient!) conditions for a finite group to have all $ + $ type irreps?

A: Some stuff I scrounged up. First, an easier result: an element $g$ of a finite group $G$ is real if it is conjugate to $g^{-1}$, or equivalently if the character of $g$ is always real in every representation. So the following conditions are equivalent:

*

*Every element of $G$ is conjugate to its inverse.

*Every character of $G$ is real.

*Every finite-dimensional representation of $G$ is either real or quaternionic.

Such groups are called ambivalent. This is a necessary condition for all representations being real; the symmetric groups obviously satisfy it, but I'm not sure if all finite Coxeter groups do (edit: they do, see the comments). However, it turns out to be satisfied by all Weyl groups.
The stronger condition that every representation is real is called being totally orthogonal; apparently it's known (see the link) that any such group must be generated by involutions. It doesn't seem like necessary and sufficient conditions are known in general.
Finally, the Weyl groups satisfy an even stronger condition which implies total orthogonality, that every representation is realizable over $\mathbb{Q}$: this is claimed in Humphreys in Section 8.10 and the citation is to Benard's On the Schur indices of characters of the exceptional Weyl groups. Such a group must in particular satisfy the property that every character is integer-valued and this condition is called being rational.


text:
Q: Multidimensional Fourier series On $\mathbb{T}$, we have approximation series $\{f_n\}$ of $f\in L^p,p\in[1,\infty)$ in the form of $f_n(x)=\sum_{|k|\le n}a_{n,k}e^{ikx}$, converging to $f$ in $L^p$. (for example, we can consider convolution with Fejer kernel)
Can we do something similar for $\mathbb{T}^n$ as well?

A: Summability is no problem, for example if $K_n(t)$ is the Fejer kernel then $K_n(s)K_n(t)$ is an approximate identity on $\Bbb T^2$. Now, convergence for multiple Fourier series is a serious problem...


text:
Q: IIExpress tracelog file I am debugging an asp.net mvc 4 web site wsccc1. To traced any error, I designed my trace file log in web.config. I use Visual Studio 2012, the default hosted server is IIS Express.
<?xml version="1.0"?>
<configuration>
   <system.web>
     <compilation debug="true" targetFramework="4.5"/>
     <httpRuntime targetFramework="4.5"/>
     <customErrors mode="Off"></customErrors>
   </system.web>
   <system.serviceModel>
     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true">
     <serviceActivations>
     <add factory="System.ServiceModel.Activation.WebServiceHostFactory"
    relativeAddress="wscccService.svc"
    service="service.wservice"/>
  </serviceActivations>
  <baseAddressPrefixFilters>
    <add prefix="http://localhost:8080/" />
  </baseAddressPrefixFilters>
  </serviceHostingEnvironment>
 <behaviors>
  <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
      </behavior>
  </serviceBehaviors>
 </behaviors>
 <diagnostics>
     <messageLogging logEntireMessage="true"
              logMessagesAtServiceLevel="false"
              logMessagesAtTransportLevel="false"
              logMalformedMessages="true"
              maxMessagesToLog="5000"
              maxSizeOfMessageToLog="2000">
 </messageLogging>
</diagnostics>
</system.serviceModel>
 <system.webServer>
    <validation validateIntegratedModeConfiguration="true" />
    <handlers>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
   </system.webServer>
 <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
        <add name="messagelistener"
         type="System.Diagnostics.XmlWriterTraceListener"
              initializeData="C:\myMessages.svclog"></add>
     </listeners>
  </source>
  </sources>
    <trace autoflush="true"></trace>
  </system.diagnostics>

But I couldn't find any .svclog file in C drive. There are log files in the path 'C:\Users\hui\Documents\IISExpress\TraceLogFiles\wsccc1'. All the files begin with 'fr' such as 'fr00400.xml'.
It has the exception information.
My question is why it begin with 'fr'? Is it referred to French but I am in USA?
Also why I could not generate 'C:\myMessages.svclog'.

A: Files in C:\Users\hui\Documents\IISExpress\TraceLogFiles\wsccc1 are IIS logs files : HTTP request url + response status  + timestamp +.... HttpLoggingModule is required for this and it's not related to WCF or even asp.net.
*.svclog are WCF trace files : this generally requires to edit the configuration file in order to enable WCF tracing (as you did). A good tutorial is here.

Also why I could not generate 'C:\myMessages.svclog'.

Maybe because of security. Add full control to everyone on C Drive (not recommanded) or specify a public directory (such as c:\logs) where everyone could generate trace logs.
Edit :

Why IIS log files begin with 'fr'?

Even if i'm french it's not made for us. fr means here Failed Request. It's a new feature in IIS called "Failed Request Tracing" : it is designed to buffer the trace events for a request and only flush them to disk if the request "fails. Explanation here.


text:
Q: Load csv into html, where to set path to csv? My embarrasing problem...my brain is not working so early :D
I have a html page where i use a import of a csv file to show status from a job that runs in the background.
Everything worked fine until i have to change the path of my csv file.
Before i had the csv file in the same folder as my html files in the webapp folder from apache.
Now i have to change the path to C:/tmp/ for the csv file.
Iv'e tried many ways to change the function to get it to change the path to C:/tmp/ but i can't get it work.
Where do i have to make the change?
Function look like this now:
function()
                {
                $('#csv').load(lnr.val()+'_JobStatus.csv?'+new Date().getTime(),function(data){$(this).html(data).fadeIn("slow");});          });

Iv'e tried something like this but it's not working..
$('#csv').load('C:/tmp/'+lnr.val()+'_JobStatus.csv?

A: Try it.
$(document).ready(function() {
 $("#loadData").click(function() {
    $.ajax({
        url : "articlename.csv",
        dataType: "text",
        success : function (data) {
            $("#csv").html(data);
        }
    });
 });
});