text:
Q: Different fields for different users (people or organizations) I have a website which allows only people registration. Now I would like to add organizations registration.
The problem is that people and organizations have some identical fields and some different fields (e.g. organizations haven't got a surname or date of birth but may have other fields that people don't need).
Users behavior is the same. Only fields are different.
What is the best way to implement organizations registration?
Should I create a polymorphic association or there is a simpler/better solution?

A: simply create first step where people can choose usual or organization's registration, and render right form then
for validations use :if => lambda { self.organization? }  ( organization boolean field)


text:
Q: Custom list view filter not working in mobile view I had to filter sharepoint list view dynamically with n number of conditions so I have written the code in PageHead delegate control. Everything works fine on browser but when I try to check the same page in mobile view it says cannot complete action.
I had debug to see the issue and have found the delegate control is not getting called for mobile view.
Can someone please assist as to how I can execute delegate control in mobile view also??

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why Reveal effect not working as per Developer blog I want to have Reveal Effect with in my app. I come to know about it for how it can be implemented. I got the information from the Andoid Developer Blog.
But when i have updated that with in my code, it is not showing any effect.
I have also try with Demo given by Google to demostrate Reveal effect. But it also not showing the effect. If there any permission i need to add or whats wrong i am doing?
My animator is as below:
View button = rootView.findViewById(R.id.button);
    final View shape = rootView.findViewById(R.id.circle);
    shape.setClipToOutline(false);
    shape.setVisibility(View.INVISIBLE);
    // Set a listener to reveal the view when clicked.
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(isShowing==false){
                // previously invisible view

                // get the center for the clipping circle
                int cx = (shape.getLeft() + shape.getRight()) / 2;
                int cy = (shape.getTop() + shape.getBottom()) / 2;

                // get the final radius for the clipping circle
                int finalRadius = Math.max(shape.getWidth(), shape.getHeight());

                // create the animator for this view (the start radius is zero)
                Animator anim =
                        ViewAnimationUtils.createCircularReveal(shape, cx, cy, 0, finalRadius);

                // make the view visible and start the animation
                shape.setVisibility(View.VISIBLE);
                anim.setDuration(4000);
                anim.start();
            }else{

                // get the center for the clipping circle
                int cx = (shape.getLeft() + shape.getRight()) / 2;
                int cy = (shape.getTop() + shape.getBottom()) / 2;

                // get the initial radius for the clipping circle
                int initialRadius = shape.getWidth();

                // create the animation (the final radius is zero)
                Animator anim =
                        ViewAnimationUtils.createCircularReveal(shape, cx, cy, initialRadius, 0);

                // make the view invisible when the animation is done
                anim.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        shape.setVisibility(View.INVISIBLE);
                    }
                });

                anim.setDuration(4000);
                // start the animation
                anim.start();
            }

            isShowing = !isShowing;

    }
    });

Please let me know how to achieve this effect.

A: Not everything that was introduced with Lollipop was backported. Reveal, ripple and elevation are some examples. The main reason is that some of them rely heavily on the new UI Thread introduced whit ART. You can find more info here, on the very bottom, in the faq section


text:
Q: Use column references in Oracle SQL select query to avoid re-calculation I want to create a summarised database backup report, which includes data from multiple database tables which has no relation to each other. For example, I want to include the name of the database from v$database view:
SQL> Select name from v$database;

And the size of the database:
SQL> SELECT sum(bytes) FROM v$datafile;

And consider there is no common column between those two views.
Beside that I want to include the database size in Bytes, KBs, MBs ,......, and so on.
I am using the following query:
SQL> SELECT
        "Database", "DB_SIZE_IN_Bytes", "DB_SIZE_IN_KBs", "DB_SIZE_IN_MBs",
        "DB_SIZE_IN_GBs", "DB_SIZE_IN_TBs"
FROM (
    SELECT
           (SELECT name FROM v$database ) "Database",
           (SELECT sum(bytes) FROM v$datafile ) "DB_SIZE_IN_Bytes",
           (SELECT sum(bytes)/1024 FROM v$datafile ) "DB_SIZE_IN_KBs",
           (SELECT sum(bytes)/1024/1024 FROM v$datafile ) "DB_SIZE_IN_MBs",
           (SELECT sum(bytes)/1024/1024/1024 FROM v$datafile ) "DB_SIZE_IN_GBs",
           (SELECT sum(bytes)/1024/1024/1024/1024 FROM v$datafile ) "DB_SIZE_IN_TBs"
    FROM dual
    );

In this way I am avoiding the join condition between v$database and v$datafile.
This is just an example, however, in my project I have more than 10 tables. Most of them without a common column.
The question is while converting bytes into kbs, mbs, and so on, I want to use the column references such as:
(SELECT DB_SIZE_IN_Bytes/1024 FROM dual ) "DB_SIZE_IN_KBs",
(SELECT DB_SIZE_IN_KBs /1024 FROM dual ) "DB_SIZE_IN_MBs",
(SELECT DB_SIZE_IN_MBs /1024 FROM dual ) "DB_SIZE_IN_GBs",
(SELECT DB_SIZE_IN_GBs /1024 FROM dual ) "DB_SIZE_IN_TBs"

instead of again and again calculations. Is there any way to use the column references such as mentioned above in the example instead of re-calculation?

A: Use a subquery to calculate the results of the sum once in the from clause and then use that:
SELECT (SELECT name FROM v$database ) as "Database",
        DB_SIZE_IN_Bytes,
        DB_SIZE_IN_Bytes / 1024 as DB_SIZE_IN_KBs,
        DB_SIZE_IN_Bytes / (1024 * 1024) as DB_SIZE_IN_MBs,
        DB_SIZE_IN_Bytes / (1024 * 1024 * 1024) as DB_SIZE_IN_GBs,
        DB_SIZE_IN_Bytes / (1024 * 1024 * 1024 * 1024) as DB_SIZE_IN_TBs
FROM (SELECT sum(bytes) as DB_SIZE_IN_Bytes FROM v$datafile ) x;

You can also do this use lateral joins, but it is definitely overkill for this particular example:
SELECT (SELECT name FROM v$database ) as "Database",
        bb.*, bk.*, bm.*, bg.*, bt.*
FROM (SELECT sum(bytes) as DB_SIZE_IN_Bytes FROM v$datafile
     ) bb CROSS JOIN LATERAL
     (SELECT bb.DB_SIZE_IN_Bytes / 1024 as DB_SIZE_IN_Kb
      FROM dual
     ) bk CROSS JOIN LATERAL
     (SELECT bk.DB_SIZE_IN_Kb / 1024 as DB_SIZE_IN_Mb
      FROM dual
     ) bm CROSS JOIN LATERAL
     (SELECT bm.DB_SIZE_IN_Mb / 1024 as DB_SIZE_IN_Gb
      FROM dual
     ) bg CROSS JOIN LATERAL
     (SELECT bb.DB_SIZE_IN_Gb / 1024 as DB_SIZE_IN_Tb
      FROM dual
     ) t;


