text:
Q: kubernetes elastic all-in-one fails on arm64 machines? I was working on setting up ELK on a Kubernetes cluster, and it works on my macbookpro for tests, but when i tried to do it on my ubunutu arm64 machines clustered together it fails.
When i noticed it was giving exec errors, I immediately knew it was failing to run an arm64 variant as I had a similar issue with some containers i was using for different projects and just needed to use buildx to create arm64 support.
Anyways, This is my current flow.  Join me on an adventure.
Given a fresh Ubuntu install on a Arm64, Raspberry Pi 4, 4G.

*

*Update, Upgrade, and install kubeadm,kubectl, etc.  I set up a second machine, so now i have a cluster of size 2.  (sweet! Im proud so far!)

*I go to the k8s website, and grab the all in one.
kubectl apply -f https://download.elastic.co/downloads/eck/1.3.0/all-in-one.yaml

*Now that all the kubernetes is set up, I should be able to launch my Elasticsearch pod, and I do.  I do a kubectl get elasticsearch to see my new pod.  Says the name but no state.

*Time to see whats up.  kubectl get pods --all-namespaces
BUT WAIT. What is this, elastic-operator-0.  Interesting, never used THIS before.  BUT it exists on my machine and on my pro, so it much have some value.  Wait. Its in an indefinite crashloopbackoff.  Interesting.  Attempts to describe or logs failed.  Realized it is giving exec errors, which I know is from an architecture mismatch.
So this leads me to now.
Desired Endstate:
I am trying to install Elasticsearch, Kibana, and Logstash.
Elasticsearch AND Kibana arent built off of images, but instead the Types in the all in one,   elasticseatch.k8s.elastic.co and kibana.k8s.elastic.co respectively.  Logstash though is built off of a docker container: docker.elastic.co/logstash/logstash:7.9.2
So here is my conundrum.   How do I get this back up and functional?  It seems that kibana and elasticsearch are not developing state (red, green or otherwise) until this elastic-operator-0 is up and running.
I am trying to trim and clean this all up such this works again.  I have no problem with removing everything installed with all-in-one, and then just doing tweaks but im not sure how much additional work it would be.
Below is my sample YAML file.
---
apiVersion: elasticsearch.k8s.elastic.co/v1
kind: Elasticsearch
metadata:
  name: elasticsearch
  labels:
    app.kubernetes.io/name: eck-logstash
    app.kubernets.io/component: elasticsearch
spec:
  version: 7.9.2
  nodeSets:
    - name: default
      count: 1
      config:
        node.store.allow_mmap: false
---
apiVersion: kibana.k8s.elastic.co/v1
kind: Kibana
metadata:
  name: kibana
  labels:
    app.kubernetes.io/name: eck-logstash
    app.kubernets.io/component: kibana
spec:
  version: 7.9.2
  count: 1
  elasticsearchRef:
    name: elasticsearch
---
apiVersion: v1
kind: ConfigMap

metadata:
  name: logstash-config
  labels:
    app.kubernetes.io/name: eck-logstash
    app.kubernets.io/component: logstash
data:
  logstash.yml: |
    http.host: "0.0.0.0"
    path.config: /usr/share/logstash/pipeline
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: logstash-pipeline
  labels:
    app.kubernetes.io/name: eck-logstash
    app.kubernets.io/component: logstash
data:
  logstash.conf: |
    input { }

    filter { }

    output {
      elasticsearch {
        hosts => [ "${ES_HOSTS}" ]
        user => "${ES_USER}"
        password => "${ES_PASSWORD}"
        cacert => '/etc/logstash/certificates/ca.crt'
        index => "sample-%{+YYYY.MM.dd}"
      }
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: logstash
  labels:
    app.kubernetes.io/name: eck-logstash
    app.kubernets.io/component: logstash
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: eck-logstash
      app.kubernets.io/component: logstash
  template:
    metadata:
      labels:
        app.kubernetes.io/name: eck-logstash
        app.kubernets.io/component: logstash
    spec:
      containers:
        - name: logstash
          image: docker.elastic.co/logstash/logstash:7.9.2
          env:
            - name: ES_HOSTS
              value: "https://elasticsearch-es-http.default.svc:9200"
            - name: ES_USER
              value: "elastic"
            - name: CUSTOM_ENV_TEST
              value: "Helloworld"
            - name: ES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: elasticsearch-es-elastic-user
                  key: elastic
          volumeMounts:
            - name: config-volume
              mountPath: /usr/share/logstash/config
            - name: pipeline-volume
              mountPath: /usr/share/logstash/pipeline
            - name: ca-certs
              mountPath: /etc/logstash/certificates
              readOnly: true
      volumes:
        - name: config-volume
          configMap:
            name: logstash-config
        - name: pipeline-volume
          configMap:
            name: logstash-pipeline
        - name: ca-certs
          secret:
            secretName: elasticsearch-es-http-certs-public


text:
Q: Date Parameters and Values From SSAS Tabular 2016 / SSRS 2016 I have a tabular model in SSAS, with a date column as a dimension member - set to date and general in SSAS column properties.
When I use this column to return data in SSRS 2016 - and more importantly - as a parameter, it looks like a string - with no date picker. I also can't use things like > @date or < @date as a filter.
Have I missed a step to declare the column as a date. I'm used to using this in a standard sql connection which works perfectly - just not in SSAS Tabular / DAX.
Any help appreciated
Thanks,
W

A: You need to change both the "Data Type" and "Data Format" to date types in your SSAS tabular data model. Please see the image below:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel 4 Database configuration with $_ENV I want to use Laravel Environment for my Database credential, I did this:
inside bootstrap\start.php :

$env = $app->detectEnvironment(array(
'local' => array('My_PC'),
'production' => array('server.example.com')
));

created .env.local.php on same directory where serve.php is, and inside this code:

return array(
'DATABASE_NAME' => 'laravel_db',
'DATABASE_USER' => 'root',
'DATABASE_PASSWORD' => '1234'

);

and inside app\config created a local\app.php file containing this code:

return array(
'debug' => true,
);

and inside the app\config\database.php for my secured mysql connection I did:
'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => $_ENV['DATABASE_NAME'],
            'username'  => $_ENV['DATABASE_USER'],
            'password'  => $_ENV['DATABASE_PASSWORD'],
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

but I'm getting an error on the CLI:
{"error":{"type":"ErrorException","message":"Undefined index: DATABASE_NAME","file":"c:\\xampp\\htdocs\\Larave_project\\app\\config\\database.php","line":58}}
How to resolve this issue?

A: The hostname based env detection solution will only work on Unix type system.
It won't work on Windows.

A: In Laravel 4.2 you can detect environment this way:
$env = $app->detectEnvironment(function() {
    if ($_SERVER['SERVER_NAME'] == "127.0.0.1") {
            $domain = $_SERVER['HTTP_HOST'];

            if (strpos($domain, 'localhost') !== FALSE || strpos($domain, "127.0.0.1") !== FALSE) {
                die("Configure your local `hosts` file and go to address: http://{storeName}.local");
            }

        $len = strpos($domain, ".local");

        if ($len !== FALSE) {
            // will load .env.*.php
            $len = strpos($domain, ".local");
            $env = substr($domain, 0, $len);

            return $env;
        }
    }

    // will load .env.php
    return 'production';
});

(this is bootstrap/start.php)
Then:

*

*setup hosts file (in your operating system) to redirect mysuperstore.local to 127.0.0.1

*go to URL like http://mysuperstore.local which loads .env.mysuperstore.php into $_ENV.

In configuration files (those placed in app/config/) refer to $_ENV. To see where $_ENV does come from take a look into documentation topic about "Protecting Sensitive Configuration".


text:
Q: Использование Wait() Pulse(). Разделение общего ресурса Пишу простенькую программу, в которой есть несколько потоков, и каждый из них поочередно получает доступ к общему ресурсу и выполняет какое-то действие. Я понимаю, что Wait() - освобождает объект блокировки, и блокирует выполнение потока пока другой поток не вызовет Pulse(), ну и Pulse() - позволяет потоку в находящемуся в Wait() выполнятся дальше.
Ресурс
class Sourse
{
    object objLock = new object();

    public void toDo(string name)
    {
        lock (objLock)
        {
            Monitor.Pulse(objLock);
            Console.WriteLine($"Поток {name} получил доступ и выполняется.");
            Monitor.Wait(objLock);
        }
    }
}

Мои треды
class MyThread
{
    Thread thrd;
    static Sourse srs = new Sourse();

    public MyThread(string name)
    {
        thrd = new Thread(this.Run);
        thrd.Name = name;
        thrd.Start();
    }

    public void Run()
    {
        while (true)
        {
            srs.toDo(thrd.Name);
            Thread.Sleep(1000);
        }
    }
}

И точка входа в программу:
class Program
{
    static void Main(string[] args)
    {
        MyThread first = new MyThread("1");
        MyThread second = new MyThread("2");
        MyThread third = new MyThread("3");
    }
}

Если я организовываю код таким образом, каким показал выше - выполняется несколько потоков одновременно, действия никак не синхронизированы. Если я пишу таким образом:
lock (objLock)
    {
        Monitor.Wait(objLock);
        Console.WriteLine($"Поток {name} получил доступ и выполняется.");
        Monitor.Pulse(objLock);
    }

То разумеется все потоки заблокируются не выполнив никаких действий, и все встанут в ожидание. Худо бедно необходимый мне результат достигается если я организовываю ресурс следующим образом:
      bool key = true;
      lock (objLock)
        {
            if(key == true)
            {
                Console.WriteLine($"Поток {name} получил доступ и выполняется");
                key = false;
                Monitor.Wait(objLock);
            }
            else
            {
                key = true;
                Monitor.Pulse(objLock);
            }
        }

но подобная запись выглядит как костыльный костыль, и тем более, не отвечает всем выдвигаемым требованиям, так как при старте программы сразу 2 потока получает доступ и выполняется одновременно, а этого к слову того не должно быть. Вопрос в следующем: как реализовать поочередный доступ из нескольких потоков к общему ресурсу таким образом, чтобы ресурс всегда был доступен только одному потоку? Можно ли добиться нужного мне результата без подобных булевых кеев?

A: У вас уже используется lock, который внутри использует Monitor. Ручной работой через Monitor вы ему мешаете. Просто уберите ручные вызовы и все заработает.
class Sourse
{
    object objLock = new object();

    public void toDo(string name)
    {
        lock (objLock)
        {
            Console.WriteLine($"Поток {name} получил доступ и выполняется.");
        }
    }
}


text:
Q: EF CodeFirst THT - Column 'Id' specified as part of this MSL does not exist in MetaDataWorkspace I'm using a 'table-per-type' hierarchy in my code-first project (EF5).
My derived classes override the default primary-key name to clearly identify this relationship from a database point of view, like so:
/* change primary keys to Chair.ProductId and Table.ProductId */
modelBuilder.Entity<Chair>()
    .Property(x => x.Id)
    .HasColumnName("ProductId");

modelBuilder.Entity<Table>()
    .Property(x => x.Id)
    .HasColumnName("ProductId");

Using the following classes as example:
[Table("Product")]
public class Product
{
   public int Id {get; set;}

   /* generic product properties */
}

[Table("Chair")]
public class Chair : Product
{
     /* specific chair properties */
}

[Table("Table")]
public class Table : Product
{
     public virtual ICollection<Chair> Chairs {get; set;}

     /* specific table properties */
}

Which causes the following error on property Table.Chairs: Column 'Id' specified as part of this MSL does not exist in MetaDataWorkspace.
Which I kinda understand as EF probably didn't see that the PK of Chair Product was changed.. (and still assumes it's called 'Id') But I can't figure out how I instruct EF to use the alternate key.
Thx,
PS. Yes I know, if I don't change the names of the PK's it works... but can it be done using the EF Fluent API?

