text:
Q: printing pdf to multiple pages using jscrip via VBA After many days searching to print multiples pages of a pdf file in a single sheet by using only VBA code on Excel I find a way to use javascript via VBA thanks to user ReFran https://stackoverflow.com/a/49538950/16279586
Combining the code ReFran wrote with this reference https://opensource.adobe.com/dc-acrobat-sdk-docs/acrobatsdk/pdfs/acrobatsdk_jsapiref.pdf#G4.1959527
I build some Frankenstein monster that doesn't work at all.
Suposedly it will open a pdf file, then print 2x2 pages on a single sheet and save in the same document the changes (turning from a 4 pages pdf to a 1 page pdf)
I'm a newbie in VBA and absolutely ignorant in javascript, can anyone give me a helping hand with this?
Sub test()
Dim app As acroApp
Dim avdoc As AcroAVDoc
Dim aform As AFormApp

Path = "C:\1.pdf"

Set app = CreateObject("Acroexch.app")
app.Show
Set avdoc = CreateObject("AcroExch.AVDoc")
Set aform = CreateObject("AFormAut.App") 'from AFormAPI

If avdoc.Open(Path, "") Then
    '// write some js code on a vbs variable

    js = "pp = this.getPrintParams();" _
    & "pp.printerName = "";" _
    & "pp.pageHandling = pp.constants.handling.nUp;" _
    & "pp.nUpPageOrders = pp.constants.nUpPageOrders.Horizontal;" _
    & "pp.nUpNumPagesH = 2;" _
    & "pp.nUpNumPagesV = 2;" _
    & "pp.nUpPageBorder=true;" _
    & "this.print(pp);"
     '//execute the js code
    aform.Fields.ExecuteThisJavaScript js
End If

Set aform = Nothing
Set avdoc = Nothing
Set app = Nothing
End Sub


text:
Q: Creating Near Table between points in one layer that share an attribute with points in another layer? I am trying to calculate the distance between some geographic features (point layer) and the capital of the country that they fall in. I have a shapefile of "features" and a shapefile of "world capitals". My current system is to generate a NearTable between the two layers and then use another program (Stata) to keep only the relevant distances (where the country of the feature and city are the same). However, my program takes a while to run when I do this because, due to the size of the countries I'm looking at, I need to calculate the distance between all points and the nearest 20 capital cities.
Is there a faster way to do this?
Here is a snippet of my code:
in_features = gpts
near_features = world_capitals
arcpy.GenerateNearTable_analysis(in_features, near_features, near_world_capitals_tbl, \
closest="ALL", closest_count="20", method="GEODESIC")

I am working in ArcPy, but answer in ArcMap are also helpful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: confidence intervals around lines from glmer in lme4 I have spent a large amount of time trying to figure out how to generate a desired plot, and was wondering if any one can help. The plot is to illustrate an interaction between 'time' and 'group' on a binary response variable, which increases faster over time for 'group 2' than 'group 1'.  Below is a simplified version of what I need using simulated data. I have correctly got to the point of plotting a slope for each group (I think), but now want to plot a measure of confidence around each of these slopes.
#simulate 41 individuals, each occurring over a random number of days:
days.each<-sapply(sample(2:40,41,T),function(a)1:a)
thedata<-data.frame(day=unlist(days.each))

#add the individual id in:
thedata$id<-rep(1:41,sapply(days.each,length))

#9 of these individuals are in group 1, and 10 and in group 2:
thedata$group<-ifelse(thedata$id<20,1,2)

#with increasing 'day', the y increases. This relationship is stronger in individuals from group 2:
thedata$y<-(thedata$day*thedata$group)

#Also, some individuals have generally higher 'y' than others:
thedata$y<-thedata$y+rnorm(41,10,3)[thedata$id]

#the y is binomial:
thedata$y<-rbinom(nrow(thedata),1,thedata$y/max(thedata$y))

#change the group and id to class "factor"
thedata$id<-as.factor(thedata$id);thedata$group<-as.factor(thedata$group)

#run the full model:
library(lme4)
model <- glmer(formula=y ~ day*group+(1|id),family=binomial,data=thedata)

#to illustrate the interaction, plot one line for each group:
vals<-predict(model,re.form=NA,type ="response")

plot(y~day,data=thedata,type="n")
lines(sort(vals[thedata$group==1])~sort(thedata$day[thedata$group==1]),col="black")
    lines(sort(vals[thedata$group==2])~sort(thedata$day[thedata$group==2]),col="purple")

#now add confidence around these slopes?

any help would be massively appreciated

A: I was able to get confidence intervals for the model parameters by doing this:
CI<-confint(model)
> CI
                  2.5 %      97.5 %
.sig01       0.00000000  0.24128544
(Intercept) -2.28835314 -1.35990281
day          0.01994399  0.07218563
group2      -0.48619173  0.71667529
day:group2   0.01479008  0.08282838

I imagine there is a way to use the predict() function with the minimum and maximum values for each parameter. That may be what you are specifically asking for, but I could not figure out the syntax immediately and am not really sure what is going on in the background here. Perhaps someone else can help with that.
Instead, or at least in addition to that, I was thinking something like this should be included to visualize the actual data rather than just model output:
Calculate cumulative number of "type 1" outcomes:
CumSum<-NULL
for(i in unique(thedata$id)){
sub<-thedata[which(thedata$id==i),]
CumSum<-c(CumSum,cumsum(sub$y))
}
thedata<-cbind(thedata,CumSum)

Calculate group-level mean and CIs:
GroupLevel=matrix(ncol=6,nrow=2*length(unique(thedata$day)))
cnt=1
for(g in as.numeric(unique(thedata$group))){
sub1<-thedata[which(thedata$group==g),]
for(i in unique(sub1$day)){
sub2<-sub1[which(sub1$day==i),]
if(length(unique(sub2[,"CumSum"]))>1){
res<-t.test(sub2[,"CumSum"])
GroupLevel[cnt,]<-c(g, nrow(sub2), i, res$estimate, res$conf.int[1], res$conf.int[2])
}else{
GroupLevel[cnt,]<-c(g, nrow(sub2), i, mean(sub2[,"CumSum"]), NA, NA)
}
cnt=cnt+1
}
}
colnames(GroupLevel)<-c("group","N","day","mean","LowCI","HighCI")

Plot group-level cumulative outcomes and sample size for each day:
par(mfcol=c(2,1))
#y.max<-max(GroupLevel[,"HighCI"], na.rm=T)
y.max<-30
plot(0,0, type="n", panel.first=grid(), xlim=c(0, max(GroupLevel[,"day"])), xlab="Day",
ylim=c(0,y.max), ylab="CumSum(Y)")
for(g in as.numeric(unique(GroupLevel[,"group"]))){
sub1<-GroupLevel[which(GroupLevel[,"group"]==g),]
color<-c("Blue","Red")[g]
lines(sub1[,"day"],sub1[,"mean"], type="b", pch=16, col=color)
lines(sub1[,"day"],sub1[,"LowCI"], lty=2, col=color)
lines(sub1[,"day"],sub1[,"HighCI"], lty=2, col=color)
}
legend("topleft", legend=paste("Group", unique(GroupLevel[,"group"])),
col=c("Blue","Red"), lwd=4, bg="White")

plot(0,0, type="n", panel.first=grid(), xlim=c(0, max(GroupLevel[,"day"])), xlab="Day",
ylim=c(0,max(GroupLevel[,"N"], na.rm=T)), ylab="Sample Size (N)")
for(g in as.numeric(unique(GroupLevel[,"group"]))){
sub1<-GroupLevel[which(GroupLevel[,"group"]==g),]
color<-c("Blue","Red")[g]
lines(sub1[,"day"],sub1[,"N"], type="b", pch=16, col=color)
}


text:
Q: Simple bootstrap with replacement of list I'm attempting to perform a simple bootstrap process with replacement applied to a list formatted like so:
a = [[0.2,0.5,0.4,0.8], [0.3,0.7,0.1,0.6], [0.3,1.2,1.0,0.6], ....]

That is: a is a list made of N sublists each with the same number of floats (4 in this case)
In order to choose random elements (ie: sub-lists) from a with replacement to perform the bootstrap process I can do:
import random

bts_a = []
for elem in a:
    r = random.randint(0,len(a))
    bts_a.append(a[r])

Is there a more succinct and/or faster way to accomplish this? I particulary dislike having to initialize an empty list (ie: bts_a=[]), it feels very non-pythonic to me.

A: You can use random.choice and list comprehension or map:
a = [[0.2, 0.5, 0.4, 0.8], [0.3, 0.7, 0.1, 0.6], [0.3, 1.2, 1.0, 0.6]]

>>> [random.choice(e) for e in a]
[0.5, 0.6, 0.6]
>>> [random.choice(e) for e in a]
[0.4, 0.3, 1.2]

>>> map(random.choice, a)
[0.5, 0.1, 1.0]
>>> map(random.choice, a)
[0.8, 0.3, 0.3]

to choose random sublist from a:
>>> random.choice(a)
[0.3, 0.7, 0.1, 0.6]
>>> random.choice(a)
[0.2, 0.5, 0.4, 0.8]

bts_a = [random.choice(a) for _ in a]
>>> bts_a
[[0.3, 1.2, 1.0, 0.6], [0.2, 0.5, 0.4, 0.8], [0.3, 1.2, 1.0, 0.6]]

A: This will give you random sub-list using random:
>>> from random import choice
>>> a = [[0.2,0.5,0.4,0.8], [0.3,0.7,0.1,0.6], [0.3,1.2,1.0,0.6]]
>>> print choice(a)
[0.3, 1.2, 1.0, 0.6]
>>>

Or
 >>> print a[int(random()*len(a))]
 [0.3, 1.2, 1.0, 0.6]
 >>> a
 [[0.2, 0.5, 0.4, 0.8], [0.3, 0.7, 0.1, 0.6], [0.3, 1.2, 1.0, 0.6]]
 >>> from random import random
 >>> print a[int(random()*len(a))]
 [0.2, 0.5, 0.4, 0.8]
 >>> print a[int(random()*len(a))]
 [0.3, 0.7, 0.1, 0.6]
 >>>

A: I think what you are looking for is random.shuffle:
random.shuffle(a)

Note that it changes the list inline. If you want a different list. You need to create a copy:
bts = a[:]
random.shuffle(bts)

Example:
>>> a = [[0.2, 0.5, 0.4, 0.8], [0.3, 0.7, 0.1, 0.6], [0.3, 1.2, 1.0, 0.6]]
>>> import random
>>> random.shuffle(a)
>>> a
[[0.3, 0.7, 0.1, 0.6], [0.2, 0.5, 0.4, 0.8], [0.3, 1.2, 1.0, 0.6]]


text:
Q: Using a List in a where clause in Entity Framework I am trying to retrieve document id's over a one-to-many table. I want to use a List in the where clause to find all id's that are connected with every element in the list.
List<int> docIds = (from d in doc
                      where _tags.Contains(d.Tags)
                      select d.id).ToList<int>();

I know that the contains must be incorrect but I can't work it out. If I try a foreach I can't  work out how to check if the document contains all Tags.

