text:
Q: Forcing deallocation of large cache object in Java I use a large (millions) entries hashmap to cache values needed by an algorithm, the key is a combination of two objects as a long. Since it grows continuously (because keys in the map changes, so old ones are not needed anymore) it would be nice to be able to force wiping all the data contained in it and start again during the execution, is there a way to do effectively in Java?
I mean release the associated memory (about 1-1.5gb of hashmap) and restart from the empty hashmap..

A: Clear the hashmap:
hashmap.clear();

Then force a garbage collector run:
Runtime.getRuntime().gc();

This is the Javadoc page for Runtime.gc().

A: For a memory-aware cache, you may want to use Apache Commons collections, in particular their org.apache.commons.collections.map.ReferenceMap class. The Java special operation is a soft reference. Java provides WeakHashMap for weak references, but weak references are not what you want for a cache. Java does not provide a SoftHashMap, but ReferenceMap from Apache Commons can be a workable substitute.
Memory awareness of soft references is somewhat crude and inflexible. You can play with some Java options to somehow configure them, especially the -XX:SoftRefLRUPolicyMSPerMB value, which expresses (in milliseconds) how long soft-referenced values are kept in memory (when they cease to be directly reachable). For instance, with this:
java -XX:SoftRefLRUPolicyMSPerMB=2500

then the JVM will try to keep cached value for 2.5 seconds more than what it would have done with a WeakHashMap.
If soft references do not provide what you are looking for, then you will have to implement your own cache strategy, and, indeed, flush the map manually. This is your initial question. For flushing, you can use the clear() method, or simply create a new HashMap. The difference should be slight, and you may even have trouble simply measuring that difference.
Alternating between "full cache" and "empty cache" may also be considered as a bit crude, so you could maintain several maps. For instance, you maintain ten maps. When you look for a cached value, you look in all maps, but when you had a value, you put it in the first map only. When you want to flush, you rotate the maps: the first map becomes the second, the second becomes the third, and so on, up to the tenth map which is discarded. A new fresh first map is created. This would look like this:
import java.util.*;

public class Cache {

    private static final int MAX_SIZE = 500000;

    private Map[] backend;
    private int size = 0;

    public Cache(int n)
    {
        backend = new Map[n];
        for (int i = 0; i < n; i ++)
            backend[i] = new HashMap();
    }

    public int size()
    {
        return size;
    }

    public Object get(Object key)
    {
        for (Map m : backend) {
            if (m.containsKey(key))
                return m.get(key);
        }
        return null;
    }

    public Object put(Object key, Object value)
    {
        if (backend[0].containsKey(key))
            return backend[0].put(key, value);
        int n = backend.length;
        for (int i = 1; i < n; i ++) {
            Map m = backend[i];
            if (m.containsKey(key)) {
                Object old = m.remove(key);
                backend[0].put(key, value);
                return old;
            }
        }
        backend[0].put(key, value);
        size ++;
        while (size > MAX_SIZE) {
            size -= backend[n - 1].size();
            System.arraycopy(backend, 0, backend, 1, n - 1);
            backend[0] = new HashMap();
        }
        return null;
    }
}

The code above is completely untested, and should be enhanced with generics. However, it illustrates the main ideas: all maps are tested when reading (get()), all new values go to the first map, the total size is maintained, and when the size exceeds a given limit, maps are rotated. Note that there is some special treatment when a new value is put for a known key. Also, in this version, nothing special is done when finding a cached value, but we could "rejuvenate" accessed cached value: upon get(), when a value is found but not in the first map, it could be moved into the first map. Thus, frequently accessed values would remain cached forever.

A: You can call HashMap.clear(). That will remove all data. Note that this will only discard all entries, but keep the internal array used to store the entries at the same size (rather than shrinking to an initial capacity). If you also need to eliminate that, the easiest way would be to discard the whole HashMap and replace it with a new instance. That of course only works if you control who has a pointer to the map.
As for reclaiming the memory, you will have to let the garbage collector do its work.
Are your values also Long? In this case, you may want to look at a more (memory-) efficient
implementation than the generic HashMap, such as the TLongLongHashMap found in the GNU Trove library. That should save a lot of memory.

A: It sounds like you need a WeakHashMap instead:

A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.

I'm not sure how this works with Long as keys, though. Also, this might be of interest:
WeakHashMap is not a cache! Understanding WeakReference and SoftReference

A: Have you taken a look at WeakHashMap?

A: If you have a bit of spare memory you could implement a timout cache where each value in the hashmap contains your long value and an insersion timestamp in millis - then have a background thread iterate over the values every X seconds and remove anything more than X seconds/millis old.
Just my 2 cents :)

A: Instead of using a HashMap or other map implementation as a cache you could try to use a framework specialized in caching. A well known caching framework for Java is Ehcache.
Caching frameworks let you usually configure expiration policies based on time (e.g. time to live, time to idle) or usage (e.g. least frequently used, least recently used), some may even allow you to specify a maximum amount of memory usage.


text:
Q: Expected payout after a deductible To my understanding E[X-1] = E[x] - 1.  So why doesn't the following work?
A policy has a deductible of 1 and a capped payment of 5 and losses are distributed exponentially with mean 2.  The expected loss in the range of 1-6 (where variable payment amounts are made) would be $\int_{1}^{6}.5xe^{-.5x}dx$ which is about 1.42.  I would have thought the expected payout was then .42 = E[x] - 1, but it's not.  If you replace .5x by .5(x-1) in the integral you get roughly .86.
I see how the math works, but why doesn't using expectation as a linear operator work here?

A: We first have to understand what $$\int_{x=1}^6 x f_X(x) \, dx$$ represents.  It is the conditional expectation of the ground-up loss between $1$ and $6$, multiplied by the probability of the loss being in that range.  In other words, it is $$\int_{x=1}^6 x f_X(x) \, dx = \operatorname{E}[X \mid 1 \le X \le 6]\Pr[1 \le X \le 6]. \tag{1}$$  So the expression $$\begin{align}
\int_{x=1}^6 (x-1) f_X(x) \, dx &= \operatorname{E}[X - 1 \mid 1 \le X \le 6]\Pr[1 \le X \le 6] \\
&= (\operatorname{E}[X \mid 1 \le X \le 6] - 1)\Pr[1 \le X \le 6], \tag{2} \end{align}$$ and unless $\Pr[1 \le X \le 6] = 1$, we see why subtracting $1$ from $(1)$ does not yield $(2)$.

A: $P(x) = \begin{cases} 0, & x < 1 \\
x-1, & 1  \le x < 6 \\
5,& 6 \le x
\end{cases}$
Let $f$ be the pdf, then
$E[P] = \int_0^\infty P(x) f(x) dx =\int_1^6 (x-1){ 1\over 2} e^{- {x \over 2}} dx + \int_6^\infty (5){ 1\over 2} e^{- {x \over 2}} dx$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i solve that slowdown loading this static page? I have a very simple static php page which i found it takes between 300 to 500ms to load when i tested it on USA and Germany using pingdom and web speed testing websites. i tested this page on a localhost and i found that it takes in average around 20ms to load. So i'm wondering if there is a problem with my webhosting and if so then do you suggest any other shared webhosting that can provide better performance?
I'm using Hostgator Cloud Plan
Php 7.1
Im using Cloudflare CDN
This is the page
https://bonvivo.de/amazon/

And this is the page source
https://jsfiddle.net/arabtornado/tb16d7xf/1/

and here is a test result
https://i.stack.imgur.com/v2cO5.png

A: I switched to other shared hosting company (A2Hosting) Amsterdam datacenter, Turbo shared plan. Here is a test for the same page (Page delivered from the hosting server not from the cdn) snag.gy/2EwLBo.jpg
TTFB from when tested from frankfurt is 38-80ms


text:
Q: Entity Framework 5 code first cannot get model to work Tearing my hair out again on this one...using EF 5 Code First, building the model in code - compiles, so it is syntactically correct, but I get an exception when the code builds the model.  Here is the entity class (I also have vaidation attributes, but have removed them here for readability):
[Table("USERS")]
public class User : IPEntity
{
    #region Constructor (needs to initialize list objects for related entities)

    public User()
    {
        this.Profiles = new List<Profile>();
        this.ProfileDivs = new List<ProfileDiv>();
        this.ProfileDepts = new List<ProfileDept>();
    }

    #endregion

    #region Entity properties and validation attributes

    [Key]
    public long UserId { get; set; }

    public long PclientId { get; set; }

    public string UserName { get; set; }

    public string UserDescription { get; set; }

    public long? EmpId { get; set; }

    public string MustChangePassword { get; set; }

    public long? FailedLogins { get; set; }

    public DateTime? LastLogin { get; set; }

    public long? SequenceNumber { get; set; }

    public string AllDivs { get; set; }

    public string AllDepts { get; set; }

    public string UserRole { get; set; }

    public DateTime? BeginSupport { get; set; }

    public DateTime? EndSupport { get; set; }

    public string OneTimeAccess { get; set; }

    public long? ClonedFromUser { get; set; }

    public string Email { get; set; }

    public string ResetEmail { get; set; }

    public DateTime? ResetTimeout { get; set; }

    public long? ChallengeFailures { get; set; }

    public string PermUserRole { get; set; }

    public DateTime? PasswordChangedDate { get; set; }

    public virtual ICollection<Profile> Profiles { get; set; }

    public virtual ICollection<ProfileDiv> ProfileDivs { get; set; }

    public virtual ICollection<ProfileDept> ProfileDepts { get; set; }

    public virtual WorkSession WorkSession { get; set; }

}

The model builder class is:
public class User_Map : EntityTypeConfiguration<User>
{
    public User_Map()
    {
        this.ToTable("USERS");

        this.HasKey(t => new { t.UserId });

        this.Property(t => t.UserId)
            .HasColumnName("USER_ID")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
            .IsRequired();

        this.Property(t => t.UserName)
            .HasColumnName("USERNAME")
            .IsRequired()
            .HasMaxLength(25);

        this.Property(t => t.PclientId)
            .HasColumnName("PCLIENT_ID");

        this.Property(t => t.EmpId)
            .HasColumnName("EMP_ID");

        this.Property(t => t.MustChangePassword)
            .HasColumnName("MUST_CHANGE_PASSWORD")
            .HasMaxLength(1);

        this.Property(t => t.UserDescription)
            .HasColumnName("USER_DESCRIPTION")
            .HasMaxLength(80);

        this.Property(t => t.FailedLogins)
            .HasColumnName("FAILED_LOGINS");

        this.Property(t => t.LastLogin)
            .HasColumnName("LAST_LOGIN");

        this.Property(t => t.SequenceNumber)
            .HasColumnName("SEQUENCE_NUMBER");

        this.Property(t => t.AllDivs)
            .HasColumnName("ALL_DIVS")
            .HasMaxLength(1);

        this.Property(t => t.AllDepts)
            .HasColumnName("ALL_DEPTS")
            .HasMaxLength(1);

        this.Property(t => t.UserRole)
            .HasColumnName("USER_ROLE")
            .HasMaxLength(2);

        this.Property(t => t.BeginSupport)
            .HasColumnName("BEGIN_SUPPORT");

        this.Property(t => t.EndSupport)
            .HasColumnName("END_SUPPORT");

        this.Property(t => t.OneTimeAccess)
            .HasColumnName("ONE_TIME_ACCESS")
            .HasMaxLength(1);

        this.Property(t => t.ClonedFromUser)
            .HasColumnName("CLONED_FROM_USER");

        this.Property(t => t.Email)
            .HasColumnName("EMAIL")
            .HasMaxLength(60);

        this.Property(t => t.ResetEmail)
            .HasColumnName("RESET_EMAIL")
            .HasMaxLength(60);

        this.Property(t => t.ResetTimeout)
            .HasColumnName("RESET_TIMEOUT");

        this.Property(t => t.ChallengeFailures)
            .HasColumnName("CHALLENGE_FAILURES");

        this.Property(t => t.PermUserRole)
            .HasColumnName("PERM_USER_ROLE")
            .HasMaxLength(2);

        this.Property(t => t.PasswordChangedDate)
            .HasColumnName("PASSWORD_CHANGED_DATE");

        this.HasOptional(t => t.WorkSession)
            .WithRequired(t => t.User);

        // TODO: This is syntactically correct but model blows up!

        this.HasMany(t => t.Profiles)
            .WithRequired(t => t.User)
            .HasForeignKey(t => t.UserId);

    }
}