text:
Q: NoSuchMethodError when running Arquillian test with Spring I have a project at work in Spring 5 (version 5.1.6.RELEASE) and I want to write a test with Arquillian. I have used Arquillian with JavaEE (EJB) in the past and it is the first time that I use it with Spring.
I have found this repository https://github.com/arquillian/arquillian-extension-spring and I have added the relevant dependencies.
All the Arquillian relevant dependencies I have in pom.xml are the below:
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.21.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.arquillian.extension</groupId>
            <artifactId>arquillian-service-integration-spring</artifactId>
            <version>${arquillian.spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.extension</groupId>
            <artifactId>arquillian-service-integration-spring-inject</artifactId>
            <version>${arquillian.spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.extension</groupId>
            <artifactId>arquillian-service-integration-spring-javaconfig</artifactId>
            <version>${arquillian.spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.shrinkwrap.resolver</groupId>
            <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
            <version>3.1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <version>1.4.1.Final</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.wildfly.arquillian</groupId>
            <artifactId>wildfly-arquillian-container-managed</artifactId>
            <version>2.1.1.Final</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.wildfly.arquillian</groupId>
            <artifactId>wildfly-arquillian-container-domain-managed</artifactId>
            <version>2.1.1.Final</version>
            <scope>test</scope>
        </dependency>

The arquillian.xml is as per below (with the necessary modifications in the property values):
<?xml version="1.0"?>
<arquillian xmlns="http://jboss.org/schema/arquillian" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="
        http://jboss.org/schema/arquillian
        http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

    <!-- Sets the protocol which is how Arquillian talks and executes the tests inside the container -->
    <defaultProtocol type="Servlet 3.0"/>

    <container qualifier="wildfly-managed" default="true">
        <configuration>
            <property name="managementAddress">IP</property>
            <property name="managementPort">port</property>
            <property name="username">username</property>
            <property name="wildflyHome">path/to/wildfly</property>
            <property name="password">password</property>
        </configuration>
    </container>
    <extension qualifier="spring">
        <property name="customContextClass">org.springframework.context.support.ClassPathXmlApplicationContext
        </property>

        <property name="customAnnotationContextClass">
            org.springframework.context.annotation.AnnotationConfigApplicationContext
        </property>
    </extension>
</arquillian>

I have created the below class in order to create the necessary jar:
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;

public class MyDeployment {

    public static JavaArchive getJar() {
        JavaArchive jar = ShrinkWrap.create(JavaArchive.class).addPackages(true, "package.name");
        JavaArchive[] dependencies = Maven.configureResolver().workOffline().loadPomFromFile("pom.xml").
                importRuntimeDependencies().resolve().withTransitivity().as(JavaArchive.class);

        for(JavaArchive lib: dependencies) {
            jar = jar.merge(lib);
        }
        return jar;
    }
}

I have added a demo test just to run Arquillian as per below:
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.spring.integration.test.annotation.SpringAnnotationConfiguration;
import org.jboss.shrinkwrap.api.Archive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;

@RunWith(Arquillian.class)
//@SpringAnnotationConfiguration(classes = {BackendAppConfig.class, DatabaseConfig.class})
public class ArquillianExampleTest {

    @Deployment
    public static Archive<?> createTestArchive() {
        return MyDeployment.getJar();
    }

    @Test
    public void testAddNewInteraction() {
        String hello = "Hello";
        Assert.assertEquals("Hello", hello);
    }

}

However I get the below error:
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:66)
Caused by: java.lang.NoSuchMethodError: org.junit.runners.model.TestClass.getAnnotatedFields()Ljava/util/List;
    at org.jboss.arquillian.junit.State.hasAnyArquillianRule(State.java:93)
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:84)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    ... 5 more

Could you please help me with this error? Why I get NoSuchMethodError, since I have added the pom dependencies in the JavaArchive (in MyDeployment.java class I provided above)?


text:
Q: RCurl getURLContent detect content type through final redirect This is a followup question to RCurl getURL with loop - link to a PDF kills looping :
I have the following getURL command:
require(RCurl)
#set a bunch of options for curl
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
agent="Firefox/23.0"
curl = getCurlHandle()
curlSetOpt(
  cookiejar = 'cookies.txt' ,
  useragent = agent,
  followlocation = TRUE ,
  autoreferer = TRUE ,
  httpauth = 1L, # "basic" http authorization version -- this seems to make a difference for India servers
  curl = curl
)

x = getURLContent('http://timesofindia.indiatimes.com//articleshow/2933019.cms')
class(x)
#[1] "character"
attr(x, "Content-Type")
#"text/plain"

In a browser, the link above ends up redirecting to:
x = getURLContent('http://timesofindia.indiatimes.com/photo.cms?msid=2933009')
class(x)
#[1] "raw"
attr(x, "Content-Type")
#"application/pdf"

Assuming I know only the first link, how can I detect that the final location of the redirect (or redirects) is of a certain type (in this case PDF)?
Thanks!!

A: Maybe there's a better solution, but one way could be this:
# ...
h <- basicTextGatherer()
x = getBinaryURL('http://timesofindia.indiatimes.com//articleshow/2933019.cms',
                 headerfunction = h$update, curl = curl)
r <- gregexpr("Content-Type:.*?\n", h$value())
tail(regmatches(h$value(), r)[[1]], 1)
# [1] "Content-Type: application/pdf\r\n"

A: I have run into a similar issue trying to run getURLContent using digest authentication to get at binary data (using a non-standard mime type).  I am running RCurl v1.95-4.1 on R 2.15.3.
If I run getURLContent without the binary=TRUE flag, it won't autoswitch to binary=TRUE because of the mime header for this data type, so it attempts to perform a rawToChar() and throws a 'embedded NULL in string' error.  However the authentication does work.
If I add a binary=TRUE flag to the getURLContent call, it seems to cause issues with the authentication step, since I then get an 'Error: Unauthorized' response.
What finally worked was to replace getURLContent() with getBinaryURL() [as in the example above], which allowed the userpwd="u:p" authorization to work and delivered the binary data to my assigned object.
I think that the author of RCurl has made improvements to getURLContent's handling of binary data for v1.97, based on what I see in GitHub, so this may become a thing of the past...except for those of us still running older R setups.


text:
Q: Why Cloud Vision API returns not exact matches? I am trying to use the Cloud Vision API to identify similar images in a webpage using example from https://cloud.google.com/vision/docs/detecting-web#web_detection_requests. I enabled the WEB_DETECTION feature and provided the image as input.
The API returned the collection of PagesWithMatchingImages, that are very similar to the input image, but are not exact matches. Both records with FullMatchingImages and PartialMatchingImages are affected by the problem. Is this expected behavior for the WEB_DETECTION feature? Is there an option to control or show how similar the found images are to the input image?

A: I don't think the result score still exists... no documentation confirmation.
https://cloud.google.com/vision/docs/reference/rest/v1/AnnotateImageResponse#WebImage[enter image description here]1
But sth like FullMatching should exist:


text:
Q: how to stack vertical content to horizontal in bootstrap I am trying to make this setup in boostrap 3, is there a way to do it?

A: You have to learn the grid bootstrap system. You can define the size for each device. Take a look at bootstrap. The idea is simple, col-xs defines phones width, col-sm defines tablet width, col-md defines desktop width and col-lg defines large devices like TV's.
See the example below, you can preview (like mobile) and click at "Full Page" to preview bigger devices.
I hope it help

.well{
  font-size:40px;
  font-weight: 500;
  text-align:center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

    1

      2.1

      2.2

      3.1

      3.2

A: It's fairly easy to do, you just need to make it a nested structure and apply the correct col-lg-x, col-md-x, col-sm-x, col-xs-x classes to each level.
Here's a quick little throw together that does exactly what you're looking for:

div {
    border: 1px solid black;
    padding: 10px;
}
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://getbootstrap.com/dist/css/bootstrap-theme.min.css" rel="stylesheet"/>

1

2.1

2.2

3.1

3.2

4.1

4.2

5.1

5.2

Note: I added a 1px border and a 10px padding to make it more noticeable.
For a better demonstration of this, here's a Bootply: http://www.bootply.com/WOrm6c6sm1
References: http://getbootstrap.com/css/#grid

A: For sure there is, I would recommend you look at bootstrap's documentation of the grid system (link below). This seams to be a relatively simple problem to fix just by playing around with nesting grids however to get you started i've made you this plunker.
read this first
http://getbootstrap.com/css/#grid

http://plnkr.co/edit/bQRdmdd1eSSpJ27Pghzj?p=preview


text:
Q: Cant call javascript function in php file (Laravel) Im curently learning laravel with QR code. I use the code that I got from github. Its working fine when I run the html file. But when I add to my code in php file (Laravel) I get some error.
The error:

ErrorException (E_ERROR)
  Call to undefined function formatName() (View: C:\xampp\htdocs\museumadityawarman\resources\views\topups\scan_qrcode.blade.php)

The error points out to this part of my view:
{{ formatName(camera.name) }}

This does fix the error message but I still can't get the value.
This is some of Javascript code:
 methods: {
    formatName: function (name) {
      return name || '(unknown)';
    },
    selectCamera: function (camera) {
      this.activeCameraId = camera.id;
      this.scanner.start(camera);
    }   }

Thanks, sorry for my bad english.

A: You have to put an @ before the {{ formatName(camera.name) }}
@{{ formatName(camera.name) }}

Look at the Laravel doc https://laravel.com/docs/5.6/blade#blade-and-javascript-frameworks:

Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade rendering engine an expression should remain untouched

EDIT:
Since you look like you are using vue.js, you could also use the directive v-text like so :


text:
Q: Is "get cut" a passive voice?
The wild flowers and herbs get cut before they have a chance to flower
  and propagate.

I think the sentence is in the passive voice. Why does the writer use get instead of are ? When we have to use get not verb to be?

A: Yes, that is a passive construction.  "They get cut" can be phrased in the active voice: "Something cuts them".
Yes, there is a difference.  The verb to be expresses a state.  The verb to get expresses an action.

The window was closed yesterday.
  The window got closed yesterday.

With to get, the action is explicitly placed in the recent past.  This suggests that the window was open the day before yesterday.  With to be, the state is placed in the recent past, but there is no mention of the time of the action.  We are free to assume that the window has been closed since some time in the distant past.  For all we know, before yesterday the window might never have been open.
However, to be also leaves us free to assume that the times of state and action coincide.  Under that interpretation, was closed and got closed are rough synonyms.


text:
Q: Fatal error: Call to undefined function oci_connect() Erro ao conectar no banco Oracle.
Segue abaixo o código em PHP:
<?php
$ora_bd = "(DESCRIPTION=
      (ADDRESS_LIST=
        (ADDRESS=(PROTOCOL=TCP)
          (HOST=192.168.0.249)(PORT=1521)
        )
      )
      (CONNECT_DATA=(SERVICE_NAME=CSTESTE))
 )";

$ora_conexao = oci_connect('refeitorio', 'tiete2018', $ora_bd);

if (!$ora_conexao) {
$erro = oci_error();
    trigger_error(htmlentities($erro['message'], ENT_QUOTES), E_USER_ERROR);
    exit;
}else{
echo "Conectado com Sucesso.";
}

Lembrando que já habilitei os seguintes comandos no php.ini
extension=php_oci8.dll
extension=php_pdo_oci.dll
extension=php_oracle.dll

Aparece o seguinte erro:

Fatal error: Uncaught Error: Call to undefined function oci_connect() in C:\wamp64\www\Sistema\Refeicao\Core\TesteCon.php:11 Stack trace: #0 {main} thrown in C:\wamp64\www\Sistema\Refeicao\Core\TesteCon.php on line 11

A: Tive esse problema recentemente e a solução foi esta:
Você baixa o xamp ou wamp 32 ou 64 bits esta terá que ser sua versão do instant client oracle
após instalar eles com qualquer versão do php, ao chamar uma função oci_oracle vai dar erro.
Você precisa então primeiro habilitar as extensões no php.ini
um exemplo de como acessar o php.ini no xamp:

habilite essas extensões nessa ordem:
extension=php_oci8.dll
extension=php_oci8_12c.dll
extension=php_oracle.dll

Observação: se não tiver para habilitar, crie e verifique a segunda, eu coloquei 12c pois meu instant client é 12c.
Depois disso você precisa instalar o instant client.
Abre o cmd COMO ADMINISTRADOR vai no local do instant client e roda odbc_install
O próximo passo é o mais importante, e é por isso que eu tava levando uma surra:
você precisa adicionar no PATH onde está seu oracle instant client:

e criar a TNS.ADMIN:

faz isso para as duas caixas de variáveis, sistema e usuário:

Feito isso, configure o arquivo tnsnames.ora reinicie sua máquina, e você poderá usar as funções oci.

Seu instant client tem que estar na mesma versão do php, 32 ou 64

baixando o php 7 no php.ini dele ele pede a versão 12 do instant client como você pode ver na foto.

A: Cara, tive esse problema e ele me tirou o sono por alguns dias. No meu caso o erro era:

Fatal error: Call to undefined function oci_connect()

Só consegui resolver reinstalando tudo na versão 32 bits. Pra mim funcionou bem. Eu instalei o XAMPP xampp-win32-7.3.2-0-VC15 e habilitei a extensão:
 extension=oci8_12c

no arquivo php.ini. Vale a pena conferir também se a extensão está no lugar certo:
extension_dir="C:\xampp\php\ext"

Depois disso você instala o Oracle Instant Client na versão certa, no meu caso foi 32-bits na versão 12_2. O próximo passo é colocar esse caminho nas variáveis de ambiente, como o amigo acima falou.
Depois de fazer isso deve ser possível ver a OCI8 na página do phpInfo:

Uma outra dica é verificar quais erros existem no seu php. Para fazer isso abra o prompt de comando e navegue até a pasta do php do xampp. no meu caso era "C:\xampp\php". Digite o comando 'php' e veja se há algum problema com as dlls habilitadas. Caso exista, o problema será mostrado. Se quiser fazer isso como teste na sua versão atual, veja se aparece alguma mensagem como "arquivo não encontrado" ou "arquivo não é win 32". Se aparecer, muito provavelmente essa solução, de passagem para versão 32 bits, irá resolver seu problema!


text:
Q: How to transfer Javascript code correctly? I have two codes, both generate a line chart. However, the first one doesn't use mysql datasource, it uses random math generated datapoints. But it uses a refresh interval and thus is live.
The second code does in fact use a mysql datasource and displays the data in my database in the line-chart. However it is not live, because it does not it has not refresh-interval function.
I was trying to transfer the refresh-Interval / chart-update code parts of the first code  to my second code that is not live but uses a real data source.
Here is my live code, with random datapoints:

This is my code of the static line chart (not live) but uses real data source:

This is what I have tried so far:

But it keeps saying

Unexpected token ')' at line 42

            chart.render();

    )};