A: If you want that all d.Tags should be in the included in the _tags list, you can try:
List<int> docIds = (from d in doc
                      where d.Tags.All(t => _tags.Contains(t))
                      select d.id).ToList<int>();

If you want that d.Tags should contain all the item from _tags you need:
List<int> docIds = (from d in doc
                      where _tags.All(t => d.Tags.Contains(t))
                      select d.id).ToList<int>();

But I don't know how it translates to SQL by EF so maybe you need to evaluate it on the client site.

A: Use a join:
List<int> docIds = (from d in doc
from t in tags
where d.Tags.Contains(t)
select d.id).ToList<int>();


text:
Q: Vb.Net MustOverride vs New vs MustInherit I am trying to implement a codefix using some private code from Rolyn
Partial Public Class SynatxEditorFixAllProvider
       Inherits FixAllProvider
       Public Overrides Async Function GetFixAsync(ByVal fixAllContext As FixAllContext) As Task(Of CodeAction)
            Dim documentsAndDiagnosticsToFixMap As ImmutableDictionary(Of Document, ImmutableArray(Of Diagnostic)) = Await fixAllContext.GetDocumentDiagnosticsToFixAsync().ConfigureAwait(False)
            Return Await GetFixAsync1(documentsAndDiagnosticsToFixMap, fixAllContext, fixAllContext.CancellationToken).ConfigureAwait(False)
       End Function

        Async Function GetFixAsync1(ByVal documentsAndDiagnosticsToFixMap As ImmutableDictionary(Of Document, ImmutableArray(Of Diagnostic)), ByVal _FixAllContext As FixAllContext, ByVal cancellationToken As CancellationToken) As Task(Of CodeAction)
        ' Process all documents in parallel.
        Dim updatedDocumentTasks As IEnumerable(Of Task(Of Document)) = documentsAndDiagnosticsToFixMap.Select(Function(kvp) FixDocumentAsync(kvp.Key, kvp.Value, cancellationToken))

        Await Task.WhenAll(updatedDocumentTasks).ConfigureAwait(False)

        Dim currentSolution As Solution = _FixAllContext.Solution
        For Each Task As Task(Of Document) In updatedDocumentTasks
            ' 'await' the tasks so that if any completed in a canceled manner then we'll
            ' throw the right exception here.  Calling .Result on the tasks might end up
            ' with AggregateExceptions being thrown instead.
            Dim updatedDocument As Document = Await Task.ConfigureAwait(False)
            currentSolution = currentSolution.WithDocumentSyntaxRoot(updatedDocument.Id, Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False))
        Next Task

        Dim title As String = GetFixAllTitle(_FixAllContext)
        Return New SolutionChangeAction(title, Function(underscore) Task.FromResult(currentSolution))
End Function

With just this code I get an error and it wants the code below
Partial Public MustInherit Class SynatxEditorFixAllProvider
    Protected MustOverride Function FixAllAsync(ByVal document As Document, ByVal diagnostics As ImmutableArray(Of Diagnostic), ByVal editor As SyntaxEditor, ByVal cancellationToken As CancellationToken) As Task
End Class

But if I add the code above the following line gets an error,

"New can not be used on a class that is declared MustInherit"

Public Shared ReadOnly Property Instance() As FixAllProvider = New SynatxEditorFixAllProvider()

A: MustInherit is the VB .NET syntax for an abstract class.
These classes cannot be instantiated directly.  However, classes that derive from them can be instantiated as new objects.
For example, Animal might be a good example of MustInherit.   Dog would be a class that might be derived from Animal, and is not marked with MustInherit.
The developer can create a new instance of Dog, but not of Animal.
MustOverride is a method that a derived class must provide an implementation for.   In the Animal example, let's say that it has a method called MakeNoise.   You could never implement that method at the Animal level, because you don't know what noise a generic animal makes, but in your derived Dog class, you can.
In your case, if you want to derive from SynatxEditorFixAllProvider, make sure you provide an implemention the FixAllAsync method of your derived class.

A: MustInherit means your Class is abstract and cannot be instantiated. Such classes can only be instantiated indirectly, that is, you Inherit a Class from them which implements the not implemented methods and instantiate that child Class.
MustOverride means your method is not implemented and should be implemented in the first non-abstract descendant class (the latest point to do that).
New is a keyword for instantiation. If you say
New SolutionChangeAction(title, Function(underscore) Task.FromResult(currentSolution))

then you intend to create(instantiate) an Object of the SolutionChangeAction Class. From your question it seems that SolutionChangeAction is abstract as well, so you need to inherit from it a non-abstract Class and instantiate that.

A: Thanks everyone, I needed to change
MustInherit Class SynatxEditorFixAllProvider

To
MustInherit Class SynatxEditorFixAllProviderBase

Then change the class to
Partial Public Class SynatxEditorFixAllProvider
   Inherits SynatxEditorFixAllProviderBase

The C# code I used as an example used case to separate the abstract class from the implementation and that does not work in VB.


text:
Q: Simple LINQ question about Any() I wanna write a linq query to do this
Select id from selectedBrands
where name='Nick' or name='Matt'

is this linq correct????
  var brandsToNotShow=new[] {"Nick","Matt"};
    model.Names=

                    (from s in selectedBrands
                    where  brandsToNotShow.Any()
                    select s.Brand.name
                ).ToList();

where model.Names is a List

A: No, it is not correct.
brandsNotToShow.Any()

asks "are there any elements of this list", the answer to which is, yes, there are two elements.
This query is probably closer to what you want:
 from s in selectedBrands
 where brandsNotToShow.Contains(s.Brand.Name)
 select s.Brand.Name