When the model builder class' constructor executes, I get the following exception thrown on the line above (after the comment):
The expression 't => t.User' is not a valid property expression.
The expression should represent a property: C#: 't => t.MyProperty'
VB.Net: 'Function(t) t.MyProperty'.

The Profiles entity is very simple:
[Table("PROFILE")]
public class Profile : IPEntity
{
    [Key, Column(Order = 0)]
    [ForeignKey("UserId")]
    public long UserId { get; set; }

    [Key, Column(Order = 1)]
    public string FunctionalArea { get; set; }

    public int RightsId { get; set; }

    public User User;

}

I have been beating on this for two or three days, if anyone can spot my mistake, I would be MOST appreciative!
Thanks,
Peter
UPDATE: I found one bone-headed mistake by reading this post, since I had declared something as a field and not a property...but now I get a different exception which I do not understand:
The navigation property 'UserId' is not a declared property on type 'Profile'.
Verify that it has not been explicitly excluded from the model and that
it is a valid navigation property.

This has me confused as UserId IS a declared property on Profile...?
SECOND UPDATE:
I understand the exception but (since there is no inner exception detail) cannot determine where it is coming from.  I changed the User_map class to include:
        this.HasMany(t => t.Profiles)
            .WithRequired(t => t.User)
            .HasForeignKey(t => t.UserId)
            .WillCascadeOnDelete(false);

and the Profile_map class to include:
        this.HasRequired(t => t.User)
            .WithMany()
            .HasForeignKey(t => t.UserId)
            .WillCascadeOnDelete(false);

Since I have to work with the existing database, I am stuck with the property "UserId" being a foreign key in both tables (in User table it is foreign key for Profiles table, in Profiles table it is foreign key for User table.)  I added the .WillCascadeOnDelete(false) to both in case there was some kind of circularity problem.  Like I said, I cannot determine which map is blowing things up, the calls to both constructors pass without exception, it is only when the override for OnModelCreating in the context exits that the exception is thrown.  Here is the override:
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        var mbProfile = new Profile_map();
        modelBuilder.Configurations.Add(mbProfile);

        var mbUser = new User_Map();
        modelBuilder.Configurations.Add(mbUser);

        base.OnModelCreating(modelBuilder);
    }

I know I'm still an EF newbie, but I cannot find the problem (well, haven't yet anyway...)
Thanks again.

A: public User User;

should be a property instead of a field - like all the others :)
public User User { get; set; }

With virtual preferably (to allow lazy loading), because you have marked all your navigation properties as virtual.
Edit about the UPDATE
The exception talks about a navigation property UserId and complains that it is not a "valid navigation property". Indeed it isn't a valid navigation property. The exception indicates that you possibly have used UserId (instead of User) in the WithRequired method. You should take a closer look at that.

A: Peter, with regard to your issue with the two "UserId" columns, you said that they were both foreign keys. I don't think you are correct. The User.UserId is marked with [Key] and it is the only one in the User class marked that way. It must be the primary id for the User table. On the Profile class, you have both UserId and FunctionalArea marked with [Key]. This means that the Profile table has a joint primary key, one of which is the foreign key to the User table's UserId column.
That design is perfectly fine. However, in order to have a relationship between User and Profile records where the Profile record is the parent, you would have to have TWO columns on your User table that reference the Profile table's two primary keys, and NEITHER of those columns could be the UserId column of the User table, otherwise you would have a circular dependency with no way of creating either record.
Bottom line is, you don't have two relationships between the User and Profile tables, just one. So delete the following block from your Profile_map class:
this.HasRequired(t => t.User)
    .WithMany()
    .HasForeignKey(t => t.UserId)
    .WillCascadeOnDelete(false);

That should fix it right up! ;)


text:
Q: Simulink and arduino serial communication I am running a code on arduino which works fine in arduinoide, I want to get those values in simulink for real time using serial connection.
I am burnig a program in arduino and want to access both send and receive function of serial monitor, on simulink. I want these to plot graphs in real time and run PID algorithm using simulink.
But for some odd reason, simulink values are either not updating(in external mode) or fluctuating some odd values(in normal mode). Any help.

A: If you are doing a communication between the Arduino and Simulink there might be some problems in your connection. I'm assuming you are using the Serial Send and Serial Receive block to do the communication.
I did a complete tutorial how to connect both platforms in my Github page.

By your description I can think of this problems:
Simulink is not updating?
If your Simulink is not updating probably because it is waiting Arduino to send some serial data, but is not receiving anything. Some possible causes of this problem might be:

*

*Wrong Serial baud rate

*Wrong data type (i.e. If you are sending Arduino float you have to receive a single in Simulink.)

*Wrong data size

*Different step time (Remember to use the same step time in Simulink and Arduino)

Simulink receiving odd values?
If Simulink is updating but showing odd values, the communication between both might be damaged.

*

*Desynchronization of the communication - Try to use a Header and a Terminator in the Serial Send and Serial Receive block and remember to set this in your Arduino code.

*Different step time - Make sure both application are sending and receiving at same rate.

*Verify what you are sending - You can check what exactly you are sending to the serial with a scope, remember that in the Serial Send block the input signal must be a byte. If you are using a single or double remember to cast it to byte with a Byte Pack block.


text:
Q: How to run sparkR in 64-bit mode I've install Spark - 1.4.1 (have R 3.1.3 version). Currently testing SparkR to run statistical models. I'm able to run some sample code such as,
Sys.setenv(SAPRK_HOME = "C:\\hdp\\spark-1.4.1-bin-hadoop2.6")
.libPaths(c(file.path(Sys.getenv("SPARK_HOME"), "R", "lib"), .libPaths()))
#load the Sparkr library
library(SparkR)
# Create a spark context and a SQL context
sc <- sparkR.init(master = "local")

sqlContext <- sparkRSQL.init(sc)

#create a sparkR DataFrame
DF <- createDataFrame(sqlContext, faithful)

sparkR.stop()

So Next,I'm installing rJava package in to SparkR. But its not installing. Giving below error.
> install.packages("rJava")
Installing package into 'C:/hdp/spark-1.4.1-bin-hadoop2.6/R/lib'
(as 'lib' is unspecified)
trying URL 'http://ftp.iitm.ac.in/cran/bin/windows/contrib/3.1/rJava_0.9-7.zip'
Content type 'text/html; charset="utf-8"' length 898 bytes
opened URL
downloaded 898 bytes

Error in read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open the connection
In addition: Warning messages:
1: In unzip(zipname, exdir = dest) : error 1 in extracting from zip file
2: In read.dcf(file.path(pkgname, "DESCRIPTION"), c("Package", "Type")) :
  cannot open compressed file 'rJava/DESCRIPTION', probable reason 'No such file or directory'

Also when, I'm running SparkR command on shell it is started as 32-bit application. I highlighted the version info as below.

So, please help me to resolve this issue.

A: When in the SparkR shell, it seems to change where it installs R packages. The key line is
Installing package into 'C:/hdp/spark-1.4.1-bin-hadoop2.6/R/lib'

I suspect that

*