A: This is some bug of EDMX model generator in Visual Studio.
To solve this do:

*

*remove particular table from EF.

*save EF and restart Visual Studio

*add particular table to the model again

*save and compile

I have Visual Studio 2015 udpate 3

A: I recently was searching for a fix to a similar error, but designing things Database first.  I post my finding here because this is where my search kept landing me.
I had multiple similar errors, on build.  What they really meant is that my Model never built successfully.
I was able to fix the issue by removing and re-adding some table valued functions that had been modified in the database recently.
Most of the errors and details I could find where actually just red-herrings; other than the concept that the model didn't build successfully; and having knowledge of things someone else was changing in the database helped.

A: Posting your comment as an answer:
Add the following:
modelBuilder.Entity<Table>().HasMany(x => x.Chairs).WithMany()
.Map(m => {
 m.MapLeftKey("TableId"); m.MapRightKey("ChairId");
 m.ToTable("TableChairs");
});

A: I was experiencing similar errors and had made some manual fixes to my edmx file, but Visual Studio was still reporting this warning.
Turns out it was a false warning and clean/rebuild got rid of the error. Spent hours trying to figure out what was wrong with the edmx file but never thought of giving it a run and checking if it was actually a problem.

A: I got the same one. Looking at all this I thought something is off with visual studio I mean no software is perfect right, a minute later I found a typo in my code :-|