(actually, if it's brands NOT to show, it might be
where !brandsNotToShow.Contains(s.Brand.Name)

I can't tell from your example)

A: According to MSDN Any():

Determines whether any element of a
  sequence satisfies a condition.

So in your example Any just checks to see if there are any items in brandsToNotSHow.
You probably want something like this:
from s in selectedBrands
where brantsToNotShow.Contains (s.Brand.Name)
SELECT s.Brand.Name

A: It's difficult to say what you want based on your choice of variable names, but the literal LINQ version of your SQL is
from brand in selectedBrands
where brand.name == 'Nick' || brand.name == 'Matt'
select brand.id;

If you had an array or sequnce in your code, you could use Contains
from brand in selectedBrands
where nameSequence.Contains(brand.name)
select brand.id;

But if that sequence is sizable, it is probably best to just join to the sequence.
from brand in selectedBrands
join name in nameSequence on brand.name equals name
select brand.id;


text:
Q: Adjusted $R^2$ calculations I'm struggling to figure out how these adjusted $R^2$ values for linear regression were calculated:

Footnote 124 says that for a model with just an intercept, $RSS$ (residual sum of squares) equals $TSS$ (total sum of squares). So using $R^2=1-\frac{RSS}{TSS}$, we get $R^2=0$ for the model with just an intercept. Then I use the formula
$$R^2_{adj} = 1-\left((1-R^2)\frac{n-1}{n-k-1}\right)$$
where $n$ is the number of observations (here $n=8$), and $k$ is the number of slopes (not including the intercept). So for the model with just the intercept, I get
$$R^2_{adj} = 1-\left((1-0)\frac{8-1}{8-1}\right) = 0$$
whereas the book has $0.4077$.
I get a different answer for the other models as well. For instance, for the model only using $X_2$ I get
$$R^2_{adj} = 1-\left(\frac{6981.58}{10693.5}\cdot \frac{8-1}{8-2}\right)=0.2383.$$
For the model with $X_1$ and $X_2$:
$$R^2_{adj} = 1-\left(\frac{915.375}{10693.5}\cdot\frac{8-1}{8-3}\right) = 0.8802$$
For the model using all three predictors:
$$R^2_{adj} = 1-\left(\frac{908.166}{10693.5}\cdot\frac{8-1}{8-4}\right) = 0.8514.$$
What am I missing or doing wrong?


text:
Q: How to archive file from folder using ZipFile c# I have to take a file from a folder and make a archive in another folder.
I use this code but get an error:
************** Exception Text **************
System.IO.IOException: The directory name is invalid.

I use this code:
            private void button1_Click(object sender, EventArgs e)
        {
            string Info = "";
            string startPath = @"D:\dosfiles\SYNOPD\SYNOPD$$.PD\" + comboBox3.SelectedItem.ToString() + @"\" + comboBox2.SelectedItem.ToString() + @"\" + station;
            string zipPath = @"D:\dosfiles\SYNOPD\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "_" + comboBox3.SelectedItem.ToString() + ".zip";

            if (File.Exists(zipPath))
            {
                File.Delete(zipPath);
                ZipFile.CreateFromDirectory(startPath, zipPath);
                Info += "Вашият архив е създаден в папка D:\\dosfiles\\SYNOPD\\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "." + comboBox3.SelectedItem.ToString() + ".zip" + Environment.NewLine;
            }
            else
            {
                ZipFile.CreateFromDirectory(startPath, zipPath);
                Info += "Вашият архив е създаден в папка D:\\dosfiles\\SYNOPD\\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "." + comboBox3.SelectedItem.ToString() + ".zip" + Environment.NewLine;
            }

            this.Hide();
            Form1 frm = new Form1();
            frm.Show();
        }


text:
Q: How to change file permissions when booted from a live disk/stick Let me start by saying that I am new to Ubuntu so please forgive my inexperience.  Also, this question goes along with my question I posted on 5/15/2017 titled:  Fstab edit crashed system.
THE PROBLEM
I can not save the edit to my /etc/fstab file while booting from a live disk.
When I open the /etc/fstab file with gedit as root, this is the header information I see:
*fstab [Read-Only] (491 GB Volume /media/ubuntu/0823c4f5-e42b-45ee-97b8-ad5d424b8b

MY QUESTION
How can I change the file permission of  /etc/fstab file to read - write in order to allow me to edit and save it while booting from a live disk?

EDIT UPDATE 5/21/2017
I am trying to apply sudodus solution (Thank You) to my issue, and I am not positive on how to proceed. Below is the result of me running his code to Identify the partition:
root@ubuntu:~# sudo lsblk -o model,size,name,fstype,label,mountpoint
MODEL     SIZE NAME   FSTYPE  LABEL                    MOUNTPOINT
TOSHIBA 465.8G sda
      487M ├─sda1 ext2                             /media/ubuntu/99ee9dc0-67
        1K ├─sda2
    465.3G └─sda5 LVM2_me
    457.3G   ├─ubuntu--vg-root
             │    ext4                             /media/ubuntu/0823c4f5-e4
        8G   └─ubuntu--vg-swap_1
                  swap
WDC WD1 931.5G sdb
    931.5G └─sdb1
ST4000D   3.7T sdc
      128M ├─sdc1
      3.7T └─sdc2 ext4    Seagate D1               /media/ubuntu/Seagate D1
ST4000D   3.7T sdd
      128M ├─sdd1
      3.7T └─sdd2 ext4    Seagate D2               /media/ubuntu/Seagate D2
DVD-ROM   1.4G sr0    iso9660 Ubuntu 16.04.1 LTS amd64 /cdrom
      1.4G loop0  squashf                          /rofs

My next step would be to Mount the partition using the information above, which I believe I needed to mount sda5, so I ran the following:
sudo mount /dev/sda5 /mnt

However, I then get the following:
root@ubuntu:~# sudo mount /dev/sda5 /mnt
mount: unknown filesystem type 'LVM2_member'

New Questions

*

*Is sda5 the correct mount point, and did I type the command correctly?

*What is this unknown filesystem type 'LVM2_member'?

EDIT UPDATE 5/22/2017
PROBLEM SOLVED
I was able to save my edit to my /etc/fstab file while booting from a live disk by following the comment left by @mook765, and then following the next steps suggested by @sudodus.
The partition I needed to mount was indeed a logical partition (LVM@_member). I was able to mount it with:
sudo mount /dev/mapper/ubuntu--vg-root /mnt

After that, I was able to edit and save the /etc/fstab file, which fixed the problem I had with my question I posted on 5/15/2017 titled:  Fstab edit crashed system.
A very huge THANK YOU to @mook765 and @sudodus for all of your help!  I do not think I could have gotten my system back up and running without it.
I will be researching and reading much more on how to edit the fstab file before trying this again.

A: I booted from a [persistent] live drive and could edit fstab in an installed system (both systems are 16.04.1) according to the following dialogue.

*

*Identify the partition
ubuntu@ubuntu:~$ sudo lsblk -o model,size,name,fstype,label,mountpoint
MODEL              SIZE NAME        FSTYPE   LABEL                    MOUNTPOINT
Samsung SSD 850  232.9G sda
                   300M ├─sda1      vfat     EFI
                     1M ├─sda2
                   100G ├─sda3      ext4     root
                     5G └─sda4      swap                              [SWAP]
                   1.4G loop0       squashfs                          /rofs
                  29.7G mmcblk0
                     7G ├─mmcblk0p1 ntfs     usbdata                  /media/ubuntu/usbdata
                     1K ├─mmcblk0p2
                   122M ├─mmcblk0p3 vfat     usbboot                  /media/ubuntu/usbboot
                   1.4G ├─mmcblk0p4 iso9660  Ubuntu 16.04.1 LTS amd64 /media/ubuntu/Ubuntu 16.04.1 LTS amd64
                  21.1G └─mmcblk0p5 ext4     casper-rw                /media/ubuntu/casper-rw

*Mount the partition
ubuntu@ubuntu:~$ sudo mount /dev/sdxn /mnt

where x is the drive letter and n is the partition number. In my case:
ubuntu@ubuntu:~$ sudo mount /dev/sda3 /mnt

*List the file with the permissions
ubuntu@ubuntu:~$ sudo ls -l /mnt/etc/fstab
-rw-r--r-- 1 root root 717 Apr 30  2016 /mnt/etc/fstab

*Back it up
ubuntu@ubuntu:~$ sudo cp -p /mnt/etc/fstab /mnt/etc/fstab.bak

*Edit /mnt/etc/fstab with root (superuser) privileges
ubuntu@ubuntu:~$ sudo nano /mnt/etc/fstab

*Check versus the backup file
ubuntu@ubuntu:~$ sudo diff /mnt/etc/fstab /mnt/etc/fstab.bak
14d13
< # added this line for demo

*List the file and its backup file
ubuntu@ubuntu:~$ sudo ls -l /mnt/etc/fstab*
-rw-r--r-- 1 root root 744 May 20 15:54 /mnt/etc/fstab
-rw-r--r-- 1 root root 717 Apr 30  2016 /mnt/etc/fstab.bak
ubuntu@ubuntu:~$

*Comment: So the edit was successful. The modified version was written.


text:
Q: Which are the differences and advantages on single INDEX or compound INDEX? I have two INDEX on a n:m relationship table as you can see on pics below:

Now I can have this also:

My questions:

*

*What is the advantage from last way(pic compound) over the two first?

*Can the # have some weight or significance in the composite INDEX?

A: Here's some explanation of which index you could use and when:
First, indexes speed up retrievals but slow down inserts and deletes, as well as updates of values in indexed columns. That is, indexes slow down most operations that involve writing. This occurs because writing a record requires writing not only the data row, it requires changes to any indexes as well. The more indexes a table has, the more changes need to be made, and the greater the average performance degradation. In the section "Loading Data Efficiently," we'll go into more detail about this phenomenon and what you can do about it.
Second, an index takes up disk space, and multiple indexes take up correspondingly more space. This might cause you to reach a table size limit more quickly than if there are no indexes.
Example:
mysql> ALTER TABLE customer ADD INDEX idx_sub
 (subscription)
mysql> EXPLAIN SELECT name FROM customer
WHERE subscription='2009-01-01' ORDER BY name
*************************** 1. row ***************************
 ...
 type: ref
 key: idx_sub
 rows: 4370
 Extra: Using where; Using filesort

The ideal way:
mysql> ALTER TABLE customer ADD INDEX
 idx_sub_name (subscription,name)
mysql> EXPLAIN SELECT name FROM customer
WHERE subscription='2009-01-01' ORDER BY name
*************************** 1. row ***************************
 ...
 type: ref
 key: idx_sub_name
 rows: 4363
 Extra: Using where; Using index

Benchmarks:

*

*Avg number of sec to run the query:

*

*Without index: 3.743

*Index on subscription: 0.435

*Covering index: 0.012

*Covering index:

*

*35x faster than index on subscription

*300x faster than full table scan

Related:

*

*Better Indexing for MySQL?

*Covering Indexes


text:
Q: How to setup local database development process for small web team? Background
I am working on creating a new development process for a small web team of about 4 programmers and 4 designers, with the obvious potential to grow the team in the future.
Our product is a central application that powers client websites that we also design and host.
Previously, we all worked via FTP on a dev server, with a single dev database. It "worked"* for a while, but we are moving into a new direction, so it is time to mature our process.
We use Percona Server 5.5, but this should be database agnostic, with the idea of keeping costs low.
Goals:
I am looking into creating a continuous integration (CI) process for database development with the following in mind:

*

*Developers have local copy of data to run development code against

*Able to rollback database structure to a previous changeset

*Able to separate new feature schema changes vs schema design fix changes

*Able to modify database structure locally for testing

Initial Concept
I have sketched out a process below using SVN and LiquiBase, though it completely removes #4.

*

*create a 'development' branch from trunk

*central 'development' db server runs off the 'development' branch

*local developers are set up as slaves to the development branch (provides #1 above)

*liquibase changesets are committed regularly to the development branch, which execute a post-commit hook to update the central development database (which will trickle down to the local machines running as slaves to this development server) (liquibase provides #2 above)

*when features or schema fixes are ready to go to QA, DBA (me) will merge the appropriate changes from development branch into trunk. This act will create a sql script to apply to a staging database server.

*Staging server should reflect TRUNK, which should have the same structure as Production, plus changes that are in QA

*after executing the sql script on the staging server, do some QA on the changes.

*If all looks good, TAG the structure. This will generate the .sql script to be run in production manually by the DBA (for off-peak hours if required)

This process requires that all developers run off the same 'development' branch, meaning there is only one version of the database schema at any given time (not sure that I want this).
It also means that any changes to the schema cannot be tested out locally and could affect other developers if not done right. In our environment, developers might add new tables but rarely modify existing structure. As the DBA, design fixes are done by me. But the inability to test fixes locally is my biggest hangup of the process.
How can the above process be tweaked to allow local development, while still maintaining a relatively up-to-date copy of data (as provided by replication in my proposed process)? I do not require the data to be current up to even the last week.

* By 'worked', I mean it sufficed but was a PITA.

A: Managing environments
I think you definitely don't want to be forced into a single database version.  You've got enough developers that you will inevitably have multiple development work streams, and requirements to apply patches to the current production environment independent of development workstreams.
You can use Liquibase or a manual process to produce patch scripts to upgrade versions.  I suggest starting out with a manual process and using the schema comparison tool for QA on the patches.  Clean, automated, transparent synchronisation of a nontrivially complex database is a bit utopian.
Your central data model can be kept in whatever system takes your fancy.  I've used everything from tedious enterprise repository tools to create table scripts.  Create table scripts play nicely with ordinary source control tools such as subversion and not all repository tools do a good job of versioning.
Whatever you use as your master data model repository you need a fairly clean mechanism for deploying an environment from that model.  It should be structured so that rollouts to an environment are easy.  You also need a mechanism to patch from one released version to the next.
What I've done
I've done the following in the past when I was managing development environments.  It's not particularly high tech, but it's amenable to version control and automated builds, so it makes it easy to roll out an environment to a specific version, and maitaining a large number of environments is quite practical.
Maintain a central repository: This could be a set of database creation scripts held in a version control systems, or a repository model in a data modelling tool.  Take your pick.  This model should have a build mechanism that allows an environment to be rolled out from the scripts without a lot of manual intervention.
If you have a lot of reference data you will need a load mechanism for it.  Depending on how you want to do it, you could keep this in a database or in a set of files.  The advantage of files is that they can also be versioned and labelled from the same version control system as your code base.  A bunch of CSV files and bulk loader scripts in a source control repository can do this easily enough.
One option for deploying development environments is to take backups of the production database patched to the appropriate version and make them available for devs to restore into a development environment.
Make it easy to roll out: Like any CI build process, the database should be deployable from a single script.  Set it up so that database connections can be paramaterised, or the script is location independent and can just be run through the connection.
Patch scripts: You will need roll forward and probably roll back scripts from each released version.
Build test environments from the repository model: This ensures that development on environments that are out of sync with the repository gets caught in testing.
Test the deployment process: Automated patching scripts, however they are created should be testable.  Schema comparison tools are quite good for this, even if you dont't use them to generate the patch scripts.

*

*Create a reference environment with the repository model build you tested against

*Create a smoke test environment with either a backup of your production release or a build based on the current released version.

*Run the patch script against the smoke test environment.

*Use the schema comparison tool to compare the smoke test environment with the reference environment.  The patch script should result in the two databases being identical, so you can investigate any differences.
What I like about this process
This is a bit heavyweight, and was designed for deploying into fairly bureaucratic and opaque production environments.  However, it has the following strengths:

*

*Developers can tinker where they need to.

*Multiple branches and streams of development can be accommodated.

*The deployment scripts themselves can be tested in a repeatable manner.  This is very helpful to shut down deployment bunfights, as the repeatability can be demonstrated.

*The schema comparison tools provide QA on the deployment itself.

*Testing is always done against what is expected to be released, and this will catch issues arising from environments being out of sync.

*Deployment based on repository models and patch scripts means that uncontrolled rubbish doesn't get accidentally migrated from development environments into production.

*A lot of the process can be automated, although it is often desirable to prepare and test the deployment patch scripts manually.

*Environments are cheap and easy to deploy without having to jump through hoops.

*Developers are forced to make a system that is amenable to a simple build and deployment process.

*Developers are forced to learn basic database administration tasks, but test and production environments are insulated from noob mistakes.
How it addresses your requirements

*

*Developers have local copy of data to run development code againstThe deployment scripts or DB images mean that they can set up an environment from any version that's available.

*Able to rollback database structure to a previous changesetAgain, sorted by the deployment scripts.  Either through DDL or test database backup images created through a controlled process, developers can bring up an environment to any specific version that you have.

*Able to separate new feature schema changes vs schema design fix changesPatches to a common version can be maintained in a separate fork in the svn tree.  If database backups are used as the reference environments they need to be stored somewhere with the same folder structure as the branching of the source control projects.

*Able to modify database structure locally for testingThe simple deployment process allows devs to tinker, and easily restore an environment to a local state, or bring up a reference environment to do comparisons and make change sets against.


text:
Q: Designing a high intensity flash attachment for airsoft rifle Dear readers of this community,
I've been looking into starting an electrical project and in my research I've often came across this community. Because none of the topics fully covered my question, I decided to ask a question of my own.
I play airsoft as a hobby (a team-based shooting game, similar to paintball) and many players (myself included) have a flashlight as attachment on their rifle. The thing is, this flashlight is mostly used to blind other players, instead of lighting your own path, so that got me thinking.
Would it be possible to create a capacitor-driven flash that would deliver more lumens in a fairly small/light package? I've looked into it myself and have considered the following options:

*

*modifying a camera flash

*a capacitor-driven LED

*a capacitor-driven Xenon headlight (from a car)

*a capacitor-driven flash bulb

The first option doesn't appear to be a good option, since most camera flashed don't deliver a lot of lumen or are either very pricey.
The other options would require a DIY circuit. I've been trying to design a circuit (in a program called Yenka, formerly Crocodile Physics) as I have some basic electrical knowledge (physics teacher), but not enough to confidently make the right choices.
I am therefore hoping some of you will be willing to share your wisdom on the matter. I am mainly curious as to which option seems best to you guys, and for some guidance for the circuit. One problem I've encountered is choosing a resistance for the charging circuit for the capacitor. A higher resistance results in a longer charge time and a lower charging current, but what is an acceptable current for a battery and a capacitor?
EDIT: Another thing I found regarding the LED: apparently they work better on a LED-driver. Is that a necessary component or would it work on a capacitor?
Thank you for your attention and your reply in advance!


text:
Q: How can I create a password protected .zip file in Windows 10? Winzip claims that it can create a password protected zip on Windows 10, but the Winzip installer fails part way during the installation on Win10.
https://www.winzip.com/win/en/downwz.html
Is there an alternative to Winzip?

A: Consider Total Commander, a Shareware file manager for Windows. One, out of a zillion of its features, is handling ZIP files, which also includes an option to enter an encryption key, which is used to protect a ZIP file with a password (which has to be entered whenever such file is to be unzipped.

A: You can easily create password protected archives with 7zip.

Create a password for the document, re-enter it, then change the encryption method to AES-256, then press "OK."


text:
Q: Please help me install Nvidia drivers please help and please explain it like I'm five. It's been a long time since I've done any Ubuntu computer tasks.
So I have dug out my old HP ISTART-D2314 computer.
The specs are
Memory - 1.7 GiB
Processor - Intel Pentium E2160 @ 1.80GHz
It has this Nvidia installed.
NVIDIA GeForce 7050 / NVIDIA nForce 610i
It currently has 14.04 LTS installed and it is happily using the Nvidia proprietary drivers.
I've burnt 20.04 LTS to a disc as I was planning to upgrade but when booting from the live CD the screen is pixelated and Is pretty much unusable, I can just about manage to get to the software update page but there are no proprietary drivers available.
My questions,
are my current driver's no longer supported for 20.04?
If they are how can I install what I need.
And how do I know what drivers I need?
And on another note, would 20.04 run ok on my current machine or should I just forget about the Nvidia drivers and go with something lighter like lubuntu instead?
Thanks :-)


text:
Q: FTP: Unable to connect to the remote server I have a website that I use to upload images to the server and it eventually uploads them to an FTP site from the server.  The problem is that it gets part of the way through the transfer - it transfers some of the files and then stops and gives the error
Unable to connect to the remote server

This only happens with 1 ftp server.  I have a second ftp server on which this process works fine, so I doubt it's a code issue.  What could the issue be?
thanks,
Sachin

A: Some FTP servers block flood requests, interrupting the connection. You should try using another FTP client and / or compress all the files, send to server and unzip them from the server using SSH or other method available.
Note: Recommend FileZilla client.


text:
Q: Add X-Forwarder-For HTTP header to HAProxy I use HAProxy 1.3.26 on my CentOS 5.8 to proxy all requests to a dedicated server. I use HAProxy just to proxy HTTP and HTTPS to a single server, so no load balancing.
My haproxy.cfg is rather simple:
global
        log 127.0.0.1   local0
        log 127.0.0.1   local1 notice
        maxconn 4096
        user haproxy
        group haproxy
        daemon

defaults
        log global
        option dontlognull
        option httpclose
        option forwardfor
        clitimeout 60000
        srvtimeout 60000
        contimeout 5000
        retries 3
        option redispatch

listen http 192.168.0.1:80
        mode tcp
        option tcplog
        maxconn 10000
        server web01 192.0.1.13:80 maxconn 5000

listen https 192.168.0.1:443
        mode tcp
        maxconn 10000
        server web01 192.0.1.13:443 maxconn 5000

where:
192.168.0.1 - server where HAProxy is installed
192.0.1.13  - server to which HTTP requests are forwarded

I would like to see the clients' IP addresses in my Apache 2.2.3 access logs. This option is usually achieved by adding the HTTP X-Forwarded-For header and then reading it in the web server logs. So, I've added the following lines to httpd.conf:
LogFormat "%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\"" combined
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\"" combined_forwarded
SetEnvIfNoCase X-Forwarded-For "." from_proxy=1
CustomLog logs/access_log combined env=!from_proxy
CustomLog logs/access_log combined_forwarded env=from_proxy

The problem is the only logged IP address is 192.168.0.1 (HAProxy server). I've tried different configurations, read documentation, googled but still can't understand why the clients' IPs are not logged.
I feel like I'm missing something simple, as the configs are very straightforward. Please help to correct the configs if possible.
Thank you for any help.

A: Please do not forget that this will not work for the https proxy since haproxy will not be able to mangle the contents of an encrypted session. You might also want to check the mod_rpaf module for Apache which makes all this easier.


text:
Q: Gaussian surface and and Gauss law Can we consider a cube as a Gaussian surface, for a point charge located at its center.since,Gaussian surface is a closed surface which has a constant electric field but in this case the both the magnitude and direction of electric field is changing at different points on the surface of cuboid. Can we use Gauss law for this surface in this condition.

A: Yes, any closed surface is a Gaussian surface in the sense that integrating the electric flux over it gives the charge inside the surface. The surface does not have to have a constant field strength or direction over it. However, if possible we normally choose a surface where the field strength and direction, if not constant, at least obeys a simple equation because that makes it easier to do the integral.


text:
Q: Spring AWS Elastic cache Redis session time out/TTL issue for key PRINCIPAL_NAME_INDEX_NAME Tools used:

*

*springBootVersion = '2.1.3.RELEASE'

*jdk-11.0.4

*AWS Elastic Cache -Redis

How do we kill the cache indices created by Spring default session by setting timeout (TTL) or programmatically - By default spring:session:index:org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME index is created in Redis with -1 expiry which is infinite in nature and it is eating Cache memory.
I have tried spring.cache.redis.time-to-live but it doesn't work.


text:
Q: What is the opposite of being "everything to everyone"? I think of this in the following context: when someone tries to be everything to everyone, they end up being nothing to nobody.  That of course is a double negative, but I believe expresses the intent of what I am looking for very well.  That is, you end up being the opposite of everything to everyone.  Can anyone think of a opposite that would fit well in that phrase that is gramatically correct?

A: "If you try to be everything to everyone, you end up being nothing to anyone."
About anyone, Macmillan says:

anyone, pronoun: [usually in negatives or questions] used instead of "someone" when asking or saying whether there is even one
  person

A: "Complete nobody" probably is more common as an opposite to "everything to everyone" than is  "Nothing to nobody".  Of course the logical opposites of "everything to everyone" include   "everything to nobody" and "nothing to anyone" but as noted in  Robusto's comment they don't sound as well.

A: You might consider universally underwhelming

Underwhelm: Fail to impress or make a positive impact on (someone);
  disappoint: "American voters seem underwhelmed by the choices for
  president".
Universally: By everyone; in every case: "progress is not always universally welcomed".

Universal disappointment is another that might fit, along with "unpopular disappointment" (but the latter doesn't have the same meaning as "universal").
"The President set himself out to be everything to everybody, but instead, he was a universal disappointment."
In most cases, the double negative in English is resolved into a positive. This is a case where "nothing to nobody" might be interpreted colloquially to have the meaning you are looking for. In formal writing though, it would be taken with disapproval.


text:
Q: What exatly is a REST resource and a representation? I am very new in RESTful application and I have some doubts related to some REST concept.
I know that the fundamental concept in any RESTful API is the resource. A resource is an object with a type, associated data, relationships to other resources, and a set of methods that operate on it (the HTTP methods: GET, POST, PUT and DELETE)
So my first doubt is related to the resource concept. I am trying to do myself some example and I don't know if I have correctly understand what a resource is.
In my mind a resource is "what I have to transmit with my REST web sercice". So for example if I have a REST web service that given a VAT number come backs the invoices related to this VAT number. So these returned invoices "objects" are my resources.
So a resource is something that I can working on: I can obtain an existing reourcem add a new resource, update an existing resource or delete an existing resource.
Is it correct or am I missing something?
If it correct the second doubt is on the representation concept.
From what I have understand I can see a resource in serveral differents shapes (or a resource can be exposed in several different ways), for example as HTML or as XML or as JSON and so on.
So the same resource can be exposed in different ways and exist a mecchanism that convert a resource (that can be a row stored into a database table) into an HTML message or into an XML message or into a JSON message.
Is this interpratation correct?

A: From this paragraph (emphasys mine):

In my mind a resource is "what I have to transmit with my REST web sercice". So for example if I have a REST web service that given a VAT number come backs the invoices related to this VAT number. So these returned invoices "objects" are my resources.

You got it wrong. By reviewing the concept of a resource (stated in your question, emphasys mine):

A resource is an object with a type, associated data, relationships to other resources, and a set of methods that operate on it (the HTTP methods: GET, POST, PUT and DELETE)

From your example, the invoices objects don't have any set of methods that operate them. They are part of the response of the REST service. Instead, the component (that may be a Java or a C# class) that has a method to receive the VAT number and will return the invoices associated to the VAT number and that will be called to support the proper HTTP method (in this case, GET) is the resource.
Now, after understanding this, there's this other paragraph:

From what I have understand I can see a resource in serveral differents shapes (or a resource can be exposed in several different ways), for example as HTML or as XML or as JSON and so on.

The resource will return the response in the proper format: HTML, XML, JSON, plain text, ect. Again, your invoices are not the resource, and they should not choose the format they should be returned.


text:
Q: Pointer Event/Hover change size or disable When you hover over the "related articles" section of the page - the hover effect creates a huge red box - is there a way I can make it the same size as the article preview or disable it if not?
http://insightcxo.com/5-ways-to-increase-profit-this-year/
It works fine on the homepage though:
http://insightcxo.com/
Cheers!

A: Modify your css as follows:
.related-item figure {
    background-color: #222222;
    width: 100%;
    height: auto;
    position: relative;
    background-color: #212121;
}

This will make it behave like the one's present in your homepage.


text:
Q: How has someone voted to delete a recently closed question? At the time of this writing, this question was written 57 minutes ago, closed 43 seconds ago and has already earned itself one delete vote:

According to the FAQ page about deleted questions, there's only one scenario in which posts earn delete votes: when they've been closed for more than 48 hours. So how did someone vote to delete?
Here's some good old-fashioned wild speculation:

*

*after question is closed, OP's right to delete unilaterally gets converted to the right to cast one delete vote not bound by the 48-hour timer EDIT: this guess is wrong, per that question's OP

*based on the comment and revision history, it looks like the OP deleted and then undeleted the question shortly after it was asked; this might be some kind of unintentional aftereffect of that deletion

A: That was my question. I deleted it almost immediately after the link to the duplicate was provided. I must have accidentally hit undelete on a subsequent page thinking it wasn't deleted yet.
After coming back to the site and seeing it was now marked as closed, I was unable to delete it as a message stating

To allow for possible reopneing, you
  may delete in 2 days

was showing up when I hit delete.

A: Your second guess is mostly on the spot. This is the same situation that happened here and here. Here is a related post which explains why things happen the way they do. It's not so much unintentional as it is confusing.
It has one successful delete vote, cast before the closing happened. Because that successful delete vote was in the past 2 days and the question is currently not deleted, you'll see it in the recent delete votes. There are no live delete votes on that question.


text:
Q: Using isset from a name of an input I am not sure if I am going about this correctly. I have a set of checkbox inputs. If someone selects the last check box all_users_check, I want a new form to appear where I will be listing all of the users in a drop down (haven't added the drop down yet). I thought I could do this by using the name of the input, but I am mistaken apparently as I am getting this error..
How else could I structure what I am doing so that if someone checks that option the new form displays?

<form action="">
  <input type="checkbox" name="spectator_check" value=""> Spectators

  <input type="checkbox" name="member_check" value="" checked> Team Members

  <input type="checkbox" name="commissioner_check" value="" checked> Commissioner(s)

  <input type="checkbox" name="all_users_check" value="" checked> Individual User

</form>

This is how the page looks on load. Those fields are already checked for some reason.

A: isset is a language construct and can't accept anything other than a variable as indicated by this warning on the linked to manual page:

Warning isset() only works with variables as passing anything else will result in a parse error.

You are not passing in a variable to the isset function, you are passing in a constant value, basically an array with a single string all_users_check.  This is not a variable because you are not assigning it to a variable name.  Try this instead:
if(isset($_POST['all_users_check']))

Here the variable being passed in is the superglobal $_POST, and you are checking to see if the index all_users_check is set inside of that array.
Update
To check if an input is empty or not via javascript, take a look at this question.

A: Issues in your code.

*

*.all_users_check that is looking for a class. Your element doesn't have a class so this isn't found. You can use a different selector to use the name attribute, https://api.jquery.com/attribute-equals-selector/.

*This $(".user_dropdown").hide(); hides your whole form. You might want to move around your divs, or remove that altogether.

*The checked attribute checks the field it is on. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input

Use the checked attribute to indicate whether this item is selected

<form>
  <input type="checkbox" name="spectator_check" value=""> Spectators

  <input type="checkbox" name="member_check" value=""> Team Members

  <input type="checkbox" name="commissioner_check" value=""> Commissioner(s)

  <input type="checkbox" name="all_users_check" value=""> Individual User

</form>

A: Try using this script, you have set the state of check boxes as checked by default.

<form action="">
  <input type="checkbox" name="spectator_check" value=""> Spectators

  <input type="checkbox" name="member_check" value=""> Team Members

  <input type="checkbox" name="commissioner_check" value=""> Commissioner(s)

  <input type="checkbox" name="all_users_check" value="" > Individual User

</form>

For the other issue of showing the hidden section again, try whether class all_users_check is visible to click.


text:
Q: SQL Temp table Array to perfrom rolling caluclations I wish to use some sort of SQL array to subtract values from a certain row (QTYOnHand) that decreases that row value every time and throws it into a rolling calculation for the other rows. I've been thinking of some sort of Self Join/Temp Table solution, but not sure how to formulate. Also, All the results will be partitioned by the ItemID below. Help would be appreciated.
Here's some data, If I do a simple row by row subtraction I will get this: 17-3 = 14, 17-5 = 12 and so on.
(Item_ID)  (ItemQty) (QTYOnHand)  (QtyOnHand - ItemQty)
123         3        17              14
123         5        17              12
123         4        17              13
456         7        12              5
456         8        12              4
456         2        12              10
456         3        12              9
789         2        6               4
789         2        6               4
789         2        6               4

These are the results that I want, where I subtract every next value from the new QTYOnHand-ItemQty column value. Looks like 17-3 then 14 -5 then 9 -4 for Item_ID (123):
(Item_ID)  (ItemQty)  (QTYOnHand)   (QtyOnHand - ItemQty)
123         3        17              14
123         5        17              9
123         4        17              5
456         7        12              5
456         8        12              -3
456         2        12              -5
456         3        12              -8
789         2        6               4
789         2        6               2
789         2        6               0

A: try the following:
;with cte as
(
    select *, ROW_NUMBER() over (partition by Item_ID order by Item_ID) rn
    from YourTable
)
, cte2 as
(
    select Item_ID, ItemQty, QTYOnHand, Case when rn = 1 then QTYOnHand else 0 end - ItemQty as calc, rn
    from cte
)
select Item_ID, ItemQty, QTYOnHand, sum(calc) over (partition by Item_ID order by rn) as [QtyOnHand - ItemQty]
from cte2 t1

Please find the db<>fiddle here.


text:
Q: Save after Edit code improvements I'm working on a simple application and am looking to get my head around the CodeFirst EF approach. So far so good.
I have managed to get Create and delete sorted and have got edit working. The thing is I think the edit code could be improved; I'm just not sure how. So here it is:
 public ActionResult Edit(int id, CreateResourceViewModel model)
        {
            if (ModelState.IsValid)
            {
                // save the changes
                //UpdateModel(model.Resource);
                //resourceAdminManager.SaveChanges();

                Resource current = resourceAdminManager.Resources.Find(id);
                current.ResourceTypeID = model.Resource.ResourceTypeID;
                current.Name = model.Resource.Name;
                current.Description = model.Resource.Description;
                current.Email = model.Resource.Email;
                current.TurnAroundTime = model.Resource.TurnAroundTime;

                resourceAdminManager.SaveChanges();

                return RedirectToAction("Index");
            }
            else
            {
                return View(model);
            }
        }

I know there is no exception handling around this, which I need to address but my main concern is the fact that I have manually updated the model. My concerns are:
1. This is in the controller
2. This is hard coded and so any changes to the model will require a re-work of code
Can someone suggest a better way of doing this please.
Many thanks
Nathan
So following on from the AutoMapper suggestions:
This is very helpful and I've started to play with this. I'm running into a little trouble with it.
The contoller now looks like:
if (ModelState.IsValid)
            {
                try
                {
                    var current = resourceAdminManager.Resources.Find(id);
                    current = Mapper.Map<CreateResourceViewModel, Resource>(model);
                    resourceAdminManager.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch (Exception exc)
                {
                    ModelState.AddModelError("Error", exc); // or, use a generic error.
                }
            }

            return View(model);

The error occurs in the view when I click save. I get null exception on the following:
<%: Html.DropDownListFor(model => model.Resource.ResourceTypeID, new SelectList(Model.ResourceTypes, "ResourceTypeId", "Title"), "-- Select Resource Type --")%>

Any ideas on what I may be missing here?

A: You are using ViewModel which is very good practise.
1] For Exception handling will suggest to inherit your Controller
from your custom "BaseControllor" instead of System.Web.Mvc.Controller
public class YourController : BaseController

In "BaseControllor" override OnException so that all excptions across your Controllor Actions will be catch in it.
public class BaseController: Controller
{

    protected override void OnException(ExceptionContext filterContext)
    {
        base.OnException(filterContext);
    }

}
2] You need to refactor your "Save" code into differnt class in same project or differnt project and differnt Class
3] Yes for any Changes in model you would need to make changes in  viewmodel, and in your save logic

A: One word: AutoMapper.
Will turn those 5 left-to-right boilerplate lines into one.
One of the best MVC (well, C#) add-on's i've ever found.
If implemented correctly (i think your ViewModel may need to change a tad), your action will look like this:
public ActionResult Edit(int id, CreateResourceViewModel model)
{
   if (ModelState.IsValid)
   {
      try
      {
         var current = resourceAdminManager.Resources.Find(id);
         current = Mapper.Map<CreateResourceViewModel,Resource>(model);
         resourceAdminManager.SaveChanges();
         return RedirectToAction("Index");
      }
      catch (Exception exc)
      {
         ModelState.AddModelError("Error", exc); // or, use a generic error.
      }
   }

   return View(model);

}

A warning: this will basically replace the entire entity. So if you only want certain fields changed, only include those in the ViewModel, so the other's will be unchanged. You can also specify "Ignore" in AutoMapper so those fields won't get touched.
And to address your concerns:

*

*This is in the controller

Well actually, it should be. In fact, that's the controllers job - updating the model.
The fact you have boilerplate L-R code is bad, which is why AutoMapper helps.

*

*This is hard coded and so any changes to the model will require a re-work of code

Yup, again - AutoMapper solves this. It works on convention (like MVC), so if you have a proeprty in the ViewModel with the same name as the target model (domain object), you won't have to explicitly map -> it will just work. Furthermore, the mapping is a single static class, so it can be easily maintained.


text:
Q: How to add insert tab to the insert/edit image plugin in the tinyMCE to insert image from the desktop? I am using TinyMCE plugin, but for the insert/edit image plugin, it doesn't allow me to add an image from the desktop.
I don't want image to upload on the server but want to display in the editor, so i want to add an image insert in the insert/image plugin.
How can i achive this.
While this thing can be done in the on line tinyMCE editor's demo.
please help me with this, please gimme some guide lines or credible links to achieve this.

A: If you're looking for a cost-free way to upload files from your own computer (which I assume is what you mean by desktop) you can use http://www.phpletter.com/Demo/Tinymce-Ajax-File-Manager/ to achieve this. I have successfully integrated this in my own envirnonment almost hassle-free (which any other free plugin couldn't achieve ;)). Their own solution is propietary (I think), but Ajax File Manager works just as good.
I use it for PHP but I think supports ASP also.
EDIT: Looks like it doesn't support ASP after all :|


text:
Q: Stripe - Radar Rules Hope you are doing well.
I am going through the following documentation of Stripe "https://stripe.com/docs/radar/radar-session". In the following page it is mentioned We have to create Radar session at client side and send it your server and after that we have to send from server to stripe. So my question is where we have to define rules (Block if :card_country: = 'CA' OR :card_country: = 'DE' OR :card_country: = 'AE') at client side or server side?

A: You create the rules in your Stripe account's dashboard, not through code neither on the front or backend. https://dashboard.stripe.com/test/radar/rules


text:
Q: CSS- Why this doesn't work? I have a CSS Class:
.ImageBorder
{
border-style:solid; border-color:Black;
}

I then set the CSS Class to an asp.net Image:
<asp:Image ID="Image3" runat="server" Height="150px"
                ImageUrl="~/Photos/defaultA.jpg" CssClass="ImageBorder"  />

But it doesn't work.  It will work if I put the image in a div tag and then set the divs css class, but I'd rather not do this?  What gives?

A: Try giving the border a width:
border: 1px solid black;

A: As noted in other answers, you should specify the border-width. You may experience an additional "gotcha", though: asp images may have a "border-width:0" inline styling. In which case, your rule would need the !important declaration to override it:
.ImageBorder
{
border: 1px solid black !important;
}

The !important declaration ignores the normal rules of precedence that CSS follows. Normally, inline styling takes precedence over embedded or external style sheets, which take precedence over the user agent's styling. An important property will take precedence over all non-important properties, regardless of where it is declared.
Using !important can lead to some frustration, however. Suppose you wanted to have an image with all the same qualities as your ImageBorder images, but with a width of 100. You might write
<img src="superBorderedImage.png" class="ImageBorder" style="border-width:100"/>

... But this will not work. You specified with great importance that ImageBorder images have width 1, so your "super bordered image" won't have its special thick border. For this reason, you should use !important only when you're certain you won't need to override it later for special cases.

A: As noted by David, you're not specifying any width for your border, which means it has no width and consequently, you can't see it.
You can use the shorthand:
.ImageBorder
{
    border: 1px solid black;
}

or the longhand way:
.ImageBorder
{
    border-style: solid;
    border-color: Black;
    border-width: 1px;
}


text:
Q: breakout collision detection I'm coding a Breakout game with Javascript. I took the MDN tutorial and another tutorial and I'm trying to modify the original with a OOP approach. Until now, everything works fine except for the collision detection with the paddle. Which is not happening. Why is that? Here's my code. Can somebody help? Thanks!

var canvas = document.getElementById('game');
var theLoop;
var paddleSpeed = 4;

//OBJECTS
//Game
function Game() {
  this.width = canvas.width;
  this.height = canvas.height;
  this.ctx = canvas.getContext('2d');
  this.ctx.fillStyle = "white";
  this.p = new Paddle(0, 130);
  this.p.x = (this.width - this.p.width) / 2;
  this.keys = new Keylistener();
  this.ball = new Ball();
  this.ball.x = this.width / 2;
  this.ball.y = 125;
  this.ball.vy = Math.floor(Math.random() * 12 - 6);
  this.ball.vx = 7 - Math.abs(this.ball.vy);
}

Game.prototype.draw = function() {
  this.ctx.clearRect(0, 0, this.width, this.height);
  this.p.draw(this.ctx);
  this.ball.draw(this.ctx);
};

Game.prototype.update = function() {
  if (this.paused) return;
  this.ball.update();
  //Right Paddle's Directions
  if (this.keys.isPressed(37)) { // LEFT
    this.p.x = Math.max(0, this.p.x - paddleSpeed);
  } else if (this.keys.isPressed(39)) { // RIGHT

    this.p.x = Math.min(this.p.x + paddleSpeed, this.width - this.p.width);
  }

  if (this.ball.x < this.ball.ballRadius || this.ball.x > this.width - this.ball.ballRadius) { //LEFT & RIGHT
    this.ball.vx = -this.ball.vx;
  }
  if (this.ball.y < this.ball.ballRadius) { //TOP
    this.ball.vy = -this.ball.vy;
  } else if (this.ball.y > this.height - this.ball.ballRadius) {
    if (this.ball.x > this.p.x && this.ball.x < this.p.x + this.p.width) {
      this.ball.vy = -this.ball.vy;
      console.log('hit');
    } else {
      //      console.log(this.ball.x);
    }
  }
};

/////Paddle
function Paddle(x, y) {
  this.x = x;
  this.y = y;
  this.width = 30;
  this.height = 5;
  this.score = 0;
}

Paddle.prototype.draw = function(p) {
  p.fillRect(this.x, this.y, this.width, this.height);
};

///KEY LISTENER
function Keylistener() {
  this.pressedKeys = [];
  this.keydown = function(e) {
    this.pressedKeys[e.keyCode] = true;
  };
  this.keyup = function(e) {
    this.pressedKeys[e.keyCode] = false;
  };
  document.addEventListener("keydown", this.keydown.bind(this));
  document.addEventListener("keyup", this.keyup.bind(this));
}

Keylistener.prototype.isPressed = function(key) {
  return this.pressedKeys[key] ? true : false;
};

Keylistener.prototype.addKeyPressListener = function(keyCode, callback) {
  document.addEventListener("keypress", function(e) {
    if (e.keyCode == keyCode) callback(e);
  });
};

///BALL
function Ball() {
  this.x = 0;
  this.y = 0;
  this.vx = 0;
  this.vy = 0;
  this.ballRadius = 5;
}

Ball.prototype.update = function() {
  this.x += this.vx;
  this.y += this.vy;
};

Ball.prototype.draw = function(p) {
  p.beginPath();
  p.arc(this.x, this.y, this.ballRadius, 0, Math.PI * 2, false);
  p.fill();
  p.closePath();
};

//Initialize the game
var game = new Game();

//the Main Engine
function mainLoop() {
  theLoop = setInterval(function() {
    game.update();
    game.draw();
  }, 33.3333);
}

//calling the Main Engine
mainLoop();
#game {
  width: 800px;
  height: 400px;
  background-color: #353535;
}
<canvas id="game"></canvas>

A: Your problem is this section right here.
else if (this.ball.y > this.height - this.ball.ballRadius) {
    if (this.ball.x > this.p.x && this.ball.x < this.p.x + this.p.width) {

You aren't trying to register a hit with the paddle unless the ball is at the bottom of the screen. You need to be checking if the ball intersects with the paddle before you hit the bottom of the screen.
var paddleLeft = this.p.x;
var paddleRight = paddleLeft + this.p.width;
var paddleTop = this.p.y;
var ballLeft = this.ball.x;
var ballRight = ballLeft + this.ball.ballRadius;
var ballBottom = this.ball.y + this.ball.ballRadius;
var xCollision = (ballLeft <= paddleRight && ballRight >= paddleLeft);
var yCollision = (ballBottom >= paddleTop);
if (this.ball.y < this.ball.ballRadius) { //TOP
  this.ball.vy = -this.ball.vy;
} else if (xCollision && yCollision) {
  this.ball.vy = -this.ball.vy;
  console.log('hit');
}

Here it is running in your game.

var canvas = document.getElementById('game');
var theLoop;
var paddleSpeed = 4;

//OBJECTS
//Game
function Game() {
  this.width = canvas.width;
  this.height = canvas.height;
  this.ctx = canvas.getContext('2d');
  this.ctx.fillStyle = "white";
  this.p = new Paddle(0, 220);
  this.p.x = (this.width - this.p.width) / 2;
  this.keys = new Keylistener();
  this.ball = new Ball();
  this.ball.x = this.width / 2;
  this.ball.y = 125;
  this.ball.vy = Math.floor(Math.random() * 12 - 6);
  this.ball.vx = 7 - Math.abs(this.ball.vy);
}

Game.prototype.draw = function() {
  this.ctx.clearRect(0, 0, this.width, this.height);
  this.p.draw(this.ctx);
  this.ball.draw(this.ctx);
};

Game.prototype.update = function() {
  if (this.paused) return;
  this.ball.update();
  //Right Paddle's Directions
  if (this.keys.isPressed(37)) { // LEFT
    this.p.x = Math.max(0, this.p.x - paddleSpeed);
  } else if (this.keys.isPressed(39)) { // RIGHT

    this.p.x = Math.min(this.p.x + paddleSpeed, this.width - this.p.width);
  }

  var leftBallCollision = this.ball.x < this.ball.ballRadius;
  var rightBallCollision = this.ball.x > this.width - this.ball.ballRadius;
  if (leftBallCollision || rightBallCollision) { //LEFT & RIGHT
    this.ball.vx = -this.ball.vx;
  }

  var paddleLeft = this.p.x;
  var paddleRight = paddleLeft + this.p.width;
  var paddleTop = this.p.y;
  var ballLeft = this.ball.x;
  var ballRight = ballLeft + this.ball.ballRadius;
  var ballBottom = this.ball.y + this.ball.ballRadius;
  var xCollision = (ballLeft <= paddleRight && ballRight >= paddleLeft);
  var yCollision = (ballBottom >= paddleTop);
  if (this.ball.y < this.ball.ballRadius) { //TOP
    this.ball.vy = -this.ball.vy;
  } else if (xCollision && yCollision) {
    this.ball.vy = -this.ball.vy;
    console.log('hit');
  }
};

/////Paddle
function Paddle(x, y) {
  this.x = x;
  this.y = y;
  this.width = 30;
  this.height = 5;
  this.score = 0;
}

Paddle.prototype.draw = function(p) {
  p.fillRect(this.x, this.y, this.width, this.height);
};

///KEY LISTENER
function Keylistener() {
  this.pressedKeys = [];
  this.keydown = function(e) {
    this.pressedKeys[e.keyCode] = true;
  };
  this.keyup = function(e) {
    this.pressedKeys[e.keyCode] = false;
  };
  document.addEventListener("keydown", this.keydown.bind(this));
  document.addEventListener("keyup", this.keyup.bind(this));
}

Keylistener.prototype.isPressed = function(key) {
  return this.pressedKeys[key] ? true : false;
};

Keylistener.prototype.addKeyPressListener = function(keyCode, callback) {
  document.addEventListener("keypress", function(e) {
    if (e.keyCode == keyCode) callback(e);
  });
};

///BALL
function Ball() {
  this.x = 0;
  this.y = 0;
  this.vx = 0;
  this.vy = 0;
  this.ballRadius = 5;
}

Ball.prototype.update = function() {
  this.x += this.vx;
  this.y += this.vy;
};

Ball.prototype.draw = function(p) {
  p.beginPath();
  p.arc(this.x, this.y, this.ballRadius, 0, Math.PI * 2, false);
  p.fill();
  p.closePath();
};

//Initialize the game
var game = new Game();

//the Main Engine
function mainLoop() {
  theLoop = setInterval(function() {
    game.update();
    game.draw();
  }, 33.3333);
}

//calling the Main Engine
mainLoop();
#game {
  background-color: #353535;
}
<canvas id="game" width="320" height="240"></canvas>

A:

var canvas = document.getElementById('game');
var theLoop;
var paddleSpeed = 4;

//OBJECTS
//Game
function Game() {
  this.width = canvas.width;
  this.height = canvas.height;
  this.ctx = canvas.getContext('2d');
  this.ctx.fillStyle = "white";
  this.p = new Paddle(0, 130);
  this.p.x = (this.width - this.p.width) / 2;
  this.keys = new Keylistener();
  this.ball = new Ball();
  this.ball.x = this.width / 2;
  this.ball.y = 125;
  this.ball.vy = Math.floor(Math.random() * 12 - 6);
  this.ball.vx = 7 - Math.abs(this.ball.vy);
}

Game.prototype.draw = function() {
  this.ctx.clearRect(0, 0, this.width, this.height);
  this.p.draw(this.ctx);
  this.ball.draw(this.ctx);
};

Game.prototype.update = function() {
  if (this.paused) return;
  this.ball.update();
  //Right Paddle's Directions
  if (this.keys.isPressed(37)) { // LEFT
    this.p.x = Math.max(0, this.p.x - paddleSpeed);
  } else if (this.keys.isPressed(39)) { // RIGHT

    this.p.x = Math.min(this.p.x + paddleSpeed, this.width - this.p.width);
  }

  if (this.ball.x < this.ball.ballRadius || this.ball.x > this.width - this.ball.ballRadius) { //LEFT & RIGHT
    this.ball.vx = -this.ball.vx;
  }
  if (this.ball.y < this.ball.ballRadius) { //TOP
    this.ball.vy = -this.ball.vy;
  } else if (this.ball.y > this.p.y - this.ball.ballRadius &&
            this.ball.y < this.p.y + this.p.height + this.ball.ballRadius) {

   if (this.ball.x > this.p.x && this.ball.x < this.p.x + this.p.width) {
      this.ball.vy = -this.ball.vy;
      console.log('hit');
    } else {
      //      console.log(this.ball.x);
    }
  }
};

/////Paddle
function Paddle(x, y) {
  this.x = x;
  this.y = y;
  this.width = 30;
  this.height = 5;
  this.score = 0;
}

Paddle.prototype.draw = function(p) {
  p.fillRect(this.x, this.y, this.width, this.height);
};

///KEY LISTENER
function Keylistener() {
  this.pressedKeys = [];
  this.keydown = function(e) {
    this.pressedKeys[e.keyCode] = true;
  };
  this.keyup = function(e) {
    this.pressedKeys[e.keyCode] = false;
  };
  document.addEventListener("keydown", this.keydown.bind(this));
  document.addEventListener("keyup", this.keyup.bind(this));
}

Keylistener.prototype.isPressed = function(key) {
  return this.pressedKeys[key] ? true : false;
};

Keylistener.prototype.addKeyPressListener = function(keyCode, callback) {
  document.addEventListener("keypress", function(e) {
    if (e.keyCode == keyCode) callback(e);
  });
};

///BALL
function Ball() {
  this.x = 0;
  this.y = 0;
  this.vx = 0;
  this.vy = 0;
  this.ballRadius = 5;
}

Ball.prototype.update = function() {
  this.x += this.vx;
  this.y += this.vy;
};

Ball.prototype.draw = function(p) {
  p.beginPath();
  p.arc(this.x, this.y, this.ballRadius, 0, Math.PI * 2, false);
  p.fill();
  p.closePath();
};

//Initialize the game
var game = new Game();

//the Main Engine
function mainLoop() {
  theLoop = setInterval(function() {
    game.update();
    game.draw();
  }, 33.3333);
}

//calling the Main Engine
mainLoop();
#game {
  width: 800px;
  height: 400px;
  background-color: #353535;
}
<canvas id="game"></canvas>


text:
Q: Should I refer std::vector size when the number is explicitly given I'm coding a simple function using std::vector below where input is an integer vector and the function proceeds the iteration based on the number of elements in the vector.
In terms of space and time efficiency, which following code are suitable?
HugeClass is actually a Big Integer which contains complex arithmetic while I put a simple arithmetic below for simplicity.
1) Gives a dimension of vector
void (HugeClass& huge, std::vector<int>& vec, int dim){
    for(int i=0;i<dim;i++){
        huge+=vec[i];
    }
}

2) Calls a std::vector.size() to iterate
void (HugeClass& huge, std::vector<int>& vec){
    for(int i=0;i<vec.size();i++){
        huge+=vec[i];
    }
}