*You do not have write permission for `C:/hdp/spark-1.4.1-bin-hadoop2.6/R/lib'

*You don't want to put the package there in the first place.

You have two options,

*

*Start a vanilla R session and install as usual

*Or, use the lib argument in install.packages to specify where you want to install rJava

A: I solved the issue. It was R version issue, previously i'm using R 3.1.3.That time it was giving me error, that the rJava package is not available for current R version.
To solve I follow this steps:
1) Installed new R version i.e R 3.2.2
2) Then update the Path variable and new R version path(Windows -> "Path" -> "Edit environment variables to for your account" -> PATH -> edit the value.)
3) Again restart sparkR shell.

Thanks all for your support!!!


text:
Q: How to make a Google App Engine authentiated request from an Android app? I'm trying to make an authenticated request from an Android app on my backend deployed on Google App Engine.
I tried to follow this guide but apparently I'm missing something...
Here is what I've already done:
In Google Cloud Console, I added an Android app giving the app package name (defined in the manifest.package attribute of AndroidManifest.xml) and the app's certificate SHA1 hash retrieved with this command (I'm in debug mode, using the debug keystore):
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -v -list

Now in the android app I try to get a token
Account account = mAccountManager.getAccountsByType("com.google")[0]
String scope = "audience:server:client_id:THE_CLIENT_ID_FROM_GOOGLE_CLOUD_CONSOLE_GAVE_ME";
String token = GoogleAuthUtil.getToken(myActivity, account.name, scope);

Unfortunately this code systematically raises a GoogleAuthException("Unknown")
Does anyone have any clue on what I'm doing wrong ?

A: I think you are using the client id of your Android application in the scope.
It doesn't work this way: you have to create a web application client ID in the same project where the Android client id is, and use the web project's client id in your scope.
Then in your GAE application you can check the validity of the token by setting the web application client ID as your audience, and using your Android client id for checking the authorized party.


text:
Q: SQL Server Dúvidas ao Somar turno 3 (SUM) Como fazer uma soma (SUM) do turno 3 de uma empresa e organizar por dia? O problema é que o turno 3 acaba no dia seguinte (começa as 22hrs e acaba as 6hrs do dia seguinte), então estou tentando fazer uma exceção somente ao turno 3 que no dia atual desconsidere os valores obtidos antes das 6 da manhã e some das 22 horas até as 6 da manhã do dia seguinte.
Segue abaixo o script que eu já fiz e o resultado obtido
No resultado obtido o Turno 3 de hoje (dia 14 já está com dado produzido, porém esse dado deveria ser do turno 3 de ontem)
SELECT
STR(DAY(E3TimeStamp),2) + '/' + STR(MONTH(E3TimeStamp),1) + '/' + STR(YEAR(E3TimeStamp),4) AS Data,
Maquina AS Maquina,
Parametro AS Código,
ROUND(sum(Metrica),2) AS 'Metrica Total' ,
ROUND(SUM(CASE WHEN Turno = 1 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 01',
ROUND(SUM(CASE WHEN Turno = 2 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 02',
ROUND(SUM(CASE WHEN Turno = 3 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 03'
FROM Tab_Dados_Escolha
GROUP BY
YEAR(E3TimeStamp), MONTH(E3TimeStamp),DAY(E3TimeStamp), Maquina, Parametro

Resultado obtido do script acima:

Resultado que deveria ocorrer (Turno 03 foi somado ao dia anterior, pois ainda não iniciou hoje):

A: Vamos lá,
a consulta abaixo deve trazer o que você está precisando
select Dataturno,
       Maquina AS Maquina,
       Parametro AS Código,
       ROUND(sum(Metrica),2) AS 'Metrica Total' ,
       ROUND(SUM(CASE WHEN Turno = 1 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 01',
       ROUND(SUM(CASE WHEN Turno = 2 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 02',
       ROUND(SUM(CASE WHEN Turno = 3 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 03'
 from (
 select cast( iif( turno = 3 and datepart(hour, E3TimeStamp) < 6, dateadd( -1, day, E3TimeStamp ), E3TimeStamp ) as date ) as Dataturno,
       Maquina AS Maquina,
       Parametro AS Código,
       Turno,
       Metrica
  from Tab_Dados_Escolha
) x
group by
    Dataturno, Maquina, Parametro,

Vou explicar o que fiz.
na linha 12: se o turno = 3 e a hora < 6, eu considero a E3TimeStamp como dia anterior.
Assim você vai contar todo o turno, como dia anterior.
Usei um cast, para trazer somente a data, e não precisar pegar o dia, mes e ano.
Não tenho como testar, mas se der algum erro e não conseguir resolver, me avise que tento te ajudar.

A:
O problema é que o turno 3 acaba no dia seguinte (começa as 22hrs e
acaba as 6hrs do dia seguinte)

Para resolver esse problema, considere que a data datetime deve ser manipulada de forma  a "parecer" que pertence ao final do dia anterior. Após essa manipulação, você pode executar sua consulta que obterá o resultado esperado. Fiz um exemplo no Fiddle que está disponível neste link SQL Fiddle.
MS SQL Server 2017 Schema Setup:
CREATE TABLE tab_dados_escolha (
    Maquina varchar(100) COLLATE Latin1_General_CI_AS DEFAULT NULL NULL,
    Metrica decimal(10,0) DEFAULT NULL NULL,
    E3TimeStamp datetime DEFAULT NULL NULL,
    Turno int DEFAULT NULL NULL,
    Parametro int NULL
);

INSERT INTO tab_dados_escolha (Maquina,Metrica,E3TimeStamp,Turno,Parametro) VALUES
     (N'ESC_RET',10,'2021-05-13 05:00:00.0',3,125),
     (N'ESC_RET',7,'2021-05-14 03:00:00.0',3,125),
     (N'ESC_RET',22,'2021-05-13 10:00:00.0',1,125),
     (N'ESC_RET',15,'2021-05-13 16:00:00.0',2,125),
     (N'ESC_RET',2,'2021-05-13 23:00:00.0',3,125),
     (N'ESC_RET',4,'2021-05-14 23:00:00.0',3,125);

Consulta 1:
select * from tab_dados_escolha

Resultado:

Maquina
Metrica
E3TimeStamp
Turno
Parametro

ESC_RET
10
2021-05-13T05:00:00Z
3
125

ESC_RET
7
2021-05-14T03:00:00Z
3
125

ESC_RET
22
2021-05-13T10:00:00Z
1
125

ESC_RET
15
2021-05-13T16:00:00Z
2
125

ESC_RET
2
2021-05-13T23:00:00Z
3
125

ESC_RET
4
2021-05-14T23:00:00Z
3
125

A Solução
Consulta 2:
with tab_dados_escolha_corrigido as
(
    Select * from tab_dados_escolha
    except
    Select Maquina, Metrica, E3TimeStamp, Turno, Parametro
      from tab_dados_escolha
     where DatePart(hour,E3TimeStamp) < 6
    Union
    Select Maquina, Metrica, cast(cast(cast(E3TimeStamp-1 as date) as varchar) + ' 23:59:00' as datetime) as E3TimeStamp, Turno, Parametro
      from tab_dados_escolha
     where DatePart(hour,E3TimeStamp) < 6
)
SELECT
  convert(varchar,E3TimeStamp,103) AS Data,
  Maquina AS Maquina,
  Parametro AS Código,
  ROUND(sum(Metrica),2) AS 'Metrica Total' ,
  ROUND(SUM(CASE WHEN Turno = 1 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 01',
  ROUND(SUM(CASE WHEN Turno = 2 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 02',
  ROUND(SUM(CASE WHEN Turno = 3 THEN Metrica ELSE 0 END),2) As 'Metrica Turno 03'
FROM tab_dados_escolha_corrigido
GROUP BY convert(varchar,E3TimeStamp,103), Maquina, Parametro

Resultado:

Data
Maquina
Código
Metrica Total
Metrica Turno 01
Metrica Turno 02
Metrica Turno 03

12/05/2021
ESC_RET
125
10
0
0
10

13/05/2021
ESC_RET
125
46
22
15
9

14/05/2021
ESC_RET
125
4
0
0
4

A ideia
A ideia foi utilizando lógica dos conjuntos da seguinte forma:
Pegue todos os registros da tabela com exceção except daquele cuja hora é inferior a 6 horas.
O resultado, faça uma união com todos os registros que foram excluídos com o except, mas manipulamos a data para passar a pertencer ao dia anterior cast(cast(cast(E3TimeStamp-1 as date) as varchar) + ' 23:59:00' as datetime) as E3TimeStamp, dessa forma o forçamos a data a apontar para o dia no qual o campo ´metrica´ deve ser somado.
Comando With ... As
O comando with tab_dados_escolha_corrigido as () permite criar o que é chamado de CTE (common table expression) ou expressão de tabela comum que é uma espécie de tabela temporária definida no escopo de execução de uma única instrução SELECT. No seu caso, você poderia criar um view chamada tab_dados_escolha_corrigido.
Convert
Foi utilizado o convert(varchar,E3TimeStamp,103) para tornar o resultado da data no formato que você evidenciou na sua consulta original.


text:
Q: SVNKit how to commit renamed files and edited files in the same opperation I'm new to SVNKit. I've been searching for an answer for a couple of days now without success.
From what I found so far to commit a renamed file, a deleted file and a new or edited file the opperations can be done seperatly giving a different revision for each action.
Can you give or refer to a working example to do such opperations together so that only one message must given for all and one new revision is generated? Or a reference in the documentation I can start with?
Someone ask a similar question years ago but no answered was given.


text:
Q: Symmetric and anti-symmetric parts of the covariant derivative of a connection The following is an excerpt from Sharpe's Differential Geometry - Cartan's Generalization of Klein's Erlangen Program.

Now we come to the question of higher derivatives. As usual in modern
  differential geometry, we shall be concerned only with the skew-symmetric
  part of the higher derivatives. In essence, what we shall be doing is taking
  the partial derivatives with respect to the base (i.e., manifold) variables
  and skew-symmetrizing the result, thus forgetting about the part of the
  higher derivatives that vanish under this procedure. However, this will not
  be made explicit in our treatment. The part of the higher derivative that
  disappears has not been studied much in differential geometry since Elie
  Cartan showed how useful it is to consider only the skew-symmetric part,
  that is, the exterior derivative. The old masters did use the symmetric part...

"Partial derivatives with respect to the base" must be the covariant derivative of the connection. If I correctly understand what's written in this answer, then we have for any torsion free connection on a manifold the equality $ \mathrm dw=\operatorname{Alt}(\nabla w)$.
This already seems rather remarkable since the exterior derivative is intrinsic.
Question 1. What is the geometric meaning of the above fact for torsion-free connections? How does taking anti-symmetrization "forget" the structure of a horizontal bundle (connection)?
Question 2. Still for a torsion-free connection, what is the geometric meaning of "the part of the higher derivative that vanish under this procedure" of anti-symmetrization (i.e the symmetric part)?
Question 3. What's the conceptual picture for an arbitrary connection on a manifold (possibly with torsion)? Is the anti-symmetrization still the exterior derivative? What is the symmetric part?
Remark on Q3. I vaguely recall being told that torsion measures the failure of the fundamental theorem of calculus, and also that in torsion-free connections the parallel transport commutator is given by the Lie bracket (again, the latter is intrinsic).

A: Here's some calculations that may help. (I'll leave it to you to decide if the arguments are valid or not.) We'll work in a two-dimensional manifold with local coordinates $x$ and $y$. Let $d$ be the covariant derivative at a point in some direction and let $dx$ and $dy$ be the components of the directional vector.
We apply $d$ to a scalar function $f(x,y)$ and get
$$
df = f_xdx+f_ydy
$$
which is the usual differential of $f$. Apply $d$ a second time and we get
$$
d^2f = f_{xx}dx^2+2f_{xy}dxdy+f_{yy}dy^2+f_xd^2x+f_yd^2y.
$$
This is the second differential of $f$ and is a form on the second order tangent bundle, but since $d$ is to be interpreted as the covariant derivative, the connection gives that the second order differentials are expressed as quadratic forms on the tangent bundle:
\begin{align*}
d^2x &= -(\Gamma^1_{11}dx^2+(\Gamma^1_{12}+\Gamma^1_{21})dxdy+\Gamma^1_{22}dy^2)\\
d^2y &= -(\Gamma^2_{11}dx^2+(\Gamma^2_{12}+\Gamma^2_{21})dxdy+\Gamma^2_{22}dy^2)
\end{align*}
and we have that
\begin{align*}
d^2f &= (f_{xx}-\Gamma^1_{11}f_x-\Gamma^2_{11}f_y)dx^2\\
 &+(2f_{xy}-(\Gamma^1_{12}+\Gamma^1_{21})f_x-(\Gamma^2_{12}+\Gamma^2_{21})f_y)dxdy\\
 &+(f_{yy}-\Gamma^1_{22}f_x-\Gamma^2_{22}f_ydy^2.
\end{align*}
So the symmetric part of the connection is what comes in to play when we calculate higher order forms, the anti-symmetric part does not affect these calculations.
To calculate an anti-symmetric derivative we let $\partial$ denote the covariant derivative in some other direction and let $\partial x$ and $\partial y$ be the components of this other direction vector. This time we'll investigate the derivative of a one-form so let $\omega=a(x,y)dx+b(x,y)dy$ be some one-form. This one-form can be evaluated on either of the two direction vectors so we let
\begin{align*}
    \omega(d) &= adx+bdy\\
    \omega(\partial) &= a\partial x+b\partial y
\end{align*}
mean that the one-form is evaluated on $(dx,dy)$ and $(\partial x, \partial y)$ respectively.
We now calculate the anti-symmetric derivative of the one-form
\begin{align*}
    \partial\omega(d)-d\omega(\partial) &= a_x\partial xdx + a_y\partial ydx +b_x\partial xdy + b_y\partial ydy + a\partial dx + b\partial dy\\
    &- (a_xdx\partial x + a_ydy\partial x +b_xdx\partial y + b_ydy\partial y + ad\partial x + bd\partial y)\\
    &= a_y(dx\partial y-\partial xdy) + b_x(\partial xdy-dx\partial y) \\
    &+ a(\partial d-d\partial)x + b(\partial d-d\partial)y
\end{align*}
Our connection defines that
\begin{align*}
\partial dx &= -(\Gamma^1_{11}\partial xdx+\Gamma^1_{12}\partial xdy+\Gamma^1_{21}dx\partial y+\Gamma^1_{22}\partial ydy)\\
\partial dy &= -(\Gamma^2_{11}\partial xdx+\Gamma^2_{12}\partial xdy+\Gamma^2_{21}dx\partial y+\Gamma^2_{22}\partial ydy)
\end{align*}
and we have that
\begin{align*}
    (\partial d-d\partial)x &= -(\Gamma^1_{12}-\Gamma^1_{21})(\partial xdy-dx\partial y)\\
    (\partial d-d\partial)y &= -(\Gamma^2_{12}-\Gamma^2_{21})(\partial xdy-dx\partial y)
\end{align*}
We now replace $\partial xdy-\partial ydx$ with standard notation $dx\wedge dy$ and the anti-symmetric derivative of the one-form is then expressed as
\begin{align*}
    \partial\omega(d)-d\omega(\partial) &= (b_x-a_y-a(\Gamma^1_{12}-\Gamma^1_{21})-b(\Gamma^2_{12}-\Gamma^2_{21}))\,dx\wedge dy
\end{align*}
The anti-symmetric derivative is also called the covariant exterior derivative and for symmetric connections it coincides with the usual exterior derivative on linear forms.

A: Although higher derivatives are best thought through with jet bundles where we actually differentiate a bundle and not just a manifold, there is a useful description of second derivatives using secondary tangent bundles, this is just iterating the tangent bundle, ie $TTM$. This is described in one of the early chapters in Kolár, Michor & Slováks book on natural bundles. (They also describe a generalisation of this in one of the later chapters which they call section forms - but they don't do anything with it).

Question 3. What's the conceptual picture for an arbitrary connection on a manifold (possibly with torsion)? Is the anti-symmetrization still the exterior derivative? What is the symmetric part?

On the last part of this question you may be interested in this paper, A Description of the Derivations of the Algebra of Symmetric Tensors, by A. Heydari, N. Boroojerdian, E. Peyghan and published in Archivum Mathematicum. They introduce symmetric forms, bracket, Lie derivative and differential. Whilst the symmetric differential is not nilpotent, ie $(d^s)^2$ does not vanish, they show

proposition 5:
Let $(M, g)$ be a Riemmanian manifold with Levi-Civita connection
$∇$. The 1-form $ω$ is Killing if and only if $d^sω = 0$.

and

proposition 7:
Every derivation of degree 1 on symmetric forms, whose value for a function is the differential of the function, is of the form of a symmetric differential of a connection which is also unique.

A: The meaning of higher-order derivatives in differential geometry is better understood through jet bundles. The covariant derivative $\nabla\phi$ of (say) a smooth section $\phi:M\rightarrow E$ of a vector bundle $\pi:E\rightarrow M$, being a derivative, can be seen as a section of the so-called first-order jet bundle $\pi^1_0:J^1 E\cong\mathrm{End}(TM,E)\rightarrow E$ of $E$. Likewise, derivatives of higher order (say, $k\in\mathbb{N}$) of smooth sections of $\pi$ are described in a coordinate-free fashion by the so-called jet bundle of order $k$ $\pi^k_0:J^k E\rightarrow E$. This hierarchy of (vector) bundles over $E$ is endowed with vector bundle projections $\pi^k_l:J^kE\rightarrow J^l E$, $k>l$ such that $\pi^l_m\circ\pi^k_l=\pi^k_m$ for all integers $k>l>m\geq 0$. Roughly speaking, one may identify elements of $J^k E$ locally with Taylor polynomials of order $k$, and the projections $\pi^k_l$ discard derivatives of order above $l$.
The key point is that the leading-order derivatives are, in a sense, always symmetric: the kernel of $\pi^k_{k-1}$ is a bundle whose total space is canonically isomorphic to $S^kT^*M\otimes E$ = the tensor product of the symmetrized $k$-fold tensor power of $T^*M$ with $E$. Particularly, any reference to a specific covariant derivative when globally defining highest-order derivatives disappears - more precisely, all yield the same result (differences only affect lower-order terms). One can exploit this fact to write smooth sections of $J^k E$ in terms of symmetrized iterated covariant derivatives (see e.g. this MO question of mine).
This also means that any partial antisymmetrization will always discard highest-order derivatives - this holds irrespectively of $\nabla$ being torsion-free or not (for general vector bundles, this concept usually has no meaning). Hence, if you totally antisymmetrize (as done with $k$-forms), only derivatives of at most first order survive. This is of course related to the nilpotency of the exterior derivative.
(EDIT 2) To illustrate this, let us consider the concept of iterated covariant derivatives, mentioned in the MO question linked in the second paragraph. To that end, we combine a covariant derivative on the vector bundle $\pi$ with a covariant derivative on $TM$ in order to define covariant derivatives on the tensor bundles $\otimes^k T^*M \otimes E\rightarrow M$ for all $k\in\mathbb{N}$ by means of Leibniz's rule. We denote all these covariant derivatives collectively by $\nabla$. Once this is done, the iterated covariant derivatives $\nabla^k\phi$ of all orders $k\in\mathbb{N}$ of smooth sections $\phi$ of $\pi$ are defined recursively as follows: $$\nabla^0\phi=\phi\ ,\,\nabla^1\phi=\nabla\phi\ ,\,\nabla^{k+1}\varphi=\nabla(\nabla^k\phi)\ ,$$ so that $\nabla^k\phi$ is a smooth section of $\otimes^k T^*M \otimes E\rightarrow M$ for all $k\in\mathbb{N}$. Particularly, for $k=2$, one can write $$\nabla^2\phi(X,Y)=\nabla_X(\nabla_Y\phi)-\nabla_{\nabla_X Y}\phi\ .$$ If we antisymmetrize $\nabla^2\phi$, we obtain $$\nabla^2\phi(X,Y)-\nabla^2\phi(Y,X)=\nabla_X(\nabla_Y\phi)-\nabla_Y(\nabla_X\phi)-\nabla_{\nabla_X Y-\nabla_Y X}\phi$$ $$=\text{Riem}_\nabla(X,Y)\phi-\nabla_{T_\nabla(X,Y)}\phi\ ,$$ where $$\text{Riem}_\nabla(X,Y)\phi=\nabla_X(\nabla_Y\phi)-\nabla_Y(\nabla_X\phi)-\nabla_{[X,Y]}\phi$$ is the Riemann curvature tensor of the covariant derivative on $\pi$  and $$T_\nabla(X,Y)=\nabla_X Y-\nabla_Y X-[X,Y]$$ is the torsion tensor of the covariant derivative on $TM$. The above expression clearly depends on derivatives of $\phi$ of at most first order. Notice that the above antisymmetrization is closely related to the operation of exterior covariant differentiation $d^\nabla$ of $E$-valued differential forms, as mentioned in Jesper Göransson's answer: since $\phi$ is a $E$-valued 0-form and therefore $d^\nabla\phi=\nabla\phi$, we have that $$d^\nabla(d^\nabla\phi)(X,Y)=\nabla_X(\nabla_Y\phi)-\nabla_Y(\nabla_X\phi)-\nabla_{[X,Y]}\varphi=\text{Riem}_\nabla(X,Y)\varphi$$ $$=\nabla^2\phi(X,Y)-\nabla^2\phi(Y,X)+\nabla_{T_\nabla(X,Y)}\varphi\ .$$ Particularly, if $E=M\times\mathbb{R}$ (i.e. sections of $\pi$ are just real-valued functions on $M$) and $\nabla$ is just ordinary differentiation of functions on $M$ (so that $\text{Riem}_\nabla=0$ and $T_\nabla=0$), we thus recover the nilpotency of the (ordinary) exterior derivative.
A similar phenomenon happens if we antisymmetrize the vector field entries of the tensor field $\nabla^k\phi$ for $k>2$ - any antisymmetrization with respect to (say) $j$ entries leaves us with an expression which depends on $\nabla^i\phi$ for $i$ only up to $k-(j-1)=k-j+1$ for all $2\leq j\leq k$.
If $j<k$, this is what is called "partial antisymmetrization" above.
Returning to covariant derivatives $\nabla$ on $M$ (that is, on $TM$), the equivalence of the vanishing of the torsion tensor $T_\nabla(X,Y)$ of the connection $\nabla$ (which, by the way, simply states that $\nabla_X Y-\nabla_Y X$ is the Lie bracket of $X$ and $Y$ = Lie derivative of $Y$ along $X$) to the antisymmetric part of $\nabla\omega$ being equal to $d\omega$ for all 1-forms $\omega$, mentioned by Deane Yang in his comment to the OP's question, comes from Henri Cartan's formula relating Lie differentiation and exterior differentiation: $\mathscr{L}_{\!X}\omega=d(i_X\omega)+i_X(d\omega)$.
(EDIT 1) To see this, suppose that the torsion tensor of $\nabla$ vanishes, i.e. $$\nabla_X Y-\nabla_Y X=[X,Y]=\mathscr{L}_{\!X}Y\ .$$ Recall that the action of $\nabla$ on an 1-form $\omega$ is given by Leibniz's rule$$(\nabla_X\omega)(Y)=X(\omega(Y))-\omega(\nabla_X Y)$$ and so is the Lie derivative of $\omega$: $$(\mathscr{L}_{\!X}\omega)(Y)=X(\omega(Y))-\omega(\mathscr{L}_{\!X}Y)=X(\omega(Y))-\omega([X,Y])\ .$$ The antisymmetric part of $\nabla\omega$ is then given by $$(\nabla_X\omega)(Y)-(\nabla_Y\omega)(X)=X(\omega(Y))-Y(\omega(X))-\omega([X,Y])\ .$$
Notice that I used the vanishing of the torsion of $\nabla$ in the rhs. On the other hand, Henri Cartan's formula tells us that $$d\omega(X,Y)=(\mathscr{L}_{\!X}\omega)(Y)-Y(\omega(X))=X(\omega(Y))-Y(\omega(X))-\omega([X,Y])\ ,$$ hence indeed $(\nabla_X\omega)(Y)-(\nabla_Y\omega)(X)=d\omega(X,Y)$. Conversely, if one assumes this last identity and backtracks the above calculations, one obtains that $\omega(T_\nabla(X,Y))=0$ for all 1-forms $\omega$, hence $T_\nabla(X,Y)=0$ for all vector fields $X,Y$.
More generally, torsion introduces a sort of "internal rotation" on the frame bundle along parallel transport which cannot be accounted for by pushing forward by the diffeomorphism flow integrating the vector field along which we are differentiating (the latter is the effect measured by Lie derivatives) - hence the failure of the fundamental theorem of calculus. Interestingly, given any covariant derivative $\nabla$ on $M$, there is a unique covariant derivative $\nabla'$ on $M$ which is torsion-free and has the same geodesics as $\nabla$, which means that this "internal rotation" effect can be cancelled by suitably redefining $\nabla$. This is not to say that torsion should be always discarded - for instance, when dealing with foliations, there is a natural connection (the so-called Bott connection) which is only defined along vector fields tangent to the foliation - that is, a so-called partial connection. This connection is flat but has nonvanishing torsion, which therefore is important in dealing with the holonomy of the foliation.


text:
Q: Trying to add an alert to detection model "ssd_mobilenet_v2", throws an error Using "ssd_mobilenet_v2_fpn_keras" i am trying to add an alert system
The detection model is loaded in to the below function
 def detect_fn(image):
    image, shapes = detection_model.preprocess(image)
    prediction_dict = detection_model.predict(image, shapes)
    detections = detection_model.postprocess(prediction_dict, shapes)
    return detections

The image is converted to a tensor
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)

The the tensor is fead to the detection model
detections = detect_fn(input_tensor)
The output of the detection model is a dictionary, with the following keys:
dict_keys(['detection_boxes', 'detection_scores', 'detection_classes', 'raw_detection_boxes', 'raw_detection_scores', 'detection_multiclass_scores', 'detection_anchor_indices', 'num_detections'])

detections[detection_classes], gives the following output ie 0 is ClassA, 1 is ClassB
[0 1 1 0 0 1 0 0 1 0 1 1 0 0 1 0 1 1 0 1 0 1 1 0 0 1 0 0 1 0 1 0 0 1 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 1 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 1 0 1]

detections['detection_scores'] gives the score for each box detected (a few shown below)
[0.988446 0.7998712 0.1579772 0.13801616 0.13227147 0.12731305 0.09515342 0.09203091 0.09191579 0.08860824 0.08313078 0.07684237

I am trying to Print("Attention needed"), if detection classB ie 1 is observed
for key in detections['detection_classes']:
if key==1:
    print('Alert')

When i try to do that i get an error
`ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How do make it work?
I want the code to print "Attention needed" is Class =1 or A and detection_scores >= 14
Code Explained, a bit further