text:
Q: Marginal effects with logistic generalized additive model in R I am currently working with a logistic semi-parametric model in R using the mgcv package.  The output from the model gives the standard log-odds coefficients; however, reviewers have requested marginal effects (like the ones in Stata using the margins command).  I would like to do average marginal effects (though, marginal effects at the means--modes for categorical covariates--would at least be a start).
I was wondering if anyone has an implementation for this in R for models that use the gam() function.  I have a rather large data set (1.2 million observations, a large number of discrete and continuous covariates, and fixed effects for 2,000 individuals).  Are these estimates even tractable, given the non-parametric treatment of a couple of the continuous covariates?  Any information would be helpful.
Here is what I am working with, though I get errors when attempting to do the bootstrapped SEs for the effects (comes from this helpful site probitlogit-marginal-effects-in-r-2/).  I am not sure how this treats the non-parametrically estimated smooths (but maybe these don't matter, since it is using the "predict" function?):
mfxboot <- function(modform,dist,data,boot=1000,digits=3){ #dist is the distribution choice of logit or probit
      require(mgcv)

x <- gam(modform, family=binomial(link=dist),method="GCV.Cp",data)
      # get marginal effects

pdf <- ifelse(dist=="probit",
 mean(dnorm(predict(x, type = "link")))
 mean(dlogis(predict(x, type = "link")))
 marginal.effects <- pdf*coef(x)

bootvals <- matrix(rep(NA,boot*length(coef(x))), nrow=boot)
set.seed(1111)
for(i in 1:boot){
samp1 <- data[sample(1:dim(data)[1],replace=T,dim(data)[1]),]
x1 <- gam(modform, family=binomial(link=dist),method="GCV.Cp",samp1)
pdf1 <- ifelse(dist=="probit",
mean(dnorm(predict(x1, type = "link"))),
mean(dlogis(predict(x1, type = "link"))))
bootvals[i,] <- pdf1*coef(x1)
}

res <- cbind(marginal.effects,apply(bootvals,2,sd),marginal.effects/apply(bootvals,2,sd))
if(names(x$coefficients[1])=="(Intercept)"){
res1 <- res[2:nrow(res),]
res2 <- matrix(as.numeric(sprintf(paste("%.",paste(digits,"f",sep=""),sep=""),res1)),nrow=dim(res1)[1])
rownames(res2) <- rownames(res1)
} else {
res2 <- matrix(as.numeric(sprintf(paste("%.",paste(digits,"f",sep=""),sep="")),nrow=dim(res)[1]))
rownames(res2) <- rownames(res)
}
colnames(res2) <- c("marginal.effect","standard.error","z.ratio")
      return(res2)
}


text:
Q: Heatmap - Generating Simple 'HeatPoint' Google Maps Android Android SDK 2.3.3
Google Maps V2
Currently I'm drawing circles overlays and adding them to a MapView. The size is dictated by a certain value and I'm looking to determine the RadialGradient color of the circle by something else.
            circle.setShader(new RadialGradient(pt.x, pt.y, 40, Color.argb(150, 252, 5, 5), Color.argb(60, 234, 231, 0), TileMode.MIRROR));
            canvas.drawCircle(pt.x, pt.y, radius, circle);

It works, however I'd prefer the edges to look more similar to the classic heatpoint map.
Current

What I'd like to achieve (I'd still like the shape to be circular)

I'm thinking of possibly drawing a circle directly underneath the current with a sightly bigger area in order to achieve a more typical heatmap look, however this has performance implications considering I'm doing this on a mobile device which has to re-render per zoom in or out action.

A: There are a few obvious options here, and I'm sure there are many more non-obvious ways to do this as well:

*

*Draw multiple concentric circles as you suggested

*Load a concentric circle pattern from an image and draw that (less rendering, but, of course, you have to load the image)

*Use a BitmapShader to draw a single circle with a custom gradient that matches what you're looking for: http://developer.android.com/reference/android/graphics/BitmapShader.html
Unfortunately, I don't know which of these options will give you the best performance, so you'll probably have to test them yourself. I suspect that, for a large number of heatmap points, one of the later two options will be more efficient, but that's nothing more than a guess.


text:
Q: What does the return value of removal of string from variable mean in Bash? I would like to check what the following code really did.
"resultant_value="${original_value%/*}"

It removes a pattern, '/*', from a variable, original_value.
To check the removal had happened I checked the return value of it, like following.
original_value=''
resultant_value="${original_value%/*}"
result=$?
echo "remove 1: result = ${result} : original_value = ${original_value}, resultant_value = ${resultant_value}"

original_value='../..'
resultant_value="${original_value%/*}"
result=$?
echo "remove 2: result = ${result} : original_value = ${original_value}, resultant_value = ${resultant_value}"

The outputs are following
remove 1: result = 0 : original_value = , resultant_value =
remove 2: result = 0 : original_value = ../.., resultant_value = ..

Both return values are 0. It seems that return value from ${original_value%/*} does not care of removal of matched pattern or not.
What does the return value of removal of string from variable mean in Bash?
Thank you very much.

A: In bash, the return value/exit status of a variable assignment statement is defined by the following rules:

The text after the = in each variable assignment undergoes tilde
  expansion, parameter expansion, command substitution, arithmetic
  expansion, and quote removal before being assigned to the variable.
If any of the assignments attempts to assign a value to a readonly
  variable, an error occurs, and the command exits with a non-zero
  status.
If one of the expansions contained a command substitution, the exit
  status of the command is the exit status of the last command
  substitution performed.  If there were no command substitutions, the
  command exits with a status of zero.

Thus, of all different types of expansions only command substitution ($(...)) can affect the status of an assignment statement. Parameter expansions, including prefix/suffix removals, don't influence the return value in any way*.
* The only exception is the ${parameter:?error_message} - Display  Error if Null or Unset version of parameter expansion when used in an interactive shell (in a non-interactive shell a failed expansion of this kind simply quits the shell).


text:
Q: Need date time formatting help This code record.Start_Time__c.time() is giving me 11:30:00.000Z but I just want 11:30am or pm or army time might be ok too.
This code currStartDate.Date() is giving me 2015-07-08 00:00:00 but I just want 2015-07-08
What do I need to do?

A: Take a look at Java SimpleDateFormat.
system.debug(Datetime.now().format('hh:mmaa')); // 08:24AM
system.debug(Datetime.now().format('hh:mm:ss aa')); // 08:24:07 AM
system.debug(Datetime.now().format('yyyy-MM-dd'));  // 2016-05-31

Note that these are methods on Datetime, so you should not call date() or time() on your Datetime value before doing the formatting, as doing so will change the type to Date or Time respectively, and neither of these types have a format method defined`.

A: You should be able to use below lines,
record.Start_Time__c.format('hh:mm a');    //11:30 AM
currStartDate.format('yyyy-MM-dd');        //2015-07-08


text:
Q: Displaying logged tickets for CompanyX when user with role X is logged in I am setting up an app where citizens can log tickets online to companies registered on our app. We have 5 types of User Roles

- [ App Super Admin, App Admin & App Support User ]
  ** Must see all logged tickets for all companies
- [ Company Admin & Company Support User ]
  ** Must see only tickets for their company
- [ App User ]
  ** Must see only their own logged tickets

Problem is that I see all tickets for all companies, irrespective of which user is logged-in.
I want the logged-in Company Support user or Company Admin to see only tickets logged for their company only and the app user who logged the ticket to only see their own tickets.
    {
        $companyUser = companyUser::findOrfail($user);

        if (Auth::user()->id = $companyUser) {
            $tickets = DB::table('tickets')
                ->join('company_users', 'company_users.company_id', '=', 'companies.id')
                ->join('tickets', 'ticket.company_id', '=', 'company_users.company_id')
                ->select(
                    'tickets.ref_no',
                    'tickets.service_id',
                    'tickets.ticket_subject_id',
                    'tickets.ticket_status_id',
                    'tickets.ticket_priority_id',
                    'tickets.company_id',
                    'tickets.user_id',
                    'tickets.created_at'
                )
                ->where('company_users.user_id = users.id')
                ->get();
        } else {
            $tickets = DB::table('tickets')
                ->join('company_users', 'tickets.company_id', '=', 'company_users.company_id')
                ->select(
                    'tickets.ref_no',
                    'tickets.service_id',
                    'tickets.ticket_subject_id',
                    'tickets.ticket_status_id',
                    'tickets.ticket_priority_id',
                    'tickets.company_id',
                    'tickets.user_id',
                    'tickets.created_at'
                )
                ->groupBy('ref_no')
                ->get();
        }


text:
Q: how to handle backend credentional in wso2 api manager? I am using wso2 apimanager 3.2.0 and I am going to design some rest service that use my backend service. this backend service has basic authentication, so how to invoke and handle it in apim?

A: You can define endpoint security when you are developing the API the Endpoints section of the API in the Publisher portal.
For more information, see documentation.


text:
Q: Disable WCF self signed certificate validation in BizTalk I have an WCF-BasicHttp send port calling a web service that is secured with a self signed SSL certificate.  This is all deployed in a test environment, where we don't have access to proper certificates.
BizTalk returns an error "Could not establish trust relationship for the SSL/TLS secure channel" because it correctly can't trust an unsigned certificate.  Is there any way to configure BizTalk or the send port to disable the certificate validation?
I've seen code samples, but that won't work because there's nothing to code: BizTalk send ports are purely configuration:
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
...
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidationCallback);
...
 public static bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
 {
    return true;
 }

I've also looked at updating the BtsNtSvc.exe.config configuraiton file, specifying checkCertificateName="false" but that doesn't work because that setting only affects message level certificate validation, not transport.
<system.net>
<settings>
    <servicePointManager checkCertificateName="false" checkCertificateRevocationList="false"/>
</settings>
</system.net>

With Dijkgraaf's response, I have imported the certificate to the appropriate stores for my biztalk send service, and it partially resolves the issue.   We have about 65000 messages suspended.  If I resume 200 of them in a batch, 50% or more will get sent to the Https web service but the rest will error out with the same error.  Eventually BizTalk will retry and the messages will go through.  I am unsure what causes the error to manifest at this point - high throughput, or high memory consumption or other.

A: No you can't disable it. You need to add the self signed certificate into the trusted root certificate store of the BizTalk host user, this way it will trust the cert.


text:
Q: Chrome: location.reload() of popup not working In short, I have a project where I need to test XSS payloads for their validity. (if they still work or not) After some time I came to the conclusion, that the best way to test these payloads, is by creating a popup window, writing the payload, refreshing the popup and closing the popup. The code looks like the following:
function create_window_window_opt()
{
    if(payloads.length > 0)
    {
        var popup = window.open();
        popup.focus();
        var payload = "<!DOCTYPE html>" + payloads.shift() + "<script>setTimeout(function(){location.reload();},100);</scr"+"ipt></html>";
        popup.document.write(payload);
        setTimeout(function(){popup.close();create_window_window_opt();},200);
    }
}

The location.reload() is necessary for some payloads to trigger. Though, when reloading the popup in chrome, it seems that the content is completely gone. This problem has already been adressed by this question, however the proposed solutions didn't work.
So here is my question:
Is there a solution to this problem, or do you have any workarounds?

A: If what you want to do is communication between to browser windows or any form XSS, i suggest to check out postMessage here


text:
Q: Let $(s_n)$ and $(t_n)$ be bounded sequences of nonnegative numbers. Prove $\lim \sup{s_n,t_n}$ $\leq$ $(\lim \sup{s_n})(\lim \sup{t_n})$? Let $(s_n)$ and $(t_n)$ be bounded sequences of nonnegative numbers. Prove $\lim \sup{s_n,t_n}$ $\leq$ $(\lim \sup{s_n})(\lim \sup{t_n})$?
Can someone help explain this proof to me?

A: Hint:
For any $\epsilon > 0$ there is $N_s,N_t \in \mathbb{N}$ such that  $s_n < \limsup s_n + \epsilon$ for all $n \geqslant N_s$ and $t_n < \limsup t_n + \epsilon$ for all $n \geqslant N_t$.  Then what can you say about $s_nt_n$?


text:
Q: Word-wrap radio button text in Java? I have some radio buttons whose text may be very long.  Is there an easy way to word-wrap them?
Yes, wrapping them in  tags and inserting
 tags would work, but is there a more automatic way to accomplish this?  I don't really want to roll my own typesetter.

A: The quickest and dirtiest way is simply to prepend  at the start of the radio button's label text. This will make line wrapping start to occur but you'll now need to be careful about that text if it has < characters in it. This also maintains the functionality of click on the label text being a click on the radio button.
Here's a cheap and cheerful example:
public class Test extends JFrame {
    public static void main(String[] args) {
        new Test();
    }

    private Test() {
        Container  c = getContentPane();
        c.setLayout( new BorderLayout() );
        c.add( new JRadioButton( "I've got a very long text description that's going to wrap over very long lines because I stuck an <html> tag at the start of its label string.") );
        setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        setSize( 200,200 );
        setVisible( true );
    }
}

A: I don't think that there are any perfect solutions for this. Other than using
 tags, you could use a JTextArea and make it look like a label. Then set lineWrap and wrapStyleWord to true.
Then, you lose the functionality of clicking on the labels to select/deselect your radio button, so you will have to add a mouse listener.

A: Wrapping them in  tags and making sure they get enough vertical space should work. No need to break the lines yourself.


text:
Q: Put a grey background behind code extracts in a Latex document (like this site does) I'm using the listings user package to insert extracts of code into my document, however it isn't distinct enough from the normal text as I'd like. Is there a way to put a grey background behind the code extracts, like the ones used on this site?
e.g:
#include <stdio.h>

int main(int argc, char ** argv)
{
  printf("Hello world!\n");
  return 0;
}

Also/alternatively, can I indent the code, so the areas of code have wider margins?

A: Here's yet another solution using tcolorbox (version 3.02).
The first variant is breakable and uses the full line width:
\documentclass{article}
\usepackage{xcolor}
\usepackage[skins,listings,breakable]{tcolorbox}
\begin{document}

\begin{tcblisting}{breakable,listing only,
  listing options={language=c,aboveskip=0pt,belowskip=0pt},
  size=fbox,boxrule=0pt,frame hidden,arc=0pt,colback=lightgray}
#include <stdio.h>

int main(int argc, char ** argv)
{
  printf("Hello world!\n");
  return 0;
}
\end{tcblisting}

\end{document}

The second variant is not breakable, but the gray background adapts to the code width:
\documentclass{article}
\usepackage{xcolor}
\usepackage[skins,listings,breakable]{tcolorbox}
\begin{document}

\begin{tcblisting}{hbox,listing only,
  listing options={language=c,aboveskip=0pt,belowskip=0pt},
  size=fbox,boxrule=0pt,frame hidden,arc=0pt,colback=lightgray}
#include <stdio.h>

int main(int argc, char ** argv)
{
  printf("Hello world!\n");
  return 0;
}
\end{tcblisting}

\end{document}

A: The key backgroundcolor of the lstlisting is what you are looking for for the colored background. To indent a bit the code, play with xleftmargin and framexleftmargin to fit your needs.
\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\begin{document}
Test

\begin{lstlisting}[backgroundcolor = \color{lightgray},
                   language = C,
                   xleftmargin = 2cm,
                   framexleftmargin = 1em]
#include <stdio.h>

int main(int argc, char ** argv)
{
  printf("Hello world!\n");
  return 0;
}
\end{lstlisting}
\end{document}

A: I've been playing around with different options and I found another way to do it. I'll add it here as an alternative suggestion.
This looks very similar to the style used on the stackexchange sites.
%Put in the header

\usepackage{listings} %code extracts
\usepackage{xcolor} %custom colours
\usepackage{mdframed} %nice frames

\definecolor{light-gray}{gray}{0.95} %the shade of grey that stack exchange uses

%Put in the main document

\begin{mdframed}[backgroundcolor=light-gray, roundcorner=10pt,leftmargin=1, rightmargin=1, innerleftmargin=15, innertopmargin=15,innerbottommargin=15, outerlinewidth=1, linecolor=light-gray]
\begin{lstlisting}
    #include <stdio.h>

    int main(int argc, char ** argv)
    {
      printf("Hello world!\n");
      return 0;
    }
\end{lstlisting}
\end{mdframed}


text:
Q: Why is my neural network handwritten digital test set cross entropy correct, the output rate is always 10% correct compared to the label? I run my code in spyder,the test set cross entropy is correct, but the accuracy of test set is always very low. This is my code. I use the mnist. Any advice how I can improve the performance?
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
from tensorflow.contrib.layers import fully_connected
from tensorflow.examples.tutorials.mnist import input_data

x = tf.placeholder(dtype=tf.float32,shape=[None,784])
y = tf.placeholder(dtype=tf.float32,shape=[None,10])
test_x = tf.placeholder(dtype=tf.float32,shape=[None,784])
test_y = tf.placeholder(dtype=tf.float32,shape=[None,10])

mnist = input_data.read_data_sets("/home/xuenzhu/mnist_data", one_hot=True)

hidden1 = fully_connected(x,100,activation_fn=tf.nn.relu,weights_initializer=tf.random_normal_initializer())

hidden2 = fully_connected(hidden1,100,activation_fn=tf.nn.relu,weights_initializer=tf.random_normal_initializer())

outputs = fully_connected(hidden2,10,activation_fn=tf.nn.relu,weights_initializer=tf.random_normal_initializer())

loss = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=outputs)
reduce_mean_loss = tf.reduce_mean(loss)

equal_result = tf.equal(tf.argmax(outputs,1),tf.argmax(y,1))
cast_result = tf.cast(equal_result,dtype=tf.float32)
accuracy = tf.reduce_mean(cast_result)

train_op = tf.train.AdamOptimizer(0.001).minimize(reduce_mean_loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))
    for i in range(10000):
        xs,ys = mnist.train.next_batch(128)
        sess.run(train_op,feed_dict={x:xs,y:ys})
        if i%1000==0:
                print(sess.run(equal_result,feed_dict={x:mnist.test.images,y:mnist.test.labels}))
                print(sess.run(reduce_mean_loss,feed_dict={x:mnist.test.images,y:mnist.test.labels}))[enter image description here][1]
                print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))

A: There is no use in using a ReLu activation function before applying softmax_cross_entropy. Change the activation function in the last fully connected layer to None and you'll get good accuracy.
from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf
from tensorflow.contrib.layers import fully_connected

x = tf.placeholder(dtype=tf.float32,shape=[None,784])
y = tf.placeholder(dtype=tf.float32,shape=[None,10])
test_x = tf.placeholder(dtype=tf.float32,shape=[None,784])
test_y = tf.placeholder(dtype=tf.float32,shape=[None,10])

mnist = input_data.read_data_sets("/home/xuenzhu/mnist_data", one_hot=True)

hidden1 = fully_connected(x,100,activation_fn=tf.nn.relu,weights_initializer=tf.random_normal_initializer())

hidden2 = fully_connected(hidden1,100,activation_fn=tf.nn.relu,weights_initializer=tf.random_normal_initializer())

outputs = fully_connected(hidden2,10,activation_fn=None,weights_initializer=tf.random_normal_initializer())

loss = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=outputs)
reduce_mean_loss = tf.reduce_mean(loss)

equal_result = tf.equal(tf.argmax(outputs,1),tf.argmax(y,1))
cast_result = tf.cast(equal_result,dtype=tf.float32)
accuracy = tf.reduce_mean(cast_result)

train_op = tf.train.AdamOptimizer(0.001).minimize(reduce_mean_loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))
    for i in range(10000):
        xs,ys = mnist.train.next_batch(128)
        sess.run(train_op,feed_dict={x:xs,y:ys})
        if i%1000==0:
                print(sess.run(equal_result,feed_dict={x:mnist.test.images,y:mnist.test.labels}))
                print(sess.run(reduce_mean_loss,feed_dict={x:mnist.test.images,y:mnist.test.labels}))
                print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))

A: Try changing this

for i in range(10000): #Try increasing this value to >10k. Try 100k or higher

You should be able to see an increase in accuracy thereafter.


text:
Q: The Props Console Log as Undefined This is my Posts.tsx file. When I go to the browsers console it says undefined and point to this line console.log(posts);
import React from 'react'
import {sanityClient, urlFor} from '../sanity'
import { Post } from '../typings';
import Head from 'next/head'
import type { NextPage } from 'next'

export const getServerSideProps =async () => {
  const query = `*[_type == "post"]{
    _id,
    title,
    slug,
    description,
    author -> {
    name,
    image
   }
  }`;

  const posts = await sanityClient.fetch(query);

  return {
    props: {
      posts,
}
}};

interface Props {
 posts?: [Post];
}

const Posts: NextPage = ({posts}: Props) => {
  console.log(posts);
  return (

Posts

  )
}

export default Posts

This is where the Post typings come form. A typings.d.ts file.
export interface Post {
    _id: string;
    _createdAt: string;
    title: string;
    author: {
        name: string;
        image: string;
    };
    description: string;
    mainImage: {
        asset: {
            url: string;
        };
    };
    slug: {
        current: string;
    };
    body: [object];
}


text:
Q: Neo4j: Enforcing schema with XSD I was wondering if there exists a tool for Neo4j that can read an XSD file and use it to enforce a schema on Neo4j.
I'm newbie on graph databases but I'm starting to appreciate the schema-less approach. There's a lot of projects out there that have been pumping in a lot of non-sequential data and making sense of it all which is really cool.
I've come across some requirements that call for control on what properties a node or edge can have given a certain label and what labels an edge can have given the labels of its source and destination nodes. The schema is also subject to change - although not frequent.
As I understand, the standard practice is to control the schema from the application itself which to me doesn't seem like it should be a BEST practice. For example, the picky developers from Oracle land create views for applications to interact with and then apply triggers onto the views that execute the appropriate transactions upon the application attempting to insert or update on the view.
I would be looking for a similar device in Neo4j and since I already have the XSD files, it would be a lot less work overall to simply dump them into a folder and have it use those for reference on what to enforce.
This is something I'm willing to write myself unless there's already a library out there for this. I have a day job after all. :)
Thanks!

A: Not only does this tool not exist, but it couldn't even exist without more work on standardizing how XML is stored in neo4j.  There are key differences between the XML model and the neo4j model.
There's this python application here that can import XML into neo4j; documents, not schemas.  But in the way that it does it, there are many things to keep in mind:

*

*There's no obvious mapping from XML elements/attributes on to neo4j nodes/properties.  You'd think that elements should be nodes, attributes properties; but a better graph model would usually be different than that.  For example, XML namespaces would make great nodes because they connect to so many other things (e.g. all elements defined in a namespace) yet typically they're attributes.  Maybe namespaces should be labels?  Also maybe a reasonable choice, except there's no standard answer there.

*XML trees have sequence, and sequence matters; graphs don't.   Say you have an XML element with 2 children, A and B.  In neo4j you might have a node connected to two other nodes, but you need a way of expressing (probably via a relationship property) that A comes before B.  That's of course doable in neo4j, but there's no agreement as far as I know about how to do that.  So maybe you pick a sequence attribute, and give it an integer value.  Seems reasonable...but now your schema validation software has a dependency on that design choice.  XML in neo4j stored any other way won't validate.

*There's a host of XML processing options that matter in schema validation that wouldn't in a graph, for example whether or not you care about ignoring whitespace nodes, strict vs. lax schema validation, and so on.

Look, neo4j is great but if you really need to validate a pile of XML documents, it's probably not your best choice because of some mismatches between the graph model and XML's document model.   Possible options might be to validate the documents before they go into neo4j, or just to come up with a way of synthesizing XML documents from what is in neo4j, and then validating that result once it's outside of the graph database, as an XML file.


text:
Q: Using django-oscar to sell fully custom products I am looking into using django-oscar to sell custom-made products. There is only one SKU, but it has 4 properties that customers can specify: chemicals, color, scent and weight.

*

*Chemicals is a JSON object (a dictionary of name/value pairs), and we will need to use that to keep track of inventory of the chemicals.

*Weight is an integer between 200 and 20000.

*Scent and color each have a dozen values at present.

Customers will make up recipes and share them with each other. A recipe is a combination of the 4 properties.
Product will be made to order, so we will only stock raw ingredients, not finished product.
We already have an HTML/JavaScript page that allows customers to choose values for the 4 product properties. Costing needs to be done via an Ajax call to an API that needs to be exposed by Django.
Currently, there is one fulfillment partner (me), but out of the box django-oscar only applies fulfillment partners to fully defined products.
It seems (but I am a bit uncertain) that manage.py oscar_fork_app creates forked Oscar apps within an existing webapp, like Frobshop... is that right?
It seems from what I read that django-oscar is capable of selling custom products such as I describe. I think that I'll need to fork the Catalogue and the Dashboard apps. Will I also need to fork Basket and Order and Partner also?
How would I approach setting this type of store up? I have looked at https://django-oscar.readthedocs.io/en/latest/topics/customisation.html, but I have not tried to move forward yet, still trying to get a handle on things.
I decided to try and see what happened. I decided to call the root module ancientwarmth. The following worked just fine, and I forked catalogue, dashboard, basket, order and partner.
for x in catalogue dashboard basket order partner; do
  ./manage.py oscar_fork_app $x ancientwarmth
  sed -i s/oscar.apps.$x.apps.${x^}/ancientwarmth.$x.apps.${x^}/ \
    frobshop/settings/base.py
done

However, I was unable to fork any of these:

*

*oscar.apps.dashboard.orders.apps.OrdersDashboardConfig

*oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig

*oscar.apps.dashboard.partners.apps.PartnersDashboardConfig
I got an error like CommandError: There is no app with the label 'dashboard.catalogue'.

A: This is quite a broad question, and not one that is likely to get a comprehensive answer because of the time it would take to write one, but a few comments (and help with the forking error):

*

*It's quite possible to sell custom products using Oscar.

*Which apps you need to fork really depends on your use case and what from Oscar's core functionality you need to override. You need to first develop a good understanding of what Oscar's apps provide out of the box to determine whether you need to override their functionality. It's not really possible to answer in the general case what apps you need to fork. Oscar is designed to give you as much flexibility to override its functionality as possible - knowing when/where to do this does require becoming familiar with its functionality first though.

*The first argument to oscar_fork_app is the label of a Django AppConfig, not a module name, which is what you're trying to use. That is why you're getting an error when attempting to fork the dashboard apps. The correct command would be manage.py oscar_fork_app catalogue_dashboard <destination_path>. This isn't made very clear in the documentation, and there is an issue to fix this. catalogue_dashboard is defined here.
(It worked for the catalogue, basket, etc. apps because for those the app name defined for the app is identical to the argument you supplied).


text:
Q: Change the scope of search Sharepoint 2010 I have a page where I want to search for  items only in an exam sharepoint 2010 list.
To achieve  that

*

*I created a search scope  called exams.

*I created a webpage page and added a search box and search results  box to it.
I set the scope in the webpage properties to exams and set the target url to the out of the box "/search/results.aspx".
This results in issue that the search shows me all the site content. If I append the query  text &s=examlist. The search results on the page seems to show all the items in the site instead of refining the search results to only items from the exams list.
It would be good if I can show the results on the same page.

A: The important point while creating the scope to only search in a specific list is that:
Scope Rule Type:

*

*Web Address: (http://server/site)
In Web Address select "Folder" and type the url of custom list e.g.
http://server:port/sites/sitename/Lists/MyCustomList
Below sources will guide you step by step how to use Search scopes:

*

*Steps to search a specific custom list.

*Create a Search Scope for a Sharepoint 2010 List or Library.


text:
Q: Looping Video Buffer in ActionScript3 I'm trying to create an AS3 app with looping, seamless video background. The background is loaded from an flv. The problem thus far is with the seamless bit, because all the video looping tactics I've come accross regarding AS3 always seem to have that short but noticeable pause at the end of the video before going back to the beginning and playing again.
The best way I've determined to deal with this is to play a video and buffer the video frames as BitmapData objects into a queue of a defined length (without adding the video to stage). This way Rendering the video would then really involve popping each of those BitmapDatas into a Bitmap
object attached to my stage in a timed manner, which then gets drawn.
Sort of like:
/*VideoBufferer loops the input video and queues frames and then updates*/
var vidbuffer:VideoBufferer = new MyVideo("video.flv",outputImage)

var outputImage:Bitmap = new Bitmap();
stage.addChild(outputImage);

//forgive syntax, this is pseudoCode
timed process that happens X times per second{
  outputImage.bitmapData = vidbuffer.popBitmapData(); //returns bitmap data from the queue
}

I don't care about sound.
However I seem to not know how to implement this desired VideoBufferer class as I don't know how to play a video without adding it to stage and grabbing frames from it. Dows anyone know of any such class out there that already does this or could someone give me pointers on how to implement the frame grabbing side of VideoBufferer?
Thanks

A: I know this is a very late answer, but I have a solution for seamless flv playback, described here: http://blog.redannick.com/seamlessly-looping-video-files-in-as3-with-netstream-appendbytes/
example code on a gist here: https://gist.github.com/redannick/7772246

A: Yours and my best friend for open source: Mr. Doob, to the rescue.
http://code.google.com/p/mrdoob/source/browse/trunk/libs/net/hires/utils/display/BitmapDataSequence.as
It's designed to load a SWF and convert the frames to a sequence of BitmapData objects. It should be updated to use Vectors, etc. as it hasn't been updated since 2008, but it's the answer.
It's definitely trickier to do it on the fly with video, but if you have the luxury of embedding the video on the timeline ( get those frame rates correct! ) and exporting a SWF to load later on, it's worth it and works well.


text:
Q: No overload for method 'Equals' takes '0' arguments I am trying to fix an error I am getting in the code below line 34 and 35.
aliq.ALIQUOT_ID = reader["ALIQUOT_ID"].Equals();
aliq.SAMPLE_ID = reader["SAMPLE_ID"].Equals();

Both Aliquot_ID and Sample_ID are integers. However, the way I wrote those lines
I am getting the following error:
Error   1   No overload for method 'Equals' takes '0' arguments C:...App_Code\DAL\DAL.cs    34.
Error   2   No overload for method 'Equals' takes '0' arguments C:...App_Code\DAL\DAL.cs    35.

How should I write these two lines in order to fix this issue.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Oracle.DataAccess.Client;

namespace Data
{
/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
    public static Model.Aliquot GetAliquot_ID(int aliqID)
    {
        string cs =         ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        OracleConnection conn = null;
        OracleDataReader reader = null;
        try
        {
            conn = new OracleConnection(cs);
            string oracle = "SELECT SAMPLE_ID, ALIQUOT_ID, MATRIX_TYPE FROM LIMS.ALIQUOT WHERE ALIQUOT_ID = '" + aliqID + "'";
            OracleCommand cmd = new OracleCommand(oracle, conn);
            conn.Open();
            reader = cmd.ExecuteReader();
            reader.Read();
            Model.Aliquot aliq = new Model.Aliquot();
            aliq.ALIQUOT_ID = reader["ALIQUOT_ID"].Equals();
            aliq.SAMPLE_ID = reader["SAMPLE_ID"].Equals();
            aliq.MATRIX_TYPE = reader["MATRIX_TYPE"].ToString();
            return aliq;
        }
        catch (Exception exp)
        {
            //Add Logging
            HttpContext.Current.Trace.Warn("Error", "Error in GetAliquot_ID()", exp);
        }
        finally
        {
            if (reader != null) reader.Close();
            if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
        }
        return null;
    }
}

A: Equals() doesn't make much sense in that context. What are you trying to do? Convert those results to int, right?
So instead of
aliq.ALIQUOT_ID =reader["ALIQUOT_ID"].Equals();

use
aliq.ALIQUOT_ID =Convert.ToInt32(reader["ALIQUOT_ID"]);

A: Just remove the .Equals() from the end of each line.  Assuming that the field in your table for each of these is an integer, then the reader[<fieldname>] will give you the associated value.

A: MSDN says about the OracleDataReader column indexer:

Gets the value of the specified column in its native format given the
  column name.

So, you should be able to remove .Equals() from those lines.
If that doesn't work, try:
Convert.ToInt32(reader["ALIQUOT_ID"])

Hope that helps


text:
Q: simple fading in/out with jquery, is it worth it? I have read all your responses and come to the conclusion that is a bad idea all together. Thank you very much, multiple pages is so much easier anyway.
I am building a website and I don't want the page to refresh. My idea was that I would have 3 different divs of the same size fade in and out depending the the nav link the user selected.
Example code: (#about is the nav div and #about_main is the main div, and so on)
$('#about a').click(function() {
    $('#portfolio_main, #contact_main').fadeOut('fast', function() {
        $('#about_main').delay(405).fadeIn();
    });
});

//hide all divs that ren't on portfolio link
$('#portfolio a').click(function() {
    $('#about_main, #contact_main').fadeOut('fast', function() {
        $('#portfolio_main').delay(405).fadeIn();
    });
});

$('#contact a').click(function() {
    $('#about_main, #portfolio_main').fadeOut('fast', function() {
        $('#contact_main').delay(405).fadeIn();
    });

});

This proves to be a problem as you can click on the $('#about a') 100 times and it will fire 100x. Also, if I click on many a tags quickly, the divs get all messed up.
Example: My Site
How can I have it so that it fades in and out easily and nicely? Is there way to unbind the click when the user has already clicked it? Is there an easier way of doing this?

A: Putting aside the obvious question of the wisdom of arranging your site this way -- first, you might want to set a fixed height for your container, so you don't get that jumping effect between transitions.
As to the overlapping animations, you should take a look at .stop()

A: I was facing a similar issue today as well.  I came to the conclusion that sometimes flashy effects, though appealing, are just not appropriate.  Especially for something as large as what you are applying the effects to.  I would just redirect to another page.
I am not sure what server-side language you are using but your page can easily be separated into sections so that you can re-use the header and footer, i.e.  Asp.net master pages.

A: While I agree with Robert that you should not do this, however, if you are compelled to do so you can check out this example here: http://jsfiddle.net/xWu3C/2/
I didn't bring your styles over or anything but the principle is is the same.

A: The title of this questions asks "is it worth it?" so I will address that rather than "how to" posed in the question body.  The answer is:  No, please don't break the internet.


text:
Q: Design of abstract generic DbContext class in EF Core I'm having trouble implementing an abstract generic base class, using EF Core. It's probably something obvious, but I'm not seeing it.
base class:
public abstract class AContext<TUser> : IdentityDbContext<TUser>
  where TUser : IdentityUser {

    public AContext(DbContextOptions<AContext<TUser>> options, ILogger<AContext<TUser>> logger)
      : base(options) {
    }

}

subclass:
public class Context : AContext<User> {

    public Context(DbContextOptions<Context> options, ILogger<Context> logger)
      : base(options, logger) {   // problem is here with "options"
    }

}

Error: Cannot convert from 'DbContextOptions<Context>' to 'DbContextOptions<AContext<User>>'.
I tried casting but that doesn't work. Is the problem due to it not being covariant? Can I redesign it somehow?

A: A DbContextOptions<Context> is not assignable to DbContextOptions<AContext<TUser>>. The reason is that there could be internal write operations to objects of type T, which for DbContextOptions<Context> would be Context. DbContextOptions<AContext<TUser>> can not provide that, because it's T is an AContext<TUser>.
Covariance is not an answer for you, since co- and contravariance is only available for interfaces, not for classes.
If you change the parameter type in your constructor from DbContextOptions<Context> to DbContextOptions<AContext<User>>, everything should work fine.


text:
Q: Blogger no longer respects the chosen dynamic view I have a Blogger site with CSS customized dynamic view template, where each section on the menu had a default view (magazine, flipcard, mosaic).
I say "had", because recently I've noticed that Blogger does not longer respect the choosen view, when passing from one section to another which has a different view (for example url: from ?view=mosaic to ?view=flipcard). I wonder if anyone has encountered the same problem, or if there is a way to "force" a certain view, as formerly.
I'm no expert at all, but i think the fastest solution should be finding a way to 'force' the browser on refreshing the URL query strings. For example, when I navigate from
www.alesserfate.com/search/label/audioKB?view=timeslide
to
www.alesserfate.com/search/label/videogame?view=mosaic,
, and then back to the first link, the URL query "?view=timeslide" seems to be overridden and the page is displayed with the (wrong) mosaic view.There must be a way to fix this ("forcing" to refresh url query?). I want to emphasize that, this behaviour is NEW ,without touching anything on the blog. Definitely Google has changed something under Blogger's hood.


text:
Q: Is it possible to write Groovy tests with Arquillian/Drone/Graphene I'm writing function UI tests and  need to know does Arquillian/Drone/Graphene frameworks support Groovy tests.
I'm finding it hard to find information online.
Can groovy be implemented in this way or should is it easier to stick with Spock and Geb for groovy tests?


text:
Q: Symfony 3. Problems with join and the VichUploaderBundle I load several pictures with the Vichuploaderbundle and the EntryImg Entity.
That is successful!
I have also an Entity named Entries.
Each Entry should be linked with one or more Images
I want to join both Entities in the Repository.
What is the error?
Here is my Entries Entity
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
//use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\EntriesRepository")
 * @ORM\Table(name="entries")
 */
class Entries
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\EntryImg", mappedBy="entries")
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     */
    private $name;

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    /**
    * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
    * @ORM\JoinColumn()
    */
    private $user;

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getDescription()
    {
        return $this->description();
    }

    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    public function getUser()
    {
      return $this->user;
    }

    public function setUser(User $user)
    {
        $this->user = $user;
    }

}

My Image Entity
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
//use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
* @ORM\Entity
* @ORM\Table(name="`entry_img`")
* @Vich\Uploadable
*/
class EntryImg
{

    /**
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    * @ORM\Column(type="integer")
    */
    protected $id;

    /**
    * @ORM\Column(type="string", length=255)
    * @var string
    */
    private $image;

    /**
     * @Assert\File(maxSize="2000k",mimeTypes={"image/png", "image/jpeg", "image/pjpeg"})
     * @Vich\UploadableField(mapping="entry_images", fileNameProperty="image")
     * @var File
     */
    private $imageFile;

    /**
      * @ORM\Column(type="datetime")
      * @var \DateTime
      */
     private $updatedAt;

     /**
     *  @ORM\ManyToOne(targetEntity="AppBundle\Entity\Entries")
     *  @ORM\JoinColumn(name="entries_id",referencedColumnName="id",nullable=true)
     */
     private $entry;

     public function setImageFile(File $image = null)
     {
         $this->imageFile = $image;

         // VERY IMPORTANT:
         // It is required that at least one field changes if you are using Doctrine,
         // otherwise the event listeners won't be called and the file is lost
         if ($image) {
             // if 'updatedAt' is not defined in your entity, use another property
             $this->updatedAt = new \DateTime('now');
         }
     }

     public function getImageFile()
     {
         return $this->imageFile;
     }

     public function setImage($image)
     {
         $this->image = $image;
     }

     public function getImage()
     {
         return $this->image;
     }

      public function getId()
      {
          return $this->id;
      }

      public function getEntry(){

        return $this->entry();
      }

      public function setEntry(Entries $entry){

        $this->entry = $entry;
      }
}

and my repository
<?php
namespace AppBundle\Repository;

use AppBundle\Entity\Entries;
use AppBundle\Entity\EntryImg;
use Doctrine\ORM\EntityRepository;

class EntriesRepository extends EntityRepository
{
    public function findAllEntries($e_ids)
    {

        $query = $this->createQueryBuilder('e')
          ->leftJoin('e.id','entry_img');
        $i = 0;
        foreach($e_ids as $e_id){
            if($i==0){
              //var_dump($e_id);
              $query->where('e.id = :entries_'.$i)
              ->setParameter('entries_'.$i,$e_id['entry']);
            }else if($i>0){
              $query->orWhere('e.id = :entries_'.$i)
              ->setParameter('entries_'.$i,$e_id['entry']);
            }
            $i++;
          }
        $result = $query->getQuery()->execute();
        return $result;
    }

A: In your class Entries, you have this line:
@ORM\OneToMany(targetEntity="AppBundle\Entity\EntryImg", mappedBy="entries")

But in your EntryImg class, there isn't any $entries property.
Also, if 1 Entries can have many EntryImg, you need to use arraycollection.
I think you should rewrite your Entries class like this:
use Doctrine\Common\Collections\ArrayCollection; //don't forget this line for the constructor
class Entries
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
       //look here I remove the relation and put it on $entriesImg property
     */
    private $id;

    /**
     * @ORM\Column(type="array")
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\EntryImg", mappedBy="entry") //look here I changed "entries" by "entry" which is the actual property in your EntryImg class. (you did not have any $entries property)
     */
    private $entriesImg;

     .. the rest of your properties

    public function __construct()
    {
        $this->entriesImg= new ArrayCollection();
    }

    public function addEntryImg(\AppBundle\Entity\EntryImg $entryImg)
    {
        $this->entriesImg[] = $entryImg;

        return $this;
    }

    public function removeEntryImg(\AppBundle\Entity\EntryImg $entryImg)
    {
        $this->entriesImg->removeElement($entryImg);
    }
       // also don't forget to implement classic getters and setters for the $entriesImg property

Don't forget to implement a toString method for both your entities, you will need it for Crud operation.
Then, later in your repository, you forgot to use the ->addSelect(); method like this
class EntriesRepository extends EntityRepository
{
    public function findAllEntries()
    {
        $query = $this->createQueryBuilder('e')
          ->leftJoin('e.entriesImg','i');
          ->addSelect('i')
          // whatever from your logic ....


text:
Q: Why does elasticsearch raise elasticsearch_dsl.exceptions.ValidationException: You cannot write to a wildcard index.on pypy but not cpython? I have some code that saves data to Elasticsearch. It runs fine in Python 3.5.2 (cpython), but raises an exception when running on pypi3 6.0.0 (Python 3.5.3). Any ideas why?
File "/opt/venvs/parsedmarc/site-packages/parsedmarc/elastic.py", line 366, in save_forensic_report_to_elasticsearch
  forensic_doc.save()
File "/opt/venvs/parsedmarc/site-packages/elasticsearch_dsl/document.py", line 394, in save
  index=self._get_index(index),
File "/opt/venvs/parsedmarc/site-packages/elasticsearch_dsl/document.py", line 138, in _get_index
  raise ValidationException('You cannot write to a wildcard index.')
elasticsearch_dsl.exceptions.ValidationException: You cannot write to a wildcard index

A: I have tried several combinations of swapping DocType for Document, adding or deleting class Index or class Meta. However, in any combination, the name of the index was left empty. Debugging proved that, and after a bit of tweaking, I got it to work.
This bit of code worked for me:
 class Index:
    # index = 'sample_index'
    name = 'sample_index'

Note that I haven't tried to use this with name only. Also, it worked with DocType, but it should work with new Document class as well.
Reference to Sean's question at GitHub. The above solution is confirmed on the thread.
Keeping it in one place, previously mentioned link: Document to replace DocType for newer versions of Elasticsearch.

A: We ran into similar issues, seems like elasticsearch_dsl renamed DocType to Document in their new version 6.2 what breaks backwards compatibility.
https://github.com/elastic/elasticsearch-dsl-py/blob/master/Changelog.rst
Either fix your version to 6.1 or you have to update to the new Document type.


text:
Q: Core data database deletes itself Im having trouble with my core data database. It randomly deletes itself. I've used my app for a week and everything worked perfectly, but today y opened the app and figured out that all the entries had been deleted (not the first time that happens). Im new to core data programming, but I understand iOS and Objective-C. I need to know where i should check in my code for bugs, is it the save function? Thanks!

A: You might want to check if you're explicitly calling the save function for the UIManagedDocument. For simplicity's sake, the Stanford CS193P demo project on this, if I'm not mistaken, relied on the automatic calling of the save function of UIManagedDocument. In some cases, the saving takes a while. And the app can be terminated even before this is done. This might explain the loss of your data.
Here's a sample code for saving your database:
- (void) saveDatabase{
    [myDatabase saveToURL:myDatabase.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
    if(success == YES) NSLog(@"Awesome, databse is saved! booooyah!");
}];}


text:
Q: Alternate method for setting size of input textbox? Basics of CSS for rounded corners here.
Update:  In order to render my textbox consistently across iOS/BlackBerry/Android, the only successful way was NOT to use size=# or =#em or =#%, but to set the width of the input to be width: ###px .  When I do that (inline or in CSS) it wrecks the rounded corners effect.

I have determined that setting the width attribute is what breaks the corners.
My question: Is there another way to set the width attribute?  I'm open to another idea of how I can render the size of the textbox consistently cross-platform?

A: No, size is set only by the attribute size= which is unreliable so you can only use the css attribute width: 50px

A: I solved my issue by decreasing the radius of the rounded corners (see comments)


text:
Q: How to print rdlc report with reportviewer hello guys can anyone help me how to print my receipt using a controll button?

this is my screen shot [1]" https://ibb.co/kfk8SF
if I click the "SAVE PRINT" button a preview dialog box appeared
all I want is to automatically print the report that i want by clicking only the button and no dialog box appeared

[2] https://ibb.co/kSpDuv

A: You can get default printer name first (before opening report viewer):
System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.PrinterSettings();
defaultPrinterName = settings.PrinterName;

When printing, assign your printer name to PrinterName property of PrintDocument:
 LocalReport rep = new LocalReport();
 //set your data and parameters here
 //...
 rep.Refresh();
 ExportLandscape(rep);

 PrintDocument printDoc = new PrintDocument();
 PrinterSettings ps = new PrinterSettings();
 ps.PrinterName = defaultPrinterName;
 printDoc.PrinterSettings = ps;

 printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
 m_currentPageIndex = 0;
 printDoc.Print();

The event to handle actual print:
 //this has to declared somewhere at the "top":
 private IList<Stream> m_streams;
 private int m_currentPageIndex;

 private void PrintPage(object sender, PrintPageEventArgs ev) {
        Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]);

        // Adjust rectangular area with printer margins.
        Rectangle adjustedRect = new Rectangle(
            ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
            ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
            ev.PageBounds.Width,
            ev.PageBounds.Height);

        // Draw a white background for the report
        ev.Graphics.FillRectangle(Brushes.White, adjustedRect);

        // Draw the report content
        ev.Graphics.DrawImage(pageImage, adjustedRect);

        // Prepare for the next page. Make sure we haven't hit the end.
        m_currentPageIndex++;
        ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
    }

Here is code to create print document:
private void ExportPortrait(LocalReport report) {
            string deviceInfo =
              @"<DeviceInfo>
                <OutputFormat>EMF</OutputFormat>
                <PageWidth>8.5in</PageWidth>
                <PageHeight>11in</PageHeight>
                <MarginTop>0.5in</MarginTop>
                <MarginLeft>0.5in</MarginLeft>
                <MarginRight>0.5in</MarginRight>
                <MarginBottom>0.5in</MarginBottom>
            </DeviceInfo>";
            Warning[] warnings;
            m_streams = new List<Stream>();
            report.Render("Image", deviceInfo, CreateStream, out warnings);
            foreach (Stream stream in m_streams)
                stream.Position = 0;
}

private void ExportLandscape(LocalReport report) {
        string deviceInfo =
          @"<DeviceInfo>
            <OutputFormat>EMF</OutputFormat>
            <PageWidth>11in</PageWidth>
            <PageHeight>8.5in</PageHeight>
            <MarginTop>0.5in</MarginTop>
            <MarginLeft>0.5in</MarginLeft>
            <MarginRight>0.5in</MarginRight>
            <MarginBottom>0.5in</MarginBottom>
        </DeviceInfo>";
        Warning[] warnings;
        m_streams = new List<Stream>();
        report.Render("Image", deviceInfo, CreateStream, out warnings);
        foreach (Stream stream in m_streams)
            stream.Position = 0;
}

private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) {
            Stream stream = new MemoryStream();
            m_streams.Add(stream);
            return stream;
 }

You can use something like this to convert code to vb.net is needed.


text:
Q: Re-dispatching event in FLEX In a FLEX app, I am trying to "re-dispatch" a custom event. I.e. component1 does dispatchEvnet(event), component2 registers a handler for the event, the only function of the handler being, again, dispatch(event). Finally, component3 listens for the event coming out of component2. What I am trying to do is similar to the concept of "re-throwing" exceptions (and for similar reasons). The difference is that re-dispatching does not seem to work in AS3 (Flash 10). In IE, nothing happens, and in FF3 there is an exception saying that the type cast failed while trying to coerce the Event type to my CustomEvent while calling the handler in component3. Tracing code in the debugger shows that by the time component3 is called, the event is, indeed, a generic one, with all my custom stuff lost. Is this supposed to be the case?

A: The problem you are experiencing is caused by not overriding the clone() event in your custom event.
When events are redispatched, they are cloned and modified. If you don't override clone() you get the base implementation of clone(), which returns an Event. Because Event cannot be cast to your custom event type, a runtime error is thrown.
From the documentation:

When creating your own custom Event class, you must override the inherited Event.clone()  method in order for it to duplicate the properties of your custom class. If you do not set all the properties that you add in your event subclass, those properties will not have the correct values when listeners handle the redispatched event.

A: more see:http://casario.blogs.com/mmworld/2006/08/the_clone_metho.html


text:
Q: Limit logarithm $\lim_{n \to \infty}(4n-6)[\ln(2n+5)-\ln(2n-7)]$. please any advice for this limit?
$$\lim_{n \to \infty}(4n-6)[\ln(2n+5)-\ln(2n-7)]$$
Thanks for any advice.

A: $\ln(2n+5)-\ln(2n-7)=\ln(\frac{2n+5}{2n-7})=\ln(\frac{2n-7+12}{2n-7})=\ln(1+\frac{12}{2n-7})\sim\frac{12}{2n-7}$
So your limit is equivalent to $\frac{12(4n-6)}{2n-7}\sim24$


text:
Q: Cadena de caracteres capicua java Estoy intentando hacer un programa que diga si la frase introducida o palabra es capicua, es decir holaloh. Lo que hago son dos for, que empiece a recorrer desde el inicio y el otro desde el final, y después guardarlos con el charAt y la posición del indice pero me lo hace bien en algunas palabras y en otras no. No se si hay algo mal en el código.
import java.util.Scanner;

public class capicua {
public static void main(String args[]) {
    Scanner teclado = new Scanner(System.in);

    System.out.println("Escriba una cadena.");
    String x = teclado.nextLine();
    int s = x.length();
    int z = s / 2;
    char k;
    char m;

    for (int i = 0; i <= z; i++) {
        for (int j = (s - 1); j>z ; j--) {

            k = x.charAt(i);
            m = x.charAt(j);

            if (k==m) {
                System.out.println("Bien.");
            }

        }
     }
  }
}

A: no es necesario que user for anidado, no estabas comparando como deberia ser la comparacion para este problema, lo cual es comparar

el primer elemento con el ultimo
el segundo elemento con el penultimo
el tercer elemento con el antepenultimo
  etc.

tu error radica en la comparacion: lo que tu codigo hace es:

i=0
  comparar el primer elemento con el ultimo elemento
comparar el primer elemento con el penultimo elemento
comparar el primer elemento con el antepenultimo elemento ...
i=1
  comparar el segundo elemento con el ultimo elemento
comparar el segundo elemento con el penultimo elemento
comparar el segundo elemento con el antepenultimo elemento ...
i=2
comparar el tercer elemento con el ultimo elemento
comparar el tercer elemento con el penultimo elemento
comparar el tercer elemento con el antepenultimo elemento ...etc

te dejo una solucion:
import java.util.Scanner;

public class capicua {
public static void main(String args[]) {
    Scanner teclado = new Scanner(System.in);

    String x = "anitalavalatina";
    int s = x.length();
    int z = s / 2;
    char k;
    char m;
    int p=0;

        for (int j = (s - 1); j>z && p<z ; j--) {

            k = x.charAt(p);
            m = x.charAt(j);

      System.out.println(k+" "+m );

            if (k==m) {
                System.out.println("Bien.");
            }
          p++;

        }

  }
}

A: Si no tienes limitaciones para utilizar StringUtils el código te va a quedar mucho más reducido:
String prueba = "prueba";
String aux = StringUtils.reverse(prueba);
System.out.println(String.format("'%s' %s es palíndromo: '%s'", prueba, (prueba.equals(aux)?"SI":"NO"),aux));

prueba = "acurruca";
aux = StringUtils.reverse(prueba);
System.out.println(String.format("'%s' %s es palíndromo: '%s'", prueba, (prueba.equals(aux)?"SI":"NO"),aux));

Nos da la siguiente salida:

'prueba' NO es palíndromo: 'abeurp'
  'acurruca' SI es palíndromo: 'acurruca'

NOTA: Cuando nos referimos a palabras se usa la expresión palíndromo para lo que buscas en vez de capicúa que se usa para numerales.


text:
Q: Web audio API - LFO with 'triangle' shape connected to biquadFilter clicks I have an LFO connected to a biquadFilter.
When the LFO gain is greater than the current biquadFilter.frequency.value, it results in notice-able clicking of audio.
Is there a way prevent this clicking ?
The biquadFilter has an envelope on it, so the frequency sweeps up and down after a note on the keyboard is pressed.
This is what I think is happening :

This is what I'd like to happen :

Here is a minimal example :
http://codepen.io/js-bs/pen/bgyZPx
var audioContext = new AudioContext();
var masterGain = audioContext.createGain()
masterGain.connect(audioContext.destination)
masterGain.gain.value = .3;

// Filter
var filter = audioContext.createBiquadFilter();
filter.type = 'lowpass'
filter.frequency.value = 0;
filter.connect(masterGain);

// Oscillator
var osc = audioContext.createOscillator();
osc.frequency.value = 440;
osc.type = 'square';
osc.start();
osc.connect(filter);

// LFO
var lfo = this.audioContext.createOscillator();
var lfoGain = this.audioContext.createGain();
lfo.type = 'triangle';
lfo.start();
lfo.connect(lfoGain);
lfo.frequency.value = 5;
lfoGain.gain.value = 10000;
lfoGain.connect(filter.frequency);

document.addEventListener('click', function(e){
  if(e.target.id==='lfo' && e.target.checked){
    lfo.connect(lfoGain);
  } else if (e.target.id==='lfo') {
    lfo.disconnect();
  }
})

document.addEventListener('mousedown', filterEnvelopeOn);
document.addEventListener('mouseup', filterEnvelopeOff);

function filterEnvelopeOn () {
  let now = audioContext.currentTime;
  let frequency = filter.frequency;
  let attack = 0.5;
  let decay = 0.4;
  let sustain = 200;

  let freq = 10000;
  frequency.cancelScheduledValues(0)
  frequency.setValueAtTime(60, now)
  frequency.linearRampToValueAtTime(freq, now + attack)
  frequency.linearRampToValueAtTime(sustain, now + attack + decay)
}

 function filterEnvelopeOff () {
   filter.frequency.cancelScheduledValues(0);
   let now = audioContext.currentTime;
   let frequency = filter.frequency;
   let release = 0.1;
   frequency.cancelScheduledValues(0);
   frequency.setValueAtTime(frequency.value, now);
   frequency.linearRampToValueAtTime(0, now + release);
  }

A:
If I change my codepen example code from :
lfoGain.connect(filter.frequency);
to :
lfoGain.connect(filter.detune);
The audible clicking is gone, and the synth sounds as I intend it to.
If anyone can explain why this works that would be helpful and I'll mark your answer as accepted.

When you have AudioNodes connected to an AudioParam, that AudioParam takes its value as all of the outputs from the AudioNodes and its own value added together. In your case, the values output by your lfoGain range from -10000 to +10000, because the output of the oscillator ranges from -1 to 1, and those values are then multiplied by your lfoGain.gain value.
When you have your lfoGain connected to the frequency, you're telling the frequency to oscillate between 0Hz and +20000Hz (10000 ± 10000) immediately after the attack of your envelope, between -9800Hz and +10200Hz (200 ± 10000) at your sustain, and between -10000Hz and +10000Hz ( 0 ± 10000 ) after the release of your envelope.
When you instead have your lfoGain connected to the detune, the computed frequency will oscillate proportionally to the frequency value you set with the envelope.

computedFrequency(t) = frequency(t) * pow(2, detune(t) / 1200)

You're now telling the detune value to oscillate between -10000cents and +10000cents (0 ± 10000 ), and this oscillation, rather than adding to the frequency, multiplies it by a value that's approximately between 1/323 and 323.
Immediately after the envelope's attack, the minimum computed frequency in the oscillation is approximately 31Hz, at the sustain, the minimum is approximately 0.62Hz, and after the release of your envelope, the computed frequency range is between 0 and 0 (0/323, 0*323).
This is at least what it's being told to do, actual implementation may be different.

A: The answer won't satisfy you but it's like that.
The clicking happens when the audio signal drops too strong. Perhaps you have a logical error in your LFO => When the LFO drops below 0 it starts clicking. That is pretty normal behaviour. See at my website gtube.de and select in the Database "dubstep like 2" and you can hear the clicking as well if you then reduce the amount from "GAIN 2" which acts as amplifier to 1999 you don't cross the 0 border of the filter and it won't click.
=> if you want to hear examples midi is not working correct at the moment.

A: If I change my codepen example code from :
lfoGain.connect(filter.frequency);
to :
lfoGain.connect(filter.detune);
The audible clicking is gone, and the synth sounds as I intend it to.
If anyone can explain why this works that would be helpful and I'll mark your answer as accepted.

A: If I change to
lfoGain.connect(filter.detune);

the sound itself is gone for me. I couldn't reproduce it.
If you want to make the clicking away i reduce the gain amount to
 lfoGain.gain.value = 2000;

Then it doesn't click and you have this nice "wable" effect.
Or do you just not want this wable effect?
You can as well  reduce the amount of time the wable takes to:
lfo.frequency.value = 1;

so it doesn't click. The clicking happens if the sound drops too fast. If the curve drops too fast than it clicks. Everywhere on every synthesizer always! And that's the right answer :)