dim can range in [100,1000000]

A: The syntax of a for loop in C++ is:
for ( init; condition; increment ) {
   statement(s);
}

Here is the flow of control in a for loop:

*

*The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

*Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.

*After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
So in the case of
for(int i=0;i<vec.size();i++) {
        huge+=vec[i];
}

vec.size() called each time but is probably inlined, and is probably a simple function.
On top of which
A smart enough optimizer may be able to deduce that it is a loop invariant with no side effects and elide it entirely (this is easier if the code is inlined, but may be possible even if it is not if the compiler does global optimization)


text:
Q: OS X mysql cannot connect ERROR 2002 (HY000) after installing pear package. Using XAMPP I installed the PEAR ImageGraph module as follows:
pear install Image_Graph-alpha
This command came from the github page
Now when I try to connect to MySql I get the following message:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock' (2)

I am using XAMPP and OS X Mavericks.
Any advice? I would hate to have to reinstall everything.

A: I can't see how there can be any link between installing ImageGraph and you suddenly not being able to connect to MySQL.
Judging from your question, it seems that you did not make any project specific changes, perhaps you did some system upgrades recently? That would more easily explain the sudden inability to connect.
Speaking of mysql and upgrades, you should be using the mysqli or pdo extensions as the [original] mysql one is deprecated and support for it may be removed in PHP7. More information on this can be read on the PHP The Right Way site. If you do this now you should have fewer surprises later on.