links for the complete code are below :

*

*Tutorial on YouTube

*GitHub sources repository

A: As mentioned in the error message, you should use .any(). like:
if (key == 1).any():
  print('Alert')

As key == 1 will be an array with [False, True, True, False, ...]
You might also want to detect ones that exceeds certain score, say 0.7:
for key, score in zip(
  detections['detection_classes'],
  detections['detection_scores']):
  if score > 0.7 and key == 1:
    print('Alert')
    break


text:
Q: Bulk insert in migration not inserting data As I've updated my postgres database scheme, I wanted to use a migration to migrate all existing data to the new tables in a migration, so it runs automagically when I deploy it to my host.
Unfortunately, that doesn't work. You'll find my code below. When I copy the exact same code to an artisan command, it works. When I copy that to artisan tinker, it works. When I run it via the migration, it doesn't. While DB#insert returns true, nothing gets inserted into the database.
I also tried calling the previously created working artisan command from the migration, but it doesn't insert any data then.
I've truncated the tables between the tests. Also the connection is correct as DB#getDefaultConnection returns the correct connection name and all other migrations work as expteced. Also another migration with DB#insert in it.
The weird thing: It worked a few weeks before. When I wrote this, I only made changes in the VueJS frontend, but not in the backend. I also haven't updated any packages or the postgres database. I am absolutely not sure what's going on there.
Also: No constraints are violated.
public function up()
{
    $platform_id = DB::table('platforms')->where('slug', '[...]')->first()->id;

    DB::table('apps')->chunkById(20, function ($apps) use ($platform_id) {
        $transformed = [];

        foreach ($apps as $app) {
            echo "{$app->app_id} - {$app->name}\n";
            $transformed[] = [
                'uuid'        => (string)Uuid::generate(4),
                'platform_id' => $platform_id,
                'remote_id'   => $app→app_id,
                // [...]
            ];
        }

        echo "Inserting...\n\n";
        DB::table('products')->insert($transformed);
    });

    // [...]
    // The same thing again with another table.


text: Q: What is the local extrema of a Greatest Integer Function I am trying to find the local extrema of Greatest Integer Function f(x)=int(x). Because the function has many constant points, would there be infinitely many local extrema? Also, how would one find the continuity, asymptotes, and end behavior? Thanks


text:
Q: Menu burger animation toggle full page menu Basically I need a menu burger that toggles on and off a full page menu but I can't get the coding to work together.
So I created both the Menu burger animation toggle and the Full page menu separately which work fine, now I dont know how to put them together, I have tried for ages but can't seem to make it work, can anyone help please?
Here are the links to the codes:
1. Menu Burger FIDDLE
css:
body {
    padding: 0px;
}

.border {
    position: fixed;
    background: #f9f8f3;
}

.top, .bottom {
    left: 0;
    right: 0;
    height: 50px;
}

.top {
    top: 0;
}

.bottom {
    bottom: 0;
}

.right, .left {
    top: 0;
    bottom: 0;
    width: 50px;
}

.right {
    right: 0;
}

.left {
    left: 0;
}

/* End of -->> Body border */

/* Nav */

.c-hamburger {
  display: block;
  position: fixed;
  left: 0px;
  bottom: 0px;
  overflow: hidden;
  margin: 0;
  padding: 0;
  width: 50px;
  height: 50px;
  font-size: 0;
  text-indent: -9999px;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  box-shadow: none;
  border-radius: none;
  border: none;
  cursor: pointer;
  -webkit-transition: background 0.3s;
  transition: background 0.3s;
}

.c-hamburger:focus {
  outline: none;
}

.c-hamburger span {
  display: block;
  position: absolute;
  top: 25px;
  left: 12px;
  right: 12px;
  height: 2px;
  background: #262626;
}

.c-hamburger span::before,
.c-hamburger span::after {
  position: absolute;
  display: block;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #262626;
  content: "";
}

.c-hamburger span::before {
  top: -7px;
}

.c-hamburger span::after {
  bottom: -7px;
}

.c-hamburger--htx {
  background-color: #f9f8f3;
}

.c-hamburger--htx span {
  -webkit-transition: background 0s 0.3s;
  transition: background 0s 0.3s;
}

.c-hamburger--htx span::before,
.c-hamburger--htx span::after {
  -webkit-transition-duration: 0.3s, 0.3s;
  transition-duration: 0.3s, 0.3s;
  -webkit-transition-delay: 0.3s, 0s;
  transition-delay: 0.3s, 0s;
}

.c-hamburger--htx span::before {
  -webkit-transition-property: top, -webkit-transform;
  transition-property: top, transform;
}

.c-hamburger--htx span::after {
  -webkit-transition-property: bottom, -webkit-transform;
  transition-property: bottom, transform;
}

/* active state, i.e. menu open */
.c-hamburger--htx.is-active {
  background-color: #fafd37;
}

.c-hamburger--htx.is-active span {
  background: none;
}

.c-hamburger--htx.is-active span::before {
  top: 0;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

.c-hamburger--htx.is-active span::after {
  bottom: 0;
  -webkit-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
}

.c-hamburger--htx.is-active span::before,
.c-hamburger--htx.is-active span::after {
  -webkit-transition-delay: 0s, 0.3s;
  transition-delay: 0s, 0.3s;
}

2. Full Page Menu FIDDLE
css:
ul, li{
    list-style: none;
}

#yellowMenu {
    background: #fafd37;
    font-size: 2em;
    text-align: center;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    padding-top: 16%;
}

#yellowMenu a {
    color: black;
    text-decoration: none;
    width: 100%;
    height: 2em;
    display: block;
    line-height: 2.1;
    font-family: 'FF_Super_Grotesk';
    font-weight: normal;
    font-style: normal;
    transition: background-color 2s ease;
}