I am pretty embarrassed but I can't find the solution due to all the bracelets/parenthesizes. I have tried everything. With ) and without } but nothing seems to deliver.
If this is solved, will the chronological positions of the code be alright?
EDIT: FIRST PROBLEM SOLVED, NEW PROBLEM: JS POSITIONING
<!DOCTYPE HTML>

output:

Can't find variable: updateChart

A: You used )}; instead of });
also at the end of your JS you used only } instead of });
also call your chart like
setInterval(updateChart, updateInterval);

and make sure your updateInterval is in the right function scope.
Here's how it should approximately look like:
jQuery(function ($) {

    function updateChart( result ) { // move it here!!!
        $.getJSON("arduino_data.php", function( result ){
            var dataPoints = [];
            var dataLength = 500; // number of dataPoints visible at any point
            var updateInterval = 1000;
            var chart = new CanvasJS.Chart("chartContainer",{ // new chart Object
                title :{
                    text: "Patient #01"
                },
                data: [{
                    type: "line",
                    dataPoints: dataPoints
                }]
            });
            for (var i = 0; i <= result.length - 1; i++) {
                dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
            }
            if (dataPoints.length > dataLength){
                dataPoints.shift();
            }
            chart.render();
        });
    }

    // First read - Start
    updateChart();
    // Update chart after specified time.
    setInterval(updateChart, updateInterval);

});


text:
Q: PPTPD Couldn't open the /dev/ppp device: Permission denied I cannot connect to my pptpd server, because it fails to send LCP: Config-Requests to my client. I found the problem, it was located in syslog
 Jan 14 03:45:38 mightyowl3 pppd[22256]: Couldn't open the /dev/ppp device: Permission denied

can someone please help me fix this...
Extra stuff:
I did
chown root
chmod 777

on it.

A: What is the permission on /dev/ppp?  Who owns /dev/ppp?  What is the group membership of /dev/ppp?  What is the username/group under which pptpd being run as?
Providing and analyzing at least this information would help you and perhaps allow us to direct you to the right place to fix this problem.

A: Some VPS has the configuration of enable PPP service, so you can check it and enable the PPP item. The default settings may be disabled, this can cause error:
Couldn't open the /dev/ppp device: No such file or directory

vps config for ppp

A: It seems that the user running the pppd process cannot access to the device. Probably you need to add the user at least to the group of /dev/ppp


text:
Q: Sorting Adjacency List Children Alphabetically If I have an adjacency list sorted by id/parent_id, is there an easy way to sort all of a parent's children alphabetically by a third text field (say "name")?
I have used information provided here: http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/ to get MySQL to return the sorted adjacency list. Ideally this would allow me to sort the children by a third column, but the test data set does not include extra columns at all in that example.
My data looks like this after I query for it but it needs to be sorted by the descendants, alphabetically.
$myArr[] = array(1,0,"instruments");
$myArr[] = array(2,1,"electric");
$myArr[] = array(3,1,"acoustic");
$myArr[] = array(4,2,"guitar");
$myArr[] = array(5,2,"banjo");
$myArr[] = array(6,3,"guitar");
$myArr[] = array(5,3,"banjo");

Or:
array (
  0 =>
  array (
    0 => 1,
    1 => 0,
    2 => 'instruments',
  ),
  1 =>
  array (
    0 => 2,
    1 => 1,
    2 => 'electric',
  ),
  2 =>
  array (
    0 => 3,
    1 => 1,
    2 => 'acoustic',
  ),
  3 =>
  array (
    0 => 4,
    1 => 2,
    2 => 'guitar',
  ),
  4 =>
  array (
    0 => 5,
    1 => 2,
    2 => 'banjo',
  ),
  5 =>
  array (
    0 => 6,
    1 => 3,
    2 => 'guitar',
  ),
  6 =>
  array (
    0 => 5,
    1 => 3,
    2 => 'banjo',
  ),
)

I need this to be sorted like so:
instruments
    acoustic
        banjo
        guitar
    electric
        banjo
        guitar

Thanks!

A: I don't know what exactly you want to do given that you have no code example, but isn't it easier to do like this:
SELECT * FROM my_table ORDER BY id, parent_id, title;

that orders first by id, then by parent_id when ids are the same and for title if ids and parent_ids are the same


text:
Q: Passing array within functions - form validation & display error I have 3 functions (cut down version of what I am trying to do). It seems when the function returns the array, it only returns the last value (which is null in my case) and loses the values appended before:
    function addError($err){
      $error = array();
      if ($err != NULL){
          $error[] = $err;
     }
       return $error;
     }

    // temp function to populate addError
    function populateError(){
       for ($i = 0; $i < 20; $i++){
       addError($i);
      }
    }

    // temp function to display Errors
    function display(){
       $v = addError(NULL);
       print_r($v);
    }
   //to test the functions
    populateError();
    display();

When I call display function, it gives an empty array. I tried to print it in the function addError, just before return statement and it has the values, but when called from another function (display) only empty array is printed as I am passing NULL to the function when calling.
Not quite sure how I can achieve this, I am hoping the function will return an array with all the values appended in the cycle (one form submit). I would greatly appreciate any help/pointer. Much thanks in advance!

A: ok, so I figured out the problem. Not sure if it will help anyone, but I was redirecting the user on validation error (via header tag) and as a result the variable values were being lost. Instead of that I included the functions page after form was posted and the page was posted to self, as a result I could display the errors, highlight fields etc. I am still not convinced with this way and the code quality, but as a step one it seems to be working, now to improving it. Hopefully, someone else can also benefit from this, Thank you!


text:
Q: Stuck in tty1, unable to log in (18.04 MATE) I'm stuck in the black tty1 login screen.
I think I know why. I use MATE but wanted to try cinnamon, installed it, wasn't satisfied so I removed it again via
sudo apt remove cinnamon-desktop-environment lightdm

I guess I shouldn't have included light dm. I just replaced install with remove in the code I used to install cinnamon and didn't think it through.
The issue is that in tty1 I can't get past the login because I am not given enough time to put in my password correctly. I put my username and then it almost immediately jumps to "login incorrect" after I hit enter and try to actually put in my password.
I have already tried  Ctrl+Alt+F1 all the way through F7, but no success.
I have also tried booting with a different kernel version from the advanced options. I only have 4.15.0-45 and 4.15.0-44 available and neither worked.
Edit: this keeps getting marked as a duplicate of this post:
TTY doesn't wait for password
But like I've stated above, I have already tried using a different kernel from the advanced options menu to no avail.
The other answer requires command lines, but how can I type those before being able to log in?


text:
Q: Nasalization in IPA I am learning IPA to learn the English pronunciation.
When "n" is inserted after a vowel and it is not followed by another vowel, how to know if /n/ is pronounced or it is only a mark to nasalize the vowel?
The pronunciation of "dune" in the dictionary is /djun/, and "sun" is /sʌn/. But I listened to those words and "dune" ends with an "n" sound (the tongue moves), but "sun" does not.
The IPA does not tell the nasalized phoneme in diphthongs.
In "find" /faɪnd/, "a" is not nasalized, but "ɪ" is. In "saint" /seɪnt/, both "e" and "ɪ" are nasalized.

A: The /n/ in IPA is never a mark of nasalization of the vowel preceding it. It always means your tongue is touching the tooth ridge and air passes through the nose. Therefore it is a nasal consonant. Vowels before a nasal consonant are technically nasal through assimilation, but in English, unlike some other languages, there is no phonemic distinction between nasal and oral vowels. Therefore you should not worry about it.
Both "dune" and "sun" end with the same sound, the only difference is in the vowel. The UK english pronunciation of "dune" differs slightly from the US: /djuːn/ vs. /duːn/. The IPA for english words does not mark nasalized phonemes in diphthongs because, again, there is no phonemic distinction between nasal and oral vowels in English. Perhaps you perceive a difference in the final "n" sound because the vowel in "dune" is a long vowel? Because of assimilation, you think the "n" sound is different: the only difference is in the duration of time air passes through the nose, the position of the tongue should be (more or less) identical.
The degree of nasalization of the diphthongs in "find" and "saint" will vary from person to person, and personally I hardly nasalize them at all.

A: In a comment, John Lawler wrote:

In English, there is nasalization in vowels preceding nasal resonants; the degree varies broadly from person to person and situation to situation, since the velic and the tongue are independently innervated and articulated. As long as there's some nasalization before nasals in English, that'll pass, so it's not phonemic but predictable. Other languages work differently -- in Bahasa Melayu (Indonesian, Malay) it's the vowel following the nasal that gets nasalized, for instance. And in a language like Acehnese, there are interactions of two kinds of nasals with phonemic nasalized vowels.


text:
Q: During compilation in Visual Studio (C) i cant get a correct debug #include <stdio.h>

int main (void)
{
    int a;
    a = 4;
    printf("a = %d \n");
    return 0;
}

and that is what i get when debug:
a = 1220497792 or other big numbers.

A: You are not passing anything to you're printf call so it is printing garbage.
To fix you need to pass a as a second argument to printf.
#include <stdio.h>

int main (void)
{
    int a;
    a = 4;
    printf("a = %d \n", a);
    return 0;
}


text:
Q: XSS Security using AntiSamy in Spring MVC I want to filter the contents of all input tags from my HTML. I am using the AntiSamy filter, as of now my filter is filtering out complete html content (instead of input value only).
I am using the implementation provided here:
Github
Inside the doFilter method i am using this piece of code to scan the content
HttpServletResponseInvocationHandler invocationHandler = httpResponseInvocationHandlerFactory.build((HttpServletResponse) response);

CleanResults cleanResults = antiSamy.scan(invocationHandler.getContents(), policy);

whereas what i want is about:
CleanResults cleanResults = antiSamy.scan(request.getParameter("input"), policy);

So that only the content of input field is filtered.
here is the whole doFilter Method:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (response instanceof HttpServletResponse) {
        HttpServletResponseInvocationHandler invocationHandler = httpResponseInvocationHandlerFactory.build((HttpServletResponse) response);
        HttpServletResponse proxiedResponse = httpResponseProxyFactory.build(invocationHandler);
        chain.doFilter(request, proxiedResponse);

        if ("text/html;charset=UTF-8".equals(proxiedResponse.getContentType())) {
            try {
                Policy policy = policyFileLoader.load(policyFile);
                antiSamy.setInputEncoding(inputEncoding);
                antiSamy.setOutputEncoding(outputEncoding);

                CleanResults cleanResults = antiSamy.scan(invocationHandler.getContents(), policy);
                log.info("Number of Errors: " + cleanResults.getNumberOfErrors());
                if (log.isDebugEnabled()) {
                    log.debug("Errors found: ");
                    List errors = cleanResults.getErrorMessages();
                    for (int i = 0; i < errors.size(); i++) {
                        log.debug("\t" + (i + 1) + ". " + errors.get(i));
                    }
                }
                log.info("Scan time (in seconds): " + cleanResults.getScanTime());
                response.getOutputStream().write(cleanResults.getCleanHTML().getBytes());
            } catch (ScanException e) {
                log.error(GENERIC_ERROR, e);
            } catch (PolicyException e) {
                log.error(GENERIC_ERROR, e);
            }
        } else {

            response.getOutputStream().write(invocationHandler.getBytes());
        }
    } else {
        chain.doFilter(request, response);
    }
}

I have tried it on ALL policy files provided by AntiSamy as default.
It'd be great if can get some help on this.

A: Found the solution, the error was with the incorrect regular expression. Works well now.


text:
Q: jcombobox not loading values from an array jComboBox1.setModel(customers);

