text:
Q: $f''+f \ge 0$ implies $f(x)+f(x+\pi) \ge 0$ Let $f: \mathbb{R} \to \mathbb{R}$ be a function of class $C^2$ satisfying $f''(t)+f(t) \ge 0$ for all $t \in \mathbb{R}$. Show that $f(t)+f(t+\pi) \ge 0$.

What I did:
Set $f''(t)+f(t)=g(t)$. This is an LDE of order 2, and we denote this equation by (E), and the corresponding homegoneous equation by (H). and $f$ is of the form $A\cos(t)+B\sin(t)+y_0(t)$ where $y_0(t)$ is a particular solution of (E), $A,B$ are constants. The trigonometric part cancels in the evaluation of $f(t)+f(t+\pi)$, so the problem boils down to finding a $y_0(t)$ which is always nonnegative.
Well let's search for such a $y_0(t)$ using the technique of reductin of order, i.e let's set $y_0(t)=\lambda y_h(t)$ where $y_h(t)$ is a particular solution of $(H)$. All solutions of $(H)$ are sinusoidal so if this method is going to work we might as well set $y_0(t)=\lambda \sin(t)$. Substituting, we find
$\sin(t)\lambda''+2\cos(t)\lambda'=g$.
So if $\sin(t)=0$, $\lambda'=g(t)/2$. Let $I_{2k}=(2k\pi,(2k+1)\pi)$, $I_{2k+1}=((2k+1)\pi,(2k+2)\pi)$. Define $L_I=2k\pi$ if $I=I_{2k}$, $L_I=(2k+1)*\pi$ if $I=I_{2k+1}$. If $I \in \{I_{2k},I_{2k+1}\}$ we have
$(\frac{d}{dt} [\lambda'\sin(t)])/\sin^2(t)=g$ for all $t \in I$
$\lambda'\sin^2(t)=\int^t_{L_I} g(u)\sin(u)\,du+C_I$ for all $t \in I$
where $C_I$ is a constant of integration.Note that the integral is well-defined since $gsin(u)$ is continuous, and the integral is therefore itself continuous. Note that if $I=I_{2k}$, then the integrand is positive, and $\sin^2(t)$  is always positive, so if we choose $C_I$ correctly then $\lambda'$ is positive. The opposite holds if $I=I_{2k+1}$. This is good because we want $\lambda$ positive on $I_{2k}$ and negative on $I_{2k+1}$.
Now note that $\lambda'$ is continuous on all the $I$'s. However if we impose that $\lambda'$ be continuous on $\mathbb{R}$ then we run into a problem because
$\lim_{t \to L_I, t>L_I}RHS=C_I$, which must be equal to $\lambda'(L_I)\sin^2(L_I)=0$, for all $I$. But then
$\lim_{t \to L_I, t<L_I}RHS=\int^{L_I}_{L_I'} g(u)\sin(u)\,du=0$, where $I'$ is the interval that precedes $I$. Of course in general $g$ doesn't have to satisfy this.
So this method kind of breaks down when we consider continuity but I believe it gives a function $f$ which is continuous and differentiable everywhere (and nonnegative, if we choose $C_I=0$) except for the points $L_I$.
Edit: Can you please tell me whether my method could work, or is the only possible solution the magical invaraint one given by achille?

A: Method 1 - unmotivated magic.
For any fixed $x$, we have
$$\frac{d}{dt}\left[\sin(t-x)f'(t) - \cos(t-x)f(t)\right] = \sin(t-x)(f''(t) + f(t))$$
Integrate both sides for $t$ over $[x,x+\pi]$, one find
$$
f(x)+f(x+\pi)
= \left[\sin(t-x)f'(t) - \cos(t-x)f(t)\right]_x^{x+\pi}\\
= \int_x^{x+\pi}\sin(t-x)(f''(t) + f(t)) dt
\ge 0
$$
because both factors in the integrand: $\sin(t-x)$ and $f''(t) + f(t)$ are non-negative over $[x,x+\pi]$.

Method 2 - a slightly more constructive approach.
Since OP complains about method 1 is too unmotivated, following is an alternate
approach which is more constructive. The basic idea is let $f'' + f = g$
and attempt to express $f$ in terms of $g$.
For simplicity of presentation, we will assume $x = 0$.
Notice LHS of $f''(t) + f(t) = g(t)$ can be rewritten as
$$\left(\frac{d}{dt} + i\right)\left(\frac{d}{dt} -i\right)f(t)
= \left(e^{-it} \frac{d}{dt} e^{it}\right)\left(e^{it} \frac{d}{dt} e^{-it}\right)f(t)
=  e^{-it}\frac{d}{dt}\left[ e^{2it} \frac{d}{dt} \left(e^{it}f(t)\right)\right]
$$
Multiply both sides by $e^{it}$, integrate once and matching derivatives at $t = 0$, we get
$$e^{2it}\frac{d}{dt}( e^{-it}f(t) ) = f'(0) - if(0) + \int_0^t g(v) e^{iv} dv
$$
Mutiply both sides by $e^{-2it}$, integrate and matching derivatives at $t = 0$ again, we get
$$\begin{align}e^{-it}f(t)
&= f(0) + \int_0^t \left[ f'(0) - if(0) +
\int_0^u g(v) e^{iv} dv \right] e^{-2iu} du\\
&= f(0) + (f'(0) - if(0))e^{-it}\sin(t)
+ \int_0^t g(v) e^{iv} \left( \int_v^t e^{-2iu} du \right) dv\\
&= f(0) + e^{-it}\left[ (f'(0) - if(0))\sin(t)
+ \int_0^t g(v) \sin(t-v) dv\right]\\
\implies\quad
f(t) &= f(0)\cos(t) + f'(0)\sin(t) + \int_0^t g(v)\sin(t-v) dv\tag{*1}
\end{align}
$$
Setting $t = \pi$, this leads to
$$f(\pi) + f(0) = \int_0^\pi  g(v) \sin(\pi - v) dv = \int_0^\pi  g(v) \sin v dv \ge 0$$
because $g(v)$ and $\sin v$ are non-negative on $[0,\pi]$.
Notes
Please note that the appearance of the function
$$G(t,v) \stackrel{def}{=} \begin{cases}\sin(t-v), &t > v\\
0, &t < v\end{cases}$$
in the integral of $(*1)$ is not accidental.
It is the Green's function for the linear differential operator $\frac{d^2}{dt^2} + 1$. In certain sense,
one can think of $G$ as the right inverse of this differential operator.


text:
Q: How do I use packages in Erlang? Recently I found out about such thing as packages in Erlang language. The problem is I cannot compile module with package declaration. File main.erl with code represented below is located in directory /home/my_user/erl/update/src just like said in manual, but all my attempts to compile it failed. I use 18.0 version of erlang.
-module(update.src.main).
-author("legacy").

-export([start/0]).

start()->
  ok.

This is the result I got each time from erlang compiler:
5> c(main).
main.erl:9: syntax error before: '.'
main.erl:10: no module definition
error

Moreover, IntelliJ IDEA plugin for erlang language, which I use, reports an error in the string with module declaration and says that module update should be declared in file update.erl. I've tried to find something about problems with package usage, but all I've got was this question. So, haven't the packages in erlang been implemented yet or I missed something during compiling?

A: http://www.erlang.org/news/35

The board decided to remove the unsupported 'packages' support from
  the product in R16.

For more details see also Why aren't erlang packages used?

A: Old Manpage
Packages have been implemented but as yet they are only experimental, mainly because there is no consensus whether they should be in the language or not.
Almost erlang don't use package。Belong to otp ruler, you can use application to organize your code as package。
Erlang need that module name && file is the same name。
In erlang atom's name, it can't contain '.' . If you must use that, you can use 'a.c'.
Just Like that a.b.erl

-module('a.b').

redpajama_set_name: RedPajamaStackExchange


text:
Q: module Directory or module file inside name should be same or not Directory Structure
.
├── out
│   └── calc-module
│       ├── com
│       │   └── ngsharma
│       │       └── ocp
│       │           └── Calculator.class
│       └── module-info.class
└── src
    └── calculator
        ├── com
        │   └── ngsharma
        │       └── ocp
        │           └── Calculator.java
        └── module-info.java

Successfully compile and generate the out/calc-module directory.
javac -d out/calc-module src/calculator/module-info.java src/calculator/com/ngsharma/ocp/Calculator.java

module-info.java
module calc {}

Calculator.java
package com.ngsharma.ocp;

public class Calculator {

    public static int add(int i1, int i2) { return i1 + i2; }

    public static void main(String[] args) {
        System.out.println(add(20,40));
    }
}

When i compile this module  in following command.
1. java -p out --add-modules calc-module com.ngsharma.ocp.Calculator
When i'm using this command, it throw exception FindException: Module calc-module not found.
According to 1. module inside name and module directory name should be same other throw FindException.
2 java -p out --add-modules calc com.ngsharma.ocp.Calculator
but in this situation i'm not using module directory name i'm using only module-info.java inside file name, and successfully run. How..? and Why..?  module file name and module folder name should be same, otherwise not compile and run it is corrent or not.Please anybody suggest me and correct me what is my mistake.(newbie in module).

A: This (first of your commands) doesn't work because there is no module named calc-module. The name of the module is calc as specified in the module-info.java
java -p out --add-modules calc-module com.ngsharma.ocp.Calculator <-- cannot work

Either of these two will work for you:
java -p out --add-modules calc com.ngsharma.ocp.Calculator
java -p out --module calc/com.ngsharma.ocp.Calculator

Compiling
Immediate parent directory
There is a way to compile modules easily if the directory name of the contained module is identical to the module name. As in this structure:
.
+-- src
    +-- calc
        +-- com
        ¦   +-- ngsharma
        ¦       +-- ocp
        ¦           +-- Calculator.java
        +-- module-info.java

Now the entire module can be compiled using:
javac -d out --module-source-path src -m calc

The out directory structure will automatically have the name of the module, and hence be identical to the src structure.
This command will not work if the directory name is not identical to the module name, and in such case you will get error: module calc not found in module source path.
There is no difference in how the program is run. This is only valid for compilation.
Not immediate parent directory
The use of --module-source-path doesn't require that the directory name identical to the module name is the immediate parent directory to your package though. You can also create this common structure, where the module name is at the root several directories up:
.
+-- calc
    +-- src
        +-- main
            +-- java
                 +-- com
                 ¦    +-- ngsharma
                 ¦        +-- ocp
                 ¦            +-- Calculator.java
                 +-- module-info.java

However you need to tweek the compile command is this case (as Stephan Herrmann explains in an answer to "Java 9 error: not in a module on the module source path"):
javac -d out --module-source-path "./*/src/main/java/" -m calc

Note that there is no requirement that the directory shares the name with the module itself. It just helps to structure your program and make compiling easier.

A: The latter command
java -p out --add-modules calc com.ngsharma.ocp.Calculator

works since the --add-modules accepts as argument the name of modules present on the modulepath (out directory) which in this case is calc and not the name of the folder within which the module-info.java resides.
To answer the question directly, there is no mandate to name the directory where you build the module same as the module name.


text:
Q: file_get_contents echoes something, but fgets returns false This is my code:
<?php
                extract ($_POST);
                $fh = fopen ("./s.txt", "a");
                echo file_get_contents( "./s.txt" );
                if(($line = fgets($fh)) !== false) {}
                echo($line);
                file_put_contents("./signup.txt", "");

                if($line!=false && $line!='') {
                        echo '';
                        fwrite ($fh, "$line \n");
                        $n = $line;
                }
                else {
                        fwrite ($fh, "$_POST[n] \n");
                        $n = $_POST[n];
                }
                fclose ($fh);

  $script = $_SERVER['PHP_SELF'];
  print <<<TOP

  <form method = "post" action = "$script">

           Name
           <input type = "text" value = "$n" name = "n" size = "30" />

TOP;
  print <<<BOTTOM

<input type = "submit" name = "order" value = "Submit Order" />

</form>
BOTTOM;
?>

Basically, this has one entry spot which someone can enter into, and once someone enters into it, the data is written to a file. Every time after that the page is loaded, the data should be read from the file and set as the value to the input.
But when I load the program, enter "Word" as the field, and press submit, then open a new tab (to ensure it's not just the data being saved) and reenter the URL, "Word" is echoed as file_get_contents, but nothing is echoed for echo($line) and nothing is in the field for the input.
Why is this and how can I fix it?

A: While this doesn't appear to be documented explicitly/clearly in php.net (I'll provide links to relevant documentations below), having just run a test on my end, I've found that fgets() will always return false if you run it on a file resource where you used 'a' as the mode in fopen()
This I imagine is a side-effect of the 'a' mode opening the file for writing only. Running the exact same test, using 'a+' (Open the file for writing and reading) as the mode instead, has both fgets() and file_get_contents() output 'word'. The fopen documentation has details on the different modes.
http://php.net/manual/en/function.fopen.php
http://php.net/manual/en/function.fgets.php
And a couple screenshots of my testing this on my end, if you want to see the code I tested with and the results yourself:


text:
Q: adding semicolon at the end those do not have one I have file in which most(NOT ALL) lines ends with a semicolon. I would like to add semicolon at the end of only those line thats do not ends with a semicolon. Thanks

A: Technically, this will work:
sed '/;$/!s/$/;/' input

But you probably care about trailing whitespace, so:
sed '/; *$/!s/$/;/' input

If your sed supports \s:
 sed '/;\s*$/!s/$/;/' input

Or you might use:
sed '/;[[:space:]]*$/!s/$/;/' input

A: Using sed:
sed -i '/[^;] *$/s/$/;/' input_file

which means:
-i          overwrite the original file with new contents
/[^;] *$/   find lines that do not contain a `;` at the end (after
            ignoring trailing spaces)
s/$/;/      add a semicolon at the end


text:
Q: What is upper copula? Could I have a mathematical defintion of the upper copula ?
Is it between two different variable like (X1, X2) or only between same variable (X1, X1) ?
I'm not familiar with this term.
Thank you in advance for your answers


text:
Q: Can't add custom font to Xcode I'm trying to add a downloaded font to Xcode and I've folowed every single step based on this link: http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/

I added the font to my Xcode Project,

included it in Copy Bundle Resources (Build Phases),

and typed it in Fonts Provided by Application (in Info.plist).

Then I typed this in GameScene.swift inside didMoveToView
It has worked with other fonts but not with this one. This is really frustrating me and I've got no idea what the problem is, thanks.

A: The name of the font is not always the name of the file. Try looking for the file and then opening in. It should automatically pull it up in font book, and the name of the font is located on the top bar. Simply enter that instead of the file name and it should work.


text:
Q: How can i wait until download will be finished? My idea is easy:
1. I have a ViewController with button
2. After click button i want get data from my site
3. I want put indicator info about data are downloading
4. After finished show message OK or NOT OK
I have a class CCCLass
class CCClass {
let CCClass BaseURL: NSURL?
var seed: String?

init() {
    CCClassBaseURL = NSURL(string: "mysiteblabla")
}

func getData() {
    if let CCClassURL = NSURL(string: "", relativeToURL: CCClassBaseURL ) {
        let networkOperation = NetworkOperation(url: CCClassURL)
        networkOperation.downloadJSONFromURL {
            (let JSONDictionary) in
            print(JSONDictionary?["seed"])
            self.seed = JSONDictionary?["seed"] as? String
        }
    } else {
        print("Cold not construct a valid URL")
    }
}

}
On click button  i have
let ccClass = CCClass()

ccClass.getData() {
    (let test) in
     dispatch_async(dispatch_get_main_queue()) {
         // go to something on the main thread
         print(ccClass.seed)
    }
}

And i have error : Cannot invoke 'getData' with an argument list of type '((_) -> _)'
And i am not sure should I in function getData create Array and return to main thread ? after data will be download i want use this to next http query.

A: You're calling getData with a trailing closure, but the definition of getData doesn't take a closure parameter (or call it). What you have will work if you change the method to take the closure and use it (probably to pass the download result back).

A: You have to declare a closure parameter in your method if you want to call it with a trailing closure:
func getData( completion:()->() ) {
    if let CCClassURL = NSURL(string: "", relativeToURL: CCClassBaseURL ) {
        let networkOperation = NetworkOperation(url: CCClassURL)
        networkOperation.downloadJSONFromURL {
            (let JSONDictionary) in
            print(JSONDictionary?["seed"])
            self.seed = JSONDictionary?["seed"] as? String
            completion()
        }
    } else {
        print("Cold not construct a valid URL")
        completion()
    }
}

A good rule of thumb to follow is that any method that takes some kind of "completion" closure should always call that closure even if the operation fails.  So make sure you call completion() in your else block where URL construction failed, or if a network error occurred, or if a JSON parsing error occurred.


text:
Q: UNKNOWN NAME Showing up instead of actual phone number When receiving a phone call from a number not listed in my Contacts, the name displays as "UNKNOWN NAME" rather than simply showing the number initiating the call. I'm pretty sure this hasn't always been the case, and that my phone used to list the number itself.
Is there any way to get it to go back to listing the number? There seems to be no option for this under Settings.

A: The cell phone carrier sends this information, so I would do in order:

*

*check for carrier setting update

*Check for iOS update

*Test with a couple numbers (delete the number from contacts if needed)

*If it's systematic, restart the device and update it.

*If it's not systematic, call your carrier for support.

In the end, carrier support may be needed to validate why this happens if it's not a simple need to update or restart and retest.


text:
Q: Error: The prefix "xsd" for element "xsd:schema" is not bound I am getting a error that says

The prefix "xsd" for element "xsd:element" is not bound.

My XSD file is below:
<?xml version="1.0"?>
<!--XSD schema for file companylist.xml-->

<CompanyList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="companies.xsd">
    <xsd:element name="CompanyList">
      <xsd:complexType>
      <xsd:sequence>
      <xsd:element name="Company"
                 maxOccurs="unbounded">
          <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="CompanyID"
                    type="xsd:integer"/>
            <xsd:element name="contactname"
                    type="xsd:string"/>
          </xsd:sequence>
          </xsd:complexType>
      </xsd:element>
      </xsd:sequence>
      </xsd:complexType>
    </xsd:element>
</xsd:schema>

How can I fix this error?

A: To resolve the error,

The prefix "xsd" for element "xsd:schema" is not bound

define the xsd namespace prefix as follows on the root schema element of the XSD:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

Note also that the first tag of your XSD appears to be from an XML document instance.
Here is the entire XSD with the above problems resolved:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="CompanyList">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Company" maxOccurs="unbounded">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="CompanyID" type="xsd:integer"/>
              <xsd:element name="contactname" type="xsd:string"/>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>


text:
Q: Are ASP.NET WebAPI 2.2/SignalR 2.2/EntityFramework 6 realtime database notifications possible? I have put together a small ASP.NET WebAPI application which currently receives real-time database updates utilizing the SqlDependency OnChange notification event.  I've got this working perfectly like so:

*

*Javascript client performs a GET request to http://localhost:8888/api/HostEntry

*API controller's GetHosts() creates a new instance of a HostRepository which utilizes a raw SqlCommand to pull all host entries from the database.  This is where the SqlDependency OnChangeEventHandler is wired up.

*When changes are detected, the dependency_OnChange event fires and calls into a static method on my hub, HostsHub.NotifyUpdate().

*The HostsHub.NotifyUpdate() method notifies all clients that changes have been made and calls back to the client-side like so: context.Clients.All.updateData().

This is all working fine and dandy, but I am curious as to how I can handle this situation with an ORM such as Entity Framework.  I understand that lifecycle we should be utilizing for the EF DB context would be "context-per-request" and that a global context is a horrible practice which most likely wouldn't work.
From every angle I look at this it seems as if both the SignalR hub as well as Web API controller need access to the same DBContext to be able to provide notifications via SqlDependency.  Please let me know if any clarification is needed.


text:
Q: Extending `this` in Typescript class by Object.assign I have an object remote which is not a class instance itself. Due to the nature of Angular 2-5 I need to wrap this Object in a service so I can inject it into components. The object has an interface declared 'Remote'.
How would I make the following work?
import { Injectable } from '@angular/core';
import { remote, Remote } from 'electron';

@Injectable()
export class RemoteService implements Remote {
    constructor() {
        Object.assign(this, remote);
    }
}

I.e., how do I make a service class RemoteService which instances look like Remote, without having to manually wrap all remote's members? I cannot use extend because remote is not itself an instance of a class, just an object.
In the example above the Typescript compiler will complain that RemoteService incorrectly implements Remote (naturally). Is there any way to coerce the compiler into understand RemoteService as implementing Remote?

A: TypeScript class should be augmented with an interface. This results in merged declaration that asserts that Remote methods are implemented:
import { remote, Remote } from 'electron';

export interface RemoteService extends Remote {}

@Injectable()
export class RemoteService implements Remote {
    constructor() {
        Object.assign(this, remote);
    }
}

Object.assign will only work properly if properties are constant, and methods are own and enumerable.
For more efficient inheritance, base class can be created in order to provide prototype chain:
import { remote, Remote } from 'electron';

export interface BaseRemote extends Remote {}
export class BaseRemote implements Remote {}
Object.setPrototypeOf(BaseRemote.prototype, remote);
// or
/*
export const BaseRemote = function BaseRemote() {} as Function as { new(): Remote };
BaseRemote.prototype = remote;
*/

@Injectable()
export class RemoteService extends BaseRemote {
    /* custom methods */
}

If a class extends an exotic object that has restrictions on this context (see the example with native sessionStorage object), or object methods were bound, wrapper methods should be provided for original methods any way. If wrapper methods are created programmatically (by iterating over properties with for..in, etc) and not through class syntax, merged declaration should be additionally used for proper typing.


text:
Q: Which file should I override to change edit form template in Sonata Admin? I follow this tutorial to add a preview of my image file in my sonata admin (symfony3)
http://symfony.com/doc/current/bundles/SonataAdminBundle/cookbook/recipe_image_previews.html
But I not being able to add the CSS parte. The image is too large.
Should I override one of the sonata templates for it? If yes, which file I change and how do I do it? [I'm pretty new in sonata/symfony3]
If not, how should I add the css file in the project?
My actual code is exactly as the tutorial:
class ImageAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        // get the current Image instance
        $image = $this->getSubject();

        // use $fileFieldOptions so we can add other options to the field
        $fileFieldOptions = array('required' => false);
        if ($image && ($webPath = $image->getWebPath())) {
            // get the container so the full path to the image can be set
            $container = $this->getConfigurationPool()->getContainer();
            $fullPath = $container->get('request')->getBasePath().'/'.$webPath;

            // add a 'help' option containing the preview's img tag
            $fileFieldOptions['help'] = '<img src="'.$fullPath.'" class="admin-preview" />';
        }

        $formMapper
            // ... other fields ...
            ->add('file', 'file', $fileFieldOptions)
        ;
    }
    // ...
}

A: You'll need to add some code to include a CSS file in your Symfony project. Something similar to
{% stylesheets 'bundles/app/css/*' filter='cssrewrite' %}
  <link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}

Then you'd put the following CSS from the tutorial into that file.
img.admin-preview {
  max-height: 200px;
  max-width: 200px;
}

You can learn more about including CSS files with Symfony here.

A: First you need to make a template that extends SonataAdminBundle:CRUD:base_edit.html.twig, here is an example:
    {# BlastBaseEntitiesBundle:CRUD:edit.html.twig #}

    {% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}

    {# ... #}

Then create your css file in Resources/Public/css.
Execute the command bin/console assets:install to publish your stylesheet to the web/bundles directory.
  {# blastcore/css corresponds to BlastCoreBundle/Resources/Public/css and web/bundles/blastcore/js #}
    <link rel="stylesheet" href="{{ asset(blastcore/css/style.css) }}" />

http://symfony.com/doc/current/assetic/asset_management.html
Now you need to tell sonata to use your template for your admin.
you can do that in the service definition :
admin.yml
blast_base_entities.admin.search_index_entity:
        class: Blast\BaseEntitiesBundle\Admin\SearchIndexEntityAdmin
        arguments: [~, Blast\BaseEntitiesBundle\Entity\SearchIndexEntity, BlastCoreBundle:CRUD]
        tags:
            - name: sonata.admin
              manager_type: orm
              group: admin
              label: SearchIndexEntity
        calls:
        - [ setTemplate, [edit, BlastBaseEntitiesBundle:CRUD:edit.html.twig]]

https://sonata-project.org/bundles/admin/master/doc/reference/templates.html#crudcontroller-actions-templates


text:
Q: Spring WebFlow - add flow XML configuration check at compile time is there a way to check the sanity of the XML configuration at compile time ? Or at worst, at application startup ?
What I mean by sanity is not only validation & well-formedness but also well-formed method names in expression attributes (not necessarily existing but at least, missing parentheses are detected).
Thanks in advance,
Florent

A: To solve it from a compilation/build perspective, Spring webflow has a base AbstractXmlFlowExecutionTests test class that you can extend in order to write flow integration tests.  Any test methods you write will blow up with a FlowModelBuilderException ("Could not parse the XML...") exception if the xml fails to parse, either due to xsd validation errors or other xml wellformedness failures.  It is pretty good practice to use this utility for unit-testing your flow, and making it part of your build.
For any evaluations in your flow that are using your custom spring beans, you'll likely need to override registerMockFlowBeans or configureFlowBuilderContext, and provide mocks/test-implementations of your beans.  The javadoc has a simple example.


text:
Q: Forcing an irregular Bootstrap column / row wrapping I have a typical grid layout as seen attached:

I have 2 rows - one with the widget / header columns and another with the sidebar and content.  I did this to keep the widget and header height the same and responsive WITHOUT specifying the height via CSS.
The issue is when it wraps for mobile I want the header and content to stay together at the bottom.  I can do a single row with two columns then nest two rows in each but then I am back to specifying the height of the first rows of each nested grid.
I can make that work but it just seems to me that perhaps there is a more elegant solution which escapes me at the moment.

A: DEMO
Instead of putting widget-header & sidebar-content pairs in 2 separate rows & using pull  & pushto adjust the grid, you can easily put widget-sidebar in one column & header-content in another to solve the problem.
HTML:

Widget

sidebar

header

content

CSS:
.a{ /*for demo only*/
    height:100px;
    border:2px solid red;
}
.main{
    padding:0px; /*for no padding between 2 columns in small devices*/
}


text:
Q: Dialog Progress Fundo Branco opaco Estou tentando há alguns dias chegar á um dialog progress transparente com um fundo branco opaco igual as imagens abaixo porém só conseguir chegar a fundo preto opaco no padrão do android já vi alguns apps que conseguiram fazer assim alguém ja conseguiu ? se conseguiram poderiam me ajudar como ? desde de já agradeço a ajuda de todos.
public static Dialog showDialogLoading(Context context, String msg) {
    Dialog dialog = new Dialog(context, R.style.AppThemeLoading);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.progress_dialog);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(context, R.color.corBranco_dialog)));
    dialog.show();
    return dialog;
}

<style name="AppThemeLoading" parent="Base.ThemeOverlay.AppCompat">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
</style>

<color name="corBranco_dialog">#80ffffff</color>


text:
Q: Couchbase is there any limit of documents in a bucket? is there any limit of documents in a bucket?
We have a scenario of loading 1.8million documents, that was storing successfuly only upto 1.5m.
Another issue, When we write a basic view, its resulting into only 1535results, though more results (almost all) possible.
Through .net client also, we have verified that GetView is returning only 1535.
again, any limitation on number of documents and also on View results?
Please guide us with any resources, links - if possible.
thanks

A: Couchbase does not have any limit on the numbers of document (as soon  as you have enough memory for the keys and disk for the document)
It looks like your problem is not a "size" issue but the way you are using the views.
Could you confirm that your view us publish in "production"?
If you still use the view in development you will have only a subset of the document except if you execute the query with full_set=true.

A: Have you verified that the documents have been written to disk or is that queue not processed? If not, they will not be indexed.

"Once the document has been persisted to disk, the document can be
  indexed by the view mechanism." - http://www.couchbase.com/docs/couchbase-manual-2.0/couchbase-views-datastore-indexseq.html

Have you tried executing the query against the view and controlling the Stale flag?
var view = client.GetView("foo","bar").Stale(StaleMode.False);

More info:

*

*http://www.couchbase.com/docs/couchbase-manual-2.0/couchbase-views-writing-stale.html

*http://www.couchbase.com/docs/couchbase-devguide-2.0/creating-views-from-sdk.html


text:
Q: Dynamic symbols in Clojure Macro/Special Form I have a question regarding how to define functions/macros which call other macros or special forms but where one of the symbols passed in needs to be dynamic.
The simplest version of this question is described below:
We can define variables using def
(def x 0)

But what if we wanted the name x to be determined programmatically so that we could do the equivalent of?
(let [a 'b]
  (our-def a 3)) => user/b

We could try to define a function
(defn defn2 [sym val]
  (def sym val))

However it does not do what we want
(def2 'y 1)   => #'user/sym

At first it seems like a macro works (even though it seems like it would be unnecessary)
(defmacro def3 [sym val]
  `(def ~sym ~val))

(def3 z 2) => user/z

but it is just superficial, because we're really right back where we started with regular def.
(let [a 'b]
  (def3 a 3)) => user/a

I can do it if I use eval, but it doesn't seem like eval should be necessary
(defn def4 [sym val]
  (eval `(def ~sym ~val)))

(let [a 'b]
  (def4 a 4)) => user/b

If there are other built-in commands that could achieve this particular example, they are not really what I am looking for since def is just to show a particular example. There are macros more complicated than def that I might want to call and not have to worry about how they were internally implemented.

A: First: The right way to do this is to use macro that starts with def... since this is the way people have been doing defs and is of little surprise to the user.
To answer you question: Use intern:
(def foo 'bar)
(intern *ns* foo :hi)
(pr bar) ;; => :hi
(intern *ns* foo :hi2)
(pr bar) ;; => :hi2

If you want to use macros do this:
(def z 'aa)
(defmacro def3 [sym val]
  `(def ~(eval sym) ~val))
(def3 z 2)
(pr aa) ;; => 2


text:
Q: Facebook Rss Feed retrieve original image of thumbnail. I using this format of Facebook rss feed (format=atom10). I have problem with images all images are thumbnails they are very small now I want to get original size.
example feed
 https://www.facebook.com/feeds/page.php?id=193742123995472&format=atom10

image src= link
https://fbexternal-a.akamaihd.net/safe_image.php?d=AQCdnW-j48FEyfew&w=154&h=154&url=http%3A%2F%2Fcdn3.vox-cdn.com%2Fuploads%2Fchorus_image%2Fimage%2F36268722%2Fhateful-iimage-7-30.0_cinema_1200.0.jpg

A: Parse the image URL, remove everything up to ...url=, replace the escaped characters

*

*%3A -> :

*%2F -> /
and you get what you want: http://cdn3.vox-cdn.com/uploads/chorus_image/image/36268722/hateful-iimage-7-30.0_cinema_1200.0.jpg

You might also consider using the facebook Graph API. See this: facebook rss - how to increase thumbs image size?


text:
Q: "'django_mongodb_engine' isn't an available database backend" when pushing to Heroku I have a Django app that successfully ran on Heroku and uses mongodb engine. All of a sudden, I can not push it anymore. It does not seem to recognize the django_mongodb_engine module anymore. I even reverted all changes to the version that last ran, but it's still the same. I suspect a version conflict or so, but can not figure out how to fix it.
This is the error I'm getting:
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 429, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 191, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 220, in execute
    output = self.handle(*args, **options)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 351, in handle
    return self.handle_noargs(**options)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/commands/shell.py", line 46, in handle_noargs
    from django.db.models.loading import get_models
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/__init__.py", line 78, in <module>
    connection = connections[DEFAULT_DB_ALIAS]
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py", line 93, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py", line 51, in load_backend
    raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: 'django_mongodb_engine' isn't an available database backend.
Try using django.db.backends.XXX, where XXX is one of:
    'dummy', 'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2', 'sqlite3'
Error was: No module named utils

And these are the important parts from the requirements.txt:
hg+https://bitbucket.org/wkornewald/django-nonrel
git+https://github.com/django-nonrel/mongodb-engine
hg+https://bitbucket.org/wkornewald/djangotoolbox

pymongo==2.2.1
pytz==2012d

I'm especially confused because I reverted all changes. Exactly this code with the same configuration ran perfectly (and still does on my production server), just pushing does not work.
Thanks
Simon

A: Of course, just when I asked on SO I figure out the answer :-)
I don't know why exactly, but defining the exact revision that i want to check out solved the problem.
So the requirements.txt looks now like this:
-e hg+http://bitbucket.org/wkornewald/django-nonrel@be48c152abc6b15e45155e2bbcfd69c665ccb536#egg=Django-dev
-e git+https://github.com/django-nonrel/mongodb-engine@52257b5d90dcfaa564e708264a9cfe591d301fe6#egg=django_mongodb_engine-dev
-e hg+https://bitbucket.org/wkornewald/djangotoolbox@a8cdf61ba9c0cdc7cbbbd37d693e9a222d9a8e5f#egg=djangotoolbox-dev

pymongo==2.2.1
pytz==2012d


text:
Q: How to fetch aws rds endpoint using java code? I have made an AWS RDS Postgres instance using stacks and Java SDK.
I can see the Endpoint on AWS GUI and also able to connect it through DBeaver.
I need to fetch the RDS Endpoint of this instance using Java code?


text:
Q: vaex Object dtype dtype('O') has no native HDF5 equivalent I use vaex.from_csv() to convert csv  to hdf5 .
import vaex
vaex.from_csv("/Users/xxxx/development/vaex/dataAN/testdata1.csv", convert=True)

Get

IPython/core/interactiveshell.py:3331: DtypeWarning: Columns (53,55) have mixed types.Specify dtype option on import or set low_memory=False.
  exec(code_obj, self.user_global_ns, self.user_ns)
ERROR:MainThread:root:error creating dataset for 'EXT_SUB_ACC', with type dtype('O')
Traceback (most recent call last):
  File "/Users/xxxx/development/vaex/install/vaex/packages/vaex-core/vaex/hdf5/export.py", line 201, in export_hdf5
    array = h5column_output.require_dataset('data', shape=shape, dtype=dtype.newbyteorder(byteorder))
  File "/Users/xxxx/.conda/envs/vaex/lib/python3.7/site-packages/h5py/_hl/group.py", line 191, in require_dataset
    return self.create_dataset(name, *(shape, dtype), **kwds)
  File "/Users/xxxx/.conda/envs/vaex/lib/python3.7/site-packages/h5py/_hl/group.py", line 136, in create_dataset
    dsid = dataset.make_new_dset(self, shape, dtype, data, **kwds)
  File "/Users/xxxx/.conda/envs/vaex/lib/python3.7/site-packages/h5py/_hl/dataset.py", line 119, in make_new_dset
    tid = h5t.py_create(dtype, logical=1)
  File "h5py/h5t.pyx", line 1634, in h5py.h5t.py_create
  File "h5py/h5t.pyx", line 1656, in h5py.h5t.py_create
  File "h5py/h5t.pyx", line 1711, in h5py.h5t.py_create
TypeError: Object dtype dtype('O') has no native HDF5 equivalent

what these error mean?

A: A hint is given here:
IPython/core/interactiveshell.py:3331: DtypeWarning: Columns (53,55) have mixed types.Specify dtype option on import or set low_memory=False.

Pandas cannot find a common type, and therefore uses dtype=object, which cannot be saved to hdf5 (there is not native machine representation of it). If you force the dtype, by passing that argument to from_csv, vaex will pass it on to pandas.


text:
Q: Geographic Data types in JTS I recently discovered the potential of using JTS library when dealing with geographic types within a project. I'm using hibernate as my ORM (including hibernate spatial).
Before knowing the existence of JTS, I stored coordinates in a custom class called LatLon; whenever I wanted to manage polylines, I created a list of them, e.g. List. I realised how bad it was, speaking in terms of performance when making CRUD operations in the database.
So, as I've told you before, I discovered that my LatLon class could be replaced by the JTS' Point class. I'm starting to implement it and replacing the LatLon attributes, but I've several questions:

*

*I map my classes using XML (not annotations). Is the following correct?
(Java class)
...
private Point puntoInicio;
...
(XML mapping)
<property name="puntoInicio" type="org.hibernate.spatial.GeometryType" column="RUTA_PUNTOINICIO" not-null="true" />

*How do I store Polylines? I haven't found any data type with the name of Polyline. However, I've found others like LineString. Could I use this to represent polylines? How do I map them?
Thank you so much!
Edit: I'm using Hibernate 5.0.7.Final + Hibernate Spatial 5.0.7.Final
Edit 2: Sorry for my delay and for not accepting any answer. I undid the whole modifications some time ago, but I want to modify and implement this way. Thank you for your time and your patience.

A: I've been able to make it work not specifying the type of the column and updating Hibernate and Hibernate Spatial to 5. That way, the data is stored as binary. The problem comes now, I've got a class called "Conductor" that, when retrieving data from the database Hibernate throws an exception:
    Error Exception: could not deserialize
org.hibernate.type.SerializationException: could not deserialize
    at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:243)
    at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:138)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:113)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:27)
    at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:53)
    at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:238)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:234)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:224)
    at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:300)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2727)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1728)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1654)
    at org.hibernate.loader.Loader.getRow(Loader.java:1543)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:727)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
    at org.hibernate.loader.Loader.doQuery(Loader.java:930)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doList(Loader.java:2611)
    at org.hibernate.loader.Loader.doList(Loader.java:2594)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423)
    at org.hibernate.loader.Loader.list(Loader.java:2418)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
    ...
    //stuff from my webapp
    ...
Caused by: java.io.StreamCorruptedException: invalid stream header: 01303130
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309)
    at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299)
    at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218)
    ... 85 more


text:
Q: StyleTransformer is not run when BundleTable.EnableOptimizations = false; We're using script and style bundles to minify and bundle our resources. We're also using the StyleTransformer to transpile our .less files to .css.
coreCsss.Transforms.Add(new StyleTransformer());
coreCss.Include("~/Content/Common/Styles/core.less");

We also have a processor directive to only enable optimisations when building a non-debug configuration.
#if DEBUG
            BundleTable.EnableOptimizations = false;
#else
            BundleTable.EnableOptimizations = true;
#endif

The intention of the above is to allow us to more easily debug unpackaged and unminified javascript during development.
The problem we have noticed is that with EnableOptimizations disabled, then our .less files are not being transpiled and instead the raw .less is being served to the browser. Is there anyway to disable minification and bundling but still enable transformation? I would guess this is a fairly common scenario.

A: First, the code you have is completely unnecessary. Out of the box, EnableOptimizations is false in development and true in production. The only reason you might need to set it to something is if you actually wanted to enable the bundling in development (where it's disabled by default). That said, bundling is an all or nothing affair, if StyleTransformer depends on the bundling process to function, then if will have to be enabled in development, or you'll get exactly what you have.
Personally, I would recommend using something like the Web Essentials Visual Studio Extension, which among other things, will auto-compile LESS into CSS on save. Then, you can work with the LESS, and simply reference the CSS version. I'm sure there's other extensions with similar functionality. You can also set up build tasks to run gulp and such, but that's a little more complex.


text:
Q: How to access virtual remember_token attribute in the integration test? I'm working on michal hart's Ruby on rails tutorial  at chapter 8
Click here for details, I get stuck at exercise 8.6, The author introduced a way to access the virtual remember_token attribute in the integration test and he left some work for us,
assert_equal assigns(:user).FILL_IN, FILL_IN

Im supposed to replace the correct code with "FILL_IN" placeholder. I just couldn't think of the correct one. I tried with
assert_equal assigns(:user).cookies, remember_token

app/controllers/sessions_controller.rb
def create
     @user = User.find_by(email: params[:session][:email].downcase)
    if @user && @user.authenticate(params[:session][:password])
      log_in @user
      params[:session][:remember_me] == '1' ? remember(@user) : forget(@user)
      redirect_to @user

But it didn't work,
 Erros:
 "test_login_with_remembering", UsersLoginTest, 0.590876]
 test_login_with_remembering#UsersLoginTest (0.59s)
NoMethodError:         NoMethodError: undefined method `cookies' for #<User:0x007f964f1a91d0>

I know it's something very simple, I actually did some research , it seems no one has asked the same question, because the tutorial is quite new.
   Please understand that I'm just a beginner,I would be greatly appreciated , if you can help  me to solve  this problem.

A: I have got the answer by purchasing Michael's book. And the answer is included in the solution manual.  I think it's worth to share since i have asked this question
assert_equal assigns(:user).remember_token, cookies['remember_token']

It's worth nothing that, Reading about ruby language will be greatly helpful to understand this code,My problem was i didn't do much reading about Ruby before I dive in rails studies, But it's not a big problem, I have just moved on to Ruby beginning in order to get a deeper understanding about Ruby language!
                  Good luck

A: I got an error when I tried like @Snailwalker
assert_equal assigns(:user).remember_token, cookies['remember_token']
But it works like this
assert_equal assigns[:user].remember_token, cookies['remember_token']


text:
Q: Dynamically create a folder with "button" on click through the Java server page/ Java I am trying to create an automatic directory (via "input button") through the JSP. For this purpose, I have followed the following code:
<form action ="index.jsp">
<input type="button" name="systemDes" value="Build ">

<%
        String startTodir = request.getParameter("systemDes");
        String path="home/user1/Desktop/";
        File folderCreation = new File (path+"01");
            System.out.println("hello+2");
            if (startTodir != null){
            System.out.println("hello+1");
            folderCreation.mkdirs();
            }
    %>`
</form>

How to debug the above code for creating directory?

A: You should avoid using scriptlets in JSP.
Instead, use Ajax:

*

*Create a servlet that will get the request parameter and create the folder

*Use ajax in the onClick of your button and make a call to the servlet.

If you still want to have the logic in jsp file, I would suggest changing scriptlets syntax (<% ... %>) to declaration syntax (<%! ... %>) and declare your file creation code in method say createFile. and use this method on button click. Your code is not working on button click because it seems request.getParameter is returning null and with this declarative syntax, this can be avoided

A: When you reload the page the request parameter systemDes is present so the startTodir is not null and the if is satisfied and the directory is created.
All you need to do is change to <form action=""> this will reload the page when the submit button is hit and pass the systemDes parameter in the request.
This kind of code in JSP is not recommended, you should really consider writing a servlet to do the file creation.
The complete code is
<form action="">
<input type="submit" name="systemDes" value="Build ">
<%
        String startTodir = request.getParameter("systemDes");
        String path="home/user1/Desktop/";
        File folderCreation = new File (path+"01");
            System.out.println("hello+2");
            if (startTodir != null){
            System.out.println("hello+1");
            folderCreation.mkdirs();
            }
    %>
</form>


text:
Q: Push message to websockets with ratchet php and without ZeroMQ I try to make websocket server with rachet and pawl.
I read doc ratchet with ZeroMQ http://socketo.me/docs/push
But can't run it with Pawl https://github.com/ratchetphp/Pawl
I create client:
<script>
    var ws = new WebSocket('ws://site.ll:8008/?user=tester01');
    ws.onmessage = function(evt) { console.log(evt.data); };
</script>

Create worker:
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Pusher.php';

$loop   = React\EventLoop\Factory::create();
$pusher = new Pusher;

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server('0.0.0.0:8008', $loop);

$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();

Pusher class usgin the same like in tutorial http://socketo.me/docs/push#zeromq_messages
Using post.php to send message through ws:
$localsocket = 'tcp://127.0.0.1:1235';
$user = 'tester01';
$message = 'test';

$instance = stream_socket_client($localsocket);
fwrite($instance, json_encode(['user' => $user, 'message' => $message])  . "\n");

But still can't understand how to create tcp server withou ZeroMQ, like this part:
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:1235');
$pull->on('message', array($pusher, 'onBlogEntry'));

A: If you don't wan't to use ZeroMQ, you can use the same React mecanisms Ratchet uses.
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Pusher.php';

use React\EventLoop\Factory;
use React\Socket\ConnectionInterface;
use React\Socket\Server;

$loop   = Factory::create();
$pusher = new Pusher;

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server('0.0.0.0:8080', $loop);
$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

// Set up an incoming TCP socket to receive the messages to push
$inSocket = new Server('127.0.0.1:5555', $loop);
$inSocket->on('connection', function (ConnectionInterface $conn) use ($pusher) {
    // New data arrives at the socket
    $conn->on('data', function ($data) use ($conn, $pusher) {
        // Push the new blog entry update
        $pusher->onBlogEntry($data);
        // Close the incoming connection when the message is consumed
        $conn->close();
    });
});

$loop->run();

A: Doing with Pawl next and load on github:
https://github.com/Shkarbatov/WebSocketPHPRatchet


text:
Q: ngModel binding data angular 4 I have a response json data like this:
{
  "trainingClassId": 22,
  "classId": "class001",
  "startDate": 1541178000000,
  "endDate": 1510333200000,
  "examDate": 1510333200000,
  "numOfAttendee": "15"
}

on service:
getDetailApp(id: number):  Promise<any[]> {
    const url = `${this.URL}/${id}`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.json())
      .catch(this.handleError);
  }

on ts file:
ngOnInit() {

    this.getAppDetail();
    };

     async getAppDetail(){
       await this.appService.getDetailApp(this.data.id).then(data =>this.sub = data);

      console.log("=="+this.sub.classId);
    }

in html file:
 <mat-form-field>
                <input matInput [(ngModel)]="sub.classId" name="classId" id="classId" placeholder="Class ID">

            </mat-form-field>

when init html page, the input classID show data well. but in console browser it shows error message:
 ERROR TypeError: Cannot read property 'classId' of undefined
    at Object.eval [as updateDirectives]

after that, the page is crash. I cannot do anything on this.
Please advice me.


text:
Q: flask-socketio doesn't allow connection from android device Ok so I am following these tutorials to build a socketIO server using flask-socketIO and a client app for android devices.  My python setup is pretty simple:
Python server:

init.py:

from flask import Flask, render_template
from flask.ext.socketio import SocketIO, emit
import logging
from os import getcwd
from datetime import datetime

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

def openDir(folder):
    import os, errno

    try:
        os.makedirs(folder)
    except OSError, e:
        if e.errno != errno.EEXIST:
            raise

openDir('logs')

def fileAndChannelLogger(file_location,name):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    fh = logging.FileHandler("".join([getcwd(),'/',file_location,'/',datetime.today().strftime("%Y%m%d_%H_%M"),"_",name,".log"]))
    fh.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s | %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    logger.addHandler(fh)
    logger.addHandler(ch)

    return logger

logger = fileAndChannelLogger('logs', 'test')

@app.route('/')
def index():
    logger.debug("Someone accessed the root page")
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    logger.debug('Client connected')

@socketio.on('new message', namespace='/test')
def new_message(message):
    logger.debug(message)

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    logger.debug('Client disconnected')

run.py

from app import app, socketio
if __name__ == '__main__':
    socketio.run(app,host='My_cool_host_name')

Android client:

MainActivity.java

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.net.URISyntaxException;
import java.util.Objects;

import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;

import org.json.JSONException;
import org.json.JSONObject;

import static android.app.PendingIntent.getActivity;

public class MainActivity extends Activity implements View.OnClickListener {
    EditText userID;
    EditText statement;

    private Socket mSocket;
    {
        try {
            mSocket = IO.socket("http://My_cool_host_name:5000/test");
        } catch (URISyntaxException e) {}
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSocket.connect();
        Button send = (Button) findViewById(R.id.sendBtn);
        send.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        String ID_data = userID.getText().toString();
        String statement_data = statement.getText().toString();
        if (TextUtils.isEmpty(ID_data)) {
            return;
        }
        if (TextUtils.isEmpty(statement_data)) {
            return;
        }

        statement.setText("");
        JSONObject json = new JSONObject();
        try {
            json.put("user",ID_data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            json.put("statement",statement_data);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mSocket.emit("new message",json);
    }
}

Basically it takes in two edit boxes and then passes the info off to the server, nothing super fancy, just enough to get the basic groundwork of how this all works. I start the server, I can see the index.html from my browser when I go to the address with the specified port, when I run the client app in my an emulated device I get this error in the console:
 * Running on http://My_cool_host_name:5000/
2015-08-05 22:37:31,311 - DEBUG | Someone accessed the root page
192.168.1.163 - - [2015-08-05 22:37:31] "GET / HTTP/1.1" 200 210 0.022884
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/gevent/pywsgi.py", line 508, in handle_                                                                                one_response
    self.run_application()
  File "/usr/lib/python2.7/site-packages/gevent/pywsgi.py", line 494, in run_app                                                                                lication
    self.result = self.application(self.environ, self.start_response)
  File "/usr/lib/python2.7/site-packages/flask_socketio/__init__.py", line 27, i                                                                                n __call__
    raise RuntimeError('You need to use a gevent-socketio server.')
RuntimeError: You need to use a gevent-socketio server.
{'GATEWAY_INTERFACE': 'CGI/1.1',
 'HTTP_ACCEPT_ENCODING': 'gzip',
 'HTTP_CONNECTION': 'Keep-Alive',
 'HTTP_HOST': 'My_cool_host_name:5000',
 'HTTP_USER_AGENT': 'Dalvik/2.1.0 (Linux; U; Android 5.1; Android SDK built for                                                                                x86 Build/LKY45)',
 'PATH_INFO': '/socket.io/',
 'QUERY_STRING': 'EIO=3&transport=polling',
 'REMOTE_ADDR': '192.168.1.163',
 'REMOTE_PORT': '57754',
 'REQUEST_METHOD': 'GET',
 'SCRIPT_NAME': '',
 'SERVER_NAME': 'server_name',
 'SERVER_PORT': '5000',
 'SERVER_PROTOCOL': 'HTTP/1.1',
 'SERVER_SOFTWARE': 'gevent/1.0 Python/2.7',
 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x7f344d15b1e0>,
 'wsgi.input': <gevent.pywsgi.Input object at 0x7f34461ddd10>,
 'wsgi.multiprocess': False,
 'wsgi.multithread': False,
 'wsgi.run_once': False,
 'wsgi.url_scheme': 'http',
 'wsgi.version': (1, 0)} failed with RuntimeError

192.168.1.163 - - [2015-08-05 22:39:08] "GET /socket.io/?EIO=3&transport=polling HTTP/1.1" 500 161 0.010306

As you can see it says something about

You need to use a gevent-socketio server.

But I thought I could just run it like this, do I need to turn around and shuffle this behind a gevent-socketio server just for this simple test? If so can someone recommend a direction?  These are my installed python libraries:
alembic==0.6.2
Babel==1.3
Beaker==1.7.0.dev0
BeautifulSoup==3.2.1
blinker==1.3
decorator==3.4.0
Flask==0.10.1
Flask-Babel==0.9
Flask-Bootstrap==3.0.3.1
Flask-Login==0.2.9
Flask-Mail==0.9.0
Flask-Migrate==1.1.0
Flask-Mobility==0.1.1
Flask-Passlib==0.1
Flask-Script==0.6.6
Flask-Scrypt==0.1.3.1
Flask-SocketIO==0.6.0
Flask-SQLAlchemy==1.0
Flask-WhooshAlchemy==0.55a0
Flask-WTF==0.9.4
flup==1.0.2
gevent==1.0
gevent-socketio==0.3.6
gevent-websocket==0.9.2
greenlet==0.4.2
itsdangerous==0.24
Jinja2==2.8
lxml==3.4.4
Mako==0.9.1
MarkupSafe==0.23
MySQL-python==1.2.5
netsnmp-python==1.0a1
numpy==1.9.2
parse==1.6.3
passlib==1.6.2
pycrypto==2.6.1
python-dateutil==2.4.2
pytz==2013.9
PyYAML==3.11
scipy==0.15.1
scrypt==0.6.1
selenium==2.45.0
six==1.9.0
speaklater==1.3
SQLAlchemy==0.7.10
sqlalchemy-migrate==0.7.2
team==1.0
Tempita==0.5.1
Twisted==15.2.1
ujson==1.33
uWSGI==2.0.10
Werkzeug==0.10.4
Whoosh==2.5.6
WTForms==1.0.5
XlsxWriter==0.7.3
yamlog==0.9
zope.interface==4.1.2

Any help would be greatly appreciated, thanks.

A: Sadly,I also meet the same problems and doesn't know how to solve it. While waiting for some's answer here, I try another library https://github.com/koush/AndroidAsync, and luckily it works. Maybe you can have a try.

A: I had a similar issue, and it wound up being about the encoding that flask-socketio uses when communicating with Android. Try:
 mSocket = IO.socket("http://My_cool_host_name:5000/test?b64=1");

See this thread for more details:


text:
Q: unable to set calendar start date in pikaday calendar When i trigger the start date input box, I want to show the future or past month in calendar popup as a starting date in end date calendar.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://dbushell.com/Pikaday/css/pikaday.css">
    <link rel="stylesheet" href="https://dbushell.com/Pikaday/css/site.css">
</head>
<body>
    <input type="text" id="datepicker">
    <br/>
    <input type="text" id="datepicker2">
    <script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js">    </script>
    <script src="https://dbushell.com/Pikaday/pikaday.js">    </script>
    <script>
    var picker = new Pikaday({
        field: document.getElementById('datepicker'),
        format: 'D MMM YYYY',
        minDate: new Date(),
        onSelect: function (date) {
            picker2.setMinDate(date);
            //picker2.???? to set the starting month of picker2 calendar
        }
    });
    var picker2 = new Pikaday({
        field: document.getElementById('datepicker2'),
        format: 'D MMM YYYY',
        minDate: new Date(),
        onSelect: function () {
            console.log(this.getMoment().format('Do MMMM YYYY'));
        }
    });
    </script>
</body>
</html>

please check the above example, based on start day selection i want to trigger the end date calendar starting month. please suggest.
JS bin link

A: As I understand your question, you want to set the selected month in picker to the picker2 object. use the API onOpen.
Example
var picker = new Pikaday({
    field: document.getElementById('datepicker'),
    format: 'D MMM YYYY',
    minDate: new Date(),
    onSelect: function(date) {
        //console.log(this.getMoment().format('Do MMMM YYYY'));
        console.log('test ' + date);
        picker2.setMinDate(date);
        //picker2.setStartRange(date)
    }
});

var picker2 = new Pikaday({
    field: document.getElementById('datepicker2'),
    format: 'D MMM YYYY',
    minDate: new Date(),
    onOpen: function() {
        picker2.gotoDate(picker.getDate())
    },
    onSelect: function() {
        console.log(this.getMoment().format('Do MMMM YYYY'));
    }
});

A: When I worked with Pikaday package in Vue.Js project I had to set default date to my date field in form. I tried many different versions of setting default date.  But they didn't work for me. Finally I found the solution for my situation. The solution was to set prop like auto-default="autoDefault" here autoDefault is equels to true to Pikaday component like this...
<vue-pikaday v-model='date' auto-default="autoDefault" :options="pikadayOptions" />

 data() {
    return {
       autoDefault : true,
       pikadayOptions: {
           format  : 'YYYY/MM/DD',
           minDate : moment().toDate(),
       },
   }
},


text:
Q: Connecting Ubuntu server to internet through lan I have an old computer running Ubuntu 10.04. I installed a LAMP server on it and it works fine; however, the computer is connected to the internet through a large network connected to one modem. I have the ip address of the computer/server for our network, and it works fine, but I need this server to be accessible from the internet, anywhere. I have the ip address of the modem, but using it returns a "server not found" error. Any help would be greatly appreciated.

A: You need to setup a NAT or port forwarding to redirect a port on the modem to point to your server.

A: Your router's firewall is probably blocking the traffic.  You need to either tell your router to put the server in its DMZ (so it will receive all traffic) or tell it to forward a particular port (such as 80 for http) to the server's internal IP address.

A: Your "wireless apple time machine" is probably a router. I think you're referring to a time capsule. The good news it has a very nice NAT interface, just download the apple configuration utility. These instructions look pretty good:


text:
Q: Script to write Excel data to SQL Server database I need some sort of starting point for the following task:
Some kind of script should watch a certain folder for incoming excel files. These excel files all have a worksheet with an equal name. The script should then take a certain range of columns of each excel file run down all the rows and write the column data to a running Microsoft SQL Server table.
Now I don't know what scripting language I should/could use for this task. Maybe perl or windows power shell?
Hope you can point me to the right direction.
UPDATE: shouldn't I also look into SSIS since this seems to offer quite a lot of features?
Thank you.

A: You can create a Windows Service that can monitor a certain folder for a certain interval (say 10 minutes) using .Net.
Using ADO.Net, you can connect to both Excel workbooks and SQL sever perform SQL style data transformations.  If the Excel doc isn't conducive to performing SQL queries, there's alway MS Office interop to interface with Excel to select specific values of cells (this tends to be more difficult than the former).

A: I would probably write a script in Perl or Python trying to call the file in the folder, and if successful, parse the data into either dictionaries/hashes (would be really easy to break rows and columns into a hash), or arrays, making it easy to write to a database.
Then (my knowledge is better in Python, sorry) use the PyODBC module, or whatever other module is necessary to connect to the server, and start writing. I am sorry if this is not as helpful, I am a beginner.


text:
Q: how to preventDefault jquery when click on search How to close when click everywhere and not close when click on class form-cauta ?

    $("body").on("click",function(){
        $("#searchresult").css("display","none");
    });
    $(".form-cauta , #search , #cauta").on("click",function(){
        $("#searchresult").css("display","block");
    });

<form class="form-cauta" action="{{URL("search")}}">
    <input type="text" id="search" name="search" placeholder="Cauta" autocomplete="off"/>
    <button type="submit" id="cauta">

    </button>
</form> This is body

dsasdasdasad

dsasdasdasad

dsasdasdasad

dsasdasdasad

dsasdasdasad

How to close when click everywhere and not close when click on class form-cauta ?

A: You need to pass the event as a parameter for the closure function of form click event.
$(".form-cauta, #search, #cauta").on("click", function(event){
    event.stopPropagation(); // Passing the event and stoping propagation
    $("#searchresult").css("display", "block");
});

JsBin Example

A: Check this working code.

$().ready(function(){
        $("body").on("click",function(){
            $("#searchresult").css("display","none");
        });
        $(".form-cauta , #search , #cauta").on("click",function(){
            $("#searchresult").css("display","block");
        });

         $(".form-cauta").submit(function (e) {
            e.preventDefault();
        });
    });

<form class="form-cauta" action="{{URL("search")}}">
    <input type="text" id="search" name="search" placeholder="Cauta" autocomplete="off"/>
    <button type="submit" id="cauta">

    </button>
</form> This is body

dsasdasdasad

dsasdasdasad

dsasdasdasad

dsasdasdasad

dsasdasdasad


text:
Q: JFrog as Apache Spark artifactory with authentication Trying to use JFrog as authenticated Artifactory with Apache Spark with the https://user:pswd@url suggested here: https://spark.apache.org/docs/latest/submitting-applications.html#advanced-dependency-management and it is not working with next configuration:
"jars":"https://user:pswd@test.jfrog.io/artifactory/default-generic-local/spark-sql-kafka-0-10_2.12-3.0.3.jar"

It doesn't work:
22/04/27 15:27:21 INFO SecurityManager - SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(1000690000); groups with view permissions: Set(); users  with modify permissions: Set(1000690000); groups with modify permissions: Set()
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: https://user:pswd@test.jfrog.io/artifactory/default-generic-local/spark-sql-kafka-0-10_2.12-3.0.3.jar

Even if you try from a console this work:
curl -v "https://user:pswd@test.jfrog.io/artifactory/default-generic-local/"

Also a no authenticated JFrog artifact it works good. Any advice to use an authenticated artifact from Spark?


text:
Q: Remove timezone format I would like to know how could I remove the timezone automatically shown in my service output.
Let me explain:
My webservice's output contains a field derived from this Simple Type:
<xs:simpleType name="tsMyDateTime">
    <xs:restriction base="xs:dateTime">
        <xs:pattern value="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}" />
    </xs:restriction>
</xs:simpleType>

I would expect the following tsMyDateTime output format (for instance):
2026-02-25T00:00:00

But the output looks like:
2026-02-25T00:00:00.835-03:00

The original date object has the correct date and time, but I need to use Calendar (for xs:dateTime), but the timezone always appears.
I set the Calendar object by this way:
java.util.Date dateObject = (...)
calendar.setTime(dateObject);

Can someone give me suggestions?


text:
Q: Is possible to ignore the TextBox? I'm creating a program to calculate the average. There are 12 TextBox and I want to create the possibility to leave some fields blank. Now there are only errors and the crash of the program. Is possible to create that?
This is part of code:
ItalianoScritto = (TextBox1.Text)
MatematicaScritto = (TextBox2.Text)
IngleseScritto = (TextBox3.Text)
InformaticaScritto = (TextBox4.Text)
ScienzeScritto = (TextBox5.Text)
FisicaScritto = (TextBox6.Text)
MediaScritto = (ItalianoScritto + MatematicaScritto + IngleseScritto + InformaticaScritto + ScienzeScritto + FisicaScritto) / 6
Label10.Text = Str(MediaScritto)

If i leave blank the textbox1 when I click on the button to calculate the average Vb says Cast not valid from the string "" to type 'Single' and the bar of te textbox1 become yellow

A: I would do the following:
Iterate over the textboxes and check if you can parse the value into an iteger. If yes, add it to a value list.
Then add all values from that list and divide it by the number of cases.
It is faster than big if-statements and resilient against error
dim TBList as new list(of Textbox)
'add your textboxes to the list here
TbList.add(Textbox1)
...

dim ValList as new List(Of Integer)
for each elem in Tblist
  dim value as integer
  If integer.tryparse(elem.text,value)=True
    ValList.add(Value)
  else
    'report error or do nothing
  end if
next

dim Result as Integer
Dim MaxVal as Integer =0
for each elem in ValList
  Maxval +=elem
next

Result = MaxVal / ValList.count

If you need support for point values, just choose double or single instead of Integer.
Also: regardless what you do -CHECK if the values in the textboxes are numbers or not. If you omit the tryparse, somebody will enter "A" and your app will crash and burn
Also: You OPTION STRICT ON!

A: You just have to check if the TextBox is blank on each one before using the value:
If TextBox7.TextLength <> 0 Then
    'Use the value inside
End If

The way to do it depends a lot of your code. You should consider editing your question giving more information (and code) in order to us to help you better.


text:
Q: Convert form submit to AJAX post within an AJAX post I need to change a form submit to an ajax post. I am working within codeigniter framework. The current JS code is:
$('#book-appointment-submit').click(function(event) {
    event.preventDefault();

    var formData = jQuery.parseJSON($('input[name="post_data"]').val());
    var postData = {
        'csrfToken': GlobalVariables.csrfToken,
        'id_users_provider': formData['appointment']['id_users_provider'],
        'id_services': formData['appointment']['id_services'],
        'start_datetime': formData['appointment']['start_datetime'],
    };
    if (GlobalVariables.manageMode) {
        postData.exclude_appointment_id = GlobalVariables.appointmentData.id;
    }
    var postUrl = GlobalVariables.baseUrl + '/index.php/appointments/ajax_check_datetime_availability';
    $.post(postUrl, postData, function(response) {
        console.log('Check Date/Time Availability Post Response :', response);
        if (response.exceptions) {
            response.exceptions = GeneralFunctions.parseExceptions(response.exceptions);
            GeneralFunctions.displayMessageBox('Unexpected Issues', 'Unfortunately '
                + 'the check appointment time availability could not be completed. '
                + 'The following issues occurred:');
            $('#message_box').append(GeneralFunctions.exceptionsToHtml(response.exceptions));
            return false;
        }
        if (response === true) {
            $('#book-appointment-form').submit(); //on submit
        } else {
            GeneralFunctions.displayMessageBox('Appointment Hour Taken', 'Unfortunately '
                + 'the selected appointment hour is not available anymore. Please select '
                + 'another hour.');
            FrontendBook.getAvailableHours($('#select-date').val());
            alert('#select-date');
        }
    }, 'json');
});

THE CONTROLLER
if($this->input->post('submit2')) {
    $post_waiting = json_decode($_POST['post_waiting'], true);
    $waitinglist = $post_waiting['appointment'];
    $this->load->model('appointments_model');
    $this->appointments_model->waitinglist_to_db($waitinglist);
    $this->load->view('appointments/waiting_success');//return to book view
} else {
    try {
        $post_data = json_decode($_POST['post_data'], true);
        $appointment = $post_data['appointment'];
        $customer = $post_data['customer'];
        if ($this->customers_model->exists($customer))
            $customer['id'] = $this->customers_model->find_record_id($customer);
        $customer_id = $this->customers_model->add($customer);
        $appointment['id_users_customer'] = $customer_id;
        $appointment['id'] = $this->appointments_model->add($appointment);
        $appointment['hash'] = $this->appointments_model->get_value('hash', $appointment['id']);
        $provider = $this->providers_model->get_row($appointment['id_users_provider']);
        $service = $this->services_model->get_row($appointment['id_services']);
        $company_settings = array(
            'company_name'  => $this->settings_model->get_setting('company_name'),
            'company_link'  => $this->settings_model->get_setting('company_link'),
            'company_email' => $this->settings_model->get_setting('company_email')
        );

The form submits fine with this code but when the form is used in frame the data is lost. To deal with this I need to change the line $('#book-appointment-form').submit(); to be an ajax call instead. I have tried replacing the line using a similar format to the other ajax call above in the JS:
...
if (response === true) {
    var dataUrl = GlobalVariables.baseUrl + '/index.php/appointments/';
    $.post(dataUrl, formData, function(response) {
        console.log('Customer Confirms Post Response:', response);
        if (response.exceptions) {
            response.exceptions = GeneralFunctions.parseExceptions(response.exceptions);
            GeneralFunctions.displayMessageBox('Unexpected Issues', 'Unfortunately '
                + 'the check appointment time availability could not be completed. '
                + 'The following issues occurred:');
            $('#message_box').append(GeneralFunctions.exceptionsToHtml(response.exceptions));
            return false;
        }
    }, 'json');
} else {
...

This did not work.

I got a 500 server error.

I do not think I am handling the ajax call correctly within the other ajax call. I assumed I needed to make a function in my controller to receive the call so I added "ajax_customer_confirms" to the url and made a ajax_customer_confirms() function in my controller and that did not work either.
QUESTIONS:

*

*How can I add an ajax call within the ajax call to replace my form submit?

*Do I need to handle the ajax call with a function in the controller or can I just replace the .submit() with an ajax call and leave the controller alone?

A: Each iteration of working on this issue brought up more questions but the final answer was posted here:
AJAX submit and 500 server error


text:
Q: Post-Build should ignore Exit-Code of Sub-Task I have a Visual Studio 2019 project with a Post-Build-Event, that is calling an EXE file I have written in C#.
Post-Build event:
MyTool.exe "$(TargetPath)"
This EXE file is doing some stuff and then calling another EXE file.
AnotherTool.exe SomeArguments
Problem is, if that second EXE file (AnotherTool.exe) gives an error (on StandardError output) or an exit code != 0, Visual Studio is "seeing" that codes, although the AnotherTool.exe is not called directly from the Post-Build event. The Post-Build just called the MyTool.exe.
I want MyTool.exe to handle that exit codes, so Visual Studio should ignore them. But the build fails, when AnotherTool.exe exits with an error.
Any ideas?
Edit: The "MyTool.exe" is calling the "AnotherTool.exe" using System.Diagnostics.Process. I set RedirectStandardOutput = true and RedirectStandardError = true, and then call the Process with Start() and WaitForExit().
But no matter what that process result is, MyTool.exe is always exiting with Environment.Exit(0) to give a clean exit.

A: Not an answer, but a Workaround that is working:
I created a batch file, that is calling:
start MyTool.exe %1
With this workaround, the build succeeds without error, and the tool chain is started correctly. I get no more error messages displayed in Visual Studio.
Trade off 1: The "MyTool.exe" is now displayed in a command window while running.
Trade off 2: If "MyTool.exe" fails with exit code != 0, Visual Studio won't notice.
If I remove the "start" from the batch, behaviour is like a direct call of MyTool.exe.


text:
Q: Rails: Best practice for model dependency class locations? I have a rails app moving along fairly well, but the fact that I'm doing this myself means that some poor sod is eventually going to see this and say, "What the hell were you thinking?  Why did you put this here?!?!"
Where is that poor, sorry soul going to expect to see a series of classes that aren't used by anything but a single model class?  Obviously, I could chuck it in the_model.rb along with class TheModel, but this may expand beyond the planned two classes...
I thought about lib, but it doesn't need to clutter everyone's view of the world....
Thank you.
My predecessor thanks you.

A: Leave them in the_model.rb until you need them in more than one place. If you refactor needlessly, you're not doing the simplest thing that could possibly work. You aren't gonna need it.
At that point, the general pattern is to create a directory for "concerns". See this weblog post by Jamis Buck or this one by Peter Marklund for more information.

A: In general: follow the Rails naming conventions when translating class names into filesystem locations. (that is: keep the class FooHelper::Bar in foo_helper/bar.rb)
You can make exceptions for small helper classes that are only used once and keep them in the same file as your model, but those should be exceptions. (but the converse is also true, don't create one-line thousands of single line files)
Use modules and class namespaces to your advantage.  If you have a helper class that is only used by (and dependent on) your model, put them into the namespace of the model class:
class TheModel::HelperClass
end

the location in the file system would be app/models/the_model/helper_class.rb
And something that is not dependent on your model can probably still be namespaced
module Bar
  class Foo
  end
end

living in bar/foo.rb, of course
You should probably not be afraid to put things that are not models into lib -- that's what this directory is for
I'd say concerns, while useful, are not really the right way to go because that is a way to split a single class into multiple files and you don't seem to be doing that.


text:
Q: Worklight, SQL-Adapter, The user specified as a definer ('mobilefirst'@'localhost') does not exist Im new to sql and worklight. Im following SQL-Adapter tutorial from IBM Worklight, and import the sample code to worklight studio.
After deployed adapter, I choose Run as -> Call Mobilefirst Adapter.
This is my response for procedure "getAccountTransactions1":
{   "isSuccessful": true,   "resultSet": [   ]}

This is my response for procedure "getAccountTransactions2":
{   "errors": [      "Runtime: Failed to retrieve data with procedure : getAccountTransactions"   ],   "info": [   ],   "isSuccessful": false,   "warnings": [   ]}

And this is the errors console for procedure "getAccountTransactions2"
FWLSE0101E: Caused by:  [project Adapters]java.sql.SQLException: The user specified as a definer ('mobilefirst'@'localhost') does not existjava.lang.RuntimeException: Failed to retrieve data with procedure : getAccountTransactions
I think I have something wrong with sql user 'mobilefirst'@'localhost', but i dont know why, cause I use root user in SQLAdapter.xml.
And how to set permission for "Worklight" sql user if I use it as the default of this sample code?
Image for error console

A:
User who created that procedure has been deleted. If
  you recreate that user, it should address your error.

You can try to use:
grant all on *.* to 'root'@'%' identified by 'password' with grant option;

A: You've mentioned the user "mobilefirst", which makes it seem like you're using MobileFirst Platform Foundation 6.3 or 7.0 (previously known as "Worklight"), but for some reason you are following/using a sample from Worklight 6.0.0.0... why is that?
You have somehow mixed something in your database...
What ever the reason of the mess that you've done, the easiest solution for you is to simply grant all permissions to both mobilefirst@localhost user as well as Worklight@localhost.
You then need to also make sure in your adapter's XML file that you are using that same user - either "mobilefirst" or "Worklight" (the same user from the database that you've granted all permissions for).
For exact query to run, you can refer to Stanislovas's answer - simply replace "root" with the appropriate username.
And don't mix old samples with new product releases...


text:
Q: Table view cells mess up after scrolling I've got a UITableViewCell, containing a specific of UIImages that I generate from code.
I've got this problem: the images are generated fine when I first load the view. However, if, for example, I scroll down and then I go back up, I find a completely different set of images.
I imagine this is a problem connected to the reusable cells, but I really don't know how to solve it.
for collabsImages in secImageUrls[indexPath.row] {

    dispatch_async(dispatch_get_main_queue()){
        let image = UIImageView()
        image.tag = i
        image.userInteractionEnabled = true
        image.frame = CGRectMake(CGFloat(10 + i*50 + 7*i), self.view.frame.height/2 - self.navigationController!.navigationBar.frame.height - 55, 40, 40)
        image.layer.cornerRadius = image.frame.width/2
        image.layer.masksToBounds = true
        image.sd_setImageWithURL(NSURL(string: collabsImages), placeholderImage: nil, options: [])
        cell1.addSubview(image)
        let didTapOnCollabImage = CollabsGestureRecognizer(target: self, action: "didTapOnCollabImage:", row: indexPath.row)
        image.addGestureRecognizer(didTapOnCollabImage)

        i++
    }
}

Here's the code for cellForRowAtIndexpath:
let cell1 : cellTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! cellTableViewCell

        tableView.allowsSelection = false
        cell1.profileImg.userInteractionEnabled = true

        let tappedOnImage = UITapGestureRecognizer(target: self, action: "tappedOnImage:")

        cell1.profileImg.tag = indexPath.row
        cell1.profileImg.addGestureRecognizer(tappedOnImage)

dispatch_async(dispatch_get_main_queue()) {

                cell1.profileImg.center = CGPointMake(35, 35)
                cell1.usernameLbl.frame = CGRectMake(cell1.profileImg.frame.maxX + 7, cell1.profileImg.frame.minY, self.view.frame.size.width/2, 20)
                cell1.usernameLbl.text = (self.jsonFeeds[indexPath.row]["author"] as? String)!
                cell1.titleLbl.text = (self.jsonFeeds[indexPath.row]["title"] as? String)
                cell1.titleLbl.frame = CGRectMake(cell1.profileImg.frame.maxX + 7, cell1.usernameLbl.frame.maxY + 7, self.view.frame.size.width-20, 20)

                let textLabel = UILabel(frame: CGRectMake(cell1.profileImg.frame.minX, cell1.titleLbl.frame.maxY + 20, self.view.frame.width-30, 90))
                //textLabel.center = CGPointMake(cell1.center.x, textLabel.center.y)
                textLabel.textAlignment = NSTextAlignment.Left
                textLabel.numberOfLines = 7
                textLabel.text = self.jsonFeeds[indexPath.row]["text"] as? String
                textLabel.backgroundColor = UIColor(red: 1/255, green: 109/255, blue: 127/255, alpha: 0.1)
                cell1.contentsView.addSubview(textLabel)

                let btn = UIButton()
                btn.frame = CGRectMake(cell1.frame.maxX - 150, textLabel.frame.maxY + 30, 130, 24)
                btn.layer.cornerRadius = 15
                btn.layer.borderWidth = 1
                btn.setTitle("MESSAGE", forState: UIControlState.Normal)
                btn.titleLabel?.font = UIFont(name: "HelveticaNeue-Thin", size: 14)
                btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
                btn.layer.borderColor = UIColor.blackColor().CGColor

                cell1.contentsView.addSubview(btn)

            let block: SDWebImageCompletionBlock! = {

                (image: UIImage!, error: NSError!, cacheType: SDImageCacheType, imageURL: NSURL!) -> Void in

            }

            cell1.profileImg.sd_setImageWithURL(NSURL(string: self.imageUrls[indexPath.row]!), completed: block)

            }

            var i = 0
            for collabsImages in secImageUrls[indexPath.row] {

                if collabsImages != "This is a post"{

                    dispatch_async(dispatch_get_main_queue()){
                        let image = UIImageView()
                        image.tag = i
                        image.userInteractionEnabled = true
                        image.frame = CGRectMake(CGFloat(10 + i*50 + 7*i), self.view.frame.height/2 - self.navigationController!.navigationBar.frame.height - 55, 40, 40)
                        image.layer.cornerRadius = image.frame.width/2
                        image.layer.masksToBounds = true
                        image.sd_setImageWithURL(NSURL(string: collabsImages), placeholderImage: nil, options: [])
                        cell1.contentsView.addSubview(image)
                        let didTapOnCollabImage = CollabsGestureRecognizer(target: self, action: "didTapOnCollabImage:", row: indexPath.row)
                        image.addGestureRecognizer(didTapOnCollabImage)

                        i++
                    }
                }
            }
        }

        return cell1

A: First of all, you are dispatching to the main thread twice, and once in an existing dispatch call. You should not need to dispatch anything to the main thread in cellForRowAtIndexPath, unless you are doing background work you need to return, like a network fetch.
Second, you should set your image on the reusable cell to nil before the cell is loaded. image.image = nil right after you dequeue the cell. That might help make sure you are not reusing the image.
Apple and others have some very great tutorials on how to efficiently load images into a table view, also.

A: Using tag along with reusable cells is a bad idea. Try to code the same without the help of tag. Giving indexpath.row as tag value cause weired issues. I think this will help


text:
Q: orderBy two fields (one in reverse) I would like to order a friend list by status (online firsts, offline lasts) and by alphabetical order. All I manage to get is:

*

*Online firsts / Reversed alphabetical order

*Or offline firsts / Alphabetical order

Here is plunker to expose my problem

A: Change the orderBy filter to this:
orderBy:['-status','name']

This will order by descending status (by prefixing the - character), then ascending name. Currently you're passing true to reverse the sort, which is causing the status to be correct (online first), but the names to be reversed (i.e., descending).
If you want to keep the reverse boolean, you could use orderBy:['status','-name']:true but that seems less clear than just making status descending as shown earlier.

A: There is another option to do that, you can have multiple orderBy filter in ng-repeat and that line :

will be :

The last orderBy is execute first and the second to last etc ...
Here is my plunkr : http://plnkr.co/edit/girPFzdi3Zx0yp0ASGVQ?p=preview

A: In Angular 1.5.8 previous example does not work.
Different logic has to be applied.
It looks logic from previous orderBy is applied to the next one, so in order to sort name ASC and status DESC name order has to be reveresed:

Here is fixed example: http://plnkr.co/edit/0ZFIftSgNkU9F03xJztG?p=preview


text:
Q: iOS 13 Voice Control UIScrollView The iOS13 Voice Control feature has a command 'Scroll Down'. This command works for UITableViews but does not seem to work for UIScrollViews with scrollable content.

*

*Is this intended?

*Intended or not, is there a way to enable this command to work on a UIScrollView?

Example: a UILabel with a lot of text inside a UIScrollView (constraints are correct - it scrolls and is acknowledged by Voice Over saying 'Page 1 of 3' when active)

A:
This command works for UITableViews but does not seem to work for UIScrollViews with scrollable content.

... only if this content is a huge UILabel content that must be scrollable: add many other elements (sliders, buttons...) and you'll notice that scrolling is enabled.
About that, in the TextKit Best Practices (2018 WWDC video), it's highly recommended to use a UITextView for this purpose:

Is there a way to enable this command to work on a UIScrollView?

Switch the label and your scroll view for a text view instead to make the Voice Control feature work with your specific use case.
Otherwise, it works with many other elements different from UILabel: the scroll view knows its content size and when it has to scroll down/up but the Voice Control feature doesn't recognize the label content as an element to directly interact with inside a scroll view.
I tested with a button and a huge UILabel as you did:

*

*Scroll down that worked to reach the end of my label.

*Scroll up that never works.

The label seems to be a kind of empty box that Voice Control ignores in a scroll view: to enable this command in a scroll view, just replace your label by a text view.
Now, if your use case is a single UILabel in a UIScrollView, remove them to display a UITextView instead.
EDIT
Here's the Xcode screenshot to make the UITextView scrolling work with the VoiceControl feature:

... with the results hereunder:

As you can notice, this is just a blank project with a simple text view: iOS recognizes this single element and acts as desired when Scroll down and Scroll up are vocalized.


text:
Q: Update query in ado.net I wanted to update a column in my table, i have written the code it runs fine without any error also it displays the confirmation dialog box but the table is not updated whats wrong with the code.
    Dim sqlConn As New SqlClient.SqlConnection
    sqlConn.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\housingsociety.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"

    Try
        sqlConn.Open()
    Catch sqlError As Exception
        MsgBox(sqlError.Message, 0, "Connection Error!")
    End Try

    Dim sqlComm As New SqlClient.SqlCommand
    sqlComm.Connection = sqlConn
    sqlComm.CommandText = "update committe_member set name = '@name' where name = 'member1'"

    Dim paramString As New SqlClient.SqlParameter("@name", SqlDbType.VarChar, 50)
    paramString.Direction = ParameterDirection.Input
    sqlComm.Parameters.Add(paramString)
    paramString.Value = TextBox1.Text

    sqlComm.ExecuteNonQuery()

    MsgBox("Record Sucessfully Altered", 0, "Confirmation!")

    sqlConn.Close()

A: You do not need to quote the parameter in your SQL string.
Try the following:
sqlComm.CommandText = "update committe_member set name = @name where name = 'member1'"

I would also set the parameter value before adding it to the parameters collection:
paramString.Value = TextBox1.Text
sqlComm.Parameters.Add(paramString)


text:
Q: Python Regex - + metacharacter not being greedy I have this string.

string = """Horseradish CULTURE: Well-drained, friable soil with a pH
  range of 6.2-6.8 will yield the best results. When roots are received,
  work the soil about a foot deep and incorporate compost, manure, or
  fertilizer. Make a 5-6" deep furrow and plant root cuttings 12" apart,
  slanted 2-3" deep with the flat-cut end up..."""

and this code
seed_spacing = re.search(r'(?:sow|transplant|plant)(?:(?!rows).)+(\d+)(\'|") apart', string, re.I)
seed_spacing.group()
>>>Make a 5-6" deep furrow and plant root cuttings 12" apart
seed_spacing.group(1)
>>>2

I want to see 12, but I am getting 2. I need this to be flexible for cases in which it is a one digit number. I thought + was greedy. What am I missing?

A: + is greedy - but it's not just greedy in \d+, it's also greedy in (?:(?!rows).)+.  The latter is eating the 1.  Perhaps you'd like (?:(?!rows)\D)+ better (that is, eat characters that aren't digits).

A: This part
(?:(?!rows).)+

of  your regular expression is greedy and it matches till 1, so make it non-greedy like this
(?:(?!rows).)+?

You will get
seed_spacing.group(1)

as
12