text:
Q: Is it essential to use a return 0 statement when we use int main() in c? What will happen if we don't use it? will the compiler automatically add it like it does in C++?

A: It will return 0 automatically in C99-compliant compilers (and later). In pre-C99 compilers the return value is undefined in such cases.
In other words, in modern C you don't need an explicit return 0 at the end of main.


text:
Q: How to emulate CUDA on windows is there any way I can test the CUDA samples and codes from a computer with no NVIDIA graphic card?
I am using Windows and the latest version of CUDA.

A: There are several possibilities:

*

*Use older version of CUDA, which has built-in emulator (2.3 has it for sure). Emulator is far from good, and you won't have features from latest CUDA releases.

*Use OpenCL, it can run on CPUs (though not with nVidia SDK, you will have to install either AMD or Intel OpenCL implementation (AMD works fine on Intel CPUs, btw)). In my experience, OpenCL is usually slightly slower than CUDA.

*There is windows branch of Ocelot emulator: http://code.google.com/p/gpuocelot/. I haven't tried it, though.

However, I would recommend buying some CUDA-capable card. 8xxx or 9xxx series is ok and really cheap. Emulation would allow you to get some basic skills of GPGPU programming, but is useless when you write some real-world application since it doesn't allow you to debug and tune performance.


text:
Q: How to remove a node using Nokogiri I have an HTML structure like this:

  This is

 very

   important.