A: OK finally determined that the update to OS X was what broke MySql and prevented me from connecting to MySql. Had to backup files and then reinstall MySql.


text:
Q: Validation is showing in Start time and end time but it is not showing in Break start and Break end See the code below
function chk_submit_all()
{
  var frm = document.add_advert;
  if (frm.avl_after.value.search(/\S/) == '-1')
  {
     document.getElementById('error_avl_after').innerHTML = 'Please choose date, you are available on or after';
     frm.avl_after.focus();
     return false;
  }
  else
  {
     document.getElementById('error_avl_after').innerHTML = '';
  }
  var count_all = 0;
  $('input:checkbox.choose_days').each(function (index, element )
  {
     if (this.checked == true)
     {
         var strt_time = $(this).val();
         var strt_val = $('#start_time_'+strt_time).val();
         var startTime = new Date().setHours(GetHours(strt_val), GetMinutes(strt_val), 0);

         if ($('#start_time_'+strt_time).val() == '')
         {
             document.getElementById('error_avl_day_time').innerHTML = 'Please choose start time';
             breakOut = true;
           //alert('Please choose start time');
         }
         else
         {
                var end_time = $('#end_time_'+strt_time).val();
                var endTime = new Date(startTime)
                endTime = endTime.setHours(GetHours(end_time), GetMinutes(end_time), 0);
                if (endTime <= startTime)
                {
                   document.getElementById('error_avl_day_time').innerHTML = 'end time should be higher than start time';
                  //  alert('end time should be higher than start time');
                     breakOut = true;

                }
                else
                {

Else part is not working
please have a look where i have done wrong.
Not entering else part
Validation is showing in Start time and end time but it is not showing in Break start and Break end
 //alert ('hii'); die;
                    // alert($('#radio-'+strt_time+'-brk').val()); die;
                    if ($('#radio-'+strt_time+'-brk').checked == true)
                    {
                        alert ('hii'); exit;
                         var brk_strt_time_val = $('#break_time_start_'+strt_time).val();
                         var brk_strt_time = new Date().setHours(GetHours(brk_strt_time_val), GetMinutes(brk_strt_time_val), 0);
                         if ((brk_strt_time > strt_time) && (brk_strt_time < end_time))
                         {
                            //alert (hiii);die;
                            var brk_end_time_val = $('#break_time_end_'+strt_time).val();
                            var brk_end_time = new Date().setHours(GetHours(brk_end_time_val), GetMinutes(brk_end_time_val), 0);
                            if (brk_strt_time >= brk_end_time)
                            {
                                //alert('break end time should be higher than break start time'); die;
                                document.getElementById('error_avl_day_time').innerHTML = 'break end time should be higher than break start time';
                                //alert('break end time should be higher than break start time');
                                breakOut = true;
                            }
                            else
                            {
                                count_all++;
                            }
                        }
                    }
                    else
                    {
                        count_all++;
                    }
               }

        }
     }

   });

  if (count_all == 0)
  {
    document.getElementById('error_avl_day_time').innerHTML = 'Please choose day with time';
    return false;
  }
  else
  {
     if(breakOut)
     {
        breakOut = false;
        return false;
     }
     else
     {
        document.getElementById('error_avl_day_time').innerHTML = '';
     }

  }

}