#yellowMenu a:hover {
    color: #e0e0d4;
    background: rgba(182,182,157,0.7);

}

A: If I undesrtood you right you want to click on burger to hide and show the menu.
If that's it is, just add the menu to your burguer fiddle, hide it with display:none and add this simple jquery:
$(document).ready(function () {
            $('.c-hamburger').click(function () {
                $('#yellowMenu').toggle();
            });

        });

JSFIDDLE

A: you can use jquery show() hide() to do this ..

(function () {

    "use strict";

    var toggles = document.querySelectorAll(".c-hamburger");

    for (var i = toggles.length - 1; i >= 0; i--) {
        var toggle = toggles[i];
        toggleHandler(toggle);
    };

    function toggleHandler(toggle) {
        toggle.addEventListener("click", function (e) {
            e.preventDefault();
            (this.classList.contains("is-active") === true) ? this.classList.remove("is-active") || $("#testMenu").hide() : this.classList.add("is-active") || $("#testMenu").show();
        });
    }

})();
/* Body border */

/* https://www.youtube.com/watch?v=HbkOzrpmhUc https://css-tricks.com/body-border/ */
 body {
    padding: 0px;
}
.border {
    position: fixed;
    background: #f9f8f3;
}
.top, .bottom {
    left: 0;
    right: 0;
    height: 50px;
}
.top {
    top: 0;
}
.bottom {
    bottom: 0;
}
.right, .left {
    top: 0;
    bottom: 0;
    width: 50px;
}
.right {
    right: 0;
}
.left {
    left: 0;
}
/* End of -->> Body border */

/* Nav */
 .c-hamburger {
    display: block;
    position: fixed;
    left: 0px;
    bottom: 0px;
    overflow: hidden;
    margin: 0;
    padding: 0;
    width: 50px;
    height: 50px;
    font-size: 0;
    text-indent: -9999px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    box-shadow: none;
    border-radius: none;
    border: none;
    cursor: pointer;
    -webkit-transition: background 0.3s;
    transition: background 0.3s;
}
.c-hamburger:focus {
    outline: none;
}
.c-hamburger span {
    display: block;
    position: absolute;
    top: 25px;
    left: 12px;
    right: 12px;
    height: 2px;
    background: #262626;
}
.c-hamburger span::before, .c-hamburger span::after {
    position: absolute;
    display: block;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #262626;
    content:"";
}
.c-hamburger span::before {
    top: -7px;
}
.c-hamburger span::after {
    bottom: -7px;
}
.c-hamburger--htx {
    background-color: #f9f8f3;
}
.c-hamburger--htx span {
    -webkit-transition: background 0s 0.3s;
    transition: background 0s 0.3s;
}
.c-hamburger--htx span::before, .c-hamburger--htx span::after {
    -webkit-transition-duration: 0.3s, 0.3s;
    transition-duration: 0.3s, 0.3s;
    -webkit-transition-delay: 0.3s, 0s;
    transition-delay: 0.3s, 0s;
}
.c-hamburger--htx span::before {
    -webkit-transition-property: top, -webkit-transform;
    transition-property: top, transform;
}
.c-hamburger--htx span::after {
    -webkit-transition-property: bottom, -webkit-transform;
    transition-property: bottom, transform;
}
/* active state, i.e. menu open */
 .c-hamburger--htx.is-active {
    background-color: #fafd37;
}
.c-hamburger--htx.is-active span {
    background: none;
}
.c-hamburger--htx.is-active span::before {
    top: 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}
.c-hamburger--htx.is-active span::after {
    bottom: 0;
    -webkit-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    transform: rotate(-45deg);
}
.c-hamburger--htx.is-active span::before, .c-hamburger--htx.is-active span::after {
    -webkit-transition-delay: 0s, 0.3s;
    transition-delay: 0s, 0.3s;
}
ul, li {
    list-style: none;
}
#yellowMenu {
    background: #fafd37;
    font-size: 2em;
    text-align: center;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    padding-top: 16%;
}
#yellowMenu a {
    color: black;
    text-decoration: none;
    width: 100%;
    height: 2em;
    display: block;
    line-height: 2.1;
    font-family:'FF_Super_Grotesk';
    font-weight: normal;
    font-style: normal;
    transition: background-color 2s ease;
}
#yellowMenu a:hover {
    color: #e0e0d4;
    background: rgba(182, 182, 157, 0.7);
}

<button class="c-hamburger c-hamburger--htx"> toggle menu

</button>

PROJECTS

ABOUT

SERVICE

CONTACT

 Demo
EDIT:
For animating the hide and show use .fadeIn() and .fadeOut()
function toggleHandler(toggle) {
        toggle.addEventListener("click", function (e) {
            e.preventDefault();
            (this.classList.contains("is-active") === true) ? this.classList.remove("is-active") || $("#testMenu").fadeOut() : this.classList.add("is-active") || $("#testMenu").fadeIn();
        });
    }


text:
Q: how read active choices parameter value in another active chocices parameter's groovy script in jenkins? In a Jenkins build I created two "Active Choices Reactive Reference Parameter" (input text boxes) those are PARAMETER1 and PARAMETER2.
I can use contains() call in PARAMETER2's groovy script as below
PARAMETER1.contains("some string")

but I could not find a way to read PARAMTER1's exact value.
I am very new ing groovy and do not have understanding of Java.
How can I set use PARAMETER1 to a string in PARAMETER2's groovy script?

A: The PARAMETER1 variable gets injected into your PARAMETER2 Groovy script, as a variable.
It means that you can call it just like a normal variable. For example.
return [PARAMETER1+'ou', PARAMETER1+'AA', PARAMETER1+'11', ]

That will return the value of PARAMETER1 concatenated with some other string.
Hope that helps,
Bruno


text:
Q: Whither dispatch_once in Swift 3? Okay, so I found out about the new Swifty Dispatch API in Xcode 8. I'm having fun using DispatchQueue.main.async, and I've been browsing around the Dispatch module in Xcode to find all the new APIs.
But I also use dispatch_once to make sure that things like singleton creation and one-time setup don't get executed more than once (even in a multithreaded environment)... and dispatch_once is nowhere to be found in the new Dispatch module?
static var token: dispatch_once_t = 0
func whatDoYouHear() {
    print("All of this has happened before, and all of it will happen again.")
    dispatch_once(&token) {
        print("Except this part.")
    }
}