I know how to get a Nokogiri::XML::NodeSet from this:
dom.xpath("//div")

I now want to filter out any script tag:
dom.xpath("//script")

So I can get something like:

  This is

 very

   important.

So that I can call div.text to get:
"This is very important."

I tried recursively/iteratively going over all children nodes and trying to match every node I want to filter out any node I don't want, but I ran into problems like too much whitespace or not enough whitespace. I'm quite sure there's a nice enough and rubyesque way.
What would be a good way to do this?

A: NodeSet contains the remove method which makes it easy to remove whatever matched your selector:
require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)

foo

bar

EOT

doc.search('p').remove
puts doc.to_html

# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >>
# >>
# >>

# >>
# >>

Applied to your sample input:
require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)

  This is

 very

  important.

EOT

doc.search('script').remove
puts doc.to_html

# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >>
# >>

# >>   This is
# >>
 very
# >>
# >>

# >>    important.
# >>

# >>

At that point the text in the
 is:
doc.at('div').text # => "\n  This is\n   very\n    \n  \n   important.\n"

Normalizing that is easy:
doc.at('div').text.gsub(/[\n ]+/,' ').strip # => "This is very important."

A: 1st problem
To remove all the script nodes :
require 'nokogiri'

html = "

  This is

 very

   important.

"