A: This is the answer Coders
function chk_submit_all()
{
   var frm = document.add_advert;
   if (frm.avl_after.value.search(/\S/) == '-1')
   {
      document.getElementById('error_avl_after').innerHTML = 'Please choose date, you are available on or after';
      frm.avl_after.focus();
      return false;
   }
   else
   {
      document.getElementById('error_avl_after').innerHTML = '';
   }
   var flag=0;
   var count=0;
   var start_time = document.getElementsByName('days_val[]');
   var len = start_time.length;
   for(i=0;i<len;i++){
      if(start_time[i].checked){
         var strt_time = start_time[i].value;
         var strt_val = $('#start_time_'+strt_time).val();
         var end_val = $('#end_time_'+strt_time).val();
         if (strt_val=='') {
            document.getElementById('error_avl_day_time').innerHTML = 'Please choose a Start time';
            flag=1;
            break;
         }
         else
         {
            if (strt_val>=end_val) {
               document.getElementById('error_avl_day_time').innerHTML = 'End Time Must be greater than Start Time';
               flag=1;
               break;
            }
            else{
               if ($('#radio-'+strt_time+'-brk').is(':checked'))
               {
                  var brk_strt_time_val = $('#break_time_start_'+strt_time).val();
                  var brk_end_time_val = $('#break_time_end_'+strt_time).val();
                  if ((brk_strt_time_val=='') || (brk_end_time_val=='')) {
                     document.getElementById('error_avl_day_time').innerHTML = 'Please Choose Valid Break Time';
                     flag=1;
                     break;
                  }
                  else
                  {
                     if ((brk_strt_time_val=='00:00') || (brk_end_time_val=='00:00')) {
                        document.getElementById('error_avl_day_time').innerHTML = 'Please Choose Valid Break Start/End Time';
                        flag=1;
                        break;
                     }
                     else{
                        if (((brk_strt_time_val <= strt_val) || (brk_strt_time_val >= end_val))|| ((brk_end_time_val <= strt_val) || (brk_end_time_val >= end_val))) {
                           document.getElementById('error_avl_day_time').innerHTML = 'Break Start/End Must be within Start time and End Time';
                           flag=1;
                           break;
                        }
                        else
                        {
                           if (brk_strt_time_val>=brk_end_time_val) {
                              document.getElementById('error_avl_day_time').innerHTML = 'Break End time Must be greater than Break Start Time';
                              flag=1;
                              break;
                           }
                        }
                     }
                  }
               }
            }
         }
         count++;
      }
   }
   if (count==0 && flag==0) {
      document.getElementById('error_avl_day_time').innerHTML = 'Pleas Choose Atleast One Time Slot';
      return false;
   }
   else{
      if (flag==1) {
         return false;
      }
      else
      {
         document.getElementById('error_avl_day_time').innerHTML = '';
      }
   }
}