A: Example for "dispatch_once" in Swift 3.0
Step 1 : Just Replace below code with your Singleton.swift (Singleton class)
// Singleton Class
class Singleton: NSObject {
var strSample = NSString()

static let sharedInstance:Singleton = {
    let instance = Singleton ()
    return instance
} ()

// MARK: Init
 override init() {
    print("My Class Initialized")
    // initialized with variable or property
    strSample = "My String"
}
}

Singleton Sample Image
Step 2 : Call Singleton from ViewController.swift
// ViewController.swift
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let mySingleton = Singleton.sharedInstance
        print(mySingleton.strSample)

        mySingleton.strSample = "New String"

        print(mySingleton.strSample)

        let mySingleton1 = Singleton.sharedInstance
        print(mySingleton1.strSample)

    }

ViewController Sample Image
Output like this
My Class Initialized
My String
New String
New String

A: Since Swift 1.x, Swift has been using dispatch_once behind the scenes to perform thread-safe lazy initialization of global variables and static properties.
So the static var above was already using dispatch_once, which makes it sort of weird (and possibly problematic to use it again as a token for another dispatch_once. In fact there's really no safe way to use dispatch_once without this kind of recursion, so they got rid of it. Instead, just use the language features built on it:
// global constant: SomeClass initializer gets called lazily, only on first use
let foo = SomeClass()

// global var, same thing happens here
// even though the "initializer" is an immediately invoked closure
var bar: SomeClass = {
    let b = SomeClass()
    b.someProperty = "whatever"
    b.doSomeStuff()
    return b
}()

// ditto for static properties in classes/structures/enums
class MyClass {
    static let singleton = MyClass()
    init() {
        print("foo")
    }
}

So that's all great if you've been using dispatch_once for one-time initialization that results in some value -- you can just make that value the global variable or static property you're initializing.
But what if you're using dispatch_once to do work that doesn't necessarily have a result? You can still do that with a global variable or static property: just make that variable's type Void:
let justAOneTimeThing: () = {
    print("Not coming back here.")
}()

And if accessing a global variable or static property to perform one-time work just doesn't feel right to you -- say, you want your clients to call an "initialize me" function before they work with your library -- just wrap that access in a function:
func doTheOneTimeThing() {
    justAOneTimeThing
}

See the migration guide for more.

A: Compiles under Xcode 8 GA Swift 3
The recommended and elegant way to create a dispatch_once singleton class instance:
final class TheRoot {
static let shared = TheRoot()
var appState : AppState = .normal
...

To use it:
if TheRoot.shared.appState == .normal {
...
}

What do these lines do?
final - so the class cannot be overridden, extended, it also makes the code somewhat faster to run, less indirections.
static let shared = TheRoot() - This line does lazy init, and it only runs once.
This solution is thread safe.

A: According to the Migration Guide:

The free function dispatch_once is no longer available in Swift. In
  Swift, you can use lazily initialized globals or static properties and
  get the same thread-safety and called-once guarantees as dispatch_once
  provided.

Example:
  let myGlobal = { … global contains initialization in a call to a closure … }()

  // using myGlobal will invoke the initialization code only the first time it is used.
  _ = myGlobal

A: While the "lazy var" pattern allows me to stop caring about dispatch tokens and is generally more convenient than dispatch_once() was, I don't like what it looks like at the call site:
_ = doSomethingOnce

I would expect this statement to look more like a function call (since it implies action), but it doesn't look so at all. Also, having to write _ = to explicitly discard the result is annoying.
There is a better way:
lazy var doSomethingOnce: () -> Void = {
  print("executed once")
  return {}
}()

Which makes the following possible:
doSomethingOnce()

This might be less efficient (since it calls an empty closure instead of just discarding a Void), but improved clarity is totally worth it for me.

A: The other answers here and around the interwebs are pretty great, but I feel this little tidbit should also be mentioned:
The great thing about dispatch_once was how optimized it was, essentially nixing the code after the first run in a way that I hardly understand, but am reasonably assured that would be that much faster than setting and checking a (real) global token.
While the token thing could be reasonably implemented in Swift, having to declare yet another stored boolean isn't all that great. Not to mention thread-unsafe. As the doc says, you should use a "lazily initialized global." Yeah, but why clutter up the global scope, right?
Until somebody convinces me of a better method, I tend to declare my do-once closure inside the scope I'll be using it in, or reasonably close thereto, as follows:
private lazy var foo: Void = {
    // Do this once
}()

Basically I'm saying that "When I read this, foo should be the result of running this block." It behaves the exact same way as a global let constant would, just in the right scope. And prettier. Then I'd call it wherever I'd like, by reading it into something that'll never be used otherwise. I like Swift's _ for that. Like so:
_ = foo

This really cool quirk has actually been around a while, but hasn't seen much love. It basically leaves the variable alone at runtime, as an uncalled closure, until something wants to see its Void result. On read, it calls the closure, throws it away and keeps its result in foo. Void uses practically nothing memory-wise, so subsequent reads (i.e. _ = foo) do nothing on the CPU. (Don't quote me on that, somebody please check up on the assembly to be sure!) Have as many as you like, and Swift basically quits caring about it after the first run! Lose that old dispatch_once_t, and keep a lot of your code as pretty as when you first opened it Christmas day!
My one issue is that you can set foo to something else before its first read, and then your code will never be called! Hence the global let constant, which prevents that. Thing is, constants in class scope don't play well with self, so no playing with instance variables... But seriously, when do you set anything to Void anyway??
That, and you'd need to specify the return type as Void or (), else it'll still complain about self. Who'da thunk?
And lazy is just to make the variable as lazy as it should be, so Swift doesn't run it straight off on init().
Pretty snazzy, so long as you remember not to write to it! :P

A: Thread-safe dispatch_once:
private lazy var foo: Void = {
    objc_sync_enter(self)
    defer { objc_sync_exit(self) }

    // Do this once
}()


text:
Q: End of References At the end of my bibliography the below is being shown. Does anyone knows how i can remove it please?

A: Citations are of course added to the document by default. That is after all the way one points to an entry in the bibliography, with a citation. As you've added a bunch of citations after the bibliography, they show up there, as expected.
If you want to add something to the bibliography without generating a citation in the document, you need to set the citation style to Add to bibliography only. For existing citations, this is available via the right-click context menu:

(In LaTeX terms this changes from \cite or similar to \nocite.)


text:
Q: How to determine the dimension of a subspace I am working on a problem for my math class that I'm just not quite grasping:
Let S denote the set of all vectors (x, y, z) in V$_3$ whose components satisfy the equation x + y = 0. Determine whether S is a subspace of V$_3$. If S is a subspace, compute dim S.
I have determined S is a subspace of V$_3$ because the set is closed under addition and multiplication. Thus I must compute the dimension of S.
How do I go about finding the dimension of S? The only way I know of is to start with dimension n = 1 and increase n by one recursively if a set of n linearly independent elements of S spans V$_n$, but what does it mean for a three dimensional vector to span a two dimensional space? Does this mean the x and y components span two dimensions, the y and z components span two dimensions, x and z, any of the above, etc?

A: Since you know $x$ and $y$ must satisfy the relation $x + y = 0$, then you can rewrite your restriction as: $$x = -y$$
And your vector space will be defined as: $(-y, y, z)$. Now, there are several ways to justify that this vector space is bidimensional. I believe that the most simple one is to notice that it is defined by only two independent variables, so you need only two coordinates to uniquely define a vector in this vector space, thus making it bidimensional.
You can also show this by finding the canonical base to this vector space, and showing that it has only two vectors - $(-1, 1, 0)$ and $(0, 0, 1)$.
The geometrical meaning of a subspace of a three dimensional space being a two dimensional space is that all the vectors from that subspace are contained on a plane in the three dimensional space - besides the meaning of needing only 2 coordinates do be uniquely defined even on a three dimensional space, because the third coordinate is defined as a function of those two.

A: I suppose that $V_3$ is the space of triples over the base field $K$ (in your case it might be $\mathbb{R}$). The map
$$
T\colon V_3\to V_1
\qquad
T(x,y,z)=x+y
$$
is easily shown to be linear and surjective. Therefore $S=\ker T$ and the rank-nullity theorem tells you that
$$
3=\dim V_3=\dim\ker T+\dim\operatorname{im}T=\dim S+1
$$
so $\dim S=3-1=2$.
Since $(1,-1,0)$ and $(0,0,1)$ belong to $S$ and form a linearly independent set, they form a basis for $S$.


text:
Q: How to make firefox extension compatible? I have developed a firefox extension but firefox (v. 3.6.14) says the extension is not compatible with this firefox version.
I think my install.rdf is valid. It contains
<em:targetApplication>
      <Description>
        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!-- Firefox -->
        <em:minVersion>3.6.14</em:minVersion>
        <em:maxVersion>4.0.*</em:maxVersion>
      </Description>
 </em:targetApplication>

Any suggestions what could be the problem? What could cause this incompatibility?

A: I did not test it, but try to use the format
<em:maxVersion>4.0.0.*</em:maxVersion>
or
<em:maxVersion>4.0.*.*</em:maxVersion>
From https://developer.mozilla.org/en/extension_versioning,_update_and_compatibility:

Do not mistakenly think that * in a
  version represents any version. The *
  actually represents an infinitely high
  number and so is really only sensibly
  used in the maxVersion. Using it in a
  minVersion usually doesn't produce the
  effect you want.


text:
Q: Strugging with spring SimpleJdbcCall to call Oracle function I am struggling with the below code to make it work, searching documentation and forums and stucked.
Finally I decided to ask you for help.
What I have is package with TYPES, FUNCTION declarations and FUNCTION BODY declaration.
In future I would like to use SYNONYM to MYPACKAGE (This is only mock - I will not have package and types declarations in my database, but use dblink to external database and Java code to run procedures / functions, but now I don't have this dblink accessible) and MYPACKAGE will be something accessible through dblink:
create public synonym dblink_MYPACKAGE for SOME_SCHEMA.MYPACKAGE@dblink_externalDB;

and I will be using dblink_MYPACKAGE instead of MYPACKAGE in Java Code.
 (but this doesn't matter does it?) The external database is not ours, so we CAN'T change anything there...
public class TestClassSpringBased {

private DataSource dataSource;

private SimpleJdbcCall jdbcCall;

@Override
public void testMe(Integer id) {

    int iid = 1;
    SqlParameterSource in = new MapSqlParameterSource().addValue("IN_1", iid);

    Map<String, Object> out = jdbcCall.execute(in);

}

public DataSource getDataSource() {
    return dataSource;
}

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.setResultsMapCaseInsensitive(true);

    this.jdbcCall = new SimpleJdbcCall(dataSource)
            .withCatalogName("MYPACKAGE")
            .withProcedureName("MYFUNCTION")
            .withReturnValue()
            .useInParameterNames("IN_1")
            .declareParameters(
                    new SqlInOutParameter("IN_1", OracleTypes.NUMBER),
                    new SqlInOutParameter("OUT_1", OracleTypes.STRUCT, "MYPACKAGE.CUSTOMELEMENTSTYPE",
                            new SqlReturnType() {
                                public Object getTypeValue(CallableStatement cs, int colIndx, int sqlType,
                                        String typeName) throws SQLException {

                                    return null; //just let it work, the I will think what to write here
                                }
                            }));

}

}

 create or replace
 PACKAGE         MYPACKAGE IS

   TYPE CUSTOMELEMENTSTYPE_R IS RECORD (
     C1 VARCHAR2(60),
     C2    VARCHAR2(30)

  );

  TYPE CUSTOMELEMENTSTYPE IS TABLE OF CUSTOMELEMENTSTYPE_R
  INDEX BY PLS_INTEGER;

 FUNCTION MYFUNCTION(
   IN_1 IN INTEGER, OUT_1 OUT CUSTOMELEMENTSTYPE )
 RETURN VARCHAR2;

   END;

create or replace
 PACKAGE BODY MYPACKAGE  IS

   FUNCTION MYFUNCTION(
     IN_1 IN INTEGER, OUT_1 OUT CUSTOMELEMENTSTYPE )
    RETURN VARCHAR2  IS

  BEGIN

 SELECT *  BULK COLLECT INTO OUT_1
    FROM  SOME_TABLE;
   RETURN 'return param';
 END MYFUNCTION;

  END MYPACKAGE ;

The ERROR is:
org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{? = call MYPACKAGE.MYFUNCTION(?, ?)}]; SQL state [99999]; error code [17074]; invalid name pattern: MYPACKAGE.CUSTOMELEMENTSTYPE; nested exception is java.sql.SQLException: invalid name pattern: MYPACKAGE.CUSTOMELEMENTSTYPE
The problem is only with OUT parameter, the same code works, when I dont pass OUT parameter and run it against another version of MYFUNCTION, that has not OUT parameter.
I tried also with OracleTypes.ARRAY (invalid name pattern) and OracleTypes.OTHER (Caused by: java.sql.SQLException: wrong column type: 1111)

A: It seems that You use incorrect method call:
 Your code:
    .withProcedureName("MYFUNCTION")[..]
should be replaced by
    .withFunctionName[...]
here is some simple examle of whole function call:
JdbcTemplate jdbc = new JdbcTemplate(txManager.getDataSource());
    SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbc)
            .withCatalogName("p_adm_www")
            .withFunctionName("fn_usr_get_login_sequence")
            .declareParameters(new SqlOutParameter("RETURN", OracleTypes.NUMBER))
            .withoutProcedureColumnMetaDataAccess();
    jdbcCall.setAccessCallParameterMetaData(false);
    BigDecimal returnId = jdbcCall.executeFunction(BigDecimal.class, null);
    return returnId.longValue();