doc = Nokogiri::HTML(html)

doc.xpath("//script").remove

p doc.text
#=> "\n  This is\n   very\n    \n  \n   important.\n"

Thanks to @theTinMan for his tip (calling remove on one NodeSet instead of each Node).
2nd problem
To remove the unneeded whitespaces, you can use :

*

*strip to remove spaces (whitespace, tabs, newlines, ...) at beginning and end of string

*gsub to replace mutiple spaces by just one whitespace

p doc.text.strip.gsub(/[[:space:]]+/,' ')
#=> "This is very important."


text:
Q: State-space to transfer function I'm looking into MATLAB's state-space functionality, and I found a peculiar relation that I don't believe I've seen before, and I'm curious how one might obtain it. According to this documentation page, when converting a state-space system representation to its transfer function, the following well-known equality is used
$$H(s) = C(sI-A)^{-1}B$$
However, they go one step further and state that
$$H(s) = C(sI-A)^{-1}B = \frac{{\det}(sI-A+BC) - {\det}(sI-A)}{\det(sI-A)}$$
How did they manage to convert $C{\text {Adj}}(sI-A)B$ into ${\det}(sI-A+BC) - {\det}(sI-A)$?
As far as I understand, we can assume here that $B$ is a column vector and $C$ is a row vector, i.e. it's a single-input / single-output relationship.