text:
Q: GCM response results is not having "Not Registered IDS" list I am using curl to send push notifications using GCM. Here it is as follows:
curl --header 'Authorization: key=myAPiKey' --header 'Content-Type: application/json' https://android.googleapis.com/gcm/send -d '{"registration_ids":["registration_ids"], "collapse_key": "Turn", "data": { "title": "fdsfdsfsdfd","body": "fdsf dsf sd fsd fds fds fds", "badge": "1" , "content_available": 1 ,"url": "#/app/home"} }'

In reposnse I am getting as :
{"multicast_id":7729772425353298779,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}

I am not getting registration_ids that are not registered. How Can I do this. I want this in curl only as i am using ruby 1.8.6 application.
Please help me on this


text:
Q: Txt file close around 10000 lines of input I have written txt-files with excel and a macro in the past several times. I didn't hit 10000 lines or more. Never say Never...
My .csv file has over 87000 rows like that example "15k50,CityABC,56ab,CountryofCity,ID,Street". I use the Split() function in order to separate the values. The Macro formated and wrote the values as single lines to the txt file.
Around 9800 lines the txt-file closed... But why? I tried with Slepp() to make sure the print algho isn't overloaded or something else.
The counter 10000 is there because I want to make it easer to understand for you. If it goes over 10000 the problem is "solved".
Information txt-File format:

*

*ASCII

*Unix (LF)

Shortcut, after several comments

*

*with Minimal, Reproducible Example overworked the code (deleted sleep, simplification variable names, try to make code from scratch)

*changed SplitString() to Split(), because call over function is stupid...

*after printed line 9000 to the txt-file the following error popup "Run-Time Error 5: Invalid Procedure Call or Argument" at code line fso.WriteLine ("#  " & strArr(0) & "  #  " & strArr(1) & ...
Option Explicit

#If VBA7 Then
 Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
#Else
 Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems
#End If

Sub formattedToTxt()

Dim strArr() As String
Dim strB As String
Dim intC As Integer

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")

strB = filePathExport & "\" & filenameExport & fileFormatExport
Set fso = fso.CreateTextFile(strB, True)

Do While counter <= 10000
    strArr = Split(ActiveCell.Value, ",")
    intC = CalcWhitespace(strArr(5), 40)
    fso.WriteLine ("#  " & strArr(0) & "  #  " & strArr(1) & "  # " & strArr(2) & " # " & strArr(3) & "  # " & strArr(4) & " # " & strArr(5) & Space(intC) & "#")
    ActiveCell.Offset(1, 0).Select
    If ((counter Mod 1000) = 0) Then
        Debug.Print ("Entry " & counter & " written")
    End If
    counter = counter + 1
Loop

End Sub

Function CalcWhitespace(rawStr As String, maxLen As Integer) As Integer
    CalcWhitespace = maxLen - Len(rawStr)
End Function

Any Idea?

A: Thanks to all helpful VBA people from the comments above. I cleaned up the code. The following snipped is the full solution.
The .csv table contains diffrent strings with diffrent length in each line.
In the final solution the whitespaces are checked before. It is importend to know the max-Length strings at the data. To format the txt-file output readable.
Maybe, an other solution has a better performance, but that works well in my case.
Have a great day!
'Find max string length for each whitespace
counter = 0
ActiveSheet.Cells(2, 1).Select   'ignore Headlinedata, because diffrent format in compare to data
intC = (UBound(arrWhitespace) - LBound(arrWhitespace))
Do While ActiveCell.Value <> ""
    strArr = Split(ActiveCell.Value, ",")
    For counterTwo = 0 To intC
        If Len(strArr(counterTwo)) > arrWhitespace(counterTwo) Then arrWhitespace(counterTwo) = Len(strTempArr(counterTwo))
    Next counterTwo
    counter = counter + 1
    ActiveCell.Offset(1, 0).Select
    If ((counter Mod 1000) = 0) Then
        Debug.Print ("Entry " & counter & " checked")
    End If
Loop

'Print Body of txt-file
Do While ActiveCell.Value <> ""
    strArr = Split(ActiveCell.Value, ",")

    'build string for each line
    strB = ""
    strB = strB & "#  " & strArr(0) & "  #"
    intC = CalcWhitespace(strArr(1), arrWhitespace(1))
    strB = strB & "  " & strArr(1) & Space(intC) & "  #"
    intC = CalcWhitespace(strArr(2), arrWhitespace(2))
    strB = strB & " " & strArr(2) & Space(intC) & " #"
    intC = CalcWhitespace(strArr(3), arrWhitespace(3))
    strB = strB & " " & strArr(3) & Space(intC) & "  #"
    intC = CalcWhitespace(strArr(4), arrWhitespace(4))
    strB = strB & " " & strArr(4) & Space(intC) & " #"
    intC = CalcWhitespace(strArr(5), arrWhitespace(5))
    strB = strB & " " & strArr(5) & Space(intC) & "  #"
    fso.WriteLine (strB)
    ActiveCell.Offset(1, 0).Select
    If ((counter Mod 1000) = 0) Then
        Debug.Print ("Entry " & counter & " written")
    End If
    counter = counter + 1
Loop

Function CalcWhitespace(rawStr As String, maxLen As Integer) As Integer
    CalcWhitespace = maxLen - Len(rawStr)
End Function

Next time I will use minimal-reproducible-example to avoid .Select


text:
Q: React native react-native-paper button with greater height
I'm using react-native-paper, I would like to make a button with bigger dimensions than normal, as seen in the gif.
I've tried using both height and padding, but both don't work properly.
What you see in the gif is the example with padding.
only way to click is in the center, in other places the event does not happen.
Can you give me a hand?
<Button
          mode="contained"
          labelStyle={{ color: Colors.white }}
          style={{ padding: 30 }}
          onPress={() => console.log('Pressed')}>
          Start
        </Button>

A: YOU CAN USE
contentStyle

EXAMPLE
<Button
  onPress={() => {}}
  style={styles.completeFormButton}
  styleText={styles.completeFormButtonText}
  contentStyle={{ // <--- HERE-----
    paddingVertical: 10,
  }}
  preset="outlined"
/>

react-native-papper has these three props to pass styles
contentStyle
Type: StyleProp
Style of button's inner content. Use this prop to apply custom height and width and to set the icon on the right with flexDirection: 'row-reverse'.
style
Type: StyleProp
labelStyle
Type: StyleProp
Style for the button text.
View documentation react native paper

A: you can create a touchablehighlight view around the button and call the same onPress function. something like this:
<TouchableHighlight onPress={() => console.log('Pressed')}>
        <View
          style={{
            height: 70,
            width: 110,
            borderRadius: 5,
            backgroundColor: 'blue',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Button
            mode="contained"
            labelStyle={{ color: 'blue' }}
            onPress={() => console.log('Pressed')}>
            Start
          </Button>
        </View>
      </TouchableHighlight>


text:
Q: Adding Specific cell in Body of Message In my VBA, I need it to reference a specific cell in the body of the email.  When adding only the first one it works, but when I add the ---& Worksheets("Summary").Range("K1").Value--- to the other lines, it is not working.  Any suggestions?
Sub SendEmailandAttachFile()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim strbody As String
    Dim MakeJPG As String

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    strbody = "Good Day Everyone," & "

" & _
        "Please find the daily case report for the end of business Friday." & "
" & "Please let me know if you have any questions." & "
" & _
        "

" & "1) Cases Added Yesterday- " & Worksheets("Cases Open Yesterday").Range("D2").Value & "
" & "2) Cases Closed Yesterday - " & Worksheets("Cases Closed Yesterday").Range("D2").Value & "
" & "3) Open - " & Worksheets("Summary").Range("C5").Value & "
" & "4) Focus cases over 30 days old - " & Worksheets("Summary").Range("K1").Value & "
" & "5) Oldest Case - " & Worksheets("All Open").Range("C5").Value & "

" & "CSATs Returned Yesterday - " & "

"

    MakeJPG = CopyRangeToJPG("Chart", "C1:O22")

    If MakeJPG = "" Then
        MsgBox "Something go wrong, we can't create the mail"
        With Application
            .EnableEvents = True
            .ScreenUpdating = True
        End With
        Exit Sub
    End If

    On Error Resume Next
    With OutMail
        .Display
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = "Winn Daily Report " & Date
        .Attachments.Add MakeJPG, 1, 0
        .HTMLBody = "
" & strbody & "
" & .HTMLBody
        .Attachments.Add Application.ActiveWorkbook.FullName
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function CopyRangeToJPG(NameWorksheet As String, RangeAddress As String) As String
    Dim PictureRange As Range

    With ActiveWorkbook
        On Error Resume Next
        .Worksheets(NameWorksheet).Activate
        Set PictureRange = .Worksheets(NameWorksheet).Range(RangeAddress)

        If PictureRange Is Nothing Then
            MsgBox "Sorry this is not a correct range"
            On Error GoTo 0
            Exit Function
        End If

        PictureRange.CopyPicture
        With .Worksheets(NameWorksheet).ChartObjects.Add(PictureRange.Left, PictureRange.Top, PictureRange.Width, PictureRange.Height)
            .Activate
            .Chart.Paste
            .Chart.Export Environ$("temp") & Application.PathSeparator & "NamePicture.jpg", "JPG"
        End With
        .Worksheets(NameWorksheet).ChartObjects(.Worksheets(NameWorksheet).ChartObjects.Count).Delete
    End With

    CopyRangeToJPG = Environ$("temp") & Application.PathSeparator & "NamePicture.jpg"
    Set PictureRange = Nothing
End Function

A: Refactor the code to make it easier to identify the problem.
  Dim strbody, ar(5)
  ar(1) = Worksheets("Cases Open Yesterday").Range("D2").Value
  ar(2) = Worksheets("Cases Closed Yesterday").Range("D2").Value
  ar(3) = Worksheets("Summary").Range("C5").Value
  ar(4) = Worksheets("Summary").Range("K1").Value
  ar(5) = Worksheets("All Open").Range("C5").Value

  strbody = "Good Day Everyone,

" & _
        "Please find the daily case report for the end of business Friday.
" & _
        "Please let me know if you have any questions.

" & _
        "
1) Cases Added Yesterday- " & ar(1) & _
        "
2) Cases Closed Yesterday - " & ar(2) & _
        "
3) Open - " & ar(3) & _
        "
4) Focus cases over 30 days old - " & ar(4) & _
        "
5) Oldest Case - " & ar(5) & _
        "

CSATs Returned Yesterday -

"
  Debug.Print Join(Split(strbody, "
"), vbCrLf)