public class CustomerData {

private static final String JDBC_CONNECTION_URL = "jdbc:mysql://localhost/test";
private static final String DATABASE_USER       = "root";
private static final String DATABASE_PASSWORD   = "root";

// query to select customer data
private static final String SQL_FETCH_CUSTOMERS = "SELECT custName FROM customers";
private Connection connection = null;

public CustomerData(){
    initConnection();
}

private void initConnection() {
    try {
        //load the mysql driver
        Class.forName("com.mysql.jdbc.Driver");
        //create the database connection
        connection = DriverManager.getConnection(JDBC_CONNECTION_URL, DATABASE_USER, DATABASE_PASSWORD);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

public void closeConnection(){
    if (connection != null) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connection = null;
        }
    }
}

public ArrayList fetchCustomerData(){
    if (connection != null){
        Statement statement = null;
        try {
            statement = connection.createStatement();
            //get results from database
            ResultSet resultSet = statement.executeQuery(SQL_FETCH_CUSTOMERS);
            //get customers from resultset and return them to the app
            return convertResultSetToCustomersArray(resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //close the statement we just used
            if (statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }else{
        System.out.println("NO VALID DATABASE CONNECTION, CAN'T FETCH CUSTOMER DATA!");
    }
    return new ArrayList();
}

private ArrayList convertResultSetToCustomersArray(ResultSet results) throws SQLException{
    ArrayList customers = new ArrayList();

    //loop the results and add customers to an ArrayList
    while (results.next()){
        customers.add(results.getString("custName"));
    }
    return customers;
}
    private String[] customers = null;
    private void initData(){
    CustomerData customerData = new CustomerData();

    ArrayList custArrayList = customerData.fetchCustomerData();

    //get the array from the ArrayList and cast it to a String[]
    customers = (String[]) custArrayList.toArray(new String[0]);
}

}

A: From what I can gather from your code, you are trying to set a String[] as the model for your JComboBox.  This wont work.  you can wrap that array in a DefaultComboBoxModel like so:
jComboBox1.setModel(new DefaultComboBoxModel(customers));

A: Things to check:

*

*Is the query actually returning anything?

*The line jComboBox1.setModel(customers); where is it actually in your code? And how is customers being created? Maybe you need to post that part of the code.

*What type is the customers object that you are passing to the setmodel method?


text:
Q: bashrc function to create a folder every month and switch XDG_DESKTOP_DIR to it I am actively using desktop, so files and folders rapidly accumulate on desktop.
I need a bashrc way that it checks month on the first day then creates a directory with month name, finally sets it desktop.

A: *

*you can set up a cronjob, that runs a script of your daily: man crontab

*in the script you:

*

*create a folder for the last month on your desktop: man mkdir and How do I assign last month's date (year and month only - 2016-07) as a variable?

*you run a find that finds all files that are older than one month. Here's an example of a find that deletes (rm) older files -
you'll need to adapt it to mv older files into the created directory: Delete files older than X days +

A: First manually change the config by yourself for this month and run this for the next month.
change_desktop()
{
month=$(date +%B)
last_month=$(date '+%B' --date '1 month ago')
mkdir /home/$USER/Desktop/$month
sed -i "s|Desktop/$last_month|Desktop/$month|" ~/.config/user-dirs.dirs
}

This will create the current month's folder in Desktop and then look for the last month in the config and change it to the current month.
I don't know how to run this piece automatically using the ~/.bashrc, but you can setup a cron job for the user and let it run every month. Just add this code snippet to a file called change_desktop.sh add the following code :
#!/bin/sh
change_desktop()
{
month=$(date +%B)
last_month=$(date '+%B' --date '1 month ago')
mkdir /home/$USER/Desktop/$month
sed -i "s|Desktop/$last_month|Desktop/$month|" ~/.config/user-dirs.dirs
}
change_desktop

Then create a cron job for the current user like this :
0 0 12 * * sh /home/$USER/change_desktop.sh

If however you want to do this manually, you can add the first code snippet to the ~/.bashrc and run change_desktop in your terminal and it will do the job for you, as it is already a function in your ~/.bashrc.

A: I have managed to concoct my own script.
new_desktop="$HOME/Desktop/$(LC_ALL=tr_TR.utf8 date +'%B-%Y')"
if [ ! -d "$new_desktop" ]; then
   mkdir "$new_desktop"
   xdg-user-dirs-update --set DESKTOP "$new_desktop"
   nautilus -q
fi

But I doubt about how reliable it is.


text:
Q: PDO insert a differnet int value I'm inserting on a database with PDO but the inserted integer value is different than the expected
  $insert = $con->prepare("INSERT INTO usuarios(id,username,token)
        VALUES (:id,:username,:token)");
        echo $inst->getUser_Id();//here shows the correct value
      $insert->bindparam(':id',$inst->getUser_Id(),PDO::PARAM_INT);
      $insert->bindparam(':username',$inst->getUsername());
      $insert->bindparam(':token',$inst->getToken());
      $insert->execute();
      echo $inst->getUser_Id();//here shows the correct value too

When I check the inserted data ,the field id is different than echo $inst->getUser_Id()

A: The issue is that the id field is declared as signed integer, which has a maximum value of 2147483647. Since you try to insert a bigger value than the max and apparently the strict sql mode is turned off, mysql rounds the data down to the maximum. In the int(20) declaration the 20 does not influence the maximum value the field can hold. Change the datatype to bigint or unsigned int and you will be fine.


text:
Q: How to use both/either in negative sentences? I recently saw this sentence,
"the system has not been yet used in both large and small cities".
I wonder if both can be used in negative sentences like this? If not, how can "either" be used in such a sentence where two names are mentioned afterwards? we cannot say EITHER large And small cities. also both refers to positive sentences.
Thank you in advance

A: Replacing "both" with "either" would change the meaning of the sentence. If a system has not been used in both large and small cities, then it may have been used in one or the other, just not in both. If a system has not been used in either large or small cities, then it has been used in neither. In the latter case, one might opt for a "neither/nor" construction.


text:
Q: How can i change the timezone in eclipse console view without changing sistem time? I want the messages logged to console use a different timezone than my normal system time. Can it by done from eclipse?
PS it says on the site that you do not have to register  to post question but it is not true apparently


text:
Q: Mean a grid to decrease resolution of a Netcdf I have a very large dataset ('Tree cover') at a very high resolution of about 250m (specifications below). I want to convert this dataset to 0.25-degree resolution in python.
####Specification of the dataset
<xarray.DataArray 'Percent_Tree_Cover' (lat: 43575, lon: 70875)>
[3088378125 values with dtype=float32]
Coordinates:
    time     object 2001-03-06 00:00:00
  * lat      (lat) float64 -50.0 -50.0 -49.99 -49.99 ... 40.77 40.78 40.78 40.78
  * lon      (lon) float64 -88.45 -88.45 -88.45 -88.45 ... 59.19 59.2 59.2 59.2
Attributes:
    grid_mapping:  crs
    valid_min:     0
    valid_max:     100
    long_name:     Percent_Tree_Cover

What I want is to mean every Treecover pixel in that falls in a 0.25-degree grid (something like the figure below). I want to mean high-resolution layer in the respective grid of lower resolution pixel. For the figure below, one green pixel covers 9 white pixels, as I am assuming that the pixel's in both the layers have a non-decimal ratio or are perfectly aligned [The blue window on the high-resolution pixel defines the odd pair].

For this, I have come up with a code (mentioned below and works fine):
TC = xr.open_dataset('MOD44B.006_250m_aid0001.nc').Percent_Tree_Cover[0]
TC = TC.sel(lat = slice(50,-50))
TC = TC[::-1]
TC

## For 0.25 resolution
lon = np.arange(-179.875,180,0.25);
lat = np.arange(-89.875,90,0.25);

TC_nan = TC.where(TC != 200) #For removing 200 as NaN

TC_reshaped_nanmean = np.zeros((720,1440))

for y in tqdm(range(lat.shape[0]-1)):
    for x in range(lon.shape[0]-1):
        TC_reshaped_nanmean[y,x] = np.nanmean(TC_nan.sel(lat = slice(lat[y],lat[y+1]), lon = slice(lon[x],lon[x+1])).values)
        #print(lat[y],lat[y+1],lon[x],lon[x+1])

np.save('TC_nanmean_2001.npy', TC_reshaped_nanmean)

The above code takes about 1.5 hours to complete.
Do provide your suggestions about the credibility and how to reduce the time of the code.


text:
Q: Initial condition trouble with NDSolve for a 2nd order PDE In general, when solving a 2nd order PDE (such as the wave equation below) for $$u(x,t), \quad x \in(-\infty,\infty), \: t\in (0,\infty)$$ it should be sufficient to provide initial conditions $u(x,0)$ and $\partial_t u(x,0)$. However when I try solve this numerically in Mathematica
NDSolve[{D[u[x, t], {t, 2}] == D[u[x, t], {x, 2}],
u[x, 0] == E^(-x^2), Derivative[0, 1][u][x, 0] == 1}, u, {x, -7, 7}, {t, 0, 4}]

I get the error
NDSolve::bcart: Warning: an insufficient number of boundary conditions
have been specified for the direction of independent variable x.
Artificial boundary effects may be present in the solution.

The only thing I can think of is that when solving numerically I have introduced fictitious new boundaries to the problem by simply specifying a finite range {x,-7,7}. If this is the problem, how do I get around it?
(NB the real PDE I'm trying to solve is more complicated and does not describe localized waves).
Also, oddly, if I take out the second I.C.
Derivative[0, 1][u][x, 0] == 1

It doesn't complain but it seems to invent its own boundary conditions and gives the wrong solution.
Edit: the actual PDE I'm solving is of the form
$$
-\partial_t^2\phi +   \sqrt{\frac{2M}{r}} \left( \frac{3}{2r}\partial_t\phi  + 2\partial_t \partial_r \phi \right) +    \frac{1}{r^2} \partial_r \left[ r (r-2M)\partial_t \phi\right] -m^2\phi =0,$$
with the initial conditions $\phi(r>>1, t) = 10 - t^{1/3} $ and \partial_r\phi(r>>1,t) = 0$. Any tips regarding the best way to get around the issues above in this case would be amazing.


text:
Q: Accessing a method in a Singleton instance from multiple threads I use Ninject as my IOC.  I have two classes as shown below.
Customer:
public class Customer:ICustomer
{
   private ICustomerRepository _CustRepo;
   public Customer(ICustomerRepository custRepo){
     _CustRepo = custRepo;
   }

   public void CustomerOperations(int custId){

     var cust = _CustRepo.GetCustomer(custId);

     //Do something with the cust object

     if(condition1)
      _CustRepo.Update(cust);
     if(condition2)
      _CustRepo.Delete(cust.id);
     if(condition3)
      _CustRepo.Insert(cust);
   }
}

Repository:
public class CustomerRepository:ICustomerRepository {

   private IDataAccessLayer _Dal;

   //Ctor details skipped

   public Customer GetCustomer(int custId) {//Get customer from DB}
   public bool Update(Customer c) {//Update}
   public bool Delete(int custID) {//Delete}
   public bool Insert(Customer c) {//Insert}
}

Bindings:
     Bind<ICustomer>().To<Customer>().InThreadScope();
     Bind<ICustomerRepository>().To<CustomerRepository>().InSingletonScope();

Let's assume the scope can't be changed.  I am trying to sync the calls so thread1 doesn't delete the customer while thread2 is getting ready to update the same customer.
If locking is the recommended approach, how do I make sure the repository methods are thread safe. Thanks

A: This is a concurrency problem that locking can't solve.
Consider the following:
Client A requests the deletion of the customer before client B can make the call to delete it.  In this scenario the following occurs:

*

*Client A acquires the lock on the customer/repository

*Client B requests the lock, but has to wait until the lock is released by Client A

*Client A successfully delete the customer

*Client A releases the lock

*Client B acquires the lock

*Client B's request to update the customer fails because the customer has been deleted.

Look into the concurrency control mechanisms of your underlying data store.
If you are using SQL Server + EF, take a look at this article.

A: As MattTannahill says, this is a concurrency problem.
The only way to accomplish what you want to accomplish is to defer the execution of the actual point of no return (update/delete), and do the proper book keeping prior to that to provide enough information to perform the right sequence or sequences of operation(s)... You will, for lack of a better explanation, remove concurrency from the equation of record manipulation.
So basically, you'd have a "transaction log/trail" of sorts associated with the record, and the actual operations on the record do not occur until a later moment when it's safe to do so. In the meantime, a record is stored in a state of "to be updated".
Of course, this opens up other things you need to resolve, and it can get unmanageable very quickly:

*

*How do you display an updated/deleted record that hasn't had the operation(s) performed on it yet.

*What transaction has final say?  What you're implying here is that updates should cancel out a concurrent delete.  Which you could do if you wait to perform all of the operations and analyze the transaction trail.  The rules to this kind of thing can get very complex over time because you essentially have to "mark a record for an operation" from a client interaction point of view, and then a process job to later to actually analyze and perform the operation.

*If a delete is "cancelled" by an update, since the operation occurs later, there's no immediate way of letting the user know it didn't delete. You'd have to figure out a way to let that user know.

*You'll need to define the "safe" time to perform these modifications.  Do you do it 30 seconds after no activity on the record?  Are there certain modifications that always take precedence?


text:
Q: Kernel density estimation with FFT for a univariate non-parametric regression The non-parametric regression model to be estimated looks like the following
x_t = b(x_t-1) + epsilon_t

Forfinding the optimal bandwith h in the kernel regression a cross-validation method (leave a point out and estimate it with the rest of the sample) is used and evaluated via the expected prediction error (EPE). This takes a while since the kernel has to be calculated each time for a range of potential h-values and every sample without x_i.
Therefore the use of FFT (Paper: link and similar post: link) can speed up the calculations. In my understanding the following is the way to go:

*

*Discretize the data (x_t-1 values) by using linear binning

*Take the Fourier-transform of the binned data

*Multiply the transformed binned data with the Fourier-Transform of the Gaussian-kernel

*Inverse-transform the product back to get the kernel estimation

But I fail to understand how implement this since once the data is binned (I assume here x_t-1) the connenction to the y-values of the kernel regression (here x_t) is broken?

A: In case anyone else is also watching:
A nice explanation is given by Ichimura and Todd (2007) in their handbook chapter, "Implementing Nonparametric and Semiparametric Estimators," chapter 8.
Basically, when you "bin" your data, you are chopping the x range up into intervals, $[t_k; t_{k+1}]$. For each such interval, you construct one new y value which averages among the observations that fall in the bin. But there's a particular weighting scheme which needs to be followed, including the distance of the bins, which I believe has to be uniform (so that $t_{k+1} - t_k = \delta$ for all $k$). So I encourage you to check out the paper.


text:
Q: Obtener IP privada del cliente ¿Existe alguna manera de obtener la dirección IP privada del cliente desde el servidor o pasársela de algún modo sin que se oculte?
Actualmente lo realizo de la siguiente manera:

var ipPrivada = "";
function obtenerIPJS(variable) {

  // NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
  var RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

  if (RTCPeerConnection) (function () {
      var rtc = new RTCPeerConnection({iceServers:[]});
      if (1 || window.mozRTCPeerConnection) {      // FF [and now Chrome!] needs a channel/stream to proceed
          rtc.createDataChannel('', {reliable:false});
      };

      rtc.onicecandidate = function (evt) {
          // convert the candidate to SDP so we can run it through our general parser
          // see https://twitter.com/lancestout/status/525796175425720320 for details
          if (evt.candidate) grepSDP("a="+evt.candidate.candidate, variable);
      };
      rtc.createOffer(function (offerDesc) {
          grepSDP(offerDesc.sdp, variable);
          rtc.setLocalDescription(offerDesc);
      }, function (e) { console.warn("offer failed", e); });

      function updateDisplay(newAddr, variable) {
       var varConEval = eval(variable);
       if (varConEval != "") varConEval = varConEval+",";
       varConEval = varConEval+newAddr;
       eval(variable+" = varConEval");
      }

      function grepSDP(sdp, variable) {
          var hosts = [];
          sdp.split('\r\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39
              if (~line.indexOf("a=candidate")) {     // http://tools.ietf.org/html/rfc4566#section-5.13
                  var parts = line.split(' '),        // http://tools.ietf.org/html/rfc5245#section-15.1
                      addr = parts[4],
                      type = parts[7];
                  if (type === 'host') updateDisplay(addr, variable);
              } else if (~line.indexOf("c=")) {       // http://tools.ietf.org/html/rfc4566#section-5.7
                  var parts = line.split(' '),
                      addr = parts[2];
                  updateDisplay(addr, variable);
              }
          });
            console.log("varIP"+eval(variable));
      }
  })(); else {
  }
 }

obtenerIPJS("ipPrivada");

El problema es que esto funcionaba antes con otra versión de firefox/chrome (No se con cual). Ahora estos navegadores por defecto ocultan la IP local privada.
Y la saca con un formato de este estilo : ej1k-18fa-loquesea.local
Esta opción de ocultar la IP es algo que se puede cambiar con la variable #enable-webrtc-hide-local-ips-with-mdns del navegador, pero no es una opción.
Lo ideal es que el usuario no tenga que modificar nada en el navegador.
La IP se envía al servidor para comprobar si esta en la lista de IPs validas para realizar esa acción, por lo que la pregunta sería la del inicio:

¿Existe alguna manera de obtener la dirección IP privada del cliente
  desde el servidor o pasársela de algún modo sin que se oculte?

Relacionado pero outdated: Como obtener la IP o nombre del equipo con JavaScript

A: No, no se puede.
Históricamente no se ha podido nunca, sencillamente es un dato privado que no necesitabas saber.
Cuando se añadió el protocolo WebRTC se permitió obtener esa información en las primeras versiones del estándar... hasta que decidieron que era un problema de seguridad que debía evitarse y en las versiones actuales se pide que se oculte de nuevo.


text:
Q: Internal categories in an endofunctor category Here we see the definition of an internal category in a monoidal category.  We also know that endofunctor categories support a monoidal product which is actually functor composition.  It is the case that a monoid in an endofunctor category is a monad, and so it makes sense that a comonoid is a comonad.  We could take the route that an internal category here is a monad on the category of internal comonoids.  It also looks to me like, if there is a comonad that is also a monad, we are done, we have an internal category.  Does this make sense? Is it the case that if we have Frobenius monads (a monad that can be turned into a comonad) these are the internal categories?

A: It seems that there was a bit of truth to this question.  Here we see Spivak defining Categories as comonoids in the monoidal category $(Poly, \circ, y)$, section 2.5.  As I point out, comonoids in an endofunctor category are comonads.  I would guess that if you add a monad structure to your comonoids, you still have a category, but you have extra structure.  It would be interesting to know what extra stuff you are endowing the category with if you add monad structure.


text:
Q: Timetabling in prolog I am trying to make a timetable in Prolog, where there are 10 teachers, 5 classes and 3 groups of students. Each teacher must teach all 5 classes in a week, and one group at a time with at least 2 hours break
%% professors/10
professors([coe,chr,dan,dar,ell,elv,frank,franc,ric,rac]).

%% classes/5
classes(c1,c2,c3,c4,c5).

%%classrooms/3
seat(10,30,70).

%%daysoftheweek/5
day(monday,tuesday,wednesday,thursday,friday).


text:
Q: PHP values inside an arrays in a PHP file are displaying an error when that file is called via Ajax! I call a php file in the following way using Fancybox
index.php:

inside showcase/showcase1.php I have the following code:
<?php include_once '../localization.php'; ?>

    <?php echo l('inline_p'); ?>
    <?php echo l('inline_a'); ?>

which calls values inside an array from a language file (lang.en.php):
'inline_p' => '
Previous = Left Arrow Key

Next = Right Arrow Key

Close = Esc
',
'inline_a' => 'Visit',

helped by a "controller" (localization.php):
<?php
session_start();
header('Cache-control: private'); // IE 6 FIX

if(isSet($_GET['lang'])) {
    $lang = $_GET['lang'];

    // register the session and set the cookie
    $_SESSION['lang'] = $lang;
    setcookie("lang", $lang, time() + (3600 * 24 * 30));
}
else if(isSet($_SESSION['lang'])) {
    $lang = $_SESSION['lang'];
}
else if(isSet($_COOKIE['lang'])) {
    $lang = $_COOKIE['lang'];
}
else {
    $lang = 'en';
}

// use appropiate lang.xx.php file according to the value of the $lang
switch ($lang) {
case 'en':
    $lang_file = 'lang.en.php';
    break;

case 'es':
    $lang_file = 'lang.es.php';
    break;

case 'zh-tw':
    $lang_file = 'lang.zh-tw.php';
    break;

case 'zh-cn':
    $lang_file = 'lang.zh-cn.php';
    break;

default:
    $lang_file = 'lang.en.php';
}

//translation helper function
function l($localization) {
    global $lang;
    return $lang[$localization];
}

    include_once 'languages/'.$lang_file;
?>

The array displays the values in the language files perfectly if I directly open showcase/showcase1.php, but when it is called from the anchor link using fancybox it says:

Fatal error: Call to undefined
  function l() in
  D:\wamp\www\projects\alexchen\alexchen2.6\showcase\showcase1.php
  on line 3

Any suggestions?
EDIT:
l is an array in the languages files but i use it as a function later (see at the end of localization.php).

A: You should be using require_once do these calls. I would hazard that it is not finding localisation.php.
Include will only warn if a file is not present, whereas a require will fatal error. If the program won't work correctly without it, always use require over include.
Is the AJAX version being called from a different path, relatively speaking?

A: I found out the problem. When localization.php and langauages/lang.en.php are being called in showcase/showcase1.php the PHP code can't file those files. I placed all the showcase files in the root directory and now everything works. Thanks for the responses they helped me figure out the way!

A: I don't know for sure, but the first thing I'd try would be to copy all the code from localization.php inside showcase1.php. If in that way the AJAX call works, then you could be sure there's a problem with the way fancybox calls the php. Then I'd use the Firebug or live http headers Firefox extensions to check how the showcase1.php is called.

A: Add an error_reporting(E_ALL); in there.  I suspect you're getting another error when trying to include localization.php, and for some reason it isn't showing up.  You may also have to enable display_errors in php.ini, or with ini_set().
Use a tool to figure out what is different between calling your script directly, and calling it with AJAX.  I recommend Fiddler.


text:
Q: I want to get the size of file i select in MBs from internal storage of my phone. but file.length() always returns 0 I am able to select a pdf type file from the internal storage of my phone. I want to get the size of a file in MBs and to put limit on file select based on its size. But following code always returns 0 although the file has been successfully selected.
String uriString = PostFileUri.toString();
File myFile = new File(uriString);
// Get length of file in bytes
long fileSizeInBytes = myFile.length();
// Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
long fileSizeInKB = fileSizeInBytes / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
long fileSizeInMB = fileSizeInKB / 1024;
Log.i("FileSize", String.valueOf(fileSizeInMB));

A: Probably, you've got a 0, because you didn't get an existing file. Try this
    File rootStorage = Environment.getExternalStorageDirectory();
    File myFile = new File(rootStorage.toString() + "/download/q1.jpeg");//or whatever
    long fileSizeInBytes =  myFile.length();
    // Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
    long fileSizeInKB = fileSizeInBytes / 1024;
    // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
    long fileSizeInMB = fileSizeInKB / 1024;
    Log.i("FileSize",String.valueOf(fileSizeInMB));


text:
Q: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) python request I am getting error, when I am trying to run my program with the API. Like that
Traceback (most recent call last):
  File "/Users/hanson/Desktop/LEARNING/Python/model-test/simple-keras-rest-api-master/simple_request.py", line 17, in <module>
    r = requests.post(KERAS_REST_API_URL, files=payload).json()
  File "/Users/hanson/ICP6/lib/python3.6/site-packages/requests/models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Here is my source code of the pyfile
import requests

# initialize the Keras REST API endpoint URL along with the input
# image path
KERAS_REST_API_URL = "http://localhost:5000/predict"
IMAGE_PATH = "/Users/hanson/Desktop/LEARNING/Python/model-test/simple-keras-rest-api-master/dog.jpg"

# load the input image and construct the payload for the request
image = open(IMAGE_PATH, "rb").read()
payload = {"image": image}

# submit the request
r = requests.post(KERAS_REST_API_URL, files=payload).json()

# ensure the request was sucessful
if r["success"]:
    # loop over the predictions and display them
    for (i, result) in enumerate(r["predictions"]):
        print("{}. {}: {:.4f}".format(i + 1, result["label"],
            result["probability"]))

# otherwise, the request failed
else:
    print("Request failed")

The API as requested should be something like that

*

*beagle: 0.9901

*Walker_hound: 0.0024

*pot: 0.0014

*Brittany_spaniel: 0.0013

*bluetick: 0.0011


text:
Q: Lightning Clickable URL in Data Table I am trying to make the 'Name' field clickable in a community and having some trouble getting it point to a url.
I am following this thread:
Hyperlink record name LWC datatable
It seems like the updated solution does not require a wrapper class here so I thought it would be easy to implement. I am sure I am missing something on my end. It does not seem like I am getting anything in the row.id.
Here's the code:
import { LightningElement, wire, track, api } from 'lwc';
import StatementOfValuesDataFeed from '@salesforce/apex/StatementOfValuesDataFeed.getOldAssetValues';
import { updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import { showToastEvent } from 'lightning/platformShowToastEvent';
import getOldAssetValues from '@salesforce/apex/StatementOfValuesDataFeed.getOldAssetValues';

const COLS = [
    {label: 'Asset Value', fieldName:'nameUrl', editable: false, sortable: true, type: 'url', typeAttributes: {label: { fieldName:'Name', target: '_blank'}}},
    {label: 'Asset Name', fieldName:'Asset_Name__c', editable: false, sortable: true},
    {label: 'Asset Type', fieldName:'Asset_Type__c', editable: false, sortable: true},
    {label: 'Agency Owner Name', fieldName:'Agency_Owner__c', editable: false, sortable: true},
    {label: 'Owner Type', fieldName:'Agency_Owner_Type__c', editable: false, sortable: true},
    {label: 'Premium Net', fieldName:'Net_Premium_Number__c', editable: false, sortable: true},
    {label: 'Invoice Amount', fieldName:'Invoice_AV__c', editable: false, sortable: true},
    {label: 'System Id', fieldName:'Asset_System_ID__c', editable: false, sortable: true},
];

export default class StatementOfValuesAssetTable extends LightningElement {

    @track error;
    @track columns = COLS;
    @track oldAssets = [];

    @wire(getOldAssetValues)

    wiredAssets(result) {
        const { data, error } = result;
        if (data) {
            let nameUrl;
            this.oldAssets = data.map(row => {
                nameUrl = `/${row.id}`;
                return {...row , nameUrl}
            })
            this.error = null;
        }
        if(error) {
            this.error = error;
            this.oldAssets = [];
        }
    }
}

and
<template>
    <lightning-card title = "SOVAssetTable" icon-name="custom:custom63">

        <div class="slds-m-around_medium">
            <template if:true={oldAssets}>
                <lightning-datatable
                    key-field="Id"
                    data={oldAssets}
                    columns={columns}
                    draft-values={draftValues}
                    hide-checkbox-column="true">
                </lightning-datatable>
            </template>
            <template if:true={oldAssets.error}>
                <!--- error handling save-->
            </template>
        </div>
    </lightning-card>
</template>

Any help on how to get my row.id into the url would be superb.
Thanks,
B


text:
Q: Background of the Image created from Bitmap I am trying to create a signature component where the user can write his signature on the view and the resulting bitmap being saved as an image. I am able to achieve this successfully.
But my issue is that the background color is of the image being saved is always transparent. In my onDraw method i do the following:
@Override
protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.GREEN);
    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mPath, mPaint);
}

and while writing to the file system i do the following:
fOut = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.PNG,100, fOut);
fOut.flush();
fOut.close();

The view on the device while capturing the signature is as shown in the image below:

After the bitmap is written to the file system the image is as below:

Could some one kindly help me with this. I would like me image to have the same background as the canvas.
Thanks in advance.

A: From your question it seems like you want to save the entire view as a bitmap instead of the path object. To do this you can simply save the DrawingCache of the view as a Bitmap.
myView.buildDrawingCache()
Bitmapt b = myView.getDrawingCache()
fOut = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.PNG,100, fOut);
fOut.flush();
fOut.close();


text:
Q: What is the difference between aar and war file? I don't know what are aar archive files and how they differ from war. I read that they are somewhat convertible. When to use which one? What are pros and cons and limitations.

A: A .war is a web archive that you can deploy to any Java EE application server.
A .aar is a specific axis2 artifact that you can deploy in an application server where you have Axis2 standard web application deployed already.
You can still deploy an Axis2 application, including multiple services, in a standard web application, using the 'embedded' mode, as described here: http://wso2.com/library/90. Converting from .aar mode to embedded mode consists of extracting all files and carefully putting them in the right place for the embedded mode.
Pro's for the .aar is the hot deployment as @renat-gilmanov answered.
Pro's for the .war (embedded) is

*

*easier to deploy and manage in a production environment: just deploy one .war on any application server instead of having to follow a complex deployment procedure.

*you can include more servlets in the same .war, such as e.g. the client application.

A: Axis Archive (.aar)

Axis 2 services are packaged as Axis Archive (.aar). This is a JAR
  file (created using jar or zip utilities) with the services.xml file
  packaged in META-INF dir of the archive.

Example,The StockQuoteService when packaged as StockQuoteService.aar will have the following structures:
./stock/StockQuoteService.class
./META-INF/services.xml

Deployment of the service in Axis2 is quite simple; just copy the .aar
  file to the axis2/WEB-INF/services directory in the axis2 Web
  application in your servlet container. In case of Tomcat, it will be
  $TOMCAT_HOME/webapps/axis2/WEB-INF/services.

Rationale
Service is quite a small piece of software. Please think about the following:

*

*service life-cycle, because you need to deploy/redeploy/undeploy a service or services you are developing

*container overhead related to every single deployed application

*overhead caused by several Axis2 instances deployed in parallel

*loosely coupled architecture

*...

Basically, Axis2 suggests to treat *.aar as a lightweight application. It shares same Axis2 instance, can be easily managed and redeployed without stopping the whole business.
Let's imagine you develop a complex system. As a good developer and architect you decided to build loosely coupled system using services as a smallest piece of functionality. Decomposition went well, so you have ~100 services. Which is, by the way, good, because you will be able to:

*

*simplify the development

*develop some services in parallel

*simplify testing

*...

The question is will you prefer to develop all these services as a separate applications (wars)? I hope you won't. It will be much easier and more efficient to use such a lightweight approach as Axis Archives.
Please note, Axis allows you do manage service life-cycle as Tomcat does for application.

Availability is a big concern when it comes to enterprise-level
  applications. Even a short amount of downtime can be highly
  detrimental, so restarting a server is not a good option. You need to
  update your system without shutting it down. This is where hot
  deployment and hot update come in.
Hot deployment is the capability of deploying new services while the
  system is up and running. As an example, let's say that you have two
  services -- service1 and service2 -- up and running, and you deploy a
  new service called service3 without shutting down the system.
  Deploying service3 is a hot deployment scenario.
Hot update is the ability to make changes to an existing web service
  without shutting down the system. This is an important feature and
  required in a testing environment.

The Axis2 Deployment model, Part 1: Six ways the Axis2 deployment model is more user friendly


text:
Q: When to close MySQL connection discord.py I want to make a discord bot that saves data to a MySQL Database (currently localhost) but the problem is I don't know when to close the database connection.
Currently, when the user enters the command it always creates a new connection to the database but as you can imagine it's very slow to always connect then execute the query then close the connection, and finally after then returning the data.
Here is an example:

def open_case(case_id):
        search_query = f"SELECT `CASE_ID`, `USER_ID`, `LINK_REASON`, `LINK_SCREENSHOT` FROM `Report` WHERE CASE_ID ='{case_id}'"`

        mydb = mysql.connector.connect(
            host = "localhost",
            database = "report",
            password = "root",
            username = "root"
        )

        cursor = mydb.cursor()
        try:
            cursor.execute(search_query)
            result = cursor.fetchall()
            mydb.close()

        return result
    except:
        return print("Error case not found")
        mydb.close()

But I'm afraid if I connect to the DB at the beginning the bot crashers or so and then I've never closed the connection to the database.
Is there a way to make it better?

A: every connection has an idle timeout, that would detect a unused open connection and close it.
But your approach is  very good and clean, as it closes the connection
A much simpler approach is to add finqallyas all try catch and ecept will run through it
Also use prepared statements, when using variabels
def open_case(case_id):
        search_query = "SELECT `CASE_ID`, `USER_ID`, `LINK_REASON`, `LINK_SCREENSHOT` FROM `Report` WHERE CASE_ID =%s"

        mydb = mysql.connector.connect(
            host = "localhost",
            database = "report",
            password = "root",
            username = "root"
        )

        cursor = mydb.cursor()
        try:
            cursor.execute(search_query,(case_id,))
            result = cursor.fetchall()
            return result
        except:
            result = print("Error case not found")
        finally:
            mydb.close()
open_case(1)


text:
Q: Hide echo output, when text file is empty I have a blog/vlog where I also share my listening habits from Spotify live.
I use a little snippet called Snip (available on Github) that fetches my Spotify stream, creates text files for my data (like track, artist, album and trackID)
Now I wanted to add a link on my webpage to the actual track I am playing using the variable $i for trackID
I've come up with this code thanks to some googling and tips/trix pages:
<?php
$myfile = fopen("Snip_TrackId.txt", "r") or die("Die!");
echo " <- Listen";
fclose($myfile);
?>

This works just fine, but when I close down Spotify or pause, the text files empty themselves and my info box turns blank AND THAT'S THE WAY IT SHOULD BE :).
B
ut...... With my code above, the link, image and text "<- Listen" is still visible and I've been trying to figure out how I can fix this but I'm stuck.
(The link is also not really working as it only points to the part without the trackID)
So now I turn to you. Can you help me with a working solution for this?
If not, I will probably just keep things as they are.

A: you can just check the filesize before reading it:
<?php
if ((int)filesize("Snip_TrackId.txt") > 0)
{
    $myfile = fopen("Snip_TrackId.txt", "r") or die("Die!");
    echo " <- Listen";
    fclose($myfile);
}

A: Before writing a link check file for emptiness for example:
$file = "Snip_TrackId.txt";
if (0 < filesize($file)) {
    $myfile = fopen("Snip_TrackId.txt", "r") or die("Die!");
    echo " <- Listen";
    fclose($myfile);
}

Or if file contains spaces - check read data:
$myfile = fopen("Snip_TrackId.txt", "r") or die("Die!");
$data = trim(fread($myfile,filesize("Snip_TrackId.txt")));
if ($data) {
    echo " <- Listen";
}
fclose($myfile);


text:
Q: Create glue string with mixture of single and double quotes I am trying to create a string using the glue package in R
which is a mixture of 'single' and "double" quotes.
As a reprex, consider the following type of SQL query
string I want to build:
CREATE TABLE fact_final_table AS
(SELECT tab1.id,
    AVG(tab2."MV") FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date - integer '7'
                                                      AND tab1.start_date::date - integer '1') AS "mv_avg_1w",
    AVG(tab2."MV") FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date - integer '14'
                                                      AND tab1.start_date::date - integer '1') AS "mv_avg_2w"
FROM (SELECT id,
             start_date,
             point
      FROM base_tab
      WHERE mpfb.start_date::date >= '01-01-2000'::date) AS tab1
LEFT JOIN ghcnd_observations AS tab2
    ON (tab2.record_dt BETWEEN (tab1.start_date::date - integer '180')
                           AND (tab1.start_date::date - integer '1')
        AND ST_DWithin(tab1.point, tab2.location, 0.5))
GROUP BY tab1.id);

As you can see it is a combination of single and double quotes,
which are important to preserve literally as written above. For
example the tab2."MV" has double quotes, and tab1.start_date::date - integer '7' AND tab1.start_date::date - integer '1' has single
quotes which need to be preserved literally.
This string also needs to be built using parameters.
I tried the following in R using glue, but couldn't get it
to work.
var1       <- "MV"
var1_lowcase <- "mv"
lag_days   <- 180
var_date   <- as.Date("2000-01-01")
var_dwithin <- 0.5

glue::glue(
"CREATE TABLE fact_final_table AS
(SELECT tab1.id,
    AVG(tab2."{var1}") FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date - integer '7'
                           AND tab1.start_date::date - integer '1') AS "{var1_lowcase}_avg_1w",
    AVG(tab2."{var1}") FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date - integer '14'
                           AND tab1.start_date::date - integer '1') AS "{var1_lowcase}_avg_2w"
    FROM (SELECT id,
          start_date,
          point
          FROM base_tab
          WHERE mpfb.start_date::date >= '{format(var_date, "%d-%m-%Y")}'::date) AS tab1
    LEFT JOIN ghcnd_observations AS tab2
    ON (tab2.record_dt BETWEEN (tab1.start_date::date - integer '{lag_days}')
        AND (tab1.start_date::date - integer '1')
        AND ST_DWithin(tab1.point, tab2.location, {var_dwithin}))
    GROUP BY tab1.id);")

This does not work unfortunately due to single/double quotes not being
escaped correctly in glue::glue(...).
Could anyone please assist here with minimal amount
of breaking of the required output string? I'm not sure if this is easily
feasible. I would appreciate any other tidy approaches e.g. using stringr as well for example, as I would like this to be %>% friendly.
I've briefly looked at glue::glue_sql but didn't know how to directly
apply it here. I'd be grateful to learn how to use it here as applicable.

A: So I looked into this in more detail since yesterday, and
it does appear that glue does have functions to make single
and double quotes explicit i.e. glue::single_quote() and
glue::double_quote().
Similar to the (helpful) response by @ronakshah, I managed
the following, which is more explicit (for code readability):
var1       <- "MV"
var1_lowcase <- "mv"
lag_days   <- 180
var_date   <- as.Date("2000-01-01")
var_dwithin <- 0.5

glue::glue(
    "CREATE TABLE fact_final_table AS
   (SELECT tab1.id,
   AVG(tab2.{glue::double_quote(var1)}) FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date - integer '7'
   AND tab1.start_date::date - integer '1') AS {glue::double_quote(glue::glue({var1_lowcase},'_avg_1w'))},
   AVG(tab2.{glue::double_quote(var1)}) FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date - integer '14'
   AND tab1.start_date::date - integer '1') AS {glue::double_quote(glue::glue({var1_lowcase},'_avg_2w'))}
   FROM (SELECT id,
         start_date,
          point
   FROM base_tab
    WHERE mpfb.start_date::date >= {glue::single_quote(format(var_date, '%d-%m-%Y'))}::date)
  AS tab1
   LEFT JOIN ghcnd_observations AS tab2
   ON (tab2.record_dt BETWEEN (tab1.start_date::date - integer '{lag_days}')
   AND (tab1.start_date::date - integer '1')
   AND ST_DWithin(tab1.point, tab2.location, {var_dwithin}))
   GROUP BY tab1.id);")

Which returns the main string I required. Hope this helps others
who had similar glue requirements.

A: Try to escape the double quotes :
glue::glue(
   "CREATE TABLE fact_final_table AS
   (SELECT tab1.id,
   AVG(tab2.\"{var1}\") FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date - integer '7'
   AND tab1.start_date::date - integer '1') AS \"{var1_lowcase}_avg_1w\",
   AVG(tab2.\"{var1}\") FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date - integer '14'
   AND tab1.start_date::date - integer '1') AS \"{var1_lowcase}_avg_2w\"
   FROM (SELECT id,
         start_date,
          point
   FROM base_tab
    WHERE mpfb.start_date::date >= '{format(var_date, \"%d-%m-%Y\")}'::date)
  AS tab1
   LEFT JOIN ghcnd_observations AS tab2
   ON (tab2.record_dt BETWEEN (tab1.start_date::date - integer '{lag_days}')
   AND (tab1.start_date::date - integer '1')
   AND ST_DWithin(tab1.point, tab2.location, {var_dwithin}))
   GROUP BY tab1.id);")

which returns :
#CREATE TABLE fact_final_table AS
#(SELECT tab1.id,
#AVG(tab2."MV") FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date #- integer '7'
#AND tab1.start_date::date - integer '1') AS "mv_avg_1w",
#AVG(tab2."MV") FILTER (WHERE tab2.record_dt BETWEEN tab1.start_date::date #- integer '14'
#AND tab1.start_date::date - integer '1') AS "mv_avg_2w"
#FROM (SELECT id,
#start_date,
#point
#FROM base_tab
#WHERE mpfb.start_date::date >= '01-01-2000'::date) AS tab1
#LEFT JOIN ghcnd_observations AS tab2
#ON (tab2.record_dt BETWEEN (tab1.start_date::date - integer '180')
#AND (tab1.start_date::date - integer '1')
#AND ST_DWithin(tab1.point, tab2.location, 0.5))
#GROUP BY tab1.id);


text:
Q: How to reset password of word press admin panel from database? Actually, I forgot password of word press admin panel , and for recovery password email is not supported.
Finally i need to reset password of admin panel from word press database , my word press instance is hosted on google cloud.
please,  any one have answer of this query.
Thanks in advance.
I tried reset password by recovering mail, and as my word press site hosted on google cloud , i tried to get password from deployment manager , but this was changed previously .


text:
Q: NotReadableException in Decoder.php line 20: Unable to read image from file (). laravel 5.3 I am trying to upload image in Laravel 5.3 but I am getting NotReadableException in Decoder.php line 20:

Unable to read image from file ().
error. Could anyone help me in it. I am using Image Intervention for
  image upload.

Below the code which i have tried :
public function update(Request $request){

        // Handle the user upload of avatar
        if($request->hasFile('avatar')){
            $avatar = $request->file('avatar');
            $filename = time() . '.' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300, 300)->save( public_path('/uploads/avatars/' . $filename ) );

            $user = Auth::user();
            $user->avatar = $filename;
            $user->save();

        }

        return view('users/profile', array('user' => Auth::user()) );

    }

A: Here's possible solution
 public function update(Request $request){

    // Handle the user upload of avatar
    if($request->hasFile('avatar')){
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();
        Image::make($avatar->path())->resize(300, 300)->save( public_path('/uploads/avatars/' . $filename ) );

        $user = Auth::user();
        $user->avatar = $filename;
        $user->save();

    }

    return view('users/profile', array('user' => Auth::user()) );

}

as Request's files are placed in temp directory you need to get path() of this file to pass it into Image::make


text:
Q: For a given Date object, capture it's value relevant to GMT timezone In my application running on Java 8, I have a Date object. The timezone for this object depends on the client's location.
At one particular point, I need to convert this Date to GMT so that it could be comparable to a value that I access from the DB.
I tried SimpleDateFormat and ZonedDateTime, but there's a pain-point. These API's provide me GMT time in String values, which is perfectly fine. However, once I parse it and assign it to a Date object, it is back to my local timezone!
For Ex:
public class TimeZoneDemo {
    public static void main(String[] args) throws ParseException {
        Date istDate = Calendar.getInstance().getTime();

        ZonedDateTime gmtTime = istDate.toInstant().atZone(ZoneId.of("GMT"));
        System.out.println(gmtTime);

        Date gmtDate = Date.from(gmtTime.toInstant());
        System.out.println(gmtDate);
    }
}

In the code above, gmtTime displays the right value relevant to the GMT timezone, but gmtDate (the Date object) prints value in the local time zone.
P.S.: My ultimate goal is to have a the GMT value in a java.sql.TimeStamp object.
How could this be achieved?
UPDATE 1:
After going through the comments & replies I understand that the Date object just holds a long value containing milliseconds.
BUT, my expectation here is that when this line is executed:
Date gmtDate = Date.from(gmtTime.toInstant());

Whatever time the object gmtTime contains, I need to capture just that time in a TimeStamp or Date object. The motive is to then be able to make comparison with a value persisted in the database. I'm passing the date as parameter to my SQL query.
Can someone pls help me understand how can this be achieved?

A: First of all Date class is part of the old outdated (no pun intended) infrastructure. If it is at all possible get rid of it and just use java.time package. But if you must work with Date then your problem with time zone is not a problem. your line System.out.println(gmtDate); only prints it with your local time zone, since the system assumes that it is the best option. But regardless of that Date holds a particular moment in time in milliseconds since January 1, 1970, 00:00:00 GMT. Class Date has methods compareTo(), after() and before() that allow you to compare 2 Dates. Also Date has method getTime() that returns you the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date. So you can compare the long values. But again, The best option is to switch to java.time package and classes Instant and ZonedDateTime (and others) have methods compareTo(), isAfter() and isBefore().

A: java.time and JDBC 4.2
The answer is in @BasilBourque's comment: use OffsetDateTime.
    PreparedStatement yourPreparedStatement = yourDatabaseConnection.prepareStatement(
            "select smth from your_table where your_time_stamp_col < ?;");
    OffsetDateTime gmtTime = OffsetDateTime.now(ZoneOffset.UTC);
    yourPreparedStatement.setObject(1, gmtTime);

This requires a JDBC 4.2 compliant JDBC driver, I think that about all of us are using that by now. Which is good because it allows us to bypass java.sql.Timestamp and the other date-time types in java.sql. They are all poorly designed and long outdated.
As others have said, neither of the outdated classes Date and Timestamp have any time zone or offset from UTC/GMT.
Some related questions

*

*Get GMT Time in Java

*SimpleDateFormat returns wrong time zone during parse

*Getting the date from a ResultSet for use with java.time classes

A: You misunderstand the semantics of date time classes. java.util.Date is a specific point in time, an instant, it has no time zone associated with it. However if you have a time zone you can ask the time zone for the time of that java.util.Date.
java.sql.TimeStamp is the equivalent of java.time.LocalDateTime. It is not an instant and has no time zone associated with it.


text:
Q: How to request a package for Ubuntu? I want to see Webcamoid in my Ubuntu. What is the process to request the package?
There are instructions how to build the stuff manually at https://github.com/hipersayanX/webcamoid/wiki/Build-and-install-the-Debian-package but that is far from good user experience.
I would be able to maintain a package if the whole packaging and testing process (including API compatibility testing) could be made from web.