text:
Q: Como capturar o status (e readyState) do XHR do IE6? Como?
alert(new ActiveXObject("Microsoft.XMLHTTP").readyState);

// undefined
// 0

alert((new XMLHttpRequest).readyState);
// 0

Edit: no meu código, antes eu tinha modificado o this para xhr no escopo de onreadystatechange, mas não tinha funcionado, e depois modifiquei novamente e funcionou, quando @bfavaretto e @GuilhermeNascimento sugeriram. Acho que eu havia esquecido algo. Isso foi realmente um typo enquanto eu modificava o código, mas this deveria funcionar (porém não em alguns navegadores velhos como IE6).

A: Não tenho certeza, mas suponho que o problema seja que devido ao "Ajax" no Internet Explorer 6, 7 e 8 (estes dois últimos se usados em quirks-mode) usarem ActiveX e não o XMLHttpRequest propriamente dito deve-se fazer a checagem do ActiveX "correto", no caso tem o Microsoft.XMLHTTP e o Msxml2.XMLHTTP.

Um detalhe muito importante é que você deve sempre usar XHR em páginas http://, ou seja se usar em file:/// pode falhar.

Então se pretende dar algum suporte para IE6 e 7/8 use assim:
function XHR() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    } else if (window.ActiveXObject) {
        try {
            return new window.ActiveXObject("Msxml2.XMLHTTP");
        } catch (e1) {
            return false;
        }

        try {
            return new window.ActiveXObject("Microsoft.XMLHTTP");
        } catch (e1) {
            return false;
        }
     }
 }

Um detalhe que nos navegadores modernos não afeta, mas em alguns antigos ocorria eram o problema com a ordem da chamada dos métodos, por isto eu sempre usava a seguinte orderm, .open, .onreadystatechange (ou diretamente o .readyState) e .send.
O uso do código seria algo como (leia sobre o .readyState):
var foo = XHR();

foo.open("GET", "/url", true); //Usa chama assíncrona

//Use o readyState após o .open, como já dito
foo.onreadystatechange = function() {

    switch (foo.readyState) {
        case 0:
            //(não inicializado)
        break;
        case 1:
            //(carregando)
        break;
        case 2:
            //(já carregado)
        break;
        case 3:
            //(interativo)
        break;
        case 4:
            //(completo) ... Neste ponto já se pode chamar o responseText

            alert(foo.responseText);
        break;
    }
};

//Faz a requisição
foo.send(null);

Um exemplo com outros Activex (todavia desenvolvi muito para IEs e o código anterior funcionava desde do IE5.01+):
function XHR() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }

    var XMLHttpFactories = [
        "Msxml3.XMLHTTP", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP"
    ];

    var obj = false, i = 0, j = XMLHttpFactories.length;

    for (; i < j; i++) {

        try {
            obj = new window.ActiveXObject(XMLHttpFactories[i]);
        } catch (e) {
            continue;
        }

        break;
    }

    return obj;
}

Nota: O window. é dispensável, só o usei para evitar conflitos com variáveis em outros escopos, o que pode ser quase impossível, mas é apenas para evitar.

Uma dica, prefira evitar (nunca usar) o sync mode:
foo.open("GET", "/url", false);

A: Observe essa linha:
var xhr = window.XMLHttpRequest ? new XMLHttpRequest :

Nota algo errado? Você esqueceu os parênteses! O correto seria isso:
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() :


text:
Q: Results address of empty cell in Excel sheet using XSSF I am reading an Excel sheet using POI's XSSF . The Excel sheet has thousands of rows of user information like user name,  address, age, department etc.
I can read and write the Excel sheet successfully but i want to locate empty/null cell's address  and want to print it as result in another sheet
example result what i want is:
Empty cell  : C5
Empty cell  : E7
Empty cell  : H8

Thanks and appreciate for discussions and replies.

A: You need to check for both Null and Blank cells. Null cells are ones that have never been used, Blank ones are ones that have been used or styled in some way that Excel has decided to keep them around in the file
The easiest way to control this fetching is with a MissingCellPolicy. Your code can then be something like:
Row r = getRow(); // Logic here to get the row of interest

// Iterate over all cells in the row, up to at least the 10th column
int lastColumn = Math.max(r.getLastCellNum(), 10);

for (int cn = 0; cn < lastColumn; cn++) {
      Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
      if (c == null) {
         // The spreadsheet is empty in this cell
      } else {
         // Do something useful with the cell's contents
         // eg...
         System.out.println("There is data in cell " + (new CellReference(c)).formatAsString());
      }
}

You can find more on this in the POI docs on iterating over rows and cells

A: As far as I unterstood your question right, this should do the trick:
XSSFCell cell = (XSSFCell) row.getCell( index );
if( cell == null )
{
  cell = (XSSFCell) row.createCell( index );
}
if( cell.getStringCellValue().trim().isEmpty() )
{
  String cellRef = CellReference.convertNumToColString( cell.getColumnIndex() );
  System.err.println( "Empty cell found: " + cellRef
          + Integer.toString( row.getRowNum() ) );
}


text:
Q: How to parse json string into key value pairs? Unable to parse json string
I have got the following hard coded json. I tried converting it to dictionary and parse it but Im unable to do so.
NSString *hcResponse  = @"{\"status\":1,\"value\":\"Successfully Login\"}";

How to parse such a json into key value pairs?

A: Finally, I've figured it by myself
//convert the string to nsdata
NSData *jsonData = [hcResponse dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
//convert the data to json dictionary
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];


text:
Q: I need help to create a Report Builder in React.js I have a challenge to create a "Report Builder", which aims to allow the creation of financial reports in a customized way from existing editable components.
I haven't found a library that is able to supply what I need, so I believe that the best thing is to build it in parts. I need some help to architect the application.
The first requirements of Report Builder:

*

*A "page" component for the report

*A list of components used for a build the report

*

*(Example of components: Title, Text, Bar Graph, Column Graph, Table)

*Each component can be individually editable according to its type

*A component can be resizable

*You can have more than one component

*The component can be dragged on the report page and placed in the desired location

*The report must be saved and its editing continued later

An existing project that has something very similar to what I need is FathomHQ Reporting.
Its Reporting is showed in this video: https://www.youtube.com/watch?v=Zz-CpLcBO7M
I'm thinking about using DNDKit (https://dndkit.com/) to drag and drop the report, but I'm still not sure how I can keep track of each individual component, and allow that it can be editable.
If anyone has any  library or architectural recommendation for building this project, I'll be glad to hear.


text:
Q: c3p0 connection pooling, DataSources factory, how do I close the pool? I'm trying to use C3P0 for connection pooling with both PostgreSQL and SQLite. The PostgreSQL side works no problem. I've followed the directions here, but I don't understand how to close the SQLite side down when I'm done with it.
In other words, on the PostgreSQL side, where I'm using a ComboPooledDataSource, I can call .close() on my ComboPooledDataSource as shown here. I feel like there should be a .close() for the SQLite side too, but I don't see one on the DataSource.
How do I close down the SQLite side appropriately? Do I even need to?

A: From DataSources.pooledDataSource javadoc:

@return a DataSource that can be cast to a {@link PooledDataSource} if you are interested in pool statistics

And PooledDataSource has close method.


text:
Q: What is causing my scripts to be requested twice while using Modernizr.load (yepnope.js) I am using yepnope.js to load javascript files dynamically,and I've noticed that my scripts appear to be loaded twice according to Firebug and Webkit Inspector.
The problem is that in Firebug's Net panel (Firefox 4 latest), their response is a 200, not a 304. It seems to be slower than in Chrome.
I have uploaded this video showing the issue. You can see how the files jquery-1.6.1.min.js and libs.js are loaded an extra time.
The code I am using to do this is the following, simplified:
Modernizr.load({
                load: ['jquery-1.6.1.min.js', 'libs.js'],
                complete: function () {
                    console.log("loaded");
                }
});

Modernizr.load() is yepnope().

A: There's a note about this in their documentation:
From http://yepnopejs.com/

I'm seeing two requests in my dev
  tools, why is it loading everything
  twice?
Depending on your browser and
  your server this could mean a couple
  different things. Due to the nature of
  how yepnope works, there are two
  requests made for every file. The
  first request is to load the resource
  into the cache and the second request
  is to execute it (but since it's in
  the cache, it should execute
  immediately). Seeing two requests is
  pretty normal as long as the second
  request is cached. If you notice that
  the second request isn't cached (and
  your script load times are doubling),
  then make sure you are sending the
  correct cache headers to allow the
  caching of your scripts. This is vital
  to yepnope. It will not work without
  proper caching enabled. We actually
  test to make sure things aren't loaded
  twice in our test suite, so if you
  think we may have a bug in your
  browser regarding double loading, we
  encourage you to run the test suite to
  see if the double loading test passes.


text:
Q: Moment generating function of a sum of i.i.d. random variables Let $\{ Y_j: 1\leq j \leq K \}$ be a collection of i.i.d. random variables. Suppose we have two random variables $W$ and $W'$ that have the same distribution function, where $W'$ is given by:
$$W'=\sum_{j=1}^{K} Y_j,$$
where $K$ is a random number.
Then:

$M_W(s)=G_K(M_Y(s))$, where $M_Y$ is the moment generating function of $Y$.