A: They are using the Sherman-Morrison formula, which I remember best in the form
$$
 \det(I+MN) = \det(I+NM);
$$
this holds provided that both products $MN$ and $NM$ are defined. Note that if $M$ is
a column vector and $N$ a row vector, then $I+NM$ is a scalar. Now
$$\begin{align}
 \det(sI-A+BC) &= \det\left((sI-A)(I+(sI-A)^{-1}BC\right)\\ &= \det(sI-A)\det(I+(sI-A)^{-1}BC) \tag{1}.
\end{align}
$$
Applying the formula with $M=I+(sI-A)^{-1}B$ and $N=C$ yields that
$$
 \det(I+(sI-A)^{-1}BC) = \det(I+C(sI-A)^{-1}B).
$$
If $B$ is a column vector and $C$ a row vector then the final determinant is equal to
$$
 1 + C(sI-A)^{-1}B \tag{2}
$$
Plugging (2) to (1), gives
$$
\det(sI-A+BC) = \det(sI-A)\left( 1 + C(sI-A)^{-1}B \right)
$$
Shuffling terms gives the result.


text:
Q: Change results URL in Alfresco AIkau faceted search page I have some difficulties customizing the Aikau faceted search page on Alfresco, which may be more a matter of lack of my knowledge about dojo/AMD.
What I want to do is to replace the document details page URL by a download URL.
I extended the Search Results Widget to include my own custom module :
var searchResultWidget = widgetUtils.findObject(model.jsonModel, "id", "FCTSRCH_SEARCH_RESULT");

if(searchResultWidget) {
    searchResultWidget.name = "mynamespace/search/CustomAlfSearchResult";
}

I understand search results URLs are rendered this way :
AlfSearchResult module => uses SearchResultPropertyLink module => mixins _SearchResultLinkMixin renderer => bring the "generateSearchLinkPayload" function => renders URLs depending on the result type
I want to override this "generateSearchLinkPayload" function but I can't figure out what is the best way to do that.
Thanks in advance for the help !

A: This answer assumes you're able to use the latest version of Aikau (at the time of writing this is 1.0.61). Older versions might require slightly different overriding...
In order to do this you're going to need to override the createDisplayNameRenderer function of AlfSearchResult in your CustomAlfSearchResult widget. This will allow you to create an extension of alfresco/search/SearchResultPropertyLink.
If you want to take advantage of the the download capabilities provided by the alfresco/services/DocumentService for downloading both documents and folders (as a zip) then you're going to want to change both the publishTopic and publishPayload of the SearchResultPropertyLink.
You should extend the getPublishTopic and generateSearchLinkPayload functions. For the getPublishTopic function you'll want to change the return value to be "ALF_SMART_DOWNLOAD" (there are constants available for these strings in the alfresco/core/topics module). This topic can be used to tell the DocumentService to take care of figuring out if the node is a folder or document and will make an XHR request for the full node metadata (in order to get the contentUrl attribute that is not included in the data returned by the Search API.
You should extend the generateSearchLinkPayload function so that for document or folder types the payload contains the attribute nodes that is a single array where the object is the search result object that you wish to download.
I would recommend that you call this.inherited first to get the default payload and only update it for documents and folders.
Hopefully that all makes sense - if not, add a comment and I'll try to provide further assistance!

A: This is the answer for 1.0.25.2 - unfortunately it's not quite so straightforward...
You still need to extend the alfresco/search/AlfSearchResult widget, however this time you need to extend the postCreate function (remembering to call this.inherited(arguments)). It's not possible to stop the original alfresco/search/SearchResultPropertyLink widget from being created... so it will be necessary to find it and destroy it.
The widget is not assigned to a variable, so it will be necessary to find it using dijit/registry. Use the byNode function from dijit/registry to find the widget assigned to this.nameNode and then call destroy on it (be sure to pass the argument true to preserve the DOM). However, you will then need to empty the DOM node so that you can start again...
Now you need to add in your extension to alfresco/search/SearchResultPropertyLink. Unfortunately, because the smart download capability is not available you'll need to do more work. The difference here is that you'll need to make an XHR request to retrieve the full node metadata in order to obtain the contentURL. It's possible to publish a request to the DocumentService(via the "ALF_RETRIEVE_SINGLE_DOCUMENT_REQUEST" topic). However, you need to be aware that having the XHR step will not allow you to then proceed with the download as is. Instead you'll need to use an iframe download solution, I'd suggest you take a look at the changes in the pull request we recently made to solve this problem and backport them into your own solution.


text:
Q: Call CasperJS from a script I currently run a CasperJS script from CLI like so:
casperjs --ignore-ssl-errors=true --ssl-protocol=any scrape.js

.. but to automate the whole process I need to call it from another script as a module/function and pass parameters (keywords etc). So wondering whats the best way to do it.

A: Figured it. Spooky!
var spooky = new Spooky({
  casper: {
    //configure casperjs here
  }
}, function (err) {
  // NODE CONTEXT
  console.log('We in the Node context');
  spooky.start('http://www.example.com
  spooky.then(function() {
    // CASPERJS CONTEXT
    console.log('We in the CasperJS context');
    this.emit('consoleWe can also emit events here.');
    this.click('a#somelink  });
  spooky.then(function() {
    // CASPERJS CONTEXT
    var size = this.evaluate(function() {
    // PAGE CONTEXT
    console.log('....'); // DOES NOT GET PRINTED OUT
    __utils__.echo('We in the Page context'); // Gets printed out
    this.capture('screenshot.png');
    var $selectsize = $('select#myselectlist option').size();
      return $selectsize;
    })
  })

source


text:
Q: Linq Sum for Multiple Joins Can someone help me out with the following Linq statement? I'm trying to get join 4 tables through Linq, group by the last table and sum a property of the first.
var payments = (
                from payment in db.Payments
                join payees in db.cmsMembers on payment.PayeeID equals payees.nodeId
                join payeeGroups in db.cmsMember2MemberGroups on payees.nodeId equals payeeGroups.Member
                join groups in db.umbracoNodes on payeeGroups.MemberGroup equals groups.id
                group groups by new {groups.text, payment} into groupedPayments
                select new
                {
                    Group = groupedPayments.Key.text,
                    Count = groupedPayments.Count(),
                    Amount = groupedPayments.Sum(?)
                }
            ).ToList();

The issue I'm having is that the in the groupedPayments.Sum(..) call I'm only getting access to the "groups" object. This is fine for the Group name and count aspect but the SUM has to be performed on the payment.Amount property.

A: I've managed to resolve my issue. I hadn't realised that the object in the group declaration would become the actual object witin the resulting group item. By altering the original statement to the following:
group payment by groups into groupedPayments

it seems that each instance of groupedPayments.Key in the select statement now corresponds to the payment row which is what I required.


text:
Q: Deselect a Table View Cell that has been selected programmatically I am implementing a search feature where you can select results and I'm trying to make it so that it remembers which cells were selected if they show up in the results again.
I'm using cell.setSelected(true, animated: false) in the willDisplayCell function. However, now there is no way to deselect the cells. When tapped on again, neither the didSelectRowAtIndexPath nor the didDeselectRowAtIndexPath functions are being called. What can I do?

A: Try to use tableView.selectRowAtIndexPath(indexPath: NSIndexPath?NSIndexPath?, animated: Bool, scrollPosition: UITableViewScrollPosition) to select cells. Then you'll get deselect events.


text:
Q: Concatenate two columns with different names I have two tables, joined on one column, I want to concatenate one of the columns with different names into the same column, I have tried this
I want whstocks.warehouse to be concatenated with brnstocks.brachcode.
current result (no 900 brachcode from whstocks)

brachcode | varint | stock
---------------------------
201       |24601121| 2
204       |24601121| 3
197       |24601121| 4

Desired result (bring 900 from whstocks.warehouse into branchcode)

brachcode | varint | stock
---------------------------
201       |24601121| 2
204       |24601121| 3
197       |24601121| 4
900       |24601121| 400

SELECT  brnstocks.branchcode , brnstocks.varint , SUM(brnstocks.retail)
FROM dbo.brnstocks
INNER JOIN dbo.whstocks
ON brnstocks.varint = whstocks.varint
GROUP BY brnstocks.branchcode, whstocks.warehouse
        ,brnstocks.varint
        ,brnstocks.retail
        ,whstocks.stock
HAVING (SUM(brnstocks.retail) > 0)

A: Try this:
SELECT
    P.branchcode , P.varint , SUM(P.retail)
FROM
(SELECT
    branchcode , varint , retail
FROM dbo.brnstocks
UNION
SELECT
    branchcode , varint , retail
FROM dbo.whstocks
) AS P

GROUP BY P.branchcode , P.varint
HAVING (SUM(P.retail) > 0)

Assuming that whstocks has the same fields as brnstocks. If not, substitute the matching fields from whstocks

A: Since you're already grouping by both, you should be able to concatenate them using the + operator.
SELECT  whstocks.warehouse + brnstocks.branchcode [WarehousePlusBranch], brnstocks.varint , SUM(brnstocks.retail)
FROM dbo.brnstocks
INNER JOIN dbo.whstocks
ON brnstocks.varint = whstocks.varint
GROUP BY brnstocks.branchcode
        ,whstocks.warehouse
        ,brnstocks.varint
        ,brnstocks.retail
        ,whstocks.stock
HAVING (SUM(brnstocks.retail) > 0)


text:
Q: Finding nth Occurrence in multiple columns in Excel I have two columns with team names and two columns with corresponding stats.  I need to go through the 2 columns and find the stats that match the team name, and they need to be in order.  VLOOKUP, MATCH, and SEARCH don't seem to work with multiple columns.  Does anyone know how this can be done?

A: Assuming in your picture, the "Home" title is in cell B2 then the following array formula can be put in the cells H3:L7 (array formulas need to be entered with Ctrl+Shift+Enter)
=IFERROR(OFFSET($D$1,-1+SMALL(IF(($B$3:$B$7=H$2)+($C$3:$C$7=H$2),ROW($B$3:$B$7),"X"),ROW()-ROW($2:$2)),--NOT((INDEX($B:$B,SMALL(IF(($B$3:$B$7=H$2)+($C$3:$C$7=H$2),ROW($B$3:$B$7),"X"),ROW()-ROW($2:$2)))=H$2))),"")

Let me break it down...

*

*the logic is: OFFSET(top_of_results,row_number_that_has_Nth_team_score,0_or_1_for_home_or_away)

*this is wrapped in an IFERROR in for where there isn't e.g. a 5th score for team A

*using the array part IF(($B$3:$B$7=H$2)+($C$3:$C$7=H$2),ROW($B$3:$B$7),"X" we get an array of that has the ROW number if either (done using +) B or C have a value matching our team header (H$2) or an X otherwise

*using SMALL(...,ROW()-ROW($2:$2)) we get the Nth smallest row, based on 1st being in row 3, 2nd in row 4 etc.

*to get whether it is home or away, we check column B on our row to see if it matches --NOT((INDEX($B:$B,row_number_that_has_Nth_team_score-O)=H$2)) this gives 0 for home, 1 for away and this is used to offset the column

Hopefully it makes sense. Array formulas are very powerful, if a little confusing :-) I recommend CPearson's intro for more information.
Good luck!


text:
Q: Change php.ini used by commandline I try to run a script from the command line, a script made by zend framework. I used also the Zend Server who has her own php.ini. When I try to start my script on the command line I am not able to connect with my mysql database. It's because from the command line it takes (it has to be) another php.ini file located somewhere on my Mac OS X Lion system because the path to the mysql.sock isnt the path who is configurated in the zend server php.ini.
I would like to let the command line use my php.ini of zend Server.
I hope someone knows how to do this.
Kind regards,
Nicky

A: You can launch php from the command line with an option to specific the path where the php.ini file you want it to use is located:
php -c /path/to/zend/phpini/folder myfile.php

To find out the the folder where the command line php.ini is located, you can use:
php -i | grep php.ini