Since $W$ and $W'$ have the same distribution, they have the same moment generating function: $$M_W(s)=M_{W'}(s).$$
By definition of the probability generating function, the RHS is given by:
$$G_K(M_Y(s))=\mathbb{E}[(M_Y(s))^K]=\mathbb{E}[(\mathbb{E}[e^{Ys}])^K].$$
To compute the LHS, I condition on $K$:
$$M_{W'}(s)=\mathbb{E}[e^{W' s}]=\mathbb{E}[\mathbb{E}[e^{W' s} \vert K]]=\mathbb{E}[\mathbb{E}[e^{s\sum_{j=1}^{K}Y_j } \vert K]]=\mathbb{E}[\mathbb{E}[e^{sY_1s+...Y_Ks} \vert K]]=\mathbb{E}[\mathbb{E}[e^{Y_1s}\vert K]...\mathbb{E}[e^{Y_Ks}\vert K] ]=\mathbb{E}[\mathbb{E}[e^{Ys}\vert K]^K ].$$
So is $\mathbb{E}[(\mathbb{E}[e^{Ys}])^K]=\mathbb{E}[\mathbb{E}[e^{Ys}\vert K]^K ]$?

A: If the random variables $Y$ and $K$ are independent, then $
\Bbb E[e^{Ys}\mid K] = \Bbb E[e^{Ys}]$ a.s., hence
$$
\Bbb E[\Bbb E[e^{Ys} \mid K]^K] = \Bbb E[\Bbb E [e^{Ys}]^K].
$$


text:
Q: Asp.Net, SQL and TimeZones It's been asked, but I am battling to grasp the concept of how to handle timezones in a web app. I have a system that tracks the progress of projects. I have a ProjectStartDate DATE in my SQL Server database. (There's a few more fields and tables, but lets focus on one).
The server is located somewhere in the United States. I live in Australia.
Calling SELECT GETDATE() returns "2013-08-11 14:40:50.630"
My system clock shows "2013-08-12 07:40"
In my database, I have 'CreateDateTime' columns on all tables. When I store that, within my c# code, I use CreateDate = DateTime.UtcNow
I use that, as I heard it was better to use UTC.
But, when a user is presented with a calendar control, and they select a Start Date for a project, I store what ever the user selected. No conversion... And as I said, the StartDate is a DATE type in the database.
The problem is, if a project started today - my front end says that the current project is No Started, because the server is still in Yesterday.
I think the dates should be stored as I am storing them. But maybe I need to somehow get the users timezone, and apply that on the UI level?
Problems I see are:

*

*I don't know the users timezone. Add something to allow them to select it?

*The status of the project maybe determined in a stored procedure, so when can I apply the conversion? In the proc, it might do a check, and return a VARCHAR stating "Not Started" if the StartDate <= DateTime.Now?

I use EntityFramework and Linq to get data most of the time. I need a strategy for inserting and retrieving data, both from a  SQL sense, and a .Net sense.
I have added code to get the user to select their timezone based on this:
public List<TimeZoneDto> GetTimeZones()
{
    var zones = TimeZoneInfo.GetSystemTimeZones();
    var result = zones.Select(tz => new TimeZoneDto
        {
            Id = tz.Id,
            Description = tz.DisplayName
        }).ToList();

    return result;
}

That is then persisted in their profile.
All dates are being stored as UTC, as advised in the answers below.
I'm still confused how to handle the dates when they go to and from the database, to the client. Here is an example of how I am storing a record:
public int SaveNonAvailibility(PersonNonAvailibilityDto n)
{
    person_non_availibility o;

    if (n.Id == 0)
    {
        o = new person_non_availibility
            {
                PersonId = n.PersonId,
                Reason = n.Reason,
                StartDate = n.StartDate,
                EndDate = n.EndDate,
                NonAvailibilityTypeId = n.NonAvailibilityTypeId,
                CreateUser = _userId,
                CreateDate = DateTime.UtcNow

            };
        _context.person_non_availibility.Add(o);
    }
    else
    {
        o = (from c in _context.person_non_availibility where c.Id == n.Id select c).FirstOrDefault();
        o.StartDate = n.StartDate;
        o.EndDate = n.EndDate;
        o.Reason = n.Reason;
        o.NonAvailibilityTypeId = n.NonAvailibilityTypeId;
        o.LastUpdateDate = DateTime.UtcNow;
        o.LastUpdateUser = _userId;
        o.Deleted = n.Deleted ? DateTime.UtcNow : (DateTime?)null;
    }
    _context.SaveChanges();
    return o.Id;
}

This method basically saves when a person is not available for work. Note the way I store the LastUpdateDate. Also, the 'Start' and 'End' dates. Those dates are more 'Business' dates.
On selection, and then date checking, is where I have issues. In this example, I am getting a persons rate of charge, based on NOW.
public decimal CurrentRate
{
    get
    {
        if (ResourceCosts != null)
        {
            var i = ResourceCosts.FirstOrDefault(t => DateTime.UtcNow <= (t.EndDate.HasValue ? t.EndDate.Value : DateTime.UtcNow) && DateTime.UtcNow >= t.StartDate);
            if (i != null) return i.Cost;
            return 0;
        }
        return 0;
    }
}

So, what I am wanting to do here, is, based on the current date, I want to see his rate (As his charge our rate maybe be $100 from the 1st Jan, to the 15th Jan, and then $110 from the 16th until the 31st of Jan. So, I look for the rate applicable today (if any). This doesn't work across time zones, and it's maybe here where I need to do some date manipulation based on the 'DateTime.UTCNow'?
Note, I now know the users timezone based on the code above where I am storing his timezone. I can use that somehow here? Maybe, when the user logs in, grab the date info from his profile (Zimezone info), and then have a global shared function, that returns the users datetime, based on adding or removing hours from the UTC Date... and using that where ever I am doing DateTime.UTCNow?
Hope someone can guide me.

A: You may find that there is not one single "right" way to handle all of this.  There are multiple approaches to the several different problems you describe in your question. I will attempt to clarify a few points.

*

*First, don't ever attempt to think about local time on a server.  Your code and data should not have to change based on where you deploy it.  You said your server was in the USA, but there are multiple time zones to consider, and many servers will have their time zone set to UTC regardless of their physical location.
You should avoid GETDATE() or SYSDATETIME() in SQL Server.  If you need a current timestamp in SQL, use GETUTCDATE() or SYSUTCDATETIME().  If for some reason the server's time zone is important to you, use SYSDATETIMEOFFSET() instead.
Likewise, avoid using DateTime.Now in .Net from any server-side code.  Use DateTime.UtcNow or DateTimeOffset.UtcNow  for a UTC timestamp, or use DateTimeOffset.Now if for some reason the server's time zone is important to you.
You can read more about this in my blog post: The Case Against DateTime.Now

*Next, let's talk about the data type you're using.  The date type in SQL Server stores just a date. That's it.  No time, no offset, and no time zone.  An example would be 2013-08-11.  You should use it when you really mean a whole calendar date.  There is no worldwide uniform context of "today".  Instead, everyone has their own meaning based on their time zone.  Also, not every calendar day is 24 hours in length.  A day could be 23, 23.5, 24, 24.5 or 25 hours long, depending on how daylight saving time is applied in the particular time zone, and if you are evaluating the day of a DST transition.
In .Net - there is no Date type, so a SQL date is converted to a DateTime with the time set to midnight (00:00:00), and the kind set to Unspecified.  But don't fool yourself - the time isn't suddenly midnight, we are just filling in zeros for the time.  This can lead to a lot of error and confusion.  (If you want to avoid that, you can try Noda Time, which has a LocalDate type for this purpose.)

*What you really need to be thinking about, and haven't defined in your question, is this:

What exact moment does a project start?

Right now you are just saying 2013-08-11, which doesn't refer to a specific moment in time.  Do you mean the beginning of that day in a particular time zone?  Or do you mean the beginning of that day according to the user's time zone?  Those might not be the same thing.  You can't compare to anyone's "now" (utc, local, or otherwise) unless you know what moment in time you are talking about.
If the project starts at an exact moment in time worldwide, then the easiest thing would be to store a datetime (or datetime2) type that contains that precise time in UTC.  So you might say that a project starts at 2013-08-10T14:00:00Z - which would be exactly midnight on August 11th in Sydney, Australia.  In .Net, you would use a DateTime type with the .Kind set to Utc.
Another way you could represent this is by storing a datetimeoffset type that has a value of 2013-08-11T00:00:00+10:00 - which is the same moment in time, but uses the offset to give you a value that is pre-converted.  (Sydney is at UTC+10 on that date).  You would use the DateTimeOffset type to work with this in .Net.
But if the project starts at different times depending on the user, then it's not really an exact moment in time.  It's more of a "floating" start.  If users from different places around the world are assigned to the same project, then some users could be starting before others.  If that's your intention, then you can just use the date type if all projects start at midnight, or you can use a datetime or (datetime2) type if projects might start at different times.  In your .Net code, you would use a DateTime type with the .Kind set to Unspecified.

*With regard to getting the user's time zone, the best thing you could do would be to ask them.  Despite the common misconception - you can't just get it from the browser.  All you could tell from the browser is what their current offset is.  (Read the "TimeZone != Offset" section of the timezone tag wiki).
When asking the user for their time zone, if you decide to use Windows time zones you can produce a dropdown list from the TimeZoneInfo.GetSystemTimeZones method.  The .Id is the key you store in your database, and you show the .DisplayName to the user.  Later you can use the TimeZoneInfo.FindSystemTimeZoneById method to get a TimeZoneInfo object that you can use for conversions.
If you wanted to be more precise, you could use IANA time zones instead of the Windows time zones.  For that, I recommend using a map-based timezone picker control, such as this one.  You might also use jsTimeZoneDetect to guess a default value for your control.  On the server you would use Noda Time to perform time zone conversions.

*There is an approach that doesn't require time zone conversions.  Basically, you do everything in UTC.  That includes transmitting the time to the browser in UTC.  You can then use JavaScript to get the user's current time in UTC and compare against that.
You can use various functions of the JavaScript Date class to do this if you wish.  But you may find it easier to work with a library such as moment.js.
While this approach is viable for many things, security is not one of them.  Your user can easily change the clock of their computer to work around this.

*Another approach would be to compare server-side against UTC.  If you have the exact UTC starting time in your database, then you can just check DateTime.UtcNow in your .Net code and use that to decide what to do.  You won't need the user's time zone to make this comparison, but you will need it if you want to show them what that means in their local time.
I hope this clears up the confusion and didn't make it worse! :)  If you have additional concerns, please edit your question or ask in comments.
UPDATE
In response to your updated question, I suggest you try the following:
var timeZoneId = "Eastern Standard Time"; // from your user's selection
var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
var nowInTimeZone = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZone);
var todayInTimeZone = nowInTimeZone.Date;

var i = ResourceCosts.FirstOrDefault(t => t.StartDate <= todayInTimeZone &&
            (!t.EndDate.HasValue || t.EndDate >= todayInTimeZone));

Of course this means that in your StartDate and EndDate fields, you are not storing these as UTC - but rather as the "business dates" that are relevant to the user.  These only line up to a specific moment in time when you apply a time zone, so the same UTC timestamp could fall on different dates depending on what the user's time zone is.
Also, you are using fully inclusive ranges, which is usually OK for these kind calendar date ranges.  But make sure you realize that there could be overlap.  So if you have 2013-01-01 - 2013-02-01 and 2013-02-01 - 2013-03-01, then there is that one day 2013-02-01 that is in both ranges.
A common way around this problem is to use half-open intervals, [start,end).  In other words, start <= now && end > now.  But this is more common when using a full date and time instead of just a date.  You might not need to do this, but you should at least think about it for your particular scenario.

A: You can get a user's timezone from the browser. This will only get the value that they've set on their computer.  So they can manipulate this for their advantage. For example, if you were limiting access until midnight local time, they could change their time to get "early" access.  So keep that in mind.
Next what you'll want to do is store all times in UTC in the database. Instead of using GetDate() you can use GetUTCDate().
Next, you can either store their timezone, or their offset from UTC in the database.  You get into some danger just storing the UTC offset, because timezones that observe daylights savings will have different offsets at different time of the year.
But with these two pieces of information, you can calculate the "local" time of the user. You can either add the number of hours to your stored date, then compare that to the local server time (also adjusted from UTC.)
Of if you don't really care that much, you can store the time in UTC in the database, then simply compare DateTime.UTCNow on the server to determine if they should have